Skip to content

Commit

Permalink
add fix and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
xenowits committed Oct 19, 2023
1 parent bbf582d commit 2f65e8b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
9 changes: 7 additions & 2 deletions api/v1/validatorstate.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package v1

import (
"fmt"
"github.com/pkg/errors"

Check failure on line 18 in api/v1/validatorstate.go

View workflow job for this annotation

GitHub Actions / lint

File is not `goimports`-ed (goimports)
"strings"

"github.com/attestantio/go-eth2-client/spec/phase0"
Expand Down Expand Up @@ -94,8 +95,12 @@ func (v *ValidatorState) UnmarshalJSON(input []byte) error {
return err
}

func (v ValidatorState) String() string {
return validatorStateStrings[v]
func (v ValidatorState) String() (string, error) {
if int(v) < 0 || int(v) > len(validatorStateStrings) {
return "", errors.New("invalid validator state")
}

return validatorStateStrings[v], nil
}

// IsPending returns true if the validator is pending.
Expand Down
20 changes: 19 additions & 1 deletion api/v1/validatorstate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,10 @@ func TestValidatorStateJSON(t *testing.T) {
assert.Equal(t, test.isExited, res.IsExited())
assert.Equal(t, test.hasExited, res.HasExited())
assert.Equal(t, test.hasBalance, res.HasBalance())
assert.Equal(t, strings.Trim(string(rt), `"`), res.String())

valState, err := res.String()
require.NoError(t, err)
assert.Equal(t, strings.Trim(string(rt), `"`), valState)
}
})
}
Expand Down Expand Up @@ -261,3 +264,18 @@ func TestValidatorToState(t *testing.T) {
})
}
}

func TestString(t *testing.T) {
t.Run("valid state", func(t *testing.T) {
state := api.ValidatorStateActiveOngoing
resp, err := state.String()
require.NoError(t, err)
require.Equal(t, resp, "active_ongoing")
})

t.Run("invalid state", func(t *testing.T) {
state := api.ValidatorState(25)
_, err := state.String()
require.Error(t, err)
})
}

0 comments on commit 2f65e8b

Please sign in to comment.