assertions.go 26 KB

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