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

assert.Regexp: handle []byte array properly #1587

Merged
merged 1 commit into from May 22, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions assert/assertions.go
Expand Up @@ -1615,15 +1615,21 @@ 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 {

var r *regexp.Regexp
if rr, ok := rx.(*regexp.Regexp); ok {
r = rr
} else {
r = regexp.MustCompile(fmt.Sprint(rx))
}

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

}

Expand Down
5 changes: 5 additions & 0 deletions assert/assertions_test.go
Expand Up @@ -1972,13 +1972,16 @@ func TestRegexp(t *testing.T) {
}{
{"^start", "start of the line"},
{"end$", "in the end"},
{"end$", "in the end"},
{"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
}

for _, tc := range cases {
True(t, Regexp(mockT, tc.rx, tc.str))
True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
True(t, Regexp(mockT, regexp.MustCompile(tc.rx), []byte(tc.str)))
False(t, NotRegexp(mockT, tc.rx, tc.str))
False(t, NotRegexp(mockT, tc.rx, []byte(tc.str)))
False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
}

Expand All @@ -1993,7 +1996,9 @@ func TestRegexp(t *testing.T) {
for _, tc := range cases {
False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
False(t, Regexp(mockT, regexp.MustCompile(tc.rx), []byte(tc.str)))
True(t, NotRegexp(mockT, tc.rx, tc.str))
True(t, NotRegexp(mockT, tc.rx, []byte(tc.str)))
True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
}
}
Expand Down