| 1 |
// Copyright (c) 2018-2025, Maxime Soulé |
| 2 |
// All rights reserved. |
| 3 |
// |
| 4 |
// This source code is licensed under the BSD-style license found in the |
| 5 |
// LICENSE file in the root directory of this source tree. |
| 6 |
|
| 7 |
package td |
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"reflect" |
| 12 |
"regexp" |
| 13 |
|
| 14 |
"github.com/maxatome/go-testdeep/internal/ctxerr" |
| 15 |
"github.com/maxatome/go-testdeep/internal/dark" |
| 16 |
"github.com/maxatome/go-testdeep/internal/types" |
| 17 |
) |
| 18 |
|
| 19 |
type tdRe struct { |
| 20 |
base |
| 21 |
re *regexp.Regexp |
| 22 |
captures reflect.Value |
| 23 |
numMatches int |
| 24 |
} |
| 25 |
|
| 26 |
var _ TestDeep = &tdRe{} |
| 27 |
|
| 28 |
func newRe(regIf any, capture ...any) *tdRe { |
| 29 |
r := &tdRe{ |
| 30 |
base: newBase(4), |
| 31 |
} |
| 32 |
|
| 33 |
const ( |
| 34 |
usageRe = "(STRING|*regexp.Regexp[, NON_NIL_CAPTURE])" |
| 35 |
usageReAll = "(STRING|*regexp.Regexp, NON_NIL_CAPTURE)" |
| 36 |
) |
| 37 |
|
| 38 |
usage := usageRe |
| 39 |
if len(r.location.Func) != 2 { |
| 40 |
usage = usageReAll |
| 41 |
} |
| 42 |
|
| 43 |
switch len(capture) { |
| 44 |
case 0: |
| 45 |
case 1: |
| 46 |
if capture[0] != nil { |
| 47 |
r.captures = reflect.ValueOf(capture[0]) |
| 48 |
} |
| 49 |
default: |
| 50 |
r.err = ctxerr.OpTooManyParams(r.location.Func, usage) |
| 51 |
return r |
| 52 |
} |
| 53 |
|
| 54 |
switch reg := regIf.(type) { |
| 55 |
case *regexp.Regexp: |
| 56 |
r.re = reg |
| 57 |
case string: |
| 58 |
var err error |
| 59 |
r.re, err = regexp.Compile(reg) |
| 60 |
if err != nil { |
| 61 |
r.err = &ctxerr.Error{ |
| 62 |
Message: "invalid regexp given to " + r.location.Func + " operator", |
| 63 |
Summary: ctxerr.NewSummary(err.Error()), |
| 64 |
User: true, |
| 65 |
} |
| 66 |
} |
| 67 |
default: |
| 68 |
r.err = ctxerr.OpBadUsage(r.location.Func, usage, regIf, 1, false) |
| 69 |
} |
| 70 |
return r |
| 71 |
} |
| 72 |
|
| 73 |
// summary(Re): allows to apply a regexp on a string (or convertible), |
| 74 |
// []byte, error or fmt.Stringer interfaces, and even test the |
| 75 |
// captured groups |
| 76 |
// input(Re): str,slice([]byte),if(✓ + fmt.Stringer/error) |
| 77 |
|
| 78 |
// Re operator allows to apply a regexp on a string (or convertible), |
| 79 |
// []byte, error or [fmt.Stringer] interface (error interface is tested |
| 80 |
// before [fmt.Stringer].) |
| 81 |
// |
| 82 |
// reg is the regexp. It can be a string that is automatically |
| 83 |
// compiled using [regexp.Compile], or a [*regexp.Regexp]. |
| 84 |
// |
| 85 |
// Optional capture parameter can be used to match the contents of |
| 86 |
// regexp groups. Groups are presented as a []string or [][]byte |
| 87 |
// depending the original matched data. Note that an other operator |
| 88 |
// can be used here. |
| 89 |
// |
| 90 |
// td.Cmp(t, "foobar zip!", td.Re(`^foobar`)) // succeeds |
| 91 |
// td.Cmp(t, "John Doe", |
| 92 |
// td.Re(`^(\w+) (\w+)`, []string{"John", "Doe"})) // succeeds |
| 93 |
// td.Cmp(t, "John Doe", |
| 94 |
// td.Re(`^(\w+) (\w+)`, td.Bag("Doe", "John"))) // succeeds |
| 95 |
// |
| 96 |
// When matching many, many lines with a single regexp, it is |
| 97 |
// sometimes difficult to see where the regexp failed in the input |
| 98 |
// string. To avoid that, the regexp can be split by lines and so the |
| 99 |
// failure is easier to locate, thanks to [List] operator and [Flatten]: |
| 100 |
// |
| 101 |
// td.Cmp(t, |
| 102 |
// strings.Split(got, "\n"), |
| 103 |
// td.List(td.Flatten(strings.Split(expectedRe, "\n"), |
| 104 |
// func(line string) any { |
| 105 |
// return `^` + td.Re(line) + `\z` |
| 106 |
// }))) |
| 107 |
// |
| 108 |
// See also the multilines example. |
| 109 |
// |
| 110 |
// See also [ReAll]. |
| 111 |
func Re(reg any, capture ...any) TestDeep { |
| 112 |
r := newRe(reg, capture...) |
| 113 |
r.numMatches = 1 |
| 114 |
return r |
| 115 |
} |
| 116 |
|
| 117 |
// summary(ReAll): allows to successively apply a regexp on a string |
| 118 |
// (or convertible), []byte, error or fmt.Stringer interfaces, and |
| 119 |
// even test the captured groups |
| 120 |
// input(ReAll): str,slice([]byte),if(✓ + fmt.Stringer/error) |
| 121 |
|
| 122 |
// ReAll operator allows to successively apply a regexp on a string |
| 123 |
// (or convertible), []byte, error or [fmt.Stringer] interface (error |
| 124 |
// interface is tested before [fmt.Stringer]) and to match its groups |
| 125 |
// contents. |
| 126 |
// |
| 127 |
// reg is the regexp. It can be a string that is automatically |
| 128 |
// compiled using [regexp.Compile], or a [*regexp.Regexp]. |
| 129 |
// |
| 130 |
// capture is used to match the contents of regexp groups. Groups |
| 131 |
// are presented as a []string or [][]byte depending the original |
| 132 |
// matched data. Note that an other operator can be used here. |
| 133 |
// |
| 134 |
// td.Cmp(t, "John Doe", |
| 135 |
// td.ReAll(`(\w+)(?: |\z)`, []string{"John", "Doe"})) // succeeds |
| 136 |
// td.Cmp(t, "John Doe", |
| 137 |
// td.ReAll(`(\w+)(?: |\z)`, td.Bag("Doe", "John"))) // succeeds |
| 138 |
// |
| 139 |
// See also [Re]. |
| 140 |
func ReAll(reg, capture any) TestDeep { |
| 141 |
r := newRe(reg, capture) |
| 142 |
r.numMatches = -1 |
| 143 |
return r |
| 144 |
} |
| 145 |
|
| 146 |
func (r *tdRe) needCaptures() bool { |
| 147 |
return r.captures.IsValid() |
| 148 |
} |
| 149 |
|
| 150 |
func (r *tdRe) matchByteCaptures(ctx ctxerr.Context, got []byte, result [][][]byte) *ctxerr.Error { |
| 151 |
if len(result) == 0 { |
| 152 |
return r.doesNotMatch(ctx, got) |
| 153 |
} |
| 154 |
|
| 155 |
num := 0 |
| 156 |
for _, set := range result { |
| 157 |
num += len(set) - 1 |
| 158 |
} |
| 159 |
|
| 160 |
// Not perfect but cast captured groups to string |
| 161 |
|
| 162 |
// Special case to accepted expected []any type |
| 163 |
if r.captures.Type() == types.SliceInterface { |
| 164 |
captures := make([]any, 0, num) |
| 165 |
for _, set := range result { |
| 166 |
for _, match := range set[1:] { |
| 167 |
captures = append(captures, string(match)) |
| 168 |
} |
| 169 |
} |
| 170 |
return r.matchCaptures(ctx, captures) |
| 171 |
} |
| 172 |
|
| 173 |
captures := make([]string, 0, num) |
| 174 |
for _, set := range result { |
| 175 |
for _, match := range set[1:] { |
| 176 |
captures = append(captures, string(match)) |
| 177 |
} |
| 178 |
} |
| 179 |
return r.matchCaptures(ctx, captures) |
| 180 |
} |
| 181 |
|
| 182 |
func (r *tdRe) matchStringCaptures(ctx ctxerr.Context, got string, result [][]string) *ctxerr.Error { |
| 183 |
if len(result) == 0 { |
| 184 |
return r.doesNotMatch(ctx, got) |
| 185 |
} |
| 186 |
|
| 187 |
num := 0 |
| 188 |
for _, set := range result { |
| 189 |
num += len(set) - 1 |
| 190 |
} |
| 191 |
|
| 192 |
// Special case to accepted expected []any type |
| 193 |
if r.captures.Type() == types.SliceInterface { |
| 194 |
captures := make([]any, 0, num) |
| 195 |
for _, set := range result { |
| 196 |
for _, match := range set[1:] { |
| 197 |
captures = append(captures, match) |
| 198 |
} |
| 199 |
} |
| 200 |
return r.matchCaptures(ctx, captures) |
| 201 |
} |
| 202 |
|
| 203 |
captures := make([]string, 0, num) |
| 204 |
for _, set := range result { |
| 205 |
captures = append(captures, set[1:]...) |
| 206 |
} |
| 207 |
return r.matchCaptures(ctx, captures) |
| 208 |
} |
| 209 |
|
| 210 |
func (r *tdRe) matchCaptures(ctx ctxerr.Context, captures any) (err *ctxerr.Error) { |
| 211 |
return deepValueEqual( |
| 212 |
ctx.ResetPath("("+ctx.Path.String()+" =~ "+r.String()+")"), |
| 213 |
reflect.ValueOf(captures), r.captures) |
| 214 |
} |
| 215 |
|
| 216 |
func (r *tdRe) matchBool(ctx ctxerr.Context, got any, result bool) *ctxerr.Error { |
| 217 |
if result { |
| 218 |
return nil |
| 219 |
} |
| 220 |
return r.doesNotMatch(ctx, got) |
| 221 |
} |
| 222 |
|
| 223 |
func (r *tdRe) doesNotMatch(ctx ctxerr.Context, got any) *ctxerr.Error { |
| 224 |
if ctx.BooleanError { |
| 225 |
return ctxerr.BooleanError |
| 226 |
} |
| 227 |
return ctx.CollectError(&ctxerr.Error{ |
| 228 |
Message: "does not match Regexp", |
| 229 |
Got: got, |
| 230 |
Expected: types.RawString(r.re.String()), |
| 231 |
}) |
| 232 |
} |
| 233 |
|
| 234 |
func (r *tdRe) Match(ctx ctxerr.Context, got reflect.Value) *ctxerr.Error { |
| 235 |
if r.err != nil { |
| 236 |
return ctx.CollectError(r.err) |
| 237 |
} |
| 238 |
|
| 239 |
var str string |
| 240 |
switch got.Kind() { |
| 241 |
case reflect.String: |
| 242 |
str = got.String() |
| 243 |
|
| 244 |
case reflect.Slice: |
| 245 |
if got.Type().Elem().Kind() == reflect.Uint8 { |
| 246 |
gotBytes := got.Bytes() |
| 247 |
if r.needCaptures() { |
| 248 |
return r.matchByteCaptures(ctx, |
| 249 |
gotBytes, r.re.FindAllSubmatch(gotBytes, r.numMatches)) |
| 250 |
} |
| 251 |
return r.matchBool(ctx, gotBytes, r.re.Match(gotBytes)) |
| 252 |
} |
| 253 |
if ctx.BooleanError { |
| 254 |
return ctxerr.BooleanError |
| 255 |
} |
| 256 |
return ctx.CollectError(&ctxerr.Error{ |
| 257 |
Message: "bad slice type", |
| 258 |
Got: types.RawString("[]" + got.Type().Elem().Kind().String()), |
| 259 |
Expected: types.RawString("[]uint8"), |
| 260 |
}) |
| 261 |
|
| 262 |
default: |
| 263 |
var strOK bool |
| 264 |
iface := dark.MustGetInterface(got) |
| 265 |
|
| 266 |
switch gotVal := iface.(type) { |
| 267 |
case error: |
| 268 |
str = gotVal.Error() |
| 269 |
strOK = true |
| 270 |
case fmt.Stringer: |
| 271 |
str = gotVal.String() |
| 272 |
strOK = true |
| 273 |
default: |
| 274 |
} |
| 275 |
|
| 276 |
if !strOK { |
| 277 |
if ctx.BooleanError { |
| 278 |
return ctxerr.BooleanError |
| 279 |
} |
| 280 |
return ctx.CollectError(&ctxerr.Error{ |
| 281 |
Message: "bad type", |
| 282 |
Got: types.RawString(got.Type().String()), |
| 283 |
Expected: types.RawString( |
| 284 |
"string (convertible) OR fmt.Stringer OR error OR []uint8"), |
| 285 |
}) |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
if r.needCaptures() { |
| 290 |
return r.matchStringCaptures(ctx, |
| 291 |
str, r.re.FindAllStringSubmatch(str, r.numMatches)) |
| 292 |
} |
| 293 |
return r.matchBool(ctx, str, r.re.MatchString(str)) |
| 294 |
} |
| 295 |
|
| 296 |
func (r *tdRe) String() string { |
| 297 |
if r.err != nil { |
| 298 |
return r.stringError() |
| 299 |
} |
| 300 |
return r.re.String() |
| 301 |
} |