Skip to content

Commit

Permalink
Create errorAssertionFunction creators
Browse files Browse the repository at this point in the history
To clean up table driven test with often repeated functions we can add a
simple function creator that generates a errorAssertionFunction
  • Loading branch information
JERHAV committed Mar 4, 2024
1 parent bb548d0 commit 9262a71
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
23 changes: 23 additions & 0 deletions assert/assertions.go
Expand Up @@ -48,6 +48,29 @@ type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
// Comparison is a custom function that returns true on success and false on failure
type Comparison func() (success bool)

// ErrorIsFor returns an [ErrorAssertionFunc] which tests if the error wraps target.
func ErrorIsFor(target error) ErrorAssertionFunc {
return func(t TestingT, err error, msgsAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}

return ErrorIs(t, err, target, msgsAndArgs...)
}
}

// ErrorAsFor returns an [ErrorAssertionFunc] which tests if the any error in err's tree matches target and if so, assigns it to target.
// The returned function panics if target is not a non-nil pointer to either a type that implements error, or to any interface type.
func ErrorAsFor(target interface{}) ErrorAssertionFunc {
return func(t TestingT, err error, msgsAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}

return ErrorAs(t, err, target, msgsAndArgs...)
}
}

/*
Helper functions
*/
Expand Down
23 changes: 23 additions & 0 deletions require/requirements.go
Expand Up @@ -26,4 +26,27 @@ type BoolAssertionFunc func(TestingT, bool, ...interface{})
// for table driven tests.
type ErrorAssertionFunc func(TestingT, error, ...interface{})

// ErrorIsFunc returns an [ErrorAssertionFunc] which tests if the error wraps target.
func ErrorIsFor(expectedError error) ErrorAssertionFunc {
return func(t TestingT, err error, i ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
}

ErrorIs(t, err, expectedError, i...)
}
}

// ErrorAsFunc returns an [ErrorAssertionFunc] which tests if the any error in err's tree matches target and if so, assigns it to target.
// The returned function panics if target is not a non-nil pointer to either a type that implements error, or to any interface type.
func ErrorAsFor(expectedInterface interface{}) ErrorAssertionFunc {
return func(t TestingT, err error, i ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
}

ErrorAs(t, err, expectedInterface, i...)
}
}

//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=require -template=require.go.tmpl -include-format-funcs"

0 comments on commit 9262a71

Please sign in to comment.