http urls monitor.

assertions.go 38KB

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