You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

478 lines
20 KiB

  1. /*
  2. Gomega is the Ginkgo BDD-style testing framework's preferred matcher library.
  3. The godoc documentation describes Gomega's API. More comprehensive documentation (with examples!) is available at http://onsi.github.io/gomega/
  4. Gomega on Github: http://github.com/onsi/gomega
  5. Learn more about Ginkgo online: http://onsi.github.io/ginkgo
  6. Ginkgo on Github: http://github.com/onsi/ginkgo
  7. Gomega is MIT-Licensed
  8. */
  9. package gomega
  10. import (
  11. "fmt"
  12. "reflect"
  13. "time"
  14. "github.com/onsi/gomega/internal/assertion"
  15. "github.com/onsi/gomega/internal/asyncassertion"
  16. "github.com/onsi/gomega/internal/testingtsupport"
  17. "github.com/onsi/gomega/types"
  18. )
  19. const GOMEGA_VERSION = "1.12.0"
  20. const nilFailHandlerPanic = `You are trying to make an assertion, but Gomega's fail handler is nil.
  21. If you're using Ginkgo then you probably forgot to put your assertion in an It().
  22. Alternatively, you may have forgotten to register a fail handler with RegisterFailHandler() or RegisterTestingT().
  23. Depending on your vendoring solution you may be inadvertently importing gomega and subpackages (e.g. ghhtp, gexec,...) from different locations.
  24. `
  25. var globalFailWrapper *types.GomegaFailWrapper
  26. var defaultEventuallyTimeout = time.Second
  27. var defaultEventuallyPollingInterval = 10 * time.Millisecond
  28. var defaultConsistentlyDuration = 100 * time.Millisecond
  29. var defaultConsistentlyPollingInterval = 10 * time.Millisecond
  30. // RegisterFailHandler connects Ginkgo to Gomega. When a matcher fails
  31. // the fail handler passed into RegisterFailHandler is called.
  32. func RegisterFailHandler(handler types.GomegaFailHandler) {
  33. RegisterFailHandlerWithT(testingtsupport.EmptyTWithHelper{}, handler)
  34. }
  35. // RegisterFailHandlerWithT ensures that the given types.TWithHelper and fail handler
  36. // are used globally.
  37. func RegisterFailHandlerWithT(t types.TWithHelper, handler types.GomegaFailHandler) {
  38. if handler == nil {
  39. globalFailWrapper = nil
  40. return
  41. }
  42. globalFailWrapper = &types.GomegaFailWrapper{
  43. Fail: handler,
  44. TWithHelper: t,
  45. }
  46. }
  47. // RegisterTestingT connects Gomega to Golang's XUnit style
  48. // Testing.T tests. It is now deprecated and you should use NewWithT() instead.
  49. //
  50. // Legacy Documentation:
  51. //
  52. // You'll need to call this at the top of each XUnit style test:
  53. //
  54. // func TestFarmHasCow(t *testing.T) {
  55. // RegisterTestingT(t)
  56. //
  57. // f := farm.New([]string{"Cow", "Horse"})
  58. // Expect(f.HasCow()).To(BeTrue(), "Farm should have cow")
  59. // }
  60. //
  61. // Note that this *testing.T is registered *globally* by Gomega (this is why you don't have to
  62. // pass `t` down to the matcher itself). This means that you cannot run the XUnit style tests
  63. // in parallel as the global fail handler cannot point to more than one testing.T at a time.
  64. //
  65. // NewWithT() does not have this limitation
  66. //
  67. // (As an aside: Ginkgo gets around this limitation by running parallel tests in different *processes*).
  68. func RegisterTestingT(t types.GomegaTestingT) {
  69. tWithHelper, hasHelper := t.(types.TWithHelper)
  70. if !hasHelper {
  71. RegisterFailHandler(testingtsupport.BuildTestingTGomegaFailWrapper(t).Fail)
  72. return
  73. }
  74. RegisterFailHandlerWithT(tWithHelper, testingtsupport.BuildTestingTGomegaFailWrapper(t).Fail)
  75. }
  76. // InterceptGomegaFailures runs a given callback and returns an array of
  77. // failure messages generated by any Gomega assertions within the callback.
  78. //
  79. // This is accomplished by temporarily replacing the *global* fail handler
  80. // with a fail handler that simply annotates failures. The original fail handler
  81. // is reset when InterceptGomegaFailures returns.
  82. //
  83. // This is most useful when testing custom matchers, but can also be used to check
  84. // on a value using a Gomega assertion without causing a test failure.
  85. func InterceptGomegaFailures(f func()) []string {
  86. originalHandler := globalFailWrapper.Fail
  87. failures := []string{}
  88. RegisterFailHandler(func(message string, callerSkip ...int) {
  89. failures = append(failures, message)
  90. })
  91. f()
  92. RegisterFailHandler(originalHandler)
  93. return failures
  94. }
  95. // Ω wraps an actual value allowing assertions to be made on it:
  96. // Ω("foo").Should(Equal("foo"))
  97. //
  98. // If Ω is passed more than one argument it will pass the *first* argument to the matcher.
  99. // All subsequent arguments will be required to be nil/zero.
  100. //
  101. // This is convenient if you want to make an assertion on a method/function that returns
  102. // a value and an error - a common patter in Go.
  103. //
  104. // For example, given a function with signature:
  105. // func MyAmazingThing() (int, error)
  106. //
  107. // Then:
  108. // Ω(MyAmazingThing()).Should(Equal(3))
  109. // Will succeed only if `MyAmazingThing()` returns `(3, nil)`
  110. //
  111. // Ω and Expect are identical
  112. func Ω(actual interface{}, extra ...interface{}) Assertion {
  113. return ExpectWithOffset(0, actual, extra...)
  114. }
  115. // Expect wraps an actual value allowing assertions to be made on it:
  116. // Expect("foo").To(Equal("foo"))
  117. //
  118. // If Expect is passed more than one argument it will pass the *first* argument to the matcher.
  119. // All subsequent arguments will be required to be nil/zero.
  120. //
  121. // This is convenient if you want to make an assertion on a method/function that returns
  122. // a value and an error - a common patter in Go.
  123. //
  124. // For example, given a function with signature:
  125. // func MyAmazingThing() (int, error)
  126. //
  127. // Then:
  128. // Expect(MyAmazingThing()).Should(Equal(3))
  129. // Will succeed only if `MyAmazingThing()` returns `(3, nil)`
  130. //
  131. // Expect and Ω are identical
  132. func Expect(actual interface{}, extra ...interface{}) Assertion {
  133. return ExpectWithOffset(0, actual, extra...)
  134. }
  135. // ExpectWithOffset wraps an actual value allowing assertions to be made on it:
  136. // ExpectWithOffset(1, "foo").To(Equal("foo"))
  137. //
  138. // Unlike `Expect` and `Ω`, `ExpectWithOffset` takes an additional integer argument
  139. // that is used to modify the call-stack offset when computing line numbers.
  140. //
  141. // This is most useful in helper functions that make assertions. If you want Gomega's
  142. // error message to refer to the calling line in the test (as opposed to the line in the helper function)
  143. // set the first argument of `ExpectWithOffset` appropriately.
  144. func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Assertion {
  145. if globalFailWrapper == nil {
  146. panic(nilFailHandlerPanic)
  147. }
  148. return assertion.New(actual, globalFailWrapper, offset, extra...)
  149. }
  150. // Eventually wraps an actual value allowing assertions to be made on it.
  151. // The assertion is tried periodically until it passes or a timeout occurs.
  152. //
  153. // Both the timeout and polling interval are configurable as optional arguments:
  154. // The first optional argument is the timeout
  155. // The second optional argument is the polling interval
  156. //
  157. // Both intervals can either be specified as time.Duration, parsable duration strings or as floats/integers. In the
  158. // last case they are interpreted as seconds.
  159. //
  160. // If Eventually is passed an actual that is a function taking no arguments and returning at least one value,
  161. // then Eventually will call the function periodically and try the matcher against the function's first return value.
  162. //
  163. // Example:
  164. //
  165. // Eventually(func() int {
  166. // return thingImPolling.Count()
  167. // }).Should(BeNumerically(">=", 17))
  168. //
  169. // Note that this example could be rewritten:
  170. //
  171. // Eventually(thingImPolling.Count).Should(BeNumerically(">=", 17))
  172. //
  173. // If the function returns more than one value, then Eventually will pass the first value to the matcher and
  174. // assert that all other values are nil/zero.
  175. // This allows you to pass Eventually a function that returns a value and an error - a common pattern in Go.
  176. //
  177. // For example, consider a method that returns a value and an error:
  178. // func FetchFromDB() (string, error)
  179. //
  180. // Then
  181. // Eventually(FetchFromDB).Should(Equal("hasselhoff"))
  182. //
  183. // Will pass only if the the returned error is nil and the returned string passes the matcher.
  184. //
  185. // Eventually's default timeout is 1 second, and its default polling interval is 10ms
  186. func Eventually(actual interface{}, intervals ...interface{}) AsyncAssertion {
  187. return EventuallyWithOffset(0, actual, intervals...)
  188. }
  189. // EventuallyWithOffset operates like Eventually but takes an additional
  190. // initial argument to indicate an offset in the call stack. This is useful when building helper
  191. // functions that contain matchers. To learn more, read about `ExpectWithOffset`.
  192. func EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion {
  193. if globalFailWrapper == nil {
  194. panic(nilFailHandlerPanic)
  195. }
  196. timeoutInterval := defaultEventuallyTimeout
  197. pollingInterval := defaultEventuallyPollingInterval
  198. if len(intervals) > 0 {
  199. timeoutInterval = toDuration(intervals[0])
  200. }
  201. if len(intervals) > 1 {
  202. pollingInterval = toDuration(intervals[1])
  203. }
  204. return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset)
  205. }
  206. // Consistently wraps an actual value allowing assertions to be made on it.
  207. // The assertion is tried periodically and is required to pass for a period of time.
  208. //
  209. // Both the total time and polling interval are configurable as optional arguments:
  210. // The first optional argument is the duration that Consistently will run for
  211. // The second optional argument is the polling interval
  212. //
  213. // Both intervals can either be specified as time.Duration, parsable duration strings or as floats/integers. In the
  214. // last case they are interpreted as seconds.
  215. //
  216. // If Consistently is passed an actual that is a function taking no arguments and returning at least one value,
  217. // then Consistently will call the function periodically and try the matcher against the function's first return value.
  218. //
  219. // If the function returns more than one value, then Consistently will pass the first value to the matcher and
  220. // assert that all other values are nil/zero.
  221. // This allows you to pass Consistently a function that returns a value and an error - a common pattern in Go.
  222. //
  223. // Consistently is useful in cases where you want to assert that something *does not happen* over a period of time.
  224. // For example, you want to assert that a goroutine does *not* send data down a channel. In this case, you could:
  225. //
  226. // Consistently(channel).ShouldNot(Receive())
  227. //
  228. // Consistently's default duration is 100ms, and its default polling interval is 10ms
  229. func Consistently(actual interface{}, intervals ...interface{}) AsyncAssertion {
  230. return ConsistentlyWithOffset(0, actual, intervals...)
  231. }
  232. // ConsistentlyWithOffset operates like Consistently but takes an additional
  233. // initial argument to indicate an offset in the call stack. This is useful when building helper
  234. // functions that contain matchers. To learn more, read about `ExpectWithOffset`.
  235. func ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion {
  236. if globalFailWrapper == nil {
  237. panic(nilFailHandlerPanic)
  238. }
  239. timeoutInterval := defaultConsistentlyDuration
  240. pollingInterval := defaultConsistentlyPollingInterval
  241. if len(intervals) > 0 {
  242. timeoutInterval = toDuration(intervals[0])
  243. }
  244. if len(intervals) > 1 {
  245. pollingInterval = toDuration(intervals[1])
  246. }
  247. return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset)
  248. }
  249. // SetDefaultEventuallyTimeout sets the default timeout duration for Eventually. Eventually will repeatedly poll your condition until it succeeds, or until this timeout elapses.
  250. func SetDefaultEventuallyTimeout(t time.Duration) {
  251. defaultEventuallyTimeout = t
  252. }
  253. // SetDefaultEventuallyPollingInterval sets the default polling interval for Eventually.
  254. func SetDefaultEventuallyPollingInterval(t time.Duration) {
  255. defaultEventuallyPollingInterval = t
  256. }
  257. // SetDefaultConsistentlyDuration sets the default duration for Consistently. Consistently will verify that your condition is satisfied for this long.
  258. func SetDefaultConsistentlyDuration(t time.Duration) {
  259. defaultConsistentlyDuration = t
  260. }
  261. // SetDefaultConsistentlyPollingInterval sets the default polling interval for Consistently.
  262. func SetDefaultConsistentlyPollingInterval(t time.Duration) {
  263. defaultConsistentlyPollingInterval = t
  264. }
  265. // AsyncAssertion is returned by Eventually and Consistently and polls the actual value passed into Eventually against
  266. // the matcher passed to the Should and ShouldNot methods.
  267. //
  268. // Both Should and ShouldNot take a variadic optionalDescription argument.
  269. // This argument allows you to make your failure messages more descriptive.
  270. // If a single argument of type `func() string` is passed, this function will be lazily evaluated if a failure occurs
  271. // and the returned string is used to annotate the failure message.
  272. // Otherwise, this argument is passed on to fmt.Sprintf() and then used to annotate the failure message.
  273. //
  274. // Both Should and ShouldNot return a boolean that is true if the assertion passed and false if it failed.
  275. //
  276. // Example:
  277. //
  278. // Eventually(myChannel).Should(Receive(), "Something should have come down the pipe.")
  279. // Consistently(myChannel).ShouldNot(Receive(), func() string { return "Nothing should have come down the pipe." })
  280. type AsyncAssertion interface {
  281. Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool
  282. ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool
  283. }
  284. // GomegaAsyncAssertion is deprecated in favor of AsyncAssertion, which does not stutter.
  285. type GomegaAsyncAssertion = AsyncAssertion
  286. // Assertion is returned by Ω and Expect and compares the actual value to the matcher
  287. // passed to the Should/ShouldNot and To/ToNot/NotTo methods.
  288. //
  289. // Typically Should/ShouldNot are used with Ω and To/ToNot/NotTo are used with Expect
  290. // though this is not enforced.
  291. //
  292. // All methods take a variadic optionalDescription argument.
  293. // This argument allows you to make your failure messages more descriptive.
  294. // If a single argument of type `func() string` is passed, this function will be lazily evaluated if a failure occurs
  295. // and the returned string is used to annotate the failure message.
  296. // Otherwise, this argument is passed on to fmt.Sprintf() and then used to annotate the failure message.
  297. //
  298. // All methods return a bool that is true if the assertion passed and false if it failed.
  299. //
  300. // Example:
  301. //
  302. // Ω(farm.HasCow()).Should(BeTrue(), "Farm %v should have a cow", farm)
  303. type Assertion interface {
  304. Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool
  305. ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool
  306. To(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool
  307. ToNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool
  308. NotTo(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool
  309. }
  310. // GomegaAssertion is deprecated in favor of Assertion, which does not stutter.
  311. type GomegaAssertion = Assertion
  312. // OmegaMatcher is deprecated in favor of the better-named and better-organized types.GomegaMatcher but sticks around to support existing code that uses it
  313. type OmegaMatcher types.GomegaMatcher
  314. // WithT wraps a *testing.T and provides `Expect`, `Eventually`, and `Consistently` methods. This allows you to leverage
  315. // Gomega's rich ecosystem of matchers in standard `testing` test suites.
  316. //
  317. // Use `NewWithT` to instantiate a `WithT`
  318. type WithT struct {
  319. t types.GomegaTestingT
  320. }
  321. // GomegaWithT is deprecated in favor of gomega.WithT, which does not stutter.
  322. type GomegaWithT = WithT
  323. // NewWithT takes a *testing.T and returngs a `gomega.WithT` allowing you to use `Expect`, `Eventually`, and `Consistently` along with
  324. // Gomega's rich ecosystem of matchers in standard `testing` test suits.
  325. //
  326. // func TestFarmHasCow(t *testing.T) {
  327. // g := gomega.NewWithT(t)
  328. //
  329. // f := farm.New([]string{"Cow", "Horse"})
  330. // g.Expect(f.HasCow()).To(BeTrue(), "Farm should have cow")
  331. // }
  332. func NewWithT(t types.GomegaTestingT) *WithT {
  333. return &WithT{
  334. t: t,
  335. }
  336. }
  337. // NewGomegaWithT is deprecated in favor of gomega.NewWithT, which does not stutter.
  338. func NewGomegaWithT(t types.GomegaTestingT) *GomegaWithT {
  339. return NewWithT(t)
  340. }
  341. // ExpectWithOffset is used to make assertions. See documentation for ExpectWithOffset.
  342. func (g *WithT) ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Assertion {
  343. return assertion.New(actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), offset, extra...)
  344. }
  345. // EventuallyWithOffset is used to make asynchronous assertions. See documentation for EventuallyWithOffset.
  346. func (g *WithT) EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion {
  347. timeoutInterval := defaultEventuallyTimeout
  348. pollingInterval := defaultEventuallyPollingInterval
  349. if len(intervals) > 0 {
  350. timeoutInterval = toDuration(intervals[0])
  351. }
  352. if len(intervals) > 1 {
  353. pollingInterval = toDuration(intervals[1])
  354. }
  355. return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, offset)
  356. }
  357. // ConsistentlyWithOffset is used to make asynchronous assertions. See documentation for ConsistentlyWithOffset.
  358. func (g *WithT) ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interface{}) AsyncAssertion {
  359. timeoutInterval := defaultConsistentlyDuration
  360. pollingInterval := defaultConsistentlyPollingInterval
  361. if len(intervals) > 0 {
  362. timeoutInterval = toDuration(intervals[0])
  363. }
  364. if len(intervals) > 1 {
  365. pollingInterval = toDuration(intervals[1])
  366. }
  367. return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, offset)
  368. }
  369. // Expect is used to make assertions. See documentation for Expect.
  370. func (g *WithT) Expect(actual interface{}, extra ...interface{}) Assertion {
  371. return g.ExpectWithOffset(0, actual, extra...)
  372. }
  373. // Eventually is used to make asynchronous assertions. See documentation for Eventually.
  374. func (g *WithT) Eventually(actual interface{}, intervals ...interface{}) AsyncAssertion {
  375. return g.EventuallyWithOffset(0, actual, intervals...)
  376. }
  377. // Consistently is used to make asynchronous assertions. See documentation for Consistently.
  378. func (g *WithT) Consistently(actual interface{}, intervals ...interface{}) AsyncAssertion {
  379. return g.ConsistentlyWithOffset(0, actual, intervals...)
  380. }
  381. func toDuration(input interface{}) time.Duration {
  382. duration, ok := input.(time.Duration)
  383. if ok {
  384. return duration
  385. }
  386. value := reflect.ValueOf(input)
  387. kind := reflect.TypeOf(input).Kind()
  388. if reflect.Int <= kind && kind <= reflect.Int64 {
  389. return time.Duration(value.Int()) * time.Second
  390. } else if reflect.Uint <= kind && kind <= reflect.Uint64 {
  391. return time.Duration(value.Uint()) * time.Second
  392. } else if reflect.Float32 <= kind && kind <= reflect.Float64 {
  393. return time.Duration(value.Float() * float64(time.Second))
  394. } else if reflect.String == kind {
  395. duration, err := time.ParseDuration(value.String())
  396. if err != nil {
  397. panic(fmt.Sprintf("%#v is not a valid parsable duration string.", input))
  398. }
  399. return duration
  400. }
  401. panic(fmt.Sprintf("%v is not a valid interval. Must be time.Duration, parsable duration string or a number.", input))
  402. }
  403. // Gomega describes the essential Gomega DSL. This interface allows libraries
  404. // to abstract between the standard package-level function implementations
  405. // and alternatives like *WithT.
  406. type Gomega interface {
  407. Expect(actual interface{}, extra ...interface{}) Assertion
  408. Eventually(actual interface{}, intervals ...interface{}) AsyncAssertion
  409. Consistently(actual interface{}, intervals ...interface{}) AsyncAssertion
  410. }
  411. type globalFailHandlerGomega struct{}
  412. // DefaultGomega supplies the standard package-level implementation
  413. var Default Gomega = globalFailHandlerGomega{}
  414. // Expect is used to make assertions. See documentation for Expect.
  415. func (globalFailHandlerGomega) Expect(actual interface{}, extra ...interface{}) Assertion {
  416. return Expect(actual, extra...)
  417. }
  418. // Eventually is used to make asynchronous assertions. See documentation for Eventually.
  419. func (globalFailHandlerGomega) Eventually(actual interface{}, extra ...interface{}) AsyncAssertion {
  420. return Eventually(actual, extra...)
  421. }
  422. // Consistently is used to make asynchronous assertions. See documentation for Consistently.
  423. func (globalFailHandlerGomega) Consistently(actual interface{}, extra ...interface{}) AsyncAssertion {
  424. return Consistently(actual, extra...)
  425. }