1 package assert
2
3 import (
4 "bufio"
5 "bytes"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "math"
11 "os"
12 "path/filepath"
13 "reflect"
14 "regexp"
15 "runtime"
16 "strings"
17 "testing"
18 "time"
19 )
20
21 var (
22 i interface{}
23 zeros = []interface{}{
24 false,
25 byte(0),
26 complex64(0),
27 complex128(0),
28 float32(0),
29 float64(0),
30 int(0),
31 int8(0),
32 int16(0),
33 int32(0),
34 int64(0),
35 rune(0),
36 uint(0),
37 uint8(0),
38 uint16(0),
39 uint32(0),
40 uint64(0),
41 uintptr(0),
42 "",
43 [0]interface{}{},
44 []interface{}(nil),
45 struct{ x int }{},
46 (*interface{})(nil),
47 (func())(nil),
48 nil,
49 interface{}(nil),
50 map[interface{}]interface{}(nil),
51 (chan interface{})(nil),
52 (<-chan interface{})(nil),
53 (chan<- interface{})(nil),
54 }
55 nonZeros = []interface{}{
56 true,
57 byte(1),
58 complex64(1),
59 complex128(1),
60 float32(1),
61 float64(1),
62 int(1),
63 int8(1),
64 int16(1),
65 int32(1),
66 int64(1),
67 rune(1),
68 uint(1),
69 uint8(1),
70 uint16(1),
71 uint32(1),
72 uint64(1),
73 uintptr(1),
74 "s",
75 [1]interface{}{1},
76 []interface{}{},
77 struct{ x int }{1},
78 (&i),
79 (func() {}),
80 interface{}(1),
81 map[interface{}]interface{}{},
82 (make(chan interface{})),
83 (<-chan interface{})(make(chan interface{})),
84 (chan<- interface{})(make(chan interface{})),
85 }
86 )
87
88
89 type AssertionTesterInterface interface {
90 TestMethod()
91 }
92
93
94 type AssertionTesterConformingObject struct {
95 }
96
97 func (a *AssertionTesterConformingObject) TestMethod() {
98 }
99
100
101 type AssertionTesterNonConformingObject struct {
102 }
103
104 func TestObjectsAreEqual(t *testing.T) {
105 cases := []struct {
106 expected interface{}
107 actual interface{}
108 result bool
109 }{
110
111 {"Hello World", "Hello World", true},
112 {123, 123, true},
113 {123.5, 123.5, true},
114 {[]byte("Hello World"), []byte("Hello World"), true},
115 {nil, nil, true},
116
117
118 {map[int]int{5: 10}, map[int]int{10: 20}, false},
119 {'x', "x", false},
120 {"x", 'x', false},
121 {0, 0.1, false},
122 {0.1, 0, false},
123 {time.Now, time.Now, false},
124 {func() {}, func() {}, false},
125 {uint32(10), int32(10), false},
126 }
127
128 for _, c := range cases {
129 t.Run(fmt.Sprintf("ObjectsAreEqual(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
130 res := ObjectsAreEqual(c.expected, c.actual)
131
132 if res != c.result {
133 t.Errorf("ObjectsAreEqual(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
134 }
135
136 })
137 }
138 }
139
140 func TestObjectsAreEqualValues(t *testing.T) {
141 now := time.Now()
142
143 cases := []struct {
144 expected interface{}
145 actual interface{}
146 result bool
147 }{
148 {uint32(10), int32(10), true},
149 {0, nil, false},
150 {nil, 0, false},
151 {now, now.In(time.Local), false},
152 {int(270), int8(14), false},
153 {int8(14), int(270), false},
154 {[]int{270, 270}, []int8{14, 14}, false},
155 {complex128(1e+100 + 1e+100i), complex64(complex(math.Inf(0), math.Inf(0))), false},
156 {complex64(complex(math.Inf(0), math.Inf(0))), complex128(1e+100 + 1e+100i), false},
157 {complex128(1e+100 + 1e+100i), 270, false},
158 {270, complex128(1e+100 + 1e+100i), false},
159 {complex128(1e+100 + 1e+100i), 3.14, false},
160 {3.14, complex128(1e+100 + 1e+100i), false},
161 {complex128(1e+10 + 1e+10i), complex64(1e+10 + 1e+10i), true},
162 {complex64(1e+10 + 1e+10i), complex128(1e+10 + 1e+10i), true},
163 }
164
165 for _, c := range cases {
166 t.Run(fmt.Sprintf("ObjectsAreEqualValues(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
167 res := ObjectsAreEqualValues(c.expected, c.actual)
168
169 if res != c.result {
170 t.Errorf("ObjectsAreEqualValues(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
171 }
172 })
173 }
174 }
175
176 type Nested struct {
177 Exported interface{}
178 notExported interface{}
179 }
180
181 type S struct {
182 Exported1 interface{}
183 Exported2 Nested
184 notExported1 interface{}
185 notExported2 Nested
186 }
187
188 type S2 struct {
189 foo interface{}
190 }
191
192 type S3 struct {
193 Exported1 *Nested
194 Exported2 *Nested
195 }
196
197 type S4 struct {
198 Exported1 []*Nested
199 }
200
201 type S5 struct {
202 Exported Nested
203 }
204
205 type S6 struct {
206 Exported string
207 unexported string
208 }
209
210 func TestObjectsExportedFieldsAreEqual(t *testing.T) {
211
212 intValue := 1
213
214 cases := []struct {
215 expected interface{}
216 actual interface{}
217 result bool
218 }{
219 {S{1, Nested{2, 3}, 4, Nested{5, 6}}, S{1, Nested{2, 3}, 4, Nested{5, 6}}, true},
220 {S{1, Nested{2, 3}, 4, Nested{5, 6}}, S{1, Nested{2, 3}, "a", Nested{5, 6}}, true},
221 {S{1, Nested{2, 3}, 4, Nested{5, 6}}, S{1, Nested{2, 3}, 4, Nested{5, "a"}}, true},
222 {S{1, Nested{2, 3}, 4, Nested{5, 6}}, S{1, Nested{2, 3}, 4, Nested{"a", "a"}}, true},
223 {S{1, Nested{2, 3}, 4, Nested{5, 6}}, S{1, Nested{2, "a"}, 4, Nested{5, 6}}, true},
224 {S{1, Nested{2, 3}, 4, Nested{5, 6}}, S{"a", Nested{2, 3}, 4, Nested{5, 6}}, false},
225 {S{1, Nested{2, 3}, 4, Nested{5, 6}}, S{1, Nested{"a", 3}, 4, Nested{5, 6}}, false},
226 {S{1, Nested{2, 3}, 4, Nested{5, 6}}, S2{1}, false},
227 {1, S{1, Nested{2, 3}, 4, Nested{5, 6}}, false},
228
229 {S3{&Nested{1, 2}, &Nested{3, 4}}, S3{&Nested{1, 2}, &Nested{3, 4}}, true},
230 {S3{nil, &Nested{3, 4}}, S3{nil, &Nested{3, 4}}, true},
231 {S3{&Nested{1, 2}, &Nested{3, 4}}, S3{&Nested{1, 2}, &Nested{3, "b"}}, true},
232 {S3{&Nested{1, 2}, &Nested{3, 4}}, S3{&Nested{1, "a"}, &Nested{3, "b"}}, true},
233 {S3{&Nested{1, 2}, &Nested{3, 4}}, S3{&Nested{"a", 2}, &Nested{3, 4}}, false},
234 {S3{&Nested{1, 2}, &Nested{3, 4}}, S3{}, false},
235 {S3{}, S3{}, true},
236
237 {S4{[]*Nested{{1, 2}}}, S4{[]*Nested{{1, 2}}}, true},
238 {S4{[]*Nested{{1, 2}}}, S4{[]*Nested{{1, 3}}}, true},
239 {S4{[]*Nested{{1, 2}, {3, 4}}}, S4{[]*Nested{{1, "a"}, {3, "b"}}}, true},
240 {S4{[]*Nested{{1, 2}, {3, 4}}}, S4{[]*Nested{{1, "a"}, {2, "b"}}}, false},
241
242 {Nested{&intValue, 2}, Nested{&intValue, 2}, true},
243 {Nested{&Nested{1, 2}, 3}, Nested{&Nested{1, "b"}, 3}, true},
244 {Nested{&Nested{1, 2}, 3}, Nested{nil, 3}, false},
245
246 {
247 Nested{map[interface{}]*Nested{nil: nil}, 2},
248 Nested{map[interface{}]*Nested{nil: nil}, 2},
249 true,
250 },
251 {
252 Nested{map[interface{}]*Nested{"a": nil}, 2},
253 Nested{map[interface{}]*Nested{"a": nil}, 2},
254 true,
255 },
256 {
257 Nested{map[interface{}]*Nested{"a": nil}, 2},
258 Nested{map[interface{}]*Nested{"a": {1, 2}}, 2},
259 false,
260 },
261 {
262 Nested{map[interface{}]Nested{"a": {1, 2}, "b": {3, 4}}, 2},
263 Nested{map[interface{}]Nested{"a": {1, 5}, "b": {3, 7}}, 2},
264 true,
265 },
266 {
267 Nested{map[interface{}]Nested{"a": {1, 2}, "b": {3, 4}}, 2},
268 Nested{map[interface{}]Nested{"a": {2, 2}, "b": {3, 4}}, 2},
269 false,
270 },
271 }
272
273 for _, c := range cases {
274 t.Run(fmt.Sprintf("ObjectsExportedFieldsAreEqual(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
275 res := ObjectsExportedFieldsAreEqual(c.expected, c.actual)
276
277 if res != c.result {
278 t.Errorf("ObjectsExportedFieldsAreEqual(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
279 }
280
281 })
282 }
283 }
284
285 func TestCopyExportedFields(t *testing.T) {
286 intValue := 1
287
288 cases := []struct {
289 input interface{}
290 expected interface{}
291 }{
292 {
293 input: Nested{"a", "b"},
294 expected: Nested{"a", nil},
295 },
296 {
297 input: Nested{&intValue, 2},
298 expected: Nested{&intValue, nil},
299 },
300 {
301 input: Nested{nil, 3},
302 expected: Nested{nil, nil},
303 },
304 {
305 input: S{1, Nested{2, 3}, 4, Nested{5, 6}},
306 expected: S{1, Nested{2, nil}, nil, Nested{}},
307 },
308 {
309 input: S3{},
310 expected: S3{},
311 },
312 {
313 input: S3{&Nested{1, 2}, &Nested{3, 4}},
314 expected: S3{&Nested{1, nil}, &Nested{3, nil}},
315 },
316 {
317 input: S3{Exported1: &Nested{"a", "b"}},
318 expected: S3{Exported1: &Nested{"a", nil}},
319 },
320 {
321 input: S4{[]*Nested{
322 nil,
323 {1, 2},
324 }},
325 expected: S4{[]*Nested{
326 nil,
327 {1, nil},
328 }},
329 },
330 {
331 input: S4{[]*Nested{
332 {1, 2}},
333 },
334 expected: S4{[]*Nested{
335 {1, nil}},
336 },
337 },
338 {
339 input: S4{[]*Nested{
340 {1, 2},
341 {3, 4},
342 }},
343 expected: S4{[]*Nested{
344 {1, nil},
345 {3, nil},
346 }},
347 },
348 {
349 input: S5{Exported: Nested{"a", "b"}},
350 expected: S5{Exported: Nested{"a", nil}},
351 },
352 {
353 input: S6{"a", "b"},
354 expected: S6{"a", ""},
355 },
356 }
357
358 for _, c := range cases {
359 t.Run("", func(t *testing.T) {
360 output := copyExportedFields(c.input)
361 if !ObjectsAreEqualValues(c.expected, output) {
362 t.Errorf("%#v, %#v should be equal", c.expected, output)
363 }
364 })
365 }
366 }
367
368 func TestEqualExportedValues(t *testing.T) {
369 cases := []struct {
370 value1 interface{}
371 value2 interface{}
372 expectedEqual bool
373 expectedFail string
374 }{
375 {
376 value1: S{1, Nested{2, 3}, 4, Nested{5, 6}},
377 value2: S{1, Nested{2, nil}, nil, Nested{}},
378 expectedEqual: true,
379 },
380 {
381 value1: S{1, Nested{2, 3}, 4, Nested{5, 6}},
382 value2: S{1, Nested{1, nil}, nil, Nested{}},
383 expectedEqual: false,
384 expectedFail: `
385 Diff:
386 --- Expected
387 +++ Actual
388 @@ -3,3 +3,3 @@
389 Exported2: (assert.Nested) {
390 - Exported: (int) 2,
391 + Exported: (int) 1,
392 notExported: (interface {}) <nil>`,
393 },
394 {
395 value1: S3{&Nested{1, 2}, &Nested{3, 4}},
396 value2: S3{&Nested{"a", 2}, &Nested{3, 4}},
397 expectedEqual: false,
398 expectedFail: `
399 Diff:
400 --- Expected
401 +++ Actual
402 @@ -2,3 +2,3 @@
403 Exported1: (*assert.Nested)({
404 - Exported: (int) 1,
405 + Exported: (string) (len=1) "a",
406 notExported: (interface {}) <nil>`,
407 },
408 {
409 value1: S4{[]*Nested{
410 {1, 2},
411 {3, 4},
412 }},
413 value2: S4{[]*Nested{
414 {1, "a"},
415 {2, "b"},
416 }},
417 expectedEqual: false,
418 expectedFail: `
419 Diff:
420 --- Expected
421 +++ Actual
422 @@ -7,3 +7,3 @@
423 (*assert.Nested)({
424 - Exported: (int) 3,
425 + Exported: (int) 2,
426 notExported: (interface {}) <nil>`,
427 },
428 {
429 value1: S{[2]int{1, 2}, Nested{2, 3}, 4, Nested{5, 6}},
430 value2: S{[2]int{1, 2}, Nested{2, nil}, nil, Nested{}},
431 expectedEqual: true,
432 },
433 {
434 value1: &S{1, Nested{2, 3}, 4, Nested{5, 6}},
435 value2: &S{1, Nested{2, nil}, nil, Nested{}},
436 expectedEqual: true,
437 },
438 {
439 value1: &S{1, Nested{2, 3}, 4, Nested{5, 6}},
440 value2: &S{1, Nested{1, nil}, nil, Nested{}},
441 expectedEqual: false,
442 expectedFail: `
443 Diff:
444 --- Expected
445 +++ Actual
446 @@ -3,3 +3,3 @@
447 Exported2: (assert.Nested) {
448 - Exported: (int) 2,
449 + Exported: (int) 1,
450 notExported: (interface {}) <nil>`,
451 },
452 }
453
454 for _, c := range cases {
455 t.Run("", func(t *testing.T) {
456 mockT := new(mockTestingT)
457
458 actual := EqualExportedValues(mockT, c.value1, c.value2)
459 if actual != c.expectedEqual {
460 t.Errorf("Expected EqualExportedValues to be %t, but was %t", c.expectedEqual, actual)
461 }
462
463 actualFail := mockT.errorString()
464 if !strings.Contains(actualFail, c.expectedFail) {
465 t.Errorf("Contains failure should include %q but was %q", c.expectedFail, actualFail)
466 }
467 })
468 }
469
470 }
471
472 func TestImplements(t *testing.T) {
473
474 mockT := new(testing.T)
475
476 if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
477 t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface")
478 }
479 if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
480 t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface")
481 }
482 if Implements(mockT, (*AssertionTesterInterface)(nil), nil) {
483 t.Error("Implements method should return false: nil does not implement AssertionTesterInterface")
484 }
485
486 }
487
488 func TestNotImplements(t *testing.T) {
489
490 mockT := new(testing.T)
491
492 if !NotImplements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
493 t.Error("NotImplements method should return true: AssertionTesterNonConformingObject does not implement AssertionTesterInterface")
494 }
495 if NotImplements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
496 t.Error("NotImplements method should return false: AssertionTesterConformingObject implements AssertionTesterInterface")
497 }
498 if NotImplements(mockT, (*AssertionTesterInterface)(nil), nil) {
499 t.Error("NotImplements method should return false: nil can't be checked to be implementing AssertionTesterInterface or not")
500 }
501
502 }
503
504 func TestIsType(t *testing.T) {
505
506 mockT := new(testing.T)
507
508 if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
509 t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject")
510 }
511 if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) {
512 t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject")
513 }
514
515 }
516
517 func TestEqual(t *testing.T) {
518 type myType string
519
520 mockT := new(testing.T)
521 var m map[string]interface{}
522
523 cases := []struct {
524 expected interface{}
525 actual interface{}
526 result bool
527 remark string
528 }{
529 {"Hello World", "Hello World", true, ""},
530 {123, 123, true, ""},
531 {123.5, 123.5, true, ""},
532 {[]byte("Hello World"), []byte("Hello World"), true, ""},
533 {nil, nil, true, ""},
534 {int32(123), int32(123), true, ""},
535 {uint64(123), uint64(123), true, ""},
536 {myType("1"), myType("1"), true, ""},
537 {&struct{}{}, &struct{}{}, true, "pointer equality is based on equality of underlying value"},
538
539
540 {m["bar"], "something", false, ""},
541 {myType("1"), myType("2"), false, ""},
542
543
544 {10, uint(10), false, ""},
545 }
546
547 for _, c := range cases {
548 t.Run(fmt.Sprintf("Equal(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
549 res := Equal(mockT, c.expected, c.actual)
550
551 if res != c.result {
552 t.Errorf("Equal(%#v, %#v) should return %#v: %s", c.expected, c.actual, c.result, c.remark)
553 }
554 })
555 }
556 }
557
558 func ptr(i int) *int {
559 return &i
560 }
561
562 func TestSame(t *testing.T) {
563
564 mockT := new(testing.T)
565
566 if Same(mockT, ptr(1), ptr(1)) {
567 t.Error("Same should return false")
568 }
569 if Same(mockT, 1, 1) {
570 t.Error("Same should return false")
571 }
572 p := ptr(2)
573 if Same(mockT, p, *p) {
574 t.Error("Same should return false")
575 }
576 if !Same(mockT, p, p) {
577 t.Error("Same should return true")
578 }
579 }
580
581 func TestNotSame(t *testing.T) {
582
583 mockT := new(testing.T)
584
585 if !NotSame(mockT, ptr(1), ptr(1)) {
586 t.Error("NotSame should return true; different pointers")
587 }
588 if !NotSame(mockT, 1, 1) {
589 t.Error("NotSame should return true; constant inputs")
590 }
591 p := ptr(2)
592 if !NotSame(mockT, p, *p) {
593 t.Error("NotSame should return true; mixed-type inputs")
594 }
595 if NotSame(mockT, p, p) {
596 t.Error("NotSame should return false")
597 }
598 }
599
600 func Test_samePointers(t *testing.T) {
601 p := ptr(2)
602
603 type args struct {
604 first interface{}
605 second interface{}
606 }
607 tests := []struct {
608 name string
609 args args
610 assertion BoolAssertionFunc
611 }{
612 {
613 name: "1 != 2",
614 args: args{first: 1, second: 2},
615 assertion: False,
616 },
617 {
618 name: "1 != 1 (not same ptr)",
619 args: args{first: 1, second: 1},
620 assertion: False,
621 },
622 {
623 name: "ptr(1) == ptr(1)",
624 args: args{first: p, second: p},
625 assertion: True,
626 },
627 {
628 name: "int(1) != float32(1)",
629 args: args{first: int(1), second: float32(1)},
630 assertion: False,
631 },
632 {
633 name: "array != slice",
634 args: args{first: [2]int{1, 2}, second: []int{1, 2}},
635 assertion: False,
636 },
637 }
638 for _, tt := range tests {
639 t.Run(tt.name, func(t *testing.T) {
640 tt.assertion(t, samePointers(tt.args.first, tt.args.second))
641 })
642 }
643 }
644
645
646
647 type bufferT struct {
648 buf bytes.Buffer
649 }
650
651 func (t *bufferT) Errorf(format string, args ...interface{}) {
652
653 decorate := func(s string) string {
654 _, file, line, ok := runtime.Caller(3)
655 if ok {
656
657 if index := strings.LastIndex(file, "/"); index >= 0 {
658 file = file[index+1:]
659 } else if index = strings.LastIndex(file, "\\"); index >= 0 {
660 file = file[index+1:]
661 }
662 } else {
663 file = "???"
664 line = 1
665 }
666 buf := new(bytes.Buffer)
667
668 buf.WriteByte('\t')
669 fmt.Fprintf(buf, "%s:%d: ", file, line)
670 lines := strings.Split(s, "\n")
671 if l := len(lines); l > 1 && lines[l-1] == "" {
672 lines = lines[:l-1]
673 }
674 for i, line := range lines {
675 if i > 0 {
676
677 buf.WriteString("\n\t\t")
678 }
679 buf.WriteString(line)
680 }
681 buf.WriteByte('\n')
682 return buf.String()
683 }
684 t.buf.WriteString(decorate(fmt.Sprintf(format, args...)))
685 }
686
687 func TestStringEqual(t *testing.T) {
688 for i, currCase := range []struct {
689 equalWant string
690 equalGot string
691 msgAndArgs []interface{}
692 want string
693 }{
694 {equalWant: "hi, \nmy name is", equalGot: "what,\nmy name is", want: "\tassertions.go:\\d+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"hi, \\\\nmy name is\"\n\\s+actual\\s+: \"what,\\\\nmy name is\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1,2 \\+1,2 @@\n\\s+-hi, \n\\s+\\+what,\n\\s+my name is"},
695 } {
696 mockT := &bufferT{}
697 Equal(mockT, currCase.equalWant, currCase.equalGot, currCase.msgAndArgs...)
698 Regexp(t, regexp.MustCompile(currCase.want), mockT.buf.String(), "Case %d", i)
699 }
700 }
701
702 func TestEqualFormatting(t *testing.T) {
703 for i, currCase := range []struct {
704 equalWant string
705 equalGot string
706 msgAndArgs []interface{}
707 want string
708 }{
709 {equalWant: "want", equalGot: "got", want: "\tassertions.go:\\d+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n"},
710 {equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{"hello, %v!", "world"}, want: "\tassertions.go:[0-9]+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n\\s+Messages:\\s+hello, world!\n"},
711 {equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{123}, want: "\tassertions.go:[0-9]+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n\\s+Messages:\\s+123\n"},
712 {equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{struct{ a string }{"hello"}}, want: "\tassertions.go:[0-9]+: \n\t+Error Trace:\t\n\t+Error:\\s+Not equal:\\s+\n\\s+expected: \"want\"\n\\s+actual\\s+: \"got\"\n\\s+Diff:\n\\s+-+ Expected\n\\s+\\++ Actual\n\\s+@@ -1 \\+1 @@\n\\s+-want\n\\s+\\+got\n\\s+Messages:\\s+{a:hello}\n"},
713 } {
714 mockT := &bufferT{}
715 Equal(mockT, currCase.equalWant, currCase.equalGot, currCase.msgAndArgs...)
716 Regexp(t, regexp.MustCompile(currCase.want), mockT.buf.String(), "Case %d", i)
717 }
718 }
719
720 func TestFormatUnequalValues(t *testing.T) {
721 expected, actual := formatUnequalValues("foo", "bar")
722 Equal(t, `"foo"`, expected, "value should not include type")
723 Equal(t, `"bar"`, actual, "value should not include type")
724
725 expected, actual = formatUnequalValues(123, 123)
726 Equal(t, `123`, expected, "value should not include type")
727 Equal(t, `123`, actual, "value should not include type")
728
729 expected, actual = formatUnequalValues(int64(123), int32(123))
730 Equal(t, `int64(123)`, expected, "value should include type")
731 Equal(t, `int32(123)`, actual, "value should include type")
732
733 expected, actual = formatUnequalValues(int64(123), nil)
734 Equal(t, `int64(123)`, expected, "value should include type")
735 Equal(t, `<nil>(<nil>)`, actual, "value should include type")
736
737 type testStructType struct {
738 Val string
739 }
740
741 expected, actual = formatUnequalValues(&testStructType{Val: "test"}, &testStructType{Val: "test"})
742 Equal(t, `&assert.testStructType{Val:"test"}`, expected, "value should not include type annotation")
743 Equal(t, `&assert.testStructType{Val:"test"}`, actual, "value should not include type annotation")
744 }
745
746 func TestNotNil(t *testing.T) {
747
748 mockT := new(testing.T)
749
750 if !NotNil(mockT, new(AssertionTesterConformingObject)) {
751 t.Error("NotNil should return true: object is not nil")
752 }
753 if NotNil(mockT, nil) {
754 t.Error("NotNil should return false: object is nil")
755 }
756 if NotNil(mockT, (*struct{})(nil)) {
757 t.Error("NotNil should return false: object is (*struct{})(nil)")
758 }
759
760 }
761
762 func TestNil(t *testing.T) {
763
764 mockT := new(testing.T)
765
766 if !Nil(mockT, nil) {
767 t.Error("Nil should return true: object is nil")
768 }
769 if !Nil(mockT, (*struct{})(nil)) {
770 t.Error("Nil should return true: object is (*struct{})(nil)")
771 }
772 if Nil(mockT, new(AssertionTesterConformingObject)) {
773 t.Error("Nil should return false: object is not nil")
774 }
775
776 }
777
778 func TestTrue(t *testing.T) {
779
780 mockT := new(testing.T)
781
782 if !True(mockT, true) {
783 t.Error("True should return true")
784 }
785 if True(mockT, false) {
786 t.Error("True should return false")
787 }
788
789 }
790
791 func TestFalse(t *testing.T) {
792
793 mockT := new(testing.T)
794
795 if !False(mockT, false) {
796 t.Error("False should return true")
797 }
798 if False(mockT, true) {
799 t.Error("False should return false")
800 }
801
802 }
803
804 func TestExactly(t *testing.T) {
805
806 mockT := new(testing.T)
807
808 a := float32(1)
809 b := float64(1)
810 c := float32(1)
811 d := float32(2)
812 cases := []struct {
813 expected interface{}
814 actual interface{}
815 result bool
816 }{
817 {a, b, false},
818 {a, d, false},
819 {a, c, true},
820 {nil, a, false},
821 {a, nil, false},
822 }
823
824 for _, c := range cases {
825 t.Run(fmt.Sprintf("Exactly(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
826 res := Exactly(mockT, c.expected, c.actual)
827
828 if res != c.result {
829 t.Errorf("Exactly(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
830 }
831 })
832 }
833 }
834
835 func TestNotEqual(t *testing.T) {
836
837 mockT := new(testing.T)
838
839 cases := []struct {
840 expected interface{}
841 actual interface{}
842 result bool
843 }{
844
845 {"Hello World", "Hello World!", true},
846 {123, 1234, true},
847 {123.5, 123.55, true},
848 {[]byte("Hello World"), []byte("Hello World!"), true},
849 {nil, new(AssertionTesterConformingObject), true},
850
851
852 {nil, nil, false},
853 {"Hello World", "Hello World", false},
854 {123, 123, false},
855 {123.5, 123.5, false},
856 {[]byte("Hello World"), []byte("Hello World"), false},
857 {new(AssertionTesterConformingObject), new(AssertionTesterConformingObject), false},
858 {&struct{}{}, &struct{}{}, false},
859 {func() int { return 23 }, func() int { return 24 }, false},
860
861 {int(10), uint(10), true},
862 }
863
864 for _, c := range cases {
865 t.Run(fmt.Sprintf("NotEqual(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
866 res := NotEqual(mockT, c.expected, c.actual)
867
868 if res != c.result {
869 t.Errorf("NotEqual(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
870 }
871 })
872 }
873 }
874
875 func TestNotEqualValues(t *testing.T) {
876 mockT := new(testing.T)
877
878 cases := []struct {
879 expected interface{}
880 actual interface{}
881 result bool
882 }{
883
884 {"Hello World", "Hello World!", true},
885 {123, 1234, true},
886 {123.5, 123.55, true},
887 {[]byte("Hello World"), []byte("Hello World!"), true},
888 {nil, new(AssertionTesterConformingObject), true},
889
890
891 {nil, nil, false},
892 {"Hello World", "Hello World", false},
893 {123, 123, false},
894 {123.5, 123.5, false},
895 {[]byte("Hello World"), []byte("Hello World"), false},
896 {new(AssertionTesterConformingObject), new(AssertionTesterConformingObject), false},
897 {&struct{}{}, &struct{}{}, false},
898
899
900 {func() int { return 23 }, func() int { return 24 }, true},
901 {int(10), int(11), true},
902 {int(10), uint(10), false},
903
904 {struct{}{}, struct{}{}, false},
905 }
906
907 for _, c := range cases {
908 t.Run(fmt.Sprintf("NotEqualValues(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
909 res := NotEqualValues(mockT, c.expected, c.actual)
910
911 if res != c.result {
912 t.Errorf("NotEqualValues(%#v, %#v) should return %#v", c.expected, c.actual, c.result)
913 }
914 })
915 }
916 }
917
918 func TestContainsNotContains(t *testing.T) {
919
920 type A struct {
921 Name, Value string
922 }
923 list := []string{"Foo", "Bar"}
924
925 complexList := []*A{
926 {"b", "c"},
927 {"d", "e"},
928 {"g", "h"},
929 {"j", "k"},
930 }
931 simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
932 var zeroMap map[interface{}]interface{}
933
934 cases := []struct {
935 expected interface{}
936 actual interface{}
937 result bool
938 }{
939 {"Hello World", "Hello", true},
940 {"Hello World", "Salut", false},
941 {list, "Bar", true},
942 {list, "Salut", false},
943 {complexList, &A{"g", "h"}, true},
944 {complexList, &A{"g", "e"}, false},
945 {simpleMap, "Foo", true},
946 {simpleMap, "Bar", false},
947 {zeroMap, "Bar", false},
948 }
949
950 for _, c := range cases {
951 t.Run(fmt.Sprintf("Contains(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
952 mockT := new(testing.T)
953 res := Contains(mockT, c.expected, c.actual)
954
955 if res != c.result {
956 if res {
957 t.Errorf("Contains(%#v, %#v) should return true:\n\t%#v contains %#v", c.expected, c.actual, c.expected, c.actual)
958 } else {
959 t.Errorf("Contains(%#v, %#v) should return false:\n\t%#v does not contain %#v", c.expected, c.actual, c.expected, c.actual)
960 }
961 }
962 })
963 }
964
965 for _, c := range cases {
966 t.Run(fmt.Sprintf("NotContains(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
967 mockT := new(testing.T)
968 res := NotContains(mockT, c.expected, c.actual)
969
970
971 if res == Contains(mockT, c.expected, c.actual) {
972 if res {
973 t.Errorf("NotContains(%#v, %#v) should return true:\n\t%#v does not contains %#v", c.expected, c.actual, c.expected, c.actual)
974 } else {
975 t.Errorf("NotContains(%#v, %#v) should return false:\n\t%#v contains %#v", c.expected, c.actual, c.expected, c.actual)
976 }
977 }
978 })
979 }
980 }
981
982 func TestContainsNotContainsFailMessage(t *testing.T) {
983 mockT := new(mockTestingT)
984
985 type nonContainer struct {
986 Value string
987 }
988
989 cases := []struct {
990 assertion func(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
991 container interface{}
992 instance interface{}
993 expected string
994 }{
995 {
996 assertion: Contains,
997 container: "Hello World",
998 instance: errors.New("Hello"),
999 expected: "\"Hello World\" does not contain &errors.errorString{s:\"Hello\"}",
1000 },
1001 {
1002 assertion: Contains,
1003 container: map[string]int{"one": 1},
1004 instance: "two",
1005 expected: "map[string]int{\"one\":1} does not contain \"two\"\n",
1006 },
1007 {
1008 assertion: NotContains,
1009 container: map[string]int{"one": 1},
1010 instance: "one",
1011 expected: "map[string]int{\"one\":1} should not contain \"one\"",
1012 },
1013 {
1014 assertion: Contains,
1015 container: nonContainer{Value: "Hello"},
1016 instance: "Hello",
1017 expected: "assert.nonContainer{Value:\"Hello\"} could not be applied builtin len()\n",
1018 },
1019 {
1020 assertion: NotContains,
1021 container: nonContainer{Value: "Hello"},
1022 instance: "Hello",
1023 expected: "assert.nonContainer{Value:\"Hello\"} could not be applied builtin len()\n",
1024 },
1025 }
1026 for _, c := range cases {
1027 name := filepath.Base(runtime.FuncForPC(reflect.ValueOf(c.assertion).Pointer()).Name())
1028 t.Run(fmt.Sprintf("%v(%T, %T)", name, c.container, c.instance), func(t *testing.T) {
1029 c.assertion(mockT, c.container, c.instance)
1030 actualFail := mockT.errorString()
1031 if !strings.Contains(actualFail, c.expected) {
1032 t.Errorf("Contains failure should include %q but was %q", c.expected, actualFail)
1033 }
1034 })
1035 }
1036 }
1037
1038 func TestContainsNotContainsOnNilValue(t *testing.T) {
1039 mockT := new(mockTestingT)
1040
1041 Contains(mockT, nil, "key")
1042 expectedFail := "<nil> could not be applied builtin len()"
1043 actualFail := mockT.errorString()
1044 if !strings.Contains(actualFail, expectedFail) {
1045 t.Errorf("Contains failure should include %q but was %q", expectedFail, actualFail)
1046 }
1047
1048 NotContains(mockT, nil, "key")
1049 if !strings.Contains(actualFail, expectedFail) {
1050 t.Errorf("Contains failure should include %q but was %q", expectedFail, actualFail)
1051 }
1052 }
1053
1054 func TestSubsetNotSubset(t *testing.T) {
1055 cases := []struct {
1056 list interface{}
1057 subset interface{}
1058 result bool
1059 message string
1060 }{
1061
1062 {[]int{1, 2, 3}, nil, true, `nil is the empty set which is a subset of every set`},
1063 {[]int{1, 2, 3}, []int{}, true, `[] is a subset of ['\x01' '\x02' '\x03']`},
1064 {[]int{1, 2, 3}, []int{1, 2}, true, `['\x01' '\x02'] is a subset of ['\x01' '\x02' '\x03']`},
1065 {[]int{1, 2, 3}, []int{1, 2, 3}, true, `['\x01' '\x02' '\x03'] is a subset of ['\x01' '\x02' '\x03']`},
1066 {[]string{"hello", "world"}, []string{"hello"}, true, `["hello"] is a subset of ["hello" "world"]`},
1067 {map[string]string{
1068 "a": "x",
1069 "c": "z",
1070 "b": "y",
1071 }, map[string]string{
1072 "a": "x",
1073 "b": "y",
1074 }, true, `map["a":"x" "b":"y"] is a subset of map["a":"x" "b":"y" "c":"z"]`},
1075
1076
1077 {[]string{"hello", "world"}, []string{"hello", "testify"}, false, `[]string{"hello", "world"} does not contain "testify"`},
1078 {[]int{1, 2, 3}, []int{4, 5}, false, `[]int{1, 2, 3} does not contain 4`},
1079 {[]int{1, 2, 3}, []int{1, 5}, false, `[]int{1, 2, 3} does not contain 5`},
1080 {map[string]string{
1081 "a": "x",
1082 "c": "z",
1083 "b": "y",
1084 }, map[string]string{
1085 "a": "x",
1086 "b": "z",
1087 }, false, `map[string]string{"a":"x", "b":"y", "c":"z"} does not contain map[string]string{"a":"x", "b":"z"}`},
1088 {map[string]string{
1089 "a": "x",
1090 "b": "y",
1091 }, map[string]string{
1092 "a": "x",
1093 "b": "y",
1094 "c": "z",
1095 }, false, `map[string]string{"a":"x", "b":"y"} does not contain map[string]string{"a":"x", "b":"y", "c":"z"}`},
1096 }
1097
1098 for _, c := range cases {
1099 t.Run("SubSet: "+c.message, func(t *testing.T) {
1100
1101 mockT := new(mockTestingT)
1102 res := Subset(mockT, c.list, c.subset)
1103
1104 if res != c.result {
1105 t.Errorf("Subset should return %t: %s", c.result, c.message)
1106 }
1107 if !c.result {
1108 expectedFail := c.message
1109 actualFail := mockT.errorString()
1110 if !strings.Contains(actualFail, expectedFail) {
1111 t.Log(actualFail)
1112 t.Errorf("Subset failure should contain %q but was %q", expectedFail, actualFail)
1113 }
1114 }
1115 })
1116 }
1117 for _, c := range cases {
1118 t.Run("NotSubSet: "+c.message, func(t *testing.T) {
1119 mockT := new(mockTestingT)
1120 res := NotSubset(mockT, c.list, c.subset)
1121
1122
1123 if res == Subset(mockT, c.list, c.subset) {
1124 t.Errorf("NotSubset should return %t: %s", !c.result, c.message)
1125 }
1126 if c.result {
1127 expectedFail := c.message
1128 actualFail := mockT.errorString()
1129 if !strings.Contains(actualFail, expectedFail) {
1130 t.Log(actualFail)
1131 t.Errorf("NotSubset failure should contain %q but was %q", expectedFail, actualFail)
1132 }
1133 }
1134 })
1135 }
1136 }
1137
1138 func TestNotSubsetNil(t *testing.T) {
1139 mockT := new(testing.T)
1140 NotSubset(mockT, []string{"foo"}, nil)
1141 if !mockT.Failed() {
1142 t.Error("NotSubset on nil set should have failed the test")
1143 }
1144 }
1145
1146 func Test_containsElement(t *testing.T) {
1147
1148 list1 := []string{"Foo", "Bar"}
1149 list2 := []int{1, 2}
1150 simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
1151
1152 ok, found := containsElement("Hello World", "World")
1153 True(t, ok)
1154 True(t, found)
1155
1156 ok, found = containsElement(list1, "Foo")
1157 True(t, ok)
1158 True(t, found)
1159
1160 ok, found = containsElement(list1, "Bar")
1161 True(t, ok)
1162 True(t, found)
1163
1164 ok, found = containsElement(list2, 1)
1165 True(t, ok)
1166 True(t, found)
1167
1168 ok, found = containsElement(list2, 2)
1169 True(t, ok)
1170 True(t, found)
1171
1172 ok, found = containsElement(list1, "Foo!")
1173 True(t, ok)
1174 False(t, found)
1175
1176 ok, found = containsElement(list2, 3)
1177 True(t, ok)
1178 False(t, found)
1179
1180 ok, found = containsElement(list2, "1")
1181 True(t, ok)
1182 False(t, found)
1183
1184 ok, found = containsElement(simpleMap, "Foo")
1185 True(t, ok)
1186 True(t, found)
1187
1188 ok, found = containsElement(simpleMap, "Bar")
1189 True(t, ok)
1190 False(t, found)
1191
1192 ok, found = containsElement(1433, "1")
1193 False(t, ok)
1194 False(t, found)
1195 }
1196
1197 func TestElementsMatch(t *testing.T) {
1198 mockT := new(testing.T)
1199
1200 cases := []struct {
1201 expected interface{}
1202 actual interface{}
1203 result bool
1204 }{
1205
1206 {nil, nil, true},
1207
1208 {nil, nil, true},
1209 {[]int{}, []int{}, true},
1210 {[]int{1}, []int{1}, true},
1211 {[]int{1, 1}, []int{1, 1}, true},
1212 {[]int{1, 2}, []int{1, 2}, true},
1213 {[]int{1, 2}, []int{2, 1}, true},
1214 {[2]int{1, 2}, [2]int{2, 1}, true},
1215 {[]string{"hello", "world"}, []string{"world", "hello"}, true},
1216 {[]string{"hello", "hello"}, []string{"hello", "hello"}, true},
1217 {[]string{"hello", "hello", "world"}, []string{"hello", "world", "hello"}, true},
1218 {[3]string{"hello", "hello", "world"}, [3]string{"hello", "world", "hello"}, true},
1219 {[]int{}, nil, true},
1220
1221
1222 {[]int{1}, []int{1, 1}, false},
1223 {[]int{1, 2}, []int{2, 2}, false},
1224 {[]string{"hello", "hello"}, []string{"hello"}, false},
1225 }
1226
1227 for _, c := range cases {
1228 t.Run(fmt.Sprintf("ElementsMatch(%#v, %#v)", c.expected, c.actual), func(t *testing.T) {
1229 res := ElementsMatch(mockT, c.actual, c.expected)
1230
1231 if res != c.result {
1232 t.Errorf("ElementsMatch(%#v, %#v) should return %v", c.actual, c.expected, c.result)
1233 }
1234 })
1235 }
1236 }
1237
1238 func TestDiffLists(t *testing.T) {
1239 tests := []struct {
1240 name string
1241 listA interface{}
1242 listB interface{}
1243 extraA []interface{}
1244 extraB []interface{}
1245 }{
1246 {
1247 name: "equal empty",
1248 listA: []string{},
1249 listB: []string{},
1250 extraA: nil,
1251 extraB: nil,
1252 },
1253 {
1254 name: "equal same order",
1255 listA: []string{"hello", "world"},
1256 listB: []string{"hello", "world"},
1257 extraA: nil,
1258 extraB: nil,
1259 },
1260 {
1261 name: "equal different order",
1262 listA: []string{"hello", "world"},
1263 listB: []string{"world", "hello"},
1264 extraA: nil,
1265 extraB: nil,
1266 },
1267 {
1268 name: "extra A",
1269 listA: []string{"hello", "hello", "world"},
1270 listB: []string{"hello", "world"},
1271 extraA: []interface{}{"hello"},
1272 extraB: nil,
1273 },
1274 {
1275 name: "extra A twice",
1276 listA: []string{"hello", "hello", "hello", "world"},
1277 listB: []string{"hello", "world"},
1278 extraA: []interface{}{"hello", "hello"},
1279 extraB: nil,
1280 },
1281 {
1282 name: "extra B",
1283 listA: []string{"hello", "world"},
1284 listB: []string{"hello", "hello", "world"},
1285 extraA: nil,
1286 extraB: []interface{}{"hello"},
1287 },
1288 {
1289 name: "extra B twice",
1290 listA: []string{"hello", "world"},
1291 listB: []string{"hello", "hello", "world", "hello"},
1292 extraA: nil,
1293 extraB: []interface{}{"hello", "hello"},
1294 },
1295 {
1296 name: "integers 1",
1297 listA: []int{1, 2, 3, 4, 5},
1298 listB: []int{5, 4, 3, 2, 1},
1299 extraA: nil,
1300 extraB: nil,
1301 },
1302 {
1303 name: "integers 2",
1304 listA: []int{1, 2, 1, 2, 1},
1305 listB: []int{2, 1, 2, 1, 2},
1306 extraA: []interface{}{1},
1307 extraB: []interface{}{2},
1308 },
1309 }
1310 for _, test := range tests {
1311 test := test
1312 t.Run(test.name, func(t *testing.T) {
1313 actualExtraA, actualExtraB := diffLists(test.listA, test.listB)
1314 Equal(t, test.extraA, actualExtraA, "extra A does not match for listA=%v listB=%v",
1315 test.listA, test.listB)
1316 Equal(t, test.extraB, actualExtraB, "extra B does not match for listA=%v listB=%v",
1317 test.listA, test.listB)
1318 })
1319 }
1320 }
1321
1322 func TestCondition(t *testing.T) {
1323 mockT := new(testing.T)
1324
1325 if !Condition(mockT, func() bool { return true }, "Truth") {
1326 t.Error("Condition should return true")
1327 }
1328
1329 if Condition(mockT, func() bool { return false }, "Lie") {
1330 t.Error("Condition should return false")
1331 }
1332
1333 }
1334
1335 func TestDidPanic(t *testing.T) {
1336
1337 const panicMsg = "Panic!"
1338
1339 if funcDidPanic, msg, _ := didPanic(func() {
1340 panic(panicMsg)
1341 }); !funcDidPanic || msg != panicMsg {
1342 t.Error("didPanic should return true, panicMsg")
1343 }
1344
1345 if funcDidPanic, msg, _ := didPanic(func() {
1346 panic(nil)
1347 }); !funcDidPanic || msg != nil {
1348 t.Error("didPanic should return true, nil")
1349 }
1350
1351 if funcDidPanic, _, _ := didPanic(func() {
1352 }); funcDidPanic {
1353 t.Error("didPanic should return false")
1354 }
1355
1356 }
1357
1358 func TestPanics(t *testing.T) {
1359
1360 mockT := new(testing.T)
1361
1362 if !Panics(mockT, func() {
1363 panic("Panic!")
1364 }) {
1365 t.Error("Panics should return true")
1366 }
1367
1368 if Panics(mockT, func() {
1369 }) {
1370 t.Error("Panics should return false")
1371 }
1372
1373 }
1374
1375 func TestPanicsWithValue(t *testing.T) {
1376
1377 mockT := new(testing.T)
1378
1379 if !PanicsWithValue(mockT, "Panic!", func() {
1380 panic("Panic!")
1381 }) {
1382 t.Error("PanicsWithValue should return true")
1383 }
1384
1385 if !PanicsWithValue(mockT, nil, func() {
1386 panic(nil)
1387 }) {
1388 t.Error("PanicsWithValue should return true")
1389 }
1390
1391 if PanicsWithValue(mockT, "Panic!", func() {
1392 }) {
1393 t.Error("PanicsWithValue should return false")
1394 }
1395
1396 if PanicsWithValue(mockT, "at the disco", func() {
1397 panic("Panic!")
1398 }) {
1399 t.Error("PanicsWithValue should return false")
1400 }
1401 }
1402
1403 func TestPanicsWithError(t *testing.T) {
1404
1405 mockT := new(testing.T)
1406
1407 if !PanicsWithError(mockT, "panic", func() {
1408 panic(errors.New("panic"))
1409 }) {
1410 t.Error("PanicsWithError should return true")
1411 }
1412
1413 if PanicsWithError(mockT, "Panic!", func() {
1414 }) {
1415 t.Error("PanicsWithError should return false")
1416 }
1417
1418 if PanicsWithError(mockT, "at the disco", func() {
1419 panic(errors.New("panic"))
1420 }) {
1421 t.Error("PanicsWithError should return false")
1422 }
1423
1424 if PanicsWithError(mockT, "Panic!", func() {
1425 panic("panic")
1426 }) {
1427 t.Error("PanicsWithError should return false")
1428 }
1429 }
1430
1431 func TestNotPanics(t *testing.T) {
1432
1433 mockT := new(testing.T)
1434
1435 if !NotPanics(mockT, func() {
1436 }) {
1437 t.Error("NotPanics should return true")
1438 }
1439
1440 if NotPanics(mockT, func() {
1441 panic("Panic!")
1442 }) {
1443 t.Error("NotPanics should return false")
1444 }
1445
1446 }
1447
1448 func TestNoError(t *testing.T) {
1449
1450 mockT := new(testing.T)
1451
1452
1453 var err error
1454
1455 True(t, NoError(mockT, err), "NoError should return True for nil arg")
1456
1457
1458 err = errors.New("some error")
1459
1460 False(t, NoError(mockT, err), "NoError with error should return False")
1461
1462
1463 err = func() error {
1464 var err *customError
1465 return err
1466 }()
1467
1468 if err == nil {
1469 t.Errorf("Error should be nil due to empty interface: %s", err)
1470 }
1471
1472 False(t, NoError(mockT, err), "NoError should fail with empty error interface")
1473 }
1474
1475 type customError struct{}
1476
1477 func (*customError) Error() string { return "fail" }
1478
1479 func TestError(t *testing.T) {
1480
1481 mockT := new(testing.T)
1482
1483
1484 var err error
1485
1486 False(t, Error(mockT, err), "Error should return False for nil arg")
1487
1488
1489 err = errors.New("some error")
1490
1491 True(t, Error(mockT, err), "Error with error should return True")
1492
1493
1494 True(t, Errorf(mockT, err, "example with %s", "formatted message"), "Errorf with error should return True")
1495
1496
1497 err = func() error {
1498 var err *customError
1499 return err
1500 }()
1501
1502 if err == nil {
1503 t.Errorf("Error should be nil due to empty interface: %s", err)
1504 }
1505
1506 True(t, Error(mockT, err), "Error should pass with empty error interface")
1507 }
1508
1509 func TestEqualError(t *testing.T) {
1510 mockT := new(testing.T)
1511
1512
1513 var err error
1514 False(t, EqualError(mockT, err, ""),
1515 "EqualError should return false for nil arg")
1516
1517
1518 err = errors.New("some error")
1519 False(t, EqualError(mockT, err, "Not some error"),
1520 "EqualError should return false for different error string")
1521 True(t, EqualError(mockT, err, "some error"),
1522 "EqualError should return true")
1523 }
1524
1525 func TestErrorContains(t *testing.T) {
1526 mockT := new(testing.T)
1527
1528
1529 var err error
1530 False(t, ErrorContains(mockT, err, ""),
1531 "ErrorContains should return false for nil arg")
1532
1533
1534 err = errors.New("some error: another error")
1535 False(t, ErrorContains(mockT, err, "bad error"),
1536 "ErrorContains should return false for different error string")
1537 True(t, ErrorContains(mockT, err, "some error"),
1538 "ErrorContains should return true")
1539 True(t, ErrorContains(mockT, err, "another error"),
1540 "ErrorContains should return true")
1541 }
1542
1543 func Test_isEmpty(t *testing.T) {
1544
1545 chWithValue := make(chan struct{}, 1)
1546 chWithValue <- struct{}{}
1547
1548 True(t, isEmpty(""))
1549 True(t, isEmpty(nil))
1550 True(t, isEmpty([]string{}))
1551 True(t, isEmpty(0))
1552 True(t, isEmpty(int32(0)))
1553 True(t, isEmpty(int64(0)))
1554 True(t, isEmpty(false))
1555 True(t, isEmpty(map[string]string{}))
1556 True(t, isEmpty(new(time.Time)))
1557 True(t, isEmpty(time.Time{}))
1558 True(t, isEmpty(make(chan struct{})))
1559 True(t, isEmpty([1]int{}))
1560 False(t, isEmpty("something"))
1561 False(t, isEmpty(errors.New("something")))
1562 False(t, isEmpty([]string{"something"}))
1563 False(t, isEmpty(1))
1564 False(t, isEmpty(true))
1565 False(t, isEmpty(map[string]string{"Hello": "World"}))
1566 False(t, isEmpty(chWithValue))
1567 False(t, isEmpty([1]int{42}))
1568 }
1569
1570 func TestEmpty(t *testing.T) {
1571
1572 mockT := new(testing.T)
1573 chWithValue := make(chan struct{}, 1)
1574 chWithValue <- struct{}{}
1575 var tiP *time.Time
1576 var tiNP time.Time
1577 var s *string
1578 var f *os.File
1579 sP := &s
1580 x := 1
1581 xP := &x
1582
1583 type TString string
1584 type TStruct struct {
1585 x int
1586 }
1587
1588 True(t, Empty(mockT, ""), "Empty string is empty")
1589 True(t, Empty(mockT, nil), "Nil is empty")
1590 True(t, Empty(mockT, []string{}), "Empty string array is empty")
1591 True(t, Empty(mockT, 0), "Zero int value is empty")
1592 True(t, Empty(mockT, false), "False value is empty")
1593 True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty")
1594 True(t, Empty(mockT, s), "Nil string pointer is empty")
1595 True(t, Empty(mockT, f), "Nil os.File pointer is empty")
1596 True(t, Empty(mockT, tiP), "Nil time.Time pointer is empty")
1597 True(t, Empty(mockT, tiNP), "time.Time is empty")
1598 True(t, Empty(mockT, TStruct{}), "struct with zero values is empty")
1599 True(t, Empty(mockT, TString("")), "empty aliased string is empty")
1600 True(t, Empty(mockT, sP), "ptr to nil value is empty")
1601 True(t, Empty(mockT, [1]int{}), "array is state")
1602
1603 False(t, Empty(mockT, "something"), "Non Empty string is not empty")
1604 False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty")
1605 False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty")
1606 False(t, Empty(mockT, 1), "Non-zero int value is not empty")
1607 False(t, Empty(mockT, true), "True value is not empty")
1608 False(t, Empty(mockT, chWithValue), "Channel with values is not empty")
1609 False(t, Empty(mockT, TStruct{x: 1}), "struct with initialized values is empty")
1610 False(t, Empty(mockT, TString("abc")), "non-empty aliased string is empty")
1611 False(t, Empty(mockT, xP), "ptr to non-nil value is not empty")
1612 False(t, Empty(mockT, [1]int{42}), "array is not state")
1613 }
1614
1615 func TestNotEmpty(t *testing.T) {
1616
1617 mockT := new(testing.T)
1618 chWithValue := make(chan struct{}, 1)
1619 chWithValue <- struct{}{}
1620
1621 False(t, NotEmpty(mockT, ""), "Empty string is empty")
1622 False(t, NotEmpty(mockT, nil), "Nil is empty")
1623 False(t, NotEmpty(mockT, []string{}), "Empty string array is empty")
1624 False(t, NotEmpty(mockT, 0), "Zero int value is empty")
1625 False(t, NotEmpty(mockT, false), "False value is empty")
1626 False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty")
1627 False(t, NotEmpty(mockT, [1]int{}), "array is state")
1628
1629 True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty")
1630 True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty")
1631 True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty")
1632 True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty")
1633 True(t, NotEmpty(mockT, true), "True value is not empty")
1634 True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty")
1635 True(t, NotEmpty(mockT, [1]int{42}), "array is not state")
1636 }
1637
1638 func Test_getLen(t *testing.T) {
1639 falseCases := []interface{}{
1640 nil,
1641 0,
1642 true,
1643 false,
1644 'A',
1645 struct{}{},
1646 }
1647 for _, v := range falseCases {
1648 l, ok := getLen(v)
1649 False(t, ok, "Expected getLen fail to get length of %#v", v)
1650 Equal(t, 0, l, "getLen should return 0 for %#v", v)
1651 }
1652
1653 ch := make(chan int, 5)
1654 ch <- 1
1655 ch <- 2
1656 ch <- 3
1657 trueCases := []struct {
1658 v interface{}
1659 l int
1660 }{
1661 {[]int{1, 2, 3}, 3},
1662 {[...]int{1, 2, 3}, 3},
1663 {"ABC", 3},
1664 {map[int]int{1: 2, 2: 4, 3: 6}, 3},
1665 {ch, 3},
1666
1667 {[]int{}, 0},
1668 {map[int]int{}, 0},
1669 {make(chan int), 0},
1670
1671 {[]int(nil), 0},
1672 {map[int]int(nil), 0},
1673 {(chan int)(nil), 0},
1674 }
1675
1676 for _, c := range trueCases {
1677 l, ok := getLen(c.v)
1678 True(t, ok, "Expected getLen success to get length of %#v", c.v)
1679 Equal(t, c.l, l)
1680 }
1681 }
1682
1683 func TestLen(t *testing.T) {
1684 mockT := new(testing.T)
1685
1686 False(t, Len(mockT, nil, 0), "nil does not have length")
1687 False(t, Len(mockT, 0, 0), "int does not have length")
1688 False(t, Len(mockT, true, 0), "true does not have length")
1689 False(t, Len(mockT, false, 0), "false does not have length")
1690 False(t, Len(mockT, 'A', 0), "Rune does not have length")
1691 False(t, Len(mockT, struct{}{}, 0), "Struct does not have length")
1692
1693 ch := make(chan int, 5)
1694 ch <- 1
1695 ch <- 2
1696 ch <- 3
1697
1698 cases := []struct {
1699 v interface{}
1700 l int
1701 expected1234567 string
1702 }{
1703 {[]int{1, 2, 3}, 3, `"[1 2 3]" should have 1234567 item(s), but has 3`},
1704 {[...]int{1, 2, 3}, 3, `"[1 2 3]" should have 1234567 item(s), but has 3`},
1705 {"ABC", 3, `"ABC" should have 1234567 item(s), but has 3`},
1706 {map[int]int{1: 2, 2: 4, 3: 6}, 3, `"map[1:2 2:4 3:6]" should have 1234567 item(s), but has 3`},
1707 {ch, 3, ""},
1708
1709 {[]int{}, 0, `"[]" should have 1234567 item(s), but has 0`},
1710 {map[int]int{}, 0, `"map[]" should have 1234567 item(s), but has 0`},
1711 {make(chan int), 0, ""},
1712
1713 {[]int(nil), 0, `"[]" should have 1234567 item(s), but has 0`},
1714 {map[int]int(nil), 0, `"map[]" should have 1234567 item(s), but has 0`},
1715 {(chan int)(nil), 0, `"<nil>" should have 1234567 item(s), but has 0`},
1716 }
1717
1718 for _, c := range cases {
1719 True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
1720 False(t, Len(mockT, c.v, c.l+1), "%#v have %d items", c.v, c.l)
1721 if c.expected1234567 != "" {
1722 msgMock := new(mockTestingT)
1723 Len(msgMock, c.v, 1234567)
1724 Contains(t, msgMock.errorString(), c.expected1234567)
1725 }
1726 }
1727 }
1728
1729 func TestWithinDuration(t *testing.T) {
1730
1731 mockT := new(testing.T)
1732 a := time.Now()
1733 b := a.Add(10 * time.Second)
1734
1735 True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference")
1736 True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference")
1737
1738 False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference")
1739 False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference")
1740
1741 False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference")
1742 False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference")
1743
1744 False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference")
1745 False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference")
1746 }
1747
1748 func TestWithinRange(t *testing.T) {
1749
1750 mockT := new(testing.T)
1751 n := time.Now()
1752 s := n.Add(-time.Second)
1753 e := n.Add(time.Second)
1754
1755 True(t, WithinRange(mockT, n, n, n), "Exact same actual, start, and end values return true")
1756
1757 True(t, WithinRange(mockT, n, s, e), "Time in range is within the time range")
1758 True(t, WithinRange(mockT, s, s, e), "The start time is within the time range")
1759 True(t, WithinRange(mockT, e, s, e), "The end time is within the time range")
1760
1761 False(t, WithinRange(mockT, s.Add(-time.Nanosecond), s, e, "Just before the start time is not within the time range"))
1762 False(t, WithinRange(mockT, e.Add(time.Nanosecond), s, e, "Just after the end time is not within the time range"))
1763
1764 False(t, WithinRange(mockT, n, e, s, "Just after the end time is not within the time range"))
1765 }
1766
1767 func TestInDelta(t *testing.T) {
1768 mockT := new(testing.T)
1769
1770 True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01")
1771 True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01")
1772 True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1")
1773 False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail")
1774 False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail")
1775 False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail")
1776 False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail")
1777 False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail")
1778 True(t, InDelta(mockT, math.NaN(), math.NaN(), 0.01), "Expected NaN for both to pass")
1779
1780 cases := []struct {
1781 a, b interface{}
1782 delta float64
1783 }{
1784 {uint(2), uint(1), 1},
1785 {uint8(2), uint8(1), 1},
1786 {uint16(2), uint16(1), 1},
1787 {uint32(2), uint32(1), 1},
1788 {uint64(2), uint64(1), 1},
1789
1790 {int(2), int(1), 1},
1791 {int8(2), int8(1), 1},
1792 {int16(2), int16(1), 1},
1793 {int32(2), int32(1), 1},
1794 {int64(2), int64(1), 1},
1795
1796 {float32(2), float32(1), 1},
1797 {float64(2), float64(1), 1},
1798 }
1799
1800 for _, tc := range cases {
1801 True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta)
1802 }
1803 }
1804
1805 func TestInDeltaSlice(t *testing.T) {
1806 mockT := new(testing.T)
1807
1808 True(t, InDeltaSlice(mockT,
1809 []float64{1.001, math.NaN(), 0.999},
1810 []float64{1, math.NaN(), 1},
1811 0.1), "{1.001, NaN, 0.009} is element-wise close to {1, NaN, 1} in delta=0.1")
1812
1813 True(t, InDeltaSlice(mockT,
1814 []float64{1, math.NaN(), 2},
1815 []float64{0, math.NaN(), 3},
1816 1), "{1, NaN, 2} is element-wise close to {0, NaN, 3} in delta=1")
1817
1818 False(t, InDeltaSlice(mockT,
1819 []float64{1, math.NaN(), 2},
1820 []float64{0, math.NaN(), 3},
1821 0.1), "{1, NaN, 2} is not element-wise close to {0, NaN, 3} in delta=0.1")
1822
1823 False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
1824 }
1825
1826 func TestInDeltaMapValues(t *testing.T) {
1827 mockT := new(testing.T)
1828
1829 for _, tc := range []struct {
1830 title string
1831 expect interface{}
1832 actual interface{}
1833 f func(TestingT, bool, ...interface{}) bool
1834 delta float64
1835 }{
1836 {
1837 title: "Within delta",
1838 expect: map[string]float64{
1839 "foo": 1.0,
1840 "bar": 2.0,
1841 "baz": math.NaN(),
1842 },
1843 actual: map[string]float64{
1844 "foo": 1.01,
1845 "bar": 1.99,
1846 "baz": math.NaN(),
1847 },
1848 delta: 0.1,
1849 f: True,
1850 },
1851 {
1852 title: "Within delta",
1853 expect: map[int]float64{
1854 1: 1.0,
1855 2: 2.0,
1856 },
1857 actual: map[int]float64{
1858 1: 1.0,
1859 2: 1.99,
1860 },
1861 delta: 0.1,
1862 f: True,
1863 },
1864 {
1865 title: "Different number of keys",
1866 expect: map[int]float64{
1867 1: 1.0,
1868 2: 2.0,
1869 },
1870 actual: map[int]float64{
1871 1: 1.0,
1872 },
1873 delta: 0.1,
1874 f: False,
1875 },
1876 {
1877 title: "Within delta with zero value",
1878 expect: map[string]float64{
1879 "zero": 0,
1880 },
1881 actual: map[string]float64{
1882 "zero": 0,
1883 },
1884 delta: 0.1,
1885 f: True,
1886 },
1887 {
1888 title: "With missing key with zero value",
1889 expect: map[string]float64{
1890 "zero": 0,
1891 "foo": 0,
1892 },
1893 actual: map[string]float64{
1894 "zero": 0,
1895 "bar": 0,
1896 },
1897 f: False,
1898 },
1899 } {
1900 tc.f(t, InDeltaMapValues(mockT, tc.expect, tc.actual, tc.delta), tc.title+"\n"+diff(tc.expect, tc.actual))
1901 }
1902 }
1903
1904 func TestInEpsilon(t *testing.T) {
1905 mockT := new(testing.T)
1906
1907 cases := []struct {
1908 a, b interface{}
1909 epsilon float64
1910 }{
1911 {uint8(2), uint16(2), .001},
1912 {2.1, 2.2, 0.1},
1913 {2.2, 2.1, 0.1},
1914 {-2.1, -2.2, 0.1},
1915 {-2.2, -2.1, 0.1},
1916 {uint64(100), uint8(101), 0.01},
1917 {0.1, -0.1, 2},
1918 {0.1, 0, 2},
1919 {math.NaN(), math.NaN(), 1},
1920 {time.Second, time.Second + time.Millisecond, 0.002},
1921 }
1922
1923 for _, tc := range cases {
1924 True(t, InEpsilon(t, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon), "test: %q", tc)
1925 }
1926
1927 cases = []struct {
1928 a, b interface{}
1929 epsilon float64
1930 }{
1931 {uint8(2), int16(-2), .001},
1932 {uint64(100), uint8(102), 0.01},
1933 {2.1, 2.2, 0.001},
1934 {2.2, 2.1, 0.001},
1935 {2.1, -2.2, 1},
1936 {2.1, "bla-bla", 0},
1937 {0.1, -0.1, 1.99},
1938 {0, 0.1, 2},
1939 {time.Second, time.Second + 10*time.Millisecond, 0.002},
1940 {math.NaN(), 0, 1},
1941 {0, math.NaN(), 1},
1942 {0, 0, math.NaN()},
1943 }
1944
1945 for _, tc := range cases {
1946 False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon))
1947 }
1948
1949 }
1950
1951 func TestInEpsilonSlice(t *testing.T) {
1952 mockT := new(testing.T)
1953
1954 True(t, InEpsilonSlice(mockT,
1955 []float64{2.2, math.NaN(), 2.0},
1956 []float64{2.1, math.NaN(), 2.1},
1957 0.06), "{2.2, NaN, 2.0} is element-wise close to {2.1, NaN, 2.1} in epsilon=0.06")
1958
1959 False(t, InEpsilonSlice(mockT,
1960 []float64{2.2, 2.0},
1961 []float64{2.1, 2.1},
1962 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in epsilon=0.04")
1963
1964 False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
1965 }
1966
1967 func TestRegexp(t *testing.T) {
1968 mockT := new(testing.T)
1969
1970 cases := []struct {
1971 rx, str string
1972 }{
1973 {"^start", "start of the line"},
1974 {"end$", "in the end"},
1975 {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
1976 }
1977
1978 for _, tc := range cases {
1979 True(t, Regexp(mockT, tc.rx, tc.str))
1980 True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
1981 False(t, NotRegexp(mockT, tc.rx, tc.str))
1982 False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
1983 }
1984
1985 cases = []struct {
1986 rx, str string
1987 }{
1988 {"^asdfastart", "Not the start of the line"},
1989 {"end$", "in the end."},
1990 {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"},
1991 }
1992
1993 for _, tc := range cases {
1994 False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
1995 False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
1996 True(t, NotRegexp(mockT, tc.rx, tc.str))
1997 True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
1998 }
1999 }
2000
2001 func testAutogeneratedFunction() {
2002 defer func() {
2003 if err := recover(); err == nil {
2004 panic("did not panic")
2005 }
2006 CallerInfo()
2007 }()
2008 t := struct {
2009 io.Closer
2010 }{}
2011 c := t
2012 c.Close()
2013 }
2014
2015 func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) {
2016 NotPanics(t, func() {
2017 testAutogeneratedFunction()
2018 })
2019 }
2020
2021 func TestZero(t *testing.T) {
2022 mockT := new(testing.T)
2023
2024 for _, test := range zeros {
2025 True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
2026 }
2027
2028 for _, test := range nonZeros {
2029 False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
2030 }
2031 }
2032
2033 func TestNotZero(t *testing.T) {
2034 mockT := new(testing.T)
2035
2036 for _, test := range zeros {
2037 False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
2038 }
2039
2040 for _, test := range nonZeros {
2041 True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
2042 }
2043 }
2044
2045 func TestFileExists(t *testing.T) {
2046 mockT := new(testing.T)
2047 True(t, FileExists(mockT, "assertions.go"))
2048
2049 mockT = new(testing.T)
2050 False(t, FileExists(mockT, "random_file"))
2051
2052 mockT = new(testing.T)
2053 False(t, FileExists(mockT, "../_codegen"))
2054
2055 var tempFiles []string
2056
2057 link, err := getTempSymlinkPath("assertions.go")
2058 if err != nil {
2059 t.Fatal("could not create temp symlink, err:", err)
2060 }
2061 tempFiles = append(tempFiles, link)
2062 mockT = new(testing.T)
2063 True(t, FileExists(mockT, link))
2064
2065 link, err = getTempSymlinkPath("non_existent_file")
2066 if err != nil {
2067 t.Fatal("could not create temp symlink, err:", err)
2068 }
2069 tempFiles = append(tempFiles, link)
2070 mockT = new(testing.T)
2071 True(t, FileExists(mockT, link))
2072
2073 errs := cleanUpTempFiles(tempFiles)
2074 if len(errs) > 0 {
2075 t.Fatal("could not clean up temporary files")
2076 }
2077 }
2078
2079 func TestNoFileExists(t *testing.T) {
2080 mockT := new(testing.T)
2081 False(t, NoFileExists(mockT, "assertions.go"))
2082
2083 mockT = new(testing.T)
2084 True(t, NoFileExists(mockT, "non_existent_file"))
2085
2086 mockT = new(testing.T)
2087 True(t, NoFileExists(mockT, "../_codegen"))
2088
2089 var tempFiles []string
2090
2091 link, err := getTempSymlinkPath("assertions.go")
2092 if err != nil {
2093 t.Fatal("could not create temp symlink, err:", err)
2094 }
2095 tempFiles = append(tempFiles, link)
2096 mockT = new(testing.T)
2097 False(t, NoFileExists(mockT, link))
2098
2099 link, err = getTempSymlinkPath("non_existent_file")
2100 if err != nil {
2101 t.Fatal("could not create temp symlink, err:", err)
2102 }
2103 tempFiles = append(tempFiles, link)
2104 mockT = new(testing.T)
2105 False(t, NoFileExists(mockT, link))
2106
2107 errs := cleanUpTempFiles(tempFiles)
2108 if len(errs) > 0 {
2109 t.Fatal("could not clean up temporary files")
2110 }
2111 }
2112
2113 func getTempSymlinkPath(file string) (string, error) {
2114 link := file + "_symlink"
2115 err := os.Symlink(file, link)
2116 return link, err
2117 }
2118
2119 func cleanUpTempFiles(paths []string) []error {
2120 var res []error
2121 for _, path := range paths {
2122 err := os.Remove(path)
2123 if err != nil {
2124 res = append(res, err)
2125 }
2126 }
2127 return res
2128 }
2129
2130 func TestDirExists(t *testing.T) {
2131 mockT := new(testing.T)
2132 False(t, DirExists(mockT, "assertions.go"))
2133
2134 mockT = new(testing.T)
2135 False(t, DirExists(mockT, "non_existent_dir"))
2136
2137 mockT = new(testing.T)
2138 True(t, DirExists(mockT, "../_codegen"))
2139
2140 var tempFiles []string
2141
2142 link, err := getTempSymlinkPath("assertions.go")
2143 if err != nil {
2144 t.Fatal("could not create temp symlink, err:", err)
2145 }
2146 tempFiles = append(tempFiles, link)
2147 mockT = new(testing.T)
2148 False(t, DirExists(mockT, link))
2149
2150 link, err = getTempSymlinkPath("non_existent_dir")
2151 if err != nil {
2152 t.Fatal("could not create temp symlink, err:", err)
2153 }
2154 tempFiles = append(tempFiles, link)
2155 mockT = new(testing.T)
2156 False(t, DirExists(mockT, link))
2157
2158 errs := cleanUpTempFiles(tempFiles)
2159 if len(errs) > 0 {
2160 t.Fatal("could not clean up temporary files")
2161 }
2162 }
2163
2164 func TestNoDirExists(t *testing.T) {
2165 mockT := new(testing.T)
2166 True(t, NoDirExists(mockT, "assertions.go"))
2167
2168 mockT = new(testing.T)
2169 True(t, NoDirExists(mockT, "non_existent_dir"))
2170
2171 mockT = new(testing.T)
2172 False(t, NoDirExists(mockT, "../_codegen"))
2173
2174 var tempFiles []string
2175
2176 link, err := getTempSymlinkPath("assertions.go")
2177 if err != nil {
2178 t.Fatal("could not create temp symlink, err:", err)
2179 }
2180 tempFiles = append(tempFiles, link)
2181 mockT = new(testing.T)
2182 True(t, NoDirExists(mockT, link))
2183
2184 link, err = getTempSymlinkPath("non_existent_dir")
2185 if err != nil {
2186 t.Fatal("could not create temp symlink, err:", err)
2187 }
2188 tempFiles = append(tempFiles, link)
2189 mockT = new(testing.T)
2190 True(t, NoDirExists(mockT, link))
2191
2192 errs := cleanUpTempFiles(tempFiles)
2193 if len(errs) > 0 {
2194 t.Fatal("could not clean up temporary files")
2195 }
2196 }
2197
2198 func TestJSONEq_EqualSONString(t *testing.T) {
2199 mockT := new(testing.T)
2200 True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`))
2201 }
2202
2203 func TestJSONEq_EquivalentButNotEqual(t *testing.T) {
2204 mockT := new(testing.T)
2205 True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
2206 }
2207
2208 func TestJSONEq_HashOfArraysAndHashes(t *testing.T) {
2209 mockT := new(testing.T)
2210 True(t, JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}",
2211 "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}"))
2212 }
2213
2214 func TestJSONEq_Array(t *testing.T) {
2215 mockT := new(testing.T)
2216 True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`))
2217 }
2218
2219 func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) {
2220 mockT := new(testing.T)
2221 False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`))
2222 }
2223
2224 func TestJSONEq_HashesNotEquivalent(t *testing.T) {
2225 mockT := new(testing.T)
2226 False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
2227 }
2228
2229 func TestJSONEq_ActualIsNotJSON(t *testing.T) {
2230 mockT := new(testing.T)
2231 False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON"))
2232 }
2233
2234 func TestJSONEq_ExpectedIsNotJSON(t *testing.T) {
2235 mockT := new(testing.T)
2236 False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`))
2237 }
2238
2239 func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) {
2240 mockT := new(testing.T)
2241 False(t, JSONEq(mockT, "Not JSON", "Not JSON"))
2242 }
2243
2244 func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) {
2245 mockT := new(testing.T)
2246 False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`))
2247 }
2248
2249 func TestYAMLEq_EqualYAMLString(t *testing.T) {
2250 mockT := new(testing.T)
2251 True(t, YAMLEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`))
2252 }
2253
2254 func TestYAMLEq_EquivalentButNotEqual(t *testing.T) {
2255 mockT := new(testing.T)
2256 True(t, YAMLEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
2257 }
2258
2259 func TestYAMLEq_HashOfArraysAndHashes(t *testing.T) {
2260 mockT := new(testing.T)
2261 expected := `
2262 numeric: 1.5
2263 array:
2264 - foo: bar
2265 - 1
2266 - "string"
2267 - ["nested", "array", 5.5]
2268 hash:
2269 nested: hash
2270 nested_slice: [this, is, nested]
2271 string: "foo"
2272 `
2273
2274 actual := `
2275 numeric: 1.5
2276 hash:
2277 nested: hash
2278 nested_slice: [this, is, nested]
2279 string: "foo"
2280 array:
2281 - foo: bar
2282 - 1
2283 - "string"
2284 - ["nested", "array", 5.5]
2285 `
2286 True(t, YAMLEq(mockT, expected, actual))
2287 }
2288
2289 func TestYAMLEq_Array(t *testing.T) {
2290 mockT := new(testing.T)
2291 True(t, YAMLEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`))
2292 }
2293
2294 func TestYAMLEq_HashAndArrayNotEquivalent(t *testing.T) {
2295 mockT := new(testing.T)
2296 False(t, YAMLEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`))
2297 }
2298
2299 func TestYAMLEq_HashesNotEquivalent(t *testing.T) {
2300 mockT := new(testing.T)
2301 False(t, YAMLEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
2302 }
2303
2304 func TestYAMLEq_ActualIsSimpleString(t *testing.T) {
2305 mockT := new(testing.T)
2306 False(t, YAMLEq(mockT, `{"foo": "bar"}`, "Simple String"))
2307 }
2308
2309 func TestYAMLEq_ExpectedIsSimpleString(t *testing.T) {
2310 mockT := new(testing.T)
2311 False(t, YAMLEq(mockT, "Simple String", `{"foo": "bar", "hello": "world"}`))
2312 }
2313
2314 func TestYAMLEq_ExpectedAndActualSimpleString(t *testing.T) {
2315 mockT := new(testing.T)
2316 True(t, YAMLEq(mockT, "Simple String", "Simple String"))
2317 }
2318
2319 func TestYAMLEq_ArraysOfDifferentOrder(t *testing.T) {
2320 mockT := new(testing.T)
2321 False(t, YAMLEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`))
2322 }
2323
2324 type diffTestingStruct struct {
2325 A string
2326 B int
2327 }
2328
2329 func (d *diffTestingStruct) String() string {
2330 return d.A
2331 }
2332
2333 func TestDiff(t *testing.T) {
2334 expected := `
2335
2336 Diff:
2337 --- Expected
2338 +++ Actual
2339 @@ -1,3 +1,3 @@
2340 (struct { foo string }) {
2341 - foo: (string) (len=5) "hello"
2342 + foo: (string) (len=3) "bar"
2343 }
2344 `
2345 actual := diff(
2346 struct{ foo string }{"hello"},
2347 struct{ foo string }{"bar"},
2348 )
2349 Equal(t, expected, actual)
2350
2351 expected = `
2352
2353 Diff:
2354 --- Expected
2355 +++ Actual
2356 @@ -2,5 +2,5 @@
2357 (int) 1,
2358 - (int) 2,
2359 (int) 3,
2360 - (int) 4
2361 + (int) 5,
2362 + (int) 7
2363 }
2364 `
2365 actual = diff(
2366 []int{1, 2, 3, 4},
2367 []int{1, 3, 5, 7},
2368 )
2369 Equal(t, expected, actual)
2370
2371 expected = `
2372
2373 Diff:
2374 --- Expected
2375 +++ Actual
2376 @@ -2,4 +2,4 @@
2377 (int) 1,
2378 - (int) 2,
2379 - (int) 3
2380 + (int) 3,
2381 + (int) 5
2382 }
2383 `
2384 actual = diff(
2385 []int{1, 2, 3, 4}[0:3],
2386 []int{1, 3, 5, 7}[0:3],
2387 )
2388 Equal(t, expected, actual)
2389
2390 expected = `
2391
2392 Diff:
2393 --- Expected
2394 +++ Actual
2395 @@ -1,6 +1,6 @@
2396 (map[string]int) (len=4) {
2397 - (string) (len=4) "four": (int) 4,
2398 + (string) (len=4) "five": (int) 5,
2399 (string) (len=3) "one": (int) 1,
2400 - (string) (len=5) "three": (int) 3,
2401 - (string) (len=3) "two": (int) 2
2402 + (string) (len=5) "seven": (int) 7,
2403 + (string) (len=5) "three": (int) 3
2404 }
2405 `
2406
2407 actual = diff(
2408 map[string]int{"one": 1, "two": 2, "three": 3, "four": 4},
2409 map[string]int{"one": 1, "three": 3, "five": 5, "seven": 7},
2410 )
2411 Equal(t, expected, actual)
2412
2413 expected = `
2414
2415 Diff:
2416 --- Expected
2417 +++ Actual
2418 @@ -1,3 +1,3 @@
2419 (*errors.errorString)({
2420 - s: (string) (len=19) "some expected error"
2421 + s: (string) (len=12) "actual error"
2422 })
2423 `
2424
2425 actual = diff(
2426 errors.New("some expected error"),
2427 errors.New("actual error"),
2428 )
2429 Equal(t, expected, actual)
2430
2431 expected = `
2432
2433 Diff:
2434 --- Expected
2435 +++ Actual
2436 @@ -2,3 +2,3 @@
2437 A: (string) (len=11) "some string",
2438 - B: (int) 10
2439 + B: (int) 15
2440 }
2441 `
2442
2443 actual = diff(
2444 diffTestingStruct{A: "some string", B: 10},
2445 diffTestingStruct{A: "some string", B: 15},
2446 )
2447 Equal(t, expected, actual)
2448
2449 expected = `
2450
2451 Diff:
2452 --- Expected
2453 +++ Actual
2454 @@ -1,2 +1,2 @@
2455 -(time.Time) 2020-09-24 00:00:00 +0000 UTC
2456 +(time.Time) 2020-09-25 00:00:00 +0000 UTC
2457
2458 `
2459
2460 actual = diff(
2461 time.Date(2020, 9, 24, 0, 0, 0, 0, time.UTC),
2462 time.Date(2020, 9, 25, 0, 0, 0, 0, time.UTC),
2463 )
2464 Equal(t, expected, actual)
2465 }
2466
2467 func TestTimeEqualityErrorFormatting(t *testing.T) {
2468 mockT := new(mockTestingT)
2469
2470 Equal(mockT, time.Second*2, time.Millisecond)
2471
2472 expectedErr := "\\s+Error Trace:\\s+Error:\\s+Not equal:\\s+\n\\s+expected: 2s\n\\s+actual\\s+: 1ms\n"
2473 Regexp(t, regexp.MustCompile(expectedErr), mockT.errorString())
2474 }
2475
2476 func TestDiffEmptyCases(t *testing.T) {
2477 Equal(t, "", diff(nil, nil))
2478 Equal(t, "", diff(struct{ foo string }{}, nil))
2479 Equal(t, "", diff(nil, struct{ foo string }{}))
2480 Equal(t, "", diff(1, 2))
2481 Equal(t, "", diff(1, 2))
2482 Equal(t, "", diff([]int{1}, []bool{true}))
2483 }
2484
2485
2486 func TestDiffRace(t *testing.T) {
2487 t.Parallel()
2488
2489 expected := map[string]string{
2490 "a": "A",
2491 "b": "B",
2492 "c": "C",
2493 }
2494
2495 actual := map[string]string{
2496 "d": "D",
2497 "e": "E",
2498 "f": "F",
2499 }
2500
2501
2502 numRoutines := 10
2503 rChans := make([]chan string, numRoutines)
2504 for idx := range rChans {
2505 rChans[idx] = make(chan string)
2506 go func(ch chan string) {
2507 defer close(ch)
2508 ch <- diff(expected, actual)
2509 }(rChans[idx])
2510 }
2511
2512 for _, ch := range rChans {
2513 for msg := range ch {
2514 NotZero(t, msg)
2515 }
2516 }
2517 }
2518
2519 type mockTestingT struct {
2520 errorFmt string
2521 args []interface{}
2522 }
2523
2524 func (m *mockTestingT) errorString() string {
2525 return fmt.Sprintf(m.errorFmt, m.args...)
2526 }
2527
2528 func (m *mockTestingT) Errorf(format string, args ...interface{}) {
2529 m.errorFmt = format
2530 m.args = args
2531 }
2532
2533 func (m *mockTestingT) Failed() bool {
2534 return m.errorFmt != ""
2535 }
2536
2537 func TestFailNowWithPlainTestingT(t *testing.T) {
2538 mockT := &mockTestingT{}
2539
2540 Panics(t, func() {
2541 FailNow(mockT, "failed")
2542 }, "should panic since mockT is missing FailNow()")
2543 }
2544
2545 type mockFailNowTestingT struct {
2546 }
2547
2548 func (m *mockFailNowTestingT) Errorf(format string, args ...interface{}) {}
2549
2550 func (m *mockFailNowTestingT) FailNow() {}
2551
2552 func TestFailNowWithFullTestingT(t *testing.T) {
2553 mockT := &mockFailNowTestingT{}
2554
2555 NotPanics(t, func() {
2556 FailNow(mockT, "failed")
2557 }, "should call mockT.FailNow() rather than panicking")
2558 }
2559
2560 func TestBytesEqual(t *testing.T) {
2561 var cases = []struct {
2562 a, b []byte
2563 }{
2564 {make([]byte, 2), make([]byte, 2)},
2565 {make([]byte, 2), make([]byte, 2, 3)},
2566 {nil, make([]byte, 0)},
2567 }
2568 for i, c := range cases {
2569 Equal(t, reflect.DeepEqual(c.a, c.b), ObjectsAreEqual(c.a, c.b), "case %d failed", i+1)
2570 }
2571 }
2572
2573 func BenchmarkBytesEqual(b *testing.B) {
2574 const size = 1024 * 8
2575 s := make([]byte, size)
2576 for i := range s {
2577 s[i] = byte(i % 255)
2578 }
2579 s2 := make([]byte, size)
2580 copy(s2, s)
2581
2582 mockT := &mockFailNowTestingT{}
2583 b.ResetTimer()
2584 for i := 0; i < b.N; i++ {
2585 Equal(mockT, s, s2)
2586 }
2587 }
2588
2589 func BenchmarkNotNil(b *testing.B) {
2590 for i := 0; i < b.N; i++ {
2591 NotNil(b, b)
2592 }
2593 }
2594
2595 func ExampleComparisonAssertionFunc() {
2596 t := &testing.T{}
2597
2598 adder := func(x, y int) int {
2599 return x + y
2600 }
2601
2602 type args struct {
2603 x int
2604 y int
2605 }
2606
2607 tests := []struct {
2608 name string
2609 args args
2610 expect int
2611 assertion ComparisonAssertionFunc
2612 }{
2613 {"2+2=4", args{2, 2}, 4, Equal},
2614 {"2+2!=5", args{2, 2}, 5, NotEqual},
2615 {"2+3==5", args{2, 3}, 5, Exactly},
2616 }
2617
2618 for _, tt := range tests {
2619 t.Run(tt.name, func(t *testing.T) {
2620 tt.assertion(t, tt.expect, adder(tt.args.x, tt.args.y))
2621 })
2622 }
2623 }
2624
2625 func TestComparisonAssertionFunc(t *testing.T) {
2626 type iface interface {
2627 Name() string
2628 }
2629
2630 tests := []struct {
2631 name string
2632 expect interface{}
2633 got interface{}
2634 assertion ComparisonAssertionFunc
2635 }{
2636 {"implements", (*iface)(nil), t, Implements},
2637 {"isType", (*testing.T)(nil), t, IsType},
2638 {"equal", t, t, Equal},
2639 {"equalValues", t, t, EqualValues},
2640 {"notEqualValues", t, nil, NotEqualValues},
2641 {"exactly", t, t, Exactly},
2642 {"notEqual", t, nil, NotEqual},
2643 {"notContains", []int{1, 2, 3}, 4, NotContains},
2644 {"subset", []int{1, 2, 3, 4}, []int{2, 3}, Subset},
2645 {"notSubset", []int{1, 2, 3, 4}, []int{0, 3}, NotSubset},
2646 {"elementsMatch", []byte("abc"), []byte("bac"), ElementsMatch},
2647 {"regexp", "^t.*y$", "testify", Regexp},
2648 {"notRegexp", "^t.*y$", "Testify", NotRegexp},
2649 }
2650
2651 for _, tt := range tests {
2652 t.Run(tt.name, func(t *testing.T) {
2653 tt.assertion(t, tt.expect, tt.got)
2654 })
2655 }
2656 }
2657
2658 func ExampleValueAssertionFunc() {
2659 t := &testing.T{}
2660
2661 dumbParse := func(input string) interface{} {
2662 var x interface{}
2663 _ = json.Unmarshal([]byte(input), &x)
2664 return x
2665 }
2666
2667 tests := []struct {
2668 name string
2669 arg string
2670 assertion ValueAssertionFunc
2671 }{
2672 {"true is not nil", "true", NotNil},
2673 {"empty string is nil", "", Nil},
2674 {"zero is not nil", "0", NotNil},
2675 {"zero is zero", "0", Zero},
2676 {"false is zero", "false", Zero},
2677 }
2678
2679 for _, tt := range tests {
2680 t.Run(tt.name, func(t *testing.T) {
2681 tt.assertion(t, dumbParse(tt.arg))
2682 })
2683 }
2684 }
2685
2686 func TestValueAssertionFunc(t *testing.T) {
2687 tests := []struct {
2688 name string
2689 value interface{}
2690 assertion ValueAssertionFunc
2691 }{
2692 {"notNil", true, NotNil},
2693 {"nil", nil, Nil},
2694 {"empty", []int{}, Empty},
2695 {"notEmpty", []int{1}, NotEmpty},
2696 {"zero", false, Zero},
2697 {"notZero", 42, NotZero},
2698 }
2699
2700 for _, tt := range tests {
2701 t.Run(tt.name, func(t *testing.T) {
2702 tt.assertion(t, tt.value)
2703 })
2704 }
2705 }
2706
2707 func ExampleBoolAssertionFunc() {
2708 t := &testing.T{}
2709
2710 isOkay := func(x int) bool {
2711 return x >= 42
2712 }
2713
2714 tests := []struct {
2715 name string
2716 arg int
2717 assertion BoolAssertionFunc
2718 }{
2719 {"-1 is bad", -1, False},
2720 {"42 is good", 42, True},
2721 {"41 is bad", 41, False},
2722 {"45 is cool", 45, True},
2723 }
2724
2725 for _, tt := range tests {
2726 t.Run(tt.name, func(t *testing.T) {
2727 tt.assertion(t, isOkay(tt.arg))
2728 })
2729 }
2730 }
2731
2732 func TestBoolAssertionFunc(t *testing.T) {
2733 tests := []struct {
2734 name string
2735 value bool
2736 assertion BoolAssertionFunc
2737 }{
2738 {"true", true, True},
2739 {"false", false, False},
2740 }
2741
2742 for _, tt := range tests {
2743 t.Run(tt.name, func(t *testing.T) {
2744 tt.assertion(t, tt.value)
2745 })
2746 }
2747 }
2748
2749 func ExampleErrorAssertionFunc() {
2750 t := &testing.T{}
2751
2752 dumbParseNum := func(input string, v interface{}) error {
2753 return json.Unmarshal([]byte(input), v)
2754 }
2755
2756 tests := []struct {
2757 name string
2758 arg string
2759 assertion ErrorAssertionFunc
2760 }{
2761 {"1.2 is number", "1.2", NoError},
2762 {"1.2.3 not number", "1.2.3", Error},
2763 {"true is not number", "true", Error},
2764 {"3 is number", "3", NoError},
2765 }
2766
2767 for _, tt := range tests {
2768 t.Run(tt.name, func(t *testing.T) {
2769 var x float64
2770 tt.assertion(t, dumbParseNum(tt.arg, &x))
2771 })
2772 }
2773 }
2774
2775 func TestErrorAssertionFunc(t *testing.T) {
2776 tests := []struct {
2777 name string
2778 err error
2779 assertion ErrorAssertionFunc
2780 }{
2781 {"noError", nil, NoError},
2782 {"error", errors.New("whoops"), Error},
2783 }
2784
2785 for _, tt := range tests {
2786 t.Run(tt.name, func(t *testing.T) {
2787 tt.assertion(t, tt.err)
2788 })
2789 }
2790 }
2791
2792 func TestEventuallyFalse(t *testing.T) {
2793 mockT := new(testing.T)
2794
2795 condition := func() bool {
2796 return false
2797 }
2798
2799 False(t, Eventually(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
2800 }
2801
2802 func TestEventuallyTrue(t *testing.T) {
2803 state := 0
2804 condition := func() bool {
2805 defer func() {
2806 state += 1
2807 }()
2808 return state == 2
2809 }
2810
2811 True(t, Eventually(t, condition, 100*time.Millisecond, 20*time.Millisecond))
2812 }
2813
2814
2815 type errorsCapturingT struct {
2816 errors []error
2817 }
2818
2819 func (t *errorsCapturingT) Errorf(format string, args ...interface{}) {
2820 t.errors = append(t.errors, fmt.Errorf(format, args...))
2821 }
2822
2823 func (t *errorsCapturingT) Helper() {}
2824
2825 func TestEventuallyWithTFalse(t *testing.T) {
2826 mockT := new(errorsCapturingT)
2827
2828 condition := func(collect *CollectT) {
2829 Fail(collect, "condition fixed failure")
2830 }
2831
2832 False(t, EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
2833 Len(t, mockT.errors, 2)
2834 }
2835
2836 func TestEventuallyWithTTrue(t *testing.T) {
2837 mockT := new(errorsCapturingT)
2838
2839 state := 0
2840 condition := func(collect *CollectT) {
2841 defer func() {
2842 state += 1
2843 }()
2844 True(collect, state == 2)
2845 }
2846
2847 True(t, EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
2848 Len(t, mockT.errors, 0)
2849 }
2850
2851 func TestEventuallyWithT_ConcurrencySafe(t *testing.T) {
2852 mockT := new(errorsCapturingT)
2853
2854 condition := func(collect *CollectT) {
2855 Fail(collect, "condition fixed failure")
2856 }
2857
2858
2859 False(t, EventuallyWithT(mockT, condition, 100*time.Millisecond, time.Nanosecond))
2860 Len(t, mockT.errors, 2)
2861 }
2862
2863 func TestEventuallyWithT_ReturnsTheLatestFinishedConditionErrors(t *testing.T) {
2864
2865 mustSleep := make(chan bool, 2)
2866 mustSleep <- false
2867 mustSleep <- true
2868 close(mustSleep)
2869
2870 condition := func(collect *CollectT) {
2871 if <-mustSleep {
2872
2873 time.Sleep(time.Second)
2874 return
2875 }
2876
2877
2878 Fail(collect, "condition fixed failure")
2879 }
2880
2881 mockT := new(errorsCapturingT)
2882 False(t, EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
2883 Len(t, mockT.errors, 2)
2884 }
2885
2886 func TestNeverFalse(t *testing.T) {
2887 condition := func() bool {
2888 return false
2889 }
2890
2891 True(t, Never(t, condition, 100*time.Millisecond, 20*time.Millisecond))
2892 }
2893
2894
2895 func TestNeverTrue(t *testing.T) {
2896 mockT := new(testing.T)
2897
2898
2899
2900 returns := make(chan bool, 2)
2901 returns <- false
2902 returns <- true
2903 defer close(returns)
2904
2905
2906 condition := func() bool {
2907 return <-returns
2908 }
2909
2910 False(t, Never(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
2911 }
2912
2913
2914
2915 func TestEventuallyTimeout(t *testing.T) {
2916 mockT := new(testing.T)
2917
2918 NotPanics(t, func() {
2919 done, done2 := make(chan struct{}), make(chan struct{})
2920
2921
2922 condition := func() bool {
2923
2924 <-done
2925 close(done2)
2926 return true
2927 }
2928
2929 False(t, Eventually(mockT, condition, time.Millisecond, time.Microsecond))
2930
2931 close(done)
2932 <-done2
2933 })
2934 }
2935
2936 func Test_validateEqualArgs(t *testing.T) {
2937 if validateEqualArgs(func() {}, func() {}) == nil {
2938 t.Error("non-nil functions should error")
2939 }
2940
2941 if validateEqualArgs(func() {}, func() {}) == nil {
2942 t.Error("non-nil functions should error")
2943 }
2944
2945 if validateEqualArgs(nil, nil) != nil {
2946 t.Error("nil functions are equal")
2947 }
2948 }
2949
2950 func Test_truncatingFormat(t *testing.T) {
2951
2952 original := strings.Repeat("a", bufio.MaxScanTokenSize-102)
2953 result := truncatingFormat(original)
2954 Equal(t, fmt.Sprintf("%#v", original), result, "string should not be truncated")
2955
2956 original = original + "x"
2957 result = truncatingFormat(original)
2958 NotEqual(t, fmt.Sprintf("%#v", original), result, "string should have been truncated.")
2959
2960 if !strings.HasSuffix(result, "<... truncated>") {
2961 t.Error("truncated string should have <... truncated> suffix")
2962 }
2963 }
2964
2965
2966
2967 func parseLabeledOutput(output string) []labeledContent {
2968 labelPattern := regexp.MustCompile(`^\t([^\t]*): *\t(.*)$`)
2969 contentPattern := regexp.MustCompile(`^\t *\t(.*)$`)
2970 var contents []labeledContent
2971 lines := strings.Split(output, "\n")
2972 i := -1
2973 for _, line := range lines {
2974 if line == "" {
2975
2976 continue
2977 }
2978 matches := labelPattern.FindStringSubmatch(line)
2979 if len(matches) == 3 {
2980
2981 contents = append(contents, labeledContent{
2982 label: matches[1],
2983 content: matches[2] + "\n",
2984 })
2985 i++
2986 continue
2987 }
2988 matches = contentPattern.FindStringSubmatch(line)
2989 if len(matches) == 2 {
2990
2991 if i >= 0 {
2992 contents[i].content += matches[1] + "\n"
2993 continue
2994 }
2995 }
2996
2997 return nil
2998 }
2999 return contents
3000 }
3001
3002 type captureTestingT struct {
3003 msg string
3004 }
3005
3006 func (ctt *captureTestingT) Errorf(format string, args ...interface{}) {
3007 ctt.msg = fmt.Sprintf(format, args...)
3008 }
3009
3010 func (ctt *captureTestingT) checkResultAndErrMsg(t *testing.T, expectedRes, res bool, expectedErrMsg string) {
3011 t.Helper()
3012 if res != expectedRes {
3013 t.Errorf("Should return %t", expectedRes)
3014 return
3015 }
3016 contents := parseLabeledOutput(ctt.msg)
3017 if res == true {
3018 if contents != nil {
3019 t.Errorf("Should not log an error")
3020 }
3021 return
3022 }
3023 if contents == nil {
3024 t.Errorf("Should log an error. Log output: %v", ctt.msg)
3025 return
3026 }
3027 for _, content := range contents {
3028 if content.label == "Error" {
3029 if expectedErrMsg == content.content {
3030 return
3031 }
3032 t.Errorf("Logged Error: %v", content.content)
3033 }
3034 }
3035 t.Errorf("Should log Error: %v", expectedErrMsg)
3036 }
3037
3038 func TestErrorIs(t *testing.T) {
3039 tests := []struct {
3040 err error
3041 target error
3042 result bool
3043 resultErrMsg string
3044 }{
3045 {
3046 err: io.EOF,
3047 target: io.EOF,
3048 result: true,
3049 },
3050 {
3051 err: fmt.Errorf("wrap: %w", io.EOF),
3052 target: io.EOF,
3053 result: true,
3054 },
3055 {
3056 err: io.EOF,
3057 target: io.ErrClosedPipe,
3058 result: false,
3059 resultErrMsg: "" +
3060 "Target error should be in err chain:\n" +
3061 "expected: \"io: read/write on closed pipe\"\n" +
3062 "in chain: \"EOF\"\n",
3063 },
3064 {
3065 err: nil,
3066 target: io.EOF,
3067 result: false,
3068 resultErrMsg: "" +
3069 "Target error should be in err chain:\n" +
3070 "expected: \"EOF\"\n" +
3071 "in chain: \n",
3072 },
3073 {
3074 err: io.EOF,
3075 target: nil,
3076 result: false,
3077 resultErrMsg: "" +
3078 "Target error should be in err chain:\n" +
3079 "expected: \"\"\n" +
3080 "in chain: \"EOF\"\n",
3081 },
3082 {
3083 err: nil,
3084 target: nil,
3085 result: true,
3086 },
3087 {
3088 err: fmt.Errorf("abc: %w", errors.New("def")),
3089 target: io.EOF,
3090 result: false,
3091 resultErrMsg: "" +
3092 "Target error should be in err chain:\n" +
3093 "expected: \"EOF\"\n" +
3094 "in chain: \"abc: def\"\n" +
3095 "\t\"def\"\n",
3096 },
3097 }
3098 for _, tt := range tests {
3099 tt := tt
3100 t.Run(fmt.Sprintf("ErrorIs(%#v,%#v)", tt.err, tt.target), func(t *testing.T) {
3101 mockT := new(captureTestingT)
3102 res := ErrorIs(mockT, tt.err, tt.target)
3103 mockT.checkResultAndErrMsg(t, tt.result, res, tt.resultErrMsg)
3104 })
3105 }
3106 }
3107
3108 func TestNotErrorIs(t *testing.T) {
3109 tests := []struct {
3110 err error
3111 target error
3112 result bool
3113 resultErrMsg string
3114 }{
3115 {
3116 err: io.EOF,
3117 target: io.EOF,
3118 result: false,
3119 resultErrMsg: "" +
3120 "Target error should not be in err chain:\n" +
3121 "found: \"EOF\"\n" +
3122 "in chain: \"EOF\"\n",
3123 },
3124 {
3125 err: fmt.Errorf("wrap: %w", io.EOF),
3126 target: io.EOF,
3127 result: false,
3128 resultErrMsg: "" +
3129 "Target error should not be in err chain:\n" +
3130 "found: \"EOF\"\n" +
3131 "in chain: \"wrap: EOF\"\n" +
3132 "\t\"EOF\"\n",
3133 },
3134 {
3135 err: io.EOF,
3136 target: io.ErrClosedPipe,
3137 result: true,
3138 },
3139 {
3140 err: nil,
3141 target: io.EOF,
3142 result: true,
3143 },
3144 {
3145 err: io.EOF,
3146 target: nil,
3147 result: true,
3148 },
3149 {
3150 err: nil,
3151 target: nil,
3152 result: false,
3153 resultErrMsg: "" +
3154 "Target error should not be in err chain:\n" +
3155 "found: \"\"\n" +
3156 "in chain: \n",
3157 },
3158 {
3159 err: fmt.Errorf("abc: %w", errors.New("def")),
3160 target: io.EOF,
3161 result: true,
3162 },
3163 }
3164 for _, tt := range tests {
3165 tt := tt
3166 t.Run(fmt.Sprintf("NotErrorIs(%#v,%#v)", tt.err, tt.target), func(t *testing.T) {
3167 mockT := new(captureTestingT)
3168 res := NotErrorIs(mockT, tt.err, tt.target)
3169 mockT.checkResultAndErrMsg(t, tt.result, res, tt.resultErrMsg)
3170 })
3171 }
3172 }
3173
3174 func TestErrorAs(t *testing.T) {
3175 mockT := new(testing.T)
3176 tests := []struct {
3177 err error
3178 result bool
3179 }{
3180 {fmt.Errorf("wrap: %w", &customError{}), true},
3181 {io.EOF, false},
3182 {nil, false},
3183 }
3184 for _, tt := range tests {
3185 tt := tt
3186 var target *customError
3187 t.Run(fmt.Sprintf("ErrorAs(%#v,%#v)", tt.err, target), func(t *testing.T) {
3188 res := ErrorAs(mockT, tt.err, &target)
3189 if res != tt.result {
3190 t.Errorf("ErrorAs(%#v,%#v) should return %t)", tt.err, target, tt.result)
3191 }
3192 })
3193 }
3194 }
3195
View as plain text