matchers.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. //HaveKey succeeds if actual is a map with the passed in key.
  280. //By default HaveKey uses Equal() to perform the match, however a
  281. //matcher can be passed in instead:
  282. // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`)))
  283. func HaveKey(key interface{}) types.GomegaMatcher {
  284. return &matchers.HaveKeyMatcher{
  285. Key: key,
  286. }
  287. }
  288. //HaveKeyWithValue succeeds if actual is a map with the passed in key and value.
  289. //By default HaveKeyWithValue uses Equal() to perform the match, however a
  290. //matcher can be passed in instead:
  291. // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar"))
  292. // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar"))
  293. func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher {
  294. return &matchers.HaveKeyWithValueMatcher{
  295. Key: key,
  296. Value: value,
  297. }
  298. }
  299. //BeNumerically performs numerical assertions in a type-agnostic way.
  300. //Actual and expected should be numbers, though the specific type of
  301. //number is irrelevant (float32, float64, uint8, etc...).
  302. //
  303. //There are six, self-explanatory, supported comparators:
  304. // Expect(1.0).Should(BeNumerically("==", 1))
  305. // Expect(1.0).Should(BeNumerically("~", 0.999, 0.01))
  306. // Expect(1.0).Should(BeNumerically(">", 0.9))
  307. // Expect(1.0).Should(BeNumerically(">=", 1.0))
  308. // Expect(1.0).Should(BeNumerically("<", 3))
  309. // Expect(1.0).Should(BeNumerically("<=", 1.0))
  310. func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatcher {
  311. return &matchers.BeNumericallyMatcher{
  312. Comparator: comparator,
  313. CompareTo: compareTo,
  314. }
  315. }
  316. //BeTemporally compares time.Time's like BeNumerically
  317. //Actual and expected must be time.Time. The comparators are the same as for BeNumerically
  318. // Expect(time.Now()).Should(BeTemporally(">", time.Time{}))
  319. // Expect(time.Now()).Should(BeTemporally("~", time.Now(), time.Second))
  320. func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher {
  321. return &matchers.BeTemporallyMatcher{
  322. Comparator: comparator,
  323. CompareTo: compareTo,
  324. Threshold: threshold,
  325. }
  326. }
  327. //BeAssignableToTypeOf succeeds if actual is assignable to the type of expected.
  328. //It will return an error when one of the values is nil.
  329. // Expect(0).Should(BeAssignableToTypeOf(0)) // Same values
  330. // Expect(5).Should(BeAssignableToTypeOf(-1)) // different values same type
  331. // Expect("foo").Should(BeAssignableToTypeOf("bar")) // different values same type
  332. // Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{}))
  333. func BeAssignableToTypeOf(expected interface{}) types.GomegaMatcher {
  334. return &matchers.AssignableToTypeOfMatcher{
  335. Expected: expected,
  336. }
  337. }
  338. //Panic succeeds if actual is a function that, when invoked, panics.
  339. //Actual must be a function that takes no arguments and returns no results.
  340. func Panic() types.GomegaMatcher {
  341. return &matchers.PanicMatcher{}
  342. }
  343. //BeAnExistingFile succeeds if a file exists.
  344. //Actual must be a string representing the abs path to the file being checked.
  345. func BeAnExistingFile() types.GomegaMatcher {
  346. return &matchers.BeAnExistingFileMatcher{}
  347. }
  348. //BeARegularFile succeeds if a file exists and is a regular file.
  349. //Actual must be a string representing the abs path to the file being checked.
  350. func BeARegularFile() types.GomegaMatcher {
  351. return &matchers.BeARegularFileMatcher{}
  352. }
  353. //BeADirectory succeeds if a file exists and is a directory.
  354. //Actual must be a string representing the abs path to the file being checked.
  355. func BeADirectory() types.GomegaMatcher {
  356. return &matchers.BeADirectoryMatcher{}
  357. }
  358. //And succeeds only if all of the given matchers succeed.
  359. //The matchers are tried in order, and will fail-fast if one doesn't succeed.
  360. // Expect("hi").To(And(HaveLen(2), Equal("hi"))
  361. //
  362. //And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
  363. func And(ms ...types.GomegaMatcher) types.GomegaMatcher {
  364. return &matchers.AndMatcher{Matchers: ms}
  365. }
  366. //SatisfyAll is an alias for And().
  367. // Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi")))
  368. func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher {
  369. return And(matchers...)
  370. }
  371. //Or succeeds if any of the given matchers succeed.
  372. //The matchers are tried in order and will return immediately upon the first successful match.
  373. // Expect("hi").To(Or(HaveLen(3), HaveLen(2))
  374. //
  375. //And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
  376. func Or(ms ...types.GomegaMatcher) types.GomegaMatcher {
  377. return &matchers.OrMatcher{Matchers: ms}
  378. }
  379. //SatisfyAny is an alias for Or().
  380. // Expect("hi").SatisfyAny(Or(HaveLen(3), HaveLen(2))
  381. func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher {
  382. return Or(matchers...)
  383. }
  384. //Not negates the given matcher; it succeeds if the given matcher fails.
  385. // Expect(1).To(Not(Equal(2))
  386. //
  387. //And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
  388. func Not(matcher types.GomegaMatcher) types.GomegaMatcher {
  389. return &matchers.NotMatcher{Matcher: matcher}
  390. }
  391. //WithTransform applies the `transform` to the actual value and matches it against `matcher`.
  392. //The given transform must be a function of one parameter that returns one value.
  393. // var plus1 = func(i int) int { return i + 1 }
  394. // Expect(1).To(WithTransform(plus1, Equal(2))
  395. //
  396. //And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
  397. func WithTransform(transform interface{}, matcher types.GomegaMatcher) types.GomegaMatcher {
  398. return matchers.NewWithTransformMatcher(transform, matcher)
  399. }