From 84924ff9679e8c8e7dca5dd1d3ca390b4c08548b Mon Sep 17 00:00:00 2001 From: Thiago Gomes Bento Ferreira Date: Mon, 12 Sep 2022 19:26:44 -0300 Subject: [PATCH] feat: added IsError test --- assert.go | 18 ++++++++++++++++++ assert_test.go | 7 +++++++ 2 files changed, 25 insertions(+) diff --git a/assert.go b/assert.go index a3a18ab..2eaec0b 100644 --- a/assert.go +++ b/assert.go @@ -1,6 +1,7 @@ package assert import ( + "errors" "fmt" "path" "reflect" @@ -166,6 +167,23 @@ func NotEqualSkip(t testing.TB, skip int, val1, val2 interface{}) { t.FailNow() } } +// IsErrorSkip validates that any error in err's chain matches target +// and throws an error with line number +// but the skip variable tells IsErrorSkip how far back on the stack to report the error. +// This is a building block to creating your own more complex validation functions. +func IsErrorSkip(t testing.TB, skip int, err, target error) { + if !errors.Is(err, target) { + _, file, line, _ := runtime.Caller(skip) + fmt.Printf("%s:%d %v does not is %v\n", path.Base(file), line, err, target) + t.FailNow() + } +} + +// IsError validates that any error in err's chain matches target +// and throws an error with line number +func IsError(t testing.TB, err, target error) { + IsErrorSkip(t, 2, err, target) +} // PanicMatches validates that the panic output of running fn matches the supplied string func PanicMatches(t testing.TB, fn func(), matches string) { diff --git a/assert_test.go b/assert_test.go index 6362181..ace245f 100644 --- a/assert_test.go +++ b/assert_test.go @@ -3,6 +3,7 @@ package assert import ( "errors" "testing" + "fmt" ) // NOTES: @@ -90,3 +91,9 @@ func TestEquals(t *testing.T) { Equal(t, iface, 1) NotEqual(t, iface, iface2) } + +func TestIsError(t *testing.T) { + err1 := errors.New("unknown error") + errWrapped := fmt.Errorf("another error: %w", err1) + IsError(t, errWrapped, err1) +}