assertions.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  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. "strings"
  14. "time"
  15. "unicode"
  16. "unicode/utf8"
  17. "github.com/davecgh/go-spew/spew"
  18. "github.com/pmezard/go-difflib/difflib"
  19. )
  20. //go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_format.go.tmpl
  21. // TestingT is an interface wrapper around *testing.T
  22. type TestingT interface {
  23. Errorf(format string, args ...interface{})
  24. }
  25. // ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
  26. // for table driven tests.
  27. type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
  28. // ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
  29. // for table driven tests.
  30. type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
  31. // BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
  32. // for table driven tests.
  33. type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
  34. // ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
  35. // for table driven tests.
  36. type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
  37. // Comparison a custom function that returns true on success and false on failure
  38. type Comparison func() (success bool)
  39. /*
  40. Helper functions
  41. */
  42. // ObjectsAreEqual determines if two objects are considered equal.
  43. //
  44. // This function does no assertion of any kind.
  45. func ObjectsAreEqual(expected, actual interface{}) bool {
  46. if expected == nil || actual == nil {
  47. return expected == actual
  48. }
  49. exp, ok := expected.([]byte)
  50. if !ok {
  51. return reflect.DeepEqual(expected, actual)
  52. }
  53. act, ok := actual.([]byte)
  54. if !ok {
  55. return false
  56. }
  57. if exp == nil || act == nil {
  58. return exp == nil && act == nil
  59. }
  60. return bytes.Equal(exp, act)
  61. }
  62. // ObjectsAreEqualValues gets whether two objects are equal, or if their
  63. // values are equal.
  64. func ObjectsAreEqualValues(expected, actual interface{}) bool {
  65. if ObjectsAreEqual(expected, actual) {
  66. return true
  67. }
  68. actualType := reflect.TypeOf(actual)
  69. if actualType == nil {
  70. return false
  71. }
  72. expectedValue := reflect.ValueOf(expected)
  73. if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
  74. // Attempt comparison after type conversion
  75. return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
  76. }
  77. return false
  78. }
  79. /* CallerInfo is necessary because the assert functions use the testing object
  80. internally, causing it to print the file:line of the assert method, rather than where
  81. the problem actually occurred in calling code.*/
  82. // CallerInfo returns an array of strings containing the file and line number
  83. // of each stack frame leading from the current test to the assert call that
  84. // failed.
  85. func CallerInfo() []string {
  86. pc := uintptr(0)
  87. file := ""
  88. line := 0
  89. ok := false
  90. name := ""
  91. callers := []string{}
  92. for i := 0; ; i++ {
  93. pc, file, line, ok = runtime.Caller(i)
  94. if !ok {
  95. // The breaks below failed to terminate the loop, and we ran off the
  96. // end of the call stack.
  97. break
  98. }
  99. // This is a huge edge case, but it will panic if this is the case, see #180
  100. if file == "<autogenerated>" {
  101. break
  102. }
  103. f := runtime.FuncForPC(pc)
  104. if f == nil {
  105. break
  106. }
  107. name = f.Name()
  108. // testing.tRunner is the standard library function that calls
  109. // tests. Subtests are called directly by tRunner, without going through
  110. // the Test/Benchmark/Example function that contains the t.Run calls, so
  111. // with subtests we should break when we hit tRunner, without adding it
  112. // to the list of callers.
  113. if name == "testing.tRunner" {
  114. break
  115. }
  116. parts := strings.Split(file, "/")
  117. file = parts[len(parts)-1]
  118. if len(parts) > 1 {
  119. dir := parts[len(parts)-2]
  120. if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" {
  121. callers = append(callers, fmt.Sprintf("%s:%d", file, line))
  122. }
  123. }
  124. // Drop the package
  125. segments := strings.Split(name, ".")
  126. name = segments[len(segments)-1]
  127. if isTest(name, "Test") ||
  128. isTest(name, "Benchmark") ||
  129. isTest(name, "Example") {
  130. break
  131. }
  132. }
  133. return callers
  134. }
  135. // Stolen from the `go test` tool.
  136. // isTest tells whether name looks like a test (or benchmark, according to prefix).
  137. // It is a Test (say) if there is a character after Test that is not a lower-case letter.
  138. // We don't want TesticularCancer.
  139. func isTest(name, prefix string) bool {
  140. if !strings.HasPrefix(name, prefix) {
  141. return false
  142. }
  143. if len(name) == len(prefix) { // "Test" is ok
  144. return true
  145. }
  146. rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
  147. return !unicode.IsLower(rune)
  148. }
  149. func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
  150. if len(msgAndArgs) == 0 || msgAndArgs == nil {
  151. return ""
  152. }
  153. if len(msgAndArgs) == 1 {
  154. msg := msgAndArgs[0]
  155. if msgAsStr, ok := msg.(string); ok {
  156. return msgAsStr
  157. }
  158. return fmt.Sprintf("%+v", msg)
  159. }
  160. if len(msgAndArgs) > 1 {
  161. return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
  162. }
  163. return ""
  164. }
  165. // Aligns the provided message so that all lines after the first line start at the same location as the first line.
  166. // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab).
  167. // The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the
  168. // basis on which the alignment occurs).
  169. func indentMessageLines(message string, longestLabelLen int) string {
  170. outBuf := new(bytes.Buffer)
  171. for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
  172. // no need to align first line because it starts at the correct location (after the label)
  173. if i != 0 {
  174. // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
  175. outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
  176. }
  177. outBuf.WriteString(scanner.Text())
  178. }
  179. return outBuf.String()
  180. }
  181. type failNower interface {
  182. FailNow()
  183. }
  184. // FailNow fails test
  185. func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
  186. if h, ok := t.(tHelper); ok {
  187. h.Helper()
  188. }
  189. Fail(t, failureMessage, msgAndArgs...)
  190. // We cannot extend TestingT with FailNow() and
  191. // maintain backwards compatibility, so we fallback
  192. // to panicking when FailNow is not available in
  193. // TestingT.
  194. // See issue #263
  195. if t, ok := t.(failNower); ok {
  196. t.FailNow()
  197. } else {
  198. panic("test failed and t is missing `FailNow()`")
  199. }
  200. return false
  201. }
  202. // Fail reports a failure through
  203. func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool {
  204. if h, ok := t.(tHelper); ok {
  205. h.Helper()
  206. }
  207. content := []labeledContent{
  208. {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")},
  209. {"Error", failureMessage},
  210. }
  211. // Add test name if the Go version supports it
  212. if n, ok := t.(interface {
  213. Name() string
  214. }); ok {
  215. content = append(content, labeledContent{"Test", n.Name()})
  216. }
  217. message := messageFromMsgAndArgs(msgAndArgs...)
  218. if len(message) > 0 {
  219. content = append(content, labeledContent{"Messages", message})
  220. }
  221. t.Errorf("\n%s", ""+labeledOutput(content...))
  222. return false
  223. }
  224. type labeledContent struct {
  225. label string
  226. content string
  227. }
  228. // labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner:
  229. //
  230. // \t{{label}}:{{align_spaces}}\t{{content}}\n
  231. //
  232. // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label.
  233. // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this
  234. // alignment is achieved, "\t{{content}}\n" is added for the output.
  235. //
  236. // 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.
  237. func labeledOutput(content ...labeledContent) string {
  238. longestLabel := 0
  239. for _, v := range content {
  240. if len(v.label) > longestLabel {
  241. longestLabel = len(v.label)
  242. }
  243. }
  244. var output string
  245. for _, v := range content {
  246. output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n"
  247. }
  248. return output
  249. }
  250. // Implements asserts that an object is implemented by the specified interface.
  251. //
  252. // assert.Implements(t, (*MyInterface)(nil), new(MyObject))
  253. func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool {
  254. if h, ok := t.(tHelper); ok {
  255. h.Helper()
  256. }
  257. interfaceType := reflect.TypeOf(interfaceObject).Elem()
  258. if object == nil {
  259. return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...)
  260. }
  261. if !reflect.TypeOf(object).Implements(interfaceType) {
  262. return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...)
  263. }
  264. return true
  265. }
  266. // IsType asserts that the specified objects are of the same type.
  267. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool {
  268. if h, ok := t.(tHelper); ok {
  269. h.Helper()
  270. }
  271. if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) {
  272. return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...)
  273. }
  274. return true
  275. }
  276. // Equal asserts that two objects are equal.
  277. //
  278. // assert.Equal(t, 123, 123)
  279. //
  280. // Pointer variable equality is determined based on the equality of the
  281. // referenced values (as opposed to the memory addresses). Function equality
  282. // cannot be determined and will always fail.
  283. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  284. if h, ok := t.(tHelper); ok {
  285. h.Helper()
  286. }
  287. if err := validateEqualArgs(expected, actual); err != nil {
  288. return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)",
  289. expected, actual, err), msgAndArgs...)
  290. }
  291. if !ObjectsAreEqual(expected, actual) {
  292. diff := diff(expected, actual)
  293. expected, actual = formatUnequalValues(expected, actual)
  294. return Fail(t, fmt.Sprintf("Not equal: \n"+
  295. "expected: %s\n"+
  296. "actual : %s%s", expected, actual, diff), msgAndArgs...)
  297. }
  298. return true
  299. }
  300. // formatUnequalValues takes two values of arbitrary types and returns string
  301. // representations appropriate to be presented to the user.
  302. //
  303. // If the values are not of like type, the returned strings will be prefixed
  304. // with the type name, and the value will be enclosed in parenthesis similar
  305. // to a type conversion in the Go grammar.
  306. func formatUnequalValues(expected, actual interface{}) (e string, a string) {
  307. if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
  308. return fmt.Sprintf("%T(%#v)", expected, expected),
  309. fmt.Sprintf("%T(%#v)", actual, actual)
  310. }
  311. return fmt.Sprintf("%#v", expected),
  312. fmt.Sprintf("%#v", actual)
  313. }
  314. // EqualValues asserts that two objects are equal or convertable to the same types
  315. // and equal.
  316. //
  317. // assert.EqualValues(t, uint32(123), int32(123))
  318. func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  319. if h, ok := t.(tHelper); ok {
  320. h.Helper()
  321. }
  322. if !ObjectsAreEqualValues(expected, actual) {
  323. diff := diff(expected, actual)
  324. expected, actual = formatUnequalValues(expected, actual)
  325. return Fail(t, fmt.Sprintf("Not equal: \n"+
  326. "expected: %s\n"+
  327. "actual : %s%s", expected, actual, diff), msgAndArgs...)
  328. }
  329. return true
  330. }
  331. // Exactly asserts that two objects are equal in value and type.
  332. //
  333. // assert.Exactly(t, int32(123), int64(123))
  334. func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  335. if h, ok := t.(tHelper); ok {
  336. h.Helper()
  337. }
  338. aType := reflect.TypeOf(expected)
  339. bType := reflect.TypeOf(actual)
  340. if aType != bType {
  341. return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...)
  342. }
  343. return Equal(t, expected, actual, msgAndArgs...)
  344. }
  345. // NotNil asserts that the specified object is not nil.
  346. //
  347. // assert.NotNil(t, err)
  348. func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  349. if h, ok := t.(tHelper); ok {
  350. h.Helper()
  351. }
  352. if !isNil(object) {
  353. return true
  354. }
  355. return Fail(t, "Expected value not to be nil.", msgAndArgs...)
  356. }
  357. // containsKind checks if a specified kind in the slice of kinds.
  358. func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool {
  359. for i := 0; i < len(kinds); i++ {
  360. if kind == kinds[i] {
  361. return true
  362. }
  363. }
  364. return false
  365. }
  366. // isNil checks if a specified object is nil or not, without Failing.
  367. func isNil(object interface{}) bool {
  368. if object == nil {
  369. return true
  370. }
  371. value := reflect.ValueOf(object)
  372. kind := value.Kind()
  373. isNilableKind := containsKind(
  374. []reflect.Kind{
  375. reflect.Chan, reflect.Func,
  376. reflect.Interface, reflect.Map,
  377. reflect.Ptr, reflect.Slice},
  378. kind)
  379. if isNilableKind && value.IsNil() {
  380. return true
  381. }
  382. return false
  383. }
  384. // Nil asserts that the specified object is nil.
  385. //
  386. // assert.Nil(t, err)
  387. func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  388. if h, ok := t.(tHelper); ok {
  389. h.Helper()
  390. }
  391. if isNil(object) {
  392. return true
  393. }
  394. return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
  395. }
  396. // isEmpty gets whether the specified object is considered empty or not.
  397. func isEmpty(object interface{}) bool {
  398. // get nil case out of the way
  399. if object == nil {
  400. return true
  401. }
  402. objValue := reflect.ValueOf(object)
  403. switch objValue.Kind() {
  404. // collection types are empty when they have no element
  405. case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
  406. return objValue.Len() == 0
  407. // pointers are empty if nil or if the value they point to is empty
  408. case reflect.Ptr:
  409. if objValue.IsNil() {
  410. return true
  411. }
  412. deref := objValue.Elem().Interface()
  413. return isEmpty(deref)
  414. // for all other types, compare against the zero value
  415. default:
  416. zero := reflect.Zero(objValue.Type())
  417. return reflect.DeepEqual(object, zero.Interface())
  418. }
  419. }
  420. // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either
  421. // a slice or a channel with len == 0.
  422. //
  423. // assert.Empty(t, obj)
  424. func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  425. if h, ok := t.(tHelper); ok {
  426. h.Helper()
  427. }
  428. pass := isEmpty(object)
  429. if !pass {
  430. Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
  431. }
  432. return pass
  433. }
  434. // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either
  435. // a slice or a channel with len == 0.
  436. //
  437. // if assert.NotEmpty(t, obj) {
  438. // assert.Equal(t, "two", obj[1])
  439. // }
  440. func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
  441. if h, ok := t.(tHelper); ok {
  442. h.Helper()
  443. }
  444. pass := !isEmpty(object)
  445. if !pass {
  446. Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...)
  447. }
  448. return pass
  449. }
  450. // getLen try to get length of object.
  451. // return (false, 0) if impossible.
  452. func getLen(x interface{}) (ok bool, length int) {
  453. v := reflect.ValueOf(x)
  454. defer func() {
  455. if e := recover(); e != nil {
  456. ok = false
  457. }
  458. }()
  459. return true, v.Len()
  460. }
  461. // Len asserts that the specified object has specific length.
  462. // Len also fails if the object has a type that len() not accept.
  463. //
  464. // assert.Len(t, mySlice, 3)
  465. func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool {
  466. if h, ok := t.(tHelper); ok {
  467. h.Helper()
  468. }
  469. ok, l := getLen(object)
  470. if !ok {
  471. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...)
  472. }
  473. if l != length {
  474. return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
  475. }
  476. return true
  477. }
  478. // True asserts that the specified value is true.
  479. //
  480. // assert.True(t, myBool)
  481. func True(t TestingT, value bool, msgAndArgs ...interface{}) bool {
  482. if h, ok := t.(tHelper); ok {
  483. h.Helper()
  484. }
  485. if h, ok := t.(interface {
  486. Helper()
  487. }); ok {
  488. h.Helper()
  489. }
  490. if value != true {
  491. return Fail(t, "Should be true", msgAndArgs...)
  492. }
  493. return true
  494. }
  495. // False asserts that the specified value is false.
  496. //
  497. // assert.False(t, myBool)
  498. func False(t TestingT, value bool, msgAndArgs ...interface{}) bool {
  499. if h, ok := t.(tHelper); ok {
  500. h.Helper()
  501. }
  502. if value != false {
  503. return Fail(t, "Should be false", msgAndArgs...)
  504. }
  505. return true
  506. }
  507. // NotEqual asserts that the specified values are NOT equal.
  508. //
  509. // assert.NotEqual(t, obj1, obj2)
  510. //
  511. // Pointer variable equality is determined based on the equality of the
  512. // referenced values (as opposed to the memory addresses).
  513. func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool {
  514. if h, ok := t.(tHelper); ok {
  515. h.Helper()
  516. }
  517. if err := validateEqualArgs(expected, actual); err != nil {
  518. return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)",
  519. expected, actual, err), msgAndArgs...)
  520. }
  521. if ObjectsAreEqual(expected, actual) {
  522. return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
  523. }
  524. return true
  525. }
  526. // containsElement try loop over the list check if the list includes the element.
  527. // return (false, false) if impossible.
  528. // return (true, false) if element was not found.
  529. // return (true, true) if element was found.
  530. func includeElement(list interface{}, element interface{}) (ok, found bool) {
  531. listValue := reflect.ValueOf(list)
  532. elementValue := reflect.ValueOf(element)
  533. defer func() {
  534. if e := recover(); e != nil {
  535. ok = false
  536. found = false
  537. }
  538. }()
  539. if reflect.TypeOf(list).Kind() == reflect.String {
  540. return true, strings.Contains(listValue.String(), elementValue.String())
  541. }
  542. if reflect.TypeOf(list).Kind() == reflect.Map {
  543. mapKeys := listValue.MapKeys()
  544. for i := 0; i < len(mapKeys); i++ {
  545. if ObjectsAreEqual(mapKeys[i].Interface(), element) {
  546. return true, true
  547. }
  548. }
  549. return true, false
  550. }
  551. for i := 0; i < listValue.Len(); i++ {
  552. if ObjectsAreEqual(listValue.Index(i).Interface(), element) {
  553. return true, true
  554. }
  555. }
  556. return true, false
  557. }
  558. // Contains asserts that the specified string, list(array, slice...) or map contains the
  559. // specified substring or element.
  560. //
  561. // assert.Contains(t, "Hello World", "World")
  562. // assert.Contains(t, ["Hello", "World"], "World")
  563. // assert.Contains(t, {"Hello": "World"}, "Hello")
  564. func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
  565. if h, ok := t.(tHelper); ok {
  566. h.Helper()
  567. }
  568. ok, found := includeElement(s, contains)
  569. if !ok {
  570. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
  571. }
  572. if !found {
  573. return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...)
  574. }
  575. return true
  576. }
  577. // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the
  578. // specified substring or element.
  579. //
  580. // assert.NotContains(t, "Hello World", "Earth")
  581. // assert.NotContains(t, ["Hello", "World"], "Earth")
  582. // assert.NotContains(t, {"Hello": "World"}, "Earth")
  583. func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool {
  584. if h, ok := t.(tHelper); ok {
  585. h.Helper()
  586. }
  587. ok, found := includeElement(s, contains)
  588. if !ok {
  589. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...)
  590. }
  591. if found {
  592. return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...)
  593. }
  594. return true
  595. }
  596. // Subset asserts that the specified list(array, slice...) contains all
  597. // elements given in the specified subset(array, slice...).
  598. //
  599. // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
  600. func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
  601. if h, ok := t.(tHelper); ok {
  602. h.Helper()
  603. }
  604. if subset == nil {
  605. return true // we consider nil to be equal to the nil set
  606. }
  607. subsetValue := reflect.ValueOf(subset)
  608. defer func() {
  609. if e := recover(); e != nil {
  610. ok = false
  611. }
  612. }()
  613. listKind := reflect.TypeOf(list).Kind()
  614. subsetKind := reflect.TypeOf(subset).Kind()
  615. if listKind != reflect.Array && listKind != reflect.Slice {
  616. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
  617. }
  618. if subsetKind != reflect.Array && subsetKind != reflect.Slice {
  619. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
  620. }
  621. for i := 0; i < subsetValue.Len(); i++ {
  622. element := subsetValue.Index(i).Interface()
  623. ok, found := includeElement(list, element)
  624. if !ok {
  625. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
  626. }
  627. if !found {
  628. return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...)
  629. }
  630. }
  631. return true
  632. }
  633. // NotSubset asserts that the specified list(array, slice...) contains not all
  634. // elements given in the specified subset(array, slice...).
  635. //
  636. // assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]")
  637. func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
  638. if h, ok := t.(tHelper); ok {
  639. h.Helper()
  640. }
  641. if subset == nil {
  642. return Fail(t, fmt.Sprintf("nil is the empty set which is a subset of every set"), msgAndArgs...)
  643. }
  644. subsetValue := reflect.ValueOf(subset)
  645. defer func() {
  646. if e := recover(); e != nil {
  647. ok = false
  648. }
  649. }()
  650. listKind := reflect.TypeOf(list).Kind()
  651. subsetKind := reflect.TypeOf(subset).Kind()
  652. if listKind != reflect.Array && listKind != reflect.Slice {
  653. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
  654. }
  655. if subsetKind != reflect.Array && subsetKind != reflect.Slice {
  656. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
  657. }
  658. for i := 0; i < subsetValue.Len(); i++ {
  659. element := subsetValue.Index(i).Interface()
  660. ok, found := includeElement(list, element)
  661. if !ok {
  662. return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...)
  663. }
  664. if !found {
  665. return true
  666. }
  667. }
  668. return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
  669. }
  670. // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
  671. // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements,
  672. // the number of appearances of each of them in both lists should match.
  673. //
  674. // assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
  675. func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) {
  676. if h, ok := t.(tHelper); ok {
  677. h.Helper()
  678. }
  679. if isEmpty(listA) && isEmpty(listB) {
  680. return true
  681. }
  682. aKind := reflect.TypeOf(listA).Kind()
  683. bKind := reflect.TypeOf(listB).Kind()
  684. if aKind != reflect.Array && aKind != reflect.Slice {
  685. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listA, aKind), msgAndArgs...)
  686. }
  687. if bKind != reflect.Array && bKind != reflect.Slice {
  688. return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listB, bKind), msgAndArgs...)
  689. }
  690. aValue := reflect.ValueOf(listA)
  691. bValue := reflect.ValueOf(listB)
  692. aLen := aValue.Len()
  693. bLen := bValue.Len()
  694. if aLen != bLen {
  695. return Fail(t, fmt.Sprintf("lengths don't match: %d != %d", aLen, bLen), msgAndArgs...)
  696. }
  697. // Mark indexes in bValue that we already used
  698. visited := make([]bool, bLen)
  699. for i := 0; i < aLen; i++ {
  700. element := aValue.Index(i).Interface()
  701. found := false
  702. for j := 0; j < bLen; j++ {
  703. if visited[j] {
  704. continue
  705. }
  706. if ObjectsAreEqual(bValue.Index(j).Interface(), element) {
  707. visited[j] = true
  708. found = true
  709. break
  710. }
  711. }
  712. if !found {
  713. return Fail(t, fmt.Sprintf("element %s appears more times in %s than in %s", element, aValue, bValue), msgAndArgs...)
  714. }
  715. }
  716. return true
  717. }
  718. // Condition uses a Comparison to assert a complex condition.
  719. func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool {
  720. if h, ok := t.(tHelper); ok {
  721. h.Helper()
  722. }
  723. result := comp()
  724. if !result {
  725. Fail(t, "Condition failed!", msgAndArgs...)
  726. }
  727. return result
  728. }
  729. // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics
  730. // methods, and represents a simple func that takes no arguments, and returns nothing.
  731. type PanicTestFunc func()
  732. // didPanic returns true if the function passed to it panics. Otherwise, it returns false.
  733. func didPanic(f PanicTestFunc) (bool, interface{}) {
  734. didPanic := false
  735. var message interface{}
  736. func() {
  737. defer func() {
  738. if message = recover(); message != nil {
  739. didPanic = true
  740. }
  741. }()
  742. // call the target function
  743. f()
  744. }()
  745. return didPanic, message
  746. }
  747. // Panics asserts that the code inside the specified PanicTestFunc panics.
  748. //
  749. // assert.Panics(t, func(){ GoCrazy() })
  750. func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  751. if h, ok := t.(tHelper); ok {
  752. h.Helper()
  753. }
  754. if funcDidPanic, panicValue := didPanic(f); !funcDidPanic {
  755. return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
  756. }
  757. return true
  758. }
  759. // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that
  760. // the recovered panic value equals the expected panic value.
  761. //
  762. // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
  763. func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  764. if h, ok := t.(tHelper); ok {
  765. h.Helper()
  766. }
  767. funcDidPanic, panicValue := didPanic(f)
  768. if !funcDidPanic {
  769. return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
  770. }
  771. if panicValue != expected {
  772. return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v", f, expected, panicValue), msgAndArgs...)
  773. }
  774. return true
  775. }
  776. // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.
  777. //
  778. // assert.NotPanics(t, func(){ RemainCalm() })
  779. func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool {
  780. if h, ok := t.(tHelper); ok {
  781. h.Helper()
  782. }
  783. if funcDidPanic, panicValue := didPanic(f); funcDidPanic {
  784. return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v", f, panicValue), msgAndArgs...)
  785. }
  786. return true
  787. }
  788. // WithinDuration asserts that the two times are within duration delta of each other.
  789. //
  790. // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)
  791. func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {
  792. if h, ok := t.(tHelper); ok {
  793. h.Helper()
  794. }
  795. dt := expected.Sub(actual)
  796. if dt < -delta || dt > delta {
  797. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
  798. }
  799. return true
  800. }
  801. func toFloat(x interface{}) (float64, bool) {
  802. var xf float64
  803. xok := true
  804. switch xn := x.(type) {
  805. case uint8:
  806. xf = float64(xn)
  807. case uint16:
  808. xf = float64(xn)
  809. case uint32:
  810. xf = float64(xn)
  811. case uint64:
  812. xf = float64(xn)
  813. case int:
  814. xf = float64(xn)
  815. case int8:
  816. xf = float64(xn)
  817. case int16:
  818. xf = float64(xn)
  819. case int32:
  820. xf = float64(xn)
  821. case int64:
  822. xf = float64(xn)
  823. case float32:
  824. xf = float64(xn)
  825. case float64:
  826. xf = float64(xn)
  827. case time.Duration:
  828. xf = float64(xn)
  829. default:
  830. xok = false
  831. }
  832. return xf, xok
  833. }
  834. // InDelta asserts that the two numerals are within delta of each other.
  835. //
  836. // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
  837. func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  838. if h, ok := t.(tHelper); ok {
  839. h.Helper()
  840. }
  841. af, aok := toFloat(expected)
  842. bf, bok := toFloat(actual)
  843. if !aok || !bok {
  844. return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...)
  845. }
  846. if math.IsNaN(af) {
  847. return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...)
  848. }
  849. if math.IsNaN(bf) {
  850. return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...)
  851. }
  852. dt := af - bf
  853. if dt < -delta || dt > delta {
  854. return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...)
  855. }
  856. return true
  857. }
  858. // InDeltaSlice is the same as InDelta, except it compares two slices.
  859. func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  860. if h, ok := t.(tHelper); ok {
  861. h.Helper()
  862. }
  863. if expected == nil || actual == nil ||
  864. reflect.TypeOf(actual).Kind() != reflect.Slice ||
  865. reflect.TypeOf(expected).Kind() != reflect.Slice {
  866. return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
  867. }
  868. actualSlice := reflect.ValueOf(actual)
  869. expectedSlice := reflect.ValueOf(expected)
  870. for i := 0; i < actualSlice.Len(); i++ {
  871. result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...)
  872. if !result {
  873. return result
  874. }
  875. }
  876. return true
  877. }
  878. // InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
  879. func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
  880. if h, ok := t.(tHelper); ok {
  881. h.Helper()
  882. }
  883. if expected == nil || actual == nil ||
  884. reflect.TypeOf(actual).Kind() != reflect.Map ||
  885. reflect.TypeOf(expected).Kind() != reflect.Map {
  886. return Fail(t, "Arguments must be maps", msgAndArgs...)
  887. }
  888. expectedMap := reflect.ValueOf(expected)
  889. actualMap := reflect.ValueOf(actual)
  890. if expectedMap.Len() != actualMap.Len() {
  891. return Fail(t, "Arguments must have the same number of keys", msgAndArgs...)
  892. }
  893. for _, k := range expectedMap.MapKeys() {
  894. ev := expectedMap.MapIndex(k)
  895. av := actualMap.MapIndex(k)
  896. if !ev.IsValid() {
  897. return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...)
  898. }
  899. if !av.IsValid() {
  900. return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...)
  901. }
  902. if !InDelta(
  903. t,
  904. ev.Interface(),
  905. av.Interface(),
  906. delta,
  907. msgAndArgs...,
  908. ) {
  909. return false
  910. }
  911. }
  912. return true
  913. }
  914. func calcRelativeError(expected, actual interface{}) (float64, error) {
  915. af, aok := toFloat(expected)
  916. if !aok {
  917. return 0, fmt.Errorf("expected value %q cannot be converted to float", expected)
  918. }
  919. if af == 0 {
  920. return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error")
  921. }
  922. bf, bok := toFloat(actual)
  923. if !bok {
  924. return 0, fmt.Errorf("actual value %q cannot be converted to float", actual)
  925. }
  926. return math.Abs(af-bf) / math.Abs(af), nil
  927. }
  928. // InEpsilon asserts that expected and actual have a relative error less than epsilon
  929. func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
  930. if h, ok := t.(tHelper); ok {
  931. h.Helper()
  932. }
  933. actualEpsilon, err := calcRelativeError(expected, actual)
  934. if err != nil {
  935. return Fail(t, err.Error(), msgAndArgs...)
  936. }
  937. if actualEpsilon > epsilon {
  938. return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+
  939. " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...)
  940. }
  941. return true
  942. }
  943. // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.
  944. func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool {
  945. if h, ok := t.(tHelper); ok {
  946. h.Helper()
  947. }
  948. if expected == nil || actual == nil ||
  949. reflect.TypeOf(actual).Kind() != reflect.Slice ||
  950. reflect.TypeOf(expected).Kind() != reflect.Slice {
  951. return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...)
  952. }
  953. actualSlice := reflect.ValueOf(actual)
  954. expectedSlice := reflect.ValueOf(expected)
  955. for i := 0; i < actualSlice.Len(); i++ {
  956. result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon)
  957. if !result {
  958. return result
  959. }
  960. }
  961. return true
  962. }
  963. /*
  964. Errors
  965. */
  966. // NoError asserts that a function returned no error (i.e. `nil`).
  967. //
  968. // actualObj, err := SomeFunction()
  969. // if assert.NoError(t, err) {
  970. // assert.Equal(t, expectedObj, actualObj)
  971. // }
  972. func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
  973. if h, ok := t.(tHelper); ok {
  974. h.Helper()
  975. }
  976. if err != nil {
  977. return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
  978. }
  979. return true
  980. }
  981. // Error asserts that a function returned an error (i.e. not `nil`).
  982. //
  983. // actualObj, err := SomeFunction()
  984. // if assert.Error(t, err) {
  985. // assert.Equal(t, expectedError, err)
  986. // }
  987. func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
  988. if h, ok := t.(tHelper); ok {
  989. h.Helper()
  990. }
  991. if err == nil {
  992. return Fail(t, "An error is expected but got nil.", msgAndArgs...)
  993. }
  994. return true
  995. }
  996. // EqualError asserts that a function returned an error (i.e. not `nil`)
  997. // and that it is equal to the provided error.
  998. //
  999. // actualObj, err := SomeFunction()
  1000. // assert.EqualError(t, err, expectedErrorString)
  1001. func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool {
  1002. if h, ok := t.(tHelper); ok {
  1003. h.Helper()
  1004. }
  1005. if !Error(t, theError, msgAndArgs...) {
  1006. return false
  1007. }
  1008. expected := errString
  1009. actual := theError.Error()
  1010. // don't need to use deep equals here, we know they are both strings
  1011. if expected != actual {
  1012. return Fail(t, fmt.Sprintf("Error message not equal:\n"+
  1013. "expected: %q\n"+
  1014. "actual : %q", expected, actual), msgAndArgs...)
  1015. }
  1016. return true
  1017. }
  1018. // matchRegexp return true if a specified regexp matches a string.
  1019. func matchRegexp(rx interface{}, str interface{}) bool {
  1020. var r *regexp.Regexp
  1021. if rr, ok := rx.(*regexp.Regexp); ok {
  1022. r = rr
  1023. } else {
  1024. r = regexp.MustCompile(fmt.Sprint(rx))
  1025. }
  1026. return (r.FindStringIndex(fmt.Sprint(str)) != nil)
  1027. }
  1028. // Regexp asserts that a specified regexp matches a string.
  1029. //
  1030. // assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
  1031. // assert.Regexp(t, "start...$", "it's not starting")
  1032. func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
  1033. if h, ok := t.(tHelper); ok {
  1034. h.Helper()
  1035. }
  1036. match := matchRegexp(rx, str)
  1037. if !match {
  1038. Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...)
  1039. }
  1040. return match
  1041. }
  1042. // NotRegexp asserts that a specified regexp does not match a string.
  1043. //
  1044. // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
  1045. // assert.NotRegexp(t, "^start", "it's not starting")
  1046. func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {
  1047. if h, ok := t.(tHelper); ok {
  1048. h.Helper()
  1049. }
  1050. match := matchRegexp(rx, str)
  1051. if match {
  1052. Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...)
  1053. }
  1054. return !match
  1055. }
  1056. // Zero asserts that i is the zero value for its type.
  1057. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
  1058. if h, ok := t.(tHelper); ok {
  1059. h.Helper()
  1060. }
  1061. if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
  1062. return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
  1063. }
  1064. return true
  1065. }
  1066. // NotZero asserts that i is not the zero value for its type.
  1067. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
  1068. if h, ok := t.(tHelper); ok {
  1069. h.Helper()
  1070. }
  1071. if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
  1072. return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...)
  1073. }
  1074. return true
  1075. }
  1076. // FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.
  1077. func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1078. if h, ok := t.(tHelper); ok {
  1079. h.Helper()
  1080. }
  1081. info, err := os.Lstat(path)
  1082. if err != nil {
  1083. if os.IsNotExist(err) {
  1084. return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
  1085. }
  1086. return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
  1087. }
  1088. if info.IsDir() {
  1089. return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...)
  1090. }
  1091. return true
  1092. }
  1093. // DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists.
  1094. func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool {
  1095. if h, ok := t.(tHelper); ok {
  1096. h.Helper()
  1097. }
  1098. info, err := os.Lstat(path)
  1099. if err != nil {
  1100. if os.IsNotExist(err) {
  1101. return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...)
  1102. }
  1103. return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...)
  1104. }
  1105. if !info.IsDir() {
  1106. return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...)
  1107. }
  1108. return true
  1109. }
  1110. // JSONEq asserts that two JSON strings are equivalent.
  1111. //
  1112. // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
  1113. func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
  1114. if h, ok := t.(tHelper); ok {
  1115. h.Helper()
  1116. }
  1117. var expectedJSONAsInterface, actualJSONAsInterface interface{}
  1118. if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil {
  1119. return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...)
  1120. }
  1121. if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil {
  1122. return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...)
  1123. }
  1124. return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
  1125. }
  1126. func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) {
  1127. t := reflect.TypeOf(v)
  1128. k := t.Kind()
  1129. if k == reflect.Ptr {
  1130. t = t.Elem()
  1131. k = t.Kind()
  1132. }
  1133. return t, k
  1134. }
  1135. // diff returns a diff of both values as long as both are of the same type and
  1136. // are a struct, map, slice, array or string. Otherwise it returns an empty string.
  1137. func diff(expected interface{}, actual interface{}) string {
  1138. if expected == nil || actual == nil {
  1139. return ""
  1140. }
  1141. et, ek := typeAndKind(expected)
  1142. at, _ := typeAndKind(actual)
  1143. if et != at {
  1144. return ""
  1145. }
  1146. if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String {
  1147. return ""
  1148. }
  1149. var e, a string
  1150. if et != reflect.TypeOf("") {
  1151. e = spewConfig.Sdump(expected)
  1152. a = spewConfig.Sdump(actual)
  1153. } else {
  1154. e = expected.(string)
  1155. a = actual.(string)
  1156. }
  1157. diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
  1158. A: difflib.SplitLines(e),
  1159. B: difflib.SplitLines(a),
  1160. FromFile: "Expected",
  1161. FromDate: "",
  1162. ToFile: "Actual",
  1163. ToDate: "",
  1164. Context: 1,
  1165. })
  1166. return "\n\nDiff:\n" + diff
  1167. }
  1168. // validateEqualArgs checks whether provided arguments can be safely used in the
  1169. // Equal/NotEqual functions.
  1170. func validateEqualArgs(expected, actual interface{}) error {
  1171. if isFunction(expected) || isFunction(actual) {
  1172. return errors.New("cannot take func type as argument")
  1173. }
  1174. return nil
  1175. }
  1176. func isFunction(arg interface{}) bool {
  1177. if arg == nil {
  1178. return false
  1179. }
  1180. return reflect.TypeOf(arg).Kind() == reflect.Func
  1181. }
  1182. var spewConfig = spew.ConfigState{
  1183. Indent: " ",
  1184. DisablePointerAddresses: true,
  1185. DisableCapacities: true,
  1186. SortKeys: true,
  1187. }
  1188. type tHelper interface {
  1189. Helper()
  1190. }