mirror of https://github.com/stretchr/testify.git
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.pull/1587/head
parent
a61e9e59d6
commit
a9e6121b1c
|
@ -1615,7 +1615,6 @@ 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
|
||||
|
@ -1623,7 +1622,14 @@ func matchRegexp(rx interface{}, str interface{}) bool {
|
|||
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))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
|
||||
|
@ -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))
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue