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