assertions.go 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856
  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. if len(parts) > 1 {
  120. filename := parts[len(parts)-1]
  121. dir := parts[len(parts)-2]
  122. if (dir != "assert" && dir != "mock" && dir != "require") || filename == "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, reflect.UnsafePointer},
  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.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. // array types are empty when they match their zero-initialized state
  492. default:
  493. zero := reflect.Zero(objValue.Type())
  494. return reflect.DeepEqual(object, zero.Interface())
  495. }
  496. }
  497. // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
  498. // a slice or a channel with len == 0.
  499. //
  500. // assert.Empty(t, obj)
  501. func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  502. pass := isEmpty(object)
  503. if !pass {
  504. if h, ok := t.(tHelper); ok {
  505. h.Helper()
  506. }
  507. Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
  508. }
  509. return pass
  510. }
  511. // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
  512. // a slice or a channel with len == 0.
  513. //
  514. // if assert.NotEmpty(t, obj) {
  515. // assert.Equal(t, "two", obj[1])
  516. // }
  517. func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  518. pass := !isEmpty(object)
  519. if !pass {
  520. if h, ok := t.(tHelper); ok {
  521. h.Helper()
  522. }
  523. Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
  524. }
  525. return pass
  526. }
  527. // getLen try to get length of object.
  528. // return (false, 0) if impossible.
  529. func getLen(x interface{}) (ok bool, length int) {
  530. v := reflect.ValueOf(x)
  531. defer func() {
  532. if e := recover(); e != nil {
  533. ok = false
  534. }
  535. }()
  536. return true, v.Len()
  537. }
  538. // Len asserts that the specified object has specific length.
  539. // Len also fails if the object has a type that len() not accept.
  540. //
  541. // assert.Len(t, mySlice, 3)
  542. func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
  543. if h, ok := t.(tHelper); ok {
  544. h.Helper()
  545. }
  546. ok, l := getLen(object)
  547. if !ok {
  548. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
  549. }
  550. if l != length {
  551. return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
  552. }
  553. return true
  554. }
  555. // True asserts that the specified value is true.
  556. //
  557. // assert.True(t, myBool)
  558. func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
  559. if !value {
  560. if h, ok := t.(tHelper); ok {
  561. h.Helper()
  562. }
  563. return Fail(t, "Should be true", msgAndArgs...)
  564. }
  565. return true
  566. }
  567. // False asserts that the specified value is false.
  568. //
  569. // assert.False(t, myBool)
  570. func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
  571. if value {
  572. if h, ok := t.(tHelper); ok {
  573. h.Helper()
  574. }
  575. return Fail(t, "Should be false", msgAndArgs...)
  576. }
  577. return true
  578. }
  579. // NotEqual asserts that the specified values are NOT equal.
  580. //
  581. // assert.NotEqual(t, obj1, obj2)
  582. //
  583. // Pointer variable equality is determined based on the equality of the
  584. // referenced values (as opposed to the memory addresses).
  585. func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  586. if h, ok := t.(tHelper); ok {
  587. h.Helper()
  588. }
  589. if err := validateEqualArgs(expected, actual); err != nil {
  590. return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
  591. expected, actual, err), msgAndArgs...)
  592. }
  593. if ObjectsAreEqual(expected, actual) {
  594. return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
  595. }
  596. return true
  597. }
  598. // NotEqualValues asserts that two objects are not equal even when converted to the same type
  599. //
  600. // assert.NotEqualValues(t, obj1, obj2)
  601. func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  602. if h, ok := t.(tHelper); ok {
  603. h.Helper()
  604. }
  605. if ObjectsAreEqualValues(expected, actual) {
  606. return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
  607. }
  608. return true
  609. }
  610. // containsElement try loop over the list check if the list includes the element.
  611. // return (false, false) if impossible.
  612. // return (true, false) if element was not found.
  613. // return (true, true) if element was found.
  614. func containsElement(list interface{}, element interface{}) (ok, found bool) {
  615. listValue := reflect.ValueOf(list)
  616. listType := reflect.TypeOf(list)
  617. if listType == nil {
  618. return false, false
  619. }
  620. listKind := listType.Kind()
  621. defer func() {
  622. if e := recover(); e != nil {
  623. ok = false
  624. found = false
  625. }
  626. }()
  627. if listKind == reflect.String {
  628. elementValue := reflect.ValueOf(element)
  629. return true, strings.Contains(listValue.String(), elementValue.String())
  630. }
  631. if listKind == reflect.Map {
  632. mapKeys := listValue.MapKeys()
  633. for i := 0; i < len(mapKeys); i++ {
  634. if ObjectsAreEqual(mapKeys[i].Interface(), element) {
  635. return true, true
  636. }
  637. }
  638. return true, false
  639. }
  640. for i := 0; i < listValue.Len(); i++ {
  641. if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
  642. return true, true
  643. }
  644. }
  645. return true, false
  646. }
  647. // Contains asserts that the specified string, list(array, slice...) or map contains the
  648. // specified substring or element.
  649. //
  650. // assert.Contains(t, "Hello World", "World")
  651. // assert.Contains(t, ["Hello", "World"], "World")
  652. // assert.Contains(t, {"Hello": "World"}, "Hello")
  653. func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
  654. if h, ok := t.(tHelper); ok {
  655. h.Helper()
  656. }
  657. ok, found := containsElement(s, contains)
  658. if !ok {
  659. return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
  660. }
  661. if !found {
  662. return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
  663. }
  664. return true
  665. }
  666. // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
  667. // specified substring or element.
  668. //
  669. // assert.NotContains(t, "Hello World", "Earth")
  670. // assert.NotContains(t, ["Hello", "World"], "Earth")
  671. // assert.NotContains(t, {"Hello": "World"}, "Earth")
  672. func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
  673. if h, ok := t.(tHelper); ok {
  674. h.Helper()
  675. }
  676. ok, found := containsElement(s, contains)
  677. if !ok {
  678. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
  679. }
  680. if found {
  681. return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
  682. }
  683. return true
  684. }
  685. // Subset asserts that the specified list(array, slice...) contains all
  686. // elements given in the specified subset(array, slice...).
  687. //
  688. // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
  689. func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
  690. if h, ok := t.(tHelper); ok {
  691. h.Helper()
  692. }
  693. if subset == nil {
  694. return true // we consider nil to be equal to the nil set
  695. }
  696. listKind := reflect.TypeOf(list).Kind()
  697. if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
  698. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
  699. }
  700. subsetKind := reflect.TypeOf(subset).Kind()
  701. if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
  702. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
  703. }
  704. if subsetKind == reflect.Map && listKind == reflect.Map {
  705. subsetMap := reflect.ValueOf(subset)
  706. actualMap := reflect.ValueOf(list)
  707. for _, k := range subsetMap.MapKeys() {
  708. ev := subsetMap.MapIndex(k)
  709. av := actualMap.MapIndex(k)
  710. if !av.IsValid() {
  711. return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
  712. }
  713. if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
  714. return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
  715. }
  716. }
  717. return true
  718. }
  719. subsetList := reflect.ValueOf(subset)
  720. for i := 0; i < subsetList.Len(); i++ {
  721. element := subsetList.Index(i).Interface()
  722. ok, found := containsElement(list, element)
  723. if !ok {
  724. return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
  725. }
  726. if !found {
  727. return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...)
  728. }
  729. }
  730. return true
  731. }
  732. // NotSubset asserts that the specified list(array, slice...) contains not all
  733. // elements given in the specified subset(array, slice...).
  734. //
  735. // assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
  736. func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
  737. if h, ok := t.(tHelper); ok {
  738. h.Helper()
  739. }
  740. if subset == nil {
  741. return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...)
  742. }
  743. listKind := reflect.TypeOf(list).Kind()
  744. if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
  745. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
  746. }
  747. subsetKind := reflect.TypeOf(subset).Kind()
  748. if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
  749. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
  750. }
  751. if subsetKind == reflect.Map && listKind == reflect.Map {
  752. subsetMap := reflect.ValueOf(subset)
  753. actualMap := reflect.ValueOf(list)
  754. for _, k := range subsetMap.MapKeys() {
  755. ev := subsetMap.MapIndex(k)
  756. av := actualMap.MapIndex(k)
  757. if !av.IsValid() {
  758. return true
  759. }
  760. if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
  761. return true
  762. }
  763. }
  764. return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
  765. }
  766. subsetList := reflect.ValueOf(subset)
  767. for i := 0; i < subsetList.Len(); i++ {
  768. element := subsetList.Index(i).Interface()
  769. ok, found := containsElement(list, element)
  770. if !ok {
  771. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
  772. }
  773. if !found {
  774. return true
  775. }
  776. }
  777. return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
  778. }
  779. // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
  780. // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
  781. // the number of appearances of each of them in both lists should match.
  782. //
  783. // assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
  784. func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
  785. if h, ok := t.(tHelper); ok {
  786. h.Helper()
  787. }
  788. if isEmpty(listA) && isEmpty(listB) {
  789. return true
  790. }
  791. if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) {
  792. return false
  793. }
  794. extraA, extraB := diffLists(listA, listB)
  795. if len(extraA) == 0 && len(extraB) == 0 {
  796. return true
  797. }
  798. return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...)
  799. }
  800. // isList checks that the provided value is array or slice.
  801. func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) {
  802. kind := reflect.TypeOf(list).Kind()
  803. if kind != reflect.Array && kind != reflect.Slice {
  804. return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind),
  805. msgAndArgs...)
  806. }
  807. return true
  808. }
  809. // diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B.
  810. // If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and
  811. // 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored.
  812. func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) {
  813. aValue := reflect.ValueOf(listA)
  814. bValue := reflect.ValueOf(listB)
  815. aLen := aValue.Len()
  816. bLen := bValue.Len()
  817. // Mark indexes in bValue that we already used
  818. visited := make([]bool, bLen)
  819. for i := 0; i < aLen; i++ {
  820. element := aValue.Index(i).Interface()
  821. found := false
  822. for j := 0; j < bLen; j++ {
  823. if visited[j] {
  824. continue
  825. }
  826. if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
  827. visited[j] = true
  828. found = true
  829. break
  830. }
  831. }
  832. if !found {
  833. extraA = append(extraA, element)
  834. }
  835. }
  836. for j := 0; j < bLen; j++ {
  837. if visited[j] {
  838. continue
  839. }
  840. extraB = append(extraB, bValue.Index(j).Interface())
  841. }
  842. return
  843. }
  844. func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string {
  845. var msg bytes.Buffer
  846. msg.WriteString("elements differ")
  847. if len(extraA) > 0 {
  848. msg.WriteString("\n\nextra elements in list A:\n")
  849. msg.WriteString(spewConfig.Sdump(extraA))
  850. }
  851. if len(extraB) > 0 {
  852. msg.WriteString("\n\nextra elements in list B:\n")
  853. msg.WriteString(spewConfig.Sdump(extraB))
  854. }
  855. msg.WriteString("\n\nlistA:\n")
  856. msg.WriteString(spewConfig.Sdump(listA))
  857. msg.WriteString("\n\nlistB:\n")
  858. msg.WriteString(spewConfig.Sdump(listB))
  859. return msg.String()
  860. }
  861. // Condition uses a Comparison to assert a complex condition.
  862. func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
  863. if h, ok := t.(tHelper); ok {
  864. h.Helper()
  865. }
  866. result := comp()
  867. if !result {
  868. Fail(t, "Condition failed!", msgAndArgs...)
  869. }
  870. return result
  871. }
  872. // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
  873. // methods, and represents a simple func that takes no arguments, and returns nothing.
  874. type PanicTestFunc func()
  875. // didPanic returns true if the function passed to it panics. Otherwise, it returns false.
  876. func didPanic(f PanicTestFunc) (didPanic bool, message interface{}, stack string) {
  877. didPanic = true
  878. defer func() {
  879. message = recover()
  880. if didPanic {
  881. stack = string(debug.Stack())
  882. }
  883. }()
  884. // call the target function
  885. f()
  886. didPanic = false
  887. return
  888. }
  889. // Panics asserts that the code inside the specified PanicTestFunc panics.
  890. //
  891. // assert.Panics(t, func(){ GoCrazy() })
  892. func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  893. if h, ok := t.(tHelper); ok {
  894. h.Helper()
  895. }
  896. if funcDidPanic, panicValue, _ := didPanic(f); !funcDidPanic {
  897. return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
  898. }
  899. return true
  900. }
  901. // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
  902. // the recovered panic value equals the expected panic value.
  903. //
  904. // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
  905. func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  906. if h, ok := t.(tHelper); ok {
  907. h.Helper()
  908. }
  909. funcDidPanic, panicValue, panickedStack := didPanic(f)
  910. if !funcDidPanic {
  911. return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
  912. }
  913. if panicValue != expected {
  914. 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...)
  915. }
  916. return true
  917. }
  918. // PanicsWithError asserts that the code inside the specified PanicTestFunc
  919. // panics, and that the recovered panic value is an error that satisfies the
  920. // EqualError comparison.
  921. //
  922. // assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })
  923. func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  924. if h, ok := t.(tHelper); ok {
  925. h.Helper()
  926. }
  927. funcDidPanic, panicValue, panickedStack := didPanic(f)
  928. if !funcDidPanic {
  929. return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
  930. }
  931. panicErr, ok := panicValue.(error)
  932. if !ok || panicErr.Error() != errString {
  933. 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...)
  934. }
  935. return true
  936. }
  937. // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
  938. //
  939. // assert.NotPanics(t, func(){ RemainCalm() })
  940. func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  941. if h, ok := t.(tHelper); ok {
  942. h.Helper()
  943. }
  944. if funcDidPanic, panicValue, panickedStack := didPanic(f); funcDidPanic {
  945. return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v\n\tPanic stack:\t%s", f, panicValue, panickedStack), msgAndArgs...)
  946. }
  947. return true
  948. }
  949. // WithinDuration asserts that the two times are within duration delta of each other.
  950. //
  951. // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
  952. func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
  953. if h, ok := t.(tHelper); ok {
  954. h.Helper()
  955. }
  956. dt := expected.Sub(actual)
  957. if dt < -delta || dt > delta {
  958. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
  959. }
  960. return true
  961. }
  962. // WithinRange asserts that a time is within a time range (inclusive).
  963. //
  964. // assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))
  965. func WithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool {
  966. if h, ok := t.(tHelper); ok {
  967. h.Helper()
  968. }
  969. if end.Before(start) {
  970. return Fail(t, "Start should be before end", msgAndArgs...)
  971. }
  972. if actual.Before(start) {
  973. 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...)
  974. } else if actual.After(end) {
  975. 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...)
  976. }
  977. return true
  978. }
  979. func toFloat(x interface{}) (float64, bool) {
  980. var xf float64
  981. xok := true
  982. switch xn := x.(type) {
  983. case uint:
  984. xf = float64(xn)
  985. case uint8:
  986. xf = float64(xn)
  987. case uint16:
  988. xf = float64(xn)
  989. case uint32:
  990. xf = float64(xn)
  991. case uint64:
  992. xf = float64(xn)
  993. case int:
  994. xf = float64(xn)
  995. case int8:
  996. xf = float64(xn)
  997. case int16:
  998. xf = float64(xn)
  999. case int32:
  1000. xf = float64(xn)
  1001. case int64:
  1002. xf = float64(xn)
  1003. case float32:
  1004. xf = float64(xn)
  1005. case float64:
  1006. xf = xn
  1007. case time.Duration:
  1008. xf = float64(xn)
  1009. default:
  1010. xok = false
  1011. }
  1012. return xf, xok
  1013. }
  1014. // InDelta asserts that the two numerals are within delta of each other.
  1015. //
  1016. // assert.InDelta(t, math.Pi, 22/7.0, 0.01)
  1017. func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  1018. if h, ok := t.(tHelper); ok {
  1019. h.Helper()
  1020. }
  1021. af, aok := toFloat(expected)
  1022. bf, bok := toFloat(actual)
  1023. if !aok || !bok {
  1024. return Fail(t, "Parameters must be numerical", msgAndArgs...)
  1025. }
  1026. if math.IsNaN(af) && math.IsNaN(bf) {
  1027. return true
  1028. }
  1029. if math.IsNaN(af) {
  1030. return Fail(t, "Expected must not be NaN", msgAndArgs...)
  1031. }
  1032. if math.IsNaN(bf) {
  1033. return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
  1034. }
  1035. dt := af - bf
  1036. if dt < -delta || dt > delta {
  1037. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
  1038. }
  1039. return true
  1040. }
  1041. // InDeltaSlice is the same as InDelta, except it compares two slices.
  1042. func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  1043. if h, ok := t.(tHelper); ok {
  1044. h.Helper()
  1045. }
  1046. if expected == nil || actual == nil ||
  1047. reflect.TypeOf(actual).Kind() != reflect.Slice ||
  1048. reflect.TypeOf(expected).Kind() != reflect.Slice {
  1049. return Fail(t, "Parameters must be slice", msgAndArgs...)
  1050. }
  1051. actualSlice := reflect.ValueOf(actual)
  1052. expectedSlice := reflect.ValueOf(expected)
  1053. for i := 0; i < actualSlice.Len(); i++ {
  1054. result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
  1055. if !result {
  1056. return result
  1057. }
  1058. }
  1059. return true
  1060. }
  1061. // InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
  1062. func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  1063. if h, ok := t.(tHelper); ok {
  1064. h.Helper()
  1065. }
  1066. if expected == nil || actual == nil ||
  1067. reflect.TypeOf(actual).Kind() != reflect.Map ||
  1068. reflect.TypeOf(expected).Kind() != reflect.Map {
  1069. return Fail(t, "Arguments must be maps", msgAndArgs...)
  1070. }
  1071. expectedMap := reflect.ValueOf(expected)
  1072. actualMap := reflect.ValueOf(actual)
  1073. if expectedMap.Len() != actualMap.Len() {
  1074. return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
  1075. }
  1076. for _, k := range expectedMap.MapKeys() {
  1077. ev := expectedMap.MapIndex(k)
  1078. av := actualMap.MapIndex(k)
  1079. if !ev.IsValid() {
  1080. return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
  1081. }
  1082. if !av.IsValid() {
  1083. return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
  1084. }
  1085. if !InDelta(
  1086. t,
  1087. ev.Interface(),
  1088. av.Interface(),
  1089. delta,
  1090. msgAndArgs...,
  1091. ) {
  1092. return false
  1093. }
  1094. }
  1095. return true
  1096. }
  1097. func calcRelativeError(expected, actual interface{}) (float64, error) {
  1098. af, aok := toFloat(expected)
  1099. bf, bok := toFloat(actual)
  1100. if !aok || !bok {
  1101. return 0, fmt.Errorf("Parameters must be numerical")
  1102. }
  1103. if math.IsNaN(af) && math.IsNaN(bf) {
  1104. return 0, nil
  1105. }
  1106. if math.IsNaN(af) {
  1107. return 0, errors.New("expected value must not be NaN")
  1108. }
  1109. if af == 0 {
  1110. return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
  1111. }
  1112. if math.IsNaN(bf) {
  1113. return 0, errors.New("actual value must not be NaN")
  1114. }
  1115. return math.Abs(af-bf) / math.Abs(af), nil
  1116. }
  1117. // InEpsilon asserts that expected and actual have a relative error less than epsilon
  1118. func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
  1119. if h, ok := t.(tHelper); ok {
  1120. h.Helper()
  1121. }
  1122. if math.IsNaN(epsilon) {
  1123. return Fail(t, "epsilon must not be NaN")
  1124. }
  1125. actualEpsilon, err := calcRelativeError(expected, actual)
  1126. if err != nil {
  1127. return Fail(t, err.Error(), msgAndArgs...)
  1128. }
  1129. if actualEpsilon > epsilon {
  1130. return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
  1131. " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
  1132. }
  1133. return true
  1134. }
  1135. // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
  1136. func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
  1137. if h, ok := t.(tHelper); ok {
  1138. h.Helper()
  1139. }
  1140. if expected == nil || actual == nil ||
  1141. reflect.TypeOf(actual).Kind() != reflect.Slice ||
  1142. reflect.TypeOf(expected).Kind() != reflect.Slice {
  1143. return Fail(t, "Parameters must be slice", msgAndArgs...)
  1144. }
  1145. actualSlice := reflect.ValueOf(actual)
  1146. expectedSlice := reflect.ValueOf(expected)
  1147. for i := 0; i < actualSlice.Len(); i++ {
  1148. result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
  1149. if !result {
  1150. return result
  1151. }
  1152. }
  1153. return true
  1154. }
  1155. /*
  1156. Errors
  1157. */
  1158. // NoError asserts that a function returned no error (i.e. `nil`).
  1159. //
  1160. // actualObj, err := SomeFunction()
  1161. // if assert.NoError(t, err) {
  1162. // assert.Equal(t, expectedObj, actualObj)
  1163. // }
  1164. func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
  1165. if err != nil {
  1166. if h, ok := t.(tHelper); ok {
  1167. h.Helper()
  1168. }
  1169. return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
  1170. }
  1171. return true
  1172. }
  1173. // Error asserts that a function returned an error (i.e. not `nil`).
  1174. //
  1175. // actualObj, err := SomeFunction()
  1176. // if assert.Error(t, err) {
  1177. // assert.Equal(t, expectedError, err)
  1178. // }
  1179. func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
  1180. if err == nil {
  1181. if h, ok := t.(tHelper); ok {
  1182. h.Helper()
  1183. }
  1184. return Fail(t, "An error is expected but got nil.", msgAndArgs...)
  1185. }
  1186. return true
  1187. }
  1188. // EqualError asserts that a function returned an error (i.e. not `nil`)
  1189. // and that it is equal to the provided error.
  1190. //
  1191. // actualObj, err := SomeFunction()
  1192. // assert.EqualError(t, err, expectedErrorString)
  1193. func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
  1194. if h, ok := t.(tHelper); ok {
  1195. h.Helper()
  1196. }
  1197. if !Error(t, theError, msgAndArgs...) {
  1198. return false
  1199. }
  1200. expected := errString
  1201. actual := theError.Error()
  1202. // don't need to use deep equals here, we know they are both strings
  1203. if expected != actual {
  1204. return Fail(t, fmt.Sprintf("Error message not equal:\n"+
  1205. "expected: %q\n"+
  1206. "actual : %q", expected, actual), msgAndArgs...)
  1207. }
  1208. return true
  1209. }
  1210. // ErrorContains asserts that a function returned an error (i.e. not `nil`)
  1211. // and that the error contains the specified substring.
  1212. //
  1213. // actualObj, err := SomeFunction()
  1214. // assert.ErrorContains(t, err, expectedErrorSubString)
  1215. func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool {
  1216. if h, ok := t.(tHelper); ok {
  1217. h.Helper()
  1218. }
  1219. if !Error(t, theError, msgAndArgs...) {
  1220. return false
  1221. }
  1222. actual := theError.Error()
  1223. if !strings.Contains(actual, contains) {
  1224. return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...)
  1225. }
  1226. return true
  1227. }
  1228. // matchRegexp return true if a specified regexp matches a string.
  1229. func matchRegexp(rx interface{}, str interface{}) bool {
  1230. var r *regexp.Regexp
  1231. if rr, ok := rx.(*regexp.Regexp); ok {
  1232. r = rr
  1233. } else {
  1234. r = regexp.MustCompile(fmt.Sprint(rx))
  1235. }
  1236. return (r.FindStringIndex(fmt.Sprint(str)) != nil)
  1237. }
  1238. // Regexp asserts that a specified regexp matches a string.
  1239. //
  1240. // assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
  1241. // assert.Regexp(t, "start...$", "it's not starting")
  1242. func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
  1243. if h, ok := t.(tHelper); ok {
  1244. h.Helper()
  1245. }
  1246. match := matchRegexp(rx, str)
  1247. if !match {
  1248. Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
  1249. }
  1250. return match
  1251. }
  1252. // NotRegexp asserts that a specified regexp does not match a string.
  1253. //
  1254. // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
  1255. // assert.NotRegexp(t, "^start", "it's not starting")
  1256. func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
  1257. if h, ok := t.(tHelper); ok {
  1258. h.Helper()
  1259. }
  1260. match := matchRegexp(rx, str)
  1261. if match {
  1262. Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
  1263. }
  1264. return !match
  1265. }
  1266. // Zero asserts that i is the zero value for its type.
  1267. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
  1268. if h, ok := t.(tHelper); ok {
  1269. h.Helper()
  1270. }
  1271. if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
  1272. return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
  1273. }
  1274. return true
  1275. }
  1276. // NotZero asserts that i is not the zero value for its type.
  1277. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
  1278. if h, ok := t.(tHelper); ok {
  1279. h.Helper()
  1280. }
  1281. if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
  1282. return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
  1283. }
  1284. return true
  1285. }
  1286. // FileExists checks whether a file exists in the given path. It also fails if
  1287. // the path points to a directory or there is an error when trying to check the file.
  1288. func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1289. if h, ok := t.(tHelper); ok {
  1290. h.Helper()
  1291. }
  1292. info, err := os.Lstat(path)
  1293. if err != nil {
  1294. if os.IsNotExist(err) {
  1295. return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
  1296. }
  1297. return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
  1298. }
  1299. if info.IsDir() {
  1300. return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
  1301. }
  1302. return true
  1303. }
  1304. // NoFileExists checks whether a file does not exist in a given path. It fails
  1305. // if the path points to an existing _file_ only.
  1306. func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1307. if h, ok := t.(tHelper); ok {
  1308. h.Helper()
  1309. }
  1310. info, err := os.Lstat(path)
  1311. if err != nil {
  1312. return true
  1313. }
  1314. if info.IsDir() {
  1315. return true
  1316. }
  1317. return Fail(t, fmt.Sprintf("file %q exists", path), msgAndArgs...)
  1318. }
  1319. // DirExists checks whether a directory exists in the given path. It also fails
  1320. // if the path is a file rather a directory or there is an error checking whether it exists.
  1321. func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1322. if h, ok := t.(tHelper); ok {
  1323. h.Helper()
  1324. }
  1325. info, err := os.Lstat(path)
  1326. if err != nil {
  1327. if os.IsNotExist(err) {
  1328. return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
  1329. }
  1330. return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
  1331. }
  1332. if !info.IsDir() {
  1333. return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
  1334. }
  1335. return true
  1336. }
  1337. // NoDirExists checks whether a directory does not exist in the given path.
  1338. // It fails if the path points to an existing _directory_ only.
  1339. func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1340. if h, ok := t.(tHelper); ok {
  1341. h.Helper()
  1342. }
  1343. info, err := os.Lstat(path)
  1344. if err != nil {
  1345. if os.IsNotExist(err) {
  1346. return true
  1347. }
  1348. return true
  1349. }
  1350. if !info.IsDir() {
  1351. return true
  1352. }
  1353. return Fail(t, fmt.Sprintf("directory %q exists", path), msgAndArgs...)
  1354. }
  1355. // JSONEq asserts that two JSON strings are equivalent.
  1356. //
  1357. // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
  1358. func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
  1359. if h, ok := t.(tHelper); ok {
  1360. h.Helper()
  1361. }
  1362. var expectedJSONAsInterface, actualJSONAsInterface interface{}
  1363. if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
  1364. return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
  1365. }
  1366. if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
  1367. return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
  1368. }
  1369. return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
  1370. }
  1371. // YAMLEq asserts that two YAML strings are equivalent.
  1372. func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
  1373. if h, ok := t.(tHelper); ok {
  1374. h.Helper()
  1375. }
  1376. var expectedYAMLAsInterface, actualYAMLAsInterface interface{}
  1377. if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil {
  1378. return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...)
  1379. }
  1380. if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil {
  1381. return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...)
  1382. }
  1383. return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...)
  1384. }
  1385. func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
  1386. t := reflect.TypeOf(v)
  1387. k := t.Kind()
  1388. if k == reflect.Ptr {
  1389. t = t.Elem()
  1390. k = t.Kind()
  1391. }
  1392. return t, k
  1393. }
  1394. // diff returns a diff of both values as long as both are of the same type and
  1395. // are a struct, map, slice, array or string. Otherwise it returns an empty string.
  1396. func diff(expected interface{}, actual interface{}) string {
  1397. if expected == nil || actual == nil {
  1398. return ""
  1399. }
  1400. et, ek := typeAndKind(expected)
  1401. at, _ := typeAndKind(actual)
  1402. if et != at {
  1403. return ""
  1404. }
  1405. if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
  1406. return ""
  1407. }
  1408. var e, a string
  1409. switch et {
  1410. case reflect.TypeOf(""):
  1411. e = reflect.ValueOf(expected).String()
  1412. a = reflect.ValueOf(actual).String()
  1413. case reflect.TypeOf(time.Time{}):
  1414. e = spewConfigStringerEnabled.Sdump(expected)
  1415. a = spewConfigStringerEnabled.Sdump(actual)
  1416. default:
  1417. e = spewConfig.Sdump(expected)
  1418. a = spewConfig.Sdump(actual)
  1419. }
  1420. diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
  1421. A: difflib.SplitLines(e),
  1422. B: difflib.SplitLines(a),
  1423. FromFile: "Expected",
  1424. FromDate: "",
  1425. ToFile: "Actual",
  1426. ToDate: "",
  1427. Context: 1,
  1428. })
  1429. return "\n\nDiff:\n" + diff
  1430. }
  1431. func isFunction(arg interface{}) bool {
  1432. if arg == nil {
  1433. return false
  1434. }
  1435. return reflect.TypeOf(arg).Kind() == reflect.Func
  1436. }
  1437. var spewConfig = spew.ConfigState{
  1438. Indent: " ",
  1439. DisablePointerAddresses: true,
  1440. DisableCapacities: true,
  1441. SortKeys: true,
  1442. DisableMethods: true,
  1443. MaxDepth: 10,
  1444. }
  1445. var spewConfigStringerEnabled = spew.ConfigState{
  1446. Indent: " ",
  1447. DisablePointerAddresses: true,
  1448. DisableCapacities: true,
  1449. SortKeys: true,
  1450. MaxDepth: 10,
  1451. }
  1452. type tHelper interface {
  1453. Helper()
  1454. }
  1455. // Eventually asserts that given condition will be met in waitFor time,
  1456. // periodically checking target function each tick.
  1457. //
  1458. // assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
  1459. func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
  1460. if h, ok := t.(tHelper); ok {
  1461. h.Helper()
  1462. }
  1463. ch := make(chan bool, 1)
  1464. timer := time.NewTimer(waitFor)
  1465. defer timer.Stop()
  1466. ticker := time.NewTicker(tick)
  1467. defer ticker.Stop()
  1468. for tick := ticker.C; ; {
  1469. select {
  1470. case <-timer.C:
  1471. return Fail(t, "Condition never satisfied", msgAndArgs...)
  1472. case <-tick:
  1473. tick = nil
  1474. go func() { ch <- condition() }()
  1475. case v := <-ch:
  1476. if v {
  1477. return true
  1478. }
  1479. tick = ticker.C
  1480. }
  1481. }
  1482. }
  1483. // Never asserts that the given condition doesn't satisfy in waitFor time,
  1484. // periodically checking the target function each tick.
  1485. //
  1486. // assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)
  1487. func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool {
  1488. if h, ok := t.(tHelper); ok {
  1489. h.Helper()
  1490. }
  1491. ch := make(chan bool, 1)
  1492. timer := time.NewTimer(waitFor)
  1493. defer timer.Stop()
  1494. ticker := time.NewTicker(tick)
  1495. defer ticker.Stop()
  1496. for tick := ticker.C; ; {
  1497. select {
  1498. case <-timer.C:
  1499. return true
  1500. case <-tick:
  1501. tick = nil
  1502. go func() { ch <- condition() }()
  1503. case v := <-ch:
  1504. if v {
  1505. return Fail(t, "Condition satisfied", msgAndArgs...)
  1506. }
  1507. tick = ticker.C
  1508. }
  1509. }
  1510. }
  1511. // ErrorIs asserts that at least one of the errors in err's chain matches target.
  1512. // This is a wrapper for errors.Is.
  1513. func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
  1514. if h, ok := t.(tHelper); ok {
  1515. h.Helper()
  1516. }
  1517. if errors.Is(err, target) {
  1518. return true
  1519. }
  1520. var expectedText string
  1521. if target != nil {
  1522. expectedText = target.Error()
  1523. }
  1524. chain := buildErrorChainString(err)
  1525. return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+
  1526. "expected: %q\n"+
  1527. "in chain: %s", expectedText, chain,
  1528. ), msgAndArgs...)
  1529. }
  1530. // NotErrorIs asserts that at none of the errors in err's chain matches target.
  1531. // This is a wrapper for errors.Is.
  1532. func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
  1533. if h, ok := t.(tHelper); ok {
  1534. h.Helper()
  1535. }
  1536. if !errors.Is(err, target) {
  1537. return true
  1538. }
  1539. var expectedText string
  1540. if target != nil {
  1541. expectedText = target.Error()
  1542. }
  1543. chain := buildErrorChainString(err)
  1544. return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
  1545. "found: %q\n"+
  1546. "in chain: %s", expectedText, chain,
  1547. ), msgAndArgs...)
  1548. }
  1549. // ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value.
  1550. // This is a wrapper for errors.As.
  1551. func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool {
  1552. if h, ok := t.(tHelper); ok {
  1553. h.Helper()
  1554. }
  1555. if errors.As(err, target) {
  1556. return true
  1557. }
  1558. chain := buildErrorChainString(err)
  1559. return Fail(t, fmt.Sprintf("Should be in error chain:\n"+
  1560. "expected: %q\n"+
  1561. "in chain: %s", target, chain,
  1562. ), msgAndArgs...)
  1563. }
  1564. func buildErrorChainString(err error) string {
  1565. if err == nil {
  1566. return ""
  1567. }
  1568. e := errors.Unwrap(err)
  1569. chain := fmt.Sprintf("%q", err.Error())
  1570. for e != nil {
  1571. chain += fmt.Sprintf("\n\t%q", e.Error())
  1572. e = errors.Unwrap(e)
  1573. }
  1574. return chain
  1575. }