assertions.go 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054
  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. "runtime/debug"
  14. "strings"
  15. "time"
  16. "unicode"
  17. "unicode/utf8"
  18. "github.com/davecgh/go-spew/spew"
  19. "github.com/pmezard/go-difflib/difflib"
  20. yaml "gopkg.in/yaml.v3"
  21. )
  22. //go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
  23. // TestingT is an interface wrapper around *testing.T
  24. type TestingT interface {
  25. Errorf(format string, args ...interface{})
  26. }
  27. // ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
  28. // for table driven tests.
  29. type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
  30. // ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
  31. // for table driven tests.
  32. type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
  33. // BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
  34. // for table driven tests.
  35. type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
  36. // ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
  37. // for table driven tests.
  38. type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
  39. // Comparison is a custom function that returns true on success and false on failure
  40. type Comparison func() (success bool)
  41. /*
  42. Helper functions
  43. */
  44. // ObjectsAreEqual determines if two objects are considered equal.
  45. //
  46. // This function does no assertion of any kind.
  47. func ObjectsAreEqual(expected, actual interface{}) bool {
  48. if expected == nil || actual == nil {
  49. return expected == actual
  50. }
  51. exp, ok := expected.([]byte)
  52. if !ok {
  53. return reflect.DeepEqual(expected, actual)
  54. }
  55. act, ok := actual.([]byte)
  56. if !ok {
  57. return false
  58. }
  59. if exp == nil || act == nil {
  60. return exp == nil && act == nil
  61. }
  62. return bytes.Equal(exp, act)
  63. }
  64. // copyExportedFields iterates downward through nested data structures and creates a copy
  65. // that only contains the exported struct fields.
  66. func copyExportedFields(expected interface{}) interface{} {
  67. if isNil(expected) {
  68. return expected
  69. }
  70. expectedType := reflect.TypeOf(expected)
  71. expectedKind := expectedType.Kind()
  72. expectedValue := reflect.ValueOf(expected)
  73. switch expectedKind {
  74. case reflect.Struct:
  75. result := reflect.New(expectedType).Elem()
  76. for i := 0; i < expectedType.NumField(); i++ {
  77. field := expectedType.Field(i)
  78. isExported := field.IsExported()
  79. if isExported {
  80. fieldValue := expectedValue.Field(i)
  81. if isNil(fieldValue) || isNil(fieldValue.Interface()) {
  82. continue
  83. }
  84. newValue := copyExportedFields(fieldValue.Interface())
  85. result.Field(i).Set(reflect.ValueOf(newValue))
  86. }
  87. }
  88. return result.Interface()
  89. case reflect.Ptr:
  90. result := reflect.New(expectedType.Elem())
  91. unexportedRemoved := copyExportedFields(expectedValue.Elem().Interface())
  92. result.Elem().Set(reflect.ValueOf(unexportedRemoved))
  93. return result.Interface()
  94. case reflect.Array, reflect.Slice:
  95. result := reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len())
  96. for i := 0; i < expectedValue.Len(); i++ {
  97. index := expectedValue.Index(i)
  98. if isNil(index) {
  99. continue
  100. }
  101. unexportedRemoved := copyExportedFields(index.Interface())
  102. result.Index(i).Set(reflect.ValueOf(unexportedRemoved))
  103. }
  104. return result.Interface()
  105. case reflect.Map:
  106. result := reflect.MakeMap(expectedType)
  107. for _, k := range expectedValue.MapKeys() {
  108. index := expectedValue.MapIndex(k)
  109. unexportedRemoved := copyExportedFields(index.Interface())
  110. result.SetMapIndex(k, reflect.ValueOf(unexportedRemoved))
  111. }
  112. return result.Interface()
  113. default:
  114. return expected
  115. }
  116. }
  117. // ObjectsExportedFieldsAreEqual determines if the exported (public) fields of two objects are
  118. // considered equal. This comparison of only exported fields is applied recursively to nested data
  119. // structures.
  120. //
  121. // This function does no assertion of any kind.
  122. func ObjectsExportedFieldsAreEqual(expected, actual interface{}) bool {
  123. expectedCleaned := copyExportedFields(expected)
  124. actualCleaned := copyExportedFields(actual)
  125. return ObjectsAreEqualValues(expectedCleaned, actualCleaned)
  126. }
  127. // ObjectsAreEqualValues gets whether two objects are equal, or if their
  128. // values are equal.
  129. func ObjectsAreEqualValues(expected, actual interface{}) bool {
  130. if ObjectsAreEqual(expected, actual) {
  131. return true
  132. }
  133. actualType := reflect.TypeOf(actual)
  134. if actualType == nil {
  135. return false
  136. }
  137. expectedValue := reflect.ValueOf(expected)
  138. if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
  139. // Attempt comparison after type conversion
  140. return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
  141. }
  142. return false
  143. }
  144. /* CallerInfo is necessary because the assert functions use the testing object
  145. internally, causing it to print the file:line of the assert method, rather than where
  146. the problem actually occurred in calling code.*/
  147. // CallerInfo returns an array of strings containing the file and line number
  148. // of each stack frame leading from the current test to the assert call that
  149. // failed.
  150. func CallerInfo() []string {
  151. var pc uintptr
  152. var ok bool
  153. var file string
  154. var line int
  155. var name string
  156. callers := []string{}
  157. for i := 0; ; i++ {
  158. pc, file, line, ok = runtime.Caller(i)
  159. if !ok {
  160. // The breaks below failed to terminate the loop, and we ran off the
  161. // end of the call stack.
  162. break
  163. }
  164. // This is a huge edge case, but it will panic if this is the case, see #180
  165. if file == "<autogenerated>" {
  166. break
  167. }
  168. f := runtime.FuncForPC(pc)
  169. if f == nil {
  170. break
  171. }
  172. name = f.Name()
  173. // testing.tRunner is the standard library function that calls
  174. // tests. Subtests are called directly by tRunner, without going through
  175. // the Test/Benchmark/Example function that contains the t.Run calls, so
  176. // with subtests we should break when we hit tRunner, without adding it
  177. // to the list of callers.
  178. if name == "testing.tRunner" {
  179. break
  180. }
  181. parts := strings.Split(file, "/")
  182. if len(parts) > 1 {
  183. filename := parts[len(parts)-1]
  184. dir := parts[len(parts)-2]
  185. if (dir != "assert" && dir != "mock" && dir != "require") || filename == "mock_test.go" {
  186. callers = append(callers, fmt.Sprintf("%s:%d", file, line))
  187. }
  188. }
  189. // Drop the package
  190. segments := strings.Split(name, ".")
  191. name = segments[len(segments)-1]
  192. if isTest(name, "Test") ||
  193. isTest(name, "Benchmark") ||
  194. isTest(name, "Example") {
  195. break
  196. }
  197. }
  198. return callers
  199. }
  200. // Stolen from the `go test` tool.
  201. // isTest tells whether name looks like a test (or benchmark, according to prefix).
  202. // It is a Test (say) if there is a character after Test that is not a lower-case letter.
  203. // We don't want TesticularCancer.
  204. func isTest(name, prefix string) bool {
  205. if !strings.HasPrefix(name, prefix) {
  206. return false
  207. }
  208. if len(name) == len(prefix) { // "Test" is ok
  209. return true
  210. }
  211. r, _ := utf8.DecodeRuneInString(name[len(prefix):])
  212. return !unicode.IsLower(r)
  213. }
  214. func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
  215. if len(msgAndArgs) == 0 || msgAndArgs == nil {
  216. return ""
  217. }
  218. if len(msgAndArgs) == 1 {
  219. msg := msgAndArgs[0]
  220. if msgAsStr, ok := msg.(string); ok {
  221. return msgAsStr
  222. }
  223. return fmt.Sprintf("%+v", msg)
  224. }
  225. if len(msgAndArgs) > 1 {
  226. return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
  227. }
  228. return ""
  229. }
  230. // Aligns the provided message so that all lines after the first line start at the same location as the first line.
  231. // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
  232. // The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
  233. // basis on which the alignment occurs).
  234. func indentMessageLines(message string, longestLabelLen int) string {
  235. outBuf := new(bytes.Buffer)
  236. for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
  237. // no need to align first line because it starts at the correct location (after the label)
  238. if i != 0 {
  239. // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
  240. outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
  241. }
  242. outBuf.WriteString(scanner.Text())
  243. }
  244. return outBuf.String()
  245. }
  246. type failNower interface {
  247. FailNow()
  248. }
  249. // FailNow fails test
  250. func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
  251. if h, ok := t.(tHelper); ok {
  252. h.Helper()
  253. }
  254. Fail(t, failureMessage, msgAndArgs...)
  255. // We cannot extend TestingT with FailNow() and
  256. // maintain backwards compatibility, so we fallback
  257. // to panicking when FailNow is not available in
  258. // TestingT.
  259. // See issue #263
  260. if t, ok := t.(failNower); ok {
  261. t.FailNow()
  262. } else {
  263. panic("test failed and t is missing `FailNow()`")
  264. }
  265. return false
  266. }
  267. // Fail reports a failure through
  268. func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
  269. if h, ok := t.(tHelper); ok {
  270. h.Helper()
  271. }
  272. content := []labeledContent{
  273. {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")},
  274. {"Error", failureMessage},
  275. }
  276. // Add test name if the Go version supports it
  277. if n, ok := t.(interface {
  278. Name() string
  279. }); ok {
  280. content = append(content, labeledContent{"Test", n.Name()})
  281. }
  282. message := messageFromMsgAndArgs(msgAndArgs...)
  283. if len(message) > 0 {
  284. content = append(content, labeledContent{"Messages", message})
  285. }
  286. t.Errorf("\n%s", ""+labeledOutput(content...))
  287. return false
  288. }
  289. type labeledContent struct {
  290. label string
  291. content string
  292. }
  293. // labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
  294. //
  295. // \t{{label}}:{{align_spaces}}\t{{content}}\n
  296. //
  297. // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
  298. // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
  299. // alignment is achieved, "\t{{content}}\n" is added for the output.
  300. //
  301. // 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.
  302. func labeledOutput(content ...labeledContent) string {
  303. longestLabel := 0
  304. for _, v := range content {
  305. if len(v.label) > longestLabel {
  306. longestLabel = len(v.label)
  307. }
  308. }
  309. var output string
  310. for _, v := range content {
  311. output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
  312. }
  313. return output
  314. }
  315. // Implements asserts that an object is implemented by the specified interface.
  316. //
  317. // assert.Implements(t, (*MyInterface)(nil), new(MyObject))
  318. func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
  319. if h, ok := t.(tHelper); ok {
  320. h.Helper()
  321. }
  322. interfaceType := reflect.TypeOf(interfaceObject).Elem()
  323. if object == nil {
  324. return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...)
  325. }
  326. if !reflect.TypeOf(object).Implements(interfaceType) {
  327. return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
  328. }
  329. return true
  330. }
  331. // IsType asserts that the specified objects are of the same type.
  332. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
  333. if h, ok := t.(tHelper); ok {
  334. h.Helper()
  335. }
  336. if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
  337. return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
  338. }
  339. return true
  340. }
  341. // Equal asserts that two objects are equal.
  342. //
  343. // assert.Equal(t, 123, 123)
  344. //
  345. // Pointer variable equality is determined based on the equality of the
  346. // referenced values (as opposed to the memory addresses). Function equality
  347. // cannot be determined and will always fail.
  348. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  349. if h, ok := t.(tHelper); ok {
  350. h.Helper()
  351. }
  352. if err := validateEqualArgs(expected, actual); err != nil {
  353. return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)",
  354. expected, actual, err), msgAndArgs...)
  355. }
  356. if !ObjectsAreEqual(expected, actual) {
  357. diff := diff(expected, actual)
  358. expected, actual = formatUnequalValues(expected, actual)
  359. return Fail(t, fmt.Sprintf("Not equal: \n"+
  360. "expected: %s\n"+
  361. "actual : %s%s", expected, actual, diff), msgAndArgs...)
  362. }
  363. return true
  364. }
  365. // validateEqualArgs checks whether provided arguments can be safely used in the
  366. // Equal/NotEqual functions.
  367. func validateEqualArgs(expected, actual interface{}) error {
  368. if expected == nil && actual == nil {
  369. return nil
  370. }
  371. if isFunction(expected) || isFunction(actual) {
  372. return errors.New("cannot take func type as argument")
  373. }
  374. return nil
  375. }
  376. // Same asserts that two pointers reference the same object.
  377. //
  378. // assert.Same(t, ptr1, ptr2)
  379. //
  380. // Both arguments must be pointer variables. Pointer variable sameness is
  381. // determined based on the equality of both type and value.
  382. func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  383. if h, ok := t.(tHelper); ok {
  384. h.Helper()
  385. }
  386. if !samePointers(expected, actual) {
  387. return Fail(t, fmt.Sprintf("Not same: \n"+
  388. "expected: %p %#v\n"+
  389. "actual : %p %#v", expected, expected, actual, actual), msgAndArgs...)
  390. }
  391. return true
  392. }
  393. // NotSame asserts that two pointers do not reference the same object.
  394. //
  395. // assert.NotSame(t, ptr1, ptr2)
  396. //
  397. // Both arguments must be pointer variables. Pointer variable sameness is
  398. // determined based on the equality of both type and value.
  399. func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  400. if h, ok := t.(tHelper); ok {
  401. h.Helper()
  402. }
  403. if samePointers(expected, actual) {
  404. return Fail(t, fmt.Sprintf(
  405. "Expected and actual point to the same object: %p %#v",
  406. expected, expected), msgAndArgs...)
  407. }
  408. return true
  409. }
  410. // samePointers compares two generic interface objects and returns whether
  411. // they point to the same object
  412. func samePointers(first, second interface{}) bool {
  413. firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second)
  414. if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr {
  415. return false
  416. }
  417. firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second)
  418. if firstType != secondType {
  419. return false
  420. }
  421. // compare pointer addresses
  422. return first == second
  423. }
  424. // formatUnequalValues takes two values of arbitrary types and returns string
  425. // representations appropriate to be presented to the user.
  426. //
  427. // If the values are not of like type, the returned strings will be prefixed
  428. // with the type name, and the value will be enclosed in parenthesis similar
  429. // to a type conversion in the Go grammar.
  430. func formatUnequalValues(expected, actual interface{}) (e string, a string) {
  431. if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
  432. return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)),
  433. fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual))
  434. }
  435. switch expected.(type) {
  436. case time.Duration:
  437. return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)
  438. }
  439. return truncatingFormat(expected), truncatingFormat(actual)
  440. }
  441. // truncatingFormat formats the data and truncates it if it's too long.
  442. //
  443. // This helps keep formatted error messages lines from exceeding the
  444. // bufio.MaxScanTokenSize max line length that the go testing framework imposes.
  445. func truncatingFormat(data interface{}) string {
  446. value := fmt.Sprintf("%#v", data)
  447. max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed.
  448. if len(value) > max {
  449. value = value[0:max] + "<... truncated>"
  450. }
  451. return value
  452. }
  453. // EqualValues asserts that two objects are equal or convertable to the same types
  454. // and equal.
  455. //
  456. // assert.EqualValues(t, uint32(123), int32(123))
  457. func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  458. if h, ok := t.(tHelper); ok {
  459. h.Helper()
  460. }
  461. if !ObjectsAreEqualValues(expected, actual) {
  462. diff := diff(expected, actual)
  463. expected, actual = formatUnequalValues(expected, actual)
  464. return Fail(t, fmt.Sprintf("Not equal: \n"+
  465. "expected: %s\n"+
  466. "actual : %s%s", expected, actual, diff), msgAndArgs...)
  467. }
  468. return true
  469. }
  470. // EqualExportedValues asserts that the types of two objects are equal and their public
  471. // fields are also equal. This is useful for comparing structs that have private fields
  472. // that could potentially differ.
  473. //
  474. // type S struct {
  475. // Exported int
  476. // notExported int
  477. // }
  478. // assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true
  479. // assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false
  480. func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  481. if h, ok := t.(tHelper); ok {
  482. h.Helper()
  483. }
  484. aType := reflect.TypeOf(expected)
  485. bType := reflect.TypeOf(actual)
  486. if aType != bType {
  487. return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
  488. }
  489. if aType.Kind() != reflect.Struct {
  490. return Fail(t, fmt.Sprintf("Types expected to both be struct \n\t%v != %v", aType.Kind(), reflect.Struct), msgAndArgs...)
  491. }
  492. if bType.Kind() != reflect.Struct {
  493. return Fail(t, fmt.Sprintf("Types expected to both be struct \n\t%v != %v", bType.Kind(), reflect.Struct), msgAndArgs...)
  494. }
  495. expected = copyExportedFields(expected)
  496. actual = copyExportedFields(actual)
  497. if !ObjectsAreEqualValues(expected, actual) {
  498. diff := diff(expected, actual)
  499. expected, actual = formatUnequalValues(expected, actual)
  500. return Fail(t, fmt.Sprintf("Not equal (comparing only exported fields): \n"+
  501. "expected: %s\n"+
  502. "actual : %s%s", expected, actual, diff), msgAndArgs...)
  503. }
  504. return true
  505. }
  506. // Exactly asserts that two objects are equal in value and type.
  507. //
  508. // assert.Exactly(t, int32(123), int64(123))
  509. func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  510. if h, ok := t.(tHelper); ok {
  511. h.Helper()
  512. }
  513. aType := reflect.TypeOf(expected)
  514. bType := reflect.TypeOf(actual)
  515. if aType != bType {
  516. return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
  517. }
  518. return Equal(t, expected, actual, msgAndArgs...)
  519. }
  520. // NotNil asserts that the specified object is not nil.
  521. //
  522. // assert.NotNil(t, err)
  523. func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  524. if !isNil(object) {
  525. return true
  526. }
  527. if h, ok := t.(tHelper); ok {
  528. h.Helper()
  529. }
  530. return Fail(t, "Expected value not to be nil.", msgAndArgs...)
  531. }
  532. // containsKind checks if a specified kind in the slice of kinds.
  533. func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool {
  534. for i := 0; i < len(kinds); i++ {
  535. if kind == kinds[i] {
  536. return true
  537. }
  538. }
  539. return false
  540. }
  541. // isNil checks if a specified object is nil or not, without Failing.
  542. func isNil(object interface{}) bool {
  543. if object == nil {
  544. return true
  545. }
  546. value := reflect.ValueOf(object)
  547. kind := value.Kind()
  548. isNilableKind := containsKind(
  549. []reflect.Kind{
  550. reflect.Chan, reflect.Func,
  551. reflect.Interface, reflect.Map,
  552. reflect.Ptr, reflect.Slice, reflect.UnsafePointer},
  553. kind)
  554. if isNilableKind && value.IsNil() {
  555. return true
  556. }
  557. return false
  558. }
  559. // Nil asserts that the specified object is nil.
  560. //
  561. // assert.Nil(t, err)
  562. func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  563. if isNil(object) {
  564. return true
  565. }
  566. if h, ok := t.(tHelper); ok {
  567. h.Helper()
  568. }
  569. return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
  570. }
  571. // isEmpty gets whether the specified object is considered empty or not.
  572. func isEmpty(object interface{}) bool {
  573. // get nil case out of the way
  574. if object == nil {
  575. return true
  576. }
  577. objValue := reflect.ValueOf(object)
  578. switch objValue.Kind() {
  579. // collection types are empty when they have no element
  580. case reflect.Chan, reflect.Map, reflect.Slice:
  581. return objValue.Len() == 0
  582. // pointers are empty if nil or if the value they point to is empty
  583. case reflect.Ptr:
  584. if objValue.IsNil() {
  585. return true
  586. }
  587. deref := objValue.Elem().Interface()
  588. return isEmpty(deref)
  589. // for all other types, compare against the zero value
  590. // array types are empty when they match their zero-initialized state
  591. default:
  592. zero := reflect.Zero(objValue.Type())
  593. return reflect.DeepEqual(object, zero.Interface())
  594. }
  595. }
  596. // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
  597. // a slice or a channel with len == 0.
  598. //
  599. // assert.Empty(t, obj)
  600. func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  601. pass := isEmpty(object)
  602. if !pass {
  603. if h, ok := t.(tHelper); ok {
  604. h.Helper()
  605. }
  606. Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
  607. }
  608. return pass
  609. }
  610. // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
  611. // a slice or a channel with len == 0.
  612. //
  613. // if assert.NotEmpty(t, obj) {
  614. // assert.Equal(t, "two", obj[1])
  615. // }
  616. func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  617. pass := !isEmpty(object)
  618. if !pass {
  619. if h, ok := t.(tHelper); ok {
  620. h.Helper()
  621. }
  622. Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
  623. }
  624. return pass
  625. }
  626. // getLen try to get length of object.
  627. // return (false, 0) if impossible.
  628. func getLen(x interface{}) (ok bool, length int) {
  629. v := reflect.ValueOf(x)
  630. defer func() {
  631. if e := recover(); e != nil {
  632. ok = false
  633. }
  634. }()
  635. return true, v.Len()
  636. }
  637. // Len asserts that the specified object has specific length.
  638. // Len also fails if the object has a type that len() not accept.
  639. //
  640. // assert.Len(t, mySlice, 3)
  641. func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
  642. if h, ok := t.(tHelper); ok {
  643. h.Helper()
  644. }
  645. ok, l := getLen(object)
  646. if !ok {
  647. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
  648. }
  649. if l != length {
  650. return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
  651. }
  652. return true
  653. }
  654. // True asserts that the specified value is true.
  655. //
  656. // assert.True(t, myBool)
  657. func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
  658. if !value {
  659. if h, ok := t.(tHelper); ok {
  660. h.Helper()
  661. }
  662. return Fail(t, "Should be true", msgAndArgs...)
  663. }
  664. return true
  665. }
  666. // False asserts that the specified value is false.
  667. //
  668. // assert.False(t, myBool)
  669. func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
  670. if value {
  671. if h, ok := t.(tHelper); ok {
  672. h.Helper()
  673. }
  674. return Fail(t, "Should be false", msgAndArgs...)
  675. }
  676. return true
  677. }
  678. // NotEqual asserts that the specified values are NOT equal.
  679. //
  680. // assert.NotEqual(t, obj1, obj2)
  681. //
  682. // Pointer variable equality is determined based on the equality of the
  683. // referenced values (as opposed to the memory addresses).
  684. func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  685. if h, ok := t.(tHelper); ok {
  686. h.Helper()
  687. }
  688. if err := validateEqualArgs(expected, actual); err != nil {
  689. return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
  690. expected, actual, err), msgAndArgs...)
  691. }
  692. if ObjectsAreEqual(expected, actual) {
  693. return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
  694. }
  695. return true
  696. }
  697. // NotEqualValues asserts that two objects are not equal even when converted to the same type
  698. //
  699. // assert.NotEqualValues(t, obj1, obj2)
  700. func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  701. if h, ok := t.(tHelper); ok {
  702. h.Helper()
  703. }
  704. if ObjectsAreEqualValues(expected, actual) {
  705. return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
  706. }
  707. return true
  708. }
  709. // containsElement try loop over the list check if the list includes the element.
  710. // return (false, false) if impossible.
  711. // return (true, false) if element was not found.
  712. // return (true, true) if element was found.
  713. func containsElement(list interface{}, element interface{}) (ok, found bool) {
  714. listValue := reflect.ValueOf(list)
  715. listType := reflect.TypeOf(list)
  716. if listType == nil {
  717. return false, false
  718. }
  719. listKind := listType.Kind()
  720. defer func() {
  721. if e := recover(); e != nil {
  722. ok = false
  723. found = false
  724. }
  725. }()
  726. if listKind == reflect.String {
  727. elementValue := reflect.ValueOf(element)
  728. return true, strings.Contains(listValue.String(), elementValue.String())
  729. }
  730. if listKind == reflect.Map {
  731. mapKeys := listValue.MapKeys()
  732. for i := 0; i < len(mapKeys); i++ {
  733. if ObjectsAreEqual(mapKeys[i].Interface(), element) {
  734. return true, true
  735. }
  736. }
  737. return true, false
  738. }
  739. for i := 0; i < listValue.Len(); i++ {
  740. if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
  741. return true, true
  742. }
  743. }
  744. return true, false
  745. }
  746. // Contains asserts that the specified string, list(array, slice...) or map contains the
  747. // specified substring or element.
  748. //
  749. // assert.Contains(t, "Hello World", "World")
  750. // assert.Contains(t, ["Hello", "World"], "World")
  751. // assert.Contains(t, {"Hello": "World"}, "Hello")
  752. func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
  753. if h, ok := t.(tHelper); ok {
  754. h.Helper()
  755. }
  756. ok, found := containsElement(s, contains)
  757. if !ok {
  758. return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
  759. }
  760. if !found {
  761. return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
  762. }
  763. return true
  764. }
  765. // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
  766. // specified substring or element.
  767. //
  768. // assert.NotContains(t, "Hello World", "Earth")
  769. // assert.NotContains(t, ["Hello", "World"], "Earth")
  770. // assert.NotContains(t, {"Hello": "World"}, "Earth")
  771. func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
  772. if h, ok := t.(tHelper); ok {
  773. h.Helper()
  774. }
  775. ok, found := containsElement(s, contains)
  776. if !ok {
  777. return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
  778. }
  779. if found {
  780. return Fail(t, fmt.Sprintf("%#v should not contain %#v", s, contains), msgAndArgs...)
  781. }
  782. return true
  783. }
  784. // Subset asserts that the specified list(array, slice...) contains all
  785. // elements given in the specified subset(array, slice...).
  786. //
  787. // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
  788. func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
  789. if h, ok := t.(tHelper); ok {
  790. h.Helper()
  791. }
  792. if subset == nil {
  793. return true // we consider nil to be equal to the nil set
  794. }
  795. listKind := reflect.TypeOf(list).Kind()
  796. if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
  797. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
  798. }
  799. subsetKind := reflect.TypeOf(subset).Kind()
  800. if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
  801. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
  802. }
  803. if subsetKind == reflect.Map && listKind == reflect.Map {
  804. subsetMap := reflect.ValueOf(subset)
  805. actualMap := reflect.ValueOf(list)
  806. for _, k := range subsetMap.MapKeys() {
  807. ev := subsetMap.MapIndex(k)
  808. av := actualMap.MapIndex(k)
  809. if !av.IsValid() {
  810. return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
  811. }
  812. if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
  813. return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
  814. }
  815. }
  816. return true
  817. }
  818. subsetList := reflect.ValueOf(subset)
  819. for i := 0; i < subsetList.Len(); i++ {
  820. element := subsetList.Index(i).Interface()
  821. ok, found := containsElement(list, element)
  822. if !ok {
  823. return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
  824. }
  825. if !found {
  826. return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...)
  827. }
  828. }
  829. return true
  830. }
  831. // NotSubset asserts that the specified list(array, slice...) contains not all
  832. // elements given in the specified subset(array, slice...).
  833. //
  834. // assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
  835. func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
  836. if h, ok := t.(tHelper); ok {
  837. h.Helper()
  838. }
  839. if subset == nil {
  840. return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...)
  841. }
  842. listKind := reflect.TypeOf(list).Kind()
  843. if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
  844. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
  845. }
  846. subsetKind := reflect.TypeOf(subset).Kind()
  847. if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
  848. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
  849. }
  850. if subsetKind == reflect.Map && listKind == reflect.Map {
  851. subsetMap := reflect.ValueOf(subset)
  852. actualMap := reflect.ValueOf(list)
  853. for _, k := range subsetMap.MapKeys() {
  854. ev := subsetMap.MapIndex(k)
  855. av := actualMap.MapIndex(k)
  856. if !av.IsValid() {
  857. return true
  858. }
  859. if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
  860. return true
  861. }
  862. }
  863. return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
  864. }
  865. subsetList := reflect.ValueOf(subset)
  866. for i := 0; i < subsetList.Len(); i++ {
  867. element := subsetList.Index(i).Interface()
  868. ok, found := containsElement(list, element)
  869. if !ok {
  870. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
  871. }
  872. if !found {
  873. return true
  874. }
  875. }
  876. return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
  877. }
  878. // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
  879. // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
  880. // the number of appearances of each of them in both lists should match.
  881. //
  882. // assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
  883. func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
  884. if h, ok := t.(tHelper); ok {
  885. h.Helper()
  886. }
  887. if isEmpty(listA) && isEmpty(listB) {
  888. return true
  889. }
  890. if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) {
  891. return false
  892. }
  893. extraA, extraB := diffLists(listA, listB)
  894. if len(extraA) == 0 && len(extraB) == 0 {
  895. return true
  896. }
  897. return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...)
  898. }
  899. // isList checks that the provided value is array or slice.
  900. func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) {
  901. kind := reflect.TypeOf(list).Kind()
  902. if kind != reflect.Array && kind != reflect.Slice {
  903. return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind),
  904. msgAndArgs...)
  905. }
  906. return true
  907. }
  908. // diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B.
  909. // If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and
  910. // 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored.
  911. func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) {
  912. aValue := reflect.ValueOf(listA)
  913. bValue := reflect.ValueOf(listB)
  914. aLen := aValue.Len()
  915. bLen := bValue.Len()
  916. // Mark indexes in bValue that we already used
  917. visited := make([]bool, bLen)
  918. for i := 0; i < aLen; i++ {
  919. element := aValue.Index(i).Interface()
  920. found := false
  921. for j := 0; j < bLen; j++ {
  922. if visited[j] {
  923. continue
  924. }
  925. if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
  926. visited[j] = true
  927. found = true
  928. break
  929. }
  930. }
  931. if !found {
  932. extraA = append(extraA, element)
  933. }
  934. }
  935. for j := 0; j < bLen; j++ {
  936. if visited[j] {
  937. continue
  938. }
  939. extraB = append(extraB, bValue.Index(j).Interface())
  940. }
  941. return
  942. }
  943. func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string {
  944. var msg bytes.Buffer
  945. msg.WriteString("elements differ")
  946. if len(extraA) > 0 {
  947. msg.WriteString("\n\nextra elements in list A:\n")
  948. msg.WriteString(spewConfig.Sdump(extraA))
  949. }
  950. if len(extraB) > 0 {
  951. msg.WriteString("\n\nextra elements in list B:\n")
  952. msg.WriteString(spewConfig.Sdump(extraB))
  953. }
  954. msg.WriteString("\n\nlistA:\n")
  955. msg.WriteString(spewConfig.Sdump(listA))
  956. msg.WriteString("\n\nlistB:\n")
  957. msg.WriteString(spewConfig.Sdump(listB))
  958. return msg.String()
  959. }
  960. // Condition uses a Comparison to assert a complex condition.
  961. func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
  962. if h, ok := t.(tHelper); ok {
  963. h.Helper()
  964. }
  965. result := comp()
  966. if !result {
  967. Fail(t, "Condition failed!", msgAndArgs...)
  968. }
  969. return result
  970. }
  971. // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
  972. // methods, and represents a simple func that takes no arguments, and returns nothing.
  973. type PanicTestFunc func()
  974. // didPanic returns true if the function passed to it panics. Otherwise, it returns false.
  975. func didPanic(f PanicTestFunc) (didPanic bool, message interface{}, stack string) {
  976. didPanic = true
  977. defer func() {
  978. message = recover()
  979. if didPanic {
  980. stack = string(debug.Stack())
  981. }
  982. }()
  983. // call the target function
  984. f()
  985. didPanic = false
  986. return
  987. }
  988. // Panics asserts that the code inside the specified PanicTestFunc panics.
  989. //
  990. // assert.Panics(t, func(){ GoCrazy() })
  991. func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  992. if h, ok := t.(tHelper); ok {
  993. h.Helper()
  994. }
  995. if funcDidPanic, panicValue, _ := didPanic(f); !funcDidPanic {
  996. return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
  997. }
  998. return true
  999. }
  1000. // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
  1001. // the recovered panic value equals the expected panic value.
  1002. //
  1003. // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
  1004. func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  1005. if h, ok := t.(tHelper); ok {
  1006. h.Helper()
  1007. }
  1008. funcDidPanic, panicValue, panickedStack := didPanic(f)
  1009. if !funcDidPanic {
  1010. return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
  1011. }
  1012. if panicValue != expected {
  1013. return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, expected, panicValue, panickedStack), msgAndArgs...)
  1014. }
  1015. return true
  1016. }
  1017. // PanicsWithError asserts that the code inside the specified PanicTestFunc
  1018. // panics, and that the recovered panic value is an error that satisfies the
  1019. // EqualError comparison.
  1020. //
  1021. // assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
  1022. func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  1023. if h, ok := t.(tHelper); ok {
  1024. h.Helper()
  1025. }
  1026. funcDidPanic, panicValue, panickedStack := didPanic(f)
  1027. if !funcDidPanic {
  1028. return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
  1029. }
  1030. panicErr, ok := panicValue.(error)
  1031. if !ok || panicErr.Error() != errString {
  1032. return Fail(t, fmt.Sprintf("func %#v should panic with error message:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, errString, panicValue, panickedStack), msgAndArgs...)
  1033. }
  1034. return true
  1035. }
  1036. // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
  1037. //
  1038. // assert.NotPanics(t, func(){ RemainCalm() })
  1039. func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  1040. if h, ok := t.(tHelper); ok {
  1041. h.Helper()
  1042. }
  1043. if funcDidPanic, panicValue, panickedStack := didPanic(f); funcDidPanic {
  1044. return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v\n\tPanic stack:\t%s", f, panicValue, panickedStack), msgAndArgs...)
  1045. }
  1046. return true
  1047. }
  1048. // WithinDuration asserts that the two times are within duration delta of each other.
  1049. //
  1050. // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
  1051. func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
  1052. if h, ok := t.(tHelper); ok {
  1053. h.Helper()
  1054. }
  1055. dt := expected.Sub(actual)
  1056. if dt < -delta || dt > delta {
  1057. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
  1058. }
  1059. return true
  1060. }
  1061. // WithinRange asserts that a time is within a time range (inclusive).
  1062. //
  1063. // assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
  1064. func WithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool {
  1065. if h, ok := t.(tHelper); ok {
  1066. h.Helper()
  1067. }
  1068. if end.Before(start) {
  1069. return Fail(t, "Start should be before end", msgAndArgs...)
  1070. }
  1071. if actual.Before(start) {
  1072. return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is before the range", actual, start, end), msgAndArgs...)
  1073. } else if actual.After(end) {
  1074. return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is after the range", actual, start, end), msgAndArgs...)
  1075. }
  1076. return true
  1077. }
  1078. func toFloat(x interface{}) (float64, bool) {
  1079. var xf float64
  1080. xok := true
  1081. switch xn := x.(type) {
  1082. case uint:
  1083. xf = float64(xn)
  1084. case uint8:
  1085. xf = float64(xn)
  1086. case uint16:
  1087. xf = float64(xn)
  1088. case uint32:
  1089. xf = float64(xn)
  1090. case uint64:
  1091. xf = float64(xn)
  1092. case int:
  1093. xf = float64(xn)
  1094. case int8:
  1095. xf = float64(xn)
  1096. case int16:
  1097. xf = float64(xn)
  1098. case int32:
  1099. xf = float64(xn)
  1100. case int64:
  1101. xf = float64(xn)
  1102. case float32:
  1103. xf = float64(xn)
  1104. case float64:
  1105. xf = xn
  1106. case time.Duration:
  1107. xf = float64(xn)
  1108. default:
  1109. xok = false
  1110. }
  1111. return xf, xok
  1112. }
  1113. // InDelta asserts that the two numerals are within delta of each other.
  1114. //
  1115. // assert.InDelta(t, math.Pi, 22/7.0, 0.01)
  1116. func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  1117. if h, ok := t.(tHelper); ok {
  1118. h.Helper()
  1119. }
  1120. af, aok := toFloat(expected)
  1121. bf, bok := toFloat(actual)
  1122. if !aok || !bok {
  1123. return Fail(t, "Parameters must be numerical", msgAndArgs...)
  1124. }
  1125. if math.IsNaN(af) && math.IsNaN(bf) {
  1126. return true
  1127. }
  1128. if math.IsNaN(af) {
  1129. return Fail(t, "Expected must not be NaN", msgAndArgs...)
  1130. }
  1131. if math.IsNaN(bf) {
  1132. return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
  1133. }
  1134. dt := af - bf
  1135. if dt < -delta || dt > delta {
  1136. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
  1137. }
  1138. return true
  1139. }
  1140. // InDeltaSlice is the same as InDelta, except it compares two slices.
  1141. func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  1142. if h, ok := t.(tHelper); ok {
  1143. h.Helper()
  1144. }
  1145. if expected == nil || actual == nil ||
  1146. reflect.TypeOf(actual).Kind() != reflect.Slice ||
  1147. reflect.TypeOf(expected).Kind() != reflect.Slice {
  1148. return Fail(t, "Parameters must be slice", msgAndArgs...)
  1149. }
  1150. actualSlice := reflect.ValueOf(actual)
  1151. expectedSlice := reflect.ValueOf(expected)
  1152. for i := 0; i < actualSlice.Len(); i++ {
  1153. result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
  1154. if !result {
  1155. return result
  1156. }
  1157. }
  1158. return true
  1159. }
  1160. // InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
  1161. func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  1162. if h, ok := t.(tHelper); ok {
  1163. h.Helper()
  1164. }
  1165. if expected == nil || actual == nil ||
  1166. reflect.TypeOf(actual).Kind() != reflect.Map ||
  1167. reflect.TypeOf(expected).Kind() != reflect.Map {
  1168. return Fail(t, "Arguments must be maps", msgAndArgs...)
  1169. }
  1170. expectedMap := reflect.ValueOf(expected)
  1171. actualMap := reflect.ValueOf(actual)
  1172. if expectedMap.Len() != actualMap.Len() {
  1173. return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
  1174. }
  1175. for _, k := range expectedMap.MapKeys() {
  1176. ev := expectedMap.MapIndex(k)
  1177. av := actualMap.MapIndex(k)
  1178. if !ev.IsValid() {
  1179. return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
  1180. }
  1181. if !av.IsValid() {
  1182. return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
  1183. }
  1184. if !InDelta(
  1185. t,
  1186. ev.Interface(),
  1187. av.Interface(),
  1188. delta,
  1189. msgAndArgs...,
  1190. ) {
  1191. return false
  1192. }
  1193. }
  1194. return true
  1195. }
  1196. func calcRelativeError(expected, actual interface{}) (float64, error) {
  1197. af, aok := toFloat(expected)
  1198. bf, bok := toFloat(actual)
  1199. if !aok || !bok {
  1200. return 0, fmt.Errorf("Parameters must be numerical")
  1201. }
  1202. if math.IsNaN(af) && math.IsNaN(bf) {
  1203. return 0, nil
  1204. }
  1205. if math.IsNaN(af) {
  1206. return 0, errors.New("expected value must not be NaN")
  1207. }
  1208. if af == 0 {
  1209. return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
  1210. }
  1211. if math.IsNaN(bf) {
  1212. return 0, errors.New("actual value must not be NaN")
  1213. }
  1214. return math.Abs(af-bf) / math.Abs(af), nil
  1215. }
  1216. // InEpsilon asserts that expected and actual have a relative error less than epsilon
  1217. func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
  1218. if h, ok := t.(tHelper); ok {
  1219. h.Helper()
  1220. }
  1221. if math.IsNaN(epsilon) {
  1222. return Fail(t, "epsilon must not be NaN")
  1223. }
  1224. actualEpsilon, err := calcRelativeError(expected, actual)
  1225. if err != nil {
  1226. return Fail(t, err.Error(), msgAndArgs...)
  1227. }
  1228. if actualEpsilon > epsilon {
  1229. return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
  1230. " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
  1231. }
  1232. return true
  1233. }
  1234. // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
  1235. func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
  1236. if h, ok := t.(tHelper); ok {
  1237. h.Helper()
  1238. }
  1239. if expected == nil || actual == nil ||
  1240. reflect.TypeOf(actual).Kind() != reflect.Slice ||
  1241. reflect.TypeOf(expected).Kind() != reflect.Slice {
  1242. return Fail(t, "Parameters must be slice", msgAndArgs...)
  1243. }
  1244. actualSlice := reflect.ValueOf(actual)
  1245. expectedSlice := reflect.ValueOf(expected)
  1246. for i := 0; i < actualSlice.Len(); i++ {
  1247. result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
  1248. if !result {
  1249. return result
  1250. }
  1251. }
  1252. return true
  1253. }
  1254. /*
  1255. Errors
  1256. */
  1257. // NoError asserts that a function returned no error (i.e. `nil`).
  1258. //
  1259. // actualObj, err := SomeFunction()
  1260. // if assert.NoError(t, err) {
  1261. // assert.Equal(t, expectedObj, actualObj)
  1262. // }
  1263. func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
  1264. if err != nil {
  1265. if h, ok := t.(tHelper); ok {
  1266. h.Helper()
  1267. }
  1268. return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
  1269. }
  1270. return true
  1271. }
  1272. // Error asserts that a function returned an error (i.e. not `nil`).
  1273. //
  1274. // actualObj, err := SomeFunction()
  1275. // if assert.Error(t, err) {
  1276. // assert.Equal(t, expectedError, err)
  1277. // }
  1278. func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
  1279. if err == nil {
  1280. if h, ok := t.(tHelper); ok {
  1281. h.Helper()
  1282. }
  1283. return Fail(t, "An error is expected but got nil.", msgAndArgs...)
  1284. }
  1285. return true
  1286. }
  1287. // EqualError asserts that a function returned an error (i.e. not `nil`)
  1288. // and that it is equal to the provided error.
  1289. //
  1290. // actualObj, err := SomeFunction()
  1291. // assert.EqualError(t, err, expectedErrorString)
  1292. func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
  1293. if h, ok := t.(tHelper); ok {
  1294. h.Helper()
  1295. }
  1296. if !Error(t, theError, msgAndArgs...) {
  1297. return false
  1298. }
  1299. expected := errString
  1300. actual := theError.Error()
  1301. // don't need to use deep equals here, we know they are both strings
  1302. if expected != actual {
  1303. return Fail(t, fmt.Sprintf("Error message not equal:\n"+
  1304. "expected: %q\n"+
  1305. "actual : %q", expected, actual), msgAndArgs...)
  1306. }
  1307. return true
  1308. }
  1309. // ErrorContains asserts that a function returned an error (i.e. not `nil`)
  1310. // and that the error contains the specified substring.
  1311. //
  1312. // actualObj, err := SomeFunction()
  1313. // assert.ErrorContains(t, err, expectedErrorSubString)
  1314. func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool {
  1315. if h, ok := t.(tHelper); ok {
  1316. h.Helper()
  1317. }
  1318. if !Error(t, theError, msgAndArgs...) {
  1319. return false
  1320. }
  1321. actual := theError.Error()
  1322. if !strings.Contains(actual, contains) {
  1323. return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...)
  1324. }
  1325. return true
  1326. }
  1327. // matchRegexp return true if a specified regexp matches a string.
  1328. func matchRegexp(rx interface{}, str interface{}) bool {
  1329. var r *regexp.Regexp
  1330. if rr, ok := rx.(*regexp.Regexp); ok {
  1331. r = rr
  1332. } else {
  1333. r = regexp.MustCompile(fmt.Sprint(rx))
  1334. }
  1335. return (r.FindStringIndex(fmt.Sprint(str)) != nil)
  1336. }
  1337. // Regexp asserts that a specified regexp matches a string.
  1338. //
  1339. // assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
  1340. // assert.Regexp(t, "start...$", "it's not starting")
  1341. func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
  1342. if h, ok := t.(tHelper); ok {
  1343. h.Helper()
  1344. }
  1345. match := matchRegexp(rx, str)
  1346. if !match {
  1347. Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
  1348. }
  1349. return match
  1350. }
  1351. // NotRegexp asserts that a specified regexp does not match a string.
  1352. //
  1353. // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
  1354. // assert.NotRegexp(t, "^start", "it's not starting")
  1355. func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
  1356. if h, ok := t.(tHelper); ok {
  1357. h.Helper()
  1358. }
  1359. match := matchRegexp(rx, str)
  1360. if match {
  1361. Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
  1362. }
  1363. return !match
  1364. }
  1365. // Zero asserts that i is the zero value for its type.
  1366. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
  1367. if h, ok := t.(tHelper); ok {
  1368. h.Helper()
  1369. }
  1370. if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
  1371. return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
  1372. }
  1373. return true
  1374. }
  1375. // NotZero asserts that i is not the zero value for its type.
  1376. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
  1377. if h, ok := t.(tHelper); ok {
  1378. h.Helper()
  1379. }
  1380. if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
  1381. return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
  1382. }
  1383. return true
  1384. }
  1385. // FileExists checks whether a file exists in the given path. It also fails if
  1386. // the path points to a directory or there is an error when trying to check the file.
  1387. func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1388. if h, ok := t.(tHelper); ok {
  1389. h.Helper()
  1390. }
  1391. info, err := os.Lstat(path)
  1392. if err != nil {
  1393. if os.IsNotExist(err) {
  1394. return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
  1395. }
  1396. return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
  1397. }
  1398. if info.IsDir() {
  1399. return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
  1400. }
  1401. return true
  1402. }
  1403. // NoFileExists checks whether a file does not exist in a given path. It fails
  1404. // if the path points to an existing _file_ only.
  1405. func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1406. if h, ok := t.(tHelper); ok {
  1407. h.Helper()
  1408. }
  1409. info, err := os.Lstat(path)
  1410. if err != nil {
  1411. return true
  1412. }
  1413. if info.IsDir() {
  1414. return true
  1415. }
  1416. return Fail(t, fmt.Sprintf("file %q exists", path), msgAndArgs...)
  1417. }
  1418. // DirExists checks whether a directory exists in the given path. It also fails
  1419. // if the path is a file rather a directory or there is an error checking whether it exists.
  1420. func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1421. if h, ok := t.(tHelper); ok {
  1422. h.Helper()
  1423. }
  1424. info, err := os.Lstat(path)
  1425. if err != nil {
  1426. if os.IsNotExist(err) {
  1427. return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
  1428. }
  1429. return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
  1430. }
  1431. if !info.IsDir() {
  1432. return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
  1433. }
  1434. return true
  1435. }
  1436. // NoDirExists checks whether a directory does not exist in the given path.
  1437. // It fails if the path points to an existing _directory_ only.
  1438. func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1439. if h, ok := t.(tHelper); ok {
  1440. h.Helper()
  1441. }
  1442. info, err := os.Lstat(path)
  1443. if err != nil {
  1444. if os.IsNotExist(err) {
  1445. return true
  1446. }
  1447. return true
  1448. }
  1449. if !info.IsDir() {
  1450. return true
  1451. }
  1452. return Fail(t, fmt.Sprintf("directory %q exists", path), msgAndArgs...)
  1453. }
  1454. // JSONEq asserts that two JSON strings are equivalent.
  1455. //
  1456. // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
  1457. func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
  1458. if h, ok := t.(tHelper); ok {
  1459. h.Helper()
  1460. }
  1461. var expectedJSONAsInterface, actualJSONAsInterface interface{}
  1462. if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
  1463. return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
  1464. }
  1465. if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
  1466. return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
  1467. }
  1468. return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
  1469. }
  1470. // YAMLEq asserts that two YAML strings are equivalent.
  1471. func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
  1472. if h, ok := t.(tHelper); ok {
  1473. h.Helper()
  1474. }
  1475. var expectedYAMLAsInterface, actualYAMLAsInterface interface{}
  1476. if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil {
  1477. return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...)
  1478. }
  1479. if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil {
  1480. return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...)
  1481. }
  1482. return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...)
  1483. }
  1484. func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
  1485. t := reflect.TypeOf(v)
  1486. k := t.Kind()
  1487. if k == reflect.Ptr {
  1488. t = t.Elem()
  1489. k = t.Kind()
  1490. }
  1491. return t, k
  1492. }
  1493. // diff returns a diff of both values as long as both are of the same type and
  1494. // are a struct, map, slice, array or string. Otherwise it returns an empty string.
  1495. func diff(expected interface{}, actual interface{}) string {
  1496. if expected == nil || actual == nil {
  1497. return ""
  1498. }
  1499. et, ek := typeAndKind(expected)
  1500. at, _ := typeAndKind(actual)
  1501. if et != at {
  1502. return ""
  1503. }
  1504. if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
  1505. return ""
  1506. }
  1507. var e, a string
  1508. switch et {
  1509. case reflect.TypeOf(""):
  1510. e = reflect.ValueOf(expected).String()
  1511. a = reflect.ValueOf(actual).String()
  1512. case reflect.TypeOf(time.Time{}):
  1513. e = spewConfigStringerEnabled.Sdump(expected)
  1514. a = spewConfigStringerEnabled.Sdump(actual)
  1515. default:
  1516. e = spewConfig.Sdump(expected)
  1517. a = spewConfig.Sdump(actual)
  1518. }
  1519. diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
  1520. A: difflib.SplitLines(e),
  1521. B: difflib.SplitLines(a),
  1522. FromFile: "Expected",
  1523. FromDate: "",
  1524. ToFile: "Actual",
  1525. ToDate: "",
  1526. Context: 1,
  1527. })
  1528. return "\n\nDiff:\n" + diff
  1529. }
  1530. func isFunction(arg interface{}) bool {
  1531. if arg == nil {
  1532. return false
  1533. }
  1534. return reflect.TypeOf(arg).Kind() == reflect.Func
  1535. }
  1536. var spewConfig = spew.ConfigState{
  1537. Indent: " ",
  1538. DisablePointerAddresses: true,
  1539. DisableCapacities: true,
  1540. SortKeys: true,
  1541. DisableMethods: true,
  1542. MaxDepth: 10,
  1543. }
  1544. var spewConfigStringerEnabled = spew.ConfigState{
  1545. Indent: " ",
  1546. DisablePointerAddresses: true,
  1547. DisableCapacities: true,
  1548. SortKeys: true,
  1549. MaxDepth: 10,
  1550. }
  1551. type tHelper interface {
  1552. Helper()
  1553. }
  1554. // Eventually asserts that given condition will be met in waitFor time,
  1555. // periodically checking target function each tick.
  1556. //
  1557. // assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
  1558. func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
  1559. if h, ok := t.(tHelper); ok {
  1560. h.Helper()
  1561. }
  1562. ch := make(chan bool, 1)
  1563. timer := time.NewTimer(waitFor)
  1564. defer timer.Stop()
  1565. ticker := time.NewTicker(tick)
  1566. defer ticker.Stop()
  1567. for tick := ticker.C; ; {
  1568. select {
  1569. case <-timer.C:
  1570. return Fail(t, "Condition never satisfied", msgAndArgs...)
  1571. case <-tick:
  1572. tick = nil
  1573. go func() { ch <- condition() }()
  1574. case v := <-ch:
  1575. if v {
  1576. return true
  1577. }
  1578. tick = ticker.C
  1579. }
  1580. }
  1581. }
  1582. // CollectT implements the TestingT interface and collects all errors.
  1583. type CollectT struct {
  1584. errors []error
  1585. }
  1586. // Errorf collects the error.
  1587. func (c *CollectT) Errorf(format string, args ...interface{}) {
  1588. c.errors = append(c.errors, fmt.Errorf(format, args...))
  1589. }
  1590. // FailNow panics.
  1591. func (c *CollectT) FailNow() {
  1592. panic("Assertion failed")
  1593. }
  1594. // Reset clears the collected errors.
  1595. func (c *CollectT) Reset() {
  1596. c.errors = nil
  1597. }
  1598. // Copy copies the collected errors to the supplied t.
  1599. func (c *CollectT) Copy(t TestingT) {
  1600. if tt, ok := t.(tHelper); ok {
  1601. tt.Helper()
  1602. }
  1603. for _, err := range c.errors {
  1604. t.Errorf("%v", err)
  1605. }
  1606. }
  1607. // EventuallyWithT asserts that given condition will be met in waitFor time,
  1608. // periodically checking target function each tick. In contrast to Eventually,
  1609. // it supplies a CollectT to the condition function, so that the condition
  1610. // function can use the CollectT to call other assertions.
  1611. // The condition is considered "met" if no errors are raised in a tick.
  1612. // The supplied CollectT collects all errors from one tick (if there are any).
  1613. // If the condition is not met before waitFor, the collected errors of
  1614. // the last tick are copied to t.
  1615. //
  1616. // externalValue := false
  1617. // go func() {
  1618. // time.Sleep(8*time.Second)
  1619. // externalValue = true
  1620. // }()
  1621. // assert.EventuallyWithT(t, func(c *assert.CollectT) {
  1622. // // add assertions as needed; any assertion failure will fail the current tick
  1623. // assert.True(c, externalValue, "expected 'externalValue' to be true")
  1624. // }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false")
  1625. func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
  1626. if h, ok := t.(tHelper); ok {
  1627. h.Helper()
  1628. }
  1629. collect := new(CollectT)
  1630. ch := make(chan bool, 1)
  1631. timer := time.NewTimer(waitFor)
  1632. defer timer.Stop()
  1633. ticker := time.NewTicker(tick)
  1634. defer ticker.Stop()
  1635. for tick := ticker.C; ; {
  1636. select {
  1637. case <-timer.C:
  1638. collect.Copy(t)
  1639. return Fail(t, "Condition never satisfied", msgAndArgs...)
  1640. case <-tick:
  1641. tick = nil
  1642. collect.Reset()
  1643. go func() {
  1644. condition(collect)
  1645. ch <- len(collect.errors) == 0
  1646. }()
  1647. case v := <-ch:
  1648. if v {
  1649. return true
  1650. }
  1651. tick = ticker.C
  1652. }
  1653. }
  1654. }
  1655. // Never asserts that the given condition doesn't satisfy in waitFor time,
  1656. // periodically checking the target function each tick.
  1657. //
  1658. // assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
  1659. func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
  1660. if h, ok := t.(tHelper); ok {
  1661. h.Helper()
  1662. }
  1663. ch := make(chan bool, 1)
  1664. timer := time.NewTimer(waitFor)
  1665. defer timer.Stop()
  1666. ticker := time.NewTicker(tick)
  1667. defer ticker.Stop()
  1668. for tick := ticker.C; ; {
  1669. select {
  1670. case <-timer.C:
  1671. return true
  1672. case <-tick:
  1673. tick = nil
  1674. go func() { ch <- condition() }()
  1675. case v := <-ch:
  1676. if v {
  1677. return Fail(t, "Condition satisfied", msgAndArgs...)
  1678. }
  1679. tick = ticker.C
  1680. }
  1681. }
  1682. }
  1683. // ErrorIs asserts that at least one of the errors in err's chain matches target.
  1684. // This is a wrapper for errors.Is.
  1685. func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
  1686. if h, ok := t.(tHelper); ok {
  1687. h.Helper()
  1688. }
  1689. if errors.Is(err, target) {
  1690. return true
  1691. }
  1692. var expectedText string
  1693. if target != nil {
  1694. expectedText = target.Error()
  1695. }
  1696. chain := buildErrorChainString(err)
  1697. return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+
  1698. "expected: %q\n"+
  1699. "in chain: %s", expectedText, chain,
  1700. ), msgAndArgs...)
  1701. }
  1702. // NotErrorIs asserts that at none of the errors in err's chain matches target.
  1703. // This is a wrapper for errors.Is.
  1704. func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
  1705. if h, ok := t.(tHelper); ok {
  1706. h.Helper()
  1707. }
  1708. if !errors.Is(err, target) {
  1709. return true
  1710. }
  1711. var expectedText string
  1712. if target != nil {
  1713. expectedText = target.Error()
  1714. }
  1715. chain := buildErrorChainString(err)
  1716. return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
  1717. "found: %q\n"+
  1718. "in chain: %s", expectedText, chain,
  1719. ), msgAndArgs...)
  1720. }
  1721. // ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value.
  1722. // This is a wrapper for errors.As.
  1723. func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool {
  1724. if h, ok := t.(tHelper); ok {
  1725. h.Helper()
  1726. }
  1727. if errors.As(err, target) {
  1728. return true
  1729. }
  1730. chain := buildErrorChainString(err)
  1731. return Fail(t, fmt.Sprintf("Should be in error chain:\n"+
  1732. "expected: %q\n"+
  1733. "in chain: %s", target, chain,
  1734. ), msgAndArgs...)
  1735. }
  1736. func buildErrorChainString(err error) string {
  1737. if err == nil {
  1738. return ""
  1739. }
  1740. e := errors.Unwrap(err)
  1741. chain := fmt.Sprintf("%q", err.Error())
  1742. for e != nil {
  1743. chain += fmt.Sprintf("\n\t%q", e.Error())
  1744. e = errors.Unwrap(e)
  1745. }
  1746. return chain
  1747. }