You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1417 lines
39 KiB

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