| 1 |
// Licensed under the MIT license, see LICENSE file for details. |
| 2 |
|
| 3 |
package qt |
| 4 |
|
| 5 |
import ( |
| 6 |
"encoding/json" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"reflect" |
| 10 |
"regexp" |
| 11 |
"strings" |
| 12 |
|
| 13 |
"github.com/google/go-cmp/cmp" |
| 14 |
"github.com/google/go-cmp/cmp/cmpopts" |
| 15 |
"github.com/kr/pretty" |
| 16 |
) |
| 17 |
|
| 18 |
// Checker is implemented by types used as part of Check/Assert invocations. |
| 19 |
type Checker interface { |
| 20 |
// Check runs the check for this checker. |
| 21 |
// On failure, the returned error is printed along with |
| 22 |
// the checker arguments (obtained by calling Args) |
| 23 |
// and key-value pairs added by calling the note function. |
| 24 |
// |
| 25 |
// If Check returns ErrSilent, neither the checker arguments nor |
| 26 |
// the error are printed; values with note are still printed. |
| 27 |
Check(note func(key string, value any)) error |
| 28 |
|
| 29 |
// Args returns a slice of all the arguments passed |
| 30 |
// to the checker. The first argument should always be |
| 31 |
// the "got" value being checked. |
| 32 |
Args() []Arg |
| 33 |
} |
| 34 |
|
| 35 |
// Arg holds a single argument to a checker. |
| 36 |
type Arg struct { |
| 37 |
Name string |
| 38 |
Value any |
| 39 |
} |
| 40 |
|
| 41 |
// negatedError is implemented on checkers that want to customize the error that |
| 42 |
// is returned when they have succeeded but that success has been negated. |
| 43 |
type negatedError interface { |
| 44 |
negatedError() error |
| 45 |
} |
| 46 |
|
| 47 |
// Equals returns a Checker checking equality of two comparable values. |
| 48 |
// |
| 49 |
// Note that T is not constrained to be comparable because |
| 50 |
// we also allow comparing interface values which currently |
| 51 |
// do not satisfy that constraint. |
| 52 |
func Equals[T any](got, want T) Checker { |
| 53 |
return &equalsChecker[T]{argPairOf(got, want)} |
| 54 |
} |
| 55 |
|
| 56 |
type equalsChecker[T any] struct { |
| 57 |
argPair[T, T] |
| 58 |
} |
| 59 |
|
| 60 |
func (c *equalsChecker[T]) Check(note func(key string, value any)) (err error) { |
| 61 |
defer func() { |
| 62 |
// A panic is raised when the provided values are interfaces containing |
| 63 |
// non-comparable values. |
| 64 |
if r := recover(); r != nil { |
| 65 |
err = fmt.Errorf("%s", r) |
| 66 |
} |
| 67 |
}() |
| 68 |
|
| 69 |
if any(c.got) == any(c.want) { |
| 70 |
return nil |
| 71 |
} |
| 72 |
|
| 73 |
// Customize error message for non-nil errors. |
| 74 |
if typeOf[T]() == typeOf[error]() { |
| 75 |
if any(c.want) == nil { |
| 76 |
return errors.New("got non-nil error") |
| 77 |
} |
| 78 |
if any(c.got) == nil { |
| 79 |
return errors.New("got nil error") |
| 80 |
} |
| 81 |
// Show error types when comparing errors with different types. |
| 82 |
gotType := reflect.TypeOf(c.got) |
| 83 |
wantType := reflect.TypeOf(c.want) |
| 84 |
if gotType != wantType { |
| 85 |
note("got type", Unquoted(gotType.String())) |
| 86 |
note("want type", Unquoted(wantType.String())) |
| 87 |
} |
| 88 |
return errors.New("values are not equal") |
| 89 |
} |
| 90 |
|
| 91 |
// Show line diff when comparing different multi-line strings. |
| 92 |
if c, ok := any(c).(*equalsChecker[string]); ok { |
| 93 |
isMultiLine := func(s string) bool { |
| 94 |
i := strings.Index(s, "\n") |
| 95 |
return i != -1 && i < len(s)-1 |
| 96 |
} |
| 97 |
if isMultiLine(c.got) || isMultiLine(c.want) { |
| 98 |
diff := cmp.Diff(strings.SplitAfter(c.want, "\n"), strings.SplitAfter(c.got, "\n")) |
| 99 |
note("line diff (-want +got)", Unquoted(diff)) |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
return errors.New("values are not equal") |
| 104 |
} |
| 105 |
|
| 106 |
// DeepEquals returns a Checker checking equality of two values |
| 107 |
// using cmp.DeepEqual. |
| 108 |
func DeepEquals[T any](got, want T) Checker { |
| 109 |
return CmpEquals(got, want) |
| 110 |
} |
| 111 |
|
| 112 |
// CmpEquals is like DeepEquals but allows custom compare options |
| 113 |
// to be passed too, to allow unexported fields to be compared. |
| 114 |
// |
| 115 |
// It can be useful to define your own version that uses a custom |
| 116 |
// set of compare options. See example for details. |
| 117 |
func CmpEquals[T any](got, want T, opts ...cmp.Option) Checker { |
| 118 |
return &cmpEqualsChecker[T]{ |
| 119 |
argPair: argPairOf(got, want), |
| 120 |
opts: opts, |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
type cmpEqualsChecker[T any] struct { |
| 125 |
argPair[T, T] |
| 126 |
opts []cmp.Option |
| 127 |
} |
| 128 |
|
| 129 |
func (c *cmpEqualsChecker[T]) Check(note func(key string, value any)) (err error) { |
| 130 |
defer func() { |
| 131 |
// A panic is raised in some cases, for instance when trying to compare |
| 132 |
// structs with unexported fields and neither AllowUnexported nor |
| 133 |
// cmpopts.IgnoreUnexported are provided. |
| 134 |
if r := recover(); r != nil { |
| 135 |
err = BadCheckf("%s", r) |
| 136 |
} |
| 137 |
}() |
| 138 |
if diff := cmp.Diff(c.want, c.got, c.opts...); diff != "" { |
| 139 |
// Only output values when the verbose flag is set. |
| 140 |
note("error", Unquoted("values are not deep equal")) |
| 141 |
note("diff (-want +got)", Unquoted(diff)) |
| 142 |
note("got", SuppressedIfLong{c.got}) |
| 143 |
note("want", SuppressedIfLong{c.want}) |
| 144 |
return ErrSilent |
| 145 |
} |
| 146 |
return nil |
| 147 |
} |
| 148 |
|
| 149 |
// ContentEquals is like DeepEquals but any slices in the compared values will |
| 150 |
// be sorted before being compared. |
| 151 |
func ContentEquals[T any](got, want T) Checker { |
| 152 |
return CmpEquals(got, want, cmpopts.SortSlices(func(x, y any) bool { |
| 153 |
// TODO frankban: implement a proper sort function. |
| 154 |
return pretty.Sprint(x) < pretty.Sprint(y) |
| 155 |
})) |
| 156 |
} |
| 157 |
|
| 158 |
// Matches returns a Checker checking that the provided string matches the |
| 159 |
// provided regular expression pattern. If want is a string, the pattern will be |
| 160 |
// anchored; that is: |
| 161 |
// |
| 162 |
// Matches(got, "foo") |
| 163 |
// |
| 164 |
// is equivalent to: |
| 165 |
// |
| 166 |
// Matches(got, "^foo$") |
| 167 |
// |
| 168 |
// If want is of type *regexp.Regexp, it will be matched as is. |
| 169 |
func Matches[StringOrRegexp string | *regexp.Regexp](got string, want StringOrRegexp) Checker { |
| 170 |
return &matchesChecker{ |
| 171 |
got: got, |
| 172 |
want: want, |
| 173 |
match: newMatcher(want), |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
type matchesChecker struct { |
| 178 |
got string |
| 179 |
want any |
| 180 |
match matcher |
| 181 |
} |
| 182 |
|
| 183 |
func (c *matchesChecker) Check(note func(key string, value any)) error { |
| 184 |
return c.match(c.got, "value does not match regexp", note) |
| 185 |
} |
| 186 |
|
| 187 |
func (c *matchesChecker) Args() []Arg { |
| 188 |
return []Arg{{Name: "got value", Value: c.got}, {Name: "regexp", Value: c.want}} |
| 189 |
} |
| 190 |
|
| 191 |
// ErrorMatches returns a Checker checking that the provided value is an error |
| 192 |
// whose message matches the provided regular expression pattern |
| 193 |
// (see [Matches] for more details on how the pattern is matched). |
| 194 |
func ErrorMatches[StringOrRegexp string | *regexp.Regexp](got error, want StringOrRegexp) Checker { |
| 195 |
return &errorMatchesChecker{ |
| 196 |
got: got, |
| 197 |
want: want, |
| 198 |
match: newMatcher(want), |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
type errorMatchesChecker struct { |
| 203 |
got error |
| 204 |
want any |
| 205 |
match matcher |
| 206 |
} |
| 207 |
|
| 208 |
func (c *errorMatchesChecker) Check(note func(key string, value any)) error { |
| 209 |
if c.got == nil { |
| 210 |
return errors.New("got nil error but want non-nil") |
| 211 |
} |
| 212 |
return c.match(c.got.Error(), "error does not match regexp", note) |
| 213 |
} |
| 214 |
|
| 215 |
func (c *errorMatchesChecker) Args() []Arg { |
| 216 |
return []Arg{{Name: "got error", Value: c.got}, {Name: "regexp", Value: c.want}} |
| 217 |
} |
| 218 |
|
| 219 |
// PanicMatches returns a Checker checking that the provided function panics |
| 220 |
// with a message matching the provided regular expression pattern. |
| 221 |
// (see [Matches] for more details on how the pattern is matched). |
| 222 |
func PanicMatches[StringOrRegexp string | *regexp.Regexp](f func(), want StringOrRegexp) Checker { |
| 223 |
return &panicMatchesChecker{ |
| 224 |
got: f, |
| 225 |
want: want, |
| 226 |
match: newMatcher(want), |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
type panicMatchesChecker struct { |
| 231 |
got func() |
| 232 |
want any |
| 233 |
match matcher |
| 234 |
} |
| 235 |
|
| 236 |
func (c *panicMatchesChecker) Check(note func(key string, value any)) (err error) { |
| 237 |
defer func() { |
| 238 |
r := recover() |
| 239 |
if r == nil { |
| 240 |
err = errors.New("function did not panic") |
| 241 |
return |
| 242 |
} |
| 243 |
msg := fmt.Sprint(r) |
| 244 |
note("panic value", msg) |
| 245 |
err = c.match(msg, "panic value does not match regexp", note) |
| 246 |
}() |
| 247 |
c.got() |
| 248 |
return nil |
| 249 |
} |
| 250 |
|
| 251 |
func (c *panicMatchesChecker) Args() []Arg { |
| 252 |
return []Arg{{Name: "function", Value: c.got}, {Name: "regexp", Value: c.want}} |
| 253 |
} |
| 254 |
|
| 255 |
// IsNil returns a Checker checking that the provided value is equal to nil. |
| 256 |
// |
| 257 |
// Note that an interface value containing a nil concrete |
| 258 |
// type is not considered to be nil. |
| 259 |
func IsNil[T any](got T) Checker { |
| 260 |
return isNilChecker[T]{ |
| 261 |
got: got, |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
type isNilChecker[T any] struct { |
| 266 |
got T |
| 267 |
} |
| 268 |
|
| 269 |
func (c isNilChecker[T]) Check(note func(key string, value any)) error { |
| 270 |
v := reflect.ValueOf(&c.got).Elem() |
| 271 |
if !canBeNil(v.Kind()) { |
| 272 |
return BadCheckf("type %v can never be nil", v.Type()) |
| 273 |
} |
| 274 |
if v.IsNil() { |
| 275 |
return nil |
| 276 |
} |
| 277 |
return errors.New("got non-nil value") |
| 278 |
} |
| 279 |
|
| 280 |
func (c isNilChecker[T]) Args() []Arg { |
| 281 |
return []Arg{{Name: "got", Value: c.got}} |
| 282 |
} |
| 283 |
|
| 284 |
func (c isNilChecker[T]) negatedError() error { |
| 285 |
v := reflect.ValueOf(c.got) |
| 286 |
if v.IsValid() { |
| 287 |
return fmt.Errorf("got nil %s but want non-nil", v.Kind()) |
| 288 |
} |
| 289 |
return errors.New("got <nil> but want non-nil") |
| 290 |
} |
| 291 |
|
| 292 |
// IsNotNil returns a Checker checking that the provided value is not nil. |
| 293 |
// IsNotNil(v) is the equivalent of qt.Not(qt.IsNil(v)). |
| 294 |
func IsNotNil[T any](got T) Checker { |
| 295 |
return Not(IsNil(got)) |
| 296 |
} |
| 297 |
|
| 298 |
// HasLen returns a Checker checking that the provided value has the given |
| 299 |
// length. The value may be a slice, array, channel, map or string. |
| 300 |
func HasLen[T any](got T, n int) Checker { |
| 301 |
return &hasLenChecker[T]{ |
| 302 |
got: got, |
| 303 |
wantLen: n, |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
type hasLenChecker[T any] struct { |
| 308 |
got T |
| 309 |
wantLen int |
| 310 |
} |
| 311 |
|
| 312 |
func (c *hasLenChecker[T]) Check(note func(key string, value any)) (err error) { |
| 313 |
// TODO we're deliberately not allowing HasLen(interfaceValue) here. |
| 314 |
// Perhaps we should? |
| 315 |
v := reflect.ValueOf(&c.got).Elem() |
| 316 |
switch v.Kind() { |
| 317 |
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: |
| 318 |
case reflect.Pointer: |
| 319 |
// Allow a pointer to array. |
| 320 |
if reflect.Indirect(reflect.ValueOf(c.got)).Kind() == reflect.Array { |
| 321 |
break |
| 322 |
} |
| 323 |
|
| 324 |
// Error on all other pointers. |
| 325 |
note("got", c.got) |
| 326 |
return BadCheckf("first argument of type %v has no length", v.Type()) |
| 327 |
default: |
| 328 |
note("got", c.got) |
| 329 |
return BadCheckf("first argument of type %v has no length", v.Type()) |
| 330 |
} |
| 331 |
length := v.Len() |
| 332 |
note("len(got)", length) |
| 333 |
if length != c.wantLen { |
| 334 |
return fmt.Errorf("unexpected length") |
| 335 |
} |
| 336 |
return nil |
| 337 |
} |
| 338 |
|
| 339 |
func (c *hasLenChecker[T]) Args() []Arg { |
| 340 |
return []Arg{{Name: "got", Value: c.got}, {Name: "want length", Value: c.wantLen}} |
| 341 |
} |
| 342 |
|
| 343 |
// Implements returns a Checker checking that the provided value implements the |
| 344 |
// interface specified by the type parameter. |
| 345 |
func Implements[I any](got any) Checker { |
| 346 |
return &implementsChecker{ |
| 347 |
got: got, |
| 348 |
want: typeOf[I](), |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
type implementsChecker struct { |
| 353 |
got any |
| 354 |
want reflect.Type |
| 355 |
} |
| 356 |
|
| 357 |
func (c *implementsChecker) Check(note func(key string, value any)) (err error) { |
| 358 |
if c.got == nil { |
| 359 |
note("error", Unquoted("got nil value but want non-nil")) |
| 360 |
note("got", c.got) |
| 361 |
return ErrSilent |
| 362 |
} |
| 363 |
if c.want.Kind() != reflect.Interface { |
| 364 |
note("want interface", Unquoted(c.want.String())) |
| 365 |
return BadCheckf("want an interface type but a concrete type was provided") |
| 366 |
} |
| 367 |
|
| 368 |
gotType := reflect.TypeOf(c.got) |
| 369 |
if !gotType.Implements(c.want) { |
| 370 |
return fmt.Errorf("got value does not implement wanted interface") |
| 371 |
} |
| 372 |
|
| 373 |
return nil |
| 374 |
} |
| 375 |
|
| 376 |
func (c *implementsChecker) Args() []Arg { |
| 377 |
return []Arg{{Name: "got", Value: c.got}, {Name: "want interface", Value: Unquoted(c.want.String())}} |
| 378 |
|
| 379 |
} |
| 380 |
|
| 381 |
// Satisfies returns a Checker checking that the provided value, when used as |
| 382 |
// argument of the provided predicate function, causes the function to return |
| 383 |
// true. |
| 384 |
func Satisfies[T any](got T, f func(T) bool) Checker { |
| 385 |
return &satisfiesChecker[T]{ |
| 386 |
got: got, |
| 387 |
predicate: f, |
| 388 |
} |
| 389 |
} |
| 390 |
|
| 391 |
type satisfiesChecker[T any] struct { |
| 392 |
got T |
| 393 |
predicate func(T) bool |
| 394 |
} |
| 395 |
|
| 396 |
// Check implements Checker.Check by checking that args[0](got) == true. |
| 397 |
func (c *satisfiesChecker[T]) Check(note func(key string, value any)) error { |
| 398 |
if c.predicate(c.got) { |
| 399 |
return nil |
| 400 |
} |
| 401 |
return fmt.Errorf("value does not satisfy predicate function") |
| 402 |
} |
| 403 |
|
| 404 |
func (c *satisfiesChecker[T]) Args() []Arg { |
| 405 |
return []Arg{{ |
| 406 |
Name: "got", |
| 407 |
Value: c.got, |
| 408 |
}, { |
| 409 |
Name: "predicate", |
| 410 |
Value: c.predicate, |
| 411 |
}} |
| 412 |
} |
| 413 |
|
| 414 |
// IsTrue returns a Checker checking that the provided value is true. |
| 415 |
func IsTrue[T ~bool](got T) Checker { |
| 416 |
return Equals(got, true) |
| 417 |
} |
| 418 |
|
| 419 |
// IsFalse returns a Checker checking that the provided value is false. |
| 420 |
func IsFalse[T ~bool](got T) Checker { |
| 421 |
return Equals(got, false) |
| 422 |
} |
| 423 |
|
| 424 |
// Not returns a Checker negating the given Checker. |
| 425 |
func Not(c Checker) Checker { |
| 426 |
// Not(Not(c)) becomes c. |
| 427 |
if c, ok := c.(notChecker); ok { |
| 428 |
return c.Checker |
| 429 |
} |
| 430 |
return notChecker{ |
| 431 |
Checker: c, |
| 432 |
} |
| 433 |
} |
| 434 |
|
| 435 |
type notChecker struct { |
| 436 |
Checker |
| 437 |
} |
| 438 |
|
| 439 |
func (c notChecker) Check(note func(key string, value any)) error { |
| 440 |
err := c.Checker.Check(note) |
| 441 |
if IsBadCheck(err) { |
| 442 |
return err |
| 443 |
} |
| 444 |
if err != nil { |
| 445 |
return nil |
| 446 |
} |
| 447 |
if c, ok := c.Checker.(negatedError); ok { |
| 448 |
return c.negatedError() |
| 449 |
} |
| 450 |
return errors.New("unexpected success") |
| 451 |
} |
| 452 |
|
| 453 |
// StringContains returns a Checker checking that the given string contains the |
| 454 |
// given substring. |
| 455 |
func StringContains[T ~string](got, substr T) Checker { |
| 456 |
return &stringContainsChecker[T]{ |
| 457 |
got: got, |
| 458 |
substr: substr, |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
type stringContainsChecker[T ~string] struct { |
| 463 |
got, substr T |
| 464 |
} |
| 465 |
|
| 466 |
func (c *stringContainsChecker[T]) Check(note func(key string, value any)) error { |
| 467 |
if strings.Contains(string(c.got), string(c.substr)) { |
| 468 |
return nil |
| 469 |
} |
| 470 |
return errors.New("no substring match found") |
| 471 |
} |
| 472 |
|
| 473 |
func (c *stringContainsChecker[T]) Args() []Arg { |
| 474 |
return []Arg{{ |
| 475 |
Name: "got", |
| 476 |
Value: c.got, |
| 477 |
}, { |
| 478 |
Name: "substr", |
| 479 |
Value: c.substr, |
| 480 |
}} |
| 481 |
} |
| 482 |
|
| 483 |
// SliceContains returns a Checker that succeeds if the given |
| 484 |
// slice contains the given element, by comparing for equality. |
| 485 |
func SliceContains[T any](container []T, elem T) Checker { |
| 486 |
return SliceAny(container, F2(Equals[T], elem)) |
| 487 |
} |
| 488 |
|
| 489 |
// MapContains returns a Checker that succeeds if the given value is |
| 490 |
// contained in the values of the given map, by comparing for equality. |
| 491 |
func MapContains[K comparable, V any](container map[K]V, elem V) Checker { |
| 492 |
return MapAny(container, F2(Equals[V], elem)) |
| 493 |
} |
| 494 |
|
| 495 |
// SliceAny returns a Checker that uses the given checker to check elements |
| 496 |
// of a slice. It succeeds if f(v) passes the check for any v in the slice. |
| 497 |
// |
| 498 |
// See the F2 function for a way to adapt a regular checker function |
| 499 |
// to the type expected for the f argument here. |
| 500 |
// |
| 501 |
// See also SliceAll and SliceContains. |
| 502 |
func SliceAny[T any](container []T, f func(elem T) Checker) Checker { |
| 503 |
return &anyChecker[T]{ |
| 504 |
newIter: func() containerIter[T] { |
| 505 |
return newSliceIter(container) |
| 506 |
}, |
| 507 |
container: container, |
| 508 |
elemChecker: f, |
| 509 |
} |
| 510 |
} |
| 511 |
|
| 512 |
// MapAny returns a Checker that uses checkers returned by f to check values |
| 513 |
// of a map. It succeeds if f(v) passes the check for any value v in the map. |
| 514 |
// |
| 515 |
// See the F2 function for a way to adapt a regular checker function |
| 516 |
// to the type expected for the f argument here. |
| 517 |
// |
| 518 |
// See also MapAll and MapContains. |
| 519 |
func MapAny[K comparable, V any](container map[K]V, f func(elem V) Checker) Checker { |
| 520 |
return &anyChecker[V]{ |
| 521 |
newIter: func() containerIter[V] { |
| 522 |
return newMapIter(container) |
| 523 |
}, |
| 524 |
container: container, |
| 525 |
elemChecker: f, |
| 526 |
} |
| 527 |
} |
| 528 |
|
| 529 |
type anyChecker[T any] struct { |
| 530 |
newIter func() containerIter[T] |
| 531 |
container any |
| 532 |
elemChecker func(T) Checker |
| 533 |
} |
| 534 |
|
| 535 |
func (c *anyChecker[T]) Check(note func(key string, value any)) error { |
| 536 |
for iter := c.newIter(); iter.next(); { |
| 537 |
// For the time being, discard the notes added by the sub-checker, |
| 538 |
// because it's not clear what a good behavior would be. |
| 539 |
// Should we print all the failed check for all elements? If there's only |
| 540 |
// one element in the container, the answer is probably yes, |
| 541 |
// but let's leave it for now. |
| 542 |
checker := c.elemChecker(iter.value()) |
| 543 |
err := checker.Check( |
| 544 |
func(key string, value any) {}, |
| 545 |
) |
| 546 |
if err == nil { |
| 547 |
return nil |
| 548 |
} |
| 549 |
if IsBadCheck(err) { |
| 550 |
return BadCheckf("at %s: %v", iter.key(), err) |
| 551 |
} |
| 552 |
} |
| 553 |
return errors.New("no matching element found") |
| 554 |
} |
| 555 |
|
| 556 |
func (c *anyChecker[T]) Args() []Arg { |
| 557 |
// We haven't got an instance of the underlying checker, |
| 558 |
// so just make one by passing the zero value. In general |
| 559 |
// no checker should panic when being created regardless |
| 560 |
// of the actual arguments, so that should be OK. |
| 561 |
args := []Arg{{ |
| 562 |
Name: "container", |
| 563 |
Value: c.container, |
| 564 |
}} |
| 565 |
if eargs := c.elemChecker(*new(T)).Args(); len(eargs) > 0 { |
| 566 |
args = append(args, eargs[1:]...) |
| 567 |
} |
| 568 |
return args |
| 569 |
} |
| 570 |
|
| 571 |
// SliceAll returns a Checker that uses checkers returned by f |
| 572 |
// to check elements of a slice. It succeeds if all elements |
| 573 |
// of the slice pass the check. |
| 574 |
// On failure it prints the error from the first index that failed. |
| 575 |
func SliceAll[T any](container []T, f func(elem T) Checker) Checker { |
| 576 |
return &allChecker[T]{ |
| 577 |
newIter: func() containerIter[T] { |
| 578 |
return newSliceIter(container) |
| 579 |
}, |
| 580 |
container: container, |
| 581 |
elemChecker: f, |
| 582 |
} |
| 583 |
} |
| 584 |
|
| 585 |
// MapAll returns a Checker that uses checkers returned by f to check values |
| 586 |
// of a map. It succeeds if f(v) passes the check for all values v in the map. |
| 587 |
func MapAll[K comparable, V any](container map[K]V, f func(elem V) Checker) Checker { |
| 588 |
return &allChecker[V]{ |
| 589 |
newIter: func() containerIter[V] { |
| 590 |
return newMapIter(container) |
| 591 |
}, |
| 592 |
container: container, |
| 593 |
elemChecker: f, |
| 594 |
} |
| 595 |
} |
| 596 |
|
| 597 |
type allChecker[T any] struct { |
| 598 |
newIter func() containerIter[T] |
| 599 |
container any |
| 600 |
elemChecker func(T) Checker |
| 601 |
} |
| 602 |
|
| 603 |
func (c *allChecker[T]) Check(notef func(key string, value any)) error { |
| 604 |
for iter := c.newIter(); iter.next(); { |
| 605 |
// Store any notes added by the checker so |
| 606 |
// we can add our own note at the start |
| 607 |
// to say which element failed. |
| 608 |
var notes []note |
| 609 |
checker := c.elemChecker(iter.value()) |
| 610 |
err := checker.Check( |
| 611 |
func(key string, val any) { |
| 612 |
notes = append(notes, note{key, val}) |
| 613 |
}, |
| 614 |
) |
| 615 |
if err == nil { |
| 616 |
continue |
| 617 |
} |
| 618 |
if IsBadCheck(err) { |
| 619 |
return BadCheckf("at %s: %v", iter.key(), err) |
| 620 |
} |
| 621 |
notef("error", Unquoted("mismatch at "+iter.key())) |
| 622 |
// TODO should we print the whole container value in |
| 623 |
// verbose mode? |
| 624 |
if err != ErrSilent { |
| 625 |
// If the error's not silent, the checker is expecting |
| 626 |
// the caller to print the error and the value that failed. |
| 627 |
notef("error", Unquoted(err.Error())) |
| 628 |
notef("first mismatched element", iter.value()) |
| 629 |
} |
| 630 |
for _, n := range notes { |
| 631 |
notef(n.key, n.value) |
| 632 |
} |
| 633 |
return ErrSilent |
| 634 |
} |
| 635 |
return nil |
| 636 |
} |
| 637 |
|
| 638 |
func (c *allChecker[T]) Args() []Arg { |
| 639 |
// We haven't got an instance of the underlying checker, |
| 640 |
// so just make one by passing the zero value. In general |
| 641 |
// no checker should panic when being created regardless |
| 642 |
// of the actual arguments, so that should be OK. |
| 643 |
args := []Arg{{ |
| 644 |
Name: "container", |
| 645 |
Value: c.container, |
| 646 |
}} |
| 647 |
if eargs := c.elemChecker(*new(T)).Args(); len(eargs) > 0 { |
| 648 |
args = append(args, eargs[1:]...) |
| 649 |
} |
| 650 |
return args |
| 651 |
} |
| 652 |
|
| 653 |
// JSONEquals returns a Checker that checks whether a string or byte slice is |
| 654 |
// JSON-equivalent to a Go value. See CodecEquals for more information. |
| 655 |
// |
| 656 |
// It uses DeepEquals to do the comparison. If a more sophisticated comparison |
| 657 |
// is required, use CodecEquals directly. |
| 658 |
func JSONEquals[T []byte | string](got T, want any) Checker { |
| 659 |
return CodecEquals(got, want, json.Marshal, json.Unmarshal) |
| 660 |
} |
| 661 |
|
| 662 |
// CodecEquals returns a Checker that checks for codec value equivalence. |
| 663 |
// |
| 664 |
// It expects two arguments: a byte slice or a string containing some |
| 665 |
// codec-marshaled data, and a Go value. |
| 666 |
// |
| 667 |
// It uses unmarshal to unmarshal the data into an interface{} value. |
| 668 |
// It marshals the Go value using marshal, then unmarshals the result into |
| 669 |
// an any value. |
| 670 |
// |
| 671 |
// It then checks that the two interface{} values are deep-equal to one |
| 672 |
// another, using CmpEquals(opts) to perform the check. |
| 673 |
// |
| 674 |
// See JSONEquals for an example of this in use. |
| 675 |
func CodecEquals[T []byte | string]( |
| 676 |
got T, |
| 677 |
want any, |
| 678 |
marshal func(any) ([]byte, error), |
| 679 |
unmarshal func([]byte, any) error, |
| 680 |
opts ...cmp.Option, |
| 681 |
) Checker { |
| 682 |
return &codecEqualChecker[T]{ |
| 683 |
argPair: argPairOf(got, want), |
| 684 |
marshal: marshal, |
| 685 |
unmarshal: unmarshal, |
| 686 |
opts: opts, |
| 687 |
} |
| 688 |
} |
| 689 |
|
| 690 |
type codecEqualChecker[T []byte | string] struct { |
| 691 |
argPair[T, any] |
| 692 |
marshal func(any) ([]byte, error) |
| 693 |
unmarshal func([]byte, any) error |
| 694 |
opts []cmp.Option |
| 695 |
} |
| 696 |
|
| 697 |
func (c *codecEqualChecker[T]) Check(note func(key string, value any)) error { |
| 698 |
wantContentBytes, err := c.marshal(c.want) |
| 699 |
if err != nil { |
| 700 |
return BadCheckf("cannot marshal expected contents: %v", err) |
| 701 |
} |
| 702 |
var wantContentVal any |
| 703 |
if err := c.unmarshal(wantContentBytes, &wantContentVal); err != nil { |
| 704 |
return BadCheckf("cannot unmarshal expected contents: %v", err) |
| 705 |
} |
| 706 |
var gotContentVal any |
| 707 |
if err := c.unmarshal([]byte(c.got), &gotContentVal); err != nil { |
| 708 |
return fmt.Errorf("cannot unmarshal obtained contents: %v; %q", err, c.got) |
| 709 |
} |
| 710 |
cmpEq := CmpEquals(gotContentVal, wantContentVal, c.opts...).(*cmpEqualsChecker[any]) |
| 711 |
return cmpEq.Check(note) |
| 712 |
} |
| 713 |
|
| 714 |
// ErrorAs retruns a Checker checking that the error is or wraps a specific |
| 715 |
// error type. If so, it assigns it to the provided pointer. This is analogous |
| 716 |
// to calling errors.As. |
| 717 |
func ErrorAs[T any](got error, want *T) Checker { |
| 718 |
return &errorAsChecker[T]{ |
| 719 |
got: got, |
| 720 |
want: want, |
| 721 |
} |
| 722 |
} |
| 723 |
|
| 724 |
type errorAsChecker[T any] struct { |
| 725 |
got error |
| 726 |
want *T |
| 727 |
} |
| 728 |
|
| 729 |
func (c *errorAsChecker[T]) Check(note func(key string, value any)) (err error) { |
| 730 |
if c.got == nil { |
| 731 |
return errors.New("got nil error but want non-nil") |
| 732 |
} |
| 733 |
defer func() { |
| 734 |
// A panic is raised when the target is not a pointer to an interface |
| 735 |
// or error. |
| 736 |
if r := recover(); r != nil { |
| 737 |
err = BadCheckf("%s", r) |
| 738 |
} |
| 739 |
}() |
| 740 |
want := c.want |
| 741 |
if want == nil { |
| 742 |
want = new(T) |
| 743 |
} |
| 744 |
if !errors.As(c.got, want) { |
| 745 |
return errors.New("wanted type is not found in error chain") |
| 746 |
} |
| 747 |
return nil |
| 748 |
} |
| 749 |
|
| 750 |
func (c *errorAsChecker[T]) Args() []Arg { |
| 751 |
return []Arg{{ |
| 752 |
Name: "got", |
| 753 |
Value: c.got, |
| 754 |
}, { |
| 755 |
Name: "as type", |
| 756 |
Value: Unquoted(typeOf[T]().String()), |
| 757 |
}} |
| 758 |
} |
| 759 |
|
| 760 |
// ErrorIs returns a Checker that checks that the error is or wraps a specific |
| 761 |
// error value. This is analogous to calling errors.Is. |
| 762 |
func ErrorIs(got, want error) Checker { |
| 763 |
return &errorIsChecker{ |
| 764 |
argPair: argPairOf(got, want), |
| 765 |
} |
| 766 |
} |
| 767 |
|
| 768 |
type errorIsChecker struct { |
| 769 |
argPair[error, error] |
| 770 |
} |
| 771 |
|
| 772 |
func (c *errorIsChecker) Check(note func(key string, value any)) error { |
| 773 |
if c.got == nil && c.want != nil { |
| 774 |
return errors.New("got nil error but want non-nil") |
| 775 |
} |
| 776 |
if !errors.Is(c.got, c.want) { |
| 777 |
return errors.New("wanted error is not found in error chain") |
| 778 |
} |
| 779 |
return nil |
| 780 |
} |
| 781 |
|
| 782 |
type matcher = func(got string, msg string, note func(key string, value any)) error |
| 783 |
|
| 784 |
// newMatcher returns a matcher function that can be used by checkers when |
| 785 |
// checking that a string or an error matches the provided StringOrRegexp. |
| 786 |
func newMatcher[StringOrRegexp string | *regexp.Regexp](regex StringOrRegexp) matcher { |
| 787 |
var re *regexp.Regexp |
| 788 |
switch r := any(regex).(type) { |
| 789 |
case string: |
| 790 |
re0, err := regexp.Compile("^(" + r + ")$") |
| 791 |
if err != nil { |
| 792 |
return func(got string, msg string, note func(key string, value any)) error { |
| 793 |
note("regexp", r) |
| 794 |
return BadCheckf("cannot compile regexp: %s", err) |
| 795 |
} |
| 796 |
} |
| 797 |
re = re0 |
| 798 |
case *regexp.Regexp: |
| 799 |
re = r |
| 800 |
} |
| 801 |
return func(got string, msg string, note func(key string, value any)) error { |
| 802 |
if re.MatchString(got) { |
| 803 |
return nil |
| 804 |
} |
| 805 |
return errors.New(msg) |
| 806 |
} |
| 807 |
} |
| 808 |
|
| 809 |
func argPairOf[A, B any](a A, b B) argPair[A, B] { |
| 810 |
return argPair[A, B]{a, b} |
| 811 |
} |
| 812 |
|
| 813 |
type argPair[A, B any] struct { |
| 814 |
got A |
| 815 |
want B |
| 816 |
} |
| 817 |
|
| 818 |
func (p argPair[A, B]) Args() []Arg { |
| 819 |
return []Arg{{ |
| 820 |
Name: "got", |
| 821 |
Value: p.got, |
| 822 |
}, { |
| 823 |
Name: "want", |
| 824 |
Value: p.want, |
| 825 |
}} |
| 826 |
} |
| 827 |
|
| 828 |
// canBeNil reports whether a value or type of the given kind can be nil. |
| 829 |
func canBeNil(k reflect.Kind) bool { |
| 830 |
switch k { |
| 831 |
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: |
| 832 |
return true |
| 833 |
} |
| 834 |
return false |
| 835 |
} |
| 836 |
|
| 837 |
func typeOf[T any]() reflect.Type { |
| 838 |
return reflect.TypeOf((*T)(nil)).Elem() |
| 839 |
} |
| 840 |
|
| 841 |
func valueAs[T any](v reflect.Value) (r T) { |
| 842 |
reflect.ValueOf(&r).Elem().Set(v) |
| 843 |
return |
| 844 |
} |
| 845 |
|
| 846 |
// F2 factors a 2-argument checker function into a single argument function suitable |
| 847 |
// for passing to an *Any or *All checker. Whenever the returned function is called, |
| 848 |
// cf is called with arguments (got, want). |
| 849 |
func F2[Got, Want any](cf func(got Got, want Want) Checker, want Want) func(got Got) Checker { |
| 850 |
return func(got Got) Checker { |
| 851 |
return cf(got, want) |
| 852 |
} |
| 853 |
} |