1package assert
2
3import (
4	"bufio"
5	"bytes"
6	"encoding/json"
7	"errors"
8	"fmt"
9	"math"
10	"os"
11	"reflect"
12	"regexp"
13	"runtime"
14	"strings"
15	"time"
16	"unicode"
17	"unicode/utf8"
18
19	"github.com/davecgh/go-spew/spew"
20	"github.com/pmezard/go-difflib/difflib"
21)
22
23//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_format.go.tmpl
24
25// TestingT is an interface wrapper around *testing.T
26type TestingT interface {
27	Errorf(format string, args ...interface{})
28}
29
30// ComparisonAssertionFunc is a common function prototype when comparing two values.  Can be useful
31// for table driven tests.
32type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
33
34// ValueAssertionFunc is a common function prototype when validating a single value.  Can be useful
35// for table driven tests.
36type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
37
38// BoolAssertionFunc is a common function prototype when validating a bool value.  Can be useful
39// for table driven tests.
40type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
41
42// ErrorAssertionFunc is a common function prototype when validating an error value.  Can be useful
43// for table driven tests.
44type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
45
46// Comparison a custom function that returns true on success and false on failure
47type Comparison func() (success bool)
48
49/*
50	Helper functions
51*/
52
53// ObjectsAreEqual determines if two objects are considered equal.
54//
55// This function does no assertion of any kind.
56func ObjectsAreEqual(expected, actual interface{}) bool {
57	if expected == nil || actual == nil {
58		return expected == actual
59	}
60
61	exp, ok := expected.([]byte)
62	if !ok {
63		return reflect.DeepEqual(expected, actual)
64	}
65
66	act, ok := actual.([]byte)
67	if !ok {
68		return false
69	}
70	if exp == nil || act == nil {
71		return exp == nil && act == nil
72	}
73	return bytes.Equal(exp, act)
74}
75
76// ObjectsAreEqualValues gets whether two objects are equal, or if their
77// values are equal.
78func ObjectsAreEqualValues(expected, actual interface{}) bool {
79	if ObjectsAreEqual(expected, actual) {
80		return true
81	}
82
83	actualType := reflect.TypeOf(actual)
84	if actualType == nil {
85		return false
86	}
87	expectedValue := reflect.ValueOf(expected)
88	if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
89		// Attempt comparison after type conversion
90		return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
91	}
92
93	return false
94}
95
96/* CallerInfo is necessary because the assert functions use the testing object
97internally, causing it to print the file:line of the assert method, rather than where
98the problem actually occurred in calling code.*/
99
100// CallerInfo returns an array of strings containing the file and line number
101// of each stack frame leading from the current test to the assert call that
102// failed.
103func CallerInfo() []string {
104
105	pc := uintptr(0)
106	file := ""
107	line := 0
108	ok := false
109	name := ""
110
111	callers := []string{}
112	for i := 0; ; i++ {
113		pc, file, line, ok = runtime.Caller(i)
114		if !ok {
115			// The breaks below failed to terminate the loop, and we ran off the
116			// end of the call stack.
117			break
118		}
119
120		// This is a huge edge case, but it will panic if this is the case, see #180
121		if file == "<autogenerated>" {
122			break
123		}
124
125		f := runtime.FuncForPC(pc)
126		if f == nil {
127			break
128		}
129		name = f.Name()
130
131		// testing.tRunner is the standard library function that calls
132		// tests. Subtests are called directly by tRunner, without going through
133		// the Test/Benchmark/Example function that contains the t.Run calls, so
134		// with subtests we should break when we hit tRunner, without adding it
135		// to the list of callers.
136		if name == "testing.tRunner" {
137			break
138		}
139
140		parts := strings.Split(file, "/")
141		file = parts[len(parts)-1]
142		if len(parts) > 1 {
143			dir := parts[len(parts)-2]
144			if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
145				callers = append(callers, fmt.Sprintf("%s:%d", file, line))
146			}
147		}
148
149		// Drop the package
150		segments := strings.Split(name, ".")
151		name = segments[len(segments)-1]
152		if isTest(name, "Test") ||
153			isTest(name, "Benchmark") ||
154			isTest(name, "Example") {
155			break
156		}
157	}
158
159	return callers
160}
161
162// Stolen from the `go test` tool.
163// isTest tells whether name looks like a test (or benchmark, according to prefix).
164// It is a Test (say) if there is a character after Test that is not a lower-case letter.
165// We don't want TesticularCancer.
166func isTest(name, prefix string) bool {
167	if !strings.HasPrefix(name, prefix) {
168		return false
169	}
170	if len(name) == len(prefix) { // "Test" is ok
171		return true
172	}
173	rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
174	return !unicode.IsLower(rune)
175}
176
177func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
178	if len(msgAndArgs) == 0 || msgAndArgs == nil {
179		return ""
180	}
181	if len(msgAndArgs) == 1 {
182		msg := msgAndArgs[0]
183		if msgAsStr, ok := msg.(string); ok {
184			return msgAsStr
185		}
186		return fmt.Sprintf("%+v", msg)
187	}
188	if len(msgAndArgs) > 1 {
189		return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
190	}
191	return ""
192}
193
194// Aligns the provided message so that all lines after the first line start at the same location as the first line.
195// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
196// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
197// basis on which the alignment occurs).
198func indentMessageLines(message string, longestLabelLen int) string {
199	outBuf := new(bytes.Buffer)
200
201	for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
202		// no need to align first line because it starts at the correct location (after the label)
203		if i != 0 {
204			// append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
205			outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
206		}
207		outBuf.WriteString(scanner.Text())
208	}
209
210	return outBuf.String()
211}
212
213type failNower interface {
214	FailNow()
215}
216
217// FailNow fails test
218func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
219	if h, ok := t.(tHelper); ok {
220		h.Helper()
221	}
222	Fail(t, failureMessage, msgAndArgs...)
223
224	// We cannot extend TestingT with FailNow() and
225	// maintain backwards compatibility, so we fallback
226	// to panicking when FailNow is not available in
227	// TestingT.
228	// See issue #263
229
230	if t, ok := t.(failNower); ok {
231		t.FailNow()
232	} else {
233		panic("test failed and t is missing `FailNow()`")
234	}
235	return false
236}
237
238// Fail reports a failure through
239func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
240	if h, ok := t.(tHelper); ok {
241		h.Helper()
242	}
243	content := []labeledContent{
244		{"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")},
245		{"Error", failureMessage},
246	}
247
248	// Add test name if the Go version supports it
249	if n, ok := t.(interface {
250		Name() string
251	}); ok {
252		content = append(content, labeledContent{"Test", n.Name()})
253	}
254
255	message := messageFromMsgAndArgs(msgAndArgs...)
256	if len(message) > 0 {
257		content = append(content, labeledContent{"Messages", message})
258	}
259
260	t.Errorf("\n%s", ""+labeledOutput(content...))
261
262	return false
263}
264
265type labeledContent struct {
266	label   string
267	content string
268}
269
270// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
271//
272//   \t{{label}}:{{align_spaces}}\t{{content}}\n
273//
274// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
275// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
276// alignment is achieved, "\t{{content}}\n" is added for the output.
277//
278// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line.
279func labeledOutput(content ...labeledContent) string {
280	longestLabel := 0
281	for _, v := range content {
282		if len(v.label) > longestLabel {
283			longestLabel = len(v.label)
284		}
285	}
286	var output string
287	for _, v := range content {
288		output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
289	}
290	return output
291}
292
293// Implements asserts that an object is implemented by the specified interface.
294//
295//    assert.Implements(t, (*MyInterface)(nil), new(MyObject))
296func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
297	if h, ok := t.(tHelper); ok {
298		h.Helper()
299	}
300	interfaceType := reflect.TypeOf(interfaceObject).Elem()
301
302	if object == nil {
303		return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...)
304	}
305	if !reflect.TypeOf(object).Implements(interfaceType) {
306		return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
307	}
308
309	return true
310}
311
312// IsType asserts that the specified objects are of the same type.
313func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
314	if h, ok := t.(tHelper); ok {
315		h.Helper()
316	}
317
318	if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
319		return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
320	}
321
322	return true
323}
324
325// Equal asserts that two objects are equal.
326//
327//    assert.Equal(t, 123, 123)
328//
329// Pointer variable equality is determined based on the equality of the
330// referenced values (as opposed to the memory addresses). Function equality
331// cannot be determined and will always fail.
332func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
333	if h, ok := t.(tHelper); ok {
334		h.Helper()
335	}
336	if err := validateEqualArgs(expected, actual); err != nil {
337		return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)",
338			expected, actual, err), msgAndArgs...)
339	}
340
341	if !ObjectsAreEqual(expected, actual) {
342		diff := diff(expected, actual)
343		expected, actual = formatUnequalValues(expected, actual)
344		return Fail(t, fmt.Sprintf("Not equal: \n"+
345			"expected: %s\n"+
346			"actual  : %s%s", expected, actual, diff), msgAndArgs...)
347	}
348
349	return true
350
351}
352
353// formatUnequalValues takes two values of arbitrary types and returns string
354// representations appropriate to be presented to the user.
355//
356// If the values are not of like type, the returned strings will be prefixed
357// with the type name, and the value will be enclosed in parenthesis similar
358// to a type conversion in the Go grammar.
359func formatUnequalValues(expected, actual interface{}) (e string, a string) {
360	if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
361		return fmt.Sprintf("%T(%#v)", expected, expected),
362			fmt.Sprintf("%T(%#v)", actual, actual)
363	}
364
365	return fmt.Sprintf("%#v", expected),
366		fmt.Sprintf("%#v", actual)
367}
368
369// EqualValues asserts that two objects are equal or convertable to the same types
370// and equal.
371//
372//    assert.EqualValues(t, uint32(123), int32(123))
373func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
374	if h, ok := t.(tHelper); ok {
375		h.Helper()
376	}
377
378	if !ObjectsAreEqualValues(expected, actual) {
379		diff := diff(expected, actual)
380		expected, actual = formatUnequalValues(expected, actual)
381		return Fail(t, fmt.Sprintf("Not equal: \n"+
382			"expected: %s\n"+
383			"actual  : %s%s", expected, actual, diff), msgAndArgs...)
384	}
385
386	return true
387
388}
389
390// Exactly asserts that two objects are equal in value and type.
391//
392//    assert.Exactly(t, int32(123), int64(123))
393func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
394	if h, ok := t.(tHelper); ok {
395		h.Helper()
396	}
397
398	aType := reflect.TypeOf(expected)
399	bType := reflect.TypeOf(actual)
400
401	if aType != bType {
402		return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
403	}
404
405	return Equal(t, expected, actual, msgAndArgs...)
406
407}
408
409// NotNil asserts that the specified object is not nil.
410//
411//    assert.NotNil(t, err)
412func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
413	if h, ok := t.(tHelper); ok {
414		h.Helper()
415	}
416	if !isNil(object) {
417		return true
418	}
419	return Fail(t, "Expected value not to be nil.", msgAndArgs...)
420}
421
422// containsKind checks if a specified kind in the slice of kinds.
423func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool {
424	for i := 0; i < len(kinds); i++ {
425		if kind == kinds[i] {
426			return true
427		}
428	}
429
430	return false
431}
432
433// isNil checks if a specified object is nil or not, without Failing.
434func isNil(object interface{}) bool {
435	if object == nil {
436		return true
437	}
438
439	value := reflect.ValueOf(object)
440	kind := value.Kind()
441	isNilableKind := containsKind(
442		[]reflect.Kind{
443			reflect.Chan, reflect.Func,
444			reflect.Interface, reflect.Map,
445			reflect.Ptr, reflect.Slice},
446		kind)
447
448	if isNilableKind && value.IsNil() {
449		return true
450	}
451
452	return false
453}
454
455// Nil asserts that the specified object is nil.
456//
457//    assert.Nil(t, err)
458func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
459	if h, ok := t.(tHelper); ok {
460		h.Helper()
461	}
462	if isNil(object) {
463		return true
464	}
465	return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
466}
467
468// isEmpty gets whether the specified object is considered empty or not.
469func isEmpty(object interface{}) bool {
470
471	// get nil case out of the way
472	if object == nil {
473		return true
474	}
475
476	objValue := reflect.ValueOf(object)
477
478	switch objValue.Kind() {
479	// collection types are empty when they have no element
480	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
481		return objValue.Len() == 0
482	// pointers are empty if nil or if the value they point to is empty
483	case reflect.Ptr:
484		if objValue.IsNil() {
485			return true
486		}
487		deref := objValue.Elem().Interface()
488		return isEmpty(deref)
489	// for all other types, compare against the zero value
490	default:
491		zero := reflect.Zero(objValue.Type())
492		return reflect.DeepEqual(object, zero.Interface())
493	}
494}
495
496// Empty asserts that the specified object is empty.  I.e. nil, "", false, 0 or either
497// a slice or a channel with len == 0.
498//
499//  assert.Empty(t, obj)
500func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
501	if h, ok := t.(tHelper); ok {
502		h.Helper()
503	}
504
505	pass := isEmpty(object)
506	if !pass {
507		Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
508	}
509
510	return pass
511
512}
513
514// NotEmpty asserts that the specified object is NOT empty.  I.e. not nil, "", false, 0 or either
515// a slice or a channel with len == 0.
516//
517//  if assert.NotEmpty(t, obj) {
518//    assert.Equal(t, "two", obj[1])
519//  }
520func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
521	if h, ok := t.(tHelper); ok {
522		h.Helper()
523	}
524
525	pass := !isEmpty(object)
526	if !pass {
527		Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
528	}
529
530	return pass
531
532}
533
534// getLen try to get length of object.
535// return (false, 0) if impossible.
536func getLen(x interface{}) (ok bool, length int) {
537	v := reflect.ValueOf(x)
538	defer func() {
539		if e := recover(); e != nil {
540			ok = false
541		}
542	}()
543	return true, v.Len()
544}
545
546// Len asserts that the specified object has specific length.
547// Len also fails if the object has a type that len() not accept.
548//
549//    assert.Len(t, mySlice, 3)
550func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
551	if h, ok := t.(tHelper); ok {
552		h.Helper()
553	}
554	ok, l := getLen(object)
555	if !ok {
556		return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
557	}
558
559	if l != length {
560		return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
561	}
562	return true
563}
564
565// True asserts that the specified value is true.
566//
567//    assert.True(t, myBool)
568func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
569	if h, ok := t.(tHelper); ok {
570		h.Helper()
571	}
572	if h, ok := t.(interface {
573		Helper()
574	}); ok {
575		h.Helper()
576	}
577
578	if value != true {
579		return Fail(t, "Should be true", msgAndArgs...)
580	}
581
582	return true
583
584}
585
586// False asserts that the specified value is false.
587//
588//    assert.False(t, myBool)
589func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
590	if h, ok := t.(tHelper); ok {
591		h.Helper()
592	}
593
594	if value != false {
595		return Fail(t, "Should be false", msgAndArgs...)
596	}
597
598	return true
599
600}
601
602// NotEqual asserts that the specified values are NOT equal.
603//
604//    assert.NotEqual(t, obj1, obj2)
605//
606// Pointer variable equality is determined based on the equality of the
607// referenced values (as opposed to the memory addresses).
608func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
609	if h, ok := t.(tHelper); ok {
610		h.Helper()
611	}
612	if err := validateEqualArgs(expected, actual); err != nil {
613		return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
614			expected, actual, err), msgAndArgs...)
615	}
616
617	if ObjectsAreEqual(expected, actual) {
618		return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
619	}
620
621	return true
622
623}
624
625// containsElement try loop over the list check if the list includes the element.
626// return (false, false) if impossible.
627// return (true, false) if element was not found.
628// return (true, true) if element was found.
629func includeElement(list interface{}, element interface{}) (ok, found bool) {
630
631	listValue := reflect.ValueOf(list)
632	elementValue := reflect.ValueOf(element)
633	defer func() {
634		if e := recover(); e != nil {
635			ok = false
636			found = false
637		}
638	}()
639
640	if reflect.TypeOf(list).Kind() == reflect.String {
641		return true, strings.Contains(listValue.String(), elementValue.String())
642	}
643
644	if reflect.TypeOf(list).Kind() == reflect.Map {
645		mapKeys := listValue.MapKeys()
646		for i := 0; i < len(mapKeys); i++ {
647			if ObjectsAreEqual(mapKeys[i].Interface(), element) {
648				return true, true
649			}
650		}
651		return true, false
652	}
653
654	for i := 0; i < listValue.Len(); i++ {
655		if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
656			return true, true
657		}
658	}
659	return true, false
660
661}
662
663// Contains asserts that the specified string, list(array, slice...) or map contains the
664// specified substring or element.
665//
666//    assert.Contains(t, "Hello World", "World")
667//    assert.Contains(t, ["Hello", "World"], "World")
668//    assert.Contains(t, {"Hello": "World"}, "Hello")
669func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
670	if h, ok := t.(tHelper); ok {
671		h.Helper()
672	}
673
674	ok, found := includeElement(s, contains)
675	if !ok {
676		return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
677	}
678	if !found {
679		return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...)
680	}
681
682	return true
683
684}
685
686// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
687// specified substring or element.
688//
689//    assert.NotContains(t, "Hello World", "Earth")
690//    assert.NotContains(t, ["Hello", "World"], "Earth")
691//    assert.NotContains(t, {"Hello": "World"}, "Earth")
692func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
693	if h, ok := t.(tHelper); ok {
694		h.Helper()
695	}
696
697	ok, found := includeElement(s, contains)
698	if !ok {
699		return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
700	}
701	if found {
702		return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
703	}
704
705	return true
706
707}
708
709// Subset asserts that the specified list(array, slice...) contains all
710// elements given in the specified subset(array, slice...).
711//
712//    assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
713func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
714	if h, ok := t.(tHelper); ok {
715		h.Helper()
716	}
717	if subset == nil {
718		return true // we consider nil to be equal to the nil set
719	}
720
721	subsetValue := reflect.ValueOf(subset)
722	defer func() {
723		if e := recover(); e != nil {
724			ok = false
725		}
726	}()
727
728	listKind := reflect.TypeOf(list).Kind()
729	subsetKind := reflect.TypeOf(subset).Kind()
730
731	if listKind != reflect.Array && listKind != reflect.Slice {
732		return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
733	}
734
735	if subsetKind != reflect.Array && subsetKind != reflect.Slice {
736		return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
737	}
738
739	for i := 0; i < subsetValue.Len(); i++ {
740		element := subsetValue.Index(i).Interface()
741		ok, found := includeElement(list, element)
742		if !ok {
743			return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
744		}
745		if !found {
746			return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...)
747		}
748	}
749
750	return true
751}
752
753// NotSubset asserts that the specified list(array, slice...) contains not all
754// elements given in the specified subset(array, slice...).
755//
756//    assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
757func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
758	if h, ok := t.(tHelper); ok {
759		h.Helper()
760	}
761	if subset == nil {
762		return Fail(t, fmt.Sprintf("nil is the empty set which is a subset of every set"), msgAndArgs...)
763	}
764
765	subsetValue := reflect.ValueOf(subset)
766	defer func() {
767		if e := recover(); e != nil {
768			ok = false
769		}
770	}()
771
772	listKind := reflect.TypeOf(list).Kind()
773	subsetKind := reflect.TypeOf(subset).Kind()
774
775	if listKind != reflect.Array && listKind != reflect.Slice {
776		return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
777	}
778
779	if subsetKind != reflect.Array && subsetKind != reflect.Slice {
780		return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
781	}
782
783	for i := 0; i < subsetValue.Len(); i++ {
784		element := subsetValue.Index(i).Interface()
785		ok, found := includeElement(list, element)
786		if !ok {
787			return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
788		}
789		if !found {
790			return true
791		}
792	}
793
794	return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
795}
796
797// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
798// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
799// the number of appearances of each of them in both lists should match.
800//
801// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
802func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
803	if h, ok := t.(tHelper); ok {
804		h.Helper()
805	}
806	if isEmpty(listA) && isEmpty(listB) {
807		return true
808	}
809
810	aKind := reflect.TypeOf(listA).Kind()
811	bKind := reflect.TypeOf(listB).Kind()
812
813	if aKind != reflect.Array && aKind != reflect.Slice {
814		return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listA, aKind), msgAndArgs...)
815	}
816
817	if bKind != reflect.Array && bKind != reflect.Slice {
818		return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listB, bKind), msgAndArgs...)
819	}
820
821	aValue := reflect.ValueOf(listA)
822	bValue := reflect.ValueOf(listB)
823
824	aLen := aValue.Len()
825	bLen := bValue.Len()
826
827	if aLen != bLen {
828		return Fail(t, fmt.Sprintf("lengths don't match: %d != %d", aLen, bLen), msgAndArgs...)
829	}
830
831	// Mark indexes in bValue that we already used
832	visited := make([]bool, bLen)
833	for i := 0; i < aLen; i++ {
834		element := aValue.Index(i).Interface()
835		found := false
836		for j := 0; j < bLen; j++ {
837			if visited[j] {
838				continue
839			}
840			if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
841				visited[j] = true
842				found = true
843				break
844			}
845		}
846		if !found {
847			return Fail(t, fmt.Sprintf("element %s appears more times in %s than in %s", element, aValue, bValue), msgAndArgs...)
848		}
849	}
850
851	return true
852}
853
854// Condition uses a Comparison to assert a complex condition.
855func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
856	if h, ok := t.(tHelper); ok {
857		h.Helper()
858	}
859	result := comp()
860	if !result {
861		Fail(t, "Condition failed!", msgAndArgs...)
862	}
863	return result
864}
865
866// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
867// methods, and represents a simple func that takes no arguments, and returns nothing.
868type PanicTestFunc func()
869
870// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
871func didPanic(f PanicTestFunc) (bool, interface{}) {
872
873	didPanic := false
874	var message interface{}
875	func() {
876
877		defer func() {
878			if message = recover(); message != nil {
879				didPanic = true
880			}
881		}()
882
883		// call the target function
884		f()
885
886	}()
887
888	return didPanic, message
889
890}
891
892// Panics asserts that the code inside the specified PanicTestFunc panics.
893//
894//   assert.Panics(t, func(){ GoCrazy() })
895func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
896	if h, ok := t.(tHelper); ok {
897		h.Helper()
898	}
899
900	if funcDidPanic, panicValue := didPanic(f); !funcDidPanic {
901		return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
902	}
903
904	return true
905}
906
907// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
908// the recovered panic value equals the expected panic value.
909//
910//   assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
911func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
912	if h, ok := t.(tHelper); ok {
913		h.Helper()
914	}
915
916	funcDidPanic, panicValue := didPanic(f)
917	if !funcDidPanic {
918		return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
919	}
920	if panicValue != expected {
921		return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v", f, expected, panicValue), msgAndArgs...)
922	}
923
924	return true
925}
926
927// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
928//
929//   assert.NotPanics(t, func(){ RemainCalm() })
930func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
931	if h, ok := t.(tHelper); ok {
932		h.Helper()
933	}
934
935	if funcDidPanic, panicValue := didPanic(f); funcDidPanic {
936		return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v", f, panicValue), msgAndArgs...)
937	}
938
939	return true
940}
941
942// WithinDuration asserts that the two times are within duration delta of each other.
943//
944//   assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
945func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
946	if h, ok := t.(tHelper); ok {
947		h.Helper()
948	}
949
950	dt := expected.Sub(actual)
951	if dt < -delta || dt > delta {
952		return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
953	}
954
955	return true
956}
957
958func toFloat(x interface{}) (float64, bool) {
959	var xf float64
960	xok := true
961
962	switch xn := x.(type) {
963	case uint8:
964		xf = float64(xn)
965	case uint16:
966		xf = float64(xn)
967	case uint32:
968		xf = float64(xn)
969	case uint64:
970		xf = float64(xn)
971	case int:
972		xf = float64(xn)
973	case int8:
974		xf = float64(xn)
975	case int16:
976		xf = float64(xn)
977	case int32:
978		xf = float64(xn)
979	case int64:
980		xf = float64(xn)
981	case float32:
982		xf = float64(xn)
983	case float64:
984		xf = float64(xn)
985	case time.Duration:
986		xf = float64(xn)
987	default:
988		xok = false
989	}
990
991	return xf, xok
992}
993
994// InDelta asserts that the two numerals are within delta of each other.
995//
996// 	 assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
997func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
998	if h, ok := t.(tHelper); ok {
999		h.Helper()
1000	}
1001
1002	af, aok := toFloat(expected)
1003	bf, bok := toFloat(actual)
1004
1005	if !aok || !bok {
1006		return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
1007	}
1008
1009	if math.IsNaN(af) {
1010		return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...)
1011	}
1012
1013	if math.IsNaN(bf) {
1014		return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
1015	}
1016
1017	dt := af - bf
1018	if dt < -delta || dt > delta {
1019		return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
1020	}
1021
1022	return true
1023}
1024
1025// InDeltaSlice is the same as InDelta, except it compares two slices.
1026func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1027	if h, ok := t.(tHelper); ok {
1028		h.Helper()
1029	}
1030	if expected == nil || actual == nil ||
1031		reflect.TypeOf(actual).Kind() != reflect.Slice ||
1032		reflect.TypeOf(expected).Kind() != reflect.Slice {
1033		return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
1034	}
1035
1036	actualSlice := reflect.ValueOf(actual)
1037	expectedSlice := reflect.ValueOf(expected)
1038
1039	for i := 0; i < actualSlice.Len(); i++ {
1040		result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
1041		if !result {
1042			return result
1043		}
1044	}
1045
1046	return true
1047}
1048
1049// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
1050func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1051	if h, ok := t.(tHelper); ok {
1052		h.Helper()
1053	}
1054	if expected == nil || actual == nil ||
1055		reflect.TypeOf(actual).Kind() != reflect.Map ||
1056		reflect.TypeOf(expected).Kind() != reflect.Map {
1057		return Fail(t, "Arguments must be maps", msgAndArgs...)
1058	}
1059
1060	expectedMap := reflect.ValueOf(expected)
1061	actualMap := reflect.ValueOf(actual)
1062
1063	if expectedMap.Len() != actualMap.Len() {
1064		return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
1065	}
1066
1067	for _, k := range expectedMap.MapKeys() {
1068		ev := expectedMap.MapIndex(k)
1069		av := actualMap.MapIndex(k)
1070
1071		if !ev.IsValid() {
1072			return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
1073		}
1074
1075		if !av.IsValid() {
1076			return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
1077		}
1078
1079		if !InDelta(
1080			t,
1081			ev.Interface(),
1082			av.Interface(),
1083			delta,
1084			msgAndArgs...,
1085		) {
1086			return false
1087		}
1088	}
1089
1090	return true
1091}
1092
1093func calcRelativeError(expected, actual interface{}) (float64, error) {
1094	af, aok := toFloat(expected)
1095	if !aok {
1096		return 0, fmt.Errorf("expected value %q cannot be converted to float", expected)
1097	}
1098	if af == 0 {
1099		return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
1100	}
1101	bf, bok := toFloat(actual)
1102	if !bok {
1103		return 0, fmt.Errorf("actual value %q cannot be converted to float", actual)
1104	}
1105
1106	return math.Abs(af-bf) / math.Abs(af), nil
1107}
1108
1109// InEpsilon asserts that expected and actual have a relative error less than epsilon
1110func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
1111	if h, ok := t.(tHelper); ok {
1112		h.Helper()
1113	}
1114	actualEpsilon, err := calcRelativeError(expected, actual)
1115	if err != nil {
1116		return Fail(t, err.Error(), msgAndArgs...)
1117	}
1118	if actualEpsilon > epsilon {
1119		return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
1120			"        < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
1121	}
1122
1123	return true
1124}
1125
1126// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
1127func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
1128	if h, ok := t.(tHelper); ok {
1129		h.Helper()
1130	}
1131	if expected == nil || actual == nil ||
1132		reflect.TypeOf(actual).Kind() != reflect.Slice ||
1133		reflect.TypeOf(expected).Kind() != reflect.Slice {
1134		return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
1135	}
1136
1137	actualSlice := reflect.ValueOf(actual)
1138	expectedSlice := reflect.ValueOf(expected)
1139
1140	for i := 0; i < actualSlice.Len(); i++ {
1141		result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
1142		if !result {
1143			return result
1144		}
1145	}
1146
1147	return true
1148}
1149
1150/*
1151	Errors
1152*/
1153
1154// NoError asserts that a function returned no error (i.e. `nil`).
1155//
1156//   actualObj, err := SomeFunction()
1157//   if assert.NoError(t, err) {
1158//	   assert.Equal(t, expectedObj, actualObj)
1159//   }
1160func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
1161	if h, ok := t.(tHelper); ok {
1162		h.Helper()
1163	}
1164	if err != nil {
1165		return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
1166	}
1167
1168	return true
1169}
1170
1171// Error asserts that a function returned an error (i.e. not `nil`).
1172//
1173//   actualObj, err := SomeFunction()
1174//   if assert.Error(t, err) {
1175//	   assert.Equal(t, expectedError, err)
1176//   }
1177func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
1178	if h, ok := t.(tHelper); ok {
1179		h.Helper()
1180	}
1181
1182	if err == nil {
1183		return Fail(t, "An error is expected but got nil.", msgAndArgs...)
1184	}
1185
1186	return true
1187}
1188
1189// EqualError asserts that a function returned an error (i.e. not `nil`)
1190// and that it is equal to the provided error.
1191//
1192//   actualObj, err := SomeFunction()
1193//   assert.EqualError(t, err,  expectedErrorString)
1194func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
1195	if h, ok := t.(tHelper); ok {
1196		h.Helper()
1197	}
1198	if !Error(t, theError, msgAndArgs...) {
1199		return false
1200	}
1201	expected := errString
1202	actual := theError.Error()
1203	// don't need to use deep equals here, we know they are both strings
1204	if expected != actual {
1205		return Fail(t, fmt.Sprintf("Error message not equal:\n"+
1206			"expected: %q\n"+
1207			"actual  : %q", expected, actual), msgAndArgs...)
1208	}
1209	return true
1210}
1211
1212// matchRegexp return true if a specified regexp matches a string.
1213func matchRegexp(rx interface{}, str interface{}) bool {
1214
1215	var r *regexp.Regexp
1216	if rr, ok := rx.(*regexp.Regexp); ok {
1217		r = rr
1218	} else {
1219		r = regexp.MustCompile(fmt.Sprint(rx))
1220	}
1221
1222	return (r.FindStringIndex(fmt.Sprint(str)) != nil)
1223
1224}
1225
1226// Regexp asserts that a specified regexp matches a string.
1227//
1228//  assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
1229//  assert.Regexp(t, "start...$", "it's not starting")
1230func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1231	if h, ok := t.(tHelper); ok {
1232		h.Helper()
1233	}
1234
1235	match := matchRegexp(rx, str)
1236
1237	if !match {
1238		Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
1239	}
1240
1241	return match
1242}
1243
1244// NotRegexp asserts that a specified regexp does not match a string.
1245//
1246//  assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
1247//  assert.NotRegexp(t, "^start", "it's not starting")
1248func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1249	if h, ok := t.(tHelper); ok {
1250		h.Helper()
1251	}
1252	match := matchRegexp(rx, str)
1253
1254	if match {
1255		Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
1256	}
1257
1258	return !match
1259
1260}
1261
1262// Zero asserts that i is the zero value for its type.
1263func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
1264	if h, ok := t.(tHelper); ok {
1265		h.Helper()
1266	}
1267	if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
1268		return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
1269	}
1270	return true
1271}
1272
1273// NotZero asserts that i is not the zero value for its type.
1274func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
1275	if h, ok := t.(tHelper); ok {
1276		h.Helper()
1277	}
1278	if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
1279		return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
1280	}
1281	return true
1282}
1283
1284// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.
1285func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1286	if h, ok := t.(tHelper); ok {
1287		h.Helper()
1288	}
1289	info, err := os.Lstat(path)
1290	if err != nil {
1291		if os.IsNotExist(err) {
1292			return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
1293		}
1294		return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
1295	}
1296	if info.IsDir() {
1297		return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
1298	}
1299	return true
1300}
1301
1302// DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists.
1303func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1304	if h, ok := t.(tHelper); ok {
1305		h.Helper()
1306	}
1307	info, err := os.Lstat(path)
1308	if err != nil {
1309		if os.IsNotExist(err) {
1310			return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
1311		}
1312		return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
1313	}
1314	if !info.IsDir() {
1315		return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
1316	}
1317	return true
1318}
1319
1320// JSONEq asserts that two JSON strings are equivalent.
1321//
1322//  assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
1323func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
1324	if h, ok := t.(tHelper); ok {
1325		h.Helper()
1326	}
1327	var expectedJSONAsInterface, actualJSONAsInterface interface{}
1328
1329	if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
1330		return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
1331	}
1332
1333	if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
1334		return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
1335	}
1336
1337	return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
1338}
1339
1340func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
1341	t := reflect.TypeOf(v)
1342	k := t.Kind()
1343
1344	if k == reflect.Ptr {
1345		t = t.Elem()
1346		k = t.Kind()
1347	}
1348	return t, k
1349}
1350
1351// diff returns a diff of both values as long as both are of the same type and
1352// are a struct, map, slice, array or string. Otherwise it returns an empty string.
1353func diff(expected interface{}, actual interface{}) string {
1354	if expected == nil || actual == nil {
1355		return ""
1356	}
1357
1358	et, ek := typeAndKind(expected)
1359	at, _ := typeAndKind(actual)
1360
1361	if et != at {
1362		return ""
1363	}
1364
1365	if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
1366		return ""
1367	}
1368
1369	var e, a string
1370	if et != reflect.TypeOf("") {
1371		e = spewConfig.Sdump(expected)
1372		a = spewConfig.Sdump(actual)
1373	} else {
1374		e = expected.(string)
1375		a = actual.(string)
1376	}
1377
1378	diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
1379		A:        difflib.SplitLines(e),
1380		B:        difflib.SplitLines(a),
1381		FromFile: "Expected",
1382		FromDate: "",
1383		ToFile:   "Actual",
1384		ToDate:   "",
1385		Context:  1,
1386	})
1387
1388	return "\n\nDiff:\n" + diff
1389}
1390
1391// validateEqualArgs checks whether provided arguments can be safely used in the
1392// Equal/NotEqual functions.
1393func validateEqualArgs(expected, actual interface{}) error {
1394	if isFunction(expected) || isFunction(actual) {
1395		return errors.New("cannot take func type as argument")
1396	}
1397	return nil
1398}
1399
1400func isFunction(arg interface{}) bool {
1401	if arg == nil {
1402		return false
1403	}
1404	return reflect.TypeOf(arg).Kind() == reflect.Func
1405}
1406
1407var spewConfig = spew.ConfigState{
1408	Indent:                  " ",
1409	DisablePointerAddresses: true,
1410	DisableCapacities:       true,
1411	SortKeys:                true,
1412}
1413
1414type tHelper interface {
1415	Helper()
1416}
1417