-
Notifications
You must be signed in to change notification settings - Fork 0
/
regexp.go
72 lines (67 loc) · 1.41 KB
/
regexp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package assert
import (
"fmt"
"regexp"
"testing"
)
// RegexpString is a type that can be either a [*regexp.Regexp] or a string.
//
// If it's a string, it's automatically compiled to a [*regexp.Regexp].
type RegexpString interface {
*regexp.Regexp | string
}
// RegexpMatch asserts that rs matches s.
func RegexpMatch[RS RegexpString](tb testing.TB, rs RS, s string, opts ...Option) bool {
tb.Helper()
r := getRegexp(tb, rs, opts...)
if r == nil {
return false
}
ok := r.MatchString(s)
if !ok {
Fail(
tb,
"regexp_match",
fmt.Sprintf("no match:\nrs = %q\ns = %q", r, s),
opts...,
)
}
return ok
}
// RegexpNotMatch asserts that rs doesn't match s.
func RegexpNotMatch[RS RegexpString](tb testing.TB, rs RS, s string, opts ...Option) bool {
tb.Helper()
r := getRegexp(tb, rs, opts...)
if r == nil {
return false
}
ok := !r.MatchString(s)
if !ok {
Fail(
tb,
"regexp_not_match",
fmt.Sprintf("match:\nrs = %q\ns = %q", r, s),
opts...,
)
}
return ok
}
func getRegexp[RS RegexpString](tb testing.TB, rs RS, opts ...Option) *regexp.Regexp {
tb.Helper()
r, ok := any(rs).(*regexp.Regexp)
if ok {
return r
}
s := any(rs).(string) //nolint:forcetypeassert // We know it's a string.
r, err := regexp.Compile(s)
if err != nil {
Fail(
tb,
"regexp_compile",
fmt.Sprintf("compilation failed:\nexpr = %q\nerr = %s", s, ErrorStringer(err)),
opts...,
)
return nil
}
return r
}