assertions.go 59 KB

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