Created
October 18, 2022 22:08
-
-
Save onsi/c0c5a4c6c71f2b4321a46241af435921 to your computer and use it in GitHub Desktop.
An error filter example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package foo_test | |
| import ( | |
| "context" | |
| "errors" | |
| "reflect" | |
| "testing" | |
| "time" | |
| . "github.com/onsi/ginkgo/v2" | |
| . "github.com/onsi/gomega" | |
| ) | |
| func TestFoo(t *testing.T) { | |
| RegisterFailHandler(Fail) | |
| RunSpecs(t, "Foo Suite") | |
| } | |
| var NotFoundErr = errors.New("not found") | |
| var errInterface = reflect.TypeOf((*error)(nil)).Elem() | |
| func ErrorFilter(in any) any { | |
| inType := reflect.TypeOf(in) | |
| inValue := reflect.ValueOf(in) | |
| return reflect.MakeFunc(inType, func(args []reflect.Value) []reflect.Value { | |
| out := inValue.Call(args) | |
| if len(out) > 0 { | |
| lastValue := out[len(out)-1] | |
| last := lastValue.Interface() | |
| if last != nil && lastValue.Type().Implements(errInterface) && errors.Is(last.(error), NotFoundErr) { | |
| out[len(out)-1] = reflect.Zero(errInterface) | |
| } | |
| } | |
| return out | |
| }).Interface() | |
| } | |
| func myFunc(ctx context.Context, name string) error { | |
| if name == "not-found" { | |
| return NotFoundErr | |
| } else if name == "no-error" { | |
| return nil | |
| } else if name == "timeout" { | |
| <-ctx.Done() | |
| } | |
| return errors.New("boom") | |
| } | |
| var _ = Describe("cases", func() { | |
| It("passes", func() { | |
| DeferCleanup(ErrorFilter(myFunc), "no-error") | |
| }) | |
| It("times out", func() { | |
| DeferCleanup(ErrorFilter(myFunc), "timeout", NodeTimeout(time.Millisecond*100)) | |
| }) | |
| It("pases because of the filter", func() { | |
| DeferCleanup(ErrorFilter(myFunc), "not-found") | |
| }) | |
| It("fails", func() { | |
| DeferCleanup(ErrorFilter(myFunc), "boom") | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment