assertions.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. package assert
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "math"
  8. "reflect"
  9. "regexp"
  10. "runtime"
  11. "strings"
  12. "time"
  13. "unicode"
  14. "unicode/utf8"
  15. "github.com/davecgh/go-spew/spew"
  16. "github.com/pmezard/go-difflib/difflib"
  17. )
  18. func init() {
  19. spew.Config.SortKeys = true
  20. }
  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. return reflect.DeepEqual(expected, actual)
  38. }
  39. // ObjectsAreEqualValues gets whether two objects are equal, or if their
  40. // values are equal.
  41. func ObjectsAreEqualValues(expected, actual interface{}) bool {
  42. if ObjectsAreEqual(expected, actual) {
  43. return true
  44. }
  45. actualType := reflect.TypeOf(actual)
  46. if actualType == nil {
  47. return false
  48. }
  49. expectedValue := reflect.ValueOf(expected)
  50. if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
  51. // Attempt comparison after type conversion
  52. return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
  53. }
  54. return false
  55. }
  56. /* CallerInfo is necessary because the assert functions use the testing object
  57. internally, causing it to print the file:line of the assert method, rather than where
  58. the problem actually occurred in calling code.*/
  59. // CallerInfo returns an array of strings containing the file and line number
  60. // of each stack frame leading from the current test to the assert call that
  61. // failed.
  62. func CallerInfo() []string {
  63. pc := uintptr(0)
  64. file := ""
  65. line := 0
  66. ok := false
  67. name := ""
  68. callers := []string{}
  69. for i := 0; ; i++ {
  70. pc, file, line, ok = runtime.Caller(i)
  71. if !ok {
  72. // The breaks below failed to terminate the loop, and we ran off the
  73. // end of the call stack.
  74. break
  75. }
  76. // This is a huge edge case, but it will panic if this is the case, see #180
  77. if file == "<autogenerated>" {
  78. break
  79. }
  80. f := runtime.FuncForPC(pc)
  81. if f == nil {
  82. break
  83. }
  84. name = f.Name()
  85. // testing.tRunner is the standard library function that calls
  86. // tests. Subtests are called directly by tRunner, without going through
  87. // the Test/Benchmark/Example function that contains the t.Run calls, so
  88. // with subtests we should break when we hit tRunner, without adding it
  89. // to the list of callers.
  90. if name == "testing.tRunner" {
  91. break
  92. }
  93. parts := strings.Split(file, "/")
  94. dir := parts[len(parts)-2]
  95. file = parts[len(parts)-1]
  96. if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
  97. callers = append(callers, fmt.Sprintf("%s:%d", file, line))
  98. }
  99. // Drop the package
  100. segments := strings.Split(name, ".")
  101. name = segments[len(segments)-1]
  102. if isTest(name, "Test") ||
  103. isTest(name, "Benchmark") ||
  104. isTest(name, "Example") {
  105. break
  106. }
  107. }
  108. return callers
  109. }
  110. // Stolen from the `go test` tool.
  111. // isTest tells whether name looks like a test (or benchmark, according to prefix).
  112. // It is a Test (say) if there is a character after Test that is not a lower-case letter.
  113. // We don't want TesticularCancer.
  114. func isTest(name, prefix string) bool {
  115. if !strings.HasPrefix(name, prefix) {
  116. return false
  117. }
  118. if len(name) == len(prefix) { // "Test" is ok
  119. return true
  120. }
  121. rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
  122. return !unicode.IsLower(rune)
  123. }
  124. // getWhitespaceString returns a string that is long enough to overwrite the default
  125. // output from the go testing framework.
  126. func getWhitespaceString() string {
  127. _, file, line, ok := runtime.Caller(1)
  128. if !ok {
  129. return ""
  130. }
  131. parts := strings.Split(file, "/")
  132. file = parts[len(parts)-1]
  133. return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line)))
  134. }
  135. func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
  136. if len(msgAndArgs) == 0 || msgAndArgs == nil {
  137. return ""
  138. }
  139. if len(msgAndArgs) == 1 {
  140. return msgAndArgs[0].(string)
  141. }
  142. if len(msgAndArgs) > 1 {
  143. return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
  144. }
  145. return ""
  146. }
  147. // Indents all lines of the message by appending a number of tabs to each line, in an output format compatible with Go's
  148. // test printing (see inner comment for specifics)
  149. func indentMessageLines(message string, tabs int) string {
  150. outBuf := new(bytes.Buffer)
  151. for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
  152. if i != 0 {
  153. outBuf.WriteRune('\n')
  154. }
  155. for ii := 0; ii < tabs; ii++ {
  156. outBuf.WriteRune('\t')
  157. // Bizarrely, all lines except the first need one fewer tabs prepended, so deliberately advance the counter
  158. // by 1 prematurely.
  159. if ii == 0 && i > 0 {
  160. ii++
  161. }
  162. }
  163. outBuf.WriteString(scanner.Text())
  164. }
  165. return outBuf.String()
  166. }
  167. type failNower interface {
  168. FailNow()
  169. }
  170. // FailNow fails test
  171. func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
  172. Fail(t, failureMessage, msgAndArgs...)
  173. // We cannot extend TestingT with FailNow() and
  174. // maintain backwards compatibility, so we fallback
  175. // to panicking when FailNow is not available in
  176. // TestingT.
  177. // See issue #263
  178. if t, ok := t.(failNower); ok {
  179. t.FailNow()
  180. } else {
  181. panic("test failed and t is missing `FailNow()`")
  182. }
  183. return false
  184. }
  185. // Fail reports a failure through
  186. func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
  187. message := messageFromMsgAndArgs(msgAndArgs...)
  188. errorTrace := strings.Join(CallerInfo(), "\n\r\t\t\t")
  189. if len(message) > 0 {
  190. t.Errorf("\r%s\r\tError Trace:\t%s\n"+
  191. "\r\tError:%s\n"+
  192. "\r\tMessages:\t%s\n\r",
  193. getWhitespaceString(),
  194. errorTrace,
  195. indentMessageLines(failureMessage, 2),
  196. message)
  197. } else {
  198. t.Errorf("\r%s\r\tError Trace:\t%s\n"+
  199. "\r\tError:%s\n\r",
  200. getWhitespaceString(),
  201. errorTrace,
  202. indentMessageLines(failureMessage, 2))
  203. }
  204. return false
  205. }
  206. // Implements asserts that an object is implemented by the specified interface.
  207. //
  208. // assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject")
  209. func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
  210. interfaceType := reflect.TypeOf(interfaceObject).Elem()
  211. if !reflect.TypeOf(object).Implements(interfaceType) {
  212. return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
  213. }
  214. return true
  215. }
  216. // IsType asserts that the specified objects are of the same type.
  217. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
  218. if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
  219. return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
  220. }
  221. return true
  222. }
  223. // Equal asserts that two objects are equal.
  224. //
  225. // assert.Equal(t, 123, 123, "123 and 123 should be equal")
  226. //
  227. // Returns whether the assertion was successful (true) or not (false).
  228. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  229. if !ObjectsAreEqual(expected, actual) {
  230. diff := diff(expected, actual)
  231. expected, actual = formatUnequalValues(expected, actual)
  232. return Fail(t, fmt.Sprintf("Not equal: \n"+
  233. "expected: %s\n"+
  234. "received: %s%s", expected, actual, diff), msgAndArgs...)
  235. }
  236. return true
  237. }
  238. // formatUnequalValues takes two values of arbitrary types and returns string
  239. // representations appropriate to be presented to the user.
  240. //
  241. // If the values are not of like type, the returned strings will be prefixed
  242. // with the type name, and the value will be enclosed in parenthesis similar
  243. // to a type conversion in the Go grammar.
  244. func formatUnequalValues(expected, actual interface{}) (e string, a string) {
  245. aType := reflect.TypeOf(expected)
  246. bType := reflect.TypeOf(actual)
  247. if aType != bType && isNumericType(aType) && isNumericType(bType) {
  248. return fmt.Sprintf("%v(%#v)", aType, expected),
  249. fmt.Sprintf("%v(%#v)", bType, actual)
  250. }
  251. return fmt.Sprintf("%#v", expected),
  252. fmt.Sprintf("%#v", actual)
  253. }
  254. func isNumericType(t reflect.Type) bool {
  255. switch t.Kind() {
  256. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  257. return true
  258. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  259. return true
  260. case reflect.Float32, reflect.Float64:
  261. return true
  262. }
  263. return false
  264. }
  265. // EqualValues asserts that two objects are equal or convertable to the same types
  266. // and equal.
  267. //
  268. // assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal")
  269. //
  270. // Returns whether the assertion was successful (true) or not (false).
  271. func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  272. if !ObjectsAreEqualValues(expected, actual) {
  273. diff := diff(expected, actual)
  274. expected, actual = formatUnequalValues(expected, actual)
  275. return Fail(t, fmt.Sprintf("Not equal: \n"+
  276. "expected: %s\n"+
  277. "received: %s%s", expected, actual, diff), msgAndArgs...)
  278. }
  279. return true
  280. }
  281. // Exactly asserts that two objects are equal is value and type.
  282. //
  283. // assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal")
  284. //
  285. // Returns whether the assertion was successful (true) or not (false).
  286. func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  287. aType := reflect.TypeOf(expected)
  288. bType := reflect.TypeOf(actual)
  289. if aType != bType {
  290. return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...)
  291. }
  292. return Equal(t, expected, actual, msgAndArgs...)
  293. }
  294. // NotNil asserts that the specified object is not nil.
  295. //
  296. // assert.NotNil(t, err, "err should be something")
  297. //
  298. // Returns whether the assertion was successful (true) or not (false).
  299. func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  300. if !isNil(object) {
  301. return true
  302. }
  303. return Fail(t, "Expected value not to be nil.", msgAndArgs...)
  304. }
  305. // isNil checks if a specified object is nil or not, without Failing.
  306. func isNil(object interface{}) bool {
  307. if object == nil {
  308. return true
  309. }
  310. value := reflect.ValueOf(object)
  311. kind := value.Kind()
  312. if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
  313. return true
  314. }
  315. return false
  316. }
  317. // Nil asserts that the specified object is nil.
  318. //
  319. // assert.Nil(t, err, "err should be nothing")
  320. //
  321. // Returns whether the assertion was successful (true) or not (false).
  322. func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  323. if isNil(object) {
  324. return true
  325. }
  326. return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
  327. }
  328. var numericZeros = []interface{}{
  329. int(0),
  330. int8(0),
  331. int16(0),
  332. int32(0),
  333. int64(0),
  334. uint(0),
  335. uint8(0),
  336. uint16(0),
  337. uint32(0),
  338. uint64(0),
  339. float32(0),
  340. float64(0),
  341. }
  342. // isEmpty gets whether the specified object is considered empty or not.
  343. func isEmpty(object interface{}) bool {
  344. if object == nil {
  345. return true
  346. } else if object == "" {
  347. return true
  348. } else if object == false {
  349. return true
  350. }
  351. for _, v := range numericZeros {
  352. if object == v {
  353. return true
  354. }
  355. }
  356. objValue := reflect.ValueOf(object)
  357. switch objValue.Kind() {
  358. case reflect.Map:
  359. fallthrough
  360. case reflect.Slice, reflect.Chan:
  361. {
  362. return (objValue.Len() == 0)
  363. }
  364. case reflect.Struct:
  365. switch object.(type) {
  366. case time.Time:
  367. return object.(time.Time).IsZero()
  368. }
  369. case reflect.Ptr:
  370. {
  371. if objValue.IsNil() {
  372. return true
  373. }
  374. switch object.(type) {
  375. case *time.Time:
  376. return object.(*time.Time).IsZero()
  377. default:
  378. return false
  379. }
  380. }
  381. }
  382. return false
  383. }
  384. // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
  385. // a slice or a channel with len == 0.
  386. //
  387. // assert.Empty(t, obj)
  388. //
  389. // Returns whether the assertion was successful (true) or not (false).
  390. func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  391. pass := isEmpty(object)
  392. if !pass {
  393. Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
  394. }
  395. return pass
  396. }
  397. // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
  398. // a slice or a channel with len == 0.
  399. //
  400. // if assert.NotEmpty(t, obj) {
  401. // assert.Equal(t, "two", obj[1])
  402. // }
  403. //
  404. // Returns whether the assertion was successful (true) or not (false).
  405. func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  406. pass := !isEmpty(object)
  407. if !pass {
  408. Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
  409. }
  410. return pass
  411. }
  412. // getLen try to get length of object.
  413. // return (false, 0) if impossible.
  414. func getLen(x interface{}) (ok bool, length int) {
  415. v := reflect.ValueOf(x)
  416. defer func() {
  417. if e := recover(); e != nil {
  418. ok = false
  419. }
  420. }()
  421. return true, v.Len()
  422. }
  423. // Len asserts that the specified object has specific length.
  424. // Len also fails if the object has a type that len() not accept.
  425. //
  426. // assert.Len(t, mySlice, 3, "The size of slice is not 3")
  427. //
  428. // Returns whether the assertion was successful (true) or not (false).
  429. func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
  430. ok, l := getLen(object)
  431. if !ok {
  432. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
  433. }
  434. if l != length {
  435. return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
  436. }
  437. return true
  438. }
  439. // True asserts that the specified value is true.
  440. //
  441. // assert.True(t, myBool, "myBool should be true")
  442. //
  443. // Returns whether the assertion was successful (true) or not (false).
  444. func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
  445. if value != true {
  446. return Fail(t, "Should be true", msgAndArgs...)
  447. }
  448. return true
  449. }
  450. // False asserts that the specified value is false.
  451. //
  452. // assert.False(t, myBool, "myBool should be false")
  453. //
  454. // Returns whether the assertion was successful (true) or not (false).
  455. func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
  456. if value != false {
  457. return Fail(t, "Should be false", msgAndArgs...)
  458. }
  459. return true
  460. }
  461. // NotEqual asserts that the specified values are NOT equal.
  462. //
  463. // assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal")
  464. //
  465. // Returns whether the assertion was successful (true) or not (false).
  466. func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  467. if ObjectsAreEqual(expected, actual) {
  468. return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
  469. }
  470. return true
  471. }
  472. // containsElement try loop over the list check if the list includes the element.
  473. // return (false, false) if impossible.
  474. // return (true, false) if element was not found.
  475. // return (true, true) if element was found.
  476. func includeElement(list interface{}, element interface{}) (ok, found bool) {
  477. listValue := reflect.ValueOf(list)
  478. elementValue := reflect.ValueOf(element)
  479. defer func() {
  480. if e := recover(); e != nil {
  481. ok = false
  482. found = false
  483. }
  484. }()
  485. if reflect.TypeOf(list).Kind() == reflect.String {
  486. return true, strings.Contains(listValue.String(), elementValue.String())
  487. }
  488. if reflect.TypeOf(list).Kind() == reflect.Map {
  489. mapKeys := listValue.MapKeys()
  490. for i := 0; i < len(mapKeys); i++ {
  491. if ObjectsAreEqual(mapKeys[i].Interface(), element) {
  492. return true, true
  493. }
  494. }
  495. return true, false
  496. }
  497. for i := 0; i < listValue.Len(); i++ {
  498. if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
  499. return true, true
  500. }
  501. }
  502. return true, false
  503. }
  504. // Contains asserts that the specified string, list(array, slice...) or map contains the
  505. // specified substring or element.
  506. //
  507. // assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'")
  508. // assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'")
  509. // assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'")
  510. //
  511. // Returns whether the assertion was successful (true) or not (false).
  512. func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
  513. ok, found := includeElement(s, contains)
  514. if !ok {
  515. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
  516. }
  517. if !found {
  518. return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...)
  519. }
  520. return true
  521. }
  522. // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
  523. // specified substring or element.
  524. //
  525. // assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'")
  526. // assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'")
  527. // assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'")
  528. //
  529. // Returns whether the assertion was successful (true) or not (false).
  530. func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
  531. ok, found := includeElement(s, contains)
  532. if !ok {
  533. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
  534. }
  535. if found {
  536. return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
  537. }
  538. return true
  539. }
  540. // Condition uses a Comparison to assert a complex condition.
  541. func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
  542. result := comp()
  543. if !result {
  544. Fail(t, "Condition failed!", msgAndArgs...)
  545. }
  546. return result
  547. }
  548. // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
  549. // methods, and represents a simple func that takes no arguments, and returns nothing.
  550. type PanicTestFunc func()
  551. // didPanic returns true if the function passed to it panics. Otherwise, it returns false.
  552. func didPanic(f PanicTestFunc) (bool, interface{}) {
  553. didPanic := false
  554. var message interface{}
  555. func() {
  556. defer func() {
  557. if message = recover(); message != nil {
  558. didPanic = true
  559. }
  560. }()
  561. // call the target function
  562. f()
  563. }()
  564. return didPanic, message
  565. }
  566. // Panics asserts that the code inside the specified PanicTestFunc panics.
  567. //
  568. // assert.Panics(t, func(){
  569. // GoCrazy()
  570. // }, "Calling GoCrazy() should panic")
  571. //
  572. // Returns whether the assertion was successful (true) or not (false).
  573. func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  574. if funcDidPanic, panicValue := didPanic(f); !funcDidPanic {
  575. return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
  576. }
  577. return true
  578. }
  579. // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
  580. //
  581. // assert.NotPanics(t, func(){
  582. // RemainCalm()
  583. // }, "Calling RemainCalm() should NOT panic")
  584. //
  585. // Returns whether the assertion was successful (true) or not (false).
  586. func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  587. if funcDidPanic, panicValue := didPanic(f); funcDidPanic {
  588. return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...)
  589. }
  590. return true
  591. }
  592. // WithinDuration asserts that the two times are within duration delta of each other.
  593. //
  594. // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s")
  595. //
  596. // Returns whether the assertion was successful (true) or not (false).
  597. func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
  598. dt := expected.Sub(actual)
  599. if dt < -delta || dt > delta {
  600. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
  601. }
  602. return true
  603. }
  604. func toFloat(x interface{}) (float64, bool) {
  605. var xf float64
  606. xok := true
  607. switch xn := x.(type) {
  608. case uint8:
  609. xf = float64(xn)
  610. case uint16:
  611. xf = float64(xn)
  612. case uint32:
  613. xf = float64(xn)
  614. case uint64:
  615. xf = float64(xn)
  616. case int:
  617. xf = float64(xn)
  618. case int8:
  619. xf = float64(xn)
  620. case int16:
  621. xf = float64(xn)
  622. case int32:
  623. xf = float64(xn)
  624. case int64:
  625. xf = float64(xn)
  626. case float32:
  627. xf = float64(xn)
  628. case float64:
  629. xf = float64(xn)
  630. default:
  631. xok = false
  632. }
  633. return xf, xok
  634. }
  635. // InDelta asserts that the two numerals are within delta of each other.
  636. //
  637. // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
  638. //
  639. // Returns whether the assertion was successful (true) or not (false).
  640. func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  641. af, aok := toFloat(expected)
  642. bf, bok := toFloat(actual)
  643. if !aok || !bok {
  644. return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
  645. }
  646. if math.IsNaN(af) {
  647. return Fail(t, fmt.Sprintf("Actual must not be NaN"), msgAndArgs...)
  648. }
  649. if math.IsNaN(bf) {
  650. return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
  651. }
  652. dt := af - bf
  653. if dt < -delta || dt > delta {
  654. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
  655. }
  656. return true
  657. }
  658. // InDeltaSlice is the same as InDelta, except it compares two slices.
  659. func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  660. if expected == nil || actual == nil ||
  661. reflect.TypeOf(actual).Kind() != reflect.Slice ||
  662. reflect.TypeOf(expected).Kind() != reflect.Slice {
  663. return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
  664. }
  665. actualSlice := reflect.ValueOf(actual)
  666. expectedSlice := reflect.ValueOf(expected)
  667. for i := 0; i < actualSlice.Len(); i++ {
  668. result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta)
  669. if !result {
  670. return result
  671. }
  672. }
  673. return true
  674. }
  675. func calcRelativeError(expected, actual interface{}) (float64, error) {
  676. af, aok := toFloat(expected)
  677. if !aok {
  678. return 0, fmt.Errorf("expected value %q cannot be converted to float", expected)
  679. }
  680. if af == 0 {
  681. return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
  682. }
  683. bf, bok := toFloat(actual)
  684. if !bok {
  685. return 0, fmt.Errorf("expected value %q cannot be converted to float", actual)
  686. }
  687. return math.Abs(af-bf) / math.Abs(af), nil
  688. }
  689. // InEpsilon asserts that expected and actual have a relative error less than epsilon
  690. //
  691. // Returns whether the assertion was successful (true) or not (false).
  692. func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
  693. actualEpsilon, err := calcRelativeError(expected, actual)
  694. if err != nil {
  695. return Fail(t, err.Error(), msgAndArgs...)
  696. }
  697. if actualEpsilon > epsilon {
  698. return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
  699. " < %#v (actual)", actualEpsilon, epsilon), msgAndArgs...)
  700. }
  701. return true
  702. }
  703. // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
  704. func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
  705. if expected == nil || actual == nil ||
  706. reflect.TypeOf(actual).Kind() != reflect.Slice ||
  707. reflect.TypeOf(expected).Kind() != reflect.Slice {
  708. return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
  709. }
  710. actualSlice := reflect.ValueOf(actual)
  711. expectedSlice := reflect.ValueOf(expected)
  712. for i := 0; i < actualSlice.Len(); i++ {
  713. result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
  714. if !result {
  715. return result
  716. }
  717. }
  718. return true
  719. }
  720. /*
  721. Errors
  722. */
  723. // NoError asserts that a function returned no error (i.e. `nil`).
  724. //
  725. // actualObj, err := SomeFunction()
  726. // if assert.NoError(t, err) {
  727. // assert.Equal(t, actualObj, expectedObj)
  728. // }
  729. //
  730. // Returns whether the assertion was successful (true) or not (false).
  731. func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
  732. if err != nil {
  733. return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
  734. }
  735. return true
  736. }
  737. // Error asserts that a function returned an error (i.e. not `nil`).
  738. //
  739. // actualObj, err := SomeFunction()
  740. // if assert.Error(t, err, "An error was expected") {
  741. // assert.Equal(t, err, expectedError)
  742. // }
  743. //
  744. // Returns whether the assertion was successful (true) or not (false).
  745. func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
  746. if err == nil {
  747. return Fail(t, "An error is expected but got nil.", msgAndArgs...)
  748. }
  749. return true
  750. }
  751. // EqualError asserts that a function returned an error (i.e. not `nil`)
  752. // and that it is equal to the provided error.
  753. //
  754. // actualObj, err := SomeFunction()
  755. // assert.EqualError(t, err, expectedErrorString, "An error was expected")
  756. //
  757. // Returns whether the assertion was successful (true) or not (false).
  758. func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
  759. if !Error(t, theError, msgAndArgs...) {
  760. return false
  761. }
  762. expected := errString
  763. actual := theError.Error()
  764. // don't need to use deep equals here, we know they are both strings
  765. if expected != actual {
  766. return Fail(t, fmt.Sprintf("Error message not equal:\n"+
  767. "expected: %q\n"+
  768. "received: %q", expected, actual), msgAndArgs...)
  769. }
  770. return true
  771. }
  772. // matchRegexp return true if a specified regexp matches a string.
  773. func matchRegexp(rx interface{}, str interface{}) bool {
  774. var r *regexp.Regexp
  775. if rr, ok := rx.(*regexp.Regexp); ok {
  776. r = rr
  777. } else {
  778. r = regexp.MustCompile(fmt.Sprint(rx))
  779. }
  780. return (r.FindStringIndex(fmt.Sprint(str)) != nil)
  781. }
  782. // Regexp asserts that a specified regexp matches a string.
  783. //
  784. // assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
  785. // assert.Regexp(t, "start...$", "it's not starting")
  786. //
  787. // Returns whether the assertion was successful (true) or not (false).
  788. func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
  789. match := matchRegexp(rx, str)
  790. if !match {
  791. Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
  792. }
  793. return match
  794. }
  795. // NotRegexp asserts that a specified regexp does not match a string.
  796. //
  797. // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
  798. // assert.NotRegexp(t, "^start", "it's not starting")
  799. //
  800. // Returns whether the assertion was successful (true) or not (false).
  801. func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
  802. match := matchRegexp(rx, str)
  803. if match {
  804. Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
  805. }
  806. return !match
  807. }
  808. // Zero asserts that i is the zero value for its type and returns the truth.
  809. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
  810. if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
  811. return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
  812. }
  813. return true
  814. }
  815. // NotZero asserts that i is not the zero value for its type and returns the truth.
  816. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
  817. if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
  818. return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
  819. }
  820. return true
  821. }
  822. // JSONEq asserts that two JSON strings are equivalent.
  823. //
  824. // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
  825. //
  826. // Returns whether the assertion was successful (true) or not (false).
  827. func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
  828. var expectedJSONAsInterface, actualJSONAsInterface interface{}
  829. if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
  830. return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
  831. }
  832. if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
  833. return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
  834. }
  835. return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
  836. }
  837. func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
  838. t := reflect.TypeOf(v)
  839. k := t.Kind()
  840. if k == reflect.Ptr {
  841. t = t.Elem()
  842. k = t.Kind()
  843. }
  844. return t, k
  845. }
  846. // diff returns a diff of both values as long as both are of the same type and
  847. // are a struct, map, slice or array. Otherwise it returns an empty string.
  848. func diff(expected interface{}, actual interface{}) string {
  849. if expected == nil || actual == nil {
  850. return ""
  851. }
  852. et, ek := typeAndKind(expected)
  853. at, _ := typeAndKind(actual)
  854. if et != at {
  855. return ""
  856. }
  857. if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array {
  858. return ""
  859. }
  860. e := spew.Sdump(expected)
  861. a := spew.Sdump(actual)
  862. diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
  863. A: difflib.SplitLines(e),
  864. B: difflib.SplitLines(a),
  865. FromFile: "Expected",
  866. FromDate: "",
  867. ToFile: "Actual",
  868. ToDate: "",
  869. Context: 1,
  870. })
  871. return "\n\nDiff:\n" + diff
  872. }