github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/engine/errors_test.go (about) 1 package engine 2 3 import ( 4 "errors" 5 "fmt" 6 "testing" 7 8 "github.com/stretchr/testify/require" 9 10 "github.com/onflow/flow-go/model/flow" 11 ) 12 13 // reuse an error type 14 func ErrorExecutionResultExist(resultID flow.Identifier) error { 15 return NewInvalidInputErrorf("execution result already exists in mempool, execution result ID: %v", resultID) 16 } 17 18 func TestCustomizedError(t *testing.T) { 19 var err error 20 err = ErrorExecutionResultExist(flow.Identifier{0x11}) 21 22 require.True(t, IsInvalidInputError(err)) 23 24 // if an invalid error is wrapped with `fmt.Errorf`, it 25 // is still an invalid error 26 err = fmt.Errorf("could not process, because: %w", err) 27 require.True(t, IsInvalidInputError(err)) 28 } 29 30 type CustomizedError struct { 31 Msg string 32 } 33 34 func (e CustomizedError) Error() string { 35 return e.Msg 36 } 37 38 func TestErrorWrapping(t *testing.T) { 39 var err error 40 err = CustomizedError{ 41 Msg: "customized", 42 } 43 44 // wrap with invalid input 45 err = NewInvalidInputErrorf("invalid input: %v", err) 46 47 // when a customized error is wrapped with invalid input, it is 48 // an invalid error 49 require.True(t, IsInvalidInputError(err)) 50 require.Equal(t, "invalid input: customized", err.Error()) 51 52 // when a customized error is wrapped with invalid input, it is 53 // no longer an customized error 54 var errCustomizedError CustomizedError 55 require.False(t, errors.As(err, &errCustomizedError)) 56 } 57 58 var NoFieldError = errors.New("sentinal error") 59 60 type FieldsError struct { 61 Field1 string 62 Field2 int 63 Err error 64 } 65 66 func (e FieldsError) Error() string { 67 return fmt.Sprintf("field1: %v, field2: %v, err: %v", e.Field1, e.Field2, e.Err) 68 } 69 70 func TestTypeCheck(t *testing.T) { 71 var err error 72 err = NoFieldError 73 require.True(t, errors.Is(err, NoFieldError)) 74 75 err = FieldsError{ 76 Field1: "field1 missing", 77 Field2: 100, 78 Err: NoFieldError, 79 } 80 var errFieldsError FieldsError 81 // if an no field error is wrapped with fields error, then 82 // it is a fields error 83 require.True(t, errors.As(err, &errFieldsError)) 84 }