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