1package assert
2
3import (
4	"bytes"
5	"encoding/json"
6	"errors"
7	"fmt"
8	"io"
9	"math"
10	"os"
11	"reflect"
12	"regexp"
13	"runtime"
14	"strings"
15	"testing"
16	"time"
17)
18
19var (
20	i     interface{}
21	zeros = []interface{}{
22		false,
23		byte(0),
24		complex64(0),
25		complex128(0),
26		float32(0),
27		float64(0),
28		int(0),
29		int8(0),
30		int16(0),
31		int32(0),
32		int64(0),
33		rune(0),
34		uint(0),
35		uint8(0),
36		uint16(0),
37		uint32(0),
38		uint64(0),
39		uintptr(0),
40		"",
41		[0]interface{}{},
42		[]interface{}(nil),
43		struct{ x int }{},
44		(*interface{})(nil),
45		(func())(nil),
46		nil,
47		interface{}(nil),
48		map[interface{}]interface{}(nil),
49		(chan interface{})(nil),
50		(<-chan interface{})(nil),
51		(chan<- interface{})(nil),
52	}
53	nonZeros = []interface{}{
54		true,
55		byte(1),
56		complex64(1),
57		complex128(1),
58		float32(1),
59		float64(1),
60		int(1),
61		int8(1),
62		int16(1),
63		int32(1),
64		int64(1),
65		rune(1),
66		uint(1),
67		uint8(1),
68		uint16(1),
69		uint32(1),
70		uint64(1),
71		uintptr(1),
72		"s",
73		[1]interface{}{1},
74		[]interface{}{},
75		struct{ x int }{1},
76		(*interface{})(&i),
77		(func())(func() {}),
78		interface{}(1),
79		map[interface{}]interface{}{},
80		(chan interface{})(make(chan interface{})),
81		(<-chan interface{})(make(chan interface{})),
82		(chan<- interface{})(make(chan interface{})),
83	}
84)
85
86// AssertionTesterInterface defines an interface to be used for testing assertion methods
87type AssertionTesterInterface interface {
88	TestMethod()
89}
90
91// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface
92type AssertionTesterConformingObject struct {
93}
94
95func (a *AssertionTesterConformingObject) TestMethod() {
96}
97
98// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface
99type AssertionTesterNonConformingObject struct {
100}
101
102func TestObjectsAreEqual(t *testing.T) {
103
104	if !ObjectsAreEqual("Hello World", "Hello World") {
105		t.Error("objectsAreEqual should return true")
106	}
107	if !ObjectsAreEqual(123, 123) {
108		t.Error("objectsAreEqual should return true")
109	}
110	if !ObjectsAreEqual(123.5, 123.5) {
111		t.Error("objectsAreEqual should return true")
112	}
113	if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) {
114		t.Error("objectsAreEqual should return true")
115	}
116	if !ObjectsAreEqual(nil, nil) {
117		t.Error("objectsAreEqual should return true")
118	}
119	if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) {
120		t.Error("objectsAreEqual should return false")
121	}
122	if ObjectsAreEqual('x', "x") {
123		t.Error("objectsAreEqual should return false")
124	}
125	if ObjectsAreEqual("x", 'x') {
126		t.Error("objectsAreEqual should return false")
127	}
128	if ObjectsAreEqual(0, 0.1) {
129		t.Error("objectsAreEqual should return false")
130	}
131	if ObjectsAreEqual(0.1, 0) {
132		t.Error("objectsAreEqual should return false")
133	}
134	if ObjectsAreEqual(uint32(10), int32(10)) {
135		t.Error("objectsAreEqual should return false")
136	}
137	if !ObjectsAreEqualValues(uint32(10), int32(10)) {
138		t.Error("ObjectsAreEqualValues should return true")
139	}
140	if ObjectsAreEqualValues(0, nil) {
141		t.Fail()
142	}
143	if ObjectsAreEqualValues(nil, 0) {
144		t.Fail()
145	}
146
147}
148
149func TestImplements(t *testing.T) {
150
151	mockT := new(testing.T)
152
153	if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) {
154		t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface")
155	}
156	if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) {
157		t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface")
158	}
159	if Implements(mockT, (*AssertionTesterInterface)(nil), nil) {
160		t.Error("Implements method should return false: nil does not implement AssertionTesterInterface")
161	}
162
163}
164
165func TestIsType(t *testing.T) {
166
167	mockT := new(testing.T)
168
169	if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
170		t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject")
171	}
172	if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) {
173		t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject")
174	}
175
176}
177
178type myType string
179
180func TestEqual(t *testing.T) {
181
182	mockT := new(testing.T)
183
184	if !Equal(mockT, "Hello World", "Hello World") {
185		t.Error("Equal should return true")
186	}
187	if !Equal(mockT, 123, 123) {
188		t.Error("Equal should return true")
189	}
190	if !Equal(mockT, 123.5, 123.5) {
191		t.Error("Equal should return true")
192	}
193	if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) {
194		t.Error("Equal should return true")
195	}
196	if !Equal(mockT, nil, nil) {
197		t.Error("Equal should return true")
198	}
199	if !Equal(mockT, int32(123), int32(123)) {
200		t.Error("Equal should return true")
201	}
202	if !Equal(mockT, uint64(123), uint64(123)) {
203		t.Error("Equal should return true")
204	}
205	if !Equal(mockT, myType("1"), myType("1")) {
206		t.Error("Equal should return true")
207	}
208	if !Equal(mockT, &struct{}{}, &struct{}{}) {
209		t.Error("Equal should return true (pointer equality is based on equality of underlying value)")
210	}
211	var m map[string]interface{}
212	if Equal(mockT, m["bar"], "something") {
213		t.Error("Equal should return false")
214	}
215	if Equal(mockT, myType("1"), myType("2")) {
216		t.Error("Equal should return false")
217	}
218}
219
220func TestSame(t *testing.T) {
221
222	mockT := new(testing.T)
223
224	ptr := func(i int) *int {
225		return &i
226	}
227
228	if Same(mockT, ptr(1), ptr(1)) {
229		t.Error("Same should return false")
230	}
231	if Same(mockT, 1, 1) {
232		t.Error("Same should return false")
233	}
234	p := ptr(2)
235	if Same(mockT, p, *p) {
236		t.Error("Same should return false")
237	}
238	if !Same(mockT, p, p) {
239		t.Error("Same should return true")
240	}
241}
242
243// bufferT implements TestingT. Its implementation of Errorf writes the output that would be produced by
244// testing.T.Errorf to an internal bytes.Buffer.
245type bufferT struct {
246	buf bytes.Buffer
247}
248
249func (t *bufferT) Errorf(format string, args ...interface{}) {
250	// implementation of decorate is copied from testing.T
251	decorate := func(s string) string {
252		_, file, line, ok := runtime.Caller(3) // decorate + log + public function.
253		if ok {
254			// Truncate file name at last file name separator.
255			if index := strings.LastIndex(file, "/"); index >= 0 {
256				file = file[index+1:]
257			} else if index = strings.LastIndex(file, "\\"); index >= 0 {
258				file = file[index+1:]
259			}
260		} else {
261			file = "???"
262			line = 1
263		}
264		buf := new(bytes.Buffer)
265		// Every line is indented at least one tab.
266		buf.WriteByte('\t')
267		fmt.Fprintf(buf, "%s:%d: ", file, line)
268		lines := strings.Split(s, "\n")
269		if l := len(lines); l > 1 && lines[l-1] == "" {
270			lines = lines[:l-1]
271		}
272		for i, line := range lines {
273			if i > 0 {
274				// Second and subsequent lines are indented an extra tab.
275				buf.WriteString("\n\t\t")
276			}
277			buf.WriteString(line)
278		}
279		buf.WriteByte('\n')
280		return buf.String()
281	}
282	t.buf.WriteString(decorate(fmt.Sprintf(format, args...)))
283}
284
285func TestStringEqual(t *testing.T) {
286	for i, currCase := range []struct {
287		equalWant  string
288		equalGot   string
289		msgAndArgs []interface{}
290		want       string
291	}{
292		{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"},
293	} {
294		mockT := &bufferT{}
295		Equal(mockT, currCase.equalWant, currCase.equalGot, currCase.msgAndArgs...)
296		Regexp(t, regexp.MustCompile(currCase.want), mockT.buf.String(), "Case %d", i)
297	}
298}
299
300func TestEqualFormatting(t *testing.T) {
301	for i, currCase := range []struct {
302		equalWant  string
303		equalGot   string
304		msgAndArgs []interface{}
305		want       string
306	}{
307		{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"},
308		{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"},
309		{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"},
310		{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"},
311	} {
312		mockT := &bufferT{}
313		Equal(mockT, currCase.equalWant, currCase.equalGot, currCase.msgAndArgs...)
314		Regexp(t, regexp.MustCompile(currCase.want), mockT.buf.String(), "Case %d", i)
315	}
316}
317
318func TestFormatUnequalValues(t *testing.T) {
319	expected, actual := formatUnequalValues("foo", "bar")
320	Equal(t, `"foo"`, expected, "value should not include type")
321	Equal(t, `"bar"`, actual, "value should not include type")
322
323	expected, actual = formatUnequalValues(123, 123)
324	Equal(t, `123`, expected, "value should not include type")
325	Equal(t, `123`, actual, "value should not include type")
326
327	expected, actual = formatUnequalValues(int64(123), int32(123))
328	Equal(t, `int64(123)`, expected, "value should include type")
329	Equal(t, `int32(123)`, actual, "value should include type")
330
331	expected, actual = formatUnequalValues(int64(123), nil)
332	Equal(t, `int64(123)`, expected, "value should include type")
333	Equal(t, `<nil>(<nil>)`, actual, "value should include type")
334
335	type testStructType struct {
336		Val string
337	}
338
339	expected, actual = formatUnequalValues(&testStructType{Val: "test"}, &testStructType{Val: "test"})
340	Equal(t, `&assert.testStructType{Val:"test"}`, expected, "value should not include type annotation")
341	Equal(t, `&assert.testStructType{Val:"test"}`, actual, "value should not include type annotation")
342}
343
344func TestNotNil(t *testing.T) {
345
346	mockT := new(testing.T)
347
348	if !NotNil(mockT, new(AssertionTesterConformingObject)) {
349		t.Error("NotNil should return true: object is not nil")
350	}
351	if NotNil(mockT, nil) {
352		t.Error("NotNil should return false: object is nil")
353	}
354	if NotNil(mockT, (*struct{})(nil)) {
355		t.Error("NotNil should return false: object is (*struct{})(nil)")
356	}
357
358}
359
360func TestNil(t *testing.T) {
361
362	mockT := new(testing.T)
363
364	if !Nil(mockT, nil) {
365		t.Error("Nil should return true: object is nil")
366	}
367	if !Nil(mockT, (*struct{})(nil)) {
368		t.Error("Nil should return true: object is (*struct{})(nil)")
369	}
370	if Nil(mockT, new(AssertionTesterConformingObject)) {
371		t.Error("Nil should return false: object is not nil")
372	}
373
374}
375
376func TestTrue(t *testing.T) {
377
378	mockT := new(testing.T)
379
380	if !True(mockT, true) {
381		t.Error("True should return true")
382	}
383	if True(mockT, false) {
384		t.Error("True should return false")
385	}
386
387}
388
389func TestFalse(t *testing.T) {
390
391	mockT := new(testing.T)
392
393	if !False(mockT, false) {
394		t.Error("False should return true")
395	}
396	if False(mockT, true) {
397		t.Error("False should return false")
398	}
399
400}
401
402func TestExactly(t *testing.T) {
403
404	mockT := new(testing.T)
405
406	a := float32(1)
407	b := float64(1)
408	c := float32(1)
409	d := float32(2)
410
411	if Exactly(mockT, a, b) {
412		t.Error("Exactly should return false")
413	}
414	if Exactly(mockT, a, d) {
415		t.Error("Exactly should return false")
416	}
417	if !Exactly(mockT, a, c) {
418		t.Error("Exactly should return true")
419	}
420
421	if Exactly(mockT, nil, a) {
422		t.Error("Exactly should return false")
423	}
424	if Exactly(mockT, a, nil) {
425		t.Error("Exactly should return false")
426	}
427
428}
429
430func TestNotEqual(t *testing.T) {
431
432	mockT := new(testing.T)
433
434	if !NotEqual(mockT, "Hello World", "Hello World!") {
435		t.Error("NotEqual should return true")
436	}
437	if !NotEqual(mockT, 123, 1234) {
438		t.Error("NotEqual should return true")
439	}
440	if !NotEqual(mockT, 123.5, 123.55) {
441		t.Error("NotEqual should return true")
442	}
443	if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) {
444		t.Error("NotEqual should return true")
445	}
446	if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) {
447		t.Error("NotEqual should return true")
448	}
449	funcA := func() int { return 23 }
450	funcB := func() int { return 42 }
451	if NotEqual(mockT, funcA, funcB) {
452		t.Error("NotEqual should return false")
453	}
454
455	if NotEqual(mockT, "Hello World", "Hello World") {
456		t.Error("NotEqual should return false")
457	}
458	if NotEqual(mockT, 123, 123) {
459		t.Error("NotEqual should return false")
460	}
461	if NotEqual(mockT, 123.5, 123.5) {
462		t.Error("NotEqual should return false")
463	}
464	if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) {
465		t.Error("NotEqual should return false")
466	}
467	if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) {
468		t.Error("NotEqual should return false")
469	}
470	if NotEqual(mockT, &struct{}{}, &struct{}{}) {
471		t.Error("NotEqual should return false")
472	}
473}
474
475type A struct {
476	Name, Value string
477}
478
479func TestContains(t *testing.T) {
480
481	mockT := new(testing.T)
482	list := []string{"Foo", "Bar"}
483	complexList := []*A{
484		{"b", "c"},
485		{"d", "e"},
486		{"g", "h"},
487		{"j", "k"},
488	}
489	simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
490
491	if !Contains(mockT, "Hello World", "Hello") {
492		t.Error("Contains should return true: \"Hello World\" contains \"Hello\"")
493	}
494	if Contains(mockT, "Hello World", "Salut") {
495		t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"")
496	}
497
498	if !Contains(mockT, list, "Bar") {
499		t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"")
500	}
501	if Contains(mockT, list, "Salut") {
502		t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"")
503	}
504	if !Contains(mockT, complexList, &A{"g", "h"}) {
505		t.Error("Contains should return true: complexList contains {\"g\", \"h\"}")
506	}
507	if Contains(mockT, complexList, &A{"g", "e"}) {
508		t.Error("Contains should return false: complexList contains {\"g\", \"e\"}")
509	}
510	if Contains(mockT, complexList, &A{"g", "e"}) {
511		t.Error("Contains should return false: complexList contains {\"g\", \"e\"}")
512	}
513	if !Contains(mockT, simpleMap, "Foo") {
514		t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"")
515	}
516	if Contains(mockT, simpleMap, "Bar") {
517		t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"")
518	}
519}
520
521func TestNotContains(t *testing.T) {
522
523	mockT := new(testing.T)
524	list := []string{"Foo", "Bar"}
525	simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
526
527	if !NotContains(mockT, "Hello World", "Hello!") {
528		t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"")
529	}
530	if NotContains(mockT, "Hello World", "Hello") {
531		t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"")
532	}
533
534	if !NotContains(mockT, list, "Foo!") {
535		t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"")
536	}
537	if NotContains(mockT, list, "Foo") {
538		t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"")
539	}
540	if NotContains(mockT, simpleMap, "Foo") {
541		t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"")
542	}
543	if !NotContains(mockT, simpleMap, "Bar") {
544		t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"")
545	}
546}
547
548func TestSubset(t *testing.T) {
549	mockT := new(testing.T)
550
551	if !Subset(mockT, []int{1, 2, 3}, nil) {
552		t.Error("Subset should return true: given subset is nil")
553	}
554	if !Subset(mockT, []int{1, 2, 3}, []int{}) {
555		t.Error("Subset should return true: any set contains the nil set")
556	}
557	if !Subset(mockT, []int{1, 2, 3}, []int{1, 2}) {
558		t.Error("Subset should return true: [1, 2, 3] contains [1, 2]")
559	}
560	if !Subset(mockT, []int{1, 2, 3}, []int{1, 2, 3}) {
561		t.Error("Subset should return true: [1, 2, 3] contains [1, 2, 3]")
562	}
563	if !Subset(mockT, []string{"hello", "world"}, []string{"hello"}) {
564		t.Error("Subset should return true: [\"hello\", \"world\"] contains [\"hello\"]")
565	}
566
567	if Subset(mockT, []string{"hello", "world"}, []string{"hello", "testify"}) {
568		t.Error("Subset should return false: [\"hello\", \"world\"] does not contain [\"hello\", \"testify\"]")
569	}
570	if Subset(mockT, []int{1, 2, 3}, []int{4, 5}) {
571		t.Error("Subset should return false: [1, 2, 3] does not contain [4, 5]")
572	}
573	if Subset(mockT, []int{1, 2, 3}, []int{1, 5}) {
574		t.Error("Subset should return false: [1, 2, 3] does not contain [1, 5]")
575	}
576}
577
578func TestNotSubset(t *testing.T) {
579	mockT := new(testing.T)
580
581	if NotSubset(mockT, []int{1, 2, 3}, nil) {
582		t.Error("NotSubset should return false: given subset is nil")
583	}
584	if NotSubset(mockT, []int{1, 2, 3}, []int{}) {
585		t.Error("NotSubset should return false: any set contains the nil set")
586	}
587	if NotSubset(mockT, []int{1, 2, 3}, []int{1, 2}) {
588		t.Error("NotSubset should return false: [1, 2, 3] contains [1, 2]")
589	}
590	if NotSubset(mockT, []int{1, 2, 3}, []int{1, 2, 3}) {
591		t.Error("NotSubset should return false: [1, 2, 3] contains [1, 2, 3]")
592	}
593	if NotSubset(mockT, []string{"hello", "world"}, []string{"hello"}) {
594		t.Error("NotSubset should return false: [\"hello\", \"world\"] contains [\"hello\"]")
595	}
596
597	if !NotSubset(mockT, []string{"hello", "world"}, []string{"hello", "testify"}) {
598		t.Error("NotSubset should return true: [\"hello\", \"world\"] does not contain [\"hello\", \"testify\"]")
599	}
600	if !NotSubset(mockT, []int{1, 2, 3}, []int{4, 5}) {
601		t.Error("NotSubset should return true: [1, 2, 3] does not contain [4, 5]")
602	}
603	if !NotSubset(mockT, []int{1, 2, 3}, []int{1, 5}) {
604		t.Error("NotSubset should return true: [1, 2, 3] does not contain [1, 5]")
605	}
606}
607
608func TestNotSubsetNil(t *testing.T) {
609	mockT := new(testing.T)
610	NotSubset(mockT, []string{"foo"}, nil)
611	if !mockT.Failed() {
612		t.Error("NotSubset on nil set should have failed the test")
613	}
614}
615
616func Test_includeElement(t *testing.T) {
617
618	list1 := []string{"Foo", "Bar"}
619	list2 := []int{1, 2}
620	simpleMap := map[interface{}]interface{}{"Foo": "Bar"}
621
622	ok, found := includeElement("Hello World", "World")
623	True(t, ok)
624	True(t, found)
625
626	ok, found = includeElement(list1, "Foo")
627	True(t, ok)
628	True(t, found)
629
630	ok, found = includeElement(list1, "Bar")
631	True(t, ok)
632	True(t, found)
633
634	ok, found = includeElement(list2, 1)
635	True(t, ok)
636	True(t, found)
637
638	ok, found = includeElement(list2, 2)
639	True(t, ok)
640	True(t, found)
641
642	ok, found = includeElement(list1, "Foo!")
643	True(t, ok)
644	False(t, found)
645
646	ok, found = includeElement(list2, 3)
647	True(t, ok)
648	False(t, found)
649
650	ok, found = includeElement(list2, "1")
651	True(t, ok)
652	False(t, found)
653
654	ok, found = includeElement(simpleMap, "Foo")
655	True(t, ok)
656	True(t, found)
657
658	ok, found = includeElement(simpleMap, "Bar")
659	True(t, ok)
660	False(t, found)
661
662	ok, found = includeElement(1433, "1")
663	False(t, ok)
664	False(t, found)
665}
666
667func TestElementsMatch(t *testing.T) {
668	mockT := new(testing.T)
669
670	if !ElementsMatch(mockT, nil, nil) {
671		t.Error("ElementsMatch should return true")
672	}
673	if !ElementsMatch(mockT, []int{}, []int{}) {
674		t.Error("ElementsMatch should return true")
675	}
676	if !ElementsMatch(mockT, []int{1}, []int{1}) {
677		t.Error("ElementsMatch should return true")
678	}
679	if !ElementsMatch(mockT, []int{1, 1}, []int{1, 1}) {
680		t.Error("ElementsMatch should return true")
681	}
682	if !ElementsMatch(mockT, []int{1, 2}, []int{1, 2}) {
683		t.Error("ElementsMatch should return true")
684	}
685	if !ElementsMatch(mockT, []int{1, 2}, []int{2, 1}) {
686		t.Error("ElementsMatch should return true")
687	}
688	if !ElementsMatch(mockT, [2]int{1, 2}, [2]int{2, 1}) {
689		t.Error("ElementsMatch should return true")
690	}
691	if !ElementsMatch(mockT, []string{"hello", "world"}, []string{"world", "hello"}) {
692		t.Error("ElementsMatch should return true")
693	}
694	if !ElementsMatch(mockT, []string{"hello", "hello"}, []string{"hello", "hello"}) {
695		t.Error("ElementsMatch should return true")
696	}
697	if !ElementsMatch(mockT, []string{"hello", "hello", "world"}, []string{"hello", "world", "hello"}) {
698		t.Error("ElementsMatch should return true")
699	}
700	if !ElementsMatch(mockT, [3]string{"hello", "hello", "world"}, [3]string{"hello", "world", "hello"}) {
701		t.Error("ElementsMatch should return true")
702	}
703	if !ElementsMatch(mockT, []int{}, nil) {
704		t.Error("ElementsMatch should return true")
705	}
706
707	if ElementsMatch(mockT, []int{1}, []int{1, 1}) {
708		t.Error("ElementsMatch should return false")
709	}
710	if ElementsMatch(mockT, []int{1, 2}, []int{2, 2}) {
711		t.Error("ElementsMatch should return false")
712	}
713	if ElementsMatch(mockT, []string{"hello", "hello"}, []string{"hello"}) {
714		t.Error("ElementsMatch should return false")
715	}
716}
717
718func TestCondition(t *testing.T) {
719	mockT := new(testing.T)
720
721	if !Condition(mockT, func() bool { return true }, "Truth") {
722		t.Error("Condition should return true")
723	}
724
725	if Condition(mockT, func() bool { return false }, "Lie") {
726		t.Error("Condition should return false")
727	}
728
729}
730
731func TestDidPanic(t *testing.T) {
732
733	if funcDidPanic, _ := didPanic(func() {
734		panic("Panic!")
735	}); !funcDidPanic {
736		t.Error("didPanic should return true")
737	}
738
739	if funcDidPanic, _ := didPanic(func() {
740	}); funcDidPanic {
741		t.Error("didPanic should return false")
742	}
743
744}
745
746func TestPanics(t *testing.T) {
747
748	mockT := new(testing.T)
749
750	if !Panics(mockT, func() {
751		panic("Panic!")
752	}) {
753		t.Error("Panics should return true")
754	}
755
756	if Panics(mockT, func() {
757	}) {
758		t.Error("Panics should return false")
759	}
760
761}
762
763func TestPanicsWithValue(t *testing.T) {
764
765	mockT := new(testing.T)
766
767	if !PanicsWithValue(mockT, "Panic!", func() {
768		panic("Panic!")
769	}) {
770		t.Error("PanicsWithValue should return true")
771	}
772
773	if PanicsWithValue(mockT, "Panic!", func() {
774	}) {
775		t.Error("PanicsWithValue should return false")
776	}
777
778	if PanicsWithValue(mockT, "at the disco", func() {
779		panic("Panic!")
780	}) {
781		t.Error("PanicsWithValue should return false")
782	}
783}
784
785func TestNotPanics(t *testing.T) {
786
787	mockT := new(testing.T)
788
789	if !NotPanics(mockT, func() {
790	}) {
791		t.Error("NotPanics should return true")
792	}
793
794	if NotPanics(mockT, func() {
795		panic("Panic!")
796	}) {
797		t.Error("NotPanics should return false")
798	}
799
800}
801
802func TestNoError(t *testing.T) {
803
804	mockT := new(testing.T)
805
806	// start with a nil error
807	var err error
808
809	True(t, NoError(mockT, err), "NoError should return True for nil arg")
810
811	// now set an error
812	err = errors.New("some error")
813
814	False(t, NoError(mockT, err), "NoError with error should return False")
815
816	// returning an empty error interface
817	err = func() error {
818		var err *customError
819		if err != nil {
820			t.Fatal("err should be nil here")
821		}
822		return err
823	}()
824
825	if err == nil { // err is not nil here!
826		t.Errorf("Error should be nil due to empty interface: %s", err)
827	}
828
829	False(t, NoError(mockT, err), "NoError should fail with empty error interface")
830}
831
832type customError struct{}
833
834func (*customError) Error() string { return "fail" }
835
836func TestError(t *testing.T) {
837
838	mockT := new(testing.T)
839
840	// start with a nil error
841	var err error
842
843	False(t, Error(mockT, err), "Error should return False for nil arg")
844
845	// now set an error
846	err = errors.New("some error")
847
848	True(t, Error(mockT, err), "Error with error should return True")
849
850	// go vet check
851	True(t, Errorf(mockT, err, "example with %s", "formatted message"), "Errorf with error should rturn True")
852
853	// returning an empty error interface
854	err = func() error {
855		var err *customError
856		if err != nil {
857			t.Fatal("err should be nil here")
858		}
859		return err
860	}()
861
862	if err == nil { // err is not nil here!
863		t.Errorf("Error should be nil due to empty interface: %s", err)
864	}
865
866	True(t, Error(mockT, err), "Error should pass with empty error interface")
867}
868
869func TestEqualError(t *testing.T) {
870	mockT := new(testing.T)
871
872	// start with a nil error
873	var err error
874	False(t, EqualError(mockT, err, ""),
875		"EqualError should return false for nil arg")
876
877	// now set an error
878	err = errors.New("some error")
879	False(t, EqualError(mockT, err, "Not some error"),
880		"EqualError should return false for different error string")
881	True(t, EqualError(mockT, err, "some error"),
882		"EqualError should return true")
883}
884
885func Test_isEmpty(t *testing.T) {
886
887	chWithValue := make(chan struct{}, 1)
888	chWithValue <- struct{}{}
889
890	True(t, isEmpty(""))
891	True(t, isEmpty(nil))
892	True(t, isEmpty([]string{}))
893	True(t, isEmpty(0))
894	True(t, isEmpty(int32(0)))
895	True(t, isEmpty(int64(0)))
896	True(t, isEmpty(false))
897	True(t, isEmpty(map[string]string{}))
898	True(t, isEmpty(new(time.Time)))
899	True(t, isEmpty(time.Time{}))
900	True(t, isEmpty(make(chan struct{})))
901	False(t, isEmpty("something"))
902	False(t, isEmpty(errors.New("something")))
903	False(t, isEmpty([]string{"something"}))
904	False(t, isEmpty(1))
905	False(t, isEmpty(true))
906	False(t, isEmpty(map[string]string{"Hello": "World"}))
907	False(t, isEmpty(chWithValue))
908
909}
910
911func TestEmpty(t *testing.T) {
912
913	mockT := new(testing.T)
914	chWithValue := make(chan struct{}, 1)
915	chWithValue <- struct{}{}
916	var tiP *time.Time
917	var tiNP time.Time
918	var s *string
919	var f *os.File
920	sP := &s
921	x := 1
922	xP := &x
923
924	type TString string
925	type TStruct struct {
926		x int
927		s []int
928	}
929
930	True(t, Empty(mockT, ""), "Empty string is empty")
931	True(t, Empty(mockT, nil), "Nil is empty")
932	True(t, Empty(mockT, []string{}), "Empty string array is empty")
933	True(t, Empty(mockT, 0), "Zero int value is empty")
934	True(t, Empty(mockT, false), "False value is empty")
935	True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty")
936	True(t, Empty(mockT, s), "Nil string pointer is empty")
937	True(t, Empty(mockT, f), "Nil os.File pointer is empty")
938	True(t, Empty(mockT, tiP), "Nil time.Time pointer is empty")
939	True(t, Empty(mockT, tiNP), "time.Time is empty")
940	True(t, Empty(mockT, TStruct{}), "struct with zero values is empty")
941	True(t, Empty(mockT, TString("")), "empty aliased string is empty")
942	True(t, Empty(mockT, sP), "ptr to nil value is empty")
943
944	False(t, Empty(mockT, "something"), "Non Empty string is not empty")
945	False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty")
946	False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty")
947	False(t, Empty(mockT, 1), "Non-zero int value is not empty")
948	False(t, Empty(mockT, true), "True value is not empty")
949	False(t, Empty(mockT, chWithValue), "Channel with values is not empty")
950	False(t, Empty(mockT, TStruct{x: 1}), "struct with initialized values is empty")
951	False(t, Empty(mockT, TString("abc")), "non-empty aliased string is empty")
952	False(t, Empty(mockT, xP), "ptr to non-nil value is not empty")
953}
954
955func TestNotEmpty(t *testing.T) {
956
957	mockT := new(testing.T)
958	chWithValue := make(chan struct{}, 1)
959	chWithValue <- struct{}{}
960
961	False(t, NotEmpty(mockT, ""), "Empty string is empty")
962	False(t, NotEmpty(mockT, nil), "Nil is empty")
963	False(t, NotEmpty(mockT, []string{}), "Empty string array is empty")
964	False(t, NotEmpty(mockT, 0), "Zero int value is empty")
965	False(t, NotEmpty(mockT, false), "False value is empty")
966	False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty")
967
968	True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty")
969	True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty")
970	True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty")
971	True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty")
972	True(t, NotEmpty(mockT, true), "True value is not empty")
973	True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty")
974}
975
976func Test_getLen(t *testing.T) {
977	falseCases := []interface{}{
978		nil,
979		0,
980		true,
981		false,
982		'A',
983		struct{}{},
984	}
985	for _, v := range falseCases {
986		ok, l := getLen(v)
987		False(t, ok, "Expected getLen fail to get length of %#v", v)
988		Equal(t, 0, l, "getLen should return 0 for %#v", v)
989	}
990
991	ch := make(chan int, 5)
992	ch <- 1
993	ch <- 2
994	ch <- 3
995	trueCases := []struct {
996		v interface{}
997		l int
998	}{
999		{[]int{1, 2, 3}, 3},
1000		{[...]int{1, 2, 3}, 3},
1001		{"ABC", 3},
1002		{map[int]int{1: 2, 2: 4, 3: 6}, 3},
1003		{ch, 3},
1004
1005		{[]int{}, 0},
1006		{map[int]int{}, 0},
1007		{make(chan int), 0},
1008
1009		{[]int(nil), 0},
1010		{map[int]int(nil), 0},
1011		{(chan int)(nil), 0},
1012	}
1013
1014	for _, c := range trueCases {
1015		ok, l := getLen(c.v)
1016		True(t, ok, "Expected getLen success to get length of %#v", c.v)
1017		Equal(t, c.l, l)
1018	}
1019}
1020
1021func TestLen(t *testing.T) {
1022	mockT := new(testing.T)
1023
1024	False(t, Len(mockT, nil, 0), "nil does not have length")
1025	False(t, Len(mockT, 0, 0), "int does not have length")
1026	False(t, Len(mockT, true, 0), "true does not have length")
1027	False(t, Len(mockT, false, 0), "false does not have length")
1028	False(t, Len(mockT, 'A', 0), "Rune does not have length")
1029	False(t, Len(mockT, struct{}{}, 0), "Struct does not have length")
1030
1031	ch := make(chan int, 5)
1032	ch <- 1
1033	ch <- 2
1034	ch <- 3
1035
1036	cases := []struct {
1037		v interface{}
1038		l int
1039	}{
1040		{[]int{1, 2, 3}, 3},
1041		{[...]int{1, 2, 3}, 3},
1042		{"ABC", 3},
1043		{map[int]int{1: 2, 2: 4, 3: 6}, 3},
1044		{ch, 3},
1045
1046		{[]int{}, 0},
1047		{map[int]int{}, 0},
1048		{make(chan int), 0},
1049
1050		{[]int(nil), 0},
1051		{map[int]int(nil), 0},
1052		{(chan int)(nil), 0},
1053	}
1054
1055	for _, c := range cases {
1056		True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
1057	}
1058
1059	cases = []struct {
1060		v interface{}
1061		l int
1062	}{
1063		{[]int{1, 2, 3}, 4},
1064		{[...]int{1, 2, 3}, 2},
1065		{"ABC", 2},
1066		{map[int]int{1: 2, 2: 4, 3: 6}, 4},
1067		{ch, 2},
1068
1069		{[]int{}, 1},
1070		{map[int]int{}, 1},
1071		{make(chan int), 1},
1072
1073		{[]int(nil), 1},
1074		{map[int]int(nil), 1},
1075		{(chan int)(nil), 1},
1076	}
1077
1078	for _, c := range cases {
1079		False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l)
1080	}
1081}
1082
1083func TestWithinDuration(t *testing.T) {
1084
1085	mockT := new(testing.T)
1086	a := time.Now()
1087	b := a.Add(10 * time.Second)
1088
1089	True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference")
1090	True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference")
1091
1092	False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference")
1093	False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference")
1094
1095	False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference")
1096	False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference")
1097
1098	False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference")
1099	False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference")
1100}
1101
1102func TestInDelta(t *testing.T) {
1103	mockT := new(testing.T)
1104
1105	True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01")
1106	True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01")
1107	True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1")
1108	False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail")
1109	False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail")
1110	False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail")
1111	False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail")
1112	False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail")
1113
1114	cases := []struct {
1115		a, b  interface{}
1116		delta float64
1117	}{
1118		{uint8(2), uint8(1), 1},
1119		{uint16(2), uint16(1), 1},
1120		{uint32(2), uint32(1), 1},
1121		{uint64(2), uint64(1), 1},
1122
1123		{int(2), int(1), 1},
1124		{int8(2), int8(1), 1},
1125		{int16(2), int16(1), 1},
1126		{int32(2), int32(1), 1},
1127		{int64(2), int64(1), 1},
1128
1129		{float32(2), float32(1), 1},
1130		{float64(2), float64(1), 1},
1131	}
1132
1133	for _, tc := range cases {
1134		True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta)
1135	}
1136}
1137
1138func TestInDeltaSlice(t *testing.T) {
1139	mockT := new(testing.T)
1140
1141	True(t, InDeltaSlice(mockT,
1142		[]float64{1.001, 0.999},
1143		[]float64{1, 1},
1144		0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1")
1145
1146	True(t, InDeltaSlice(mockT,
1147		[]float64{1, 2},
1148		[]float64{0, 3},
1149		1), "{1, 2} is element-wise close to {0, 3} in delta=1")
1150
1151	False(t, InDeltaSlice(mockT,
1152		[]float64{1, 2},
1153		[]float64{0, 3},
1154		0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1")
1155
1156	False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
1157}
1158
1159func TestInDeltaMapValues(t *testing.T) {
1160	mockT := new(testing.T)
1161
1162	for _, tc := range []struct {
1163		title  string
1164		expect interface{}
1165		actual interface{}
1166		f      func(TestingT, bool, ...interface{}) bool
1167		delta  float64
1168	}{
1169		{
1170			title: "Within delta",
1171			expect: map[string]float64{
1172				"foo": 1.0,
1173				"bar": 2.0,
1174			},
1175			actual: map[string]float64{
1176				"foo": 1.01,
1177				"bar": 1.99,
1178			},
1179			delta: 0.1,
1180			f:     True,
1181		},
1182		{
1183			title: "Within delta",
1184			expect: map[int]float64{
1185				1: 1.0,
1186				2: 2.0,
1187			},
1188			actual: map[int]float64{
1189				1: 1.0,
1190				2: 1.99,
1191			},
1192			delta: 0.1,
1193			f:     True,
1194		},
1195		{
1196			title: "Different number of keys",
1197			expect: map[int]float64{
1198				1: 1.0,
1199				2: 2.0,
1200			},
1201			actual: map[int]float64{
1202				1: 1.0,
1203			},
1204			delta: 0.1,
1205			f:     False,
1206		},
1207		{
1208			title: "Within delta with zero value",
1209			expect: map[string]float64{
1210				"zero": 0.0,
1211			},
1212			actual: map[string]float64{
1213				"zero": 0.0,
1214			},
1215			delta: 0.1,
1216			f:     True,
1217		},
1218		{
1219			title: "With missing key with zero value",
1220			expect: map[string]float64{
1221				"zero": 0.0,
1222				"foo":  0.0,
1223			},
1224			actual: map[string]float64{
1225				"zero": 0.0,
1226				"bar":  0.0,
1227			},
1228			f: False,
1229		},
1230	} {
1231		tc.f(t, InDeltaMapValues(mockT, tc.expect, tc.actual, tc.delta), tc.title+"\n"+diff(tc.expect, tc.actual))
1232	}
1233}
1234
1235func TestInEpsilon(t *testing.T) {
1236	mockT := new(testing.T)
1237
1238	cases := []struct {
1239		a, b    interface{}
1240		epsilon float64
1241	}{
1242		{uint8(2), uint16(2), .001},
1243		{2.1, 2.2, 0.1},
1244		{2.2, 2.1, 0.1},
1245		{-2.1, -2.2, 0.1},
1246		{-2.2, -2.1, 0.1},
1247		{uint64(100), uint8(101), 0.01},
1248		{0.1, -0.1, 2},
1249		{0.1, 0, 2},
1250		{time.Second, time.Second + time.Millisecond, 0.002},
1251	}
1252
1253	for _, tc := range cases {
1254		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)
1255	}
1256
1257	cases = []struct {
1258		a, b    interface{}
1259		epsilon float64
1260	}{
1261		{uint8(2), int16(-2), .001},
1262		{uint64(100), uint8(102), 0.01},
1263		{2.1, 2.2, 0.001},
1264		{2.2, 2.1, 0.001},
1265		{2.1, -2.2, 1},
1266		{2.1, "bla-bla", 0},
1267		{0.1, -0.1, 1.99},
1268		{0, 0.1, 2}, // expected must be different to zero
1269		{time.Second, time.Second + 10*time.Millisecond, 0.002},
1270	}
1271
1272	for _, tc := range cases {
1273		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))
1274	}
1275
1276}
1277
1278func TestInEpsilonSlice(t *testing.T) {
1279	mockT := new(testing.T)
1280
1281	True(t, InEpsilonSlice(mockT,
1282		[]float64{2.2, 2.0},
1283		[]float64{2.1, 2.1},
1284		0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06")
1285
1286	False(t, InEpsilonSlice(mockT,
1287		[]float64{2.2, 2.0},
1288		[]float64{2.1, 2.1},
1289		0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04")
1290
1291	False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail")
1292}
1293
1294func TestRegexp(t *testing.T) {
1295	mockT := new(testing.T)
1296
1297	cases := []struct {
1298		rx, str string
1299	}{
1300		{"^start", "start of the line"},
1301		{"end$", "in the end"},
1302		{"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"},
1303	}
1304
1305	for _, tc := range cases {
1306		True(t, Regexp(mockT, tc.rx, tc.str))
1307		True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
1308		False(t, NotRegexp(mockT, tc.rx, tc.str))
1309		False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
1310	}
1311
1312	cases = []struct {
1313		rx, str string
1314	}{
1315		{"^asdfastart", "Not the start of the line"},
1316		{"end$", "in the end."},
1317		{"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"},
1318	}
1319
1320	for _, tc := range cases {
1321		False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str)
1322		False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str))
1323		True(t, NotRegexp(mockT, tc.rx, tc.str))
1324		True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str))
1325	}
1326}
1327
1328func testAutogeneratedFunction() {
1329	defer func() {
1330		if err := recover(); err == nil {
1331			panic("did not panic")
1332		}
1333		CallerInfo()
1334	}()
1335	t := struct {
1336		io.Closer
1337	}{}
1338	var c io.Closer
1339	c = t
1340	c.Close()
1341}
1342
1343func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) {
1344	NotPanics(t, func() {
1345		testAutogeneratedFunction()
1346	})
1347}
1348
1349func TestZero(t *testing.T) {
1350	mockT := new(testing.T)
1351
1352	for _, test := range zeros {
1353		True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
1354	}
1355
1356	for _, test := range nonZeros {
1357		False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
1358	}
1359}
1360
1361func TestNotZero(t *testing.T) {
1362	mockT := new(testing.T)
1363
1364	for _, test := range zeros {
1365		False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
1366	}
1367
1368	for _, test := range nonZeros {
1369		True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test)))
1370	}
1371}
1372
1373func TestFileExists(t *testing.T) {
1374	mockT := new(testing.T)
1375	True(t, FileExists(mockT, "assertions.go"))
1376
1377	mockT = new(testing.T)
1378	False(t, FileExists(mockT, "random_file"))
1379
1380	mockT = new(testing.T)
1381	False(t, FileExists(mockT, "../_codegen"))
1382}
1383
1384func TestDirExists(t *testing.T) {
1385	mockT := new(testing.T)
1386	False(t, DirExists(mockT, "assertions.go"))
1387
1388	mockT = new(testing.T)
1389	False(t, DirExists(mockT, "random_dir"))
1390
1391	mockT = new(testing.T)
1392	True(t, DirExists(mockT, "../_codegen"))
1393}
1394
1395func TestJSONEq_EqualSONString(t *testing.T) {
1396	mockT := new(testing.T)
1397	True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`))
1398}
1399
1400func TestJSONEq_EquivalentButNotEqual(t *testing.T) {
1401	mockT := new(testing.T)
1402	True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
1403}
1404
1405func TestJSONEq_HashOfArraysAndHashes(t *testing.T) {
1406	mockT := new(testing.T)
1407	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}",
1408		"{\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}"))
1409}
1410
1411func TestJSONEq_Array(t *testing.T) {
1412	mockT := new(testing.T)
1413	True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`))
1414}
1415
1416func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) {
1417	mockT := new(testing.T)
1418	False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`))
1419}
1420
1421func TestJSONEq_HashesNotEquivalent(t *testing.T) {
1422	mockT := new(testing.T)
1423	False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
1424}
1425
1426func TestJSONEq_ActualIsNotJSON(t *testing.T) {
1427	mockT := new(testing.T)
1428	False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON"))
1429}
1430
1431func TestJSONEq_ExpectedIsNotJSON(t *testing.T) {
1432	mockT := new(testing.T)
1433	False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`))
1434}
1435
1436func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) {
1437	mockT := new(testing.T)
1438	False(t, JSONEq(mockT, "Not JSON", "Not JSON"))
1439}
1440
1441func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) {
1442	mockT := new(testing.T)
1443	False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`))
1444}
1445
1446func TestYAMLEq_EqualYAMLString(t *testing.T) {
1447	mockT := new(testing.T)
1448	True(t, YAMLEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`))
1449}
1450
1451func TestYAMLEq_EquivalentButNotEqual(t *testing.T) {
1452	mockT := new(testing.T)
1453	True(t, YAMLEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
1454}
1455
1456func TestYAMLEq_HashOfArraysAndHashes(t *testing.T) {
1457	mockT := new(testing.T)
1458	expected := `
1459numeric: 1.5
1460array:
1461  - foo: bar
1462  - 1
1463  - "string"
1464  - ["nested", "array", 5.5]
1465hash:
1466  nested: hash
1467  nested_slice: [this, is, nested]
1468string: "foo"
1469`
1470
1471	actual := `
1472numeric: 1.5
1473hash:
1474  nested: hash
1475  nested_slice: [this, is, nested]
1476string: "foo"
1477array:
1478  - foo: bar
1479  - 1
1480  - "string"
1481  - ["nested", "array", 5.5]
1482`
1483	True(t, YAMLEq(mockT, expected, actual))
1484}
1485
1486func TestYAMLEq_Array(t *testing.T) {
1487	mockT := new(testing.T)
1488	True(t, YAMLEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`))
1489}
1490
1491func TestYAMLEq_HashAndArrayNotEquivalent(t *testing.T) {
1492	mockT := new(testing.T)
1493	False(t, YAMLEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`))
1494}
1495
1496func TestYAMLEq_HashesNotEquivalent(t *testing.T) {
1497	mockT := new(testing.T)
1498	False(t, YAMLEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`))
1499}
1500
1501func TestYAMLEq_ActualIsSimpleString(t *testing.T) {
1502	mockT := new(testing.T)
1503	False(t, YAMLEq(mockT, `{"foo": "bar"}`, "Simple String"))
1504}
1505
1506func TestYAMLEq_ExpectedIsSimpleString(t *testing.T) {
1507	mockT := new(testing.T)
1508	False(t, YAMLEq(mockT, "Simple String", `{"foo": "bar", "hello": "world"}`))
1509}
1510
1511func TestYAMLEq_ExpectedAndActualSimpleString(t *testing.T) {
1512	mockT := new(testing.T)
1513	True(t, YAMLEq(mockT, "Simple String", "Simple String"))
1514}
1515
1516func TestYAMLEq_ArraysOfDifferentOrder(t *testing.T) {
1517	mockT := new(testing.T)
1518	False(t, YAMLEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`))
1519}
1520
1521func TestDiff(t *testing.T) {
1522	expected := `
1523
1524Diff:
1525--- Expected
1526+++ Actual
1527@@ -1,3 +1,3 @@
1528 (struct { foo string }) {
1529- foo: (string) (len=5) "hello"
1530+ foo: (string) (len=3) "bar"
1531 }
1532`
1533	actual := diff(
1534		struct{ foo string }{"hello"},
1535		struct{ foo string }{"bar"},
1536	)
1537	Equal(t, expected, actual)
1538
1539	expected = `
1540
1541Diff:
1542--- Expected
1543+++ Actual
1544@@ -2,5 +2,5 @@
1545  (int) 1,
1546- (int) 2,
1547  (int) 3,
1548- (int) 4
1549+ (int) 5,
1550+ (int) 7
1551 }
1552`
1553	actual = diff(
1554		[]int{1, 2, 3, 4},
1555		[]int{1, 3, 5, 7},
1556	)
1557	Equal(t, expected, actual)
1558
1559	expected = `
1560
1561Diff:
1562--- Expected
1563+++ Actual
1564@@ -2,4 +2,4 @@
1565  (int) 1,
1566- (int) 2,
1567- (int) 3
1568+ (int) 3,
1569+ (int) 5
1570 }
1571`
1572	actual = diff(
1573		[]int{1, 2, 3, 4}[0:3],
1574		[]int{1, 3, 5, 7}[0:3],
1575	)
1576	Equal(t, expected, actual)
1577
1578	expected = `
1579
1580Diff:
1581--- Expected
1582+++ Actual
1583@@ -1,6 +1,6 @@
1584 (map[string]int) (len=4) {
1585- (string) (len=4) "four": (int) 4,
1586+ (string) (len=4) "five": (int) 5,
1587  (string) (len=3) "one": (int) 1,
1588- (string) (len=5) "three": (int) 3,
1589- (string) (len=3) "two": (int) 2
1590+ (string) (len=5) "seven": (int) 7,
1591+ (string) (len=5) "three": (int) 3
1592 }
1593`
1594
1595	actual = diff(
1596		map[string]int{"one": 1, "two": 2, "three": 3, "four": 4},
1597		map[string]int{"one": 1, "three": 3, "five": 5, "seven": 7},
1598	)
1599	Equal(t, expected, actual)
1600}
1601
1602func TestDiffEmptyCases(t *testing.T) {
1603	Equal(t, "", diff(nil, nil))
1604	Equal(t, "", diff(struct{ foo string }{}, nil))
1605	Equal(t, "", diff(nil, struct{ foo string }{}))
1606	Equal(t, "", diff(1, 2))
1607	Equal(t, "", diff(1, 2))
1608	Equal(t, "", diff([]int{1}, []bool{true}))
1609}
1610
1611// Ensure there are no data races
1612func TestDiffRace(t *testing.T) {
1613	t.Parallel()
1614
1615	expected := map[string]string{
1616		"a": "A",
1617		"b": "B",
1618		"c": "C",
1619	}
1620
1621	actual := map[string]string{
1622		"d": "D",
1623		"e": "E",
1624		"f": "F",
1625	}
1626
1627	// run diffs in parallel simulating tests with t.Parallel()
1628	numRoutines := 10
1629	rChans := make([]chan string, numRoutines)
1630	for idx := range rChans {
1631		rChans[idx] = make(chan string)
1632		go func(ch chan string) {
1633			defer close(ch)
1634			ch <- diff(expected, actual)
1635		}(rChans[idx])
1636	}
1637
1638	for _, ch := range rChans {
1639		for msg := range ch {
1640			NotZero(t, msg) // dummy assert
1641		}
1642	}
1643}
1644
1645type mockTestingT struct {
1646}
1647
1648func (m *mockTestingT) Errorf(format string, args ...interface{}) {}
1649
1650func TestFailNowWithPlainTestingT(t *testing.T) {
1651	mockT := &mockTestingT{}
1652
1653	Panics(t, func() {
1654		FailNow(mockT, "failed")
1655	}, "should panic since mockT is missing FailNow()")
1656}
1657
1658type mockFailNowTestingT struct {
1659}
1660
1661func (m *mockFailNowTestingT) Errorf(format string, args ...interface{}) {}
1662
1663func (m *mockFailNowTestingT) FailNow() {}
1664
1665func TestFailNowWithFullTestingT(t *testing.T) {
1666	mockT := &mockFailNowTestingT{}
1667
1668	NotPanics(t, func() {
1669		FailNow(mockT, "failed")
1670	}, "should call mockT.FailNow() rather than panicking")
1671}
1672
1673func TestBytesEqual(t *testing.T) {
1674	var cases = []struct {
1675		a, b []byte
1676	}{
1677		{make([]byte, 2), make([]byte, 2)},
1678		{make([]byte, 2), make([]byte, 2, 3)},
1679		{nil, make([]byte, 0)},
1680	}
1681	for i, c := range cases {
1682		Equal(t, reflect.DeepEqual(c.a, c.b), ObjectsAreEqual(c.a, c.b), "case %d failed", i+1)
1683	}
1684}
1685
1686func BenchmarkBytesEqual(b *testing.B) {
1687	const size = 1024 * 8
1688	s := make([]byte, size)
1689	for i := range s {
1690		s[i] = byte(i % 255)
1691	}
1692	s2 := make([]byte, size)
1693	copy(s2, s)
1694
1695	mockT := &mockFailNowTestingT{}
1696	b.ResetTimer()
1697	for i := 0; i < b.N; i++ {
1698		Equal(mockT, s, s2)
1699	}
1700}
1701
1702func TestEqualArgsValidation(t *testing.T) {
1703	err := validateEqualArgs(time.Now, time.Now)
1704	EqualError(t, err, "cannot take func type as argument")
1705}
1706
1707func ExampleComparisonAssertionFunc() {
1708	t := &testing.T{} // provided by test
1709
1710	adder := func(x, y int) int {
1711		return x + y
1712	}
1713
1714	type args struct {
1715		x int
1716		y int
1717	}
1718
1719	tests := []struct {
1720		name      string
1721		args      args
1722		expect    int
1723		assertion ComparisonAssertionFunc
1724	}{
1725		{"2+2=4", args{2, 2}, 4, Equal},
1726		{"2+2!=5", args{2, 2}, 5, NotEqual},
1727		{"2+3==5", args{2, 3}, 5, Exactly},
1728	}
1729
1730	for _, tt := range tests {
1731		t.Run(tt.name, func(t *testing.T) {
1732			tt.assertion(t, tt.expect, adder(tt.args.x, tt.args.y))
1733		})
1734	}
1735}
1736
1737func TestComparisonAssertionFunc(t *testing.T) {
1738	type iface interface {
1739		Name() string
1740	}
1741
1742	tests := []struct {
1743		name      string
1744		expect    interface{}
1745		got       interface{}
1746		assertion ComparisonAssertionFunc
1747	}{
1748		{"implements", (*iface)(nil), t, Implements},
1749		{"isType", (*testing.T)(nil), t, IsType},
1750		{"equal", t, t, Equal},
1751		{"equalValues", t, t, EqualValues},
1752		{"exactly", t, t, Exactly},
1753		{"notEqual", t, nil, NotEqual},
1754		{"notContains", []int{1, 2, 3}, 4, NotContains},
1755		{"subset", []int{1, 2, 3, 4}, []int{2, 3}, Subset},
1756		{"notSubset", []int{1, 2, 3, 4}, []int{0, 3}, NotSubset},
1757		{"elementsMatch", []byte("abc"), []byte("bac"), ElementsMatch},
1758		{"regexp", "^t.*y$", "testify", Regexp},
1759		{"notRegexp", "^t.*y$", "Testify", NotRegexp},
1760	}
1761
1762	for _, tt := range tests {
1763		t.Run(tt.name, func(t *testing.T) {
1764			tt.assertion(t, tt.expect, tt.got)
1765		})
1766	}
1767}
1768
1769func ExampleValueAssertionFunc() {
1770	t := &testing.T{} // provided by test
1771
1772	dumbParse := func(input string) interface{} {
1773		var x interface{}
1774		json.Unmarshal([]byte(input), &x)
1775		return x
1776	}
1777
1778	tests := []struct {
1779		name      string
1780		arg       string
1781		assertion ValueAssertionFunc
1782	}{
1783		{"true is not nil", "true", NotNil},
1784		{"empty string is nil", "", Nil},
1785		{"zero is not nil", "0", NotNil},
1786		{"zero is zero", "0", Zero},
1787		{"false is zero", "false", Zero},
1788	}
1789
1790	for _, tt := range tests {
1791		t.Run(tt.name, func(t *testing.T) {
1792			tt.assertion(t, dumbParse(tt.arg))
1793		})
1794	}
1795}
1796
1797func TestValueAssertionFunc(t *testing.T) {
1798	tests := []struct {
1799		name      string
1800		value     interface{}
1801		assertion ValueAssertionFunc
1802	}{
1803		{"notNil", true, NotNil},
1804		{"nil", nil, Nil},
1805		{"empty", []int{}, Empty},
1806		{"notEmpty", []int{1}, NotEmpty},
1807		{"zero", false, Zero},
1808		{"notZero", 42, NotZero},
1809	}
1810
1811	for _, tt := range tests {
1812		t.Run(tt.name, func(t *testing.T) {
1813			tt.assertion(t, tt.value)
1814		})
1815	}
1816}
1817
1818func ExampleBoolAssertionFunc() {
1819	t := &testing.T{} // provided by test
1820
1821	isOkay := func(x int) bool {
1822		return x >= 42
1823	}
1824
1825	tests := []struct {
1826		name      string
1827		arg       int
1828		assertion BoolAssertionFunc
1829	}{
1830		{"-1 is bad", -1, False},
1831		{"42 is good", 42, True},
1832		{"41 is bad", 41, False},
1833		{"45 is cool", 45, True},
1834	}
1835
1836	for _, tt := range tests {
1837		t.Run(tt.name, func(t *testing.T) {
1838			tt.assertion(t, isOkay(tt.arg))
1839		})
1840	}
1841}
1842
1843func TestBoolAssertionFunc(t *testing.T) {
1844	tests := []struct {
1845		name      string
1846		value     bool
1847		assertion BoolAssertionFunc
1848	}{
1849		{"true", true, True},
1850		{"false", false, False},
1851	}
1852
1853	for _, tt := range tests {
1854		t.Run(tt.name, func(t *testing.T) {
1855			tt.assertion(t, tt.value)
1856		})
1857	}
1858}
1859
1860func ExampleErrorAssertionFunc() {
1861	t := &testing.T{} // provided by test
1862
1863	dumbParseNum := func(input string, v interface{}) error {
1864		return json.Unmarshal([]byte(input), v)
1865	}
1866
1867	tests := []struct {
1868		name      string
1869		arg       string
1870		assertion ErrorAssertionFunc
1871	}{
1872		{"1.2 is number", "1.2", NoError},
1873		{"1.2.3 not number", "1.2.3", Error},
1874		{"true is not number", "true", Error},
1875		{"3 is number", "3", NoError},
1876	}
1877
1878	for _, tt := range tests {
1879		t.Run(tt.name, func(t *testing.T) {
1880			var x float64
1881			tt.assertion(t, dumbParseNum(tt.arg, &x))
1882		})
1883	}
1884}
1885
1886func TestErrorAssertionFunc(t *testing.T) {
1887	tests := []struct {
1888		name      string
1889		err       error
1890		assertion ErrorAssertionFunc
1891	}{
1892		{"noError", nil, NoError},
1893		{"error", errors.New("whoops"), Error},
1894	}
1895
1896	for _, tt := range tests {
1897		t.Run(tt.name, func(t *testing.T) {
1898			tt.assertion(t, tt.err)
1899		})
1900	}
1901}
1902
1903func TestEventuallyFalse(t *testing.T) {
1904	mockT := new(testing.T)
1905
1906	condition := func() bool {
1907		return false
1908	}
1909
1910	False(t, Eventually(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
1911}
1912
1913func TestEventuallyTrue(t *testing.T) {
1914	state := 0
1915	condition := func() bool {
1916		defer func() {
1917			state = state + 1
1918		}()
1919		return state == 2
1920	}
1921
1922	True(t, Eventually(t, condition, 100*time.Millisecond, 20*time.Millisecond))
1923}
1924