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.

484 lines
20 KiB

  1. package gomega
  2. import (
  3. "time"
  4. "github.com/onsi/gomega/matchers"
  5. "github.com/onsi/gomega/types"
  6. )
  7. //Equal uses reflect.DeepEqual to compare actual with expected. Equal is strict about
  8. //types when performing comparisons.
  9. //It is an error for both actual and expected to be nil. Use BeNil() instead.
  10. func Equal(expected interface{}) types.GomegaMatcher {
  11. return &matchers.EqualMatcher{
  12. Expected: expected,
  13. }
  14. }
  15. //BeEquivalentTo is more lax than Equal, allowing equality between different types.
  16. //This is done by converting actual to have the type of expected before
  17. //attempting equality with reflect.DeepEqual.
  18. //It is an error for actual and expected to be nil. Use BeNil() instead.
  19. func BeEquivalentTo(expected interface{}) types.GomegaMatcher {
  20. return &matchers.BeEquivalentToMatcher{
  21. Expected: expected,
  22. }
  23. }
  24. //BeIdenticalTo uses the == operator to compare actual with expected.
  25. //BeIdenticalTo is strict about types when performing comparisons.
  26. //It is an error for both actual and expected to be nil. Use BeNil() instead.
  27. func BeIdenticalTo(expected interface{}) types.GomegaMatcher {
  28. return &matchers.BeIdenticalToMatcher{
  29. Expected: expected,
  30. }
  31. }
  32. //BeNil succeeds if actual is nil
  33. func BeNil() types.GomegaMatcher {
  34. return &matchers.BeNilMatcher{}
  35. }
  36. //BeTrue succeeds if actual is true
  37. func BeTrue() types.GomegaMatcher {
  38. return &matchers.BeTrueMatcher{}
  39. }
  40. //BeFalse succeeds if actual is false
  41. func BeFalse() types.GomegaMatcher {
  42. return &matchers.BeFalseMatcher{}
  43. }
  44. //HaveOccurred succeeds if actual is a non-nil error
  45. //The typical Go error checking pattern looks like:
  46. // err := SomethingThatMightFail()
  47. // Expect(err).ShouldNot(HaveOccurred())
  48. func HaveOccurred() types.GomegaMatcher {
  49. return &matchers.HaveOccurredMatcher{}
  50. }
  51. //Succeed passes if actual is a nil error
  52. //Succeed is intended to be used with functions that return a single error value. Instead of
  53. // err := SomethingThatMightFail()
  54. // Expect(err).ShouldNot(HaveOccurred())
  55. //
  56. //You can write:
  57. // Expect(SomethingThatMightFail()).Should(Succeed())
  58. //
  59. //It is a mistake to use Succeed with a function that has multiple return values. Gomega's Ω and Expect
  60. //functions automatically trigger failure if any return values after the first return value are non-zero/non-nil.
  61. //This means that Ω(MultiReturnFunc()).ShouldNot(Succeed()) can never pass.
  62. func Succeed() types.GomegaMatcher {
  63. return &matchers.SucceedMatcher{}
  64. }
  65. //MatchError succeeds if actual is a non-nil error that matches the passed in string/error.
  66. //
  67. //These are valid use-cases:
  68. // Expect(err).Should(MatchError("an error")) //asserts that err.Error() == "an error"
  69. // Expect(err).Should(MatchError(SomeError)) //asserts that err == SomeError (via reflect.DeepEqual)
  70. //
  71. //It is an error for err to be nil or an object that does not implement the Error interface
  72. func MatchError(expected interface{}) types.GomegaMatcher {
  73. return &matchers.MatchErrorMatcher{
  74. Expected: expected,
  75. }
  76. }
  77. //BeClosed succeeds if actual is a closed channel.
  78. //It is an error to pass a non-channel to BeClosed, it is also an error to pass nil
  79. //
  80. //In order to check whether or not the channel is closed, Gomega must try to read from the channel
  81. //(even in the `ShouldNot(BeClosed())` case). You should keep this in mind if you wish to make subsequent assertions about
  82. //values coming down the channel.
  83. //
  84. //Also, if you are testing that a *buffered* channel is closed you must first read all values out of the channel before
  85. //asserting that it is closed (it is not possible to detect that a buffered-channel has been closed until all its buffered values are read).
  86. //
  87. //Finally, as a corollary: it is an error to check whether or not a send-only channel is closed.
  88. func BeClosed() types.GomegaMatcher {
  89. return &matchers.BeClosedMatcher{}
  90. }
  91. //Receive succeeds if there is a value to be received on actual.
  92. //Actual must be a channel (and cannot be a send-only channel) -- anything else is an error.
  93. //
  94. //Receive returns immediately and never blocks:
  95. //
  96. //- If there is nothing on the channel `c` then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.
  97. //
  98. //- If the channel `c` is closed then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.
  99. //
  100. //- If there is something on the channel `c` ready to be read, then Expect(c).Should(Receive()) will pass and Ω(c).ShouldNot(Receive()) will fail.
  101. //
  102. //If you have a go-routine running in the background that will write to channel `c` you can:
  103. // Eventually(c).Should(Receive())
  104. //
  105. //This will timeout if nothing gets sent to `c` (you can modify the timeout interval as you normally do with `Eventually`)
  106. //
  107. //A similar use-case is to assert that no go-routine writes to a channel (for a period of time). You can do this with `Consistently`:
  108. // Consistently(c).ShouldNot(Receive())
  109. //
  110. //You can pass `Receive` a matcher. If you do so, it will match the received object against the matcher. For example:
  111. // Expect(c).Should(Receive(Equal("foo")))
  112. //
  113. //When given a matcher, `Receive` will always fail if there is nothing to be received on the channel.
  114. //
  115. //Passing Receive a matcher is especially useful when paired with Eventually:
  116. //
  117. // Eventually(c).Should(Receive(ContainSubstring("bar")))
  118. //
  119. //will repeatedly attempt to pull values out of `c` until a value matching "bar" is received.
  120. //
  121. //Finally, if you want to have a reference to the value *sent* to the channel you can pass the `Receive` matcher a pointer to a variable of the appropriate type:
  122. // var myThing thing
  123. // Eventually(thingChan).Should(Receive(&myThing))
  124. // Expect(myThing.Sprocket).Should(Equal("foo"))
  125. // Expect(myThing.IsValid()).Should(BeTrue())
  126. func Receive(args ...interface{}) types.GomegaMatcher {
  127. var arg interface{}
  128. if len(args) > 0 {
  129. arg = args[0]
  130. }
  131. return &matchers.ReceiveMatcher{
  132. Arg: arg,
  133. }
  134. }
  135. //BeSent succeeds if a value can be sent to actual.
  136. //Actual must be a channel (and cannot be a receive-only channel) that can sent the type of the value passed into BeSent -- anything else is an error.
  137. //In addition, actual must not be closed.
  138. //
  139. //BeSent never blocks:
  140. //
  141. //- If the channel `c` is not ready to receive then Expect(c).Should(BeSent("foo")) will fail immediately
  142. //- If the channel `c` is eventually ready to receive then Eventually(c).Should(BeSent("foo")) will succeed.. presuming the channel becomes ready to receive before Eventually's timeout
  143. //- If the channel `c` is closed then Expect(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both fail immediately
  144. //
  145. //Of course, the value is actually sent to the channel. The point of `BeSent` is less to make an assertion about the availability of the channel (which is typically an implementation detail that your test should not be concerned with).
  146. //Rather, the point of `BeSent` is to make it possible to easily and expressively write tests that can timeout on blocked channel sends.
  147. func BeSent(arg interface{}) types.GomegaMatcher {
  148. return &matchers.BeSentMatcher{
  149. Arg: arg,
  150. }
  151. }
  152. //MatchRegexp succeeds if actual is a string or stringer that matches the
  153. //passed-in regexp. Optional arguments can be provided to construct a regexp
  154. //via fmt.Sprintf().
  155. func MatchRegexp(regexp string, args ...interface{}) types.GomegaMatcher {
  156. return &matchers.MatchRegexpMatcher{
  157. Regexp: regexp,
  158. Args: args,
  159. }
  160. }
  161. //ContainSubstring succeeds if actual is a string or stringer that contains the
  162. //passed-in substring. Optional arguments can be provided to construct the substring
  163. //via fmt.Sprintf().
  164. func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher {
  165. return &matchers.ContainSubstringMatcher{
  166. Substr: substr,
  167. Args: args,
  168. }
  169. }
  170. //HavePrefix succeeds if actual is a string or stringer that contains the
  171. //passed-in string as a prefix. Optional arguments can be provided to construct
  172. //via fmt.Sprintf().
  173. func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher {
  174. return &matchers.HavePrefixMatcher{
  175. Prefix: prefix,
  176. Args: args,
  177. }
  178. }
  179. //HaveSuffix succeeds if actual is a string or stringer that contains the
  180. //passed-in string as a suffix. Optional arguments can be provided to construct
  181. //via fmt.Sprintf().
  182. func HaveSuffix(suffix string, args ...interface{}) types.GomegaMatcher {
  183. return &matchers.HaveSuffixMatcher{
  184. Suffix: suffix,
  185. Args: args,
  186. }
  187. }
  188. //MatchJSON succeeds if actual is a string or stringer of JSON that matches
  189. //the expected JSON. The JSONs are decoded and the resulting objects are compared via
  190. //reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter.
  191. func MatchJSON(json interface{}) types.GomegaMatcher {
  192. return &matchers.MatchJSONMatcher{
  193. JSONToMatch: json,
  194. }
  195. }
  196. //MatchXML succeeds if actual is a string or stringer of XML that matches
  197. //the expected XML. The XMLs are decoded and the resulting objects are compared via
  198. //reflect.DeepEqual so things like whitespaces shouldn't matter.
  199. func MatchXML(xml interface{}) types.GomegaMatcher {
  200. return &matchers.MatchXMLMatcher{
  201. XMLToMatch: xml,
  202. }
  203. }
  204. //MatchYAML succeeds if actual is a string or stringer of YAML that matches
  205. //the expected YAML. The YAML's are decoded and the resulting objects are compared via
  206. //reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter.
  207. func MatchYAML(yaml interface{}) types.GomegaMatcher {
  208. return &matchers.MatchYAMLMatcher{
  209. YAMLToMatch: yaml,
  210. }
  211. }
  212. //BeEmpty succeeds if actual is empty. Actual must be of type string, array, map, chan, or slice.
  213. func BeEmpty() types.GomegaMatcher {
  214. return &matchers.BeEmptyMatcher{}
  215. }
  216. //HaveLen succeeds if actual has the passed-in length. Actual must be of type string, array, map, chan, or slice.
  217. func HaveLen(count int) types.GomegaMatcher {
  218. return &matchers.HaveLenMatcher{
  219. Count: count,
  220. }
  221. }
  222. //HaveCap succeeds if actual has the passed-in capacity. Actual must be of type array, chan, or slice.
  223. func HaveCap(count int) types.GomegaMatcher {
  224. return &matchers.HaveCapMatcher{
  225. Count: count,
  226. }
  227. }
  228. //BeZero succeeds if actual is the zero value for its type or if actual is nil.
  229. func BeZero() types.GomegaMatcher {
  230. return &matchers.BeZeroMatcher{}
  231. }
  232. //ContainElement succeeds if actual contains the passed in element.
  233. //By default ContainElement() uses Equal() to perform the match, however a
  234. //matcher can be passed in instead:
  235. // Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar")))
  236. //
  237. //Actual must be an array, slice or map.
  238. //For maps, ContainElement searches through the map's values.
  239. func ContainElement(element interface{}) types.GomegaMatcher {
  240. return &matchers.ContainElementMatcher{
  241. Element: element,
  242. }
  243. }
  244. //BeElementOf succeeds if actual is contained in the passed in elements.
  245. //BeElementOf() always uses Equal() to perform the match.
  246. //When the passed in elements are comprised of a single element that is either an Array or Slice, BeElementOf() behaves
  247. //as the reverse of ContainElement() that operates with Equal() to perform the match.
  248. // Expect(2).Should(BeElementOf([]int{1, 2}))
  249. // Expect(2).Should(BeElementOf([2]int{1, 2}))
  250. //Otherwise, BeElementOf() provides a syntactic sugar for Or(Equal(_), Equal(_), ...):
  251. // Expect(2).Should(BeElementOf(1, 2))
  252. //
  253. //Actual must be typed.
  254. func BeElementOf(elements ...interface{}) types.GomegaMatcher {
  255. return &matchers.BeElementOfMatcher{
  256. Elements: elements,
  257. }
  258. }
  259. //ConsistOf succeeds if actual contains precisely the elements passed into the matcher. The ordering of the elements does not matter.
  260. //By default ConsistOf() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples:
  261. //
  262. // Expect([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo"))
  263. // Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo"))
  264. // Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo")))
  265. //
  266. //Actual must be an array, slice or map. For maps, ConsistOf matches against the map's values.
  267. //
  268. //You typically pass variadic arguments to ConsistOf (as in the examples above). However, if you need to pass in a slice you can provided that it
  269. //is the only element passed in to ConsistOf:
  270. //
  271. // Expect([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"}))
  272. //
  273. //Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []interface{} are different types - hence the need for this special rule.
  274. func ConsistOf(elements ...interface{}) types.GomegaMatcher {
  275. return &matchers.ConsistOfMatcher{
  276. Elements: elements,
  277. }
  278. }
  279. //ContainElements succeeds if actual contains the passed in elements. The ordering of the elements does not matter.
  280. //By default ContainElements() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples:
  281. //
  282. // Expect([]string{"Foo", "FooBar"}).Should(ContainElements("FooBar"))
  283. // Expect([]string{"Foo", "FooBar"}).Should(ContainElements(ContainSubstring("Bar"), "Foo"))
  284. //
  285. //Actual must be an array, slice or map.
  286. //For maps, ContainElements searches through the map's values.
  287. func ContainElements(elements ...interface{}) types.GomegaMatcher {
  288. return &matchers.ContainElementsMatcher{
  289. Elements: elements,
  290. }
  291. }
  292. //HaveKey succeeds if actual is a map with the passed in key.
  293. //By default HaveKey uses Equal() to perform the match, however a
  294. //matcher can be passed in instead:
  295. // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`)))
  296. func HaveKey(key interface{}) types.GomegaMatcher {
  297. return &matchers.HaveKeyMatcher{
  298. Key: key,
  299. }
  300. }
  301. //HaveKeyWithValue succeeds if actual is a map with the passed in key and value.
  302. //By default HaveKeyWithValue uses Equal() to perform the match, however a
  303. //matcher can be passed in instead:
  304. // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar"))
  305. // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar"))
  306. func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher {
  307. return &matchers.HaveKeyWithValueMatcher{
  308. Key: key,
  309. Value: value,
  310. }
  311. }
  312. //BeNumerically performs numerical assertions in a type-agnostic way.
  313. //Actual and expected should be numbers, though the specific type of
  314. //number is irrelevant (float32, float64, uint8, etc...).
  315. //
  316. //There are six, self-explanatory, supported comparators:
  317. // Expect(1.0).Should(BeNumerically("==", 1))
  318. // Expect(1.0).Should(BeNumerically("~", 0.999, 0.01))
  319. // Expect(1.0).Should(BeNumerically(">", 0.9))
  320. // Expect(1.0).Should(BeNumerically(">=", 1.0))
  321. // Expect(1.0).Should(BeNumerically("<", 3))
  322. // Expect(1.0).Should(BeNumerically("<=", 1.0))
  323. func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatcher {
  324. return &matchers.BeNumericallyMatcher{
  325. Comparator: comparator,
  326. CompareTo: compareTo,
  327. }
  328. }
  329. //BeTemporally compares time.Time's like BeNumerically
  330. //Actual and expected must be time.Time. The comparators are the same as for BeNumerically
  331. // Expect(time.Now()).Should(BeTemporally(">", time.Time{}))
  332. // Expect(time.Now()).Should(BeTemporally("~", time.Now(), time.Second))
  333. func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher {
  334. return &matchers.BeTemporallyMatcher{
  335. Comparator: comparator,
  336. CompareTo: compareTo,
  337. Threshold: threshold,
  338. }
  339. }
  340. //BeAssignableToTypeOf succeeds if actual is assignable to the type of expected.
  341. //It will return an error when one of the values is nil.
  342. // Expect(0).Should(BeAssignableToTypeOf(0)) // Same values
  343. // Expect(5).Should(BeAssignableToTypeOf(-1)) // different values same type
  344. // Expect("foo").Should(BeAssignableToTypeOf("bar")) // different values same type
  345. // Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{}))
  346. func BeAssignableToTypeOf(expected interface{}) types.GomegaMatcher {
  347. return &matchers.AssignableToTypeOfMatcher{
  348. Expected: expected,
  349. }
  350. }
  351. //Panic succeeds if actual is a function that, when invoked, panics.
  352. //Actual must be a function that takes no arguments and returns no results.
  353. func Panic() types.GomegaMatcher {
  354. return &matchers.PanicMatcher{}
  355. }
  356. //PanicWith succeeds if actual is a function that, when invoked, panics with a specific value.
  357. //Actual must be a function that takes no arguments and returns no results.
  358. //
  359. //By default PanicWith uses Equal() to perform the match, however a
  360. //matcher can be passed in instead:
  361. // Expect(fn).Should(PanicWith(MatchRegexp(`.+Foo$`)))
  362. func PanicWith(expected interface{}) types.GomegaMatcher {
  363. return &matchers.PanicMatcher{Expected: expected}
  364. }
  365. //BeAnExistingFile succeeds if a file exists.
  366. //Actual must be a string representing the abs path to the file being checked.
  367. func BeAnExistingFile() types.GomegaMatcher {
  368. return &matchers.BeAnExistingFileMatcher{}
  369. }
  370. //BeARegularFile succeeds if a file exists and is a regular file.
  371. //Actual must be a string representing the abs path to the file being checked.
  372. func BeARegularFile() types.GomegaMatcher {
  373. return &matchers.BeARegularFileMatcher{}
  374. }
  375. //BeADirectory succeeds if a file exists and is a directory.
  376. //Actual must be a string representing the abs path to the file being checked.
  377. func BeADirectory() types.GomegaMatcher {
  378. return &matchers.BeADirectoryMatcher{}
  379. }
  380. //HaveHTTPStatus succeeds if the Status or StatusCode field of an HTTP response matches.
  381. //Actual must be either a *http.Response or *httptest.ResponseRecorder.
  382. //Expected must be either an int or a string.
  383. // Expect(resp).Should(HaveHTTPStatus(http.StatusOK)) // asserts that resp.StatusCode == 200
  384. // Expect(resp).Should(HaveHTTPStatus("404 Not Found")) // asserts that resp.Status == "404 Not Found"
  385. func HaveHTTPStatus(expected interface{}) types.GomegaMatcher {
  386. return &matchers.HaveHTTPStatusMatcher{Expected: expected}
  387. }
  388. //And succeeds only if all of the given matchers succeed.
  389. //The matchers are tried in order, and will fail-fast if one doesn't succeed.
  390. // Expect("hi").To(And(HaveLen(2), Equal("hi"))
  391. //
  392. //And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
  393. func And(ms ...types.GomegaMatcher) types.GomegaMatcher {
  394. return &matchers.AndMatcher{Matchers: ms}
  395. }
  396. //SatisfyAll is an alias for And().
  397. // Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi")))
  398. func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher {
  399. return And(matchers...)
  400. }
  401. //Or succeeds if any of the given matchers succeed.
  402. //The matchers are tried in order and will return immediately upon the first successful match.
  403. // Expect("hi").To(Or(HaveLen(3), HaveLen(2))
  404. //
  405. //And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
  406. func Or(ms ...types.GomegaMatcher) types.GomegaMatcher {
  407. return &matchers.OrMatcher{Matchers: ms}
  408. }
  409. //SatisfyAny is an alias for Or().
  410. // Expect("hi").SatisfyAny(Or(HaveLen(3), HaveLen(2))
  411. func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher {
  412. return Or(matchers...)
  413. }
  414. //Not negates the given matcher; it succeeds if the given matcher fails.
  415. // Expect(1).To(Not(Equal(2))
  416. //
  417. //And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
  418. func Not(matcher types.GomegaMatcher) types.GomegaMatcher {
  419. return &matchers.NotMatcher{Matcher: matcher}
  420. }
  421. //WithTransform applies the `transform` to the actual value and matches it against `matcher`.
  422. //The given transform must be a function of one parameter that returns one value.
  423. // var plus1 = func(i int) int { return i + 1 }
  424. // Expect(1).To(WithTransform(plus1, Equal(2))
  425. //
  426. //And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
  427. func WithTransform(transform interface{}, matcher types.GomegaMatcher) types.GomegaMatcher {
  428. return matchers.NewWithTransformMatcher(transform, matcher)
  429. }
  430. //Satisfy matches the actual value against the `predicate` function.
  431. //The given predicate must be a function of one paramter that returns bool.
  432. // var isEven = func(i int) bool { return i%2 == 0 }
  433. // Expect(2).To(Satisfy(isEven))
  434. func Satisfy(predicate interface{}) types.GomegaMatcher {
  435. return matchers.NewSatisfyMatcher(predicate)
  436. }