blob: 0357b2231a2cdd81f336ebd464acc9d134e53a14 [file] [log] [blame]
Elia Battistonc8d0d462022-02-22 16:30:51 +01001package 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 file = parts[len(parts)-1]
144 if len(parts) > 1 {
145 dir := parts[len(parts)-2]
146 if (dir != "assert" && dir != "mock" && dir != "require") || file == "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},
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.Array, 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 default:
577 zero := reflect.Zero(objValue.Type())
578 return reflect.DeepEqual(object, zero.Interface())
579 }
580}
581
582// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
583// a slice or a channel with len == 0.
584//
585// assert.Empty(t, obj)
586func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
587 pass := isEmpty(object)
588 if !pass {
589 if h, ok := t.(tHelper); ok {
590 h.Helper()
591 }
592 Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
593 }
594
595 return pass
596
597}
598
599// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
600// a slice or a channel with len == 0.
601//
602// if assert.NotEmpty(t, obj) {
603// assert.Equal(t, "two", obj[1])
604// }
605func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
606 pass := !isEmpty(object)
607 if !pass {
608 if h, ok := t.(tHelper); ok {
609 h.Helper()
610 }
611 Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
612 }
613
614 return pass
615
616}
617
618// getLen try to get length of object.
619// return (false, 0) if impossible.
620func getLen(x interface{}) (ok bool, length int) {
621 v := reflect.ValueOf(x)
622 defer func() {
623 if e := recover(); e != nil {
624 ok = false
625 }
626 }()
627 return true, v.Len()
628}
629
630// Len asserts that the specified object has specific length.
631// Len also fails if the object has a type that len() not accept.
632//
633// assert.Len(t, mySlice, 3)
634func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
635 if h, ok := t.(tHelper); ok {
636 h.Helper()
637 }
638 ok, l := getLen(object)
639 if !ok {
640 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
641 }
642
643 if l != length {
644 return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
645 }
646 return true
647}
648
649// True asserts that the specified value is true.
650//
651// assert.True(t, myBool)
652func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
653 if !value {
654 if h, ok := t.(tHelper); ok {
655 h.Helper()
656 }
657 return Fail(t, "Should be true", msgAndArgs...)
658 }
659
660 return true
661
662}
663
664// False asserts that the specified value is false.
665//
666// assert.False(t, myBool)
667func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
668 if value {
669 if h, ok := t.(tHelper); ok {
670 h.Helper()
671 }
672 return Fail(t, "Should be false", msgAndArgs...)
673 }
674
675 return true
676
677}
678
679// NotEqual asserts that the specified values are NOT equal.
680//
681// assert.NotEqual(t, obj1, obj2)
682//
683// Pointer variable equality is determined based on the equality of the
684// referenced values (as opposed to the memory addresses).
685func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
686 if h, ok := t.(tHelper); ok {
687 h.Helper()
688 }
689 if err := validateEqualArgs(expected, actual); err != nil {
690 return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
691 expected, actual, err), msgAndArgs...)
692 }
693
694 if ObjectsAreEqual(expected, actual) {
695 return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
696 }
697
698 return true
699
700}
701
702// NotEqualValues asserts that two objects are not equal even when converted to the same type
703//
704// assert.NotEqualValues(t, obj1, obj2)
705func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
706 if h, ok := t.(tHelper); ok {
707 h.Helper()
708 }
709
710 if ObjectsAreEqualValues(expected, actual) {
711 return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
712 }
713
714 return true
715}
716
717// containsElement try loop over the list check if the list includes the element.
718// return (false, false) if impossible.
719// return (true, false) if element was not found.
720// return (true, true) if element was found.
Elia Battiston4750d3c2022-07-14 13:24:56 +0000721func containsElement(list interface{}, element interface{}) (ok, found bool) {
Elia Battistonc8d0d462022-02-22 16:30:51 +0100722
723 listValue := reflect.ValueOf(list)
Elia Battiston4750d3c2022-07-14 13:24:56 +0000724 listType := reflect.TypeOf(list)
725 if listType == nil {
726 return false, false
727 }
728 listKind := listType.Kind()
Elia Battistonc8d0d462022-02-22 16:30:51 +0100729 defer func() {
730 if e := recover(); e != nil {
731 ok = false
732 found = false
733 }
734 }()
735
736 if listKind == reflect.String {
737 elementValue := reflect.ValueOf(element)
738 return true, strings.Contains(listValue.String(), elementValue.String())
739 }
740
741 if listKind == reflect.Map {
742 mapKeys := listValue.MapKeys()
743 for i := 0; i < len(mapKeys); i++ {
744 if ObjectsAreEqual(mapKeys[i].Interface(), element) {
745 return true, true
746 }
747 }
748 return true, false
749 }
750
751 for i := 0; i < listValue.Len(); i++ {
752 if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
753 return true, true
754 }
755 }
756 return true, false
757
758}
759
760// Contains asserts that the specified string, list(array, slice...) or map contains the
761// specified substring or element.
762//
763// assert.Contains(t, "Hello World", "World")
764// assert.Contains(t, ["Hello", "World"], "World")
765// assert.Contains(t, {"Hello": "World"}, "Hello")
766func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
767 if h, ok := t.(tHelper); ok {
768 h.Helper()
769 }
770
Elia Battiston4750d3c2022-07-14 13:24:56 +0000771 ok, found := containsElement(s, contains)
Elia Battistonc8d0d462022-02-22 16:30:51 +0100772 if !ok {
773 return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
774 }
775 if !found {
776 return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
777 }
778
779 return true
780
781}
782
783// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
784// specified substring or element.
785//
786// assert.NotContains(t, "Hello World", "Earth")
787// assert.NotContains(t, ["Hello", "World"], "Earth")
788// assert.NotContains(t, {"Hello": "World"}, "Earth")
789func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
790 if h, ok := t.(tHelper); ok {
791 h.Helper()
792 }
793
Elia Battiston4750d3c2022-07-14 13:24:56 +0000794 ok, found := containsElement(s, contains)
Elia Battistonc8d0d462022-02-22 16:30:51 +0100795 if !ok {
796 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
797 }
798 if found {
799 return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
800 }
801
802 return true
803
804}
805
806// Subset asserts that the specified list(array, slice...) contains all
807// elements given in the specified subset(array, slice...).
808//
809// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
810func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
811 if h, ok := t.(tHelper); ok {
812 h.Helper()
813 }
814 if subset == nil {
815 return true // we consider nil to be equal to the nil set
816 }
817
818 subsetValue := reflect.ValueOf(subset)
819 defer func() {
820 if e := recover(); e != nil {
821 ok = false
822 }
823 }()
824
825 listKind := reflect.TypeOf(list).Kind()
826 subsetKind := reflect.TypeOf(subset).Kind()
827
828 if listKind != reflect.Array && listKind != reflect.Slice {
829 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
830 }
831
832 if subsetKind != reflect.Array && subsetKind != reflect.Slice {
833 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
834 }
835
836 for i := 0; i < subsetValue.Len(); i++ {
837 element := subsetValue.Index(i).Interface()
Elia Battiston4750d3c2022-07-14 13:24:56 +0000838 ok, found := containsElement(list, element)
Elia Battistonc8d0d462022-02-22 16:30:51 +0100839 if !ok {
840 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
841 }
842 if !found {
843 return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...)
844 }
845 }
846
847 return true
848}
849
850// NotSubset asserts that the specified list(array, slice...) contains not all
851// elements given in the specified subset(array, slice...).
852//
853// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
854func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
855 if h, ok := t.(tHelper); ok {
856 h.Helper()
857 }
858 if subset == nil {
Elia Battiston4750d3c2022-07-14 13:24:56 +0000859 return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...)
Elia Battistonc8d0d462022-02-22 16:30:51 +0100860 }
861
862 subsetValue := reflect.ValueOf(subset)
863 defer func() {
864 if e := recover(); e != nil {
865 ok = false
866 }
867 }()
868
869 listKind := reflect.TypeOf(list).Kind()
870 subsetKind := reflect.TypeOf(subset).Kind()
871
872 if listKind != reflect.Array && listKind != reflect.Slice {
873 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
874 }
875
876 if subsetKind != reflect.Array && subsetKind != reflect.Slice {
877 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
878 }
879
880 for i := 0; i < subsetValue.Len(); i++ {
881 element := subsetValue.Index(i).Interface()
Elia Battiston4750d3c2022-07-14 13:24:56 +0000882 ok, found := containsElement(list, element)
Elia Battistonc8d0d462022-02-22 16:30:51 +0100883 if !ok {
884 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
885 }
886 if !found {
887 return true
888 }
889 }
890
891 return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
892}
893
894// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
895// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
896// the number of appearances of each of them in both lists should match.
897//
898// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
899func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
900 if h, ok := t.(tHelper); ok {
901 h.Helper()
902 }
903 if isEmpty(listA) && isEmpty(listB) {
904 return true
905 }
906
907 if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) {
908 return false
909 }
910
911 extraA, extraB := diffLists(listA, listB)
912
913 if len(extraA) == 0 && len(extraB) == 0 {
914 return true
915 }
916
917 return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...)
918}
919
920// isList checks that the provided value is array or slice.
921func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) {
922 kind := reflect.TypeOf(list).Kind()
923 if kind != reflect.Array && kind != reflect.Slice {
924 return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind),
925 msgAndArgs...)
926 }
927 return true
928}
929
930// diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B.
931// If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and
932// 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored.
933func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) {
934 aValue := reflect.ValueOf(listA)
935 bValue := reflect.ValueOf(listB)
936
937 aLen := aValue.Len()
938 bLen := bValue.Len()
939
940 // Mark indexes in bValue that we already used
941 visited := make([]bool, bLen)
942 for i := 0; i < aLen; i++ {
943 element := aValue.Index(i).Interface()
944 found := false
945 for j := 0; j < bLen; j++ {
946 if visited[j] {
947 continue
948 }
949 if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
950 visited[j] = true
951 found = true
952 break
953 }
954 }
955 if !found {
956 extraA = append(extraA, element)
957 }
958 }
959
960 for j := 0; j < bLen; j++ {
961 if visited[j] {
962 continue
963 }
964 extraB = append(extraB, bValue.Index(j).Interface())
965 }
966
967 return
968}
969
970func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string {
971 var msg bytes.Buffer
972
973 msg.WriteString("elements differ")
974 if len(extraA) > 0 {
975 msg.WriteString("\n\nextra elements in list A:\n")
976 msg.WriteString(spewConfig.Sdump(extraA))
977 }
978 if len(extraB) > 0 {
979 msg.WriteString("\n\nextra elements in list B:\n")
980 msg.WriteString(spewConfig.Sdump(extraB))
981 }
982 msg.WriteString("\n\nlistA:\n")
983 msg.WriteString(spewConfig.Sdump(listA))
984 msg.WriteString("\n\nlistB:\n")
985 msg.WriteString(spewConfig.Sdump(listB))
986
987 return msg.String()
988}
989
990// Condition uses a Comparison to assert a complex condition.
991func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
992 if h, ok := t.(tHelper); ok {
993 h.Helper()
994 }
995 result := comp()
996 if !result {
997 Fail(t, "Condition failed!", msgAndArgs...)
998 }
999 return result
1000}
1001
1002// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
1003// methods, and represents a simple func that takes no arguments, and returns nothing.
1004type PanicTestFunc func()
1005
1006// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
Elia Battiston4750d3c2022-07-14 13:24:56 +00001007func didPanic(f PanicTestFunc) (didPanic bool, message interface{}, stack string) {
1008 didPanic = true
Elia Battistonc8d0d462022-02-22 16:30:51 +01001009
Elia Battiston4750d3c2022-07-14 13:24:56 +00001010 defer func() {
1011 message = recover()
1012 if didPanic {
1013 stack = string(debug.Stack())
1014 }
Elia Battistonc8d0d462022-02-22 16:30:51 +01001015 }()
1016
Elia Battiston4750d3c2022-07-14 13:24:56 +00001017 // call the target function
1018 f()
1019 didPanic = false
Elia Battistonc8d0d462022-02-22 16:30:51 +01001020
Elia Battiston4750d3c2022-07-14 13:24:56 +00001021 return
Elia Battistonc8d0d462022-02-22 16:30:51 +01001022}
1023
1024// Panics asserts that the code inside the specified PanicTestFunc panics.
1025//
1026// assert.Panics(t, func(){ GoCrazy() })
1027func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1028 if h, ok := t.(tHelper); ok {
1029 h.Helper()
1030 }
1031
1032 if funcDidPanic, panicValue, _ := didPanic(f); !funcDidPanic {
1033 return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
1034 }
1035
1036 return true
1037}
1038
1039// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
1040// the recovered panic value equals the expected panic value.
1041//
1042// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
1043func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1044 if h, ok := t.(tHelper); ok {
1045 h.Helper()
1046 }
1047
1048 funcDidPanic, panicValue, panickedStack := didPanic(f)
1049 if !funcDidPanic {
1050 return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
1051 }
1052 if panicValue != expected {
1053 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...)
1054 }
1055
1056 return true
1057}
1058
1059// PanicsWithError asserts that the code inside the specified PanicTestFunc
1060// panics, and that the recovered panic value is an error that satisfies the
1061// EqualError comparison.
1062//
1063// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
1064func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1065 if h, ok := t.(tHelper); ok {
1066 h.Helper()
1067 }
1068
1069 funcDidPanic, panicValue, panickedStack := didPanic(f)
1070 if !funcDidPanic {
1071 return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
1072 }
1073 panicErr, ok := panicValue.(error)
1074 if !ok || panicErr.Error() != errString {
1075 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...)
1076 }
1077
1078 return true
1079}
1080
1081// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
1082//
1083// assert.NotPanics(t, func(){ RemainCalm() })
1084func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
1085 if h, ok := t.(tHelper); ok {
1086 h.Helper()
1087 }
1088
1089 if funcDidPanic, panicValue, panickedStack := didPanic(f); funcDidPanic {
1090 return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v\n\tPanic stack:\t%s", f, panicValue, panickedStack), msgAndArgs...)
1091 }
1092
1093 return true
1094}
1095
1096// WithinDuration asserts that the two times are within duration delta of each other.
1097//
1098// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
1099func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
1100 if h, ok := t.(tHelper); ok {
1101 h.Helper()
1102 }
1103
1104 dt := expected.Sub(actual)
1105 if dt < -delta || dt > delta {
1106 return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
1107 }
1108
1109 return true
1110}
1111
1112func toFloat(x interface{}) (float64, bool) {
1113 var xf float64
1114 xok := true
1115
1116 switch xn := x.(type) {
1117 case uint:
1118 xf = float64(xn)
1119 case uint8:
1120 xf = float64(xn)
1121 case uint16:
1122 xf = float64(xn)
1123 case uint32:
1124 xf = float64(xn)
1125 case uint64:
1126 xf = float64(xn)
1127 case int:
1128 xf = float64(xn)
1129 case int8:
1130 xf = float64(xn)
1131 case int16:
1132 xf = float64(xn)
1133 case int32:
1134 xf = float64(xn)
1135 case int64:
1136 xf = float64(xn)
1137 case float32:
1138 xf = float64(xn)
1139 case float64:
1140 xf = xn
1141 case time.Duration:
1142 xf = float64(xn)
1143 default:
1144 xok = false
1145 }
1146
1147 return xf, xok
1148}
1149
1150// InDelta asserts that the two numerals are within delta of each other.
1151//
1152// assert.InDelta(t, math.Pi, 22/7.0, 0.01)
1153func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1154 if h, ok := t.(tHelper); ok {
1155 h.Helper()
1156 }
1157
1158 af, aok := toFloat(expected)
1159 bf, bok := toFloat(actual)
1160
1161 if !aok || !bok {
Elia Battiston4750d3c2022-07-14 13:24:56 +00001162 return Fail(t, "Parameters must be numerical", msgAndArgs...)
1163 }
1164
1165 if math.IsNaN(af) && math.IsNaN(bf) {
1166 return true
Elia Battistonc8d0d462022-02-22 16:30:51 +01001167 }
1168
1169 if math.IsNaN(af) {
Elia Battiston4750d3c2022-07-14 13:24:56 +00001170 return Fail(t, "Expected must not be NaN", msgAndArgs...)
Elia Battistonc8d0d462022-02-22 16:30:51 +01001171 }
1172
1173 if math.IsNaN(bf) {
1174 return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
1175 }
1176
1177 dt := af - bf
1178 if dt < -delta || dt > delta {
1179 return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
1180 }
1181
1182 return true
1183}
1184
1185// InDeltaSlice is the same as InDelta, except it compares two slices.
1186func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1187 if h, ok := t.(tHelper); ok {
1188 h.Helper()
1189 }
1190 if expected == nil || actual == nil ||
1191 reflect.TypeOf(actual).Kind() != reflect.Slice ||
1192 reflect.TypeOf(expected).Kind() != reflect.Slice {
Elia Battiston4750d3c2022-07-14 13:24:56 +00001193 return Fail(t, "Parameters must be slice", msgAndArgs...)
Elia Battistonc8d0d462022-02-22 16:30:51 +01001194 }
1195
1196 actualSlice := reflect.ValueOf(actual)
1197 expectedSlice := reflect.ValueOf(expected)
1198
1199 for i := 0; i < actualSlice.Len(); i++ {
1200 result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
1201 if !result {
1202 return result
1203 }
1204 }
1205
1206 return true
1207}
1208
1209// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
1210func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
1211 if h, ok := t.(tHelper); ok {
1212 h.Helper()
1213 }
1214 if expected == nil || actual == nil ||
1215 reflect.TypeOf(actual).Kind() != reflect.Map ||
1216 reflect.TypeOf(expected).Kind() != reflect.Map {
1217 return Fail(t, "Arguments must be maps", msgAndArgs...)
1218 }
1219
1220 expectedMap := reflect.ValueOf(expected)
1221 actualMap := reflect.ValueOf(actual)
1222
1223 if expectedMap.Len() != actualMap.Len() {
1224 return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
1225 }
1226
1227 for _, k := range expectedMap.MapKeys() {
1228 ev := expectedMap.MapIndex(k)
1229 av := actualMap.MapIndex(k)
1230
1231 if !ev.IsValid() {
1232 return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
1233 }
1234
1235 if !av.IsValid() {
1236 return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
1237 }
1238
1239 if !InDelta(
1240 t,
1241 ev.Interface(),
1242 av.Interface(),
1243 delta,
1244 msgAndArgs...,
1245 ) {
1246 return false
1247 }
1248 }
1249
1250 return true
1251}
1252
1253func calcRelativeError(expected, actual interface{}) (float64, error) {
1254 af, aok := toFloat(expected)
Elia Battiston4750d3c2022-07-14 13:24:56 +00001255 bf, bok := toFloat(actual)
1256 if !aok || !bok {
1257 return 0, fmt.Errorf("Parameters must be numerical")
1258 }
1259 if math.IsNaN(af) && math.IsNaN(bf) {
1260 return 0, nil
Elia Battistonc8d0d462022-02-22 16:30:51 +01001261 }
1262 if math.IsNaN(af) {
1263 return 0, errors.New("expected value must not be NaN")
1264 }
1265 if af == 0 {
1266 return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
1267 }
Elia Battistonc8d0d462022-02-22 16:30:51 +01001268 if math.IsNaN(bf) {
1269 return 0, errors.New("actual value must not be NaN")
1270 }
1271
1272 return math.Abs(af-bf) / math.Abs(af), nil
1273}
1274
1275// InEpsilon asserts that expected and actual have a relative error less than epsilon
1276func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
1277 if h, ok := t.(tHelper); ok {
1278 h.Helper()
1279 }
1280 if math.IsNaN(epsilon) {
1281 return Fail(t, "epsilon must not be NaN")
1282 }
1283 actualEpsilon, err := calcRelativeError(expected, actual)
1284 if err != nil {
1285 return Fail(t, err.Error(), msgAndArgs...)
1286 }
1287 if actualEpsilon > epsilon {
1288 return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
1289 " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
1290 }
1291
1292 return true
1293}
1294
1295// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
1296func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
1297 if h, ok := t.(tHelper); ok {
1298 h.Helper()
1299 }
1300 if expected == nil || actual == nil ||
1301 reflect.TypeOf(actual).Kind() != reflect.Slice ||
1302 reflect.TypeOf(expected).Kind() != reflect.Slice {
Elia Battiston4750d3c2022-07-14 13:24:56 +00001303 return Fail(t, "Parameters must be slice", msgAndArgs...)
Elia Battistonc8d0d462022-02-22 16:30:51 +01001304 }
1305
1306 actualSlice := reflect.ValueOf(actual)
1307 expectedSlice := reflect.ValueOf(expected)
1308
1309 for i := 0; i < actualSlice.Len(); i++ {
1310 result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
1311 if !result {
1312 return result
1313 }
1314 }
1315
1316 return true
1317}
1318
1319/*
1320 Errors
1321*/
1322
1323// NoError asserts that a function returned no error (i.e. `nil`).
1324//
1325// actualObj, err := SomeFunction()
1326// if assert.NoError(t, err) {
1327// assert.Equal(t, expectedObj, actualObj)
1328// }
1329func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
1330 if err != nil {
1331 if h, ok := t.(tHelper); ok {
1332 h.Helper()
1333 }
1334 return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
1335 }
1336
1337 return true
1338}
1339
1340// Error asserts that a function returned an error (i.e. not `nil`).
1341//
1342// actualObj, err := SomeFunction()
1343// if assert.Error(t, err) {
1344// assert.Equal(t, expectedError, err)
1345// }
1346func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
1347 if err == nil {
1348 if h, ok := t.(tHelper); ok {
1349 h.Helper()
1350 }
1351 return Fail(t, "An error is expected but got nil.", msgAndArgs...)
1352 }
1353
1354 return true
1355}
1356
1357// EqualError asserts that a function returned an error (i.e. not `nil`)
1358// and that it is equal to the provided error.
1359//
1360// actualObj, err := SomeFunction()
1361// assert.EqualError(t, err, expectedErrorString)
1362func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
1363 if h, ok := t.(tHelper); ok {
1364 h.Helper()
1365 }
1366 if !Error(t, theError, msgAndArgs...) {
1367 return false
1368 }
1369 expected := errString
1370 actual := theError.Error()
1371 // don't need to use deep equals here, we know they are both strings
1372 if expected != actual {
1373 return Fail(t, fmt.Sprintf("Error message not equal:\n"+
1374 "expected: %q\n"+
1375 "actual : %q", expected, actual), msgAndArgs...)
1376 }
1377 return true
1378}
1379
Elia Battiston4750d3c2022-07-14 13:24:56 +00001380// ErrorContains asserts that a function returned an error (i.e. not `nil`)
1381// and that the error contains the specified substring.
1382//
1383// actualObj, err := SomeFunction()
1384// assert.ErrorContains(t, err, expectedErrorSubString)
1385func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool {
1386 if h, ok := t.(tHelper); ok {
1387 h.Helper()
1388 }
1389 if !Error(t, theError, msgAndArgs...) {
1390 return false
1391 }
1392
1393 actual := theError.Error()
1394 if !strings.Contains(actual, contains) {
1395 return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...)
1396 }
1397
1398 return true
1399}
1400
Elia Battistonc8d0d462022-02-22 16:30:51 +01001401// matchRegexp return true if a specified regexp matches a string.
1402func matchRegexp(rx interface{}, str interface{}) bool {
1403
1404 var r *regexp.Regexp
1405 if rr, ok := rx.(*regexp.Regexp); ok {
1406 r = rr
1407 } else {
1408 r = regexp.MustCompile(fmt.Sprint(rx))
1409 }
1410
1411 return (r.FindStringIndex(fmt.Sprint(str)) != nil)
1412
1413}
1414
1415// Regexp asserts that a specified regexp matches a string.
1416//
1417// assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
1418// assert.Regexp(t, "start...$", "it's not starting")
1419func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1420 if h, ok := t.(tHelper); ok {
1421 h.Helper()
1422 }
1423
1424 match := matchRegexp(rx, str)
1425
1426 if !match {
1427 Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
1428 }
1429
1430 return match
1431}
1432
1433// NotRegexp asserts that a specified regexp does not match a string.
1434//
1435// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
1436// assert.NotRegexp(t, "^start", "it's not starting")
1437func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1438 if h, ok := t.(tHelper); ok {
1439 h.Helper()
1440 }
1441 match := matchRegexp(rx, str)
1442
1443 if match {
1444 Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
1445 }
1446
1447 return !match
1448
1449}
1450
1451// Zero asserts that i is the zero value for its type.
1452func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
1453 if h, ok := t.(tHelper); ok {
1454 h.Helper()
1455 }
1456 if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
1457 return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
1458 }
1459 return true
1460}
1461
1462// NotZero asserts that i is not the zero value for its type.
1463func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
1464 if h, ok := t.(tHelper); ok {
1465 h.Helper()
1466 }
1467 if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
1468 return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
1469 }
1470 return true
1471}
1472
1473// FileExists checks whether a file exists in the given path. It also fails if
1474// the path points to a directory or there is an error when trying to check the file.
1475func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1476 if h, ok := t.(tHelper); ok {
1477 h.Helper()
1478 }
1479 info, err := os.Lstat(path)
1480 if err != nil {
1481 if os.IsNotExist(err) {
1482 return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
1483 }
1484 return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
1485 }
1486 if info.IsDir() {
1487 return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
1488 }
1489 return true
1490}
1491
1492// NoFileExists checks whether a file does not exist in a given path. It fails
1493// if the path points to an existing _file_ only.
1494func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1495 if h, ok := t.(tHelper); ok {
1496 h.Helper()
1497 }
1498 info, err := os.Lstat(path)
1499 if err != nil {
1500 return true
1501 }
1502 if info.IsDir() {
1503 return true
1504 }
1505 return Fail(t, fmt.Sprintf("file %q exists", path), msgAndArgs...)
1506}
1507
1508// DirExists checks whether a directory exists in the given path. It also fails
1509// if the path is a file rather a directory or there is an error checking whether it exists.
1510func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1511 if h, ok := t.(tHelper); ok {
1512 h.Helper()
1513 }
1514 info, err := os.Lstat(path)
1515 if err != nil {
1516 if os.IsNotExist(err) {
1517 return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
1518 }
1519 return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
1520 }
1521 if !info.IsDir() {
1522 return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
1523 }
1524 return true
1525}
1526
1527// NoDirExists checks whether a directory does not exist in the given path.
1528// It fails if the path points to an existing _directory_ only.
1529func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
1530 if h, ok := t.(tHelper); ok {
1531 h.Helper()
1532 }
1533 info, err := os.Lstat(path)
1534 if err != nil {
1535 if os.IsNotExist(err) {
1536 return true
1537 }
1538 return true
1539 }
1540 if !info.IsDir() {
1541 return true
1542 }
1543 return Fail(t, fmt.Sprintf("directory %q exists", path), msgAndArgs...)
1544}
1545
1546// JSONEq asserts that two JSON strings are equivalent.
1547//
1548// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
1549func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
1550 if h, ok := t.(tHelper); ok {
1551 h.Helper()
1552 }
1553 var expectedJSONAsInterface, actualJSONAsInterface interface{}
1554
1555 if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
1556 return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
1557 }
1558
1559 if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
1560 return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
1561 }
1562
1563 return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
1564}
1565
1566// YAMLEq asserts that two YAML strings are equivalent.
1567func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
1568 if h, ok := t.(tHelper); ok {
1569 h.Helper()
1570 }
1571 var expectedYAMLAsInterface, actualYAMLAsInterface interface{}
1572
1573 if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil {
1574 return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...)
1575 }
1576
1577 if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil {
1578 return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...)
1579 }
1580
1581 return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...)
1582}
1583
1584func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
1585 t := reflect.TypeOf(v)
1586 k := t.Kind()
1587
1588 if k == reflect.Ptr {
1589 t = t.Elem()
1590 k = t.Kind()
1591 }
1592 return t, k
1593}
1594
1595// diff returns a diff of both values as long as both are of the same type and
1596// are a struct, map, slice, array or string. Otherwise it returns an empty string.
1597func diff(expected interface{}, actual interface{}) string {
1598 if expected == nil || actual == nil {
1599 return ""
1600 }
1601
1602 et, ek := typeAndKind(expected)
1603 at, _ := typeAndKind(actual)
1604
1605 if et != at {
1606 return ""
1607 }
1608
1609 if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
1610 return ""
1611 }
1612
1613 var e, a string
Elia Battiston4750d3c2022-07-14 13:24:56 +00001614
1615 switch et {
1616 case reflect.TypeOf(""):
Elia Battistonc8d0d462022-02-22 16:30:51 +01001617 e = reflect.ValueOf(expected).String()
1618 a = reflect.ValueOf(actual).String()
Elia Battiston4750d3c2022-07-14 13:24:56 +00001619 case reflect.TypeOf(time.Time{}):
1620 e = spewConfigStringerEnabled.Sdump(expected)
1621 a = spewConfigStringerEnabled.Sdump(actual)
1622 default:
1623 e = spewConfig.Sdump(expected)
1624 a = spewConfig.Sdump(actual)
Elia Battistonc8d0d462022-02-22 16:30:51 +01001625 }
1626
1627 diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
1628 A: difflib.SplitLines(e),
1629 B: difflib.SplitLines(a),
1630 FromFile: "Expected",
1631 FromDate: "",
1632 ToFile: "Actual",
1633 ToDate: "",
1634 Context: 1,
1635 })
1636
1637 return "\n\nDiff:\n" + diff
1638}
1639
1640func isFunction(arg interface{}) bool {
1641 if arg == nil {
1642 return false
1643 }
1644 return reflect.TypeOf(arg).Kind() == reflect.Func
1645}
1646
1647var spewConfig = spew.ConfigState{
1648 Indent: " ",
1649 DisablePointerAddresses: true,
1650 DisableCapacities: true,
1651 SortKeys: true,
1652 DisableMethods: true,
1653 MaxDepth: 10,
1654}
1655
Elia Battiston4750d3c2022-07-14 13:24:56 +00001656var spewConfigStringerEnabled = spew.ConfigState{
1657 Indent: " ",
1658 DisablePointerAddresses: true,
1659 DisableCapacities: true,
1660 SortKeys: true,
1661 MaxDepth: 10,
1662}
1663
Elia Battistonc8d0d462022-02-22 16:30:51 +01001664type tHelper interface {
1665 Helper()
1666}
1667
1668// Eventually asserts that given condition will be met in waitFor time,
1669// periodically checking target function each tick.
1670//
1671// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
1672func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
1673 if h, ok := t.(tHelper); ok {
1674 h.Helper()
1675 }
1676
1677 ch := make(chan bool, 1)
1678
1679 timer := time.NewTimer(waitFor)
1680 defer timer.Stop()
1681
1682 ticker := time.NewTicker(tick)
1683 defer ticker.Stop()
1684
1685 for tick := ticker.C; ; {
1686 select {
1687 case <-timer.C:
1688 return Fail(t, "Condition never satisfied", msgAndArgs...)
1689 case <-tick:
1690 tick = nil
1691 go func() { ch <- condition() }()
1692 case v := <-ch:
1693 if v {
1694 return true
1695 }
1696 tick = ticker.C
1697 }
1698 }
1699}
1700
1701// Never asserts that the given condition doesn't satisfy in waitFor time,
1702// periodically checking the target function each tick.
1703//
1704// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
1705func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
1706 if h, ok := t.(tHelper); ok {
1707 h.Helper()
1708 }
1709
1710 ch := make(chan bool, 1)
1711
1712 timer := time.NewTimer(waitFor)
1713 defer timer.Stop()
1714
1715 ticker := time.NewTicker(tick)
1716 defer ticker.Stop()
1717
1718 for tick := ticker.C; ; {
1719 select {
1720 case <-timer.C:
1721 return true
1722 case <-tick:
1723 tick = nil
1724 go func() { ch <- condition() }()
1725 case v := <-ch:
1726 if v {
1727 return Fail(t, "Condition satisfied", msgAndArgs...)
1728 }
1729 tick = ticker.C
1730 }
1731 }
1732}
1733
1734// ErrorIs asserts that at least one of the errors in err's chain matches target.
1735// This is a wrapper for errors.Is.
1736func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
1737 if h, ok := t.(tHelper); ok {
1738 h.Helper()
1739 }
1740 if errors.Is(err, target) {
1741 return true
1742 }
1743
1744 var expectedText string
1745 if target != nil {
1746 expectedText = target.Error()
1747 }
1748
1749 chain := buildErrorChainString(err)
1750
1751 return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+
1752 "expected: %q\n"+
1753 "in chain: %s", expectedText, chain,
1754 ), msgAndArgs...)
1755}
1756
1757// NotErrorIs asserts that at none of the errors in err's chain matches target.
1758// This is a wrapper for errors.Is.
1759func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
1760 if h, ok := t.(tHelper); ok {
1761 h.Helper()
1762 }
1763 if !errors.Is(err, target) {
1764 return true
1765 }
1766
1767 var expectedText string
1768 if target != nil {
1769 expectedText = target.Error()
1770 }
1771
1772 chain := buildErrorChainString(err)
1773
1774 return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
1775 "found: %q\n"+
1776 "in chain: %s", expectedText, chain,
1777 ), msgAndArgs...)
1778}
1779
1780// ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value.
1781// This is a wrapper for errors.As.
1782func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool {
1783 if h, ok := t.(tHelper); ok {
1784 h.Helper()
1785 }
1786 if errors.As(err, target) {
1787 return true
1788 }
1789
1790 chain := buildErrorChainString(err)
1791
1792 return Fail(t, fmt.Sprintf("Should be in error chain:\n"+
1793 "expected: %q\n"+
1794 "in chain: %s", target, chain,
1795 ), msgAndArgs...)
1796}
1797
1798func buildErrorChainString(err error) string {
1799 if err == nil {
1800 return ""
1801 }
1802
1803 e := errors.Unwrap(err)
1804 chain := fmt.Sprintf("%q", err.Error())
1805 for e != nil {
1806 chain += fmt.Sprintf("\n\t%q", e.Error())
1807 e = errors.Unwrap(e)
1808 }
1809 return chain
1810}