Skip to content

Commit 801a3e1

Browse files
authored
feat(fail): support valid patterns for Fail matcher (#14)
This change adds support for validating that the error caught by the Fail matcher will match one of a set of regex patterns. This enables using the "Fail" matcher to ensure that not only failure in general, but specific failure specifically.
1 parent 32f4caa commit 801a3e1

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

matchers_fail.go

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package justest
22

3-
import "reflect"
3+
import (
4+
"reflect"
5+
"regexp"
6+
)
47

58
//go:noinline
6-
func Fail() Matcher {
9+
func Fail(patterns ...string) Matcher {
710
return MatcherFunc(func(t T, actuals ...any) {
811
GetHelper(t).Helper()
912

@@ -19,8 +22,17 @@ func Fail() Matcher {
1922

2023
lastRT := reflect.TypeOf(last)
2124
if lastRT.AssignableTo(reflect.TypeOf((*error)(nil)).Elem()) {
22-
// ok, no-op
23-
return
25+
if len(patterns) > 0 {
26+
for _, pattern := range patterns {
27+
re := regexp.MustCompile(pattern)
28+
if re.MatchString(last.(error).Error()) {
29+
return
30+
}
31+
}
32+
t.Fatalf("Error message did not match any of these patterns: %v", patterns)
33+
} else {
34+
return
35+
}
2436
}
2537

2638
t.Fatalf("No error occurred")

matchers_fail_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package justest_test
22

33
import (
44
"fmt"
5+
"regexp"
56
"testing"
67

78
. "github.com/arikkfir/justest"
@@ -40,4 +41,16 @@ func TestFail(t *testing.T) {
4041
With(mt).Verify(tc.actuals...).Will(Fail()).OrFail()
4142
})
4243
}
44+
t.Run("Succeeds if error matches one of the patterns", func(t *testing.T) {
45+
t.Parallel()
46+
mt := NewMockT(t)
47+
defer mt.Verify(SuccessVerifier())
48+
With(mt).Verify(fmt.Errorf("expected error")).Will(Fail(`^expected error$`)).OrFail()
49+
})
50+
t.Run("Fails if error matches none of the patterns", func(t *testing.T) {
51+
t.Parallel()
52+
mt := NewMockT(t)
53+
defer mt.Verify(FailureVerifier(regexp.QuoteMeta(`Error message did not match any of these patterns: [^abc$ ^def$ ^ghi$]`)))
54+
With(mt).Verify(fmt.Errorf("expected error")).Will(Fail(`^abc$`, `^def$`, `^ghi$`)).OrFail()
55+
})
4356
}

0 commit comments

Comments
 (0)