Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(fail): support valid patterns for Fail matcher #14

Merged
merged 1 commit into from
May 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
})
}