1
0

assertions.go 29 KB

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