assertions.go 38 KB

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