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