Skip to content

Commit

Permalink
check: Add assert.ErrIs
Browse files Browse the repository at this point in the history
  • Loading branch information
thatguystone committed Aug 15, 2023
1 parent 5046d1a commit f410ca5
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
36 changes: 36 additions & 0 deletions check/assert.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package check

import (
"errors"
"fmt"
"reflect"
"runtime/debug"
Expand Down Expand Up @@ -466,6 +467,41 @@ func (a assert) NotNilf(g any, format string, args ...any) bool {
return true
}

func (a assert) failErrIs(err, target error, format string, args ...any) {
a.helper()
a.error(
fmt.Sprintf(format, args...),
fmt.Sprintf(""+
"Expected error: %q\n"+
" got: %s",
err,
target,
),
)
}

// ErrIs ensures that [errors.Is] returns true.
func (a assert) ErrIs(err, target error) bool {
if !errors.Is(err, target) {
a.helper()
a.failErrIs(err, target, "")
return false
}

return true
}

// ErrIsf ensures that [errors.Is] returns true.
func (a assert) ErrIsf(err, target error, format string, args ...any) bool {
if !errors.Is(err, target) {
a.helper()
a.failErrIs(err, target, format, args...)
return false
}

return true
}

type paniced struct {
recovered any
stack string
Expand Down
23 changes: 23 additions & 0 deletions check/assert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package check
import (
"errors"
"fmt"
"io/fs"
"testing"
)

Expand Down Expand Up @@ -517,6 +518,28 @@ func TestAssertNotNil(t *testing.T) {
)
}

func TestAssertErrIs(t *testing.T) {
ta := newTestAssert(t)

ta.check(
ta.ErrIs(fs.ErrClosed, fs.ErrClosed),
true,
)
ta.check(
ta.ErrIsf(fs.ErrClosed, fs.ErrClosed, "fmt %d", 1),
true,
)

ta.check(
ta.ErrIs(errors.New("test"), fs.ErrClosed),
false,
)
ta.check(
ta.ErrIsf(errors.New("test"), fs.ErrClosed, "fmt %d", 1),
false,
)
}

func TestAssertPanics(t *testing.T) {
ta := newTestAssert(t)

Expand Down

0 comments on commit f410ca5

Please sign in to comment.