OSDN Git Service

Hulk did something
[bytom/vapor.git] / vendor / github.com / stretchr / testify / assert / assertions.go
1 package assert
2
3 import (
4         "bufio"
5         "bytes"
6         "encoding/json"
7         "errors"
8         "fmt"
9         "math"
10         "reflect"
11         "regexp"
12         "runtime"
13         "strings"
14         "time"
15         "unicode"
16         "unicode/utf8"
17
18         "github.com/davecgh/go-spew/spew"
19         "github.com/pmezard/go-difflib/difflib"
20 )
21
22 //go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_format.go.tmpl
23
24 // TestingT is an interface wrapper around *testing.T
25 type TestingT interface {
26         Errorf(format string, args ...interface{})
27 }
28
29 // Comparison a custom function that returns true on success and false on failure
30 type Comparison func() (success bool)
31
32 /*
33         Helper functions
34 */
35
36 // ObjectsAreEqual determines if two objects are considered equal.
37 //
38 // This function does no assertion of any kind.
39 func ObjectsAreEqual(expected, actual interface{}) bool {
40
41         if expected == nil || actual == nil {
42                 return expected == actual
43         }
44         if exp, ok := expected.([]byte); ok {
45                 act, ok := actual.([]byte)
46                 if !ok {
47                         return false
48                 } else if exp == nil || act == nil {
49                         return exp == nil && act == nil
50                 }
51                 return bytes.Equal(exp, act)
52         }
53         return reflect.DeepEqual(expected, actual)
54
55 }
56
57 // ObjectsAreEqualValues gets whether two objects are equal, or if their
58 // values are equal.
59 func ObjectsAreEqualValues(expected, actual interface{}) bool {
60         if ObjectsAreEqual(expected, actual) {
61                 return true
62         }
63
64         actualType := reflect.TypeOf(actual)
65         if actualType == nil {
66                 return false
67         }
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)
72         }
73
74         return false
75 }
76
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.*/
80
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
83 // failed.
84 func CallerInfo() []string {
85
86         pc := uintptr(0)
87         file := ""
88         line := 0
89         ok := false
90         name := ""
91
92         callers := []string{}
93         for i := 0; ; i++ {
94                 pc, file, line, ok = runtime.Caller(i)
95                 if !ok {
96                         // The breaks below failed to terminate the loop, and we ran off the
97                         // end of the call stack.
98                         break
99                 }
100
101                 // This is a huge edge case, but it will panic if this is the case, see #180
102                 if file == "<autogenerated>" {
103                         break
104                 }
105
106                 f := runtime.FuncForPC(pc)
107                 if f == nil {
108                         break
109                 }
110                 name = f.Name()
111
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" {
118                         break
119                 }
120
121                 parts := strings.Split(file, "/")
122                 file = parts[len(parts)-1]
123                 if 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))
127                         }
128                 }
129
130                 // Drop the package
131                 segments := strings.Split(name, ".")
132                 name = segments[len(segments)-1]
133                 if isTest(name, "Test") ||
134                         isTest(name, "Benchmark") ||
135                         isTest(name, "Example") {
136                         break
137                 }
138         }
139
140         return callers
141 }
142
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) {
149                 return false
150         }
151         if len(name) == len(prefix) { // "Test" is ok
152                 return true
153         }
154         rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
155         return !unicode.IsLower(rune)
156 }
157
158 // getWhitespaceString returns a string that is long enough to overwrite the default
159 // output from the go testing framework.
160 func getWhitespaceString() string {
161
162         _, file, line, ok := runtime.Caller(1)
163         if !ok {
164                 return ""
165         }
166         parts := strings.Split(file, "/")
167         file = parts[len(parts)-1]
168
169         return strings.Repeat(" ", len(fmt.Sprintf("%s:%d:        ", file, line)))
170
171 }
172
173 func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
174         if len(msgAndArgs) == 0 || msgAndArgs == nil {
175                 return ""
176         }
177         if len(msgAndArgs) == 1 {
178                 return msgAndArgs[0].(string)
179         }
180         if len(msgAndArgs) > 1 {
181                 return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
182         }
183         return ""
184 }
185
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)
192
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)
195                 if i != 0 {
196                         // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
197                         outBuf.WriteString("\n\r\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
198                 }
199                 outBuf.WriteString(scanner.Text())
200         }
201
202         return outBuf.String()
203 }
204
205 type failNower interface {
206         FailNow()
207 }
208
209 // FailNow fails test
210 func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
211         Fail(t, failureMessage, msgAndArgs...)
212
213         // We cannot extend TestingT with FailNow() and
214         // maintain backwards compatibility, so we fallback
215         // to panicking when FailNow is not available in
216         // TestingT.
217         // See issue #263
218
219         if t, ok := t.(failNower); ok {
220                 t.FailNow()
221         } else {
222                 panic("test failed and t is missing `FailNow()`")
223         }
224         return false
225 }
226
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},
232         }
233
234         message := messageFromMsgAndArgs(msgAndArgs...)
235         if len(message) > 0 {
236                 content = append(content, labeledContent{"Messages", message})
237         }
238
239         t.Errorf("%s", "\r"+getWhitespaceString()+labeledOutput(content...))
240
241         return false
242 }
243
244 type labeledContent struct {
245         label   string
246         content string
247 }
248
249 // labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
250 //
251 //   \r\t{{label}}:{{align_spaces}}\t{{content}}\n
252 //
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.
256 //
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 {
259         longestLabel := 0
260         for _, v := range content {
261                 if len(v.label) > longestLabel {
262                         longestLabel = len(v.label)
263                 }
264         }
265         var output string
266         for _, v := range content {
267                 output += "\r\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
268         }
269         return output
270 }
271
272 // Implements asserts that an object is implemented by the specified interface.
273 //
274 //    assert.Implements(t, (*MyInterface)(nil), new(MyObject))
275 func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
276
277         interfaceType := reflect.TypeOf(interfaceObject).Elem()
278
279         if !reflect.TypeOf(object).Implements(interfaceType) {
280                 return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
281         }
282
283         return true
284
285 }
286
287 // IsType asserts that the specified objects are of the same type.
288 func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
289
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...)
292         }
293
294         return true
295 }
296
297 // Equal asserts that two objects are equal.
298 //
299 //    assert.Equal(t, 123, 123)
300 //
301 // Returns whether the assertion was successful (true) or not (false).
302 //
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...)
310         }
311
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"+
316                         "expected: %s\n"+
317                         "actual: %s%s", expected, actual, diff), msgAndArgs...)
318         }
319
320         return true
321
322 }
323
324 // formatUnequalValues takes two values of arbitrary types and returns string
325 // representations appropriate to be presented to the user.
326 //
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)
334         }
335
336         return fmt.Sprintf("%#v", expected),
337                 fmt.Sprintf("%#v", actual)
338 }
339
340 // EqualValues asserts that two objects are equal or convertable to the same types
341 // and equal.
342 //
343 //    assert.EqualValues(t, uint32(123), int32(123))
344 //
345 // Returns whether the assertion was successful (true) or not (false).
346 func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
347
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"+
352                         "expected: %s\n"+
353                         "actual: %s%s", expected, actual, diff), msgAndArgs...)
354         }
355
356         return true
357
358 }
359
360 // Exactly asserts that two objects are equal is value and type.
361 //
362 //    assert.Exactly(t, int32(123), int64(123))
363 //
364 // Returns whether the assertion was successful (true) or not (false).
365 func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
366
367         aType := reflect.TypeOf(expected)
368         bType := reflect.TypeOf(actual)
369
370         if aType != bType {
371                 return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...)
372         }
373
374         return Equal(t, expected, actual, msgAndArgs...)
375
376 }
377
378 // NotNil asserts that the specified object is not nil.
379 //
380 //    assert.NotNil(t, err)
381 //
382 // Returns whether the assertion was successful (true) or not (false).
383 func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
384         if !isNil(object) {
385                 return true
386         }
387         return Fail(t, "Expected value not to be nil.", msgAndArgs...)
388 }
389
390 // isNil checks if a specified object is nil or not, without Failing.
391 func isNil(object interface{}) bool {
392         if object == nil {
393                 return true
394         }
395
396         value := reflect.ValueOf(object)
397         kind := value.Kind()
398         if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
399                 return true
400         }
401
402         return false
403 }
404
405 // Nil asserts that the specified object is nil.
406 //
407 //    assert.Nil(t, err)
408 //
409 // Returns whether the assertion was successful (true) or not (false).
410 func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
411         if isNil(object) {
412                 return true
413         }
414         return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
415 }
416
417 var numericZeros = []interface{}{
418         int(0),
419         int8(0),
420         int16(0),
421         int32(0),
422         int64(0),
423         uint(0),
424         uint8(0),
425         uint16(0),
426         uint32(0),
427         uint64(0),
428         float32(0),
429         float64(0),
430 }
431
432 // isEmpty gets whether the specified object is considered empty or not.
433 func isEmpty(object interface{}) bool {
434
435         if object == nil {
436                 return true
437         } else if object == "" {
438                 return true
439         } else if object == false {
440                 return true
441         }
442
443         for _, v := range numericZeros {
444                 if object == v {
445                         return true
446                 }
447         }
448
449         objValue := reflect.ValueOf(object)
450
451         switch objValue.Kind() {
452         case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
453                 {
454                         return (objValue.Len() == 0)
455                 }
456         case reflect.Struct:
457                 switch object.(type) {
458                 case time.Time:
459                         return object.(time.Time).IsZero()
460                 }
461         case reflect.Ptr:
462                 {
463                         if objValue.IsNil() {
464                                 return true
465                         }
466                         switch object.(type) {
467                         case *time.Time:
468                                 return object.(*time.Time).IsZero()
469                         default:
470                                 return false
471                         }
472                 }
473         }
474         return false
475 }
476
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.
479 //
480 //  assert.Empty(t, obj)
481 //
482 // Returns whether the assertion was successful (true) or not (false).
483 func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
484
485         pass := isEmpty(object)
486         if !pass {
487                 Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
488         }
489
490         return pass
491
492 }
493
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.
496 //
497 //  if assert.NotEmpty(t, obj) {
498 //    assert.Equal(t, "two", obj[1])
499 //  }
500 //
501 // Returns whether the assertion was successful (true) or not (false).
502 func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
503
504         pass := !isEmpty(object)
505         if !pass {
506                 Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
507         }
508
509         return pass
510
511 }
512
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)
517         defer func() {
518                 if e := recover(); e != nil {
519                         ok = false
520                 }
521         }()
522         return true, v.Len()
523 }
524
525 // Len asserts that the specified object has specific length.
526 // Len also fails if the object has a type that len() not accept.
527 //
528 //    assert.Len(t, mySlice, 3)
529 //
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)
533         if !ok {
534                 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
535         }
536
537         if l != length {
538                 return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
539         }
540         return true
541 }
542
543 // True asserts that the specified value is true.
544 //
545 //    assert.True(t, myBool)
546 //
547 // Returns whether the assertion was successful (true) or not (false).
548 func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
549
550         if value != true {
551                 return Fail(t, "Should be true", msgAndArgs...)
552         }
553
554         return true
555
556 }
557
558 // False asserts that the specified value is false.
559 //
560 //    assert.False(t, myBool)
561 //
562 // Returns whether the assertion was successful (true) or not (false).
563 func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
564
565         if value != false {
566                 return Fail(t, "Should be false", msgAndArgs...)
567         }
568
569         return true
570
571 }
572
573 // NotEqual asserts that the specified values are NOT equal.
574 //
575 //    assert.NotEqual(t, obj1, obj2)
576 //
577 // Returns whether the assertion was successful (true) or not (false).
578 //
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...)
585         }
586
587         if ObjectsAreEqual(expected, actual) {
588                 return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
589         }
590
591         return true
592
593 }
594
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) {
600
601         listValue := reflect.ValueOf(list)
602         elementValue := reflect.ValueOf(element)
603         defer func() {
604                 if e := recover(); e != nil {
605                         ok = false
606                         found = false
607                 }
608         }()
609
610         if reflect.TypeOf(list).Kind() == reflect.String {
611                 return true, strings.Contains(listValue.String(), elementValue.String())
612         }
613
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) {
618                                 return true, true
619                         }
620                 }
621                 return true, false
622         }
623
624         for i := 0; i < listValue.Len(); i++ {
625                 if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
626                         return true, true
627                 }
628         }
629         return true, false
630
631 }
632
633 // Contains asserts that the specified string, list(array, slice...) or map contains the
634 // specified substring or element.
635 //
636 //    assert.Contains(t, "Hello World", "World")
637 //    assert.Contains(t, ["Hello", "World"], "World")
638 //    assert.Contains(t, {"Hello": "World"}, "Hello")
639 //
640 // Returns whether the assertion was successful (true) or not (false).
641 func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
642
643         ok, found := includeElement(s, contains)
644         if !ok {
645                 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
646         }
647         if !found {
648                 return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...)
649         }
650
651         return true
652
653 }
654
655 // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
656 // specified substring or element.
657 //
658 //    assert.NotContains(t, "Hello World", "Earth")
659 //    assert.NotContains(t, ["Hello", "World"], "Earth")
660 //    assert.NotContains(t, {"Hello": "World"}, "Earth")
661 //
662 // Returns whether the assertion was successful (true) or not (false).
663 func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
664
665         ok, found := includeElement(s, contains)
666         if !ok {
667                 return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
668         }
669         if found {
670                 return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
671         }
672
673         return true
674
675 }
676
677 // Subset asserts that the specified list(array, slice...) contains all
678 // elements given in the specified subset(array, slice...).
679 //
680 //    assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
681 //
682 // Returns whether the assertion was successful (true) or not (false).
683 func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
684         if subset == nil {
685                 return true // we consider nil to be equal to the nil set
686         }
687
688         subsetValue := reflect.ValueOf(subset)
689         defer func() {
690                 if e := recover(); e != nil {
691                         ok = false
692                 }
693         }()
694
695         listKind := reflect.TypeOf(list).Kind()
696         subsetKind := reflect.TypeOf(subset).Kind()
697
698         if listKind != reflect.Array && listKind != reflect.Slice {
699                 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
700         }
701
702         if subsetKind != reflect.Array && subsetKind != reflect.Slice {
703                 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
704         }
705
706         for i := 0; i < subsetValue.Len(); i++ {
707                 element := subsetValue.Index(i).Interface()
708                 ok, found := includeElement(list, element)
709                 if !ok {
710                         return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
711                 }
712                 if !found {
713                         return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...)
714                 }
715         }
716
717         return true
718 }
719
720 // NotSubset asserts that the specified list(array, slice...) contains not all
721 // elements given in the specified subset(array, slice...).
722 //
723 //    assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
724 //
725 // Returns whether the assertion was successful (true) or not (false).
726 func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
727         if subset == nil {
728                 return false // we consider nil to be equal to the nil set
729         }
730
731         subsetValue := reflect.ValueOf(subset)
732         defer func() {
733                 if e := recover(); e != nil {
734                         ok = false
735                 }
736         }()
737
738         listKind := reflect.TypeOf(list).Kind()
739         subsetKind := reflect.TypeOf(subset).Kind()
740
741         if listKind != reflect.Array && listKind != reflect.Slice {
742                 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
743         }
744
745         if subsetKind != reflect.Array && subsetKind != reflect.Slice {
746                 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
747         }
748
749         for i := 0; i < subsetValue.Len(); i++ {
750                 element := subsetValue.Index(i).Interface()
751                 ok, found := includeElement(list, element)
752                 if !ok {
753                         return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
754                 }
755                 if !found {
756                         return true
757                 }
758         }
759
760         return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
761 }
762
763 // Condition uses a Comparison to assert a complex condition.
764 func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
765         result := comp()
766         if !result {
767                 Fail(t, "Condition failed!", msgAndArgs...)
768         }
769         return result
770 }
771
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()
775
776 // didPanic returns true if the function passed to it panics. Otherwise, it returns false.
777 func didPanic(f PanicTestFunc) (bool, interface{}) {
778
779         didPanic := false
780         var message interface{}
781         func() {
782
783                 defer func() {
784                         if message = recover(); message != nil {
785                                 didPanic = true
786                         }
787                 }()
788
789                 // call the target function
790                 f()
791
792         }()
793
794         return didPanic, message
795
796 }
797
798 // Panics asserts that the code inside the specified PanicTestFunc panics.
799 //
800 //   assert.Panics(t, func(){ GoCrazy() })
801 //
802 // Returns whether the assertion was successful (true) or not (false).
803 func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
804
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...)
807         }
808
809         return true
810 }
811
812 // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
813 // the recovered panic value equals the expected panic value.
814 //
815 //   assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
816 //
817 // Returns whether the assertion was successful (true) or not (false).
818 func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
819
820         funcDidPanic, panicValue := didPanic(f)
821         if !funcDidPanic {
822                 return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
823         }
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...)
826         }
827
828         return true
829 }
830
831 // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
832 //
833 //   assert.NotPanics(t, func(){ RemainCalm() })
834 //
835 // Returns whether the assertion was successful (true) or not (false).
836 func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
837
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...)
840         }
841
842         return true
843 }
844
845 // WithinDuration asserts that the two times are within duration delta of each other.
846 //
847 //   assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
848 //
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 {
851
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...)
855         }
856
857         return true
858 }
859
860 func toFloat(x interface{}) (float64, bool) {
861         var xf float64
862         xok := true
863
864         switch xn := x.(type) {
865         case uint8:
866                 xf = float64(xn)
867         case uint16:
868                 xf = float64(xn)
869         case uint32:
870                 xf = float64(xn)
871         case uint64:
872                 xf = float64(xn)
873         case int:
874                 xf = float64(xn)
875         case int8:
876                 xf = float64(xn)
877         case int16:
878                 xf = float64(xn)
879         case int32:
880                 xf = float64(xn)
881         case int64:
882                 xf = float64(xn)
883         case float32:
884                 xf = float64(xn)
885         case float64:
886                 xf = float64(xn)
887         case time.Duration:
888                 xf = float64(xn)
889         default:
890                 xok = false
891         }
892
893         return xf, xok
894 }
895
896 // InDelta asserts that the two numerals are within delta of each other.
897 //
898 //       assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
899 //
900 // Returns whether the assertion was successful (true) or not (false).
901 func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
902
903         af, aok := toFloat(expected)
904         bf, bok := toFloat(actual)
905
906         if !aok || !bok {
907                 return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
908         }
909
910         if math.IsNaN(af) {
911                 return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...)
912         }
913
914         if math.IsNaN(bf) {
915                 return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
916         }
917
918         dt := af - bf
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...)
921         }
922
923         return true
924 }
925
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...)
932         }
933
934         actualSlice := reflect.ValueOf(actual)
935         expectedSlice := reflect.ValueOf(expected)
936
937         for i := 0; i < actualSlice.Len(); i++ {
938                 result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
939                 if !result {
940                         return result
941                 }
942         }
943
944         return true
945 }
946
947 func calcRelativeError(expected, actual interface{}) (float64, error) {
948         af, aok := toFloat(expected)
949         if !aok {
950                 return 0, fmt.Errorf("expected value %q cannot be converted to float", expected)
951         }
952         if af == 0 {
953                 return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
954         }
955         bf, bok := toFloat(actual)
956         if !bok {
957                 return 0, fmt.Errorf("actual value %q cannot be converted to float", actual)
958         }
959
960         return math.Abs(af-bf) / math.Abs(af), nil
961 }
962
963 // InEpsilon asserts that expected and actual have a relative error less than epsilon
964 //
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)
968         if err != nil {
969                 return Fail(t, err.Error(), msgAndArgs...)
970         }
971         if actualEpsilon > epsilon {
972                 return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
973                         "        < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
974         }
975
976         return true
977 }
978
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...)
985         }
986
987         actualSlice := reflect.ValueOf(actual)
988         expectedSlice := reflect.ValueOf(expected)
989
990         for i := 0; i < actualSlice.Len(); i++ {
991                 result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
992                 if !result {
993                         return result
994                 }
995         }
996
997         return true
998 }
999
1000 /*
1001         Errors
1002 */
1003
1004 // NoError asserts that a function returned no error (i.e. `nil`).
1005 //
1006 //   actualObj, err := SomeFunction()
1007 //   if assert.NoError(t, err) {
1008 //         assert.Equal(t, expectedObj, actualObj)
1009 //   }
1010 //
1011 // Returns whether the assertion was successful (true) or not (false).
1012 func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
1013         if err != nil {
1014                 return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
1015         }
1016
1017         return true
1018 }
1019
1020 // Error asserts that a function returned an error (i.e. not `nil`).
1021 //
1022 //   actualObj, err := SomeFunction()
1023 //   if assert.Error(t, err) {
1024 //         assert.Equal(t, expectedError, err)
1025 //   }
1026 //
1027 // Returns whether the assertion was successful (true) or not (false).
1028 func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
1029
1030         if err == nil {
1031                 return Fail(t, "An error is expected but got nil.", msgAndArgs...)
1032         }
1033
1034         return true
1035 }
1036
1037 // EqualError asserts that a function returned an error (i.e. not `nil`)
1038 // and that it is equal to the provided error.
1039 //
1040 //   actualObj, err := SomeFunction()
1041 //   assert.EqualError(t, err,  expectedErrorString)
1042 //
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...) {
1046                 return false
1047         }
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"+
1053                         "expected: %q\n"+
1054                         "actual: %q", expected, actual), msgAndArgs...)
1055         }
1056         return true
1057 }
1058
1059 // matchRegexp return true if a specified regexp matches a string.
1060 func matchRegexp(rx interface{}, str interface{}) bool {
1061
1062         var r *regexp.Regexp
1063         if rr, ok := rx.(*regexp.Regexp); ok {
1064                 r = rr
1065         } else {
1066                 r = regexp.MustCompile(fmt.Sprint(rx))
1067         }
1068
1069         return (r.FindStringIndex(fmt.Sprint(str)) != nil)
1070
1071 }
1072
1073 // Regexp asserts that a specified regexp matches a string.
1074 //
1075 //  assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
1076 //  assert.Regexp(t, "start...$", "it's not starting")
1077 //
1078 // Returns whether the assertion was successful (true) or not (false).
1079 func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
1080
1081         match := matchRegexp(rx, str)
1082
1083         if !match {
1084                 Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
1085         }
1086
1087         return match
1088 }
1089
1090 // NotRegexp asserts that a specified regexp does not match a string.
1091 //
1092 //  assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
1093 //  assert.NotRegexp(t, "^start", "it's not starting")
1094 //
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)
1098
1099         if match {
1100                 Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
1101         }
1102
1103         return !match
1104
1105 }
1106
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...)
1111         }
1112         return true
1113 }
1114
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...)
1119         }
1120         return true
1121 }
1122
1123 // JSONEq asserts that two JSON strings are equivalent.
1124 //
1125 //  assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
1126 //
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{}
1130
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...)
1133         }
1134
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...)
1137         }
1138
1139         return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
1140 }
1141
1142 func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
1143         t := reflect.TypeOf(v)
1144         k := t.Kind()
1145
1146         if k == reflect.Ptr {
1147                 t = t.Elem()
1148                 k = t.Kind()
1149         }
1150         return t, k
1151 }
1152
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 {
1157                 return ""
1158         }
1159
1160         et, ek := typeAndKind(expected)
1161         at, _ := typeAndKind(actual)
1162
1163         if et != at {
1164                 return ""
1165         }
1166
1167         if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array {
1168                 return ""
1169         }
1170
1171         e := spewConfig.Sdump(expected)
1172         a := spewConfig.Sdump(actual)
1173
1174         diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
1175                 A:        difflib.SplitLines(e),
1176                 B:        difflib.SplitLines(a),
1177                 FromFile: "Expected",
1178                 FromDate: "",
1179                 ToFile:   "Actual",
1180                 ToDate:   "",
1181                 Context:  1,
1182         })
1183
1184         return "\n\nDiff:\n" + diff
1185 }
1186
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")
1192         }
1193         return nil
1194 }
1195
1196 func isFunction(arg interface{}) bool {
1197         if arg == nil {
1198                 return false
1199         }
1200         return reflect.TypeOf(arg).Kind() == reflect.Func
1201 }
1202
1203 var spewConfig = spew.ConfigState{
1204         Indent:                  " ",
1205         DisablePointerAddresses: true,
1206         DisableCapacities:       true,
1207         SortKeys:                true,
1208 }