Skip to content

Commit 368167c

Browse files
Add ErrorIs, ErrorAs (#28)
Fixes #12
1 parent 7688520 commit 368167c

2 files changed

Lines changed: 33 additions & 5 deletions

File tree

be_example_test.go

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package be_test
22

33
import (
44
"errors"
5+
"os"
56
"strings"
67

78
"github.com/carlmjohnson/be"
@@ -22,11 +23,15 @@ func Example() {
2223
be.AllEqual(t, []int{3, 2, 1}, s) // bad
2324

2425
var err error
25-
be.NilErr(t, err) // good
26-
be.Nonzero(t, err) // bad
26+
be.Zero(t, err) // good
27+
be.ErrorIs(t, nil, err) // good
28+
be.Nonzero(t, err) // bad
29+
be.ErrorIs(t, os.ErrPermission, err) // bad
30+
2731
err = errors.New("(O_o)")
28-
be.NilErr(t, err) // bad
29-
be.Nonzero(t, err) // good
32+
var asErr *os.PathError
33+
be.ErrorAs(t, &asErr, err) // bad
34+
be.Nonzero(t, err) // good
3035

3136
type mytype string
3237
var mystring mytype = "hello, world"
@@ -48,7 +53,8 @@ func Example() {
4853
// got: goodbye
4954
// want: [3 2 1]; got: [1 2 3]
5055
// got: <nil>
51-
// got: (O_o)
56+
// got errors.Is(<nil>, permission denied) == false
57+
// got errors.As((O_o), **fs.PathError) == false
5258
// "World" not in "hello, world"
5359
// "\x00" in "\a\b\x00\r\t"
5460
// want len(seq) == 1; got at least 2

error.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package be
2+
3+
import (
4+
"errors"
5+
"testing"
6+
)
7+
8+
// ErrorIs calls t.Fatalf if got is not want according to [errors.Is].
9+
func ErrorIs(t testing.TB, want, got error) {
10+
t.Helper()
11+
if !errors.Is(got, want) {
12+
t.Fatalf("got errors.Is(%v, %v) == false", got, want)
13+
}
14+
}
15+
16+
// ErrorIs calls t.Fatalf if got cannot be assigned to want by [errors.As].
17+
func ErrorAs[T error](t testing.TB, want *T, got error) {
18+
t.Helper()
19+
if !errors.As(got, want) {
20+
t.Fatalf("got errors.As(%v, %T) == false", got, want)
21+
}
22+
}

0 commit comments

Comments
 (0)