-
Notifications
You must be signed in to change notification settings - Fork 0
/
check.go
1361 lines (1248 loc) · 40 KB
/
check.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package check
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"reflect"
"regexp"
"strings"
"testing"
"time"
pkgerrors "github.com/pkg/errors" //nolint:depguard // By design.
"github.com/powerman/deepequal"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
//nolint:gochecknoglobals // Const.
var (
typString = reflect.TypeOf("")
typBytes = reflect.TypeOf([]byte(nil))
typFloat64 = reflect.TypeOf(0.0)
)
// C wraps *testing.T to make it convenient to call checkers in test.
type C struct {
*testing.T
todo bool
must bool
}
const (
nameActual = "Actual"
nameExpected = "Expected"
)
// Parallel implements an internal workaround which have no visible
// effect, so you should just call t.Parallel() as you usually do - it
// will work as expected.
func (t *C) Parallel() {
t.Helper()
// Goconvey anyway doesn't provide -test.cpu= and mixed output of
// parallel tests result in reporting failed tests at wrong places
// and with wrong failed tests count in web UI.
if !flags.detect().conveyJSON {
t.T.Parallel()
}
}
// T creates and returns new *C, which wraps given tt and supposed to be
// used inplace of it, providing you with access to many useful helpers in
// addition to standard methods of *testing.T.
//
// It's convenient to rename Test function's arg from t to something
// else, create wrapped variable with usual name t and use only t:
//
// func TestSomething(tt *testing.T) {
// t := check.T(tt)
// // use only t in test and don't touch tt anymore
// }
func T(tt *testing.T) *C { //nolint:thelper // With check we name it tt!
return &C{T: tt}
}
// TODO creates and returns new *C, which have only one difference from
// original one: every passing check is now handled as failed and vice
// versa (this doesn't affect boolean value returned by check).
// You can continue using both old and new *C at same time.
//
// Swapping passed/failed gives you ability to temporary mark some failed
// test as passed. For example, this may be useful to avoid broken builds
// in CI. This is often better than commenting, deleting or skipping
// broken test because it will continue to execute, and eventually when
// reason why it fails will be fixed this test will became failed again -
// notifying you the mark can and should be removed from this test now.
//
// func TestSomething(tt *testing.T) {
// t := check.T(tt)
// // Normal tests.
// t.True(true)
// // If you need to mark just one/few broken tests:
// t.TODO().True(false)
// t.True(true)
// // If there are several broken tests mixed with working ones:
// todo := t.TODO()
// t.True(true)
// todo.True(false)
// t.True(true)
// if todo.True(false) {
// panic("never here")
// }
// // If all tests below this point are broken:
// t = t.TODO()
// t.True(false)
// ...
// }
func (t *C) TODO() *C {
return &C{T: t.T, todo: true, must: t.must}
}
// MustAll creates and returns new *C, which have only one difference from
// original one: every failed check will interrupt test using t.FailNow.
// You can continue using both old and new *C at same time.
//
// This provides an easy way to turn all checks into assertion.
func (t *C) MustAll() *C {
return &C{T: t.T, todo: t.todo, must: true}
}
func (t *C) pass() {
statsMu.Lock()
defer statsMu.Unlock()
if stats[t.T] == nil {
stats[t.T] = newTestStat(t.Name(), false)
}
if t.todo {
stats[t.T].forged.value++
} else {
stats[t.T].passed.value++
}
}
func (t *C) fail() {
statsMu.Lock()
defer statsMu.Unlock()
if stats[t.T] == nil {
stats[t.T] = newTestStat(t.Name(), false)
}
stats[t.T].failed.value++
}
func (t *C) report(ok bool, msg []any, checker string, name []string, args []any) bool { //nolint:revive // False positive.
t.Helper()
if ok != t.todo {
t.pass()
return ok
}
if t.todo {
checker = "TODO " + checker
}
dump := make([]dump, 0, len(args))
for _, arg := range args {
dump = append(dump, newDump(arg))
}
failure := new(bytes.Buffer)
fmt.Fprintf(failure, "%s\nChecker: %s%s%s\n",
format(msg...),
ansiYellow, checker, ansiReset,
)
failureShort := failure.String()
// Reverse order to show Actual: last.
for i := len(dump) - 1; i >= 0; i-- {
fmt.Fprintf(failure, "%-10s", name[i]+":")
switch name[i] {
case nameActual:
fmt.Fprint(failure, ansiRed)
default:
fmt.Fprint(failure, ansiGreen)
}
fmt.Fprintf(failure, "%s%s", dump[i], ansiReset)
}
failureLong := failure.String()
wantDiff := len(dump) == 2 && name[0] == nameActual && name[1] == nameExpected //nolint:gosec // False positive.
if wantDiff { //nolint:nestif // No idea how to simplify.
if reportToGoConvey(dump[0].String(), dump[1].String(), failureShort) == nil {
t.Fail()
} else {
fmt.Fprintf(failure, "\n%s", colouredDiff(dump[0].diff(dump[1])))
t.Errorf("%s\n", failure)
}
} else {
if reportToGoConvey("", "", failureLong) == nil {
t.Fail()
} else {
t.Errorf("%s\n", failure)
}
}
t.fail()
if t.must {
t.FailNow()
}
return ok
}
func (t *C) reportShould1(funcName string, actual any, msg []any, ok bool) bool {
t.Helper()
return t.report(ok, msg,
"Should "+funcName,
[]string{nameActual},
[]any{actual})
}
func (t *C) reportShould2(funcName string, actual, expected any, msg []any, ok bool) bool {
t.Helper()
return t.report(ok, msg,
"Should "+funcName,
[]string{nameActual, nameExpected},
[]any{actual, expected})
}
func (t *C) report0(msg []any, ok bool) bool {
t.Helper()
return t.report(ok, msg,
callerFuncName(1),
[]string{},
[]any{})
}
func (t *C) report1(actual any, msg []any, ok bool) bool {
t.Helper()
return t.report(ok, msg,
callerFuncName(1),
[]string{nameActual},
[]any{actual})
}
func (t *C) report2(actual, expected any, msg []any, ok bool) bool {
t.Helper()
checker, arg2Name := callerFuncName(1), nameExpected
if strings.Contains(checker, "Match") {
arg2Name = "Regex"
}
return t.report(ok, msg,
checker,
[]string{nameActual, arg2Name},
[]any{actual, expected})
}
func (t *C) report3(actual, expected1, expected2 any, msg []any, ok bool) bool {
t.Helper()
checker, arg2Name, arg3Name := callerFuncName(1), "arg1", "arg2"
switch {
case strings.Contains(checker, "Between"):
arg2Name, arg3Name = "Min", "Max"
case strings.Contains(checker, "Delta"):
arg2Name, arg3Name = nameExpected, "Delta"
case strings.Contains(checker, "SMAPE"):
arg2Name, arg3Name = nameExpected, "SMAPE"
}
return t.report(ok, msg,
checker,
[]string{nameActual, arg2Name, arg3Name},
[]any{actual, expected1, expected2})
}
// Must interrupt test using t.FailNow if called with false value.
//
// This provides an easy way to turn any check into assertion:
//
// t.Must(t.Nil(err))
func (t *C) Must(continueTest bool, msg ...any) { //nolint:revive // False positive.
t.Helper()
t.report0(msg, continueTest)
if !continueTest {
t.FailNow()
}
}
type (
// ShouldFunc1 is like Nil or Zero.
ShouldFunc1 func(t *C, actual any) bool
// ShouldFunc2 is like Equal or Match.
ShouldFunc2 func(t *C, actual, expected any) bool
)
// Should use user-provided check function to do actual check.
//
// anyShouldFunc must have type ShouldFunc1 or ShouldFunc2. It should
// return true if check was successful. There is no need to call t.Error
// in anyShouldFunc - this will be done automatically when it returns.
//
// args must contain at least 1 element for ShouldFunc1 and at least
// 2 elements for ShouldFunc2.
// Rest of elements will be processed as usual msg ...interface{} param.
//
// Example:
//
// func bePositive(_ *check.C, actual interface{}) bool {
// return actual.(int) > 0
// }
// func TestCustomCheck(tt *testing.T) {
// t := check.T(tt)
// t.Should(bePositive, 42, "custom check!!!")
// }
func (t *C) Should(anyShouldFunc any, args ...any) bool {
t.Helper()
switch f := anyShouldFunc.(type) {
case func(t *C, actual any) bool:
return t.should1(f, args...)
case func(t *C, actual, expected any) bool:
return t.should2(f, args...)
default:
panic("anyShouldFunc is not a ShouldFunc1 or ShouldFunc2")
}
}
func (t *C) should1(f ShouldFunc1, args ...any) bool {
t.Helper()
if len(args) < 1 {
panic("not enough params for " + funcName(f))
}
actual, msg := args[0], args[1:]
return t.reportShould1(funcName(f), actual, msg,
f(t, actual))
}
func (t *C) should2(f ShouldFunc2, args ...any) bool {
t.Helper()
const minArgs = 2
if len(args) < minArgs {
panic("not enough params for " + funcName(f))
}
actual, expected, msg := args[0], args[1], args[2:]
return t.reportShould2(funcName(f), actual, expected, msg,
f(t, actual, expected))
}
// Nil checks for actual == nil.
//
// There is one subtle difference between this check and Go `== nil` (if
// this surprises you then you should read
// https://golang.org/doc/faq#nil_error first):
//
// var intPtr *int
// var empty interface{}
// var notEmpty interface{} = intPtr
// t.True(intPtr == nil) // TRUE
// t.True(empty == nil) // TRUE
// t.True(notEmpty == nil) // FALSE
//
// When you call this function your actual value will be stored in
// interface{} argument, and this makes any typed nil pointer value `!=
// nil` inside this function (just like in example above happens with
// notEmpty variable).
//
// As it is very common case to check some typed pointer using Nil this
// check has to work around and detect nil even if usual `== nil` return
// false. But this has nasty side effect: if actual value already was of
// interface type and contains some typed nil pointer (which is usually
// bad thing and should be avoid) then Nil check will pass (which may be
// not what you want/expect):
//
// t.Nil(nil) // TRUE
// t.Nil(intPtr) // TRUE
// t.Nil(empty) // TRUE
// t.Nil(notEmpty) // WARNING: also TRUE!
//
// Second subtle case is less usual: uintptr(0) is sorta nil, but not
// really, so Nil(uintptr(0)) will fail. Nil(unsafe.Pointer(nil)) will
// also fail, for the same reason. Please do not use this and consider
// this behaviour undefined, because it may change in the future.
func (t *C) Nil(actual any, msg ...any) bool {
t.Helper()
return t.report1(actual, msg,
isNil(actual))
}
func isNil(actual any) bool {
switch val := reflect.ValueOf(actual); val.Kind() {
case reflect.Invalid:
return actual == nil
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice:
return val.IsNil()
case reflect.Uintptr, reflect.UnsafePointer: // Subtle cases documented above.
case reflect.Interface: // ???
// Can't be nil:
case reflect.Struct, reflect.Array, reflect.Bool, reflect.String:
case reflect.Complex128, reflect.Complex64, reflect.Float32, reflect.Float64:
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8:
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8:
}
return false
}
// NotNil checks for actual != nil.
//
// See Nil about subtle case in check logic.
func (t *C) NotNil(actual any, msg ...any) bool {
t.Helper()
return t.report0(msg,
!isNil(actual))
}
// Error is equivalent to Log followed by Fail.
//
// It is like t.Errorf with TODO() and statistics support.
func (t *C) Error(msg ...any) {
t.Helper()
t.report0(msg, false)
}
// True checks for cond == true.
//
// This can be useful to use your own custom checks, but this way you
// won't get nice dump/diff for actual/expected values. You'll still have
// statistics about passed/failed checks and it's shorter than usual:
//
// if !cond {
// t.Errorf(msg...)
// }
func (t *C) True(cond bool, msg ...any) bool {
t.Helper()
return t.report0(msg,
cond)
}
// False checks for cond == false.
func (t *C) False(cond bool, msg ...any) bool {
t.Helper()
return t.report0(msg,
!cond)
}
// Equal checks for actual == expected.
//
// Note: For time.Time it uses actual.Equal(expected) instead.
func (t *C) Equal(actual, expected any, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
isEqual(actual, expected))
}
func isEqual(actual, expected any) bool {
switch actual := actual.(type) {
case time.Time:
return actual.Equal(expected.(time.Time))
default:
return actual == expected
}
}
// EQ is a synonym for Equal.
func (t *C) EQ(actual, expected any, msg ...any) bool {
t.Helper()
return t.Equal(actual, expected, msg...)
}
// NotEqual checks for actual != expected.
func (t *C) NotEqual(actual, expected any, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
!isEqual(actual, expected))
}
// NE is a synonym for NotEqual.
func (t *C) NE(actual, expected any, msg ...any) bool {
t.Helper()
return t.NotEqual(actual, expected, msg...)
}
// BytesEqual checks for bytes.Equal(actual, expected).
//
// Hint: BytesEqual([]byte{}, []byte(nil)) is true (unlike DeepEqual).
func (t *C) BytesEqual(actual, expected []byte, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
bytes.Equal(actual, expected))
}
// NotBytesEqual checks for !bytes.Equal(actual, expected).
//
// Hint: NotBytesEqual([]byte{}, []byte(nil)) is false (unlike NotDeepEqual).
func (t *C) NotBytesEqual(actual, expected []byte, msg ...any) bool {
t.Helper()
return t.report1(actual, msg,
!bytes.Equal(actual, expected))
}
// DeepEqual checks for reflect.DeepEqual(actual, expected).
// It will also use Equal method for types which implements it
// (e.g. time.Time, decimal.Decimal, etc.).
// It will use proto.Equal for protobuf messages.
func (t *C) DeepEqual(actual, expected any, msg ...any) bool {
t.Helper()
protoActual, proto1 := actual.(protoreflect.ProtoMessage)
protoExpected, proto2 := expected.(protoreflect.ProtoMessage)
if proto1 && proto2 {
return t.report2(actual, expected, msg,
proto.Equal(protoActual, protoExpected))
}
return t.report2(actual, expected, msg,
deepequal.DeepEqual(actual, expected))
}
// NotDeepEqual checks for !reflect.DeepEqual(actual, expected).
// It will also use Equal method for types which implements it
// (e.g. time.Time, decimal.Decimal, etc.).
// It will use proto.Equal for protobuf messages.
func (t *C) NotDeepEqual(actual, expected any, msg ...any) bool {
t.Helper()
protoActual, proto1 := actual.(protoreflect.ProtoMessage)
protoExpected, proto2 := expected.(protoreflect.ProtoMessage)
if proto1 && proto2 {
return t.report1(actual, msg,
!proto.Equal(protoActual, protoExpected))
}
return t.report1(actual, msg,
!deepequal.DeepEqual(actual, expected))
}
// Match checks for regex.MatchString(actual).
//
// Regex type can be either *regexp.Regexp or string.
//
// Actual type can be:
// - string - will match with actual
// - []byte - will match with string(actual)
// - []rune - will match with string(actual)
// - fmt.Stringer - will match with actual.String()
// - error - will match with actual.Error()
// - nil - will not match (even with empty regex)
func (t *C) Match(actual, regex any, msg ...any) bool {
t.Helper()
ok := isMatch(&actual, regex)
return t.report2(actual, regex, msg,
ok)
}
// isMatch updates actual to be a real string used for matching, to make
// dump easier to understand, but this result in losing type information.
func isMatch(actual *any, regex any) bool { //nolint:gocritic // False positive.
if *actual == nil {
return false
}
if !stringify(actual) {
panic("actual is not a string, []byte, []rune, fmt.Stringer, error or nil")
}
s := (*actual).(string) //nolint:forcetypeassert // False positive.
switch v := regex.(type) {
case *regexp.Regexp:
return v.MatchString(s)
case string:
return regexp.MustCompile(v).MatchString(s)
}
panic("regex is not a *regexp.Regexp or string")
}
func stringify(arg *any) bool { //nolint:gocritic // False positive.
switch v := (*arg).(type) {
case nil:
return false
case error:
*arg = v.Error()
case fmt.Stringer:
*arg = v.String()
default:
typ := reflect.TypeOf(*arg)
switch typ.Kind() { //nolint:exhaustive // Covered by default case.
case reflect.String:
case reflect.Slice:
switch typ.Elem().Kind() { //nolint:exhaustive // Covered by default case.
case reflect.Uint8, reflect.Int32:
default:
return false
}
default:
return false
}
*arg = reflect.ValueOf(*arg).Convert(typString).Interface()
}
return true
}
// NotMatch checks for !regex.MatchString(actual).
//
// See Match about supported actual/regex types and check logic.
func (t *C) NotMatch(actual, regex any, msg ...any) bool {
t.Helper()
ok := !isMatch(&actual, regex)
return t.report2(actual, regex, msg,
ok)
}
// Contains checks is actual contains substring/element expected.
//
// Element of array/slice/map is checked using == expected.
//
// Type of expected depends on type of actual:
// - if actual is a string, then expected should be a string
// - if actual is an array, then expected should have array's element type
// - if actual is a slice, then expected should have slice's element type
// - if actual is a map, then expected should have map's value type
//
// Hint: In a map it looks for a value, if you need to look for a key -
// use HasKey instead.
func (t *C) Contains(actual, expected any, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
isContains(actual, expected))
}
func isContains(actual, expected any) (found bool) {
switch valActual := reflect.ValueOf(actual); valActual.Kind() { //nolint:exhaustive // Covered by default case.
case reflect.String:
strActual := valActual.Convert(typString).Interface().(string) //nolint:forcetypeassert // False positive.
valExpected := reflect.ValueOf(expected)
if valExpected.Kind() != reflect.String {
panic("expected underlying type is not a string")
}
strExpected := valExpected.Convert(typString).Interface().(string) //nolint:forcetypeassert // False positive.
found = strings.Contains(strActual, strExpected)
case reflect.Map:
if valActual.Type().Elem() != reflect.TypeOf(expected) {
panic("expected type not match actual element type")
}
keys := valActual.MapKeys()
for i := 0; i < len(keys) && !found; i++ {
found = valActual.MapIndex(keys[i]).Interface() == expected
}
case reflect.Slice, reflect.Array:
if valActual.Type().Elem() != reflect.TypeOf(expected) {
panic("expected type not match actual element type")
}
for i := 0; i < valActual.Len() && !found; i++ {
found = valActual.Index(i).Interface() == expected
}
default:
panic("actual is not a string, array, slice or map")
}
return found
}
// NotContains checks is actual not contains substring/element expected.
//
// See Contains about supported actual/expected types and check logic.
func (t *C) NotContains(actual, expected any, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
!isContains(actual, expected))
}
// HasKey checks is actual has key expected.
func (t *C) HasKey(actual, expected any, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
hasKey(actual, expected))
}
func hasKey(actual, expected any) bool {
return reflect.ValueOf(actual).MapIndex(reflect.ValueOf(expected)).IsValid()
}
// NotHasKey checks is actual has no key expected.
func (t *C) NotHasKey(actual, expected any, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
!hasKey(actual, expected))
}
// Zero checks is actual is zero value of it's type.
func (t *C) Zero(actual any, msg ...any) bool {
t.Helper()
return t.report1(actual, msg,
isZero(actual))
}
func isZero(actual any) bool {
if isNil(actual) {
return true
} else if typ := reflect.TypeOf(actual); typ.Comparable() {
// Not Func, Map, Slice, Array with non-comparable
// elements, Struct with non-comparable fields.
return actual == reflect.Zero(typ).Interface()
} else if typ.Kind() == reflect.Array {
zero := true
val := reflect.ValueOf(actual)
for i := 0; i < val.Len() && zero; i++ {
zero = isZero(val.Index(i).Interface())
}
return zero
}
// Func, Struct with non-comparable fields.
// Non-nil Map, Slice.
return false
}
// NotZero checks is actual is not zero value of it's type.
func (t *C) NotZero(actual any, msg ...any) bool {
t.Helper()
return t.report1(actual, msg,
!isZero(actual))
}
// Len checks is len(actual) == expected.
func (t *C) Len(actual any, expected int, msg ...any) bool {
t.Helper()
l := reflect.ValueOf(actual).Len()
return t.report2(l, expected, msg,
l == expected)
}
// NotLen checks is len(actual) != expected.
func (t *C) NotLen(actual any, expected int, msg ...any) bool {
t.Helper()
l := reflect.ValueOf(actual).Len()
return t.report2(l, expected, msg,
l != expected)
}
// Err checks is actual error is the same as expected error.
//
// If errors.Is() fails then it'll use more sofiscated logic:
//
// It tries to recursively unwrap actual before checking using
// errors.Unwrap() and github.com/pkg/errors.Cause().
// In case of multi-error (Unwrap() []error) it use only first error.
//
// It will use proto.Equal for gRPC status errors.
//
// They may be a different instances, but must have same type and value.
//
// Checking for nil is okay, but using Nil(actual) instead is more clean.
func (t *C) Err(actual, expected error, msg ...any) bool {
t.Helper()
actual2 := unwrapErr(actual)
equal := fmt.Sprintf("%#v", actual2) == fmt.Sprintf("%#v", expected)
_, proto1 := actual2.(interface{ GRPCStatus() *status.Status })
_, proto2 := expected.(interface{ GRPCStatus() *status.Status })
if proto1 || proto2 {
equal = proto.Equal(status.Convert(actual2).Proto(), status.Convert(expected).Proto())
}
if !equal {
equal = errors.Is(actual, expected)
}
return t.report2(actual, expected, msg, equal)
}
func unwrapErr(err error) (actual error) {
defer func() { _ = recover() }()
actual = err
for {
actual = pkgerrors.Cause(actual)
var unwrapped error
switch wrapped := actual.(type) { //nolint:errorlint // False positive.
case interface{ Unwrap() error }:
unwrapped = wrapped.Unwrap()
case interface{ Unwrap() []error }:
unwrappeds := wrapped.Unwrap()
if len(unwrappeds) > 0 {
unwrapped = unwrappeds[0]
}
}
if unwrapped == nil {
break
}
actual = unwrapped
}
return actual
}
// NotErr checks is actual error is not the same as expected error.
//
// It tries to recursively unwrap actual before checking using
// errors.Unwrap() and github.com/pkg/errors.Cause().
// In case of multi-error (Unwrap() []error) it use only first error.
//
// It will use !proto.Equal for gRPC status errors.
//
// They must have either different types or values (or one should be nil).
// Different instances with same type and value will be considered the
// same error, and so is both nil.
//
// Finally it'll use !errors.Is().
func (t *C) NotErr(actual, expected error, msg ...any) bool {
t.Helper()
actual2 := unwrapErr(actual)
notEqual := fmt.Sprintf("%#v", actual2) != fmt.Sprintf("%#v", expected)
_, proto1 := actual2.(interface{ GRPCStatus() *status.Status })
_, proto2 := expected.(interface{ GRPCStatus() *status.Status })
if proto1 || proto2 {
notEqual = !proto.Equal(status.Convert(actual2).Proto(), status.Convert(expected).Proto())
}
if notEqual {
notEqual = !errors.Is(actual, expected)
}
return t.report1(actual, msg, notEqual)
}
// Panic checks is actual() panics.
//
// It is able to detect panic(nil)… but you should try to avoid using this.
func (t *C) Panic(actual func(), msg ...any) bool {
t.Helper()
didPanic := true
func() {
defer func() { _ = recover() }()
actual()
didPanic = false
}()
return t.report0(msg,
didPanic)
}
// NotPanic checks is actual() don't panics.
//
// It is able to detect panic(nil)… but you should try to avoid using this.
func (t *C) NotPanic(actual func(), msg ...any) bool {
t.Helper()
didPanic := true
func() {
defer func() { _ = recover() }()
actual()
didPanic = false
}()
return t.report0(msg,
!didPanic)
}
// PanicMatch checks is actual() panics and panic text match regex.
//
// Regex type can be either *regexp.Regexp or string.
//
// In case of panic(nil) it will match like panic("<nil>").
func (t *C) PanicMatch(actual func(), regex any, msg ...any) bool {
t.Helper()
var panicVal any
didPanic := true
func() {
defer func() { panicVal = recover() }()
actual()
didPanic = false
}()
if !didPanic {
return t.report0(msg,
false)
}
switch panicVal.(type) {
case string, error:
default:
panicVal = fmt.Sprintf("%#v", panicVal)
}
ok := isMatch(&panicVal, regex)
return t.report2(panicVal, regex, msg,
ok)
}
// PanicNotMatch checks is actual() panics and panic text not match regex.
//
// Regex type can be either *regexp.Regexp or string.
//
// In case of panic(nil) it will match like panic("<nil>").
func (t *C) PanicNotMatch(actual func(), regex any, msg ...any) bool {
t.Helper()
var panicVal any
didPanic := true
func() {
defer func() { panicVal = recover() }()
actual()
didPanic = false
}()
if !didPanic {
return t.report0(msg,
false)
}
switch panicVal.(type) {
case string, error:
default:
panicVal = fmt.Sprintf("%#v", panicVal)
}
ok := !isMatch(&panicVal, regex)
return t.report2(panicVal, regex, msg,
ok)
}
// Less checks for actual < expected.
//
// Both actual and expected must be either:
// - signed integers
// - unsigned integers
// - floats
// - strings
// - time.Time
func (t *C) Less(actual, expected any, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
isLess(actual, expected))
}
func isLess(actual, expected any) bool {
switch v1, v2 := reflect.ValueOf(actual), reflect.ValueOf(expected); v1.Kind() { //nolint:exhaustive // Covered by default case.
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v1.Int() < v2.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v1.Uint() < v2.Uint()
case reflect.Float32, reflect.Float64:
return v1.Float() < v2.Float()
case reflect.String:
return v1.String() < v2.String()
default:
if actualTime, ok := actual.(time.Time); ok {
return actualTime.Before(expected.(time.Time))
}
}
panic("actual is not a number, string or time.Time")
}
// LT is a synonym for Less.
func (t *C) LT(actual, expected any, msg ...any) bool {
t.Helper()
return t.Less(actual, expected, msg...)
}
// LessOrEqual checks for actual <= expected.
//
// Both actual and expected must be either:
// - signed integers
// - unsigned integers
// - floats
// - strings
// - time.Time
func (t *C) LessOrEqual(actual, expected any, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
!isGreater(actual, expected))
}
func isGreater(actual, expected any) bool {
switch v1, v2 := reflect.ValueOf(actual), reflect.ValueOf(expected); v1.Kind() { //nolint:exhaustive // Covered by default case.
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v1.Int() > v2.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v1.Uint() > v2.Uint()
case reflect.Float32, reflect.Float64:
return v1.Float() > v2.Float()
case reflect.String:
return v1.String() > v2.String()
default:
if actualTime, ok := actual.(time.Time); ok {
return actualTime.After(expected.(time.Time))
}
}
panic("actual is not a number, string or time.Time")
}
// LE is a synonym for LessOrEqual.
func (t *C) LE(actual, expected any, msg ...any) bool {
t.Helper()
return t.LessOrEqual(actual, expected, msg...)
}
// Greater checks for actual > expected.
//
// Both actual and expected must be either:
// - signed integers
// - unsigned integers
// - floats
// - strings
// - time.Time
func (t *C) Greater(actual, expected any, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
isGreater(actual, expected))
}
// GT is a synonym for Greater.
func (t *C) GT(actual, expected any, msg ...any) bool {
t.Helper()
return t.Greater(actual, expected, msg...)
}
// GreaterOrEqual checks for actual >= expected.
//
// Both actual and expected must be either:
// - signed integers
// - unsigned integers
// - floats
// - strings
// - time.Time
func (t *C) GreaterOrEqual(actual, expected any, msg ...any) bool {
t.Helper()
return t.report2(actual, expected, msg,
!isLess(actual, expected))
}
// GE is a synonym for GreaterOrEqual.
func (t *C) GE(actual, expected any, msg ...any) bool {
t.Helper()
return t.GreaterOrEqual(actual, expected, msg...)
}