Skip to content
Open
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
26 changes: 19 additions & 7 deletions assert/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -1708,21 +1708,25 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in
}

// matchRegexp return true if a specified regexp matches a string.
func matchRegexp(rx interface{}, str interface{}) bool {
func matchRegexp(rx interface{}, str interface{}) (bool, error) {
var r *regexp.Regexp
if rr, ok := rx.(*regexp.Regexp); ok {
r = rr
} else {
r = regexp.MustCompile(fmt.Sprint(rx))
var err error
r, err = regexp.Compile(fmt.Sprint(rx))
if err != nil {
return false, err
}
}

switch v := str.(type) {
case []byte:
return r.Match(v)
return r.Match(v), nil
case string:
return r.MatchString(v)
return r.MatchString(v), nil
default:
return r.MatchString(fmt.Sprint(v))
return r.MatchString(fmt.Sprint(v)), nil
}
}

Expand All @@ -1735,7 +1739,11 @@ func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface
h.Helper()
}

match := matchRegexp(rx, str)
match, err := matchRegexp(rx, str)
if err != nil {
Fail(t, fmt.Sprintf("Invalid regexp \"%v\": %s", rx, err), msgAndArgs...)
return false
}

if !match {
Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
Expand All @@ -1752,7 +1760,11 @@ func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interf
if h, ok := t.(tHelper); ok {
h.Helper()
}
match := matchRegexp(rx, str)
match, err := matchRegexp(rx, str)
if err != nil {
Fail(t, fmt.Sprintf("Invalid regexp \"%v\": %s", rx, err), msgAndArgs...)
return false
}

if match {
Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
Expand Down
4 changes: 4 additions & 0 deletions assert/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2555,6 +2555,10 @@ func TestRegexp(t *testing.T) {
True(t, NotRegexp(mockT, tc.rx, []byte(tc.str)))
True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
}

// Invalid regexp should fail the test instead of panicking
False(t, Regexp(mockT, `\C`, "anything"))
False(t, NotRegexp(mockT, `\C`, "anything"))
}

func testAutogeneratedFunction() {
Expand Down