Skip to content

Commit

Permalink
feat(fail): support valid patterns for Fail matcher
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
arikkfir committed May 11, 2024
1 parent 32f4caa commit 95cc4c4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
20 changes: 16 additions & 4 deletions matchers_fail.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package justest

import "reflect"
import (
"reflect"
"regexp"
)

//go:noinline
func Fail() Matcher {
func Fail(patterns ...string) Matcher {
return MatcherFunc(func(t T, actuals ...any) {
GetHelper(t).Helper()

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

lastRT := reflect.TypeOf(last)
if lastRT.AssignableTo(reflect.TypeOf((*error)(nil)).Elem()) {
// ok, no-op
return
if len(patterns) > 0 {
for _, pattern := range patterns {
re := regexp.MustCompile(pattern)
if re.MatchString(last.(error).Error()) {
return
}
}
t.Fatalf("Error message did not match any of these patterns: %v", patterns)
} else {
return
}
}

t.Fatalf("No error occurred")
Expand Down
13 changes: 13 additions & 0 deletions matchers_fail_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package justest_test

import (
"fmt"
"regexp"
"testing"

. "github.com/arikkfir/justest"
Expand Down Expand Up @@ -40,4 +41,16 @@ func TestFail(t *testing.T) {
With(mt).Verify(tc.actuals...).Will(Fail()).OrFail()
})
}
t.Run("Succeeds if error matches one of the patterns", func(t *testing.T) {
t.Parallel()
mt := NewMockT(t)
defer mt.Verify(SuccessVerifier())
With(mt).Verify(fmt.Errorf("expected error")).Will(Fail(`^expected error$`)).OrFail()
})
t.Run("Fails if error matches none of the patterns", func(t *testing.T) {
t.Parallel()
mt := NewMockT(t)
defer mt.Verify(FailureVerifier(regexp.QuoteMeta(`Error message did not match any of these patterns: [^abc$ ^def$ ^ghi$]`)))
With(mt).Verify(fmt.Errorf("expected error")).Will(Fail(`^abc$`, `^def$`, `^ghi$`)).OrFail()
})
}

0 comments on commit 95cc4c4

Please sign in to comment.