/
td_re.go
260 lines (227 loc) · 6.8 KB
/
td_re.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// Copyright (c) 2018, Maxime Soulé
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
package td
import (
"fmt"
"reflect"
"regexp"
"github.com/maxatome/go-testdeep/internal/color"
"github.com/maxatome/go-testdeep/internal/ctxerr"
"github.com/maxatome/go-testdeep/internal/dark"
"github.com/maxatome/go-testdeep/internal/types"
)
type tdRe struct {
base
re *regexp.Regexp
captures reflect.Value
numMatches int
}
var _ TestDeep = &tdRe{}
func newRe(regIf interface{}, capture ...interface{}) (r *tdRe) {
r = &tdRe{
base: newBase(4),
}
const usage = "(STRING|*regexp.Regexp[, NON_NIL_CAPTURE])"
switch len(capture) {
case 0:
case 1:
if capture[0] != nil {
r.captures = reflect.ValueOf(capture[0])
}
default:
panic(color.TooManyParams(r.location.Func + usage))
}
switch reg := regIf.(type) {
case *regexp.Regexp:
r.re = reg
case string:
r.re = regexp.MustCompile(reg)
default:
panic(color.BadUsage(r.location.Func+usage, regIf, 1, false))
}
return
}
// summary(Re): allows to apply a regexp on a string (or convertible),
// []byte, error or fmt.Stringer interfaces, and even test the
// captured groups
// input(Re): str,slice([]byte),if(✓ + fmt.Stringer/error)
// Re operator allows to apply a regexp on a string (or convertible),
// []byte, error or fmt.Stringer interface (error interface is tested
// before fmt.Stringer.)
//
// "reg" is the regexp. It can be a string that is automatically
// compiled using regexp.MustCompile, or a *regexp.Regexp.
//
// Optional "capture" parameter can be used to match the contents of
// regexp groups. Groups are presented as a []string or [][]byte
// depending the original matched data. Note that an other operator
// can be used here.
//
// td.Cmp(t, "foobar zip!", td.Re(`^foobar`)) // succeeds
// td.Cmp(t, "John Doe",
// td.Re(`^(\w+) (\w+)`, []string{"John", "Doe"})) // succeeds
// td.Cmp(t, "John Doe",
// td.Re(`^(\w+) (\w+)`, td.Bag("Doe", "John"))) // succeeds
func Re(reg interface{}, capture ...interface{}) TestDeep {
r := newRe(reg, capture...)
r.numMatches = 1
return r
}
// summary(ReAll): allows to successively apply a regexp on a string
// (or convertible), []byte, error or fmt.Stringer interfaces, and
// even test the captured groups
// input(ReAll): str,slice([]byte),if(✓ + fmt.Stringer/error)
// ReAll operator allows to successively apply a regexp on a string
// (or convertible), []byte, error or fmt.Stringer interface (error
// interface is tested before fmt.Stringer) and to match its groups
// contents.
//
// "reg" is the regexp. It can be a string that is automatically
// compiled using regexp.MustCompile, or a *regexp.Regexp.
//
// "capture" is used to match the contents of regexp groups. Groups
// are presented as a []string or [][]byte depending the original
// matched data. Note that an other operator can be used here.
//
// td.Cmp(t, "John Doe",
// td.ReAll(`(\w+)(?: |\z)`, []string{"John", "Doe"})) // succeeds
// td.Cmp(t, "John Doe",
// td.ReAll(`(\w+)(?: |\z)`, td.Bag("Doe", "John"))) // succeeds
func ReAll(reg, capture interface{}) TestDeep {
r := newRe(reg, capture)
r.numMatches = -1
return r
}
func (r *tdRe) needCaptures() bool {
return r.captures.IsValid()
}
func (r *tdRe) matchByteCaptures(ctx ctxerr.Context, got []byte, result [][][]byte) *ctxerr.Error {
if len(result) == 0 {
return r.doesNotMatch(ctx, got)
}
num := 0
for _, set := range result {
num += len(set) - 1
}
// Not perfect but cast captured groups to string
// Special case to accepted expected []interface{} type
if r.captures.Type() == types.SliceInterface {
captures := make([]interface{}, 0, num)
for _, set := range result {
for _, match := range set[1:] {
captures = append(captures, string(match))
}
}
return r.matchCaptures(ctx, captures)
}
captures := make([]string, 0, num)
for _, set := range result {
for _, match := range set[1:] {
captures = append(captures, string(match))
}
}
return r.matchCaptures(ctx, captures)
}
func (r *tdRe) matchStringCaptures(ctx ctxerr.Context, got string, result [][]string) *ctxerr.Error {
if len(result) == 0 {
return r.doesNotMatch(ctx, got)
}
num := 0
for _, set := range result {
num += len(set) - 1
}
// Special case to accepted expected []interface{} type
if r.captures.Type() == types.SliceInterface {
captures := make([]interface{}, 0, num)
for _, set := range result {
for _, match := range set[1:] {
captures = append(captures, match)
}
}
return r.matchCaptures(ctx, captures)
}
captures := make([]string, 0, num)
for _, set := range result {
captures = append(captures, set[1:]...)
}
return r.matchCaptures(ctx, captures)
}
func (r *tdRe) matchCaptures(ctx ctxerr.Context, captures interface{}) (err *ctxerr.Error) {
return deepValueEqual(
ctx.ResetPath("("+ctx.Path.String()+" =~ "+r.String()+")"),
reflect.ValueOf(captures), r.captures)
}
func (r *tdRe) matchBool(ctx ctxerr.Context, got interface{}, result bool) *ctxerr.Error {
if result {
return nil
}
return r.doesNotMatch(ctx, got)
}
func (r *tdRe) doesNotMatch(ctx ctxerr.Context, got interface{}) *ctxerr.Error {
if ctx.BooleanError {
return ctxerr.BooleanError
}
return ctx.CollectError(&ctxerr.Error{
Message: "does not match Regexp",
Got: got,
Expected: types.RawString(r.re.String()),
})
}
func (r *tdRe) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error {
var str string
switch got.Kind() {
case reflect.String:
str = got.String()
case reflect.Slice:
if got.Type().Elem().Kind() == reflect.Uint8 {
gotBytes := got.Bytes()
if r.needCaptures() {
return r.matchByteCaptures(ctx,
gotBytes, r.re.FindAllSubmatch(gotBytes, r.numMatches))
}
return r.matchBool(ctx, gotBytes, r.re.Match(gotBytes))
}
if ctx.BooleanError {
return ctxerr.BooleanError
}
return ctx.CollectError(&ctxerr.Error{
Message: "bad slice type",
Got: types.RawString("[]" + got.Type().Elem().Kind().String()),
Expected: types.RawString("[]uint8"),
})
default:
var strOK bool
iface := dark.MustGetInterface(got)
switch gotVal := iface.(type) {
case error:
str = gotVal.Error()
strOK = true
case fmt.Stringer:
str = gotVal.String()
strOK = true
default:
}
if !strOK {
if ctx.BooleanError {
return ctxerr.BooleanError
}
return ctx.CollectError(&ctxerr.Error{
Message: "bad type",
Got: types.RawString(got.Type().String()),
Expected: types.RawString(
"string (convertible) OR fmt.Stringer OR error OR []uint8"),
})
}
}
if r.needCaptures() {
return r.matchStringCaptures(ctx,
str, r.re.FindAllStringSubmatch(str, r.numMatches))
}
return r.matchBool(ctx, str, r.re.MatchString(str))
}
func (r *tdRe) String() string {
return r.re.String()
}