assertions.go 50 KB

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