assertions.go 36 KB

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