Skip to content

Commit

Permalink
feat(fail): show mismatched error message on error (#16)
Browse files Browse the repository at this point in the history
This change makes the "Fail" matcher print the mismatched error message
when it doesn't match any pattern.

This makes it easier to debug failing tests when the error does not
match any of the patterns, but you don't know what error was actually
provided.
  • Loading branch information
arikkfir authored May 17, 2024
1 parent 473b11c commit bed70bc
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
8 changes: 6 additions & 2 deletions matchers_fail.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (

//go:noinline
func Fail(patterns ...string) Matcher {
const failureFormatMsg = `Error message did not match any pattern:
Patterns: %v
Error: %s`
return MatcherFunc(func(t T, actuals ...any) {
GetHelper(t).Helper()

Expand All @@ -23,13 +26,14 @@ func Fail(patterns ...string) Matcher {
lastRT := reflect.TypeOf(last)
if lastRT.AssignableTo(reflect.TypeOf((*error)(nil)).Elem()) {
if len(patterns) > 0 {
msg := last.(error).Error()
for _, pattern := range patterns {
re := regexp.MustCompile(pattern)
if re.MatchString(last.(error).Error()) {
if re.MatchString(msg) {
return
}
}
t.Fatalf("Error message did not match any of these patterns: %v", patterns)
t.Fatalf(failureFormatMsg, patterns, msg)
} else {
return
}
Expand Down
2 changes: 1 addition & 1 deletion matchers_fail_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func TestFail(t *testing.T) {
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$]`)))
defer mt.Verify(FailureVerifier(`.*` + regexp.QuoteMeta(`[^abc$ ^def$ ^ghi$]`) + `\n.*expected error`))
With(mt).Verify(fmt.Errorf("expected error")).Will(Fail(`^abc$`, `^def$`, `^ghi$`)).OrFail()
})
}

0 comments on commit bed70bc

Please sign in to comment.