Skip to content

Commit a9e6121

Browse files
assert: handle []byte array properly
The regexp package works more efficiently on bytes; if you have bytes, it is easier to pass these directly to assert.Regexp than to convert them to a string first. In addition, FindIndex/FindStringIndex are unnecessary here because we immediately throw away the result - let's just call Match() instead.
1 parent a61e9e5 commit a9e6121

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

assert/assertions.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1615,15 +1615,21 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in
16151615

16161616
// matchRegexp return true if a specified regexp matches a string.
16171617
func matchRegexp(rx interface{}, str interface{}) bool {
1618-
16191618
var r *regexp.Regexp
16201619
if rr, ok := rx.(*regexp.Regexp); ok {
16211620
r = rr
16221621
} else {
16231622
r = regexp.MustCompile(fmt.Sprint(rx))
16241623
}
16251624

1626-
return (r.FindStringIndex(fmt.Sprint(str)) != nil)
1625+
switch v := str.(type) {
1626+
case []byte:
1627+
return r.Match(v)
1628+
case string:
1629+
return r.MatchString(v)
1630+
default:
1631+
return r.MatchString(fmt.Sprint(v))
1632+
}
16271633

16281634
}
16291635

assert/assertions_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1972,13 +1972,16 @@ func TestRegexp(t *testing.T) {
19721972
}{
19731973
{"^start", "start of the line"},
19741974
{"end$", "in the end"},
1975+
{"end$", "in the end"},
19751976
{"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
19761977
}
19771978

19781979
for _, tc := range cases {
19791980
True(t, Regexp(mockT, tc.rx, tc.str))
19801981
True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
1982+
True(t, Regexp(mockT, regexp.MustCompile(tc.rx), []byte(tc.str)))
19811983
False(t, NotRegexp(mockT, tc.rx, tc.str))
1984+
False(t, NotRegexp(mockT, tc.rx, []byte(tc.str)))
19821985
False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
19831986
}
19841987

@@ -1993,7 +1996,9 @@ func TestRegexp(t *testing.T) {
19931996
for _, tc := range cases {
19941997
False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
19951998
False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
1999+
False(t, Regexp(mockT, regexp.MustCompile(tc.rx), []byte(tc.str)))
19962000
True(t, NotRegexp(mockT, tc.rx, tc.str))
2001+
True(t, NotRegexp(mockT, tc.rx, []byte(tc.str)))
19972002
True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
19982003
}
19992004
}

0 commit comments

Comments
 (0)