1
0

assertions.go 30 KB

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