Skip to content

Commit

Permalink
tests: add more testing to the errors package
Browse files Browse the repository at this point in the history
  • Loading branch information
noandrea committed May 14, 2021
1 parent fea37be commit 18130fa
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 11 deletions.
16 changes: 5 additions & 11 deletions server/rosetta/lib/errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,13 @@ func (e *Error) Error() string {
// Is implements errors.Is for *Error, two errors are considered equal
// if their error codes are identical
func (e *Error) Is(err error) bool {
// check if one is nil and the other isn't
if (e == nil && err != nil) || (err == nil && e != nil) {
return false
}
// assert it can be casted
rosErr, ok := err.(*Error)
if !ok {
if rosErr == nil || !ok {
return false
}
// check that both *Error's are correctly initialized to avoid dereference panics
if (rosErr.rosErr == nil && e.rosErr != nil) || (e.rosErr == nil && rosErr.rosErr != nil) {
if rosErr.rosErr == nil || e.rosErr == nil {
return false
}
// messages are equal if their error codes match
Expand All @@ -71,12 +67,10 @@ func WrapError(err *Error, msg string) *Error {
// ToRosetta attempts to converting an error into a rosetta
// error, if the error cannot be converted it will be parsed as unknown
func ToRosetta(err error) *types.Error {
if err == nil {
return nil
}
// if it's null or not known
rosErr, ok := err.(*Error)
if !ok {
return ToRosetta(WrapError(ErrUnknown, err.Error()))
if rosErr == nil || !ok {
return ToRosetta(WrapError(ErrUnknown, ErrUnknown.Error()))
}
return rosErr.rosErr
}
Expand Down
35 changes: 35 additions & 0 deletions server/rosetta/lib/errors/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,38 @@ func TestRegisterError(t *testing.T) {
assert.NotNil(t, error)

}

func TestError_Error(t *testing.T) {
var error *Error
// nil cases
assert.False(t, ErrOffline.Is(error))
error = &Error{}
assert.False(t, ErrOffline.Is(error))
// wrong type
assert.False(t, ErrOffline.Is(&MyError{}))
// test with wrapping an error
error = WrapError(ErrOffline, "offline")
assert.True(t, ErrOffline.Is(error))

// test equality
assert.False(t, ErrOffline.Is(ErrBadGateway))
assert.True(t, ErrBadGateway.Is(ErrBadGateway))
}

func TestToRosetta(t *testing.T) {
var error *Error
// nil case
assert.NotNil(t, ToRosetta(error))
// wrong type
assert.NotNil(t, ToRosetta(&MyError{}))
}

type MyError struct {
}

func (e *MyError) Error() string {
return ""
}
func (e *MyError) Is(err error) bool {
return true
}

0 comments on commit 18130fa

Please sign in to comment.