You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1052 lines
29 KiB

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