assertions.go 28 KB

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