18 "github.com/davecgh/go-spew/spew"
19 "github.com/pmezard/go-difflib/difflib"
22 //go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_format.go.tmpl
24 // TestingT is an interface wrapper around *testing.T
25 type TestingT interface {
26 Errorf(format string, args ...interface{})
29 // Comparison a custom function that returns true on success and false on failure
30 type Comparison func() (success bool)
36 // ObjectsAreEqual determines if two objects are considered equal.
38 // This function does no assertion of any kind.
39 func ObjectsAreEqual(expected, actual interface{}) bool {
41 if expected == nil || actual == nil {
42 return expected == actual
44 if exp, ok := expected.([]byte); ok {
45 act, ok := actual.([]byte)
48 } else if exp == nil || act == nil {
49 return exp == nil && act == nil
51 return bytes.Equal(exp, act)
53 return reflect.DeepEqual(expected, actual)
57 // ObjectsAreEqualValues gets whether two objects are equal, or if their
59 func ObjectsAreEqualValues(expected, actual interface{}) bool {
60 if ObjectsAreEqual(expected, actual) {
64 actualType := reflect.TypeOf(actual)
65 if actualType == nil {
68 expectedValue := reflect.ValueOf(expected)
69 if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
70 // Attempt comparison after type conversion
71 return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
77 /* CallerInfo is necessary because the assert functions use the testing object
78 internally, causing it to print the file:line of the assert method, rather than where
79 the problem actually occurred in calling code.*/
81 // CallerInfo returns an array of strings containing the file and line number
82 // of each stack frame leading from the current test to the assert call that
84 func CallerInfo() []string {
94 pc, file, line, ok = runtime.Caller(i)
96 // The breaks below failed to terminate the loop, and we ran off the
97 // end of the call stack.
101 // This is a huge edge case, but it will panic if this is the case, see #180
102 if file == "<autogenerated>" {
106 f := runtime.FuncForPC(pc)
112 // testing.tRunner is the standard library function that calls
113 // tests. Subtests are called directly by tRunner, without going through
114 // the Test/Benchmark/Example function that contains the t.Run calls, so
115 // with subtests we should break when we hit tRunner, without adding it
116 // to the list of callers.
117 if name == "testing.tRunner" {
121 parts := strings.Split(file, "/")
122 file = parts[len(parts)-1]
124 dir := parts[len(parts)-2]
125 if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
126 callers = append(callers, fmt.Sprintf("%s:%d", file, line))
131 segments := strings.Split(name, ".")
132 name = segments[len(segments)-1]
133 if isTest(name, "Test") ||
134 isTest(name, "Benchmark") ||
135 isTest(name, "Example") {
143 // Stolen from the `go test` tool.
144 // isTest tells whether name looks like a test (or benchmark, according to prefix).
145 // It is a Test (say) if there is a character after Test that is not a lower-case letter.
146 // We don't want TesticularCancer.
147 func isTest(name, prefix string) bool {
148 if !strings.HasPrefix(name, prefix) {
151 if len(name) == len(prefix) { // "Test" is ok
154 rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
155 return !unicode.IsLower(rune)
158 // getWhitespaceString returns a string that is long enough to overwrite the default
159 // output from the go testing framework.
160 func getWhitespaceString() string {
162 _, file, line, ok := runtime.Caller(1)
166 parts := strings.Split(file, "/")
167 file = parts[len(parts)-1]
169 return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line)))
173 func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
174 if len(msgAndArgs) == 0 || msgAndArgs == nil {
177 if len(msgAndArgs) == 1 {
178 return msgAndArgs[0].(string)
180 if len(msgAndArgs) > 1 {
181 return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
186 // Aligns the provided message so that all lines after the first line start at the same location as the first line.
187 // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
188 // The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
189 // basis on which the alignment occurs).
190 func indentMessageLines(message string, longestLabelLen int) string {
191 outBuf := new(bytes.Buffer)
193 for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
194 // no need to align first line because it starts at the correct location (after the label)
196 // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
197 outBuf.WriteString("\n\r\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
199 outBuf.WriteString(scanner.Text())
202 return outBuf.String()
205 type failNower interface {
209 // FailNow fails test
210 func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
211 Fail(t, failureMessage, msgAndArgs...)
213 // We cannot extend TestingT with FailNow() and
214 // maintain backwards compatibility, so we fallback
215 // to panicking when FailNow is not available in
219 if t, ok := t.(failNower); ok {
222 panic("test failed and t is missing `FailNow()`")
227 // Fail reports a failure through
228 func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
229 content := []labeledContent{
230 {"Error Trace", strings.Join(CallerInfo(), "\n\r\t\t\t")},
231 {"Error", failureMessage},
234 message := messageFromMsgAndArgs(msgAndArgs...)
235 if len(message) > 0 {
236 content = append(content, labeledContent{"Messages", message})
239 t.Errorf("%s", "\r"+getWhitespaceString()+labeledOutput(content...))
244 type labeledContent struct {
249 // labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
251 // \r\t{{label}}:{{align_spaces}}\t{{content}}\n
253 // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
254 // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
255 // alignment is achieved, "\t{{content}}\n" is added for the output.
257 // 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.
258 func labeledOutput(content ...labeledContent) string {
260 for _, v := range content {
261 if len(v.label) > longestLabel {
262 longestLabel = len(v.label)
266 for _, v := range content {
267 output += "\r\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
272 // Implements asserts that an object is implemented by the specified interface.
274 // assert.Implements(t, (*MyInterface)(nil), new(MyObject))
275 func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
277 interfaceType := reflect.TypeOf(interfaceObject).Elem()
279 if !reflect.TypeOf(object).Implements(interfaceType) {
280 return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
287 // IsType asserts that the specified objects are of the same type.
288 func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
290 if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
291 return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
297 // Equal asserts that two objects are equal.
299 // assert.Equal(t, 123, 123)
301 // Returns whether the assertion was successful (true) or not (false).
303 // Pointer variable equality is determined based on the equality of the
304 // referenced values (as opposed to the memory addresses). Function equality
305 // cannot be determined and will always fail.
306 func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
307 if err := validateEqualArgs(expected, actual); err != nil {
308 return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)",
309 expected, actual, err), msgAndArgs...)
312 if !ObjectsAreEqual(expected, actual) {
313 diff := diff(expected, actual)
314 expected, actual = formatUnequalValues(expected, actual)
315 return Fail(t, fmt.Sprintf("Not equal: \n"+
317 "actual: %s%s", expected, actual, diff), msgAndArgs...)
324 // formatUnequalValues takes two values of arbitrary types and returns string
325 // representations appropriate to be presented to the user.
327 // If the values are not of like type, the returned strings will be prefixed
328 // with the type name, and the value will be enclosed in parenthesis similar
329 // to a type conversion in the Go grammar.
330 func formatUnequalValues(expected, actual interface{}) (e string, a string) {
331 if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
332 return fmt.Sprintf("%T(%#v)", expected, expected),
333 fmt.Sprintf("%T(%#v)", actual, actual)
336 return fmt.Sprintf("%#v", expected),
337 fmt.Sprintf("%#v", actual)
340 // EqualValues asserts that two objects are equal or convertable to the same types
343 // assert.EqualValues(t, uint32(123), int32(123))
345 // Returns whether the assertion was successful (true) or not (false).
346 func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
348 if !ObjectsAreEqualValues(expected, actual) {
349 diff := diff(expected, actual)
350 expected, actual = formatUnequalValues(expected, actual)
351 return Fail(t, fmt.Sprintf("Not equal: \n"+
353 "actual: %s%s", expected, actual, diff), msgAndArgs...)
360 // Exactly asserts that two objects are equal is value and type.
362 // assert.Exactly(t, int32(123), int64(123))
364 // Returns whether the assertion was successful (true) or not (false).
365 func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
367 aType := reflect.TypeOf(expected)
368 bType := reflect.TypeOf(actual)
371 return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...)
374 return Equal(t, expected, actual, msgAndArgs...)
378 // NotNil asserts that the specified object is not nil.
380 // assert.NotNil(t, err)
382 // Returns whether the assertion was successful (true) or not (false).
383 func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
387 return Fail(t, "Expected value not to be nil.", msgAndArgs...)
390 // isNil checks if a specified object is nil or not, without Failing.
391 func isNil(object interface{}) bool {
396 value := reflect.ValueOf(object)
398 if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
405 // Nil asserts that the specified object is nil.
407 // assert.Nil(t, err)
409 // Returns whether the assertion was successful (true) or not (false).
410 func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
414 return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
417 var numericZeros = []interface{}{
432 // isEmpty gets whether the specified object is considered empty or not.
433 func isEmpty(object interface{}) bool {
437 } else if object == "" {
439 } else if object == false {
443 for _, v := range numericZeros {
449 objValue := reflect.ValueOf(object)
451 switch objValue.Kind() {
452 case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
454 return (objValue.Len() == 0)
457 switch object.(type) {
459 return object.(time.Time).IsZero()
463 if objValue.IsNil() {
466 switch object.(type) {
468 return object.(*time.Time).IsZero()
477 // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
478 // a slice or a channel with len == 0.
480 // assert.Empty(t, obj)
482 // Returns whether the assertion was successful (true) or not (false).
483 func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
485 pass := isEmpty(object)
487 Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
494 // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
495 // a slice or a channel with len == 0.
497 // if assert.NotEmpty(t, obj) {
498 // assert.Equal(t, "two", obj[1])
501 // Returns whether the assertion was successful (true) or not (false).
502 func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
504 pass := !isEmpty(object)
506 Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
513 // getLen try to get length of object.
514 // return (false, 0) if impossible.
515 func getLen(x interface{}) (ok bool, length int) {
516 v := reflect.ValueOf(x)
518 if e := recover(); e != nil {
525 // Len asserts that the specified object has specific length.
526 // Len also fails if the object has a type that len() not accept.
528 // assert.Len(t, mySlice, 3)
530 // Returns whether the assertion was successful (true) or not (false).
531 func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
532 ok, l := getLen(object)
534 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
538 return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
543 // True asserts that the specified value is true.
545 // assert.True(t, myBool)
547 // Returns whether the assertion was successful (true) or not (false).
548 func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
551 return Fail(t, "Should be true", msgAndArgs...)
558 // False asserts that the specified value is false.
560 // assert.False(t, myBool)
562 // Returns whether the assertion was successful (true) or not (false).
563 func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
566 return Fail(t, "Should be false", msgAndArgs...)
573 // NotEqual asserts that the specified values are NOT equal.
575 // assert.NotEqual(t, obj1, obj2)
577 // Returns whether the assertion was successful (true) or not (false).
579 // Pointer variable equality is determined based on the equality of the
580 // referenced values (as opposed to the memory addresses).
581 func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
582 if err := validateEqualArgs(expected, actual); err != nil {
583 return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
584 expected, actual, err), msgAndArgs...)
587 if ObjectsAreEqual(expected, actual) {
588 return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
595 // containsElement try loop over the list check if the list includes the element.
596 // return (false, false) if impossible.
597 // return (true, false) if element was not found.
598 // return (true, true) if element was found.
599 func includeElement(list interface{}, element interface{}) (ok, found bool) {
601 listValue := reflect.ValueOf(list)
602 elementValue := reflect.ValueOf(element)
604 if e := recover(); e != nil {
610 if reflect.TypeOf(list).Kind() == reflect.String {
611 return true, strings.Contains(listValue.String(), elementValue.String())
614 if reflect.TypeOf(list).Kind() == reflect.Map {
615 mapKeys := listValue.MapKeys()
616 for i := 0; i < len(mapKeys); i++ {
617 if ObjectsAreEqual(mapKeys[i].Interface(), element) {
624 for i := 0; i < listValue.Len(); i++ {
625 if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
633 // Contains asserts that the specified string, list(array, slice...) or map contains the
634 // specified substring or element.
636 // assert.Contains(t, "Hello World", "World")
637 // assert.Contains(t, ["Hello", "World"], "World")
638 // assert.Contains(t, {"Hello": "World"}, "Hello")
640 // Returns whether the assertion was successful (true) or not (false).
641 func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
643 ok, found := includeElement(s, contains)
645 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
648 return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...)
655 // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
656 // specified substring or element.
658 // assert.NotContains(t, "Hello World", "Earth")
659 // assert.NotContains(t, ["Hello", "World"], "Earth")
660 // assert.NotContains(t, {"Hello": "World"}, "Earth")
662 // Returns whether the assertion was successful (true) or not (false).
663 func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
665 ok, found := includeElement(s, contains)
667 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
670 return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
677 // Subset asserts that the specified list(array, slice...) contains all
678 // elements given in the specified subset(array, slice...).
680 // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
682 // Returns whether the assertion was successful (true) or not (false).
683 func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
685 return true // we consider nil to be equal to the nil set
688 subsetValue := reflect.ValueOf(subset)
690 if e := recover(); e != nil {
695 listKind := reflect.TypeOf(list).Kind()
696 subsetKind := reflect.TypeOf(subset).Kind()
698 if listKind != reflect.Array && listKind != reflect.Slice {
699 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
702 if subsetKind != reflect.Array && subsetKind != reflect.Slice {
703 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
706 for i := 0; i < subsetValue.Len(); i++ {
707 element := subsetValue.Index(i).Interface()
708 ok, found := includeElement(list, element)
710 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
713 return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...)
720 // NotSubset asserts that the specified list(array, slice...) contains not all
721 // elements given in the specified subset(array, slice...).
723 // assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
725 // Returns whether the assertion was successful (true) or not (false).
726 func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
728 return false // we consider nil to be equal to the nil set
731 subsetValue := reflect.ValueOf(subset)
733 if e := recover(); e != nil {
738 listKind := reflect.TypeOf(list).Kind()
739 subsetKind := reflect.TypeOf(subset).Kind()
741 if listKind != reflect.Array && listKind != reflect.Slice {
742 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
745 if subsetKind != reflect.Array && subsetKind != reflect.Slice {
746 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
749 for i := 0; i < subsetValue.Len(); i++ {
750 element := subsetValue.Index(i).Interface()
751 ok, found := includeElement(list, element)
753 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
760 return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
763 // Condition uses a Comparison to assert a complex condition.
764 func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
767 Fail(t, "Condition failed!", msgAndArgs...)
772 // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
773 // methods, and represents a simple func that takes no arguments, and returns nothing.
774 type PanicTestFunc func()
776 // didPanic returns true if the function passed to it panics. Otherwise, it returns false.
777 func didPanic(f PanicTestFunc) (bool, interface{}) {
780 var message interface{}
784 if message = recover(); message != nil {
789 // call the target function
794 return didPanic, message
798 // Panics asserts that the code inside the specified PanicTestFunc panics.
800 // assert.Panics(t, func(){ GoCrazy() })
802 // Returns whether the assertion was successful (true) or not (false).
803 func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
805 if funcDidPanic, panicValue := didPanic(f); !funcDidPanic {
806 return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
812 // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
813 // the recovered panic value equals the expected panic value.
815 // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
817 // Returns whether the assertion was successful (true) or not (false).
818 func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
820 funcDidPanic, panicValue := didPanic(f)
822 return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
824 if panicValue != expected {
825 return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%v\n\r\tPanic value:\t%v", f, expected, panicValue), msgAndArgs...)
831 // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
833 // assert.NotPanics(t, func(){ RemainCalm() })
835 // Returns whether the assertion was successful (true) or not (false).
836 func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
838 if funcDidPanic, panicValue := didPanic(f); funcDidPanic {
839 return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
845 // WithinDuration asserts that the two times are within duration delta of each other.
847 // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
849 // Returns whether the assertion was successful (true) or not (false).
850 func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
852 dt := expected.Sub(actual)
853 if dt < -delta || dt > delta {
854 return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
860 func toFloat(x interface{}) (float64, bool) {
864 switch xn := x.(type) {
896 // InDelta asserts that the two numerals are within delta of each other.
898 // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
900 // Returns whether the assertion was successful (true) or not (false).
901 func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
903 af, aok := toFloat(expected)
904 bf, bok := toFloat(actual)
907 return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
911 return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...)
915 return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
919 if dt < -delta || dt > delta {
920 return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
926 // InDeltaSlice is the same as InDelta, except it compares two slices.
927 func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
928 if expected == nil || actual == nil ||
929 reflect.TypeOf(actual).Kind() != reflect.Slice ||
930 reflect.TypeOf(expected).Kind() != reflect.Slice {
931 return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
934 actualSlice := reflect.ValueOf(actual)
935 expectedSlice := reflect.ValueOf(expected)
937 for i := 0; i < actualSlice.Len(); i++ {
938 result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
947 func calcRelativeError(expected, actual interface{}) (float64, error) {
948 af, aok := toFloat(expected)
950 return 0, fmt.Errorf("expected value %q cannot be converted to float", expected)
953 return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
955 bf, bok := toFloat(actual)
957 return 0, fmt.Errorf("actual value %q cannot be converted to float", actual)
960 return math.Abs(af-bf) / math.Abs(af), nil
963 // InEpsilon asserts that expected and actual have a relative error less than epsilon
965 // Returns whether the assertion was successful (true) or not (false).
966 func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
967 actualEpsilon, err := calcRelativeError(expected, actual)
969 return Fail(t, err.Error(), msgAndArgs...)
971 if actualEpsilon > epsilon {
972 return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
973 " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
979 // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
980 func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
981 if expected == nil || actual == nil ||
982 reflect.TypeOf(actual).Kind() != reflect.Slice ||
983 reflect.TypeOf(expected).Kind() != reflect.Slice {
984 return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
987 actualSlice := reflect.ValueOf(actual)
988 expectedSlice := reflect.ValueOf(expected)
990 for i := 0; i < actualSlice.Len(); i++ {
991 result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
1004 // NoError asserts that a function returned no error (i.e. `nil`).
1006 // actualObj, err := SomeFunction()
1007 // if assert.NoError(t, err) {
1008 // assert.Equal(t, expectedObj, actualObj)
1011 // Returns whether the assertion was successful (true) or not (false).
1012 func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
1014 return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
1020 // Error asserts that a function returned an error (i.e. not `nil`).
1022 // actualObj, err := SomeFunction()
1023 // if assert.Error(t, err) {
1024 // assert.Equal(t, expectedError, err)
1027 // Returns whether the assertion was successful (true) or not (false).
1028 func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
1031 return Fail(t, "An error is expected but got nil.", msgAndArgs...)
1037 // EqualError asserts that a function returned an error (i.e. not `nil`)
1038 // and that it is equal to the provided error.
1040 // actualObj, err := SomeFunction()
1041 // assert.EqualError(t, err, expectedErrorString)
1043 // Returns whether the assertion was successful (true) or not (false).
1044 func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
1045 if !Error(t, theError, msgAndArgs...) {
1048 expected := errString
1049 actual := theError.Error()
1050 // don't need to use deep equals here, we know they are both strings
1051 if expected != actual {
1052 return Fail(t, fmt.Sprintf("Error message not equal:\n"+
1054 "actual: %q", expected, actual), msgAndArgs...)
1059 // matchRegexp return true if a specified regexp matches a string.
1060 func matchRegexp(rx interface{}, str interface{}) bool {
1062 var r *regexp.Regexp
1063 if rr, ok := rx.(*regexp.Regexp); ok {
1066 r = regexp.MustCompile(fmt.Sprint(rx))
1069 return (r.FindStringIndex(fmt.Sprint(str)) != nil)
1073 // Regexp asserts that a specified regexp matches a string.
1075 // assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
1076 // assert.Regexp(t, "start...$", "it's not starting")
1078 // Returns whether the assertion was successful (true) or not (false).
1079 func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1081 match := matchRegexp(rx, str)
1084 Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
1090 // NotRegexp asserts that a specified regexp does not match a string.
1092 // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
1093 // assert.NotRegexp(t, "^start", "it's not starting")
1095 // Returns whether the assertion was successful (true) or not (false).
1096 func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1097 match := matchRegexp(rx, str)
1100 Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
1107 // Zero asserts that i is the zero value for its type and returns the truth.
1108 func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
1109 if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
1110 return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
1115 // NotZero asserts that i is not the zero value for its type and returns the truth.
1116 func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
1117 if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
1118 return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
1123 // JSONEq asserts that two JSON strings are equivalent.
1125 // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
1127 // Returns whether the assertion was successful (true) or not (false).
1128 func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
1129 var expectedJSONAsInterface, actualJSONAsInterface interface{}
1131 if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
1132 return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
1135 if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
1136 return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
1139 return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
1142 func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
1143 t := reflect.TypeOf(v)
1146 if k == reflect.Ptr {
1153 // diff returns a diff of both values as long as both are of the same type and
1154 // are a struct, map, slice or array. Otherwise it returns an empty string.
1155 func diff(expected interface{}, actual interface{}) string {
1156 if expected == nil || actual == nil {
1160 et, ek := typeAndKind(expected)
1161 at, _ := typeAndKind(actual)
1167 if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array {
1171 e := spewConfig.Sdump(expected)
1172 a := spewConfig.Sdump(actual)
1174 diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
1175 A: difflib.SplitLines(e),
1176 B: difflib.SplitLines(a),
1177 FromFile: "Expected",
1184 return "\n\nDiff:\n" + diff
1187 // validateEqualArgs checks whether provided arguments can be safely used in the
1188 // Equal/NotEqual functions.
1189 func validateEqualArgs(expected, actual interface{}) error {
1190 if isFunction(expected) || isFunction(actual) {
1191 return errors.New("cannot take func type as argument")
1196 func isFunction(arg interface{}) bool {
1200 return reflect.TypeOf(arg).Kind() == reflect.Func
1203 var spewConfig = spew.ConfigState{
1205 DisablePointerAddresses: true,
1206 DisableCapacities: true,