assertions.go 34 KB

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