assertions.go 62 KB

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