| 1 |
// Copyright (c) 2018, 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 |
"bytes" |
| 11 |
"errors" |
| 12 |
"fmt" |
| 13 |
"os" |
| 14 |
"path" |
| 15 |
"reflect" |
| 16 |
"regexp" |
| 17 |
"sort" |
| 18 |
"strconv" |
| 19 |
"strings" |
| 20 |
"sync" |
| 21 |
"unicode" |
| 22 |
"unicode/utf8" |
| 23 |
|
| 24 |
"github.com/maxatome/go-testdeep/internal/ctxerr" |
| 25 |
"github.com/maxatome/go-testdeep/internal/dark" |
| 26 |
"github.com/maxatome/go-testdeep/internal/util" |
| 27 |
) |
| 28 |
|
| 29 |
type tdStruct struct { |
| 30 |
tdExpectedType |
| 31 |
expectedFields fieldInfoSlice |
| 32 |
} |
| 33 |
|
| 34 |
var _ TestDeep = &tdStruct{} |
| 35 |
|
| 36 |
type fieldInfo struct { |
| 37 |
name string |
| 38 |
expected reflect.Value |
| 39 |
index []int |
| 40 |
unexported bool |
| 41 |
} |
| 42 |
|
| 43 |
type fieldInfoSlice []fieldInfo |
| 44 |
|
| 45 |
func (e fieldInfoSlice) Len() int { return len(e) } |
| 46 |
func (e fieldInfoSlice) Less(i, j int) bool { return e[i].name < e[j].name } |
| 47 |
func (e fieldInfoSlice) Swap(i, j int) { e[i], e[j] = e[j], e[i] } |
| 48 |
|
| 49 |
type fieldMatcher struct { |
| 50 |
name string |
| 51 |
match func(string) (bool, error) |
| 52 |
expected any |
| 53 |
order int |
| 54 |
ok bool |
| 55 |
} |
| 56 |
|
| 57 |
var ( |
| 58 |
reMatcherOnce sync.Once |
| 59 |
reMatcher *regexp.Regexp |
| 60 |
errNotAMatcher = errors.New("Not a matcher") |
| 61 |
) |
| 62 |
|
| 63 |
// parseMatcher parses " [NUM] OP PATTERN " and returns 3 strings |
| 64 |
// corresponding to each part or nil if "s" is not a matcher. |
| 65 |
func parseMatcher(s string) []string { |
| 66 |
reMatcherOnce.Do(func() { |
| 67 |
reMatcher = regexp.MustCompile(`^(?:(\d+)\s*)?([=!]~?)\s*(.+)`) |
| 68 |
}) |
| 69 |
subs := reMatcher.FindStringSubmatch(strings.TrimSpace(s)) |
| 70 |
if subs != nil { |
| 71 |
subs = subs[1:] |
| 72 |
} |
| 73 |
return subs |
| 74 |
} |
| 75 |
|
| 76 |
// newFieldMatcher checks name matches "[NUM] OP PATTERN" where NUM |
| 77 |
// is an optional number used to sort patterns, OP is "=~", "!~", "=" |
| 78 |
// or "!" and PATTERN is a regexp (when OP is either "=~" or "!~") or |
| 79 |
// a shell pattern (when OP is either "=" or "!"). |
| 80 |
// |
| 81 |
// NUM, OP and PATTERN can be separated by spaces (or not). |
| 82 |
func newFieldMatcher(name string, expected any) (fieldMatcher, error) { |
| 83 |
subs := parseMatcher(name) |
| 84 |
if subs == nil { |
| 85 |
return fieldMatcher{}, errNotAMatcher |
| 86 |
} |
| 87 |
|
| 88 |
fm := fieldMatcher{ |
| 89 |
name: name, |
| 90 |
expected: expected, |
| 91 |
ok: subs[1][0] == '=', |
| 92 |
} |
| 93 |
|
| 94 |
if subs[0] != "" { |
| 95 |
fm.order, _ = strconv.Atoi(subs[0]) //nolint: errcheck |
| 96 |
} |
| 97 |
|
| 98 |
// Shell pattern |
| 99 |
if subs[1] == "=" || subs[1] == "!" { |
| 100 |
pattern := subs[2] |
| 101 |
fm.match = func(s string) (bool, error) { |
| 102 |
return path.Match(pattern, s) |
| 103 |
} |
| 104 |
return fm, nil |
| 105 |
} |
| 106 |
|
| 107 |
// Regexp |
| 108 |
r, err := regexp.Compile(subs[2]) |
| 109 |
if err != nil { |
| 110 |
return fieldMatcher{}, fmt.Errorf("bad regexp field %#q: %s", name, err) |
| 111 |
} |
| 112 |
fm.match = func(s string) (bool, error) { |
| 113 |
return r.MatchString(s), nil |
| 114 |
} |
| 115 |
return fm, nil |
| 116 |
} |
| 117 |
|
| 118 |
type fieldMatcherSlice []fieldMatcher |
| 119 |
|
| 120 |
func (m fieldMatcherSlice) Len() int { return len(m) } |
| 121 |
func (m fieldMatcherSlice) Less(i, j int) bool { |
| 122 |
if m[i].order != m[j].order { |
| 123 |
return m[i].order < m[j].order |
| 124 |
} |
| 125 |
return m[i].name < m[j].name |
| 126 |
} |
| 127 |
func (m fieldMatcherSlice) Swap(i, j int) { m[i], m[j] = m[j], m[i] } |
| 128 |
|
| 129 |
// StructFields allows to pass struct fields to check in functions |
| 130 |
// [Struct] and [SStruct]. It is a map whose each key is the expected |
| 131 |
// field name (or a regexp or a shell pattern matching a field name, |
| 132 |
// see [Struct] & [SStruct] docs for details) and the corresponding |
| 133 |
// value the expected field value (which can be a [TestDeep] operator |
| 134 |
// as well as a zero value.) |
| 135 |
type StructFields map[string]any |
| 136 |
|
| 137 |
// canonStructField canonicalizes name, a key in a StructFields map, |
| 138 |
// so it can be compared with other keys during a mergeStructFields(). |
| 139 |
// - "name" → "name" |
| 140 |
// - "> name " → ">name" |
| 141 |
// - " 22 =~ [A-Z].*At$ " → "22=~[A-Z].*At$" |
| 142 |
func canonStructField(name string) string { |
| 143 |
r, _ := utf8.DecodeRuneInString(name) |
| 144 |
if r == utf8.RuneError || unicode.IsLetter(r) { |
| 145 |
return name // shortcut |
| 146 |
} |
| 147 |
|
| 148 |
// Overwrite a field |
| 149 |
if strings.HasPrefix(name, ">") { |
| 150 |
nn := strings.TrimSpace(name[1:]) |
| 151 |
if 1+len(nn) == len(name) { |
| 152 |
return name // already canonicalized |
| 153 |
} |
| 154 |
return ">" + nn |
| 155 |
} |
| 156 |
|
| 157 |
// Matcher |
| 158 |
if subs := parseMatcher(name); subs != nil { |
| 159 |
if len(subs[0])+len(subs[1])+len(subs[2]) == len(name) { |
| 160 |
return name // already canonicalized |
| 161 |
} |
| 162 |
return subs[0] + subs[1] + subs[2] |
| 163 |
} |
| 164 |
|
| 165 |
// Will probably raise an error later as it cannot be a field, not |
| 166 |
// an overwritter and not a matcher |
| 167 |
return name |
| 168 |
} |
| 169 |
|
| 170 |
// mergeStructFields merges all sfs items into one StructFields and |
| 171 |
// returns it. |
| 172 |
func mergeStructFields(sfs ...StructFields) StructFields { |
| 173 |
switch len(sfs) { |
| 174 |
case 0: |
| 175 |
return nil |
| 176 |
|
| 177 |
case 1: |
| 178 |
return sfs[0] |
| 179 |
|
| 180 |
default: |
| 181 |
// Do a smart merge so "> pipo" replaces ">pipo " for example. |
| 182 |
canon2field := map[string]string{} |
| 183 |
ret := make(StructFields, len(sfs[0])) |
| 184 |
for _, sf := range sfs { |
| 185 |
for field, value := range sf { |
| 186 |
canon := canonStructField(field) |
| 187 |
if prevField, ok := canon2field[canon]; ok { |
| 188 |
delete(ret, prevField) |
| 189 |
delete(canon2field, canon) |
| 190 |
} else { |
| 191 |
delete(ret, canon) |
| 192 |
} |
| 193 |
if canon != field { |
| 194 |
canon2field[canon] = field |
| 195 |
} |
| 196 |
ret[field] = value |
| 197 |
} |
| 198 |
} |
| 199 |
return ret |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
func newStruct(base base, vmodel reflect.Value) (*tdStruct, reflect.Value) { |
| 204 |
st := tdStruct{ |
| 205 |
tdExpectedType: tdExpectedType{ |
| 206 |
base: base, |
| 207 |
}, |
| 208 |
} |
| 209 |
|
| 210 |
switch vmodel.Kind() { |
| 211 |
case reflect.Ptr: |
| 212 |
if vmodel.Type().Elem().Kind() != reflect.Struct { |
| 213 |
break |
| 214 |
} |
| 215 |
|
| 216 |
st.isPtr = true |
| 217 |
|
| 218 |
if vmodel.IsNil() { |
| 219 |
st.expectedType = vmodel.Type().Elem() |
| 220 |
return &st, reflect.Value{} |
| 221 |
} |
| 222 |
|
| 223 |
vmodel = vmodel.Elem() |
| 224 |
fallthrough |
| 225 |
|
| 226 |
case reflect.Struct: |
| 227 |
st.expectedType = vmodel.Type() |
| 228 |
return &st, vmodel |
| 229 |
} |
| 230 |
|
| 231 |
st.err = ctxerr.OpBadUsage(st.location.Func, |
| 232 |
"(STRUCT|&STRUCT|nil, EXPECTED_FIELDS)", |
| 233 |
vmodel.Interface(), 1, true) |
| 234 |
return &st, reflect.Value{} |
| 235 |
} |
| 236 |
|
| 237 |
// structTypeString returns stringified t. It is the caller |
| 238 |
// responsibility to check t is a struct type. |
| 239 |
// - struct{} → "struct {}" |
| 240 |
// - pkg.MyType → "struct pkg.MyType" |
| 241 |
func structTypeString(t reflect.Type) string { |
| 242 |
if t.Name() == "" { |
| 243 |
return t.String() |
| 244 |
} |
| 245 |
return "struct " + t.String() |
| 246 |
} |
| 247 |
|
| 248 |
func anyStruct(base base, model reflect.Value, expectedFields StructFields, strict bool) *tdStruct { |
| 249 |
st, vmodel := newStruct(base, model) |
| 250 |
if st.err != nil { |
| 251 |
return st |
| 252 |
} |
| 253 |
|
| 254 |
st.expectedFields = make([]fieldInfo, 0, len(expectedFields)) |
| 255 |
checkedFields := make(map[string]bool, len(expectedFields)) |
| 256 |
var matchers fieldMatcherSlice //nolint: prealloc |
| 257 |
|
| 258 |
// Check that all given fields are available in model |
| 259 |
stType := st.expectedType |
| 260 |
for fieldName, expectedValue := range expectedFields { |
| 261 |
field, found := stType.FieldByName(fieldName) |
| 262 |
if found { |
| 263 |
st.addExpectedValue(field, expectedValue, "") |
| 264 |
checkedFields[fieldName] = false |
| 265 |
continue |
| 266 |
} |
| 267 |
|
| 268 |
// overwrite model field: ">fieldName", "> fieldName" |
| 269 |
if strings.HasPrefix(fieldName, ">") { |
| 270 |
name := strings.TrimSpace(fieldName[1:]) |
| 271 |
field, found = stType.FieldByName(name) |
| 272 |
if !found { |
| 273 |
st.err = ctxerr.OpBad(st.location.Func, |
| 274 |
"%s has no field %q (from %q)", structTypeString(stType), name, fieldName) |
| 275 |
return st |
| 276 |
} |
| 277 |
st.addExpectedValue( |
| 278 |
field, expectedValue, |
| 279 |
fmt.Sprintf(" (from %q)", fieldName)) |
| 280 |
checkedFields[name] = true |
| 281 |
continue |
| 282 |
} |
| 283 |
|
| 284 |
// matcher: "=~At$", "!~At$", "=*At", "!*At" |
| 285 |
matcher, err := newFieldMatcher(fieldName, expectedValue) |
| 286 |
if err != nil { |
| 287 |
if err == errNotAMatcher { |
| 288 |
st.err = ctxerr.OpBad(st.location.Func, |
| 289 |
"%s has no field %q", structTypeString(stType), fieldName) |
| 290 |
} else { |
| 291 |
st.err = ctxerr.OpBad(st.location.Func, err.Error()) |
| 292 |
} |
| 293 |
return st |
| 294 |
} |
| 295 |
matchers = append(matchers, matcher) |
| 296 |
} |
| 297 |
|
| 298 |
// Get all field names |
| 299 |
allFields := map[string]struct{}{} |
| 300 |
stType.FieldByNameFunc(func(fieldName string) bool { |
| 301 |
allFields[fieldName] = struct{}{} |
| 302 |
return false |
| 303 |
}) |
| 304 |
|
| 305 |
// Check initialized fields in model |
| 306 |
if vmodel.IsValid() { |
| 307 |
for fieldName := range allFields { |
| 308 |
overwrite, alreadySet := checkedFields[fieldName] |
| 309 |
if overwrite { |
| 310 |
continue |
| 311 |
} |
| 312 |
|
| 313 |
field, _ := stType.FieldByName(fieldName) |
| 314 |
if field.Anonymous { |
| 315 |
continue |
| 316 |
} |
| 317 |
|
| 318 |
vfield := vmodel.FieldByIndex(field.Index) |
| 319 |
|
| 320 |
// Try to force access to unexported fields |
| 321 |
fieldIf, ok := dark.GetInterface(vfield, true) |
| 322 |
if !ok { |
| 323 |
// Probably in an environment where "unsafe" package is forbidden… :( |
| 324 |
fmt.Fprintf(os.Stderr, //nolint: errcheck |
| 325 |
"%s(): field %s is unexported and cannot be overridden, skip it from model.\n", |
| 326 |
st.location.Func, |
| 327 |
fieldName) |
| 328 |
continue |
| 329 |
} |
| 330 |
|
| 331 |
// If non-zero field |
| 332 |
if !reflect.DeepEqual(reflect.Zero(field.Type).Interface(), fieldIf) { |
| 333 |
if alreadySet { |
| 334 |
st.err = ctxerr.OpBad(st.location.Func, |
| 335 |
"non zero field %s in model already exists in expectedFields", |
| 336 |
fieldName) |
| 337 |
return st |
| 338 |
} |
| 339 |
|
| 340 |
st.expectedFields = append(st.expectedFields, fieldInfo{ |
| 341 |
name: fieldName, |
| 342 |
expected: vfield, |
| 343 |
index: field.Index, |
| 344 |
unexported: field.PkgPath != "", |
| 345 |
}) |
| 346 |
checkedFields[fieldName] = true |
| 347 |
} |
| 348 |
} |
| 349 |
} |
| 350 |
|
| 351 |
// At least one matcher (regexp/shell pattern) |
| 352 |
if matchers != nil { |
| 353 |
sort.Sort(matchers) // always process matchers in the same order |
| 354 |
for _, m := range matchers { |
| 355 |
for fieldName := range allFields { |
| 356 |
if _, ok := checkedFields[fieldName]; ok { |
| 357 |
continue |
| 358 |
} |
| 359 |
field, _ := stType.FieldByName(fieldName) |
| 360 |
if field.Anonymous { |
| 361 |
continue |
| 362 |
} |
| 363 |
|
| 364 |
ok, err := m.match(fieldName) |
| 365 |
if err != nil { |
| 366 |
st.err = ctxerr.OpBad(st.location.Func, |
| 367 |
"bad shell pattern field %#q: %s", m.name, err) |
| 368 |
return st |
| 369 |
} |
| 370 |
if ok == m.ok { |
| 371 |
st.addExpectedValue( |
| 372 |
field, m.expected, |
| 373 |
fmt.Sprintf(" (from pattern %#q)", m.name)) |
| 374 |
checkedFields[fieldName] = true |
| 375 |
} |
| 376 |
} |
| 377 |
} |
| 378 |
} |
| 379 |
|
| 380 |
// If strict, fill non explicitly expected fields to zero |
| 381 |
if strict { |
| 382 |
for fieldName := range allFields { |
| 383 |
if _, ok := checkedFields[fieldName]; ok { |
| 384 |
continue |
| 385 |
} |
| 386 |
|
| 387 |
field, _ := stType.FieldByName(fieldName) |
| 388 |
if field.Anonymous { |
| 389 |
continue |
| 390 |
} |
| 391 |
|
| 392 |
st.expectedFields = append(st.expectedFields, fieldInfo{ |
| 393 |
name: fieldName, |
| 394 |
expected: reflect.New(field.Type).Elem(), // zero |
| 395 |
index: field.Index, |
| 396 |
unexported: field.PkgPath != "", |
| 397 |
}) |
| 398 |
} |
| 399 |
} |
| 400 |
|
| 401 |
sort.Sort(st.expectedFields) |
| 402 |
|
| 403 |
return st |
| 404 |
} |
| 405 |
|
| 406 |
func (s *tdStruct) addExpectedValue(field reflect.StructField, expectedValue any, ctxInfo string) { |
| 407 |
var vexpectedValue reflect.Value |
| 408 |
if expectedValue == nil { |
| 409 |
switch field.Type.Kind() { |
| 410 |
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, |
| 411 |
reflect.Ptr, reflect.Slice: |
| 412 |
vexpectedValue = reflect.Zero(field.Type) // change to a typed nil |
| 413 |
// default: |
| 414 |
// Don't raise an error if field cannot be nil as a smuggle hook can |
| 415 |
// change it at fly during the comparison |
| 416 |
} |
| 417 |
} else { |
| 418 |
vexpectedValue = reflect.ValueOf(expectedValue) |
| 419 |
// Don't check vexpectedValue type against field one as a |
| 420 |
// smuggle hook can change it at fly during the comparison |
| 421 |
} |
| 422 |
|
| 423 |
s.expectedFields = append(s.expectedFields, fieldInfo{ |
| 424 |
name: field.Name + ctxInfo, |
| 425 |
expected: vexpectedValue, |
| 426 |
index: field.Index, |
| 427 |
unexported: field.PkgPath != "", |
| 428 |
}) |
| 429 |
} |
| 430 |
|
| 431 |
// summary(Struct): compares the contents of a struct or a pointer on |
| 432 |
// a struct |
| 433 |
// input(Struct): struct,ptr(ptr on struct) |
| 434 |
|
| 435 |
// Struct operator compares the contents of a struct or a pointer on a |
| 436 |
// struct against the non-zero values of model (if any) and the |
| 437 |
// values of expectedFields. See [SStruct] to compares against zero |
| 438 |
// fields without specifying them in expectedFields. |
| 439 |
// |
| 440 |
// model must be the same type as compared data. If the expected type |
| 441 |
// is anonymous or private, model can be nil. In this case it is |
| 442 |
// considered lazy and determined each time the operator is involved |
| 443 |
// in a match, see below. |
| 444 |
// |
| 445 |
// expectedFields can be omitted, if no zero entries are expected |
| 446 |
// and no [TestDeep] operators are involved. If expectedFields |
| 447 |
// contains more than one item, all items are merged before their use, |
| 448 |
// from left to right. |
| 449 |
// |
| 450 |
// td.Cmp(t, got, td.Struct( |
| 451 |
// Person{ |
| 452 |
// Name: "John Doe", |
| 453 |
// }, |
| 454 |
// td.StructFields{ |
| 455 |
// "Children": 4, |
| 456 |
// }, |
| 457 |
// td.StructFields{ |
| 458 |
// "Age": td.Between(40, 45), |
| 459 |
// "Children": 0, // overwrite 4 |
| 460 |
// }), |
| 461 |
// ) |
| 462 |
// |
| 463 |
// It is an error to set a non-zero field in model AND to set the |
| 464 |
// same field in expectedFields, as in such cases the Struct |
| 465 |
// operator does not know if the user wants to override the non-zero |
| 466 |
// model field value or if it is an error. To explicitly override a |
| 467 |
// non-zero model in expectedFields, just prefix its name with a |
| 468 |
// ">" (followed by some optional spaces), as in: |
| 469 |
// |
| 470 |
// td.Cmp(t, got, td.Struct( |
| 471 |
// Person{ |
| 472 |
// Name: "John Doe", |
| 473 |
// Age: 23, |
| 474 |
// Children: 4, |
| 475 |
// }, |
| 476 |
// td.StructFields{ |
| 477 |
// "> Age": td.Between(40, 45), |
| 478 |
// ">Children": 0, // spaces after ">" are optional |
| 479 |
// }), |
| 480 |
// ) |
| 481 |
// |
| 482 |
// expectedFields can also contain regexps or shell patterns to |
| 483 |
// match multiple fields not explicitly listed in model and in |
| 484 |
// expectedFields. Regexps are prefixed by "=~" or "!~" to |
| 485 |
// respectively match or don't-match. Shell patterns are prefixed by "=" |
| 486 |
// or "!" to respectively match or don't-match. |
| 487 |
// |
| 488 |
// td.Cmp(t, got, td.Struct( |
| 489 |
// Person{ |
| 490 |
// Name: "John Doe", |
| 491 |
// }, |
| 492 |
// td.StructFields{ |
| 493 |
// "=*At": td.Lte(time.Now()), // matches CreatedAt & UpdatedAt fields using shell pattern |
| 494 |
// "=~^[a-z]": td.Ignore(), // explicitly ignore private fields using a regexp |
| 495 |
// }), |
| 496 |
// ) |
| 497 |
// |
| 498 |
// When several patterns can match a same field, it is advised to tell |
| 499 |
// go-testdeep in which order patterns should be tested, as once a |
| 500 |
// pattern matches a field, the other patterns are ignored for this |
| 501 |
// field. To do so, each pattern can be prefixed by a number, as in: |
| 502 |
// |
| 503 |
// td.Cmp(t, got, td.Struct( |
| 504 |
// Person{ |
| 505 |
// Name: "John Doe", |
| 506 |
// }, |
| 507 |
// td.StructFields{ |
| 508 |
// "1=*At": td.Lte(time.Now()), |
| 509 |
// "2=~^[a-z]": td.NotNil(), |
| 510 |
// }), |
| 511 |
// ) |
| 512 |
// |
| 513 |
// This way, "*At" shell pattern is always used before "^[a-z]" |
| 514 |
// regexp, so if a field "createdAt" exists it is tested against |
| 515 |
// time.Now() and never against [NotNil]. A pattern without a |
| 516 |
// prefix number is the same as specifying "0" as prefix. |
| 517 |
// |
| 518 |
// To make it clearer, some spaces can be added, as well as bigger |
| 519 |
// numbers used: |
| 520 |
// |
| 521 |
// td.Cmp(t, got, td.Struct( |
| 522 |
// Person{ |
| 523 |
// Name: "John Doe", |
| 524 |
// }, |
| 525 |
// td.StructFields{ |
| 526 |
// " 900 = *At": td.Lte(time.Now()), |
| 527 |
// "2000 =~ ^[a-z]": td.NotNil(), |
| 528 |
// }), |
| 529 |
// ) |
| 530 |
// |
| 531 |
// The following example combines all possibilities: |
| 532 |
// |
| 533 |
// td.Cmp(t, got, td.Struct( |
| 534 |
// Person{ |
| 535 |
// NickName: "Joe", |
| 536 |
// }, |
| 537 |
// td.StructFields{ |
| 538 |
// "Firstname": td.Any("John", "Johnny"), |
| 539 |
// "1 = *[nN]ame": td.NotEmpty(), // matches LastName, lastname, … |
| 540 |
// "2 ! [A-Z]*": td.NotZero(), // matches all private fields |
| 541 |
// "3 =~ ^(Crea|Upda)tedAt$": td.Gte(time.Now()), |
| 542 |
// "4 !~ ^(Dogs|Children)$": td.Zero(), // matches all remaining fields except Dogs and Children |
| 543 |
// "5 =~ .": td.NotNil(), // matches all remaining fields (same as "5 = *") |
| 544 |
// }), |
| 545 |
// ) |
| 546 |
// |
| 547 |
// If the expected type is private to the current package, it cannot |
| 548 |
// be passed as model. To overcome this limitation, model can be nil, |
| 549 |
// it is then considered as lazy. This way, the model is automatically |
| 550 |
// set during each match to the same type (still requiring struct or |
| 551 |
// struct pointer) of the compared data. Similarly, testing an |
| 552 |
// anonymous struct can be boring as all fields have to be re-declared |
| 553 |
// to define model. A nil model avoids that: |
| 554 |
// |
| 555 |
// got := struct { |
| 556 |
// name string |
| 557 |
// age int |
| 558 |
// }{"Bob", 42} |
| 559 |
// td.Cmp(t, got, td.Struct(nil, td.StructFields{"age": td.Between(40, 42)})) |
| 560 |
// |
| 561 |
// During a match, all expected fields must be found to |
| 562 |
// succeed. Non-expected fields (and so zero model fields) are |
| 563 |
// ignored. |
| 564 |
// |
| 565 |
// TypeBehind method returns the [reflect.Type] of model. |
| 566 |
// |
| 567 |
// See also [SStruct]. |
| 568 |
func Struct(model any, expectedFields ...StructFields) TestDeep { |
| 569 |
ef := mergeStructFields(expectedFields...) |
| 570 |
if model == nil { |
| 571 |
return newStructLazy(ef, false) |
| 572 |
} |
| 573 |
return anyStruct(newBase(3), reflect.ValueOf(model), ef, false) |
| 574 |
} |
| 575 |
|
| 576 |
// summary(SStruct): strictly compares the contents of a struct or a |
| 577 |
// pointer on a struct |
| 578 |
// input(SStruct): struct,ptr(ptr on struct) |
| 579 |
|
| 580 |
// SStruct operator (aka strict-[Struct]) compares the contents of a |
| 581 |
// struct or a pointer on a struct against values of model (if any) |
| 582 |
// and the values of expectedFields. The zero values are compared |
| 583 |
// too even if they are omitted from expectedFields: that is the |
| 584 |
// difference with [Struct] operator. |
| 585 |
// |
| 586 |
// model must be the same type as compared data. If the expected type |
| 587 |
// is private or anonymous, model can be nil. In this case it is |
| 588 |
// considered lazy and determined each time the operator is involved |
| 589 |
// in a match, see below. |
| 590 |
// |
| 591 |
// expectedFields can be omitted, if no [TestDeep] operators are |
| 592 |
// involved. If expectedFields contains more than one item, all |
| 593 |
// items are merged before their use, from left to right. |
| 594 |
// |
| 595 |
// To ignore a field, one has to specify it in expectedFields and |
| 596 |
// use the [Ignore] operator. |
| 597 |
// |
| 598 |
// td.Cmp(t, got, td.SStruct( |
| 599 |
// Person{ |
| 600 |
// Name: "John Doe", |
| 601 |
// }, |
| 602 |
// td.StructFields{ |
| 603 |
// "Children": 4, |
| 604 |
// }, |
| 605 |
// td.StructFields{ |
| 606 |
// "Age": td.Between(40, 45), |
| 607 |
// "Children": td.Ignore(), // overwrite 4 |
| 608 |
// }), |
| 609 |
// ) |
| 610 |
// |
| 611 |
// It is an error to set a non-zero field in model AND to set the |
| 612 |
// same field in expectedFields, as in such cases the SStruct |
| 613 |
// operator does not know if the user wants to override the non-zero |
| 614 |
// model field value or if it is an error. To explicitly override a |
| 615 |
// non-zero model in expectedFields, just prefix its name with a |
| 616 |
// ">" (followed by some optional spaces), as in: |
| 617 |
// |
| 618 |
// td.Cmp(t, got, td.SStruct( |
| 619 |
// Person{ |
| 620 |
// Name: "John Doe", |
| 621 |
// Age: 23, |
| 622 |
// Children: 4, |
| 623 |
// }, |
| 624 |
// td.StructFields{ |
| 625 |
// "> Age": td.Between(40, 45), |
| 626 |
// ">Children": 0, // spaces after ">" are optional |
| 627 |
// }), |
| 628 |
// ) |
| 629 |
// |
| 630 |
// expectedFields can also contain regexps or shell patterns to |
| 631 |
// match multiple fields not explicitly listed in model and in |
| 632 |
// expectedFields. Regexps are prefixed by "=~" or "!~" to |
| 633 |
// respectively match or don't-match. Shell patterns are prefixed by "=" |
| 634 |
// or "!" to respectively match or don't-match. |
| 635 |
// |
| 636 |
// td.Cmp(t, got, td.SStruct( |
| 637 |
// Person{ |
| 638 |
// Name: "John Doe", |
| 639 |
// }, |
| 640 |
// td.StructFields{ |
| 641 |
// "=*At": td.Lte(time.Now()), // matches CreatedAt & UpdatedAt fields using shell pattern |
| 642 |
// "=~^[a-z]": td.Ignore(), // explicitly ignore private fields using a regexp |
| 643 |
// }), |
| 644 |
// ) |
| 645 |
// |
| 646 |
// When several patterns can match a same field, it is advised to tell |
| 647 |
// go-testdeep in which order patterns should be tested, as once a |
| 648 |
// pattern matches a field, the other patterns are ignored for this |
| 649 |
// field. To do so, each pattern can be prefixed by a number, as in: |
| 650 |
// |
| 651 |
// td.Cmp(t, got, td.SStruct( |
| 652 |
// Person{ |
| 653 |
// Name: "John Doe", |
| 654 |
// }, |
| 655 |
// td.StructFields{ |
| 656 |
// "1=*At": td.Lte(time.Now()), |
| 657 |
// "2=~^[a-z]": td.NotNil(), |
| 658 |
// }), |
| 659 |
// ) |
| 660 |
// |
| 661 |
// This way, "*At" shell pattern is always used before "^[a-z]" |
| 662 |
// regexp, so if a field "createdAt" exists it is tested against |
| 663 |
// time.Now() and never against [NotNil]. A pattern without a |
| 664 |
// prefix number is the same as specifying "0" as prefix. |
| 665 |
// |
| 666 |
// To make it clearer, some spaces can be added, as well as bigger |
| 667 |
// numbers used: |
| 668 |
// |
| 669 |
// td.Cmp(t, got, td.SStruct( |
| 670 |
// Person{ |
| 671 |
// Name: "John Doe", |
| 672 |
// }, |
| 673 |
// td.StructFields{ |
| 674 |
// " 900 = *At": td.Lte(time.Now()), |
| 675 |
// "2000 =~ ^[a-z]": td.NotNil(), |
| 676 |
// }), |
| 677 |
// ) |
| 678 |
// |
| 679 |
// The following example combines all possibilities: |
| 680 |
// |
| 681 |
// td.Cmp(t, got, td.SStruct( |
| 682 |
// Person{ |
| 683 |
// NickName: "Joe", |
| 684 |
// }, |
| 685 |
// td.StructFields{ |
| 686 |
// "Firstname": td.Any("John", "Johnny"), |
| 687 |
// "1 = *[nN]ame": td.NotEmpty(), // matches LastName, lastname, … |
| 688 |
// "2 ! [A-Z]*": td.NotZero(), // matches all private fields |
| 689 |
// "3 =~ ^(Crea|Upda)tedAt$": td.Gte(time.Now()), |
| 690 |
// "4 !~ ^(Dogs|Children)$": td.Zero(), // matches all remaining fields except Dogs and Children |
| 691 |
// "5 =~ .": td.NotNil(), // matches all remaining fields (same as "5 = *") |
| 692 |
// }), |
| 693 |
// ) |
| 694 |
// |
| 695 |
// If the expected type is private to the current package, it cannot |
| 696 |
// be passed as model. To overcome this limitation, model can be nil, |
| 697 |
// it is then considered as lazy. This way, the model is automatically |
| 698 |
// set during each match to the same type (still requiring struct or |
| 699 |
// struct pointer) of the compared data. Similarly, testing an |
| 700 |
// anonymous struct can be boring as all fields have to be re-declared |
| 701 |
// to define model. A nil model avoids that: |
| 702 |
// |
| 703 |
// got := struct { |
| 704 |
// name string |
| 705 |
// age int |
| 706 |
// }{"Bob", 42} |
| 707 |
// td.Cmp(t, got, td.SStruct(nil, td.StructFields{ |
| 708 |
// "name": "Bob", |
| 709 |
// "age": td.Between(40, 42), |
| 710 |
// })) |
| 711 |
// |
| 712 |
// During a match, all expected and zero fields must be found to |
| 713 |
// succeed. |
| 714 |
// |
| 715 |
// TypeBehind method returns the [reflect.Type] of model. |
| 716 |
// |
| 717 |
// See also [SStruct]. |
| 718 |
func SStruct(model any, expectedFields ...StructFields) TestDeep { |
| 719 |
ef := mergeStructFields(expectedFields...) |
| 720 |
if model == nil { |
| 721 |
return newStructLazy(ef, false) |
| 722 |
} |
| 723 |
return anyStruct(newBase(3), reflect.ValueOf(model), ef, true) |
| 724 |
} |
| 725 |
|
| 726 |
func (s *tdStruct) Match(ctx ctxerr.Context, got reflect.Value) (err *ctxerr.Error) { |
| 727 |
if s.err != nil { |
| 728 |
return ctx.CollectError(s.err) |
| 729 |
} |
| 730 |
|
| 731 |
err = s.checkPtr(ctx, &got, false) |
| 732 |
if err != nil { |
| 733 |
return ctx.CollectError(err) |
| 734 |
} |
| 735 |
|
| 736 |
err = s.checkType(ctx, got) |
| 737 |
if err != nil { |
| 738 |
return ctx.CollectError(err) |
| 739 |
} |
| 740 |
|
| 741 |
ignoreUnexported := ctx.IgnoreUnexported || ctx.Hooks.IgnoreUnexported(got.Type()) |
| 742 |
|
| 743 |
for _, fieldInfo := range s.expectedFields { |
| 744 |
if ignoreUnexported && fieldInfo.unexported { |
| 745 |
continue |
| 746 |
} |
| 747 |
err = deepValueEqual(ctx.AddField(fieldInfo.name), |
| 748 |
got.FieldByIndex(fieldInfo.index), fieldInfo.expected) |
| 749 |
if err != nil { |
| 750 |
return |
| 751 |
} |
| 752 |
} |
| 753 |
return nil |
| 754 |
} |
| 755 |
|
| 756 |
func (s *tdStruct) String() string { |
| 757 |
if s.err != nil { |
| 758 |
return s.stringError() |
| 759 |
} |
| 760 |
|
| 761 |
buf := bytes.NewBufferString(s.location.Func) |
| 762 |
buf.WriteByte('(') |
| 763 |
|
| 764 |
if s.isPtr { |
| 765 |
buf.WriteByte('*') |
| 766 |
} |
| 767 |
|
| 768 |
buf.WriteString(s.expectedType.String()) |
| 769 |
|
| 770 |
if len(s.expectedFields) == 0 { |
| 771 |
buf.WriteString("{})") |
| 772 |
} else { |
| 773 |
buf.WriteString("{\n") |
| 774 |
|
| 775 |
maxLen := 0 |
| 776 |
for _, fieldInfo := range s.expectedFields { |
| 777 |
if len(fieldInfo.name) > maxLen { |
| 778 |
maxLen = len(fieldInfo.name) |
| 779 |
} |
| 780 |
} |
| 781 |
maxLen++ |
| 782 |
for _, fieldInfo := range s.expectedFields { |
| 783 |
fmt.Fprintf(buf, " %-*s %s\n", //nolint: errcheck |
| 784 |
maxLen, fieldInfo.name+":", util.ToString(fieldInfo.expected)) |
| 785 |
} |
| 786 |
|
| 787 |
buf.WriteString("})") |
| 788 |
} |
| 789 |
|
| 790 |
return buf.String() |
| 791 |
} |