Debian Codegraph @

check.go

raw symbols SCIP
1 package check
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "math"
10 "os"
11 "reflect"
12 "regexp"
13 "strings"
14 "testing"
15 "time"
16
17 "github.com/powerman/check/internal/deepequal"
18 )
19
20 //nolint:gochecknoglobals // Const.
21 var (
22 typString = reflect.TypeFor[string]()
23 typBytes = reflect.TypeFor[[]byte]()
24 typFloat64 = reflect.TypeFor[float64]()
25 )
26
27 // C wraps [*testing.T] to make it convenient to call checkers in test.
28 type C struct {
29 // C is a thin [*testing.T]-only compatibility shell built on the same machinery as [TB]:
30 // it embeds [*testing.T] (its sole, unambiguous [testing.TB] source -
31 // so Helper/Cleanup/Log/... and friends stay genuinely zero-cost)
32 // and *checks (which provides the wide checker API for free
33 // and never collides with [*testing.T]'s own method names).
34 // Error, Errorf, Fatal, Fatalf, Fail, FailNow and Context are the one exception:
35 // check needs to intercept them (for statistics/TODO/Must and the merged Context),
36 // so each gets a short explicit override below - direct declarations always win
37 // over promoted ones, so this doesn't reintroduce any ambiguity.
38 *checks
39 *testing.T
40 }
41
42 const (
43 nameActual = "Actual"
44 nameExpected = "Expected"
45 )
46
47 var _ testing.TB = (*C)(nil)
48
49 // T creates and returns new *C, which wraps given tt and supposed to be
50 // used inplace of it, providing you with access to many useful helpers in
51 // addition to standard methods of [*testing.T].
52 //
53 // It's convenient to rename Test function's arg from t to something
54 // else, create wrapped variable with usual name t and use only t:
55 //
56 // func TestSomething(tt *testing.T) {
57 // t := check.T(tt)
58 // // use only t in test and don't touch tt anymore
59 // }
60 //
61 // T is a soft-mode, [*testing.T]-only legacy constructor kept for backward compatibility.
62 // For new tests prefer [Must], which also works with [*testing.B] and [*testing.F].
63 func T(tt *testing.T) *C { //nolint:thelper // With check we name it tt!
64 return &C{checks: &checks{tb: tt}, T: tt}
65 }
66
67 // TODO is like [TB.TODO], but keeps working with *C and [*testing.T].
68 func (t *C) TODO() *C {
69 return &C{checks: t.withTODO(), T: t.T}
70 }
71
72 // MustAll is like [TB.MustAll], but keeps working with *C and [*testing.T].
73 func (t *C) MustAll() *C {
74 return &C{checks: t.withMustAll(), T: t.T}
75 }
76
77 // Context returns the context associated with t:
78 // the context merged in by the most recent [C.MergeContext] call if any,
79 // otherwise the standard [*testing.T.Context]().
80 func (t *C) Context() context.Context {
81 return t.context()
82 }
83
84 // MergeContext is like [TB.MergeContext], but keeps working with *C and [*testing.T].
85 func (t *C) MergeContext(ctx context.Context) *C {
86 merged, cancel := t.mergeContext(ctx)
87 t.Cleanup(cancel)
88 return &C{checks: merged, T: t.T}
89 }
90
91 // Error is equivalent to Log followed by Fail.
92 //
93 // It is like t.Errorf with TODO() and statistics support.
94 func (t *C) Error(args ...any) {
95 t.Helper()
96 t.report0(args, false)
97 }
98
99 // Errorf is equivalent to Logf followed by Fail.
100 //
101 // It is like t.Errorf with TODO() and statistics support.
102 func (t *C) Errorf(format string, args ...any) {
103 t.Helper()
104 t.report0(append([]any{format}, args...), false)
105 }
106
107 // Fatal is equivalent to Log followed by FailNow.
108 //
109 // It is like t.Fatal with TODO() and statistics support.
110 func (t *C) Fatal(args ...any) {
111 t.Helper()
112 t.report0(args, false)
113 if !t.todo {
114 t.T.FailNow() // Already counted above: bypass the counting FailNow wrapper.
115 }
116 }
117
118 // Fatalf is equivalent to Logf followed by FailNow.
119 //
120 // It is like t.Fatalf with TODO() and statistics support.
121 func (t *C) Fatalf(format string, args ...any) {
122 t.Helper()
123 t.report0(append([]any{format}, args...), false)
124 if !t.todo {
125 t.T.FailNow() // Already counted above: bypass the counting FailNow wrapper.
126 }
127 }
128
129 // Fail marks the function as having failed but continues execution.
130 //
131 // Unlike plain [*testing.T.Fail], calling it directly (rather than through a checker)
132 // is still counted in check's pass/fail statistics.
133 func (t *C) Fail() {
134 t.fail()
135 t.T.Fail()
136 }
137
138 // FailNow marks the function as having failed and stops its execution.
139 //
140 // Unlike plain [*testing.T.FailNow], calling it directly (rather than through a checker)
141 // is still counted in check's pass/fail statistics.
142 func (t *C) FailNow() {
143 t.fail()
144 t.T.FailNow()
145 }
146
147 // Should is like [TB.Should], but keeps working with *C and [*testing.T].
148 //
149 // [ShouldFunc1]/[ShouldFunc2] callbacks always receive a *[TB] (never *C):
150 // there's only one pair of callback types, shared by TB and C alike.
151 func (t *C) Should(anyShouldFunc any, args ...any) bool {
152 t.Helper()
153 tb := &TB{TB: t.T, checks: t.checks}
154 switch f := anyShouldFunc.(type) {
155 case func(t *TB, actual any) bool:
156 return tb.should1(f, args...)
157 case func(t *TB, actual, expected any) bool:
158 return tb.should2(f, args...)
159 default:
160 panic("anyShouldFunc is not a ShouldFunc1 or ShouldFunc2")
161 }
162 }
163
164 // Nil checks for actual == nil.
165 //
166 // There is one subtle difference between this check and Go `== nil` (if
167 // this surprises you then you should read
168 // https://golang.org/doc/faq#nil_error first):
169 //
170 // var intPtr *int
171 // var empty interface{}
172 // var notEmpty interface{} = intPtr
173 // t.True(intPtr == nil) // TRUE
174 // t.True(empty == nil) // TRUE
175 // t.True(notEmpty == nil) // FALSE
176 //
177 // When you call this function your actual value will be stored in
178 // interface{} argument, and this makes any typed nil pointer value `!=
179 // nil` inside this function (just like in example above happens with
180 // notEmpty variable).
181 //
182 // As it is very common case to check some typed pointer using Nil this
183 // check has to work around and detect nil even if usual `== nil` return
184 // false. But this has nasty side effect: if actual value already was of
185 // interface type and contains some typed nil pointer (which is usually
186 // bad thing and should be avoid) then Nil check will pass (which may be
187 // not what you want/expect):
188 //
189 // t.Nil(nil) // TRUE
190 // t.Nil(intPtr) // TRUE
191 // t.Nil(empty) // TRUE
192 // t.Nil(notEmpty) // WARNING: also TRUE!
193 //
194 // Second subtle case is less usual: uintptr(0) is sorta nil, but not
195 // really, so Nil(uintptr(0)) will fail. Nil(unsafe.Pointer(nil)) will
196 // also fail, for the same reason. Please do not use this and consider
197 // this behaviour undefined, because it may change in the future.
198 func (t *checks) Nil(actual any, msg ...any) bool {
199 t.tb.Helper()
200 return t.report1(actual, msg,
201 isNil(actual))
202 }
203
204 func isNil(actual any) bool {
205 switch val := reflect.ValueOf(actual); val.Kind() {
206 case reflect.Invalid:
207 return actual == nil
208 case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.Slice:
209 return val.IsNil()
210 case reflect.Uintptr, reflect.UnsafePointer, // Subtle cases documented above.
211 reflect.Interface, // ???
212 // Can't be nil:
213 reflect.Struct, reflect.Array, reflect.Bool, reflect.String,
214 reflect.Complex128, reflect.Complex64, reflect.Float32, reflect.Float64,
215 reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8,
216 reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8:
217 }
218 return false
219 }
220
221 // NotNil checks for actual != nil.
222 //
223 // See Nil about subtle case in check logic.
224 func (t *checks) NotNil(actual any, msg ...any) bool {
225 t.tb.Helper()
226 return t.report0(msg,
227 !isNil(actual))
228 }
229
230 // True checks for cond == true.
231 //
232 // This can be useful to use your own custom checks, but this way you
233 // won't get nice dump/diff for actual/expected values. You'll still have
234 // statistics about passed/failed checks and it's shorter than usual:
235 //
236 // if !cond {
237 // t.Errorf(msg...)
238 // }
239 func (t *checks) True(cond bool, msg ...any) bool {
240 t.tb.Helper()
241 return t.report0(msg,
242 cond)
243 }
244
245 // False checks for cond == false.
246 func (t *checks) False(cond bool, msg ...any) bool {
247 t.tb.Helper()
248 return t.report0(msg,
249 !cond)
250 }
251
252 // Equal checks for actual == expected.
253 //
254 // Note: For [time.Time] it uses actual.Equal(expected) instead.
255 func (t *checks) Equal(actual, expected any, msg ...any) bool {
256 t.tb.Helper()
257 return t.report2(actual, expected, msg,
258 isEqual(actual, expected))
259 }
260
261 func isEqual(actual, expected any) bool {
262 switch actual := actual.(type) {
263 case time.Time:
264 return actual.Equal(expected.(time.Time))
265 default:
266 return actual == expected
267 }
268 }
269
270 // EQ is a synonym for Equal.
271 func (t *checks) EQ(actual, expected any, msg ...any) bool {
272 t.tb.Helper()
273 return t.Equal(actual, expected, msg...)
274 }
275
276 // NotEqual checks for actual != expected.
277 func (t *checks) NotEqual(actual, expected any, msg ...any) bool {
278 t.tb.Helper()
279 return t.report2(actual, expected, msg,
280 !isEqual(actual, expected))
281 }
282
283 // NE is a synonym for NotEqual.
284 func (t *checks) NE(actual, expected any, msg ...any) bool {
285 t.tb.Helper()
286 return t.NotEqual(actual, expected, msg...)
287 }
288
289 // BytesEqual checks for [bytes.Equal](actual, expected).
290 //
291 // Hint: BytesEqual([]byte{}, []byte(nil)) is true (unlike DeepEqual).
292 func (t *checks) BytesEqual(actual, expected []byte, msg ...any) bool {
293 t.tb.Helper()
294 return t.report2(actual, expected, msg,
295 bytes.Equal(actual, expected))
296 }
297
298 // NotBytesEqual checks for !bytes.Equal(actual, expected).
299 //
300 // Hint: NotBytesEqual([]byte{}, []byte(nil)) is false (unlike NotDeepEqual).
301 func (t *checks) NotBytesEqual(actual, expected []byte, msg ...any) bool {
302 t.tb.Helper()
303 return t.report1(actual, msg,
304 !bytes.Equal(actual, expected))
305 }
306
307 // hasMethod reports whether v has a method with the given name.
308 func hasMethod(v any, name string) bool {
309 t := reflect.TypeOf(v)
310 if t == nil {
311 return false
312 }
313 _, found := t.MethodByName(name)
314 return found
315 }
316
317 // DeepEqual checks for [deepequal.DeepEqual](actual, expected).
318 // It will use Equal method for types which implements it
319 // (e.g. [time.Time], decimal.Decimal, etc.).
320 //
321 // Custom equal checkers registered via [RegisterEqualChecker] run first.
322 func (t *checks) DeepEqual(actual, expected any, msg ...any) bool {
323 t.tb.Helper()
324 equal, claimed := runEqualCheckers(actual, expected)
325 if !claimed {
326 if hasMethod(actual, "ProtoReflect") || hasMethod(expected, "ProtoReflect") {
327 panic("check: protobuf message detected; " +
328 "import github.com/powerman/checkproto to compare protobuf messages")
329 }
330 equal = deepequal.DeepEqual(actual, expected)
331 }
332 return t.report2(actual, expected, msg, equal)
333 }
334
335 // NotDeepEqual checks for ![deepequal.DeepEqual](actual, expected).
336 // It will use Equal method for types which implements it
337 // (e.g. [time.Time], decimal.Decimal, etc.).
338 //
339 // Custom equal checkers registered via [RegisterEqualChecker] run first.
340 func (t *checks) NotDeepEqual(actual, expected any, msg ...any) bool {
341 t.tb.Helper()
342 equal, claimed := runEqualCheckers(actual, expected)
343 if claimed {
344 return t.report1(actual, msg, !equal)
345 }
346 if hasMethod(actual, "ProtoReflect") || hasMethod(expected, "ProtoReflect") {
347 panic("check: protobuf message detected; " +
348 "import github.com/powerman/checkproto to compare protobuf messages")
349 }
350 return t.report1(actual, msg,
351 !deepequal.DeepEqual(actual, expected))
352 }
353
354 // Match checks for regex.MatchString(actual).
355 //
356 // Regex type can be either [*regexp.Regexp] or string.
357 //
358 // Actual type can be:
359 // - string - will match with actual
360 // - []byte - will match with string(actual)
361 // - []rune - will match with string(actual)
362 // - [fmt.Stringer] - will match with actual.String()
363 // - error - will match with actual.Error()
364 // - nil - will not match (even with empty regex)
365 func (t *checks) Match(actual, regex any, msg ...any) bool {
366 t.tb.Helper()
367 ok := isMatch(&actual, regex)
368 return t.report2(actual, regex, msg,
369 ok)
370 }
371
372 // isMatch updates actual to be a real string used for matching, to make
373 // dump easier to understand, but this result in losing type information.
374 func isMatch(actual *any, regex any) bool {
375 if *actual == nil {
376 return false
377 }
378 if !stringify(actual) {
379 panic("actual is not a string, []byte, []rune, fmt.Stringer, error or nil")
380 }
381 s := (*actual).(string) //nolint:forcetypeassert // False positive.
382
383 switch v := regex.(type) {
384 case *regexp.Regexp:
385 return v.MatchString(s)
386 case string:
387 return regexp.MustCompile(v).MatchString(s)
388 }
389 panic("regex is not a *regexp.Regexp or string")
390 }
391
392 func stringify(arg *any) bool {
393 switch v := (*arg).(type) {
394 case nil:
395 return false
396 case error:
397 *arg = v.Error()
398 case fmt.Stringer:
399 *arg = v.String()
400 default:
401 typ := reflect.TypeOf(*arg)
402 switch typ.Kind() { //nolint:exhaustive // Covered by default case.
403 case reflect.String:
404 case reflect.Slice:
405 switch typ.Elem().Kind() { //nolint:exhaustive // Covered by default case.
406 case reflect.Uint8, reflect.Int32:
407 default:
408 return false
409 }
410 default:
411 return false
412 }
413 *arg = reflect.ValueOf(*arg).Convert(typString).Interface()
414 }
415 return true
416 }
417
418 // NotMatch checks for !regex.MatchString(actual).
419 //
420 // See Match about supported actual/regex types and check logic.
421 func (t *checks) NotMatch(actual, regex any, msg ...any) bool {
422 t.tb.Helper()
423 ok := !isMatch(&actual, regex)
424 return t.report2(actual, regex, msg,
425 ok)
426 }
427
428 // Contains checks is actual contains substring/element expected.
429 //
430 // Element of array/slice/map is checked using == expected.
431 //
432 // Type of expected depends on type of actual:
433 // - if actual is a string, then expected should be a string
434 // - if actual is an array, then expected should have array's element type
435 // - if actual is a slice, then expected should have slice's element type
436 // - if actual is a map, then expected should have map's value type
437 //
438 // Hint: In a map it looks for a value, if you need to look for a key -
439 // use HasKey instead.
440 func (t *checks) Contains(actual, expected any, msg ...any) bool {
441 t.tb.Helper()
442 return t.report2(actual, expected, msg,
443 isContains(actual, expected))
444 }
445
446 func isContains(actual, expected any) (found bool) {
447 switch valActual := reflect.ValueOf(actual); valActual.Kind() { //nolint:exhaustive // Covered by default case.
448 case reflect.String:
449 strActual := valActual.Convert(typString).Interface().(string) //nolint:forcetypeassert // False positive.
450 valExpected := reflect.ValueOf(expected)
451 if valExpected.Kind() != reflect.String {
452 panic("expected underlying type is not a string")
453 }
454 strExpected := valExpected.Convert(typString).Interface().(string) //nolint:forcetypeassert // False positive.
455 found = strings.Contains(strActual, strExpected)
456
457 case reflect.Map:
458 if valActual.Type().Elem() != reflect.TypeOf(expected) {
459 panic("expected type not match actual element type")
460 }
461 keys := valActual.MapKeys()
462 for i := 0; i < len(keys) && !found; i++ {
463 found = valActual.MapIndex(keys[i]).Interface() == expected
464 }
465
466 case reflect.Slice, reflect.Array:
467 if valActual.Type().Elem() != reflect.TypeOf(expected) {
468 panic("expected type not match actual element type")
469 }
470 for i := 0; i < valActual.Len() && !found; i++ {
471 found = valActual.Index(i).Interface() == expected
472 }
473
474 default:
475 panic("actual is not a string, array, slice or map")
476 }
477 return found
478 }
479
480 // NotContains checks is actual not contains substring/element expected.
481 //
482 // See Contains about supported actual/expected types and check logic.
483 func (t *checks) NotContains(actual, expected any, msg ...any) bool {
484 t.tb.Helper()
485 return t.report2(actual, expected, msg,
486 !isContains(actual, expected))
487 }
488
489 // HasKey checks is actual has key expected.
490 func (t *checks) HasKey(actual, expected any, msg ...any) bool {
491 t.tb.Helper()
492 return t.report2(actual, expected, msg,
493 hasKey(actual, expected))
494 }
495
496 func hasKey(actual, expected any) bool {
497 return reflect.ValueOf(actual).MapIndex(reflect.ValueOf(expected)).IsValid()
498 }
499
500 // NotHasKey checks is actual has no key expected.
501 func (t *checks) NotHasKey(actual, expected any, msg ...any) bool {
502 t.tb.Helper()
503 return t.report2(actual, expected, msg,
504 !hasKey(actual, expected))
505 }
506
507 // Zero checks is actual is zero value of it's type.
508 func (t *checks) Zero(actual any, msg ...any) bool {
509 t.tb.Helper()
510 return t.report1(actual, msg,
511 isZero(actual))
512 }
513
514 func isZero(actual any) bool {
515 if isNil(actual) {
516 return true
517 } else if typ := reflect.TypeOf(actual); typ.Comparable() {
518 // Not Func, Map, Slice, Array with non-comparable
519 // elements, Struct with non-comparable fields.
520 return actual == reflect.Zero(typ).Interface()
521 } else if typ.Kind() == reflect.Array {
522 zero := true
523 val := reflect.ValueOf(actual)
524 for i := 0; i < val.Len() && zero; i++ {
525 zero = isZero(val.Index(i).Interface())
526 }
527 return zero
528 }
529 // Func, Struct with non-comparable fields.
530 // Non-nil Map, Slice.
531 return false
532 }
533
534 // NotZero checks is actual is not zero value of it's type.
535 func (t *checks) NotZero(actual any, msg ...any) bool {
536 t.tb.Helper()
537 return t.report1(actual, msg,
538 !isZero(actual))
539 }
540
541 // Len checks is len(actual) == expected.
542 func (t *checks) Len(actual any, expected int, msg ...any) bool {
543 t.tb.Helper()
544 l := reflect.ValueOf(actual).Len()
545 return t.report2(l, expected, msg,
546 l == expected)
547 }
548
549 // NotLen checks is len(actual) != expected.
550 func (t *checks) NotLen(actual any, expected int, msg ...any) bool {
551 t.tb.Helper()
552 l := reflect.ValueOf(actual).Len()
553 return t.report2(l, expected, msg,
554 l != expected)
555 }
556
557 // Err checks is actual error is the same as expected error.
558 //
559 // Custom error checkers registered via [RegisterErrChecker] run first.
560 // If none claims the pair the built-in comparison operates on the
561 // original error found by recursively unwrapping actual with
562 // [errors.Unwrap]() and [github.com/pkg/errors.Cause]()
563 // (multi-error takes only the first),
564 // and then compares it using Equal() method or same type and value ([deepequal.DeepEqual]),
565 // so they may be different instances, but must have the same type and value.
566 //
567 // If both of these fail the comparison falls back to [errors.Is]()
568 // on the original actual (not the unwrapped one).
569 //
570 // Checking for nil is okay, but using Nil(actual) instead is more clean.
571 func (t *checks) Err(actual, expected error, msg ...any) bool {
572 t.tb.Helper()
573 equal, claimed := runCheckers(actual, expected)
574 if !claimed {
575 actual2 := unwrapErr(actual)
576 if hasMethod(actual2, "GRPCStatus") || hasMethod(expected, "GRPCStatus") {
577 panic("check: gRPC status error detected; " +
578 "import github.com/powerman/checkgrpc to compare gRPC status errors")
579 }
580 equal = reflect.TypeOf(actual2) == reflect.TypeOf(expected) &&
581 deepequal.DeepEqual(actual2, expected)
582 }
583 if !equal {
584 equal = errors.Is(actual, expected)
585 }
586 return t.report2(actual, expected, msg, equal)
587 }
588
589 // cause replicates github.com/pkg/errors.Cause using duck typing,
590 // to support that (archived) package without depending on it.
591 func cause(err error) error {
592 for err != nil {
593 c, ok := err.(interface{ Cause() error })
594 if !ok {
595 break
596 }
597 err = c.Cause()
598 }
599 return err
600 }
601
602 func unwrapErr(err error) (actual error) {
603 defer func() { _ = recover() }()
604 actual = err
605 for {
606 actual = cause(actual)
607 var unwrapped error
608 switch wrapped := actual.(type) { //nolint:errorlint // False positive.
609 case interface{ Unwrap() error }:
610 unwrapped = wrapped.Unwrap()
611 case interface{ Unwrap() []error }:
612 unwrappeds := wrapped.Unwrap()
613 if len(unwrappeds) > 0 {
614 unwrapped = unwrappeds[0]
615 }
616 }
617 if unwrapped == nil {
618 break
619 }
620 actual = unwrapped
621 }
622 return actual
623 }
624
625 // NotErr checks is actual error is not the same as expected error.
626 //
627 // It tries to recursively unwrap actual before checking using
628 // [errors.Unwrap]() and [github.com/pkg/errors.Cause]().
629 // In case of multi-error (Unwrap() []error) it use only first error.
630 //
631 // They must have either different types or values (or one should be nil).
632 // Different instances with same type and value will be considered the
633 // same error, and so is both nil.
634 //
635 // Finally it'll use ![errors.Is]().
636 func (t *checks) NotErr(actual, expected error, msg ...any) bool {
637 t.tb.Helper()
638 equal, claimed := runCheckers(actual, expected)
639 var notEqual bool
640 if claimed {
641 notEqual = !equal
642 } else {
643 actual2 := unwrapErr(actual)
644 if hasMethod(actual2, "GRPCStatus") || hasMethod(expected, "GRPCStatus") {
645 panic("check: gRPC status error detected; " +
646 "import github.com/powerman/checkgrpc to compare gRPC status errors")
647 }
648 notEqual = reflect.TypeOf(actual2) != reflect.TypeOf(expected) ||
649 !deepequal.DeepEqual(actual2, expected)
650 }
651 if notEqual {
652 notEqual = !errors.Is(actual, expected)
653 }
654 return t.report1(actual, msg, notEqual)
655 }
656
657 // ErrIs checks for [errors.Is]().
658 //
659 // Unlike Err which tries to unwrap to root cause and compare values,
660 // ErrIs uses pure [errors.Is] semantics for exact error matching.
661 //
662 // See Err for value-equality checks. ErrIs is preferred when you want
663 // the standard Go unwrapping semantics without value comparison.
664 func (t *checks) ErrIs(actual, expected error, msg ...any) bool {
665 t.tb.Helper()
666 return t.report2(actual, expected, msg,
667 errors.Is(actual, expected))
668 }
669
670 // NotErrIs checks for ![errors.Is]().
671 //
672 // See ErrIs for details. Note that nil is not matched by [errors.Is]
673 // against any non-nil error, so NotErrIs(nil, [io.EOF]) passes.
674 func (t *checks) NotErrIs(actual, expected error, msg ...any) bool {
675 t.tb.Helper()
676 return t.report1(actual, msg,
677 !errors.Is(actual, expected))
678 }
679
680 // ErrAs checks for [errors.As].
681 //
682 // target must be a non-nil pointer to an error type or to an interface,
683 // as required by [errors.As]. On success target is filled
684 // with the matched error value. See [errors.As] documentation for details.
685 func (t *checks) ErrAs(actual error, target any, msg ...any) bool {
686 t.tb.Helper()
687 return t.report2(actual, target, msg,
688 errors.As(actual, target))
689 }
690
691 // NotErrAs checks for ![errors.As].
692 //
693 // target must be a non-nil pointer to an error type or to an interface,
694 // as required by [errors.As]. Note that [errors.As] may still fill target
695 // with a matched error even when this check returns true,
696 // because [errors.As] is always called regardless of the negated result.
697 func (t *checks) NotErrAs(actual error, target any, msg ...any) bool {
698 t.tb.Helper()
699 return t.report1(actual, msg,
700 !errors.As(actual, target))
701 }
702
703 // Panic checks is actual() panics.
704 //
705 // It is able to detect panic(nil)… but you should try to avoid using this.
706 func (t *checks) Panic(actual func(), msg ...any) bool {
707 t.tb.Helper()
708 didPanic := true
709 func() {
710 defer func() { _ = recover() }()
711 actual()
712 didPanic = false
713 }()
714 return t.report0(msg,
715 didPanic)
716 }
717
718 // NotPanic checks is actual() don't panics.
719 //
720 // It is able to detect panic(nil)… but you should try to avoid using this.
721 func (t *checks) NotPanic(actual func(), msg ...any) bool {
722 t.tb.Helper()
723 didPanic := true
724 func() {
725 defer func() { _ = recover() }()
726 actual()
727 didPanic = false
728 }()
729 return t.report0(msg,
730 !didPanic)
731 }
732
733 // PanicMatch checks is actual() panics and panic text match regex.
734 //
735 // Regex type can be either [*regexp.Regexp] or string.
736 //
737 // In case of panic(nil) it will match like panic("<nil>").
738 func (t *checks) PanicMatch(actual func(), regex any, msg ...any) bool {
739 t.tb.Helper()
740 var panicVal any
741 didPanic := true
742 func() {
743 defer func() { panicVal = recover() }()
744 actual()
745 didPanic = false
746 }()
747 if !didPanic {
748 return t.report0(msg,
749 false)
750 }
751
752 switch panicVal.(type) {
753 case string, error:
754 default:
755 panicVal = fmt.Sprintf("%#v", panicVal)
756 }
757
758 ok := isMatch(&panicVal, regex)
759 return t.report2(panicVal, regex, msg,
760 ok)
761 }
762
763 // PanicNotMatch checks is actual() panics and panic text not match regex.
764 //
765 // Regex type can be either [*regexp.Regexp] or string.
766 //
767 // In case of panic(nil) it will match like panic("<nil>").
768 func (t *checks) PanicNotMatch(actual func(), regex any, msg ...any) bool {
769 t.tb.Helper()
770 var panicVal any
771 didPanic := true
772 func() {
773 defer func() { panicVal = recover() }()
774 actual()
775 didPanic = false
776 }()
777 if !didPanic {
778 return t.report0(msg,
779 false)
780 }
781
782 switch panicVal.(type) {
783 case string, error:
784 default:
785 panicVal = fmt.Sprintf("%#v", panicVal)
786 }
787
788 ok := !isMatch(&panicVal, regex)
789 return t.report2(panicVal, regex, msg,
790 ok)
791 }
792
793 // Less checks for actual < expected.
794 //
795 // Both actual and expected must be either:
796 // - signed integers
797 // - unsigned integers
798 // - floats
799 // - strings
800 // - [time.Time]
801 func (t *checks) Less(actual, expected any, msg ...any) bool {
802 t.tb.Helper()
803 return t.report2(actual, expected, msg,
804 isLess(actual, expected))
805 }
806
807 func isLess(actual, expected any) bool {
808 switch v1, v2 := reflect.ValueOf(actual), reflect.ValueOf(expected); v1.Kind() { //nolint:exhaustive // Covered by default case.
809 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
810 return v1.Int() < v2.Int()
811 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
812 return v1.Uint() < v2.Uint()
813 case reflect.Float32, reflect.Float64:
814 return v1.Float() < v2.Float()
815 case reflect.String:
816 return v1.String() < v2.String()
817 default:
818 if actualTime, ok := actual.(time.Time); ok {
819 return actualTime.Before(expected.(time.Time))
820 }
821 }
822 panic("actual is not a number, string or time.Time")
823 }
824
825 // LT is a synonym for Less.
826 func (t *checks) LT(actual, expected any, msg ...any) bool {
827 t.tb.Helper()
828 return t.Less(actual, expected, msg...)
829 }
830
831 // LessOrEqual checks for actual <= expected.
832 //
833 // Both actual and expected must be either:
834 // - signed integers
835 // - unsigned integers
836 // - floats
837 // - strings
838 // - [time.Time]
839 func (t *checks) LessOrEqual(actual, expected any, msg ...any) bool {
840 t.tb.Helper()
841 return t.report2(actual, expected, msg,
842 !isGreater(actual, expected))
843 }
844
845 func isGreater(actual, expected any) bool {
846 switch v1, v2 := reflect.ValueOf(actual), reflect.ValueOf(expected); v1.Kind() { //nolint:exhaustive // Covered by default case.
847 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
848 return v1.Int() > v2.Int()
849 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
850 return v1.Uint() > v2.Uint()
851 case reflect.Float32, reflect.Float64:
852 return v1.Float() > v2.Float()
853 case reflect.String:
854 return v1.String() > v2.String()
855 default:
856 if actualTime, ok := actual.(time.Time); ok {
857 return actualTime.After(expected.(time.Time))
858 }
859 }
860 panic("actual is not a number, string or time.Time")
861 }
862
863 // LE is a synonym for LessOrEqual.
864 func (t *checks) LE(actual, expected any, msg ...any) bool {
865 t.tb.Helper()
866 return t.LessOrEqual(actual, expected, msg...)
867 }
868
869 // Greater checks for actual > expected.
870 //
871 // Both actual and expected must be either:
872 // - signed integers
873 // - unsigned integers
874 // - floats
875 // - strings
876 // - [time.Time]
877 func (t *checks) Greater(actual, expected any, msg ...any) bool {
878 t.tb.Helper()
879 return t.report2(actual, expected, msg,
880 isGreater(actual, expected))
881 }
882
883 // GT is a synonym for Greater.
884 func (t *checks) GT(actual, expected any, msg ...any) bool {
885 t.tb.Helper()
886 return t.Greater(actual, expected, msg...)
887 }
888
889 // GreaterOrEqual checks for actual >= expected.
890 //
891 // Both actual and expected must be either:
892 // - signed integers
893 // - unsigned integers
894 // - floats
895 // - strings
896 // - [time.Time]
897 func (t *checks) GreaterOrEqual(actual, expected any, msg ...any) bool {
898 t.tb.Helper()
899 return t.report2(actual, expected, msg,
900 !isLess(actual, expected))
901 }
902
903 // GE is a synonym for GreaterOrEqual.
904 func (t *checks) GE(actual, expected any, msg ...any) bool {
905 t.tb.Helper()
906 return t.GreaterOrEqual(actual, expected, msg...)
907 }
908
909 // Between checks for min < actual < max.
910 //
911 // All three actual, min and max must be either:
912 // - signed integers
913 // - unsigned integers
914 // - floats
915 // - strings
916 // - [time.Time]
917 func (t *checks) Between(actual, minimum, maximum any, msg ...any) bool {
918 t.tb.Helper()
919 return t.report3(actual, minimum, maximum, msg,
920 isBetween(actual, minimum, maximum))
921 }
922
923 func isBetween(actual, minimum, maximum any) bool {
924 switch v, vmin, vmax := reflect.ValueOf(actual), reflect.ValueOf(minimum), reflect.ValueOf(maximum); v.Kind() { //nolint:exhaustive // Covered by default case.
925 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
926 return vmin.Int() < v.Int() && v.Int() < vmax.Int()
927 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
928 return vmin.Uint() < v.Uint() && v.Uint() < vmax.Uint()
929 case reflect.Float32, reflect.Float64:
930 return vmin.Float() < v.Float() && v.Float() < vmax.Float()
931 case reflect.String:
932 return vmin.String() < v.String() && v.String() < vmax.String()
933 default:
934 if actualTime, ok := actual.(time.Time); ok {
935 minTime := minimum.(time.Time) //nolint:forcetypeassert // Want panic.
936 maxTime := maximum.(time.Time) //nolint:forcetypeassert // Want panic.
937 return minTime.Before(actualTime) && actualTime.Before(maxTime)
938 }
939 }
940 panic("actual is not a number, string or time.Time")
941 }
942
943 // NotBetween checks for actual <= min or max <= actual.
944 //
945 // All three actual, min and max must be either:
946 // - signed integers
947 // - unsigned integers
948 // - floats
949 // - strings
950 // - [time.Time]
951 func (t *checks) NotBetween(actual, minimum, maximum any, msg ...any) bool {
952 t.tb.Helper()
953 return t.report3(actual, minimum, maximum, msg,
954 !isBetween(actual, minimum, maximum))
955 }
956
957 // BetweenOrEqual checks for min <= actual <= max.
958 //
959 // All three actual, min and max must be either:
960 // - signed integers
961 // - unsigned integers
962 // - floats
963 // - strings
964 // - [time.Time]
965 func (t *checks) BetweenOrEqual(actual, minimum, maximum any, msg ...any) bool {
966 t.tb.Helper()
967 return t.report3(actual, minimum, maximum, msg,
968 isBetween(actual, minimum, maximum) || isEqual(actual, minimum) || isEqual(actual, maximum))
969 }
970
971 // NotBetweenOrEqual checks for actual < min or max < actual.
972 //
973 // All three actual, min and max must be either:
974 // - signed integers
975 // - unsigned integers
976 // - floats
977 // - strings
978 // - [time.Time]
979 func (t *checks) NotBetweenOrEqual(actual, minimum, maximum any, msg ...any) bool {
980 t.tb.Helper()
981 return t.report3(actual, minimum, maximum, msg,
982 !isBetween(actual, minimum, maximum) && !isEqual(actual, minimum) && !isEqual(actual, maximum))
983 }
984
985 // InDelta checks for expected-delta <= actual <= expected+delta.
986 //
987 // All three actual, expected and delta must be either:
988 // - signed integers
989 // - unsigned integers
990 // - floats
991 // - [time.Time] (in this case delta must be [time.Duration])
992 func (t *checks) InDelta(actual, expected, delta any, msg ...any) bool {
993 t.tb.Helper()
994 return t.report3(actual, expected, delta, msg,
995 isInDelta(actual, expected, delta))
996 }
997
998 func isInDelta(actual, expected, delta any) bool {
999 switch v, e, d := reflect.ValueOf(actual), reflect.ValueOf(expected), reflect.ValueOf(delta); v.Kind() { //nolint:exhaustive // Covered by default case.
1000 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1001 dd := d.Int()
1002 if dd < 0 {
1003 return false // negative delta: preserve old always-false behavior
1004 }
1005 a, e2 := v.Int(), e.Int()
1006 var diff uint64 // |a-e2| computed without overflow via two's complement
1007 if a >= e2 {
1008 diff = uint64(a) - uint64(e2) //nolint:gosec // Two's complement: exact even when a-e2 overflows int64.
1009 } else {
1010 diff = uint64(e2) - uint64(a) //nolint:gosec // Two's complement: exact even when e2-a overflows int64.
1011 }
1012 return diff <= uint64(dd)
1013 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1014 a, e2, dd := v.Uint(), e.Uint(), d.Uint()
1015 var diff uint64
1016 if a >= e2 {
1017 diff = a - e2
1018 } else {
1019 diff = e2 - a
1020 }
1021 return diff <= dd
1022 case reflect.Float32, reflect.Float64:
1023 minimum, maximum := e.Float()-d.Float(), e.Float()+d.Float()
1024 return minimum <= v.Float() && v.Float() <= maximum
1025 default:
1026 if actualTime, ok := actual.(time.Time); ok {
1027 expectedTime := expected.(time.Time) //nolint:forcetypeassert // Want panic.
1028 dur := delta.(time.Duration) //nolint:forcetypeassert // Want panic.
1029 minTime, maxTime := expectedTime.Add(-dur), expectedTime.Add(dur)
1030 return minTime.Before(actualTime) && actualTime.Before(maxTime) ||
1031 actualTime.Equal(minTime) ||
1032 actualTime.Equal(maxTime)
1033 }
1034 }
1035 panic("actual is not a number or time.Time")
1036 }
1037
1038 // NotInDelta checks for actual < expected-delta or expected+delta < actual.
1039 //
1040 // All three actual, expected and delta must be either:
1041 // - signed integers
1042 // - unsigned integers
1043 // - floats
1044 // - [time.Time] (in this case delta must be [time.Duration])
1045 func (t *checks) NotInDelta(actual, expected, delta any, msg ...any) bool {
1046 t.tb.Helper()
1047 return t.report3(actual, expected, delta, msg,
1048 !isInDelta(actual, expected, delta))
1049 }
1050
1051 // InSMAPE checks that actual and expected have a symmetric mean absolute
1052 // percentage error (SMAPE) is less than given smape.
1053 //
1054 // Both actual and expected must be either:
1055 // - signed integers
1056 // - unsigned integers
1057 // - floats
1058 //
1059 // Allowed smape values are: 0.0 < smape < 100.0.
1060 //
1061 // Used formula returns SMAPE value between 0 and 100 (percents):
1062 // - 0.0 when actual == expected
1063 // - ~0.5 when they differs in ~1%
1064 // - ~5 when they differs in ~10%
1065 // - ~20 when they differs in 1.5 times
1066 // - ~33 when they differs in 2 times
1067 // - 50.0 when they differs in 3 times
1068 // - ~82 when they differs in 10 times
1069 // - 99.0+ when actual and expected differs in 200+ times
1070 // - 100.0 when only one of actual or expected is 0 or one of them is
1071 // positive while another is negative
1072 func (t *checks) InSMAPE(actual, expected any, smape float64, msg ...any) bool {
1073 t.tb.Helper()
1074 return t.report3(actual, expected, smape, msg,
1075 isInSMAPE(actual, expected, smape))
1076 }
1077
1078 func isInSMAPE(actual, expected any, smape float64) bool {
1079 if !(0 < smape && smape < 100) {
1080 panic("smape is not in allowed range: 0 < smape < 100")
1081 }
1082 a := reflect.ValueOf(actual).Convert(typFloat64).Float()
1083 e := reflect.ValueOf(expected).Convert(typFloat64).Float()
1084 if a == 0 && e == 0 {
1085 return true // avoid division by zero in legal use case
1086 }
1087 return 100*math.Abs(e-a)/(math.Abs(e)+math.Abs(a)) < smape
1088 }
1089
1090 // NotInSMAPE checks that actual and expected have a symmetric mean
1091 // absolute percentage error (SMAPE) is greater than or equal to given
1092 // smape.
1093 //
1094 // See InSMAPE about supported actual/expected types and check logic.
1095 func (t *checks) NotInSMAPE(actual, expected any, smape float64, msg ...any) bool {
1096 t.tb.Helper()
1097 return t.report3(actual, expected, smape, msg,
1098 !isInSMAPE(actual, expected, smape))
1099 }
1100
1101 // HasPrefix checks for [strings.HasPrefix](actual, expected).
1102 //
1103 // Both actual and expected may have any of these types:
1104 // - string - will use as is
1105 // - []byte - will convert with string()
1106 // - []rune - will convert with string()
1107 // - [fmt.Stringer] - will convert with actual.String()
1108 // - error - will convert with actual.Error()
1109 // - nil - check will always fail
1110 func (t *checks) HasPrefix(actual, expected any, msg ...any) bool {
1111 t.tb.Helper()
1112 ok := isHasPrefix(&actual, &expected)
1113 return t.report2(actual, expected, msg,
1114 ok)
1115 }
1116
1117 // isHasPrefix updates actual and expected to be a real string used for check,
1118 // to make dump easier to understand, but this result in losing type information.
1119 func isHasPrefix(actual, expected *any) bool {
1120 if *actual == nil || *expected == nil {
1121 return false
1122 }
1123 if !stringify(actual) {
1124 panic("actual is not a string, []byte, []rune, fmt.Stringer, error or nil")
1125 }
1126 if !stringify(expected) {
1127 panic("expected is not a string, []byte, []rune, fmt.Stringer, error or nil")
1128 }
1129 return strings.HasPrefix((*actual).(string), (*expected).(string))
1130 }
1131
1132 // NotHasPrefix checks for !strings.HasPrefix(actual, expected).
1133 //
1134 // See HasPrefix about supported actual/expected types and check logic.
1135 func (t *checks) NotHasPrefix(actual, expected any, msg ...any) bool {
1136 t.tb.Helper()
1137 ok := !isHasPrefix(&actual, &expected)
1138 return t.report2(actual, expected, msg,
1139 ok)
1140 }
1141
1142 // HasSuffix checks for [strings.HasSuffix](actual, expected).
1143 //
1144 // Both actual and expected may have any of these types:
1145 // - string - will use as is
1146 // - []byte - will convert with string()
1147 // - []rune - will convert with string()
1148 // - [fmt.Stringer] - will convert with actual.String()
1149 // - error - will convert with actual.Error()
1150 // - nil - check will always fail
1151 func (t *checks) HasSuffix(actual, expected any, msg ...any) bool {
1152 t.tb.Helper()
1153 ok := isHasSuffix(&actual, &expected)
1154 return t.report2(actual, expected, msg,
1155 ok)
1156 }
1157
1158 // isHasSuffix updates actual and expected to be a real string used for check,
1159 // to make dump easier to understand, but this result in losing type information.
1160 func isHasSuffix(actual, expected *any) bool {
1161 if *actual == nil || *expected == nil {
1162 return false
1163 }
1164 if !stringify(actual) {
1165 panic("actual is not a string, []byte, []rune, fmt.Stringer, error or nil")
1166 }
1167 if !stringify(expected) {
1168 panic("expected is not a string, []byte, []rune, fmt.Stringer, error or nil")
1169 }
1170 return strings.HasSuffix((*actual).(string), (*expected).(string))
1171 }
1172
1173 // NotHasSuffix checks for !strings.HasSuffix(actual, expected).
1174 //
1175 // See HasSuffix about supported actual/expected types and check logic.
1176 func (t *checks) NotHasSuffix(actual, expected any, msg ...any) bool {
1177 t.tb.Helper()
1178 ok := !isHasSuffix(&actual, &expected)
1179 return t.report2(actual, expected, msg,
1180 ok)
1181 }
1182
1183 // JSONEqual normalize formatting of actual and expected (if they're valid
1184 // JSON) and then checks for [bytes.Equal](actual, expected).
1185 //
1186 // Both actual and expected may have any of these types:
1187 // - string
1188 // - []byte
1189 // - [json.RawMessage]
1190 // - [*json.RawMessage]
1191 // - nil
1192 //
1193 // In case any of actual or expected is nil or empty or (for string or
1194 // []byte) is invalid JSON - check will fail.
1195 func (t *checks) JSONEqual(actual, expected any, msg ...any) bool {
1196 t.tb.Helper()
1197 ok := isJSONEqual(actual, expected)
1198 if !ok {
1199 if buf := jsonify(actual); len(buf) != 0 {
1200 actual = buf
1201 }
1202 if buf := jsonify(expected); len(buf) != 0 {
1203 expected = buf
1204 }
1205 }
1206 return t.report2(actual, expected, msg,
1207 ok)
1208 }
1209
1210 func isJSONEqual(actual, expected any) bool {
1211 jsonActual, jsonExpected := jsonify(actual), jsonify(expected)
1212 return len(jsonActual) != 0 && len(jsonExpected) != 0 &&
1213 bytes.Equal(jsonActual, jsonExpected)
1214 }
1215
1216 func jsonify(arg any) json.RawMessage {
1217 switch v := (arg).(type) {
1218 case nil:
1219 return nil
1220 case json.RawMessage:
1221 return v
1222 case *json.RawMessage:
1223 if v == nil {
1224 return nil
1225 }
1226 return *v
1227 }
1228 buf := reflect.ValueOf(arg).Convert(typBytes).Interface().([]byte) //nolint:forcetypeassert // Want panic.
1229
1230 var v any
1231 err := json.Unmarshal(buf, &v)
1232 if err != nil {
1233 return nil
1234 }
1235 buf, err = json.Marshal(v)
1236 if err != nil {
1237 return nil
1238 }
1239 return buf
1240 }
1241
1242 // HasType checks is actual has same type as expected.
1243 func (t *checks) HasType(actual, expected any, msg ...any) bool {
1244 t.tb.Helper()
1245 return t.report2(actual, expected, msg,
1246 reflect.TypeOf(actual) == reflect.TypeOf(expected))
1247 }
1248
1249 // NotHasType checks is actual has not same type as expected.
1250 func (t *checks) NotHasType(actual, expected any, msg ...any) bool {
1251 t.tb.Helper()
1252 return t.report2(actual, expected, msg,
1253 reflect.TypeOf(actual) != reflect.TypeOf(expected))
1254 }
1255
1256 // Implements checks is actual implements interface pointed by expected.
1257 //
1258 // You must use pointer to interface type in expected:
1259 //
1260 // t.Implements(os.Stdin, (*io.Reader)(nil))
1261 func (t *checks) Implements(actual, expected any, msg ...any) bool {
1262 t.tb.Helper()
1263 return t.report2(actual, expected, msg,
1264 isImplements(actual, expected))
1265 }
1266
1267 func isImplements(actual, expected any) bool {
1268 typActual := reflect.TypeOf(actual)
1269 if typActual.Kind() != reflect.Pointer {
1270 typActual = reflect.PointerTo(typActual)
1271 }
1272 return typActual.Implements(reflect.TypeOf(expected).Elem())
1273 }
1274
1275 // NotImplements checks is actual does not implements interface pointed by expected.
1276 //
1277 // You must use pointer to interface type in expected:
1278 //
1279 // t.NotImplements(os.Stdin, (*fmt.Stringer)(nil))
1280 func (t *checks) NotImplements(actual, expected any, msg ...any) bool {
1281 t.tb.Helper()
1282 return t.report2(actual, expected, msg,
1283 !isImplements(actual, expected))
1284 }
1285
1286 // SortEqual checks that actual and expected contain the same elements,
1287 // ignoring order (multiset equality, duplicates counted).
1288 //
1289 // Both actual and expected must be slices or arrays.
1290 // Elements need not be sortable and are compared like DeepEqual.
1291 // Nil and empty slices are equal (like BytesEqual, unlike DeepEqual).
1292 func (t *checks) SortEqual(actual, expected any, msg ...any) bool {
1293 t.tb.Helper()
1294 return t.report2(actual, expected, msg,
1295 isSortEqual(actual, expected))
1296 }
1297
1298 // NotSortEqual checks !SortEqual(actual, expected).
1299 //
1300 // See SortEqual about supported actual/expected types and check logic.
1301 func (t *checks) NotSortEqual(actual, expected any, msg ...any) bool {
1302 t.tb.Helper()
1303 return t.report1(actual, msg,
1304 !isSortEqual(actual, expected))
1305 }
1306
1307 func isSortEqual(actual, expected any) bool {
1308 va, ve := reflect.ValueOf(actual), reflect.ValueOf(expected)
1309 if va.Kind() != reflect.Slice && va.Kind() != reflect.Array {
1310 panic("actual is not a slice or array")
1311 }
1312 if ve.Kind() != reflect.Slice && ve.Kind() != reflect.Array {
1313 panic("expected is not a slice or array")
1314 }
1315 if va.Len() != ve.Len() {
1316 return false
1317 }
1318 return isMultisetIn(va, ve)
1319 }
1320
1321 // isMultisetIn reports whether every element of small has a distinct,
1322 // not-yet-used matching element in big, i.e. small is a multiset-subset of big.
1323 func isMultisetIn(small, big reflect.Value) bool {
1324 used := make([]bool, big.Len())
1325 for i := range small.Len() {
1326 found := false
1327 for j := range big.Len() {
1328 if !used[j] && elemEqual(small.Index(i).Interface(), big.Index(j).Interface()) {
1329 used[j], found = true, true
1330 break
1331 }
1332 }
1333 if !found {
1334 return false
1335 }
1336 }
1337 return true
1338 }
1339
1340 // Subset checks that actual contains all elements of expected:
1341 // for slices/arrays - as multisets (duplicates counted), ignoring order;
1342 // for maps - every key of expected exists in actual with an equal value.
1343 //
1344 // actual and expected must both be slices/arrays or both be maps.
1345 // Elements/values are compared like DeepEqual.
1346 // An empty/nil expected is a subset of anything of the same kind.
1347 //
1348 // Note: unlike testify's Subset, duplicates are counted, so [1,1] is not a subset of [1].
1349 func (t *checks) Subset(actual, expected any, msg ...any) bool {
1350 t.tb.Helper()
1351 return t.report2(actual, expected, msg,
1352 isSubset(actual, expected))
1353 }
1354
1355 // NotSubset checks !Subset(actual, expected).
1356 //
1357 // See Subset about supported actual/expected types and check logic.
1358 func (t *checks) NotSubset(actual, expected any, msg ...any) bool {
1359 t.tb.Helper()
1360 return t.report1(actual, msg,
1361 !isSubset(actual, expected))
1362 }
1363
1364 func isSubset(actual, expected any) bool {
1365 va, ve := reflect.ValueOf(actual), reflect.ValueOf(expected)
1366 switch ve.Kind() { //nolint:exhaustive // Covered by default case.
1367 case reflect.Map:
1368 if va.Kind() != reflect.Map {
1369 panic("actual is not a map")
1370 }
1371 return isMapSubset(va, ve)
1372 case reflect.Slice, reflect.Array:
1373 if va.Kind() != reflect.Slice && va.Kind() != reflect.Array {
1374 panic("actual is not a slice or array")
1375 }
1376 return isMultisetIn(ve, va)
1377 default:
1378 panic("expected is not a slice, array or map")
1379 }
1380 }
1381
1382 func isMapSubset(actual, expected reflect.Value) bool {
1383 iter := expected.MapRange()
1384 for iter.Next() {
1385 v := actual.MapIndex(iter.Key())
1386 if !v.IsValid() || !elemEqual(v.Interface(), iter.Value().Interface()) {
1387 return false
1388 }
1389 }
1390 return true
1391 }
1392
1393 // FileExists checks that path exists and is not a directory.
1394 //
1395 // A Stat error other than "not exists" (e.g. permission denied)
1396 // counts as "does not exist", same as testify.
1397 func (t *checks) FileExists(path string, msg ...any) bool {
1398 t.tb.Helper()
1399 fi, err := os.Stat(path)
1400 return t.report1(path, msg,
1401 err == nil && !fi.IsDir())
1402 }
1403
1404 // NotFileExists checks that path does not exist or is a directory.
1405 //
1406 // See FileExists about Stat error handling.
1407 func (t *checks) NotFileExists(path string, msg ...any) bool {
1408 t.tb.Helper()
1409 fi, err := os.Stat(path)
1410 return t.report1(path, msg,
1411 err != nil || fi.IsDir())
1412 }
1413
1414 // DirExists checks that path exists and is a directory.
1415 //
1416 // See FileExists about Stat error handling.
1417 func (t *checks) DirExists(path string, msg ...any) bool {
1418 t.tb.Helper()
1419 fi, err := os.Stat(path)
1420 return t.report1(path, msg,
1421 err == nil && fi.IsDir())
1422 }
1423
1424 // NotDirExists checks that path does not exist or is not a directory.
1425 //
1426 // See FileExists about Stat error handling.
1427 func (t *checks) NotDirExists(path string, msg ...any) bool {
1428 t.tb.Helper()
1429 fi, err := os.Stat(path)
1430 return t.report1(path, msg,
1431 err != nil || !fi.IsDir())
1432 }