assertions.go 24 KB

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