/assert/assert.go

https://github.com/blend/go-sdk · Go · 1185 lines · 958 code · 154 blank · 73 comment · 210 complexity · de5cc1a333e0e42f089b5a0a0b56e7d9 MD5 · raw file

  1. /*
  2. Copyright (c) 2021 - Present. Blend Labs, Inc. All rights reserved
  3. Use of this source code is governed by a MIT license that can be found in the LICENSE file.
  4. */
  5. package assert
  6. import (
  7. "context"
  8. "fmt"
  9. "io"
  10. "math"
  11. "math/rand"
  12. "os"
  13. "reflect"
  14. "regexp"
  15. "runtime"
  16. "strings"
  17. "sync/atomic"
  18. "testing"
  19. "time"
  20. "unicode"
  21. "unicode/utf8"
  22. )
  23. // Empty returns an empty assertions handler; useful when you want to apply assertions w/o hooking into the testing framework.
  24. func Empty(opts ...Option) *Assertions {
  25. a := Assertions{
  26. OutputFormat: OutputFormatFromEnv(),
  27. Context: WithContextID(context.Background(), randomString(8)),
  28. }
  29. for _, opt := range opts {
  30. opt(&a)
  31. }
  32. return &a
  33. }
  34. // New returns a new instance of `Assertions`.
  35. func New(t *testing.T, opts ...Option) *Assertions {
  36. a := Assertions{
  37. T: t,
  38. OutputFormat: OutputFormatFromEnv(),
  39. Context: WithContextID(context.Background(), randomString(8)),
  40. }
  41. if t != nil {
  42. a.Context = WithTestName(a.Context, t.Name())
  43. }
  44. for _, opt := range opts {
  45. opt(&a)
  46. }
  47. return &a
  48. }
  49. // Assertions is the main entry point for using the assertions library.
  50. type Assertions struct {
  51. Output io.Writer
  52. OutputFormat OutputFormat
  53. T *testing.T
  54. Context context.Context
  55. Optional bool
  56. Count int32
  57. }
  58. // Background returns the assertions context.
  59. func (a *Assertions) Background() context.Context {
  60. return a.Context
  61. }
  62. // assertion represents the actions to take for *each* assertion.
  63. // it is used internally for stats tracking.
  64. func (a *Assertions) assertion() {
  65. atomic.AddInt32(&a.Count, 1)
  66. }
  67. // NonFatal transitions the assertion into a `NonFatal` assertion; that is, one that will not cause the test to abort if it fails.
  68. // NonFatal assertions are useful when you want to check many properties during a test, but only on an informational basis.
  69. // They will typically return a bool to indicate if the assertion succeeded, or if you should consider the overall
  70. // test to still be a success.
  71. func (a *Assertions) NonFatal() *Assertions { //golint you can bite me.
  72. return &Assertions{
  73. T: a.T,
  74. Output: a.Output,
  75. OutputFormat: a.OutputFormat,
  76. Optional: true,
  77. }
  78. }
  79. // NotImplemented will just error.
  80. func (a *Assertions) NotImplemented(userMessageComponents ...interface{}) {
  81. fail(a.Output, a.T, a.OutputFormat, NewFailure("the current test is not implemented", userMessageComponents...))
  82. }
  83. func (a *Assertions) fail(message string, userMessageComponents ...interface{}) bool {
  84. if a.Optional {
  85. fail(a.Output, a.T, a.OutputFormat, NewFailure(message, userMessageComponents...))
  86. return false
  87. }
  88. failNow(a.Output, a.T, a.OutputFormat, NewFailure(message, userMessageComponents...))
  89. return false
  90. }
  91. // NotNil asserts that a reference is not nil.
  92. func (a *Assertions) NotNil(object interface{}, userMessageComponents ...interface{}) bool {
  93. a.assertion()
  94. if didFail, message := shouldNotBeNil(object); didFail {
  95. return a.fail(message, userMessageComponents...)
  96. }
  97. return true
  98. }
  99. // Nil asserts that a reference is nil.
  100. func (a *Assertions) Nil(object interface{}, userMessageComponents ...interface{}) bool {
  101. a.assertion()
  102. if didFail, message := shouldBeNil(object); didFail {
  103. return a.fail(message, userMessageComponents...)
  104. }
  105. return true
  106. }
  107. // Len asserts that a collection has a given length.
  108. func (a *Assertions) Len(collection interface{}, length int, userMessageComponents ...interface{}) bool {
  109. a.assertion()
  110. if didFail, message := shouldHaveLength(collection, length); didFail {
  111. return a.fail(message, userMessageComponents...)
  112. }
  113. return true
  114. }
  115. // Empty asserts that a collection is empty.
  116. func (a *Assertions) Empty(collection interface{}, userMessageComponents ...interface{}) bool {
  117. a.assertion()
  118. if didFail, message := shouldBeEmpty(collection); didFail {
  119. return a.fail(message, userMessageComponents...)
  120. }
  121. return true
  122. }
  123. // NotEmpty asserts that a collection is not empty.
  124. func (a *Assertions) NotEmpty(collection interface{}, userMessageComponents ...interface{}) bool {
  125. a.assertion()
  126. if didFail, message := shouldNotBeEmpty(collection); didFail {
  127. return a.fail(message, userMessageComponents...)
  128. }
  129. return true
  130. }
  131. // Equal asserts that two objects are deeply equal.
  132. func (a *Assertions) Equal(expected interface{}, actual interface{}, userMessageComponents ...interface{}) bool {
  133. a.assertion()
  134. if didFail, message := shouldBeEqual(expected, actual); didFail {
  135. return a.fail(message, userMessageComponents...)
  136. }
  137. return true
  138. }
  139. // ReferenceEqual asserts that two objects are the same reference in memory.
  140. func (a *Assertions) ReferenceEqual(expected interface{}, actual interface{}, userMessageComponents ...interface{}) bool {
  141. a.assertion()
  142. if didFail, message := shouldBeReferenceEqual(expected, actual); didFail {
  143. return a.fail(message, userMessageComponents...)
  144. }
  145. return true
  146. }
  147. // NotEqual asserts that two objects are not deeply equal.
  148. func (a *Assertions) NotEqual(expected interface{}, actual interface{}, userMessageComponents ...interface{}) bool {
  149. a.assertion()
  150. if didFail, message := shouldNotBeEqual(expected, actual); didFail {
  151. return a.fail(message, userMessageComponents...)
  152. }
  153. return true
  154. }
  155. // PanicEqual asserts the panic emitted by an action equals an expected value.
  156. func (a *Assertions) PanicEqual(expected interface{}, action func(), userMessageComponents ...interface{}) bool {
  157. a.assertion()
  158. if didFail, message := shouldBePanicEqual(expected, action); didFail {
  159. return a.fail(message, userMessageComponents...)
  160. }
  161. return true
  162. }
  163. // NotPanic asserts the given action does not panic.
  164. func (a *Assertions) NotPanic(action func(), userMessageComponents ...interface{}) bool {
  165. a.assertion()
  166. if didFail, message := shouldNotPanic(action); didFail {
  167. return a.fail(message, userMessageComponents...)
  168. }
  169. return true
  170. }
  171. // Zero asserts that a value is equal to it's default value.
  172. func (a *Assertions) Zero(value interface{}, userMessageComponents ...interface{}) bool {
  173. a.assertion()
  174. if didFail, message := shouldBeZero(value); didFail {
  175. return a.fail(message, userMessageComponents...)
  176. }
  177. return true
  178. }
  179. // NotZero asserts that a value is not equal to it's default value.
  180. func (a *Assertions) NotZero(value interface{}, userMessageComponents ...interface{}) bool {
  181. a.assertion()
  182. if didFail, message := shouldBeNonZero(value); didFail {
  183. return a.fail(message, userMessageComponents...)
  184. }
  185. return true
  186. }
  187. // True asserts a boolean is true.
  188. func (a *Assertions) True(object bool, userMessageComponents ...interface{}) bool {
  189. a.assertion()
  190. if didFail, message := shouldBeTrue(object); didFail {
  191. return a.fail(message, userMessageComponents...)
  192. }
  193. return true
  194. }
  195. // False asserts a boolean is false.
  196. func (a *Assertions) False(object bool, userMessageComponents ...interface{}) bool {
  197. a.assertion()
  198. if didFail, message := shouldBeFalse(object); didFail {
  199. return a.fail(message, userMessageComponents...)
  200. }
  201. return true
  202. }
  203. // InDelta asserts that two floats are within a delta.
  204. //
  205. // The delta is computed by the absolute of the difference betwee `f0` and `f1`
  206. // and testing if that absolute difference is strictly less than `delta`
  207. // if greater, it will fail the assertion, if delta is equal to or greater than difference
  208. // the assertion will pass.
  209. func (a *Assertions) InDelta(f0, f1, delta float64, userMessageComponents ...interface{}) bool {
  210. a.assertion()
  211. if didFail, message := shouldBeInDelta(f0, f1, delta); didFail {
  212. return a.fail(message, userMessageComponents...)
  213. }
  214. return true
  215. }
  216. // InTimeDelta asserts that times t1 and t2 are within a delta.
  217. func (a *Assertions) InTimeDelta(t1, t2 time.Time, delta time.Duration, userMessageComponents ...interface{}) bool {
  218. a.assertion()
  219. if didFail, message := shouldBeInTimeDelta(t1, t2, delta); didFail {
  220. return a.fail(message, userMessageComponents...)
  221. }
  222. return true
  223. }
  224. // NotInTimeDelta asserts that times t1 and t2 are not within a delta.
  225. func (a *Assertions) NotInTimeDelta(t1, t2 time.Time, delta time.Duration, userMessageComponents ...interface{}) bool {
  226. a.assertion()
  227. if didFail, message := shouldNotBeInTimeDelta(t1, t2, delta); didFail {
  228. return a.fail(message, userMessageComponents...)
  229. }
  230. return true
  231. }
  232. // FileExists asserts that a file exists at a given filepath on disk.
  233. func (a *Assertions) FileExists(filepath string, userMessageComponents ...interface{}) bool {
  234. a.assertion()
  235. if didFail, message := shouldFileExist(filepath); didFail {
  236. return a.fail(message, userMessageComponents...)
  237. }
  238. return true
  239. }
  240. // Contains asserts that a substring is present in a corpus.
  241. func (a *Assertions) Contains(corpus, substring string, userMessageComponents ...interface{}) bool {
  242. a.assertion()
  243. if didFail, message := shouldContain(corpus, substring); didFail {
  244. return a.fail(message, userMessageComponents...)
  245. }
  246. return true
  247. }
  248. // NotContains asserts that a substring is present in a corpus.
  249. func (a *Assertions) NotContains(corpus, substring string, userMessageComponents ...interface{}) bool {
  250. a.assertion()
  251. if didFail, message := shouldNotContain(corpus, substring); didFail {
  252. return a.fail(message, userMessageComponents...)
  253. }
  254. return true
  255. }
  256. // HasPrefix asserts that a corpus has a given prefix.
  257. func (a *Assertions) HasPrefix(corpus, prefix string, userMessageComponents ...interface{}) bool {
  258. a.assertion()
  259. if didFail, message := shouldHasPrefix(corpus, prefix); didFail {
  260. return a.fail(message, userMessageComponents...)
  261. }
  262. return true
  263. }
  264. // NotHasPrefix asserts that a corpus does not have a given prefix.
  265. func (a *Assertions) NotHasPrefix(corpus, prefix string, userMessageComponents ...interface{}) bool {
  266. a.assertion()
  267. if didFail, message := shouldNotHasPrefix(corpus, prefix); didFail {
  268. return a.fail(message, userMessageComponents...)
  269. }
  270. return true
  271. }
  272. // HasSuffix asserts that a corpus has a given suffix.
  273. func (a *Assertions) HasSuffix(corpus, suffix string, userMessageComponents ...interface{}) bool {
  274. a.assertion()
  275. if didFail, message := shouldHasSuffix(corpus, suffix); didFail {
  276. return a.fail(message, userMessageComponents...)
  277. }
  278. return true
  279. }
  280. // NotHasSuffix asserts that a corpus does not have a given suffix.
  281. func (a *Assertions) NotHasSuffix(corpus, suffix string, userMessageComponents ...interface{}) bool {
  282. a.assertion()
  283. if didFail, message := shouldNotHasSuffix(corpus, suffix); didFail {
  284. return a.fail(message, userMessageComponents...)
  285. }
  286. return true
  287. }
  288. // Matches returns if a given value matches a given regexp expression.
  289. func (a *Assertions) Matches(expr string, value interface{}, userMessageComponents ...interface{}) bool {
  290. a.assertion()
  291. if didFail, message := shouldMatch(expr, value); didFail {
  292. return a.fail(message, userMessageComponents...)
  293. }
  294. return true
  295. }
  296. // NotMatches returns if a given value does not match a given regexp expression.
  297. func (a *Assertions) NotMatches(expr string, value interface{}, userMessageComponents ...interface{}) bool {
  298. a.assertion()
  299. if didFail, message := shouldNotMatch(expr, value); didFail {
  300. return a.fail(message, userMessageComponents...)
  301. }
  302. return true
  303. }
  304. // Any applies a predicate.
  305. func (a *Assertions) Any(target interface{}, predicate Predicate, userMessageComponents ...interface{}) bool {
  306. a.assertion()
  307. if didFail, message := shouldAny(target, predicate); didFail {
  308. return a.fail(message, userMessageComponents...)
  309. }
  310. return true
  311. }
  312. // AnyOfInt applies a predicate.
  313. func (a *Assertions) AnyOfInt(target []int, predicate PredicateOfInt, userMessageComponents ...interface{}) bool {
  314. a.assertion()
  315. if didFail, message := shouldAnyOfInt(target, predicate); didFail {
  316. return a.fail(message, userMessageComponents...)
  317. }
  318. return true
  319. }
  320. // AnyOfFloat64 applies a predicate.
  321. func (a *Assertions) AnyOfFloat64(target []float64, predicate PredicateOfFloat, userMessageComponents ...interface{}) bool {
  322. a.assertion()
  323. if didFail, message := shouldAnyOfFloat(target, predicate); didFail {
  324. return a.fail(message, userMessageComponents...)
  325. }
  326. return true
  327. }
  328. // AnyOfString applies a predicate.
  329. func (a *Assertions) AnyOfString(target []string, predicate PredicateOfString, userMessageComponents ...interface{}) bool {
  330. a.assertion()
  331. if didFail, message := shouldAnyOfString(target, predicate); didFail {
  332. return a.fail(message, userMessageComponents...)
  333. }
  334. return true
  335. }
  336. // AnyCount applies a predicate and passes if it fires a given number of times .
  337. func (a *Assertions) AnyCount(target interface{}, times int, predicate Predicate, userMessageComponents ...interface{}) bool {
  338. a.assertion()
  339. if didFail, message := shouldAnyCount(target, times, predicate); didFail {
  340. return a.fail(message, userMessageComponents...)
  341. }
  342. return true
  343. }
  344. // All applies a predicate.
  345. func (a *Assertions) All(target interface{}, predicate Predicate, userMessageComponents ...interface{}) bool {
  346. a.assertion()
  347. if didFail, message := shouldAll(target, predicate); didFail {
  348. return a.fail(message, userMessageComponents...)
  349. }
  350. return true
  351. }
  352. // AllOfInt applies a predicate.
  353. func (a *Assertions) AllOfInt(target []int, predicate PredicateOfInt, userMessageComponents ...interface{}) bool {
  354. a.assertion()
  355. if didFail, message := shouldAllOfInt(target, predicate); didFail {
  356. return a.fail(message, userMessageComponents...)
  357. }
  358. return true
  359. }
  360. // AllOfFloat64 applies a predicate.
  361. func (a *Assertions) AllOfFloat64(target []float64, predicate PredicateOfFloat, userMessageComponents ...interface{}) bool {
  362. a.assertion()
  363. if didFail, message := shouldAllOfFloat(target, predicate); didFail {
  364. return a.fail(message, userMessageComponents...)
  365. }
  366. return true
  367. }
  368. // AllOfString applies a predicate.
  369. func (a *Assertions) AllOfString(target []string, predicate PredicateOfString, userMessageComponents ...interface{}) bool {
  370. a.assertion()
  371. if didFail, message := shouldAllOfString(target, predicate); didFail {
  372. return a.fail(message, userMessageComponents...)
  373. }
  374. return true
  375. }
  376. // None applies a predicate.
  377. func (a *Assertions) None(target interface{}, predicate Predicate, userMessageComponents ...interface{}) bool {
  378. a.assertion()
  379. if didFail, message := shouldNone(target, predicate); didFail {
  380. return a.fail(message, userMessageComponents...)
  381. }
  382. return true
  383. }
  384. // NoneOfInt applies a predicate.
  385. func (a *Assertions) NoneOfInt(target []int, predicate PredicateOfInt, userMessageComponents ...interface{}) bool {
  386. a.assertion()
  387. if didFail, message := shouldNoneOfInt(target, predicate); didFail {
  388. return a.fail(message, userMessageComponents...)
  389. }
  390. return true
  391. }
  392. // NoneOfFloat64 applies a predicate.
  393. func (a *Assertions) NoneOfFloat64(target []float64, predicate PredicateOfFloat, userMessageComponents ...interface{}) bool {
  394. a.assertion()
  395. if didFail, message := shouldNoneOfFloat(target, predicate); didFail {
  396. return a.fail(message, userMessageComponents...)
  397. }
  398. return true
  399. }
  400. // NoneOfString applies a predicate.
  401. func (a *Assertions) NoneOfString(target []string, predicate PredicateOfString, userMessageComponents ...interface{}) bool {
  402. a.assertion()
  403. if didFail, message := shouldNoneOfString(target, predicate); didFail {
  404. return a.fail(message, userMessageComponents...)
  405. }
  406. return true
  407. }
  408. // FailNow forces a test failure (useful for debugging).
  409. func (a *Assertions) FailNow(userMessageComponents ...interface{}) {
  410. failNow(a.Output, a.T, a.OutputFormat, NewFailure("Fatal Assertion Failed", userMessageComponents...))
  411. }
  412. // Fail forces a test failure (useful for debugging).
  413. func (a *Assertions) Fail(userMessageComponents ...interface{}) bool {
  414. fail(a.Output, a.T, a.OutputFormat, NewFailure("Fatal Assertion Failed", userMessageComponents...))
  415. return true
  416. }
  417. // --------------------------------------------------------------------------------
  418. // OUTPUT
  419. // --------------------------------------------------------------------------------
  420. func failNow(w io.Writer, t *testing.T, outputFormat OutputFormat, failure Failure) {
  421. fail(w, t, outputFormat, failure)
  422. if t != nil {
  423. t.FailNow()
  424. } else {
  425. panic(failure)
  426. }
  427. }
  428. func fail(w io.Writer, t *testing.T, outputFormat OutputFormat, failure Failure) {
  429. var output string
  430. switch outputFormat {
  431. case OutputFormatDefault, OutputFormatText:
  432. output = fmt.Sprintf("\r%s", getClearString())
  433. output += failure.Text()
  434. case OutputFormatJSON:
  435. output = fmt.Sprintf("\r%s", getLocationString())
  436. output += failure.JSON()
  437. default:
  438. panic(fmt.Errorf("invalid output format: %s", outputFormat))
  439. }
  440. if t != nil {
  441. t.Error(output)
  442. }
  443. if w != nil {
  444. fmt.Fprint(w, output)
  445. }
  446. }
  447. func callerInfoStrings(frames []stackFrame) []string {
  448. output := make([]string, len(frames))
  449. for index := range frames {
  450. output[index] = frames[index].String()
  451. }
  452. return output
  453. }
  454. type stackFrame struct {
  455. PC uintptr
  456. FileFull string
  457. Dir string
  458. File string
  459. Name string
  460. Line int
  461. OK bool
  462. }
  463. func (sf stackFrame) String() string {
  464. return fmt.Sprintf("%s:%d", sf.File, sf.Line)
  465. }
  466. func callerInfo() []stackFrame {
  467. var name string
  468. var callers []stackFrame
  469. for i := 0; ; i++ {
  470. var frame stackFrame
  471. frame.PC, frame.FileFull, frame.Line, frame.OK = runtime.Caller(i)
  472. if !frame.OK {
  473. break
  474. }
  475. if frame.FileFull == "<autogenerated>" {
  476. break
  477. }
  478. parts := strings.Split(frame.FileFull, "/")
  479. frame.Dir = parts[len(parts)-2]
  480. frame.File = parts[len(parts)-1]
  481. if frame.Dir != "assert" {
  482. callers = append(callers, frame)
  483. }
  484. f := runtime.FuncForPC(frame.PC)
  485. if f == nil {
  486. break
  487. }
  488. name = f.Name()
  489. // Drop the package
  490. segments := strings.Split(name, ".")
  491. name = segments[len(segments)-1]
  492. if isTest(name, "Test") ||
  493. isTest(name, "Benchmark") ||
  494. isTest(name, "Example") {
  495. break
  496. }
  497. }
  498. return callers
  499. }
  500. func color(input string, colorCode string) string {
  501. return fmt.Sprintf("\033[%s;01m%s\033[0m", colorCode, input)
  502. }
  503. func isTest(name, prefix string) bool {
  504. if !strings.HasPrefix(name, prefix) {
  505. return false
  506. }
  507. if len(name) == len(prefix) { // "Test" is ok
  508. return true
  509. }
  510. rune, _ := utf8.DecodeRuneInString(name[len(prefix):])
  511. return !unicode.IsLower(rune)
  512. }
  513. func getClearString() string {
  514. _, file, line, ok := runtime.Caller(1)
  515. if !ok {
  516. return ""
  517. }
  518. parts := strings.Split(file, "/")
  519. file = parts[len(parts)-1]
  520. return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line))+2)
  521. }
  522. func getLocationString() string {
  523. callers := callerInfo()
  524. if len(callers) == 0 {
  525. return ""
  526. }
  527. last := callers[len(callers)-1]
  528. return fmt.Sprintf("%s:%d: ", last.File, last.Line)
  529. }
  530. func safeExec(action func()) (err error) {
  531. defer func() {
  532. if r := recover(); r != nil {
  533. err = fmt.Errorf("%v", r)
  534. }
  535. }()
  536. action()
  537. return
  538. }
  539. func randomString(length int) string {
  540. const charset = "abcdefghijklmnopqrstuvwxyz"
  541. b := make([]byte, length)
  542. for i := range b {
  543. b[i] = charset[rand.Intn(len(charset))]
  544. }
  545. return string(b)
  546. }
  547. // --------------------------------------------------------------------------------
  548. // ASSERTION LOGIC
  549. // --------------------------------------------------------------------------------
  550. func shouldHaveLength(collection interface{}, length int) (bool, string) {
  551. if l := getLength(collection); l != length {
  552. message := shouldBeMultipleMessage(length, l, "Collection should have length")
  553. return true, message
  554. }
  555. return false, ""
  556. }
  557. func shouldNotBeEmpty(collection interface{}) (bool, string) {
  558. if l := getLength(collection); l == 0 {
  559. message := "Should not be empty"
  560. return true, message
  561. }
  562. return false, ""
  563. }
  564. func shouldBeEmpty(collection interface{}) (bool, string) {
  565. if l := getLength(collection); l != 0 {
  566. message := shouldBeMessage(collection, "Should be empty")
  567. return true, message
  568. }
  569. return false, ""
  570. }
  571. func shouldBeEqual(expected, actual interface{}) (bool, string) {
  572. if !areEqual(expected, actual) {
  573. return true, equalMessage(expected, actual)
  574. }
  575. return false, ""
  576. }
  577. func shouldBeReferenceEqual(expected, actual interface{}) (bool, string) {
  578. if !areReferenceEqual(expected, actual) {
  579. return true, referenceEqualMessage(expected, actual)
  580. }
  581. return false, ""
  582. }
  583. func shouldNotPanic(action func()) (bool, string) {
  584. var actual interface{}
  585. var didPanic bool
  586. func() {
  587. defer func() {
  588. actual = recover()
  589. didPanic = actual != nil
  590. }()
  591. action()
  592. }()
  593. if didPanic {
  594. return true, notPanicMessage(actual)
  595. }
  596. return false, ""
  597. }
  598. func shouldBePanicEqual(expected interface{}, action func()) (bool, string) {
  599. var actual interface{}
  600. var didPanic bool
  601. func() {
  602. defer func() {
  603. actual = recover()
  604. didPanic = actual != nil
  605. }()
  606. action()
  607. }()
  608. if !didPanic || (didPanic && !areEqual(expected, actual)) {
  609. return true, panicEqualMessage(didPanic, expected, actual)
  610. }
  611. return false, ""
  612. }
  613. func shouldNotBeEqual(expected, actual interface{}) (bool, string) {
  614. if areEqual(expected, actual) {
  615. return true, notEqualMessage(expected, actual)
  616. }
  617. return false, ""
  618. }
  619. func shouldNotBeNil(object interface{}) (bool, string) {
  620. if isNil(object) {
  621. return true, "Should not be nil"
  622. }
  623. return false, ""
  624. }
  625. func shouldBeNil(object interface{}) (bool, string) {
  626. if !isNil(object) {
  627. return true, shouldBeMessage(object, "Should be nil")
  628. }
  629. return false, ""
  630. }
  631. func shouldBeTrue(value bool) (bool, string) {
  632. if !value {
  633. return true, "Should be true"
  634. }
  635. return false, ""
  636. }
  637. func shouldBeFalse(value bool) (bool, string) {
  638. if value {
  639. return true, "Should be false"
  640. }
  641. return false, ""
  642. }
  643. func shouldBeZero(value interface{}) (bool, string) {
  644. if !isZero(value) {
  645. return true, shouldBeMessage(value, "Should be zero")
  646. }
  647. return false, ""
  648. }
  649. func shouldBeNonZero(value interface{}) (bool, string) {
  650. if isZero(value) {
  651. return true, "Should be non-zero"
  652. }
  653. return false, ""
  654. }
  655. func shouldFileExist(filePath string) (bool, string) {
  656. _, err := os.Stat(filePath)
  657. if err != nil {
  658. pwd, _ := os.Getwd()
  659. message := fmt.Sprintf("File doesnt exist: %s, `pwd`: %s", filePath, pwd)
  660. return true, message
  661. }
  662. return false, ""
  663. }
  664. func shouldBeInDelta(from, to, delta float64) (bool, string) {
  665. diff := math.Abs(from - to)
  666. if diff > delta {
  667. message := fmt.Sprintf("Absolute difference of %0.5f and %0.5f should be less than %0.5f", from, to, delta)
  668. return true, message
  669. }
  670. return false, ""
  671. }
  672. func shouldBeInTimeDelta(from, to time.Time, delta time.Duration) (bool, string) {
  673. var diff time.Duration
  674. if from.After(to) {
  675. diff = from.Sub(to)
  676. } else {
  677. diff = to.Sub(from)
  678. }
  679. if diff > delta {
  680. message := fmt.Sprintf("Delta of %s and %s should be less than %v", from.Format(time.RFC3339), to.Format(time.RFC3339), delta)
  681. return true, message
  682. }
  683. return false, ""
  684. }
  685. func shouldNotBeInTimeDelta(from, to time.Time, delta time.Duration) (bool, string) {
  686. var diff time.Duration
  687. if from.After(to) {
  688. diff = from.Sub(to)
  689. } else {
  690. diff = to.Sub(from)
  691. }
  692. if diff <= delta {
  693. message := fmt.Sprintf("Delta of %s and %s should be greater than %v", from.Format(time.RFC3339), to.Format(time.RFC3339), delta)
  694. return true, message
  695. }
  696. return false, ""
  697. }
  698. func shouldMatch(pattern string, value interface{}) (bool, string) {
  699. matched, err := regexp.MatchString(pattern, fmt.Sprint(value))
  700. if err != nil {
  701. panic(err)
  702. }
  703. if !matched {
  704. message := fmt.Sprintf("`%v` should match `%s`", value, pattern)
  705. return true, message
  706. }
  707. return false, ""
  708. }
  709. func shouldNotMatch(pattern string, value interface{}) (bool, string) {
  710. matched, err := regexp.MatchString(pattern, fmt.Sprint(value))
  711. if err != nil {
  712. panic(err)
  713. }
  714. if matched {
  715. message := fmt.Sprintf("`%v` should not match `%s`", value, pattern)
  716. return true, message
  717. }
  718. return false, ""
  719. }
  720. func shouldContain(corpus, subString string) (bool, string) {
  721. if !strings.Contains(corpus, subString) {
  722. message := fmt.Sprintf("`%s` should contain `%s`", corpus, subString)
  723. return true, message
  724. }
  725. return false, ""
  726. }
  727. func shouldNotContain(corpus, subString string) (bool, string) {
  728. if strings.Contains(corpus, subString) {
  729. message := fmt.Sprintf("`%s` should not contain `%s`", corpus, subString)
  730. return true, message
  731. }
  732. return false, ""
  733. }
  734. func shouldHasPrefix(corpus, prefix string) (bool, string) {
  735. if !strings.HasPrefix(corpus, prefix) {
  736. message := fmt.Sprintf("`%s` should have prefix `%s`", corpus, prefix)
  737. return true, message
  738. }
  739. return false, ""
  740. }
  741. func shouldNotHasPrefix(corpus, prefix string) (bool, string) {
  742. if strings.HasPrefix(corpus, prefix) {
  743. message := fmt.Sprintf("`%s` should not have prefix `%s`", corpus, prefix)
  744. return true, message
  745. }
  746. return false, ""
  747. }
  748. func shouldHasSuffix(corpus, suffix string) (bool, string) {
  749. if !strings.HasSuffix(corpus, suffix) {
  750. message := fmt.Sprintf("`%s` should have suffix `%s`", corpus, suffix)
  751. return true, message
  752. }
  753. return false, ""
  754. }
  755. func shouldNotHasSuffix(corpus, suffix string) (bool, string) {
  756. if strings.HasSuffix(corpus, suffix) {
  757. message := fmt.Sprintf("`%s` should not have suffix `%s`", corpus, suffix)
  758. return true, message
  759. }
  760. return false, ""
  761. }
  762. func shouldAny(target interface{}, predicate Predicate) (bool, string) {
  763. t := reflect.TypeOf(target)
  764. for t.Kind() == reflect.Ptr {
  765. t = t.Elem()
  766. }
  767. v := reflect.ValueOf(target)
  768. for v.Kind() == reflect.Ptr {
  769. v = v.Elem()
  770. }
  771. if t.Kind() != reflect.Slice {
  772. return true, "`target` is not a slice"
  773. }
  774. for x := 0; x < v.Len(); x++ {
  775. obj := v.Index(x).Interface()
  776. if predicate(obj) {
  777. return false, ""
  778. }
  779. }
  780. return true, "Predicate did not fire for any element in target"
  781. }
  782. func shouldAnyCount(target interface{}, times int, predicate Predicate) (bool, string) {
  783. t := reflect.TypeOf(target)
  784. for t.Kind() == reflect.Ptr {
  785. t = t.Elem()
  786. }
  787. v := reflect.ValueOf(target)
  788. for v.Kind() == reflect.Ptr {
  789. v = v.Elem()
  790. }
  791. if t.Kind() != reflect.Slice {
  792. return true, "`target` is not a slice"
  793. }
  794. var seen int
  795. for x := 0; x < v.Len(); x++ {
  796. obj := v.Index(x).Interface()
  797. if predicate(obj) {
  798. seen++
  799. }
  800. }
  801. if seen != times {
  802. return true, shouldBeMultipleMessage(times, seen, "Predicate should fire a given number of times")
  803. }
  804. return false, ""
  805. }
  806. func shouldAnyOfInt(target []int, predicate PredicateOfInt) (bool, string) {
  807. v := reflect.ValueOf(target)
  808. for x := 0; x < v.Len(); x++ {
  809. obj := v.Index(x).Interface().(int)
  810. if predicate(obj) {
  811. return false, ""
  812. }
  813. }
  814. return true, "Predicate did not fire for any element in target"
  815. }
  816. func shouldAnyOfFloat(target []float64, predicate PredicateOfFloat) (bool, string) {
  817. v := reflect.ValueOf(target)
  818. for x := 0; x < v.Len(); x++ {
  819. obj := v.Index(x).Interface().(float64)
  820. if predicate(obj) {
  821. return false, ""
  822. }
  823. }
  824. return true, "Predicate did not fire for any element in target"
  825. }
  826. func shouldAnyOfString(target []string, predicate PredicateOfString) (bool, string) {
  827. v := reflect.ValueOf(target)
  828. for x := 0; x < v.Len(); x++ {
  829. obj := v.Index(x).Interface().(string)
  830. if predicate(obj) {
  831. return false, ""
  832. }
  833. }
  834. return true, "Predicate did not fire for any element in target"
  835. }
  836. func shouldAll(target interface{}, predicate Predicate) (bool, string) {
  837. t := reflect.TypeOf(target)
  838. for t.Kind() == reflect.Ptr {
  839. t = t.Elem()
  840. }
  841. v := reflect.ValueOf(target)
  842. for v.Kind() == reflect.Ptr {
  843. v = v.Elem()
  844. }
  845. if t.Kind() != reflect.Slice {
  846. return true, "`target` is not a slice"
  847. }
  848. for x := 0; x < v.Len(); x++ {
  849. obj := v.Index(x).Interface()
  850. if !predicate(obj) {
  851. return true, fmt.Sprintf("Predicate failed for element in target: %#v", obj)
  852. }
  853. }
  854. return false, ""
  855. }
  856. func shouldAllOfInt(target []int, predicate PredicateOfInt) (bool, string) {
  857. v := reflect.ValueOf(target)
  858. for x := 0; x < v.Len(); x++ {
  859. obj := v.Index(x).Interface().(int)
  860. if !predicate(obj) {
  861. return true, fmt.Sprintf("Predicate failed for element in target: %#v", obj)
  862. }
  863. }
  864. return false, ""
  865. }
  866. func shouldAllOfFloat(target []float64, predicate PredicateOfFloat) (bool, string) {
  867. v := reflect.ValueOf(target)
  868. for x := 0; x < v.Len(); x++ {
  869. obj := v.Index(x).Interface().(float64)
  870. if !predicate(obj) {
  871. return true, fmt.Sprintf("Predicate failed for element in target: %#v", obj)
  872. }
  873. }
  874. return false, ""
  875. }
  876. func shouldAllOfString(target []string, predicate PredicateOfString) (bool, string) {
  877. v := reflect.ValueOf(target)
  878. for x := 0; x < v.Len(); x++ {
  879. obj := v.Index(x).Interface().(string)
  880. if !predicate(obj) {
  881. return true, fmt.Sprintf("Predicate failed for element in target: %#v", obj)
  882. }
  883. }
  884. return false, ""
  885. }
  886. func shouldNone(target interface{}, predicate Predicate) (bool, string) {
  887. t := reflect.TypeOf(target)
  888. for t.Kind() == reflect.Ptr {
  889. t = t.Elem()
  890. }
  891. v := reflect.ValueOf(target)
  892. for v.Kind() == reflect.Ptr {
  893. v = v.Elem()
  894. }
  895. if t.Kind() != reflect.Slice {
  896. return true, "`target` is not a slice"
  897. }
  898. for x := 0; x < v.Len(); x++ {
  899. obj := v.Index(x).Interface()
  900. if predicate(obj) {
  901. return true, fmt.Sprintf("Predicate passed for element in target: %#v", obj)
  902. }
  903. }
  904. return false, ""
  905. }
  906. func shouldNoneOfInt(target []int, predicate PredicateOfInt) (bool, string) {
  907. v := reflect.ValueOf(target)
  908. for x := 0; x < v.Len(); x++ {
  909. obj := v.Index(x).Interface().(int)
  910. if predicate(obj) {
  911. return true, fmt.Sprintf("Predicate passed for element in target: %#v", obj)
  912. }
  913. }
  914. return false, ""
  915. }
  916. func shouldNoneOfFloat(target []float64, predicate PredicateOfFloat) (bool, string) {
  917. v := reflect.ValueOf(target)
  918. for x := 0; x < v.Len(); x++ {
  919. obj := v.Index(x).Interface().(float64)
  920. if predicate(obj) {
  921. return true, fmt.Sprintf("Predicate passed for element in target: %#v", obj)
  922. }
  923. }
  924. return false, ""
  925. }
  926. func shouldNoneOfString(target []string, predicate PredicateOfString) (bool, string) {
  927. v := reflect.ValueOf(target)
  928. for x := 0; x < v.Len(); x++ {
  929. obj := v.Index(x).Interface().(string)
  930. if predicate(obj) {
  931. return true, fmt.Sprintf("Predicate passed for element in target: %#v", obj)
  932. }
  933. }
  934. return false, ""
  935. }
  936. // --------------------------------------------------------------------------------
  937. // UTILITY
  938. // --------------------------------------------------------------------------------
  939. func shouldBeMultipleMessage(expected, actual interface{}, message string) string {
  940. expectedLabel := color("Expected", WHITE)
  941. actualLabel := color("Actual", WHITE)
  942. return fmt.Sprintf(`%s
  943. %s: %#v
  944. %s: %#v`, message, expectedLabel, expected, actualLabel, actual)
  945. }
  946. func shouldBeMessage(object interface{}, message string) string {
  947. actualLabel := color("Actual", WHITE)
  948. if err, ok := object.(error); ok {
  949. return fmt.Sprintf(`%s
  950. %s: %+v`, message, actualLabel, err)
  951. }
  952. return fmt.Sprintf(`%s
  953. %s: %#v`, message, actualLabel, object)
  954. }
  955. func notEqualMessage(expected, actual interface{}) string {
  956. return shouldBeMultipleMessage(expected, actual, "Objects should not be equal")
  957. }
  958. func equalMessage(expected, actual interface{}) string {
  959. return shouldBeMultipleMessage(expected, actual, "Objects should be equal")
  960. }
  961. func referenceEqualMessage(expected, actual interface{}) string {
  962. return shouldBeMultipleMessage(expected, actual, "References should be equal")
  963. }
  964. func panicEqualMessage(didPanic bool, expected, actual interface{}) string {
  965. if !didPanic {
  966. return "Should have produced a panic"
  967. }
  968. return shouldBeMultipleMessage(expected, actual, "Panic from action should equal")
  969. }
  970. func notPanicMessage(actual interface{}) string {
  971. return shouldBeMessage(actual, "Should not have panicked")
  972. }
  973. func getLength(object interface{}) int {
  974. if object == nil {
  975. return 0
  976. } else if object == "" {
  977. return 0
  978. }
  979. objValue := reflect.ValueOf(object)
  980. switch objValue.Kind() {
  981. case reflect.Map:
  982. fallthrough
  983. case reflect.Slice, reflect.Chan, reflect.String:
  984. {
  985. return objValue.Len()
  986. }
  987. }
  988. return 0
  989. }
  990. func isNil(object interface{}) bool {
  991. if object == nil {
  992. return true
  993. }
  994. value := reflect.ValueOf(object)
  995. kind := value.Kind()
  996. if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
  997. return true
  998. }
  999. return false
  1000. }
  1001. func isZero(value interface{}) bool {
  1002. return areEqual(0, value)
  1003. }
  1004. func areReferenceEqual(expected, actual interface{}) bool {
  1005. if expected == nil && actual == nil {
  1006. return true
  1007. }
  1008. if (expected == nil && actual != nil) || (expected != nil && actual == nil) {
  1009. return false
  1010. }
  1011. return expected == actual
  1012. }
  1013. func areEqual(expected, actual interface{}) bool {
  1014. if expected == nil && actual == nil {
  1015. return true
  1016. }
  1017. if (expected == nil && actual != nil) || (expected != nil && actual == nil) {
  1018. return false
  1019. }
  1020. actualType := reflect.TypeOf(actual)
  1021. if actualType == nil {
  1022. return false
  1023. }
  1024. expectedValue := reflect.ValueOf(expected)
  1025. if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
  1026. return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
  1027. }
  1028. return reflect.DeepEqual(expected, actual)
  1029. }