blob: 2924cf3a149234bdc0255ea3340457a56de7c76f [file] [log] [blame]
vinokumaf7605fc2023-06-02 18:08:01 +05301package 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 "runtime/debug"
15 "strings"
16 "time"
17 "unicode"
18 "unicode/utf8"
19
20 "github.com/davecgh/go-spew/spew"
21 "github.com/pmezard/go-difflib/difflib"
22 yaml "gopkg.in/yaml.v3"
23)
24
25//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
26
27// TestingT is an interface wrapper around *testing.T
28type TestingT interface {
29 Errorf(format string, args ...interface{})
30}
31
32// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
33// for table driven tests.
34type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
35
36// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
37// for table driven tests.
38type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
39
40// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
41// for table driven tests.
42type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
43
44// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
45// for table driven tests.
46type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
47
48// Comparison is a custom function that returns true on success and false on failure
49type Comparison func() (success bool)
50
51/*
52 Helper functions
53*/
54
55// ObjectsAreEqual determines if two objects are considered equal.
56//
57// This function does no assertion of any kind.
58func ObjectsAreEqual(expected, actual interface{}) bool {
59 if expected == nil || actual == nil {
60 return expected == actual
61 }
62
63 exp, ok := expected.([]byte)
64 if !ok {
65 return reflect.DeepEqual(expected, actual)
66 }
67
68 act, ok := actual.([]byte)
69 if !ok {
70 return false
71 }
72 if exp == nil || act == nil {
73 return exp == nil && act == nil
74 }
75 return bytes.Equal(exp, act)
76}
77
78// ObjectsAreEqualValues gets whether two objects are equal, or if their
79// values are equal.
80func ObjectsAreEqualValues(expected, actual interface{}) bool {
81 if ObjectsAreEqual(expected, actual) {
82 return true
83 }
84
85 actualType := reflect.TypeOf(actual)
86 if actualType == nil {
87 return false
88 }
89 expectedValue := reflect.ValueOf(expected)
90 if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
91 // Attempt comparison after type conversion
92 return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
93 }
94
95 return false
96}
97
98/* CallerInfo is necessary because the assert functions use the testing object
99internally, causing it to print the file:line of the assert method, rather than where
100the problem actually occurred in calling code.*/
101
102// CallerInfo returns an array of strings containing the file and line number
103// of each stack frame leading from the current test to the assert call that
104// failed.
105func CallerInfo() []string {
106
107 var pc uintptr
108 var ok bool
109 var file string
110 var line int
111 var name string
112
113 callers := []string{}
114 for i := 0; ; i++ {
115 pc, file, line, ok = runtime.Caller(i)
116 if !ok {
117 // The breaks below failed to terminate the loop, and we ran off the
118 // end of the call stack.
119 break
120 }
121
122 // This is a huge edge case, but it will panic if this is the case, see #180
123 if file == "<autogenerated>" {
124 break
125 }
126
127 f := runtime.FuncForPC(pc)
128 if f == nil {
129 break
130 }
131 name = f.Name()
132
133 // testing.tRunner is the standard library function that calls
134 // tests. Subtests are called directly by tRunner, without going through
135 // the Test/Benchmark/Example function that contains the t.Run calls, so
136 // with subtests we should break when we hit tRunner, without adding it
137 // to the list of callers.
138 if name == "testing.tRunner" {
139 break
140 }
141
142 parts := strings.Split(file, "/")
143 if len(parts) > 1 {
144 filename := parts[len(parts)-1]
145 dir := parts[len(parts)-2]
146 if (dir != "assert" && dir != "mock" && dir != "require") || filename == "mock_test.go" {
147 callers = append(callers, fmt.Sprintf("%s:%d", file, line))
148 }
149 }
150
151 // Drop the package
152 segments := strings.Split(name, ".")
153 name = segments[len(segments)-1]
154 if isTest(name, "Test") ||
155 isTest(name, "Benchmark") ||
156 isTest(name, "Example") {
157 break
158 }
159 }
160
161 return callers
162}
163
164// Stolen from the `go test` tool.
165// isTest tells whether name looks like a test (or benchmark, according to prefix).
166// It is a Test (say) if there is a character after Test that is not a lower-case letter.
167// We don't want TesticularCancer.
168func isTest(name, prefix string) bool {
169 if !strings.HasPrefix(name, prefix) {
170 return false
171 }
172 if len(name) == len(prefix) { // "Test" is ok
173 return true
174 }
175 r, _ := utf8.DecodeRuneInString(name[len(prefix):])
176 return !unicode.IsLower(r)
177}
178
179func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
180 if len(msgAndArgs) == 0 || msgAndArgs == nil {
181 return ""
182 }
183 if len(msgAndArgs) == 1 {
184 msg := msgAndArgs[0]
185 if msgAsStr, ok := msg.(string); ok {
186 return msgAsStr
187 }
188 return fmt.Sprintf("%+v", msg)
189 }
190 if len(msgAndArgs) > 1 {
191 return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
192 }
193 return ""
194}
195
196// Aligns the provided message so that all lines after the first line start at the same location as the first line.
197// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
198// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
199// basis on which the alignment occurs).
200func indentMessageLines(message string, longestLabelLen int) string {
201 outBuf := new(bytes.Buffer)
202
203 for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
204 // no need to align first line because it starts at the correct location (after the label)
205 if i != 0 {
206 // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
207 outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
208 }
209 outBuf.WriteString(scanner.Text())
210 }
211
212 return outBuf.String()
213}
214
215type failNower interface {
216 FailNow()
217}
218
219// FailNow fails test
220func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
221 if h, ok := t.(tHelper); ok {
222 h.Helper()
223 }
224 Fail(t, failureMessage, msgAndArgs...)
225
226 // We cannot extend TestingT with FailNow() and
227 // maintain backwards compatibility, so we fallback
228 // to panicking when FailNow is not available in
229 // TestingT.
230 // See issue #263
231
232 if t, ok := t.(failNower); ok {
233 t.FailNow()
234 } else {
235 panic("test failed and t is missing `FailNow()`")
236 }
237 return false
238}
239
240// Fail reports a failure through
241func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
242 if h, ok := t.(tHelper); ok {
243 h.Helper()
244 }
245 content := []labeledContent{
246 {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")},
247 {"Error", failureMessage},
248 }
249
250 // Add test name if the Go version supports it
251 if n, ok := t.(interface {
252 Name() string
253 }); ok {
254 content = append(content, labeledContent{"Test", n.Name()})
255 }
256
257 message := messageFromMsgAndArgs(msgAndArgs...)
258 if len(message) > 0 {
259 content = append(content, labeledContent{"Messages", message})
260 }
261
262 t.Errorf("\n%s", ""+labeledOutput(content...))
263
264 return false
265}
266
267type labeledContent struct {
268 label string
269 content string
270}
271
272// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
273//
274// \t{{label}}:{{align_spaces}}\t{{content}}\n
275//
276// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
277// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
278// alignment is achieved, "\t{{content}}\n" is added for the output.
279//
280// 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.
281func labeledOutput(content ...labeledContent) string {
282 longestLabel := 0
283 for _, v := range content {
284 if len(v.label) > longestLabel {
285 longestLabel = len(v.label)
286 }
287 }
288 var output string
289 for _, v := range content {
290 output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
291 }
292 return output
293}
294
295// Implements asserts that an object is implemented by the specified interface.
296//
297// assert.Implements(t, (*MyInterface)(nil), new(MyObject))
298func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
299 if h, ok := t.(tHelper); ok {
300 h.Helper()
301 }
302 interfaceType := reflect.TypeOf(interfaceObject).Elem()
303
304 if object == nil {
305 return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...)
306 }
307 if !reflect.TypeOf(object).Implements(interfaceType) {
308 return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
309 }
310
311 return true
312}
313
314// IsType asserts that the specified objects are of the same type.
315func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
316 if h, ok := t.(tHelper); ok {
317 h.Helper()
318 }
319
320 if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
321 return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
322 }
323
324 return true
325}
326
327// Equal asserts that two objects are equal.
328//
329// assert.Equal(t, 123, 123)
330//
331// Pointer variable equality is determined based on the equality of the
332// referenced values (as opposed to the memory addresses). Function equality
333// cannot be determined and will always fail.
334func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
335 if h, ok := t.(tHelper); ok {
336 h.Helper()
337 }
338 if err := validateEqualArgs(expected, actual); err != nil {
339 return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)",
340 expected, actual, err), msgAndArgs...)
341 }
342
343 if !ObjectsAreEqual(expected, actual) {
344 diff := diff(expected, actual)
345 expected, actual = formatUnequalValues(expected, actual)
346 return Fail(t, fmt.Sprintf("Not equal: \n"+
347 "expected: %s\n"+
348 "actual : %s%s", expected, actual, diff), msgAndArgs...)
349 }
350
351 return true
352
353}
354
355// validateEqualArgs checks whether provided arguments can be safely used in the
356// Equal/NotEqual functions.
357func validateEqualArgs(expected, actual interface{}) error {
358 if expected == nil && actual == nil {
359 return nil
360 }
361
362 if isFunction(expected) || isFunction(actual) {
363 return errors.New("cannot take func type as argument")
364 }
365 return nil
366}
367
368// Same asserts that two pointers reference the same object.
369//
370// assert.Same(t, ptr1, ptr2)
371//
372// Both arguments must be pointer variables. Pointer variable sameness is
373// determined based on the equality of both type and value.
374func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
375 if h, ok := t.(tHelper); ok {
376 h.Helper()
377 }
378
379 if !samePointers(expected, actual) {
380 return Fail(t, fmt.Sprintf("Not same: \n"+
381 "expected: %p %#v\n"+
382 "actual : %p %#v", expected, expected, actual, actual), msgAndArgs...)
383 }
384
385 return true
386}
387
388// NotSame asserts that two pointers do not reference the same object.
389//
390// assert.NotSame(t, ptr1, ptr2)
391//
392// Both arguments must be pointer variables. Pointer variable sameness is
393// determined based on the equality of both type and value.
394func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
395 if h, ok := t.(tHelper); ok {
396 h.Helper()
397 }
398
399 if samePointers(expected, actual) {
400 return Fail(t, fmt.Sprintf(
401 "Expected and actual point to the same object: %p %#v",
402 expected, expected), msgAndArgs...)
403 }
404 return true
405}
406
407// samePointers compares two generic interface objects and returns whether
408// they point to the same object
409func samePointers(first, second interface{}) bool {
410 firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second)
411 if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr {
412 return false
413 }
414
415 firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second)
416 if firstType != secondType {
417 return false
418 }
419
420 // compare pointer addresses
421 return first == second
422}
423
424// formatUnequalValues takes two values of arbitrary types and returns string
425// representations appropriate to be presented to the user.
426//
427// If the values are not of like type, the returned strings will be prefixed
428// with the type name, and the value will be enclosed in parenthesis similar
429// to a type conversion in the Go grammar.
430func formatUnequalValues(expected, actual interface{}) (e string, a string) {
431 if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
432 return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)),
433 fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual))
434 }
435 switch expected.(type) {
436 case time.Duration:
437 return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)
438 }
439 return truncatingFormat(expected), truncatingFormat(actual)
440}
441
442// truncatingFormat formats the data and truncates it if it's too long.
443//
444// This helps keep formatted error messages lines from exceeding the
445// bufio.MaxScanTokenSize max line length that the go testing framework imposes.
446func truncatingFormat(data interface{}) string {
447 value := fmt.Sprintf("%#v", data)
448 max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed.
449 if len(value) > max {
450 value = value[0:max] + "<... truncated>"
451 }
452 return value
453}
454
455// EqualValues asserts that two objects are equal or convertable to the same types
456// and equal.
457//
458// assert.EqualValues(t, uint32(123), int32(123))
459func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
460 if h, ok := t.(tHelper); ok {
461 h.Helper()
462 }
463
464 if !ObjectsAreEqualValues(expected, actual) {
465 diff := diff(expected, actual)
466 expected, actual = formatUnequalValues(expected, actual)
467 return Fail(t, fmt.Sprintf("Not equal: \n"+
468 "expected: %s\n"+
469 "actual : %s%s", expected, actual, diff), msgAndArgs...)
470 }
471
472 return true
473
474}
475
476// Exactly asserts that two objects are equal in value and type.
477//
478// assert.Exactly(t, int32(123), int64(123))
479func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
480 if h, ok := t.(tHelper); ok {
481 h.Helper()
482 }
483
484 aType := reflect.TypeOf(expected)
485 bType := reflect.TypeOf(actual)
486
487 if aType != bType {
488 return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
489 }
490
491 return Equal(t, expected, actual, msgAndArgs...)
492
493}
494
495// NotNil asserts that the specified object is not nil.
496//
497// assert.NotNil(t, err)
498func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
499 if !isNil(object) {
500 return true
501 }
502 if h, ok := t.(tHelper); ok {
503 h.Helper()
504 }
505 return Fail(t, "Expected value not to be nil.", msgAndArgs...)
506}
507
508// containsKind checks if a specified kind in the slice of kinds.
509func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool {
510 for i := 0; i < len(kinds); i++ {
511 if kind == kinds[i] {
512 return true
513 }
514 }
515
516 return false
517}
518
519// isNil checks if a specified object is nil or not, without Failing.
520func isNil(object interface{}) bool {
521 if object == nil {
522 return true
523 }
524
525 value := reflect.ValueOf(object)
526 kind := value.Kind()
527 isNilableKind := containsKind(
528 []reflect.Kind{
529 reflect.Chan, reflect.Func,
530 reflect.Interface, reflect.Map,
531 reflect.Ptr, reflect.Slice, reflect.UnsafePointer},
532 kind)
533
534 if isNilableKind && value.IsNil() {
535 return true
536 }
537
538 return false
539}
540
541// Nil asserts that the specified object is nil.
542//
543// assert.Nil(t, err)
544func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
545 if isNil(object) {
546 return true
547 }
548 if h, ok := t.(tHelper); ok {
549 h.Helper()
550 }
551 return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
552}
553
554// isEmpty gets whether the specified object is considered empty or not.
555func isEmpty(object interface{}) bool {
556
557 // get nil case out of the way
558 if object == nil {
559 return true
560 }
561
562 objValue := reflect.ValueOf(object)
563
564 switch objValue.Kind() {
565 // collection types are empty when they have no element
566 case reflect.Chan, reflect.Map, reflect.Slice:
567 return objValue.Len() == 0
568 // pointers are empty if nil or if the value they point to is empty
569 case reflect.Ptr:
570 if objValue.IsNil() {
571 return true
572 }
573 deref := objValue.Elem().Interface()
574 return isEmpty(deref)
575 // for all other types, compare against the zero value
576 // array types are empty when they match their zero-initialized state
577 default:
578 zero := reflect.Zero(objValue.Type())
579 return reflect.DeepEqual(object, zero.Interface())
580 }
581}
582
583// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
584// a slice or a channel with len == 0.
585//
586// assert.Empty(t, obj)
587func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
588 pass := isEmpty(object)
589 if !pass {
590 if h, ok := t.(tHelper); ok {
591 h.Helper()
592 }
593 Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
594 }
595
596 return pass
597
598}
599
600// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
601// a slice or a channel with len == 0.
602//
603// if assert.NotEmpty(t, obj) {
604// assert.Equal(t, "two", obj[1])
605// }
606func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
607 pass := !isEmpty(object)
608 if !pass {
609 if h, ok := t.(tHelper); ok {
610 h.Helper()
611 }
612 Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
613 }
614
615 return pass
616
617}
618
619// getLen try to get length of object.
620// return (false, 0) if impossible.
621func getLen(x interface{}) (ok bool, length int) {
622 v := reflect.ValueOf(x)
623 defer func() {
624 if e := recover(); e != nil {
625 ok = false
626 }
627 }()
628 return true, v.Len()
629}
630
631// Len asserts that the specified object has specific length.
632// Len also fails if the object has a type that len() not accept.
633//
634// assert.Len(t, mySlice, 3)
635func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
636 if h, ok := t.(tHelper); ok {
637 h.Helper()
638 }
639 ok, l := getLen(object)
640 if !ok {
641 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
642 }
643
644 if l != length {
645 return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
646 }
647 return true
648}
649
650// True asserts that the specified value is true.
651//
652// assert.True(t, myBool)
653func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
654 if !value {
655 if h, ok := t.(tHelper); ok {
656 h.Helper()
657 }
658 return Fail(t, "Should be true", msgAndArgs...)
659 }
660
661 return true
662
663}
664
665// False asserts that the specified value is false.
666//
667// assert.False(t, myBool)
668func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
669 if value {
670 if h, ok := t.(tHelper); ok {
671 h.Helper()
672 }
673 return Fail(t, "Should be false", msgAndArgs...)
674 }
675
676 return true
677
678}
679
680// NotEqual asserts that the specified values are NOT equal.
681//
682// assert.NotEqual(t, obj1, obj2)
683//
684// Pointer variable equality is determined based on the equality of the
685// referenced values (as opposed to the memory addresses).
686func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
687 if h, ok := t.(tHelper); ok {
688 h.Helper()
689 }
690 if err := validateEqualArgs(expected, actual); err != nil {
691 return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
692 expected, actual, err), msgAndArgs...)
693 }
694
695 if ObjectsAreEqual(expected, actual) {
696 return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
697 }
698
699 return true
700
701}
702
703// NotEqualValues asserts that two objects are not equal even when converted to the same type
704//
705// assert.NotEqualValues(t, obj1, obj2)
706func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
707 if h, ok := t.(tHelper); ok {
708 h.Helper()
709 }
710
711 if ObjectsAreEqualValues(expected, actual) {
712 return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
713 }
714
715 return true
716}
717
718// containsElement try loop over the list check if the list includes the element.
719// return (false, false) if impossible.
720// return (true, false) if element was not found.
721// return (true, true) if element was found.
722func containsElement(list interface{}, element interface{}) (ok, found bool) {
723
724 listValue := reflect.ValueOf(list)
725 listType := reflect.TypeOf(list)
726 if listType == nil {
727 return false, false
728 }
729 listKind := listType.Kind()
730 defer func() {
731 if e := recover(); e != nil {
732 ok = false
733 found = false
734 }
735 }()
736
737 if listKind == reflect.String {
738 elementValue := reflect.ValueOf(element)
739 return true, strings.Contains(listValue.String(), elementValue.String())
740 }
741
742 if listKind == reflect.Map {
743 mapKeys := listValue.MapKeys()
744 for i := 0; i < len(mapKeys); i++ {
745 if ObjectsAreEqual(mapKeys[i].Interface(), element) {
746 return true, true
747 }
748 }
749 return true, false
750 }
751
752 for i := 0; i < listValue.Len(); i++ {
753 if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
754 return true, true
755 }
756 }
757 return true, false
758
759}
760
761// Contains asserts that the specified string, list(array, slice...) or map contains the
762// specified substring or element.
763//
764// assert.Contains(t, "Hello World", "World")
765// assert.Contains(t, ["Hello", "World"], "World")
766// assert.Contains(t, {"Hello": "World"}, "Hello")
767func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
768 if h, ok := t.(tHelper); ok {
769 h.Helper()
770 }
771
772 ok, found := containsElement(s, contains)
773 if !ok {
774 return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
775 }
776 if !found {
777 return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
778 }
779
780 return true
781
782}
783
784// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
785// specified substring or element.
786//
787// assert.NotContains(t, "Hello World", "Earth")
788// assert.NotContains(t, ["Hello", "World"], "Earth")
789// assert.NotContains(t, {"Hello": "World"}, "Earth")
790func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
791 if h, ok := t.(tHelper); ok {
792 h.Helper()
793 }
794
795 ok, found := containsElement(s, contains)
796 if !ok {
797 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
798 }
799 if found {
800 return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
801 }
802
803 return true
804
805}
806
807// Subset asserts that the specified list(array, slice...) contains all
808// elements given in the specified subset(array, slice...).
809//
810// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
811func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
812 if h, ok := t.(tHelper); ok {
813 h.Helper()
814 }
815 if subset == nil {
816 return true // we consider nil to be equal to the nil set
817 }
818
819 listKind := reflect.TypeOf(list).Kind()
820 if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
821 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
822 }
823
824 subsetKind := reflect.TypeOf(subset).Kind()
825 if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
826 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
827 }
828
829 if subsetKind == reflect.Map && listKind == reflect.Map {
830 subsetMap := reflect.ValueOf(subset)
831 actualMap := reflect.ValueOf(list)
832
833 for _, k := range subsetMap.MapKeys() {
834 ev := subsetMap.MapIndex(k)
835 av := actualMap.MapIndex(k)
836
837 if !av.IsValid() {
838 return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
839 }
840 if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
841 return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
842 }
843 }
844
845 return true
846 }
847
848 subsetList := reflect.ValueOf(subset)
849 for i := 0; i < subsetList.Len(); i++ {
850 element := subsetList.Index(i).Interface()
851 ok, found := containsElement(list, element)
852 if !ok {
853 return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
854 }
855 if !found {
856 return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...)
857 }
858 }
859
860 return true
861}
862
863// NotSubset asserts that the specified list(array, slice...) contains not all
864// elements given in the specified subset(array, slice...).
865//
866// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
867func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
868 if h, ok := t.(tHelper); ok {
869 h.Helper()
870 }
871 if subset == nil {
872 return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...)
873 }
874
875 listKind := reflect.TypeOf(list).Kind()
876 if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
877 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
878 }
879
880 subsetKind := reflect.TypeOf(subset).Kind()
881 if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
882 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
883 }
884
885 if subsetKind == reflect.Map && listKind == reflect.Map {
886 subsetMap := reflect.ValueOf(subset)
887 actualMap := reflect.ValueOf(list)
888
889 for _, k := range subsetMap.MapKeys() {
890 ev := subsetMap.MapIndex(k)
891 av := actualMap.MapIndex(k)
892
893 if !av.IsValid() {
894 return true
895 }
896 if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
897 return true
898 }
899 }
900
901 return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
902 }
903
904 subsetList := reflect.ValueOf(subset)
905 for i := 0; i < subsetList.Len(); i++ {
906 element := subsetList.Index(i).Interface()
907 ok, found := containsElement(list, element)
908 if !ok {
909 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
910 }
911 if !found {
912 return true
913 }
914 }
915
916 return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
917}
918
919// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
920// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
921// the number of appearances of each of them in both lists should match.
922//
923// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
924func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
925 if h, ok := t.(tHelper); ok {
926 h.Helper()
927 }
928 if isEmpty(listA) && isEmpty(listB) {
929 return true
930 }
931
932 if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) {
933 return false
934 }
935
936 extraA, extraB := diffLists(listA, listB)
937
938 if len(extraA) == 0 && len(extraB) == 0 {
939 return true
940 }
941
942 return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...)
943}
944
945// isList checks that the provided value is array or slice.
946func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) {
947 kind := reflect.TypeOf(list).Kind()
948 if kind != reflect.Array && kind != reflect.Slice {
949 return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind),
950 msgAndArgs...)
951 }
952 return true
953}
954
955// diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B.
956// If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and
957// 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored.
958func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) {
959 aValue := reflect.ValueOf(listA)
960 bValue := reflect.ValueOf(listB)
961
962 aLen := aValue.Len()
963 bLen := bValue.Len()
964
965 // Mark indexes in bValue that we already used
966 visited := make([]bool, bLen)
967 for i := 0; i < aLen; i++ {
968 element := aValue.Index(i).Interface()
969 found := false
970 for j := 0; j < bLen; j++ {
971 if visited[j] {
972 continue
973 }
974 if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
975 visited[j] = true
976 found = true
977 break
978 }
979 }
980 if !found {
981 extraA = append(extraA, element)
982 }
983 }
984
985 for j := 0; j < bLen; j++ {
986 if visited[j] {
987 continue
988 }
989 extraB = append(extraB, bValue.Index(j).Interface())
990 }
991
992 return
993}
994
995func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string {
996 var msg bytes.Buffer
997
998 msg.WriteString("elements differ")
999 if len(extraA) > 0 {
1000 msg.WriteString("\n\nextra elements in list A:\n")
1001 msg.WriteString(spewConfig.Sdump(extraA))
1002 }
1003 if len(extraB) > 0 {
1004 msg.WriteString("\n\nextra elements in list B:\n")
1005 msg.WriteString(spewConfig.Sdump(extraB))
1006 }
1007 msg.WriteString("\n\nlistA:\n")
1008 msg.WriteString(spewConfig.Sdump(listA))
1009 msg.WriteString("\n\nlistB:\n")
1010 msg.WriteString(spewConfig.Sdump(listB))
1011
1012 return msg.String()
1013}
1014
1015// Condition uses a Comparison to assert a complex condition.
1016func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
1017 if h, ok := t.(tHelper); ok {
1018 h.Helper()
1019 }
1020 result := comp()
1021 if !result {
1022 Fail(t, "Condition failed!", msgAndArgs...)
1023 }
1024 return result
1025}
1026
1027// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
1028// methods, and represents a simple func that takes no arguments, and returns nothing.
1029type PanicTestFunc func()
1030
1031// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
1032func didPanic(f PanicTestFunc) (didPanic bool, message interface{}, stack string) {
1033 didPanic = true
1034
1035 defer func() {
1036 message = recover()
1037 if didPanic {
1038 stack = string(debug.Stack())
1039 }
1040 }()
1041
1042 // call the target function
1043 f()
1044 didPanic = false
1045
1046 return
1047}
1048
1049// Panics asserts that the code inside the specified PanicTestFunc panics.
1050//
1051// assert.Panics(t, func(){ GoCrazy() })
1052func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1053 if h, ok := t.(tHelper); ok {
1054 h.Helper()
1055 }
1056
1057 if funcDidPanic, panicValue, _ := didPanic(f); !funcDidPanic {
1058 return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
1059 }
1060
1061 return true
1062}
1063
1064// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
1065// the recovered panic value equals the expected panic value.
1066//
1067// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
1068func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1069 if h, ok := t.(tHelper); ok {
1070 h.Helper()
1071 }
1072
1073 funcDidPanic, panicValue, panickedStack := didPanic(f)
1074 if !funcDidPanic {
1075 return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
1076 }
1077 if panicValue != expected {
1078 return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, expected, panicValue, panickedStack), msgAndArgs...)
1079 }
1080
1081 return true
1082}
1083
1084// PanicsWithError asserts that the code inside the specified PanicTestFunc
1085// panics, and that the recovered panic value is an error that satisfies the
1086// EqualError comparison.
1087//
1088// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
1089func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1090 if h, ok := t.(tHelper); ok {
1091 h.Helper()
1092 }
1093
1094 funcDidPanic, panicValue, panickedStack := didPanic(f)
1095 if !funcDidPanic {
1096 return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
1097 }
1098 panicErr, ok := panicValue.(error)
1099 if !ok || panicErr.Error() != errString {
1100 return Fail(t, fmt.Sprintf("func %#v should panic with error message:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, errString, panicValue, panickedStack), msgAndArgs...)
1101 }
1102
1103 return true
1104}
1105
1106// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
1107//
1108// assert.NotPanics(t, func(){ RemainCalm() })
1109func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1110 if h, ok := t.(tHelper); ok {
1111 h.Helper()
1112 }
1113
1114 if funcDidPanic, panicValue, panickedStack := didPanic(f); funcDidPanic {
1115 return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v\n\tPanic stack:\t%s", f, panicValue, panickedStack), msgAndArgs...)
1116 }
1117
1118 return true
1119}
1120
1121// WithinDuration asserts that the two times are within duration delta of each other.
1122//
1123// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
1124func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
1125 if h, ok := t.(tHelper); ok {
1126 h.Helper()
1127 }
1128
1129 dt := expected.Sub(actual)
1130 if dt < -delta || dt > delta {
1131 return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
1132 }
1133
1134 return true
1135}
1136
1137// WithinRange asserts that a time is within a time range (inclusive).
1138//
1139// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
1140func WithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool {
1141 if h, ok := t.(tHelper); ok {
1142 h.Helper()
1143 }
1144
1145 if end.Before(start) {
1146 return Fail(t, "Start should be before end", msgAndArgs...)
1147 }
1148
1149 if actual.Before(start) {
1150 return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is before the range", actual, start, end), msgAndArgs...)
1151 } else if actual.After(end) {
1152 return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is after the range", actual, start, end), msgAndArgs...)
1153 }
1154
1155 return true
1156}
1157
1158func toFloat(x interface{}) (float64, bool) {
1159 var xf float64
1160 xok := true
1161
1162 switch xn := x.(type) {
1163 case uint:
1164 xf = float64(xn)
1165 case uint8:
1166 xf = float64(xn)
1167 case uint16:
1168 xf = float64(xn)
1169 case uint32:
1170 xf = float64(xn)
1171 case uint64:
1172 xf = float64(xn)
1173 case int:
1174 xf = float64(xn)
1175 case int8:
1176 xf = float64(xn)
1177 case int16:
1178 xf = float64(xn)
1179 case int32:
1180 xf = float64(xn)
1181 case int64:
1182 xf = float64(xn)
1183 case float32:
1184 xf = float64(xn)
1185 case float64:
1186 xf = xn
1187 case time.Duration:
1188 xf = float64(xn)
1189 default:
1190 xok = false
1191 }
1192
1193 return xf, xok
1194}
1195
1196// InDelta asserts that the two numerals are within delta of each other.
1197//
1198// assert.InDelta(t, math.Pi, 22/7.0, 0.01)
1199func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1200 if h, ok := t.(tHelper); ok {
1201 h.Helper()
1202 }
1203
1204 af, aok := toFloat(expected)
1205 bf, bok := toFloat(actual)
1206
1207 if !aok || !bok {
1208 return Fail(t, "Parameters must be numerical", msgAndArgs...)
1209 }
1210
1211 if math.IsNaN(af) && math.IsNaN(bf) {
1212 return true
1213 }
1214
1215 if math.IsNaN(af) {
1216 return Fail(t, "Expected must not be NaN", msgAndArgs...)
1217 }
1218
1219 if math.IsNaN(bf) {
1220 return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
1221 }
1222
1223 dt := af - bf
1224 if dt < -delta || dt > delta {
1225 return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
1226 }
1227
1228 return true
1229}
1230
1231// InDeltaSlice is the same as InDelta, except it compares two slices.
1232func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1233 if h, ok := t.(tHelper); ok {
1234 h.Helper()
1235 }
1236 if expected == nil || actual == nil ||
1237 reflect.TypeOf(actual).Kind() != reflect.Slice ||
1238 reflect.TypeOf(expected).Kind() != reflect.Slice {
1239 return Fail(t, "Parameters must be slice", msgAndArgs...)
1240 }
1241
1242 actualSlice := reflect.ValueOf(actual)
1243 expectedSlice := reflect.ValueOf(expected)
1244
1245 for i := 0; i < actualSlice.Len(); i++ {
1246 result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
1247 if !result {
1248 return result
1249 }
1250 }
1251
1252 return true
1253}
1254
1255// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
1256func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1257 if h, ok := t.(tHelper); ok {
1258 h.Helper()
1259 }
1260 if expected == nil || actual == nil ||
1261 reflect.TypeOf(actual).Kind() != reflect.Map ||
1262 reflect.TypeOf(expected).Kind() != reflect.Map {
1263 return Fail(t, "Arguments must be maps", msgAndArgs...)
1264 }
1265
1266 expectedMap := reflect.ValueOf(expected)
1267 actualMap := reflect.ValueOf(actual)
1268
1269 if expectedMap.Len() != actualMap.Len() {
1270 return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
1271 }
1272
1273 for _, k := range expectedMap.MapKeys() {
1274 ev := expectedMap.MapIndex(k)
1275 av := actualMap.MapIndex(k)
1276
1277 if !ev.IsValid() {
1278 return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
1279 }
1280
1281 if !av.IsValid() {
1282 return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
1283 }
1284
1285 if !InDelta(
1286 t,
1287 ev.Interface(),
1288 av.Interface(),
1289 delta,
1290 msgAndArgs...,
1291 ) {
1292 return false
1293 }
1294 }
1295
1296 return true
1297}
1298
1299func calcRelativeError(expected, actual interface{}) (float64, error) {
1300 af, aok := toFloat(expected)
1301 bf, bok := toFloat(actual)
1302 if !aok || !bok {
1303 return 0, fmt.Errorf("Parameters must be numerical")
1304 }
1305 if math.IsNaN(af) && math.IsNaN(bf) {
1306 return 0, nil
1307 }
1308 if math.IsNaN(af) {
1309 return 0, errors.New("expected value must not be NaN")
1310 }
1311 if af == 0 {
1312 return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
1313 }
1314 if math.IsNaN(bf) {
1315 return 0, errors.New("actual value must not be NaN")
1316 }
1317
1318 return math.Abs(af-bf) / math.Abs(af), nil
1319}
1320
1321// InEpsilon asserts that expected and actual have a relative error less than epsilon
1322func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
1323 if h, ok := t.(tHelper); ok {
1324 h.Helper()
1325 }
1326 if math.IsNaN(epsilon) {
1327 return Fail(t, "epsilon must not be NaN")
1328 }
1329 actualEpsilon, err := calcRelativeError(expected, actual)
1330 if err != nil {
1331 return Fail(t, err.Error(), msgAndArgs...)
1332 }
1333 if actualEpsilon > epsilon {
1334 return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
1335 " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
1336 }
1337
1338 return true
1339}
1340
1341// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
1342func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
1343 if h, ok := t.(tHelper); ok {
1344 h.Helper()
1345 }
1346 if expected == nil || actual == nil ||
1347 reflect.TypeOf(actual).Kind() != reflect.Slice ||
1348 reflect.TypeOf(expected).Kind() != reflect.Slice {
1349 return Fail(t, "Parameters must be slice", msgAndArgs...)
1350 }
1351
1352 actualSlice := reflect.ValueOf(actual)
1353 expectedSlice := reflect.ValueOf(expected)
1354
1355 for i := 0; i < actualSlice.Len(); i++ {
1356 result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
1357 if !result {
1358 return result
1359 }
1360 }
1361
1362 return true
1363}
1364
1365/*
1366 Errors
1367*/
1368
1369// NoError asserts that a function returned no error (i.e. `nil`).
1370//
1371// actualObj, err := SomeFunction()
1372// if assert.NoError(t, err) {
1373// assert.Equal(t, expectedObj, actualObj)
1374// }
1375func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
1376 if err != nil {
1377 if h, ok := t.(tHelper); ok {
1378 h.Helper()
1379 }
1380 return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
1381 }
1382
1383 return true
1384}
1385
1386// Error asserts that a function returned an error (i.e. not `nil`).
1387//
1388// actualObj, err := SomeFunction()
1389// if assert.Error(t, err) {
1390// assert.Equal(t, expectedError, err)
1391// }
1392func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
1393 if err == nil {
1394 if h, ok := t.(tHelper); ok {
1395 h.Helper()
1396 }
1397 return Fail(t, "An error is expected but got nil.", msgAndArgs...)
1398 }
1399
1400 return true
1401}
1402
1403// EqualError asserts that a function returned an error (i.e. not `nil`)
1404// and that it is equal to the provided error.
1405//
1406// actualObj, err := SomeFunction()
1407// assert.EqualError(t, err, expectedErrorString)
1408func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
1409 if h, ok := t.(tHelper); ok {
1410 h.Helper()
1411 }
1412 if !Error(t, theError, msgAndArgs...) {
1413 return false
1414 }
1415 expected := errString
1416 actual := theError.Error()
1417 // don't need to use deep equals here, we know they are both strings
1418 if expected != actual {
1419 return Fail(t, fmt.Sprintf("Error message not equal:\n"+
1420 "expected: %q\n"+
1421 "actual : %q", expected, actual), msgAndArgs...)
1422 }
1423 return true
1424}
1425
1426// ErrorContains asserts that a function returned an error (i.e. not `nil`)
1427// and that the error contains the specified substring.
1428//
1429// actualObj, err := SomeFunction()
1430// assert.ErrorContains(t, err, expectedErrorSubString)
1431func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool {
1432 if h, ok := t.(tHelper); ok {
1433 h.Helper()
1434 }
1435 if !Error(t, theError, msgAndArgs...) {
1436 return false
1437 }
1438
1439 actual := theError.Error()
1440 if !strings.Contains(actual, contains) {
1441 return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...)
1442 }
1443
1444 return true
1445}
1446
1447// matchRegexp return true if a specified regexp matches a string.
1448func matchRegexp(rx interface{}, str interface{}) bool {
1449
1450 var r *regexp.Regexp
1451 if rr, ok := rx.(*regexp.Regexp); ok {
1452 r = rr
1453 } else {
1454 r = regexp.MustCompile(fmt.Sprint(rx))
1455 }
1456
1457 return (r.FindStringIndex(fmt.Sprint(str)) != nil)
1458
1459}
1460
1461// Regexp asserts that a specified regexp matches a string.
1462//
1463// assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
1464// assert.Regexp(t, "start...$", "it's not starting")
1465func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1466 if h, ok := t.(tHelper); ok {
1467 h.Helper()
1468 }
1469
1470 match := matchRegexp(rx, str)
1471
1472 if !match {
1473 Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
1474 }
1475
1476 return match
1477}
1478
1479// NotRegexp asserts that a specified regexp does not match a string.
1480//
1481// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
1482// assert.NotRegexp(t, "^start", "it's not starting")
1483func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1484 if h, ok := t.(tHelper); ok {
1485 h.Helper()
1486 }
1487 match := matchRegexp(rx, str)
1488
1489 if match {
1490 Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
1491 }
1492
1493 return !match
1494
1495}
1496
1497// Zero asserts that i is the zero value for its type.
1498func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
1499 if h, ok := t.(tHelper); ok {
1500 h.Helper()
1501 }
1502 if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
1503 return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
1504 }
1505 return true
1506}
1507
1508// NotZero asserts that i is not the zero value for its type.
1509func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
1510 if h, ok := t.(tHelper); ok {
1511 h.Helper()
1512 }
1513 if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
1514 return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
1515 }
1516 return true
1517}
1518
1519// FileExists checks whether a file exists in the given path. It also fails if
1520// the path points to a directory or there is an error when trying to check the file.
1521func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1522 if h, ok := t.(tHelper); ok {
1523 h.Helper()
1524 }
1525 info, err := os.Lstat(path)
1526 if err != nil {
1527 if os.IsNotExist(err) {
1528 return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
1529 }
1530 return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
1531 }
1532 if info.IsDir() {
1533 return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
1534 }
1535 return true
1536}
1537
1538// NoFileExists checks whether a file does not exist in a given path. It fails
1539// if the path points to an existing _file_ only.
1540func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1541 if h, ok := t.(tHelper); ok {
1542 h.Helper()
1543 }
1544 info, err := os.Lstat(path)
1545 if err != nil {
1546 return true
1547 }
1548 if info.IsDir() {
1549 return true
1550 }
1551 return Fail(t, fmt.Sprintf("file %q exists", path), msgAndArgs...)
1552}
1553
1554// DirExists checks whether a directory exists in the given path. It also fails
1555// if the path is a file rather a directory or there is an error checking whether it exists.
1556func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1557 if h, ok := t.(tHelper); ok {
1558 h.Helper()
1559 }
1560 info, err := os.Lstat(path)
1561 if err != nil {
1562 if os.IsNotExist(err) {
1563 return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
1564 }
1565 return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
1566 }
1567 if !info.IsDir() {
1568 return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
1569 }
1570 return true
1571}
1572
1573// NoDirExists checks whether a directory does not exist in the given path.
1574// It fails if the path points to an existing _directory_ only.
1575func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1576 if h, ok := t.(tHelper); ok {
1577 h.Helper()
1578 }
1579 info, err := os.Lstat(path)
1580 if err != nil {
1581 if os.IsNotExist(err) {
1582 return true
1583 }
1584 return true
1585 }
1586 if !info.IsDir() {
1587 return true
1588 }
1589 return Fail(t, fmt.Sprintf("directory %q exists", path), msgAndArgs...)
1590}
1591
1592// JSONEq asserts that two JSON strings are equivalent.
1593//
1594// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
1595func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
1596 if h, ok := t.(tHelper); ok {
1597 h.Helper()
1598 }
1599 var expectedJSONAsInterface, actualJSONAsInterface interface{}
1600
1601 if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
1602 return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
1603 }
1604
1605 if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
1606 return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
1607 }
1608
1609 return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
1610}
1611
1612// YAMLEq asserts that two YAML strings are equivalent.
1613func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
1614 if h, ok := t.(tHelper); ok {
1615 h.Helper()
1616 }
1617 var expectedYAMLAsInterface, actualYAMLAsInterface interface{}
1618
1619 if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil {
1620 return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...)
1621 }
1622
1623 if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil {
1624 return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...)
1625 }
1626
1627 return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...)
1628}
1629
1630func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
1631 t := reflect.TypeOf(v)
1632 k := t.Kind()
1633
1634 if k == reflect.Ptr {
1635 t = t.Elem()
1636 k = t.Kind()
1637 }
1638 return t, k
1639}
1640
1641// diff returns a diff of both values as long as both are of the same type and
1642// are a struct, map, slice, array or string. Otherwise it returns an empty string.
1643func diff(expected interface{}, actual interface{}) string {
1644 if expected == nil || actual == nil {
1645 return ""
1646 }
1647
1648 et, ek := typeAndKind(expected)
1649 at, _ := typeAndKind(actual)
1650
1651 if et != at {
1652 return ""
1653 }
1654
1655 if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
1656 return ""
1657 }
1658
1659 var e, a string
1660
1661 switch et {
1662 case reflect.TypeOf(""):
1663 e = reflect.ValueOf(expected).String()
1664 a = reflect.ValueOf(actual).String()
1665 case reflect.TypeOf(time.Time{}):
1666 e = spewConfigStringerEnabled.Sdump(expected)
1667 a = spewConfigStringerEnabled.Sdump(actual)
1668 default:
1669 e = spewConfig.Sdump(expected)
1670 a = spewConfig.Sdump(actual)
1671 }
1672
1673 diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
1674 A: difflib.SplitLines(e),
1675 B: difflib.SplitLines(a),
1676 FromFile: "Expected",
1677 FromDate: "",
1678 ToFile: "Actual",
1679 ToDate: "",
1680 Context: 1,
1681 })
1682
1683 return "\n\nDiff:\n" + diff
1684}
1685
1686func isFunction(arg interface{}) bool {
1687 if arg == nil {
1688 return false
1689 }
1690 return reflect.TypeOf(arg).Kind() == reflect.Func
1691}
1692
1693var spewConfig = spew.ConfigState{
1694 Indent: " ",
1695 DisablePointerAddresses: true,
1696 DisableCapacities: true,
1697 SortKeys: true,
1698 DisableMethods: true,
1699 MaxDepth: 10,
1700}
1701
1702var spewConfigStringerEnabled = spew.ConfigState{
1703 Indent: " ",
1704 DisablePointerAddresses: true,
1705 DisableCapacities: true,
1706 SortKeys: true,
1707 MaxDepth: 10,
1708}
1709
1710type tHelper interface {
1711 Helper()
1712}
1713
1714// Eventually asserts that given condition will be met in waitFor time,
1715// periodically checking target function each tick.
1716//
1717// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
1718func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
1719 if h, ok := t.(tHelper); ok {
1720 h.Helper()
1721 }
1722
1723 ch := make(chan bool, 1)
1724
1725 timer := time.NewTimer(waitFor)
1726 defer timer.Stop()
1727
1728 ticker := time.NewTicker(tick)
1729 defer ticker.Stop()
1730
1731 for tick := ticker.C; ; {
1732 select {
1733 case <-timer.C:
1734 return Fail(t, "Condition never satisfied", msgAndArgs...)
1735 case <-tick:
1736 tick = nil
1737 go func() { ch <- condition() }()
1738 case v := <-ch:
1739 if v {
1740 return true
1741 }
1742 tick = ticker.C
1743 }
1744 }
1745}
1746
1747// Never asserts that the given condition doesn't satisfy in waitFor time,
1748// periodically checking the target function each tick.
1749//
1750// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
1751func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
1752 if h, ok := t.(tHelper); ok {
1753 h.Helper()
1754 }
1755
1756 ch := make(chan bool, 1)
1757
1758 timer := time.NewTimer(waitFor)
1759 defer timer.Stop()
1760
1761 ticker := time.NewTicker(tick)
1762 defer ticker.Stop()
1763
1764 for tick := ticker.C; ; {
1765 select {
1766 case <-timer.C:
1767 return true
1768 case <-tick:
1769 tick = nil
1770 go func() { ch <- condition() }()
1771 case v := <-ch:
1772 if v {
1773 return Fail(t, "Condition satisfied", msgAndArgs...)
1774 }
1775 tick = ticker.C
1776 }
1777 }
1778}
1779
1780// ErrorIs asserts that at least one of the errors in err's chain matches target.
1781// This is a wrapper for errors.Is.
1782func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
1783 if h, ok := t.(tHelper); ok {
1784 h.Helper()
1785 }
1786 if errors.Is(err, target) {
1787 return true
1788 }
1789
1790 var expectedText string
1791 if target != nil {
1792 expectedText = target.Error()
1793 }
1794
1795 chain := buildErrorChainString(err)
1796
1797 return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+
1798 "expected: %q\n"+
1799 "in chain: %s", expectedText, chain,
1800 ), msgAndArgs...)
1801}
1802
1803// NotErrorIs asserts that at none of the errors in err's chain matches target.
1804// This is a wrapper for errors.Is.
1805func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
1806 if h, ok := t.(tHelper); ok {
1807 h.Helper()
1808 }
1809 if !errors.Is(err, target) {
1810 return true
1811 }
1812
1813 var expectedText string
1814 if target != nil {
1815 expectedText = target.Error()
1816 }
1817
1818 chain := buildErrorChainString(err)
1819
1820 return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
1821 "found: %q\n"+
1822 "in chain: %s", expectedText, chain,
1823 ), msgAndArgs...)
1824}
1825
1826// ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value.
1827// This is a wrapper for errors.As.
1828func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool {
1829 if h, ok := t.(tHelper); ok {
1830 h.Helper()
1831 }
1832 if errors.As(err, target) {
1833 return true
1834 }
1835
1836 chain := buildErrorChainString(err)
1837
1838 return Fail(t, fmt.Sprintf("Should be in error chain:\n"+
1839 "expected: %q\n"+
1840 "in chain: %s", target, chain,
1841 ), msgAndArgs...)
1842}
1843
1844func buildErrorChainString(err error) string {
1845 if err == nil {
1846 return ""
1847 }
1848
1849 e := errors.Unwrap(err)
1850 chain := fmt.Sprintf("%q", err.Error())
1851 for e != nil {
1852 chain += fmt.Sprintf("\n\t%q", e.Error())
1853 e = errors.Unwrap(e)
1854 }
1855 return chain
1856}