Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/vendor/github.com/onsi/gomega/matchers.go
3510 views
1
package gomega
2
3
import (
4
"fmt"
5
"time"
6
7
"github.com/google/go-cmp/cmp"
8
"github.com/onsi/gomega/matchers"
9
"github.com/onsi/gomega/types"
10
)
11
12
// Equal uses reflect.DeepEqual to compare actual with expected. Equal is strict about
13
// types when performing comparisons.
14
// It is an error for both actual and expected to be nil. Use BeNil() instead.
15
func Equal(expected any) types.GomegaMatcher {
16
return &matchers.EqualMatcher{
17
Expected: expected,
18
}
19
}
20
21
// BeEquivalentTo is more lax than Equal, allowing equality between different types.
22
// This is done by converting actual to have the type of expected before
23
// attempting equality with reflect.DeepEqual.
24
// It is an error for actual and expected to be nil. Use BeNil() instead.
25
func BeEquivalentTo(expected any) types.GomegaMatcher {
26
return &matchers.BeEquivalentToMatcher{
27
Expected: expected,
28
}
29
}
30
31
// BeComparableTo uses gocmp.Equal from github.com/google/go-cmp (instead of reflect.DeepEqual) to perform a deep comparison.
32
// You can pass cmp.Option as options.
33
// It is an error for actual and expected to be nil. Use BeNil() instead.
34
func BeComparableTo(expected any, opts ...cmp.Option) types.GomegaMatcher {
35
return &matchers.BeComparableToMatcher{
36
Expected: expected,
37
Options: opts,
38
}
39
}
40
41
// BeIdenticalTo uses the == operator to compare actual with expected.
42
// BeIdenticalTo is strict about types when performing comparisons.
43
// It is an error for both actual and expected to be nil. Use BeNil() instead.
44
func BeIdenticalTo(expected any) types.GomegaMatcher {
45
return &matchers.BeIdenticalToMatcher{
46
Expected: expected,
47
}
48
}
49
50
// BeNil succeeds if actual is nil
51
func BeNil() types.GomegaMatcher {
52
return &matchers.BeNilMatcher{}
53
}
54
55
// BeTrue succeeds if actual is true
56
//
57
// In general, it's better to use `BeTrueBecause(reason)` to provide a more useful error message if a true check fails.
58
func BeTrue() types.GomegaMatcher {
59
return &matchers.BeTrueMatcher{}
60
}
61
62
// BeFalse succeeds if actual is false
63
//
64
// In general, it's better to use `BeFalseBecause(reason)` to provide a more useful error message if a false check fails.
65
func BeFalse() types.GomegaMatcher {
66
return &matchers.BeFalseMatcher{}
67
}
68
69
// BeTrueBecause succeeds if actual is true and displays the provided reason if it is false
70
// fmt.Sprintf is used to render the reason
71
func BeTrueBecause(format string, args ...any) types.GomegaMatcher {
72
return &matchers.BeTrueMatcher{Reason: fmt.Sprintf(format, args...)}
73
}
74
75
// BeFalseBecause succeeds if actual is false and displays the provided reason if it is true.
76
// fmt.Sprintf is used to render the reason
77
func BeFalseBecause(format string, args ...any) types.GomegaMatcher {
78
return &matchers.BeFalseMatcher{Reason: fmt.Sprintf(format, args...)}
79
}
80
81
// HaveOccurred succeeds if actual is a non-nil error
82
// The typical Go error checking pattern looks like:
83
//
84
// err := SomethingThatMightFail()
85
// Expect(err).ShouldNot(HaveOccurred())
86
func HaveOccurred() types.GomegaMatcher {
87
return &matchers.HaveOccurredMatcher{}
88
}
89
90
// Succeed passes if actual is a nil error
91
// Succeed is intended to be used with functions that return a single error value. Instead of
92
//
93
// err := SomethingThatMightFail()
94
// Expect(err).ShouldNot(HaveOccurred())
95
//
96
// You can write:
97
//
98
// Expect(SomethingThatMightFail()).Should(Succeed())
99
//
100
// It is a mistake to use Succeed with a function that has multiple return values. Gomega's Ω and Expect
101
// functions automatically trigger failure if any return values after the first return value are non-zero/non-nil.
102
// This means that Ω(MultiReturnFunc()).ShouldNot(Succeed()) can never pass.
103
func Succeed() types.GomegaMatcher {
104
return &matchers.SucceedMatcher{}
105
}
106
107
// MatchError succeeds if actual is a non-nil error that matches the passed in
108
// string, error, function, or matcher.
109
//
110
// These are valid use-cases:
111
//
112
// When passed a string:
113
//
114
// Expect(err).To(MatchError("an error"))
115
//
116
// asserts that err.Error() == "an error"
117
//
118
// When passed an error:
119
//
120
// Expect(err).To(MatchError(SomeError))
121
//
122
// First checks if errors.Is(err, SomeError).
123
// If that fails then it checks if reflect.DeepEqual(err, SomeError) repeatedly for err and any errors wrapped by err
124
//
125
// When passed a matcher:
126
//
127
// Expect(err).To(MatchError(ContainSubstring("sprocket not found")))
128
//
129
// the matcher is passed err.Error(). In this case it asserts that err.Error() contains substring "sprocket not found"
130
//
131
// When passed a func(err) bool and a description:
132
//
133
// Expect(err).To(MatchError(os.IsNotExist, "IsNotExist"))
134
//
135
// the function is passed err and matches if the return value is true. The description is required to allow Gomega
136
// to print a useful error message.
137
//
138
// It is an error for err to be nil or an object that does not implement the
139
// Error interface
140
//
141
// The optional second argument is a description of the error function, if used. This is required when passing a function but is ignored in all other cases.
142
func MatchError(expected any, functionErrorDescription ...any) types.GomegaMatcher {
143
return &matchers.MatchErrorMatcher{
144
Expected: expected,
145
FuncErrDescription: functionErrorDescription,
146
}
147
}
148
149
// MatchErrorStrictly succeeds iff actual is a non-nil error that matches the passed in
150
// expected error according to errors.Is(actual, expected).
151
//
152
// This behavior differs from MatchError where
153
//
154
// Expect(errors.New("some error")).To(MatchError(errors.New("some error")))
155
//
156
// succeeds, but errors.Is would return false so:
157
//
158
// Expect(errors.New("some error")).To(MatchErrorStrictly(errors.New("some error")))
159
//
160
// fails.
161
func MatchErrorStrictly(expected error) types.GomegaMatcher {
162
return &matchers.MatchErrorStrictlyMatcher{
163
Expected: expected,
164
}
165
}
166
167
// BeClosed succeeds if actual is a closed channel.
168
// It is an error to pass a non-channel to BeClosed, it is also an error to pass nil
169
//
170
// In order to check whether or not the channel is closed, Gomega must try to read from the channel
171
// (even in the `ShouldNot(BeClosed())` case). You should keep this in mind if you wish to make subsequent assertions about
172
// values coming down the channel.
173
//
174
// Also, if you are testing that a *buffered* channel is closed you must first read all values out of the channel before
175
// 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).
176
//
177
// Finally, as a corollary: it is an error to check whether or not a send-only channel is closed.
178
func BeClosed() types.GomegaMatcher {
179
return &matchers.BeClosedMatcher{}
180
}
181
182
// Receive succeeds if there is a value to be received on actual.
183
// Actual must be a channel (and cannot be a send-only channel) -- anything else is an error.
184
//
185
// Receive returns immediately and never blocks:
186
//
187
// - If there is nothing on the channel `c` then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.
188
//
189
// - If the channel `c` is closed then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.
190
//
191
// - 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.
192
//
193
// If you have a go-routine running in the background that will write to channel `c` you can:
194
//
195
// Eventually(c).Should(Receive())
196
//
197
// This will timeout if nothing gets sent to `c` (you can modify the timeout interval as you normally do with `Eventually`)
198
//
199
// 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`:
200
//
201
// Consistently(c).ShouldNot(Receive())
202
//
203
// You can pass `Receive` a matcher. If you do so, it will match the received object against the matcher. For example:
204
//
205
// Expect(c).Should(Receive(Equal("foo")))
206
//
207
// When given a matcher, `Receive` will always fail if there is nothing to be received on the channel.
208
//
209
// Passing Receive a matcher is especially useful when paired with Eventually:
210
//
211
// Eventually(c).Should(Receive(ContainSubstring("bar")))
212
//
213
// will repeatedly attempt to pull values out of `c` until a value matching "bar" is received.
214
//
215
// Furthermore, 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:
216
//
217
// var myThing thing
218
// Eventually(thingChan).Should(Receive(&myThing))
219
// Expect(myThing.Sprocket).Should(Equal("foo"))
220
// Expect(myThing.IsValid()).Should(BeTrue())
221
//
222
// Finally, if you want to match the received object as well as get the actual received value into a variable, so you can reason further about the value received,
223
// you can pass a pointer to a variable of the appropriate type first, and second a matcher:
224
//
225
// var myThing thing
226
// Eventually(thingChan).Should(Receive(&myThing, ContainSubstring("bar")))
227
func Receive(args ...any) types.GomegaMatcher {
228
return &matchers.ReceiveMatcher{
229
Args: args,
230
}
231
}
232
233
// BeSent succeeds if a value can be sent to actual.
234
// 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.
235
// In addition, actual must not be closed.
236
//
237
// BeSent never blocks:
238
//
239
// - If the channel `c` is not ready to receive then Expect(c).Should(BeSent("foo")) will fail immediately
240
// - 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
241
// - If the channel `c` is closed then Expect(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both fail immediately
242
//
243
// 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).
244
// Rather, the point of `BeSent` is to make it possible to easily and expressively write tests that can timeout on blocked channel sends.
245
func BeSent(arg any) types.GomegaMatcher {
246
return &matchers.BeSentMatcher{
247
Arg: arg,
248
}
249
}
250
251
// MatchRegexp succeeds if actual is a string or stringer that matches the
252
// passed-in regexp. Optional arguments can be provided to construct a regexp
253
// via fmt.Sprintf().
254
func MatchRegexp(regexp string, args ...any) types.GomegaMatcher {
255
return &matchers.MatchRegexpMatcher{
256
Regexp: regexp,
257
Args: args,
258
}
259
}
260
261
// ContainSubstring succeeds if actual is a string or stringer that contains the
262
// passed-in substring. Optional arguments can be provided to construct the substring
263
// via fmt.Sprintf().
264
func ContainSubstring(substr string, args ...any) types.GomegaMatcher {
265
return &matchers.ContainSubstringMatcher{
266
Substr: substr,
267
Args: args,
268
}
269
}
270
271
// HavePrefix succeeds if actual is a string or stringer that contains the
272
// passed-in string as a prefix. Optional arguments can be provided to construct
273
// via fmt.Sprintf().
274
func HavePrefix(prefix string, args ...any) types.GomegaMatcher {
275
return &matchers.HavePrefixMatcher{
276
Prefix: prefix,
277
Args: args,
278
}
279
}
280
281
// HaveSuffix succeeds if actual is a string or stringer that contains the
282
// passed-in string as a suffix. Optional arguments can be provided to construct
283
// via fmt.Sprintf().
284
func HaveSuffix(suffix string, args ...any) types.GomegaMatcher {
285
return &matchers.HaveSuffixMatcher{
286
Suffix: suffix,
287
Args: args,
288
}
289
}
290
291
// MatchJSON succeeds if actual is a string or stringer of JSON that matches
292
// the expected JSON. The JSONs are decoded and the resulting objects are compared via
293
// reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter.
294
func MatchJSON(json any) types.GomegaMatcher {
295
return &matchers.MatchJSONMatcher{
296
JSONToMatch: json,
297
}
298
}
299
300
// MatchXML succeeds if actual is a string or stringer of XML that matches
301
// the expected XML. The XMLs are decoded and the resulting objects are compared via
302
// reflect.DeepEqual so things like whitespaces shouldn't matter.
303
func MatchXML(xml any) types.GomegaMatcher {
304
return &matchers.MatchXMLMatcher{
305
XMLToMatch: xml,
306
}
307
}
308
309
// MatchYAML succeeds if actual is a string or stringer of YAML that matches
310
// the expected YAML. The YAML's are decoded and the resulting objects are compared via
311
// reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter.
312
func MatchYAML(yaml any) types.GomegaMatcher {
313
return &matchers.MatchYAMLMatcher{
314
YAMLToMatch: yaml,
315
}
316
}
317
318
// BeEmpty succeeds if actual is empty. Actual must be of type string, array, map, chan, or slice.
319
func BeEmpty() types.GomegaMatcher {
320
return &matchers.BeEmptyMatcher{}
321
}
322
323
// HaveLen succeeds if actual has the passed-in length. Actual must be of type string, array, map, chan, or slice.
324
func HaveLen(count int) types.GomegaMatcher {
325
return &matchers.HaveLenMatcher{
326
Count: count,
327
}
328
}
329
330
// HaveCap succeeds if actual has the passed-in capacity. Actual must be of type array, chan, or slice.
331
func HaveCap(count int) types.GomegaMatcher {
332
return &matchers.HaveCapMatcher{
333
Count: count,
334
}
335
}
336
337
// BeZero succeeds if actual is the zero value for its type or if actual is nil.
338
func BeZero() types.GomegaMatcher {
339
return &matchers.BeZeroMatcher{}
340
}
341
342
// ContainElement succeeds if actual contains the passed in element. By default
343
// ContainElement() uses Equal() to perform the match, however a matcher can be
344
// passed in instead:
345
//
346
// Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar")))
347
//
348
// Actual must be an array, slice or map. For maps, ContainElement searches
349
// through the map's values.
350
//
351
// If you want to have a copy of the matching element(s) found you can pass a
352
// pointer to a variable of the appropriate type. If the variable isn't a slice
353
// or map, then exactly one match will be expected and returned. If the variable
354
// is a slice or map, then at least one match is expected and all matches will be
355
// stored in the variable.
356
//
357
// var findings []string
358
// Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubString("Bar", &findings)))
359
func ContainElement(element any, result ...any) types.GomegaMatcher {
360
return &matchers.ContainElementMatcher{
361
Element: element,
362
Result: result,
363
}
364
}
365
366
// BeElementOf succeeds if actual is contained in the passed in elements.
367
// BeElementOf() always uses Equal() to perform the match.
368
// When the passed in elements are comprised of a single element that is either an Array or Slice, BeElementOf() behaves
369
// as the reverse of ContainElement() that operates with Equal() to perform the match.
370
//
371
// Expect(2).Should(BeElementOf([]int{1, 2}))
372
// Expect(2).Should(BeElementOf([2]int{1, 2}))
373
//
374
// Otherwise, BeElementOf() provides a syntactic sugar for Or(Equal(_), Equal(_), ...):
375
//
376
// Expect(2).Should(BeElementOf(1, 2))
377
//
378
// Actual must be typed.
379
func BeElementOf(elements ...any) types.GomegaMatcher {
380
return &matchers.BeElementOfMatcher{
381
Elements: elements,
382
}
383
}
384
385
// BeKeyOf succeeds if actual is contained in the keys of the passed in map.
386
// BeKeyOf() always uses Equal() to perform the match between actual and the map keys.
387
//
388
// Expect("foo").Should(BeKeyOf(map[string]bool{"foo": true, "bar": false}))
389
func BeKeyOf(element any) types.GomegaMatcher {
390
return &matchers.BeKeyOfMatcher{
391
Map: element,
392
}
393
}
394
395
// ConsistOf succeeds if actual contains precisely the elements passed into the matcher. The ordering of the elements does not matter.
396
// By default ConsistOf() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples:
397
//
398
// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo"))
399
// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo"))
400
// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo")))
401
//
402
// Actual must be an array, slice or map. For maps, ConsistOf matches against the map's values.
403
//
404
// 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
405
// is the only element passed in to ConsistOf:
406
//
407
// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"}))
408
//
409
// Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []any are different types - hence the need for this special rule.
410
func ConsistOf(elements ...any) types.GomegaMatcher {
411
return &matchers.ConsistOfMatcher{
412
Elements: elements,
413
}
414
}
415
416
// HaveExactElements succeeds if actual contains elements that precisely match the elements passed into the matcher. The ordering of the elements does matter.
417
// By default HaveExactElements() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples:
418
//
419
// Expect([]string{"Foo", "FooBar"}).Should(HaveExactElements("Foo", "FooBar"))
420
// Expect([]string{"Foo", "FooBar"}).Should(HaveExactElements("Foo", ContainSubstring("Bar")))
421
// Expect([]string{"Foo", "FooBar"}).Should(HaveExactElements(ContainSubstring("Foo"), ContainSubstring("Foo")))
422
//
423
// Actual must be an array or slice.
424
func HaveExactElements(elements ...any) types.GomegaMatcher {
425
return &matchers.HaveExactElementsMatcher{
426
Elements: elements,
427
}
428
}
429
430
// ContainElements succeeds if actual contains the passed in elements. The ordering of the elements does not matter.
431
// By default ContainElements() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples:
432
//
433
// Expect([]string{"Foo", "FooBar"}).Should(ContainElements("FooBar"))
434
// Expect([]string{"Foo", "FooBar"}).Should(ContainElements(ContainSubstring("Bar"), "Foo"))
435
//
436
// Actual must be an array, slice or map.
437
// For maps, ContainElements searches through the map's values.
438
func ContainElements(elements ...any) types.GomegaMatcher {
439
return &matchers.ContainElementsMatcher{
440
Elements: elements,
441
}
442
}
443
444
// HaveEach succeeds if actual solely contains elements that match the passed in element.
445
// Please note that if actual is empty, HaveEach always will fail.
446
// By default HaveEach() uses Equal() to perform the match, however a
447
// matcher can be passed in instead:
448
//
449
// Expect([]string{"Foo", "FooBar"}).Should(HaveEach(ContainSubstring("Foo")))
450
//
451
// Actual must be an array, slice or map.
452
// For maps, HaveEach searches through the map's values.
453
func HaveEach(element any) types.GomegaMatcher {
454
return &matchers.HaveEachMatcher{
455
Element: element,
456
}
457
}
458
459
// HaveKey succeeds if actual is a map with the passed in key.
460
// By default HaveKey uses Equal() to perform the match, however a
461
// matcher can be passed in instead:
462
//
463
// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`)))
464
func HaveKey(key any) types.GomegaMatcher {
465
return &matchers.HaveKeyMatcher{
466
Key: key,
467
}
468
}
469
470
// HaveKeyWithValue succeeds if actual is a map with the passed in key and value.
471
// By default HaveKeyWithValue uses Equal() to perform the match, however a
472
// matcher can be passed in instead:
473
//
474
// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar"))
475
// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar"))
476
func HaveKeyWithValue(key any, value any) types.GomegaMatcher {
477
return &matchers.HaveKeyWithValueMatcher{
478
Key: key,
479
Value: value,
480
}
481
}
482
483
// HaveField succeeds if actual is a struct and the value at the passed in field
484
// matches the passed in matcher. By default HaveField used Equal() to perform the match,
485
// however a matcher can be passed in in stead.
486
//
487
// The field must be a string that resolves to the name of a field in the struct. Structs can be traversed
488
// using the '.' delimiter. If the field ends with '()' a method named field is assumed to exist on the struct and is invoked.
489
// Such methods must take no arguments and return a single value:
490
//
491
// type Book struct {
492
// Title string
493
// Author Person
494
// }
495
// type Person struct {
496
// FirstName string
497
// LastName string
498
// DOB time.Time
499
// }
500
// Expect(book).To(HaveField("Title", "Les Miserables"))
501
// Expect(book).To(HaveField("Title", ContainSubstring("Les"))
502
// Expect(book).To(HaveField("Author.FirstName", Equal("Victor"))
503
// Expect(book).To(HaveField("Author.DOB.Year()", BeNumerically("<", 1900))
504
func HaveField(field string, expected any) types.GomegaMatcher {
505
return &matchers.HaveFieldMatcher{
506
Field: field,
507
Expected: expected,
508
}
509
}
510
511
// HaveExistingField succeeds if actual is a struct and the specified field
512
// exists.
513
//
514
// HaveExistingField can be combined with HaveField in order to cover use cases
515
// with optional fields. HaveField alone would trigger an error in such situations.
516
//
517
// Expect(MrHarmless).NotTo(And(HaveExistingField("Title"), HaveField("Title", "Supervillain")))
518
func HaveExistingField(field string) types.GomegaMatcher {
519
return &matchers.HaveExistingFieldMatcher{
520
Field: field,
521
}
522
}
523
524
// HaveValue applies the given matcher to the value of actual, optionally and
525
// repeatedly dereferencing pointers or taking the concrete value of interfaces.
526
// Thus, the matcher will always be applied to non-pointer and non-interface
527
// values only. HaveValue will fail with an error if a pointer or interface is
528
// nil. It will also fail for more than 31 pointer or interface dereferences to
529
// guard against mistakenly applying it to arbitrarily deep linked pointers.
530
//
531
// HaveValue differs from gstruct.PointTo in that it does not expect actual to
532
// be a pointer (as gstruct.PointTo does) but instead also accepts non-pointer
533
// and even interface values.
534
//
535
// actual := 42
536
// Expect(actual).To(HaveValue(Equal(42)))
537
// Expect(&actual).To(HaveValue(Equal(42)))
538
func HaveValue(matcher types.GomegaMatcher) types.GomegaMatcher {
539
return &matchers.HaveValueMatcher{
540
Matcher: matcher,
541
}
542
}
543
544
// BeNumerically performs numerical assertions in a type-agnostic way.
545
// Actual and expected should be numbers, though the specific type of
546
// number is irrelevant (float32, float64, uint8, etc...).
547
//
548
// There are six, self-explanatory, supported comparators:
549
//
550
// Expect(1.0).Should(BeNumerically("==", 1))
551
// Expect(1.0).Should(BeNumerically("~", 0.999, 0.01))
552
// Expect(1.0).Should(BeNumerically(">", 0.9))
553
// Expect(1.0).Should(BeNumerically(">=", 1.0))
554
// Expect(1.0).Should(BeNumerically("<", 3))
555
// Expect(1.0).Should(BeNumerically("<=", 1.0))
556
func BeNumerically(comparator string, compareTo ...any) types.GomegaMatcher {
557
return &matchers.BeNumericallyMatcher{
558
Comparator: comparator,
559
CompareTo: compareTo,
560
}
561
}
562
563
// BeTemporally compares time.Time's like BeNumerically
564
// Actual and expected must be time.Time. The comparators are the same as for BeNumerically
565
//
566
// Expect(time.Now()).Should(BeTemporally(">", time.Time{}))
567
// Expect(time.Now()).Should(BeTemporally("~", time.Now(), time.Second))
568
func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher {
569
return &matchers.BeTemporallyMatcher{
570
Comparator: comparator,
571
CompareTo: compareTo,
572
Threshold: threshold,
573
}
574
}
575
576
// BeAssignableToTypeOf succeeds if actual is assignable to the type of expected.
577
// It will return an error when one of the values is nil.
578
//
579
// Expect(0).Should(BeAssignableToTypeOf(0)) // Same values
580
// Expect(5).Should(BeAssignableToTypeOf(-1)) // different values same type
581
// Expect("foo").Should(BeAssignableToTypeOf("bar")) // different values same type
582
// Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{}))
583
func BeAssignableToTypeOf(expected any) types.GomegaMatcher {
584
return &matchers.AssignableToTypeOfMatcher{
585
Expected: expected,
586
}
587
}
588
589
// Panic succeeds if actual is a function that, when invoked, panics.
590
// Actual must be a function that takes no arguments and returns no results.
591
func Panic() types.GomegaMatcher {
592
return &matchers.PanicMatcher{}
593
}
594
595
// PanicWith succeeds if actual is a function that, when invoked, panics with a specific value.
596
// Actual must be a function that takes no arguments and returns no results.
597
//
598
// By default PanicWith uses Equal() to perform the match, however a
599
// matcher can be passed in instead:
600
//
601
// Expect(fn).Should(PanicWith(MatchRegexp(`.+Foo$`)))
602
func PanicWith(expected any) types.GomegaMatcher {
603
return &matchers.PanicMatcher{Expected: expected}
604
}
605
606
// BeAnExistingFile succeeds if a file exists.
607
// Actual must be a string representing the abs path to the file being checked.
608
func BeAnExistingFile() types.GomegaMatcher {
609
return &matchers.BeAnExistingFileMatcher{}
610
}
611
612
// BeARegularFile succeeds if a file exists and is a regular file.
613
// Actual must be a string representing the abs path to the file being checked.
614
func BeARegularFile() types.GomegaMatcher {
615
return &matchers.BeARegularFileMatcher{}
616
}
617
618
// BeADirectory succeeds if a file exists and is a directory.
619
// Actual must be a string representing the abs path to the file being checked.
620
func BeADirectory() types.GomegaMatcher {
621
return &matchers.BeADirectoryMatcher{}
622
}
623
624
// HaveHTTPStatus succeeds if the Status or StatusCode field of an HTTP response matches.
625
// Actual must be either a *http.Response or *httptest.ResponseRecorder.
626
// Expected must be either an int or a string.
627
//
628
// Expect(resp).Should(HaveHTTPStatus(http.StatusOK)) // asserts that resp.StatusCode == 200
629
// Expect(resp).Should(HaveHTTPStatus("404 Not Found")) // asserts that resp.Status == "404 Not Found"
630
// Expect(resp).Should(HaveHTTPStatus(http.StatusOK, http.StatusNoContent)) // asserts that resp.StatusCode == 200 || resp.StatusCode == 204
631
func HaveHTTPStatus(expected ...any) types.GomegaMatcher {
632
return &matchers.HaveHTTPStatusMatcher{Expected: expected}
633
}
634
635
// HaveHTTPHeaderWithValue succeeds if the header is found and the value matches.
636
// Actual must be either a *http.Response or *httptest.ResponseRecorder.
637
// Expected must be a string header name, followed by a header value which
638
// can be a string, or another matcher.
639
func HaveHTTPHeaderWithValue(header string, value any) types.GomegaMatcher {
640
return &matchers.HaveHTTPHeaderWithValueMatcher{
641
Header: header,
642
Value: value,
643
}
644
}
645
646
// HaveHTTPBody matches if the body matches.
647
// Actual must be either a *http.Response or *httptest.ResponseRecorder.
648
// Expected must be either a string, []byte, or other matcher
649
func HaveHTTPBody(expected any) types.GomegaMatcher {
650
return &matchers.HaveHTTPBodyMatcher{Expected: expected}
651
}
652
653
// And succeeds only if all of the given matchers succeed.
654
// The matchers are tried in order, and will fail-fast if one doesn't succeed.
655
//
656
// Expect("hi").To(And(HaveLen(2), Equal("hi"))
657
//
658
// And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
659
func And(ms ...types.GomegaMatcher) types.GomegaMatcher {
660
return &matchers.AndMatcher{Matchers: ms}
661
}
662
663
// SatisfyAll is an alias for And().
664
//
665
// Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi")))
666
func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher {
667
return And(matchers...)
668
}
669
670
// Or succeeds if any of the given matchers succeed.
671
// The matchers are tried in order and will return immediately upon the first successful match.
672
//
673
// Expect("hi").To(Or(HaveLen(3), HaveLen(2))
674
//
675
// And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
676
func Or(ms ...types.GomegaMatcher) types.GomegaMatcher {
677
return &matchers.OrMatcher{Matchers: ms}
678
}
679
680
// SatisfyAny is an alias for Or().
681
//
682
// Expect("hi").SatisfyAny(Or(HaveLen(3), HaveLen(2))
683
func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher {
684
return Or(matchers...)
685
}
686
687
// Not negates the given matcher; it succeeds if the given matcher fails.
688
//
689
// Expect(1).To(Not(Equal(2))
690
//
691
// And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
692
func Not(matcher types.GomegaMatcher) types.GomegaMatcher {
693
return &matchers.NotMatcher{Matcher: matcher}
694
}
695
696
// WithTransform applies the `transform` to the actual value and matches it against `matcher`.
697
// The given transform must be either a function of one parameter that returns one value or a
698
// function of one parameter that returns two values, where the second value must be of the
699
// error type.
700
//
701
// var plus1 = func(i int) int { return i + 1 }
702
// Expect(1).To(WithTransform(plus1, Equal(2))
703
//
704
// var failingplus1 = func(i int) (int, error) { return 42, "this does not compute" }
705
// Expect(1).To(WithTransform(failingplus1, Equal(2)))
706
//
707
// And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.
708
func WithTransform(transform any, matcher types.GomegaMatcher) types.GomegaMatcher {
709
return matchers.NewWithTransformMatcher(transform, matcher)
710
}
711
712
// Satisfy matches the actual value against the `predicate` function.
713
// The given predicate must be a function of one parameter that returns bool.
714
//
715
// var isEven = func(i int) bool { return i%2 == 0 }
716
// Expect(2).To(Satisfy(isEven))
717
func Satisfy(predicate any) types.GomegaMatcher {
718
return matchers.NewSatisfyMatcher(predicate)
719
}
720
721