本站源代码
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.

1499 lines
41KB

  1. package assert
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "math"
  9. "os"
  10. "reflect"
  11. "regexp"
  12. "runtime"
  13. "strings"
  14. "time"
  15. "unicode"
  16. "unicode/utf8"
  17. "github.com/davecgh/go-spew/spew"
  18. "github.com/pmezard/go-difflib/difflib"
  19. yaml "gopkg.in/yaml.v2"
  20. )
  21. //go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_format.go.tmpl
  22. // TestingT is an interface wrapper around *testing.T
  23. type TestingT interface {
  24. Errorf(format string, args ...interface{})
  25. }
  26. // ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
  27. // for table driven tests.
  28. type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
  29. // ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
  30. // for table driven tests.
  31. type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
  32. // BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
  33. // for table driven tests.
  34. type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
  35. // ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
  36. // for table driven tests.
  37. type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
  38. // Comparison a custom function that returns true on success and false on failure
  39. type Comparison func() (success bool)
  40. /*
  41. Helper functions
  42. */
  43. // ObjectsAreEqual determines if two objects are considered equal.
  44. //
  45. // This function does no assertion of any kind.
  46. func ObjectsAreEqual(expected, actual interface{}) bool {
  47. if expected == nil || actual == nil {
  48. return expected == actual
  49. }
  50. exp, ok := expected.([]byte)
  51. if !ok {
  52. return reflect.DeepEqual(expected, actual)
  53. }
  54. act, ok := actual.([]byte)
  55. if !ok {
  56. return false
  57. }
  58. if exp == nil || act == nil {
  59. return exp == nil && act == nil
  60. }
  61. return bytes.Equal(exp, act)
  62. }
  63. // ObjectsAreEqualValues gets whether two objects are equal, or if their
  64. // values are equal.
  65. func ObjectsAreEqualValues(expected, actual interface{}) bool {
  66. if ObjectsAreEqual(expected, actual) {
  67. return true
  68. }
  69. actualType := reflect.TypeOf(actual)
  70. if actualType == nil {
  71. return false
  72. }
  73. expectedValue := reflect.ValueOf(expected)
  74. if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
  75. // Attempt comparison after type conversion
  76. return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
  77. }
  78. return false
  79. }
  80. /* CallerInfo is necessary because the assert functions use the testing object
  81. internally, causing it to print the file:line of the assert method, rather than where
  82. the problem actually occurred in calling code.*/
  83. // CallerInfo returns an array of strings containing the file and line number
  84. // of each stack frame leading from the current test to the assert call that
  85. // failed.
  86. func CallerInfo() []string {
  87. pc := uintptr(0)
  88. file := ""
  89. line := 0
  90. ok := false
  91. name := ""
  92. callers := []string{}
  93. for i := 0; ; i++ {
  94. pc, file, line, ok = runtime.Caller(i)
  95. if !ok {
  96. // The breaks below failed to terminate the loop, and we ran off the
  97. // end of the call stack.
  98. break
  99. }
  100. // This is a huge edge case, but it will panic if this is the case, see #180
  101. if file == "<autogenerated>" {
  102. break
  103. }
  104. f := runtime.FuncForPC(pc)
  105. if f == nil {
  106. break
  107. }
  108. name = f.Name()
  109. // testing.tRunner is the standard library function that calls
  110. // tests. Subtests are called directly by tRunner, without going through
  111. // the Test/Benchmark/Example function that contains the t.Run calls, so
  112. // with subtests we should break when we hit tRunner, without adding it
  113. // to the list of callers.
  114. if name == "testing.tRunner" {
  115. break
  116. }
  117. parts := strings.Split(file, "/")
  118. file = parts[len(parts)-1]
  119. if len(parts) > 1 {
  120. dir := parts[len(parts)-2]
  121. if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
  122. callers = append(callers, fmt.Sprintf("%s:%d", file, line))
  123. }
  124. }
  125. // Drop the package
  126. segments := strings.Split(name, ".")
  127. name = segments[len(segments)-1]
  128. if isTest(name, "Test") ||
  129. isTest(name, "Benchmark") ||
  130. isTest(name, "Example") {
  131. break
  132. }
  133. }
  134. return callers
  135. }
  136. // Stolen from the `go test` tool.
  137. // isTest tells whether name looks like a test (or benchmark, according to prefix).
  138. // It is a Test (say) if there is a character after Test that is not a lower-case letter.
  139. // We don't want TesticularCancer.
  140. func isTest(name, prefix string) bool {
  141. if !strings.HasPrefix(name, prefix) {
  142. return false
  143. }
  144. if len(name) == len(prefix) { // "Test" is ok
  145. return true
  146. }
  147. rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
  148. return !unicode.IsLower(rune)
  149. }
  150. func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
  151. if len(msgAndArgs) == 0 || msgAndArgs == nil {
  152. return ""
  153. }
  154. if len(msgAndArgs) == 1 {
  155. msg := msgAndArgs[0]
  156. if msgAsStr, ok := msg.(string); ok {
  157. return msgAsStr
  158. }
  159. return fmt.Sprintf("%+v", msg)
  160. }
  161. if len(msgAndArgs) > 1 {
  162. return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
  163. }
  164. return ""
  165. }
  166. // Aligns the provided message so that all lines after the first line start at the same location as the first line.
  167. // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
  168. // The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
  169. // basis on which the alignment occurs).
  170. func indentMessageLines(message string, longestLabelLen int) string {
  171. outBuf := new(bytes.Buffer)
  172. for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
  173. // no need to align first line because it starts at the correct location (after the label)
  174. if i != 0 {
  175. // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
  176. outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
  177. }
  178. outBuf.WriteString(scanner.Text())
  179. }
  180. return outBuf.String()
  181. }
  182. type failNower interface {
  183. FailNow()
  184. }
  185. // FailNow fails test
  186. func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
  187. if h, ok := t.(tHelper); ok {
  188. h.Helper()
  189. }
  190. Fail(t, failureMessage, msgAndArgs...)
  191. // We cannot extend TestingT with FailNow() and
  192. // maintain backwards compatibility, so we fallback
  193. // to panicking when FailNow is not available in
  194. // TestingT.
  195. // See issue #263
  196. if t, ok := t.(failNower); ok {
  197. t.FailNow()
  198. } else {
  199. panic("test failed and t is missing `FailNow()`")
  200. }
  201. return false
  202. }
  203. // Fail reports a failure through
  204. func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
  205. if h, ok := t.(tHelper); ok {
  206. h.Helper()
  207. }
  208. content := []labeledContent{
  209. {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")},
  210. {"Error", failureMessage},
  211. }
  212. // Add test name if the Go version supports it
  213. if n, ok := t.(interface {
  214. Name() string
  215. }); ok {
  216. content = append(content, labeledContent{"Test", n.Name()})
  217. }
  218. message := messageFromMsgAndArgs(msgAndArgs...)
  219. if len(message) > 0 {
  220. content = append(content, labeledContent{"Messages", message})
  221. }
  222. t.Errorf("\n%s", ""+labeledOutput(content...))
  223. return false
  224. }
  225. type labeledContent struct {
  226. label string
  227. content string
  228. }
  229. // labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
  230. //
  231. // \t{{label}}:{{align_spaces}}\t{{content}}\n
  232. //
  233. // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
  234. // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
  235. // alignment is achieved, "\t{{content}}\n" is added for the output.
  236. //
  237. // If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line.
  238. func labeledOutput(content ...labeledContent) string {
  239. longestLabel := 0
  240. for _, v := range content {
  241. if len(v.label) > longestLabel {
  242. longestLabel = len(v.label)
  243. }
  244. }
  245. var output string
  246. for _, v := range content {
  247. output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
  248. }
  249. return output
  250. }
  251. // Implements asserts that an object is implemented by the specified interface.
  252. //
  253. // assert.Implements(t, (*MyInterface)(nil), new(MyObject))
  254. func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
  255. if h, ok := t.(tHelper); ok {
  256. h.Helper()
  257. }
  258. interfaceType := reflect.TypeOf(interfaceObject).Elem()
  259. if object == nil {
  260. return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...)
  261. }
  262. if !reflect.TypeOf(object).Implements(interfaceType) {
  263. return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
  264. }
  265. return true
  266. }
  267. // IsType asserts that the specified objects are of the same type.
  268. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
  269. if h, ok := t.(tHelper); ok {
  270. h.Helper()
  271. }
  272. if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
  273. return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
  274. }
  275. return true
  276. }
  277. // Equal asserts that two objects are equal.
  278. //
  279. // assert.Equal(t, 123, 123)
  280. //
  281. // Pointer variable equality is determined based on the equality of the
  282. // referenced values (as opposed to the memory addresses). Function equality
  283. // cannot be determined and will always fail.
  284. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  285. if h, ok := t.(tHelper); ok {
  286. h.Helper()
  287. }
  288. if err := validateEqualArgs(expected, actual); err != nil {
  289. return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)",
  290. expected, actual, err), msgAndArgs...)
  291. }
  292. if !ObjectsAreEqual(expected, actual) {
  293. diff := diff(expected, actual)
  294. expected, actual = formatUnequalValues(expected, actual)
  295. return Fail(t, fmt.Sprintf("Not equal: \n"+
  296. "expected: %s\n"+
  297. "actual : %s%s", expected, actual, diff), msgAndArgs...)
  298. }
  299. return true
  300. }
  301. // Same asserts that two pointers reference the same object.
  302. //
  303. // assert.Same(t, ptr1, ptr2)
  304. //
  305. // Both arguments must be pointer variables. Pointer variable sameness is
  306. // determined based on the equality of both type and value.
  307. func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  308. if h, ok := t.(tHelper); ok {
  309. h.Helper()
  310. }
  311. expectedPtr, actualPtr := reflect.ValueOf(expected), reflect.ValueOf(actual)
  312. if expectedPtr.Kind() != reflect.Ptr || actualPtr.Kind() != reflect.Ptr {
  313. return Fail(t, "Invalid operation: both arguments must be pointers", msgAndArgs...)
  314. }
  315. expectedType, actualType := reflect.TypeOf(expected), reflect.TypeOf(actual)
  316. if expectedType != actualType {
  317. return Fail(t, fmt.Sprintf("Pointer expected to be of type %v, but was %v",
  318. expectedType, actualType), msgAndArgs...)
  319. }
  320. if expected != actual {
  321. return Fail(t, fmt.Sprintf("Not same: \n"+
  322. "expected: %p %#v\n"+
  323. "actual : %p %#v", expected, expected, actual, actual), msgAndArgs...)
  324. }
  325. return true
  326. }
  327. // formatUnequalValues takes two values of arbitrary types and returns string
  328. // representations appropriate to be presented to the user.
  329. //
  330. // If the values are not of like type, the returned strings will be prefixed
  331. // with the type name, and the value will be enclosed in parenthesis similar
  332. // to a type conversion in the Go grammar.
  333. func formatUnequalValues(expected, actual interface{}) (e string, a string) {
  334. if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
  335. return fmt.Sprintf("%T(%#v)", expected, expected),
  336. fmt.Sprintf("%T(%#v)", actual, actual)
  337. }
  338. return fmt.Sprintf("%#v", expected),
  339. fmt.Sprintf("%#v", actual)
  340. }
  341. // EqualValues asserts that two objects are equal or convertable to the same types
  342. // and equal.
  343. //
  344. // assert.EqualValues(t, uint32(123), int32(123))
  345. func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  346. if h, ok := t.(tHelper); ok {
  347. h.Helper()
  348. }
  349. if !ObjectsAreEqualValues(expected, actual) {
  350. diff := diff(expected, actual)
  351. expected, actual = formatUnequalValues(expected, actual)
  352. return Fail(t, fmt.Sprintf("Not equal: \n"+
  353. "expected: %s\n"+
  354. "actual : %s%s", expected, actual, diff), msgAndArgs...)
  355. }
  356. return true
  357. }
  358. // Exactly asserts that two objects are equal in value and type.
  359. //
  360. // assert.Exactly(t, int32(123), int64(123))
  361. func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  362. if h, ok := t.(tHelper); ok {
  363. h.Helper()
  364. }
  365. aType := reflect.TypeOf(expected)
  366. bType := reflect.TypeOf(actual)
  367. if aType != bType {
  368. return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
  369. }
  370. return Equal(t, expected, actual, msgAndArgs...)
  371. }
  372. // NotNil asserts that the specified object is not nil.
  373. //
  374. // assert.NotNil(t, err)
  375. func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  376. if h, ok := t.(tHelper); ok {
  377. h.Helper()
  378. }
  379. if !isNil(object) {
  380. return true
  381. }
  382. return Fail(t, "Expected value not to be nil.", msgAndArgs...)
  383. }
  384. // containsKind checks if a specified kind in the slice of kinds.
  385. func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool {
  386. for i := 0; i < len(kinds); i++ {
  387. if kind == kinds[i] {
  388. return true
  389. }
  390. }
  391. return false
  392. }
  393. // isNil checks if a specified object is nil or not, without Failing.
  394. func isNil(object interface{}) bool {
  395. if object == nil {
  396. return true
  397. }
  398. value := reflect.ValueOf(object)
  399. kind := value.Kind()
  400. isNilableKind := containsKind(
  401. []reflect.Kind{
  402. reflect.Chan, reflect.Func,
  403. reflect.Interface, reflect.Map,
  404. reflect.Ptr, reflect.Slice},
  405. kind)
  406. if isNilableKind && value.IsNil() {
  407. return true
  408. }
  409. return false
  410. }
  411. // Nil asserts that the specified object is nil.
  412. //
  413. // assert.Nil(t, err)
  414. func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  415. if h, ok := t.(tHelper); ok {
  416. h.Helper()
  417. }
  418. if isNil(object) {
  419. return true
  420. }
  421. return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
  422. }
  423. // isEmpty gets whether the specified object is considered empty or not.
  424. func isEmpty(object interface{}) bool {
  425. // get nil case out of the way
  426. if object == nil {
  427. return true
  428. }
  429. objValue := reflect.ValueOf(object)
  430. switch objValue.Kind() {
  431. // collection types are empty when they have no element
  432. case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
  433. return objValue.Len() == 0
  434. // pointers are empty if nil or if the value they point to is empty
  435. case reflect.Ptr:
  436. if objValue.IsNil() {
  437. return true
  438. }
  439. deref := objValue.Elem().Interface()
  440. return isEmpty(deref)
  441. // for all other types, compare against the zero value
  442. default:
  443. zero := reflect.Zero(objValue.Type())
  444. return reflect.DeepEqual(object, zero.Interface())
  445. }
  446. }
  447. // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
  448. // a slice or a channel with len == 0.
  449. //
  450. // assert.Empty(t, obj)
  451. func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  452. if h, ok := t.(tHelper); ok {
  453. h.Helper()
  454. }
  455. pass := isEmpty(object)
  456. if !pass {
  457. Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
  458. }
  459. return pass
  460. }
  461. // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
  462. // a slice or a channel with len == 0.
  463. //
  464. // if assert.NotEmpty(t, obj) {
  465. // assert.Equal(t, "two", obj[1])
  466. // }
  467. func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  468. if h, ok := t.(tHelper); ok {
  469. h.Helper()
  470. }
  471. pass := !isEmpty(object)
  472. if !pass {
  473. Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
  474. }
  475. return pass
  476. }
  477. // getLen try to get length of object.
  478. // return (false, 0) if impossible.
  479. func getLen(x interface{}) (ok bool, length int) {
  480. v := reflect.ValueOf(x)
  481. defer func() {
  482. if e := recover(); e != nil {
  483. ok = false
  484. }
  485. }()
  486. return true, v.Len()
  487. }
  488. // Len asserts that the specified object has specific length.
  489. // Len also fails if the object has a type that len() not accept.
  490. //
  491. // assert.Len(t, mySlice, 3)
  492. func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
  493. if h, ok := t.(tHelper); ok {
  494. h.Helper()
  495. }
  496. ok, l := getLen(object)
  497. if !ok {
  498. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
  499. }
  500. if l != length {
  501. return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
  502. }
  503. return true
  504. }
  505. // True asserts that the specified value is true.
  506. //
  507. // assert.True(t, myBool)
  508. func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
  509. if h, ok := t.(tHelper); ok {
  510. h.Helper()
  511. }
  512. if h, ok := t.(interface {
  513. Helper()
  514. }); ok {
  515. h.Helper()
  516. }
  517. if value != true {
  518. return Fail(t, "Should be true", msgAndArgs...)
  519. }
  520. return true
  521. }
  522. // False asserts that the specified value is false.
  523. //
  524. // assert.False(t, myBool)
  525. func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
  526. if h, ok := t.(tHelper); ok {
  527. h.Helper()
  528. }
  529. if value != false {
  530. return Fail(t, "Should be false", msgAndArgs...)
  531. }
  532. return true
  533. }
  534. // NotEqual asserts that the specified values are NOT equal.
  535. //
  536. // assert.NotEqual(t, obj1, obj2)
  537. //
  538. // Pointer variable equality is determined based on the equality of the
  539. // referenced values (as opposed to the memory addresses).
  540. func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  541. if h, ok := t.(tHelper); ok {
  542. h.Helper()
  543. }
  544. if err := validateEqualArgs(expected, actual); err != nil {
  545. return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
  546. expected, actual, err), msgAndArgs...)
  547. }
  548. if ObjectsAreEqual(expected, actual) {
  549. return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
  550. }
  551. return true
  552. }
  553. // containsElement try loop over the list check if the list includes the element.
  554. // return (false, false) if impossible.
  555. // return (true, false) if element was not found.
  556. // return (true, true) if element was found.
  557. func includeElement(list interface{}, element interface{}) (ok, found bool) {
  558. listValue := reflect.ValueOf(list)
  559. listKind := reflect.TypeOf(list).Kind()
  560. defer func() {
  561. if e := recover(); e != nil {
  562. ok = false
  563. found = false
  564. }
  565. }()
  566. if listKind == reflect.String {
  567. elementValue := reflect.ValueOf(element)
  568. return true, strings.Contains(listValue.String(), elementValue.String())
  569. }
  570. if listKind == reflect.Map {
  571. mapKeys := listValue.MapKeys()
  572. for i := 0; i < len(mapKeys); i++ {
  573. if ObjectsAreEqual(mapKeys[i].Interface(), element) {
  574. return true, true
  575. }
  576. }
  577. return true, false
  578. }
  579. for i := 0; i < listValue.Len(); i++ {
  580. if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
  581. return true, true
  582. }
  583. }
  584. return true, false
  585. }
  586. // Contains asserts that the specified string, list(array, slice...) or map contains the
  587. // specified substring or element.
  588. //
  589. // assert.Contains(t, "Hello World", "World")
  590. // assert.Contains(t, ["Hello", "World"], "World")
  591. // assert.Contains(t, {"Hello": "World"}, "Hello")
  592. func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
  593. if h, ok := t.(tHelper); ok {
  594. h.Helper()
  595. }
  596. ok, found := includeElement(s, contains)
  597. if !ok {
  598. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
  599. }
  600. if !found {
  601. return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...)
  602. }
  603. return true
  604. }
  605. // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
  606. // specified substring or element.
  607. //
  608. // assert.NotContains(t, "Hello World", "Earth")
  609. // assert.NotContains(t, ["Hello", "World"], "Earth")
  610. // assert.NotContains(t, {"Hello": "World"}, "Earth")
  611. func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
  612. if h, ok := t.(tHelper); ok {
  613. h.Helper()
  614. }
  615. ok, found := includeElement(s, contains)
  616. if !ok {
  617. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
  618. }
  619. if found {
  620. return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
  621. }
  622. return true
  623. }
  624. // Subset asserts that the specified list(array, slice...) contains all
  625. // elements given in the specified subset(array, slice...).
  626. //
  627. // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
  628. func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
  629. if h, ok := t.(tHelper); ok {
  630. h.Helper()
  631. }
  632. if subset == nil {
  633. return true // we consider nil to be equal to the nil set
  634. }
  635. subsetValue := reflect.ValueOf(subset)
  636. defer func() {
  637. if e := recover(); e != nil {
  638. ok = false
  639. }
  640. }()
  641. listKind := reflect.TypeOf(list).Kind()
  642. subsetKind := reflect.TypeOf(subset).Kind()
  643. if listKind != reflect.Array && listKind != reflect.Slice {
  644. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
  645. }
  646. if subsetKind != reflect.Array && subsetKind != reflect.Slice {
  647. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
  648. }
  649. for i := 0; i < subsetValue.Len(); i++ {
  650. element := subsetValue.Index(i).Interface()
  651. ok, found := includeElement(list, element)
  652. if !ok {
  653. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
  654. }
  655. if !found {
  656. return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...)
  657. }
  658. }
  659. return true
  660. }
  661. // NotSubset asserts that the specified list(array, slice...) contains not all
  662. // elements given in the specified subset(array, slice...).
  663. //
  664. // assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
  665. func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
  666. if h, ok := t.(tHelper); ok {
  667. h.Helper()
  668. }
  669. if subset == nil {
  670. return Fail(t, fmt.Sprintf("nil is the empty set which is a subset of every set"), msgAndArgs...)
  671. }
  672. subsetValue := reflect.ValueOf(subset)
  673. defer func() {
  674. if e := recover(); e != nil {
  675. ok = false
  676. }
  677. }()
  678. listKind := reflect.TypeOf(list).Kind()
  679. subsetKind := reflect.TypeOf(subset).Kind()
  680. if listKind != reflect.Array && listKind != reflect.Slice {
  681. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
  682. }
  683. if subsetKind != reflect.Array && subsetKind != reflect.Slice {
  684. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
  685. }
  686. for i := 0; i < subsetValue.Len(); i++ {
  687. element := subsetValue.Index(i).Interface()
  688. ok, found := includeElement(list, element)
  689. if !ok {
  690. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
  691. }
  692. if !found {
  693. return true
  694. }
  695. }
  696. return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
  697. }
  698. // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
  699. // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
  700. // the number of appearances of each of them in both lists should match.
  701. //
  702. // assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
  703. func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
  704. if h, ok := t.(tHelper); ok {
  705. h.Helper()
  706. }
  707. if isEmpty(listA) && isEmpty(listB) {
  708. return true
  709. }
  710. aKind := reflect.TypeOf(listA).Kind()
  711. bKind := reflect.TypeOf(listB).Kind()
  712. if aKind != reflect.Array && aKind != reflect.Slice {
  713. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listA, aKind), msgAndArgs...)
  714. }
  715. if bKind != reflect.Array && bKind != reflect.Slice {
  716. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listB, bKind), msgAndArgs...)
  717. }
  718. aValue := reflect.ValueOf(listA)
  719. bValue := reflect.ValueOf(listB)
  720. aLen := aValue.Len()
  721. bLen := bValue.Len()
  722. if aLen != bLen {
  723. return Fail(t, fmt.Sprintf("lengths don't match: %d != %d", aLen, bLen), msgAndArgs...)
  724. }
  725. // Mark indexes in bValue that we already used
  726. visited := make([]bool, bLen)
  727. for i := 0; i < aLen; i++ {
  728. element := aValue.Index(i).Interface()
  729. found := false
  730. for j := 0; j < bLen; j++ {
  731. if visited[j] {
  732. continue
  733. }
  734. if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
  735. visited[j] = true
  736. found = true
  737. break
  738. }
  739. }
  740. if !found {
  741. return Fail(t, fmt.Sprintf("element %s appears more times in %s than in %s", element, aValue, bValue), msgAndArgs...)
  742. }
  743. }
  744. return true
  745. }
  746. // Condition uses a Comparison to assert a complex condition.
  747. func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
  748. if h, ok := t.(tHelper); ok {
  749. h.Helper()
  750. }
  751. result := comp()
  752. if !result {
  753. Fail(t, "Condition failed!", msgAndArgs...)
  754. }
  755. return result
  756. }
  757. // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
  758. // methods, and represents a simple func that takes no arguments, and returns nothing.
  759. type PanicTestFunc func()
  760. // didPanic returns true if the function passed to it panics. Otherwise, it returns false.
  761. func didPanic(f PanicTestFunc) (bool, interface{}) {
  762. didPanic := false
  763. var message interface{}
  764. func() {
  765. defer func() {
  766. if message = recover(); message != nil {
  767. didPanic = true
  768. }
  769. }()
  770. // call the target function
  771. f()
  772. }()
  773. return didPanic, message
  774. }
  775. // Panics asserts that the code inside the specified PanicTestFunc panics.
  776. //
  777. // assert.Panics(t, func(){ GoCrazy() })
  778. func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  779. if h, ok := t.(tHelper); ok {
  780. h.Helper()
  781. }
  782. if funcDidPanic, panicValue := didPanic(f); !funcDidPanic {
  783. return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
  784. }
  785. return true
  786. }
  787. // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
  788. // the recovered panic value equals the expected panic value.
  789. //
  790. // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
  791. func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  792. if h, ok := t.(tHelper); ok {
  793. h.Helper()
  794. }
  795. funcDidPanic, panicValue := didPanic(f)
  796. if !funcDidPanic {
  797. return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
  798. }
  799. if panicValue != expected {
  800. return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v", f, expected, panicValue), msgAndArgs...)
  801. }
  802. return true
  803. }
  804. // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
  805. //
  806. // assert.NotPanics(t, func(){ RemainCalm() })
  807. func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  808. if h, ok := t.(tHelper); ok {
  809. h.Helper()
  810. }
  811. if funcDidPanic, panicValue := didPanic(f); funcDidPanic {
  812. return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v", f, panicValue), msgAndArgs...)
  813. }
  814. return true
  815. }
  816. // WithinDuration asserts that the two times are within duration delta of each other.
  817. //
  818. // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
  819. func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
  820. if h, ok := t.(tHelper); ok {
  821. h.Helper()
  822. }
  823. dt := expected.Sub(actual)
  824. if dt < -delta || dt > delta {
  825. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
  826. }
  827. return true
  828. }
  829. func toFloat(x interface{}) (float64, bool) {
  830. var xf float64
  831. xok := true
  832. switch xn := x.(type) {
  833. case uint8:
  834. xf = float64(xn)
  835. case uint16:
  836. xf = float64(xn)
  837. case uint32:
  838. xf = float64(xn)
  839. case uint64:
  840. xf = float64(xn)
  841. case int:
  842. xf = float64(xn)
  843. case int8:
  844. xf = float64(xn)
  845. case int16:
  846. xf = float64(xn)
  847. case int32:
  848. xf = float64(xn)
  849. case int64:
  850. xf = float64(xn)
  851. case float32:
  852. xf = float64(xn)
  853. case float64:
  854. xf = float64(xn)
  855. case time.Duration:
  856. xf = float64(xn)
  857. default:
  858. xok = false
  859. }
  860. return xf, xok
  861. }
  862. // InDelta asserts that the two numerals are within delta of each other.
  863. //
  864. // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
  865. func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  866. if h, ok := t.(tHelper); ok {
  867. h.Helper()
  868. }
  869. af, aok := toFloat(expected)
  870. bf, bok := toFloat(actual)
  871. if !aok || !bok {
  872. return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
  873. }
  874. if math.IsNaN(af) {
  875. return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...)
  876. }
  877. if math.IsNaN(bf) {
  878. return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
  879. }
  880. dt := af - bf
  881. if dt < -delta || dt > delta {
  882. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
  883. }
  884. return true
  885. }
  886. // InDeltaSlice is the same as InDelta, except it compares two slices.
  887. func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  888. if h, ok := t.(tHelper); ok {
  889. h.Helper()
  890. }
  891. if expected == nil || actual == nil ||
  892. reflect.TypeOf(actual).Kind() != reflect.Slice ||
  893. reflect.TypeOf(expected).Kind() != reflect.Slice {
  894. return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
  895. }
  896. actualSlice := reflect.ValueOf(actual)
  897. expectedSlice := reflect.ValueOf(expected)
  898. for i := 0; i < actualSlice.Len(); i++ {
  899. result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
  900. if !result {
  901. return result
  902. }
  903. }
  904. return true
  905. }
  906. // InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
  907. func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  908. if h, ok := t.(tHelper); ok {
  909. h.Helper()
  910. }
  911. if expected == nil || actual == nil ||
  912. reflect.TypeOf(actual).Kind() != reflect.Map ||
  913. reflect.TypeOf(expected).Kind() != reflect.Map {
  914. return Fail(t, "Arguments must be maps", msgAndArgs...)
  915. }
  916. expectedMap := reflect.ValueOf(expected)
  917. actualMap := reflect.ValueOf(actual)
  918. if expectedMap.Len() != actualMap.Len() {
  919. return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
  920. }
  921. for _, k := range expectedMap.MapKeys() {
  922. ev := expectedMap.MapIndex(k)
  923. av := actualMap.MapIndex(k)
  924. if !ev.IsValid() {
  925. return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
  926. }
  927. if !av.IsValid() {
  928. return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
  929. }
  930. if !InDelta(
  931. t,
  932. ev.Interface(),
  933. av.Interface(),
  934. delta,
  935. msgAndArgs...,
  936. ) {
  937. return false
  938. }
  939. }
  940. return true
  941. }
  942. func calcRelativeError(expected, actual interface{}) (float64, error) {
  943. af, aok := toFloat(expected)
  944. if !aok {
  945. return 0, fmt.Errorf("expected value %q cannot be converted to float", expected)
  946. }
  947. if af == 0 {
  948. return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
  949. }
  950. bf, bok := toFloat(actual)
  951. if !bok {
  952. return 0, fmt.Errorf("actual value %q cannot be converted to float", actual)
  953. }
  954. return math.Abs(af-bf) / math.Abs(af), nil
  955. }
  956. // InEpsilon asserts that expected and actual have a relative error less than epsilon
  957. func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
  958. if h, ok := t.(tHelper); ok {
  959. h.Helper()
  960. }
  961. actualEpsilon, err := calcRelativeError(expected, actual)
  962. if err != nil {
  963. return Fail(t, err.Error(), msgAndArgs...)
  964. }
  965. if actualEpsilon > epsilon {
  966. return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
  967. " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
  968. }
  969. return true
  970. }
  971. // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
  972. func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
  973. if h, ok := t.(tHelper); ok {
  974. h.Helper()
  975. }
  976. if expected == nil || actual == nil ||
  977. reflect.TypeOf(actual).Kind() != reflect.Slice ||
  978. reflect.TypeOf(expected).Kind() != reflect.Slice {
  979. return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
  980. }
  981. actualSlice := reflect.ValueOf(actual)
  982. expectedSlice := reflect.ValueOf(expected)
  983. for i := 0; i < actualSlice.Len(); i++ {
  984. result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
  985. if !result {
  986. return result
  987. }
  988. }
  989. return true
  990. }
  991. /*
  992. Errors
  993. */
  994. // NoError asserts that a function returned no error (i.e. `nil`).
  995. //
  996. // actualObj, err := SomeFunction()
  997. // if assert.NoError(t, err) {
  998. // assert.Equal(t, expectedObj, actualObj)
  999. // }
  1000. func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
  1001. if h, ok := t.(tHelper); ok {
  1002. h.Helper()
  1003. }
  1004. if err != nil {
  1005. return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
  1006. }
  1007. return true
  1008. }
  1009. // Error asserts that a function returned an error (i.e. not `nil`).
  1010. //
  1011. // actualObj, err := SomeFunction()
  1012. // if assert.Error(t, err) {
  1013. // assert.Equal(t, expectedError, err)
  1014. // }
  1015. func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
  1016. if h, ok := t.(tHelper); ok {
  1017. h.Helper()
  1018. }
  1019. if err == nil {
  1020. return Fail(t, "An error is expected but got nil.", msgAndArgs...)
  1021. }
  1022. return true
  1023. }
  1024. // EqualError asserts that a function returned an error (i.e. not `nil`)
  1025. // and that it is equal to the provided error.
  1026. //
  1027. // actualObj, err := SomeFunction()
  1028. // assert.EqualError(t, err, expectedErrorString)
  1029. func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
  1030. if h, ok := t.(tHelper); ok {
  1031. h.Helper()
  1032. }
  1033. if !Error(t, theError, msgAndArgs...) {
  1034. return false
  1035. }
  1036. expected := errString
  1037. actual := theError.Error()
  1038. // don't need to use deep equals here, we know they are both strings
  1039. if expected != actual {
  1040. return Fail(t, fmt.Sprintf("Error message not equal:\n"+
  1041. "expected: %q\n"+
  1042. "actual : %q", expected, actual), msgAndArgs...)
  1043. }
  1044. return true
  1045. }
  1046. // matchRegexp return true if a specified regexp matches a string.
  1047. func matchRegexp(rx interface{}, str interface{}) bool {
  1048. var r *regexp.Regexp
  1049. if rr, ok := rx.(*regexp.Regexp); ok {
  1050. r = rr
  1051. } else {
  1052. r = regexp.MustCompile(fmt.Sprint(rx))
  1053. }
  1054. return (r.FindStringIndex(fmt.Sprint(str)) != nil)
  1055. }
  1056. // Regexp asserts that a specified regexp matches a string.
  1057. //
  1058. // assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
  1059. // assert.Regexp(t, "start...$", "it's not starting")
  1060. func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
  1061. if h, ok := t.(tHelper); ok {
  1062. h.Helper()
  1063. }
  1064. match := matchRegexp(rx, str)
  1065. if !match {
  1066. Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
  1067. }
  1068. return match
  1069. }
  1070. // NotRegexp asserts that a specified regexp does not match a string.
  1071. //
  1072. // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
  1073. // assert.NotRegexp(t, "^start", "it's not starting")
  1074. func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
  1075. if h, ok := t.(tHelper); ok {
  1076. h.Helper()
  1077. }
  1078. match := matchRegexp(rx, str)
  1079. if match {
  1080. Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
  1081. }
  1082. return !match
  1083. }
  1084. // Zero asserts that i is the zero value for its type.
  1085. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
  1086. if h, ok := t.(tHelper); ok {
  1087. h.Helper()
  1088. }
  1089. if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
  1090. return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
  1091. }
  1092. return true
  1093. }
  1094. // NotZero asserts that i is not the zero value for its type.
  1095. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
  1096. if h, ok := t.(tHelper); ok {
  1097. h.Helper()
  1098. }
  1099. if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
  1100. return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
  1101. }
  1102. return true
  1103. }
  1104. // FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.
  1105. func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1106. if h, ok := t.(tHelper); ok {
  1107. h.Helper()
  1108. }
  1109. info, err := os.Lstat(path)
  1110. if err != nil {
  1111. if os.IsNotExist(err) {
  1112. return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
  1113. }
  1114. return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
  1115. }
  1116. if info.IsDir() {
  1117. return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
  1118. }
  1119. return true
  1120. }
  1121. // DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists.
  1122. func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1123. if h, ok := t.(tHelper); ok {
  1124. h.Helper()
  1125. }
  1126. info, err := os.Lstat(path)
  1127. if err != nil {
  1128. if os.IsNotExist(err) {
  1129. return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
  1130. }
  1131. return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
  1132. }
  1133. if !info.IsDir() {
  1134. return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
  1135. }
  1136. return true
  1137. }
  1138. // JSONEq asserts that two JSON strings are equivalent.
  1139. //
  1140. // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
  1141. func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
  1142. if h, ok := t.(tHelper); ok {
  1143. h.Helper()
  1144. }
  1145. var expectedJSONAsInterface, actualJSONAsInterface interface{}
  1146. if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
  1147. return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
  1148. }
  1149. if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
  1150. return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
  1151. }
  1152. return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
  1153. }
  1154. // YAMLEq asserts that two YAML strings are equivalent.
  1155. func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
  1156. if h, ok := t.(tHelper); ok {
  1157. h.Helper()
  1158. }
  1159. var expectedYAMLAsInterface, actualYAMLAsInterface interface{}
  1160. if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil {
  1161. return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...)
  1162. }
  1163. if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil {
  1164. return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...)
  1165. }
  1166. return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...)
  1167. }
  1168. func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
  1169. t := reflect.TypeOf(v)
  1170. k := t.Kind()
  1171. if k == reflect.Ptr {
  1172. t = t.Elem()
  1173. k = t.Kind()
  1174. }
  1175. return t, k
  1176. }
  1177. // diff returns a diff of both values as long as both are of the same type and
  1178. // are a struct, map, slice, array or string. Otherwise it returns an empty string.
  1179. func diff(expected interface{}, actual interface{}) string {
  1180. if expected == nil || actual == nil {
  1181. return ""
  1182. }
  1183. et, ek := typeAndKind(expected)
  1184. at, _ := typeAndKind(actual)
  1185. if et != at {
  1186. return ""
  1187. }
  1188. if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
  1189. return ""
  1190. }
  1191. var e, a string
  1192. if et != reflect.TypeOf("") {
  1193. e = spewConfig.Sdump(expected)
  1194. a = spewConfig.Sdump(actual)
  1195. } else {
  1196. e = reflect.ValueOf(expected).String()
  1197. a = reflect.ValueOf(actual).String()
  1198. }
  1199. diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
  1200. A: difflib.SplitLines(e),
  1201. B: difflib.SplitLines(a),
  1202. FromFile: "Expected",
  1203. FromDate: "",
  1204. ToFile: "Actual",
  1205. ToDate: "",
  1206. Context: 1,
  1207. })
  1208. return "\n\nDiff:\n" + diff
  1209. }
  1210. // validateEqualArgs checks whether provided arguments can be safely used in the
  1211. // Equal/NotEqual functions.
  1212. func validateEqualArgs(expected, actual interface{}) error {
  1213. if isFunction(expected) || isFunction(actual) {
  1214. return errors.New("cannot take func type as argument")
  1215. }
  1216. return nil
  1217. }
  1218. func isFunction(arg interface{}) bool {
  1219. if arg == nil {
  1220. return false
  1221. }
  1222. return reflect.TypeOf(arg).Kind() == reflect.Func
  1223. }
  1224. var spewConfig = spew.ConfigState{
  1225. Indent: " ",
  1226. DisablePointerAddresses: true,
  1227. DisableCapacities: true,
  1228. SortKeys: true,
  1229. }
  1230. type tHelper interface {
  1231. Helper()
  1232. }
  1233. // Eventually asserts that given condition will be met in waitFor time,
  1234. // periodically checking target function each tick.
  1235. //
  1236. // assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
  1237. func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
  1238. if h, ok := t.(tHelper); ok {
  1239. h.Helper()
  1240. }
  1241. timer := time.NewTimer(waitFor)
  1242. ticker := time.NewTicker(tick)
  1243. checkPassed := make(chan bool)
  1244. defer timer.Stop()
  1245. defer ticker.Stop()
  1246. defer close(checkPassed)
  1247. for {
  1248. select {
  1249. case <-timer.C:
  1250. return Fail(t, "Condition never satisfied", msgAndArgs...)
  1251. case result := <-checkPassed:
  1252. if result {
  1253. return true
  1254. }
  1255. case <-ticker.C:
  1256. go func() {
  1257. checkPassed <- condition()
  1258. }()
  1259. }
  1260. }
  1261. }
上海开阖软件有限公司 沪ICP备12045867号-1