gomega

package module
v1.23.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2022 License: MIT Imports: 7 Imported by: 9,661

README

test

Jump straight to the docs to learn about Gomega, including a list of all available matchers.

If you have a question, comment, bug report, feature request, etc. please open a GitHub issue.

Ginkgo: a BDD Testing Framework for Golang

Learn more about Ginkgo here

Community Matchers

A collection of community matchers is available on the wiki.

License

Gomega is MIT-Licensed

The ConsistOf matcher uses goraph which is embedded in the source to simplify distribution. goraph has an MIT license.

Documentation

Overview

Gomega is the Ginkgo BDD-style testing framework's preferred matcher library.

The godoc documentation describes Gomega's API. More comprehensive documentation (with examples!) is available at http://onsi.github.io/gomega/

Gomega on Github: http://github.com/onsi/gomega

Learn more about Ginkgo online: http://onsi.github.io/ginkgo

Ginkgo on Github: http://github.com/onsi/ginkgo

Gomega is MIT-Licensed

Index

Constants

View Source
const GOMEGA_VERSION = "1.23.0"

Variables

DefaultGomega supplies the standard package-level implementation

View Source
var NewGomegaWithT = NewWithT

NewGomegaWithT is deprecated in favor of gomega.NewWithT, which does not stutter.

View Source
var StopTrying = internal.StopTrying

StopTrying can be used to signal to Eventually and Consistentlythat they should abort and stop trying. This always results in a failure of the assertion - and the failure message is the content of the StopTrying signal.

You can send the StopTrying signal by either returning StopTrying("message") as an error from your passed-in function _or_ by calling StopTrying("message").Now() to trigger a panic and end execution.

You can also wrap StopTrying around an error with `StopTrying("message").Wrap(err)` and can attach additional objects via `StopTrying("message").Attach("description", object). When rendered, the signal will include the wrapped error and any attached objects rendered using Gomega's default formatting.

Here are a couple of examples. This is how you might use StopTrying() as an error to signal that Eventually should stop:

playerIndex, numPlayers := 0, 11
Eventually(func() (string, error) {
    if playerIndex == numPlayers {
        return "", StopTrying("no more players left")
    }
    name := client.FetchPlayer(playerIndex)
    playerIndex += 1
    return name, nil
}).Should(Equal("Patrick Mahomes"))

And here's an example where `StopTrying().Now()` is called to halt execution immediately:

Eventually(func() []string {
	names, err := client.FetchAllPlayers()
	if err == client.IRRECOVERABLE_ERROR {
		StopTrying("Irrecoverable error occurred").Wrap(err).Now()
	}
	return names
}).Should(ContainElement("Patrick Mahomes"))
View Source
var TryAgainAfter = internal.TryAgainAfter

TryAgainAfter(<duration>) allows you to adjust the polling interval for the _next_ iteration of `Eventually` or `Consistently`. Like `StopTrying` you can either return `TryAgainAfter` as an error or trigger it immedieately with `.Now()`

When `TryAgainAfter(<duration>` is triggered `Eventually` and `Consistently` will wait for that duration. If a timeout occurs before the next poll is triggered both `Eventually` and `Consistently` will always fail with the content of the TryAgainAfter message. As with StopTrying you can `.Wrap()` and error and `.Attach()` additional objects to `TryAgainAfter`.

Functions

func And

And succeeds only if all of the given matchers succeed. The matchers are tried in order, and will fail-fast if one doesn't succeed.

Expect("hi").To(And(HaveLen(2), Equal("hi"))

And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.

func BeADirectory

func BeADirectory() types.GomegaMatcher

BeADirectory succeeds if a file exists and is a directory. Actual must be a string representing the abs path to the file being checked.

func BeARegularFile

func BeARegularFile() types.GomegaMatcher

BeARegularFile succeeds if a file exists and is a regular file. Actual must be a string representing the abs path to the file being checked.

func BeAnExistingFile

func BeAnExistingFile() types.GomegaMatcher

BeAnExistingFile succeeds if a file exists. Actual must be a string representing the abs path to the file being checked.

func BeAssignableToTypeOf

func BeAssignableToTypeOf(expected interface{}) types.GomegaMatcher

BeAssignableToTypeOf succeeds if actual is assignable to the type of expected. It will return an error when one of the values is nil.

Expect(0).Should(BeAssignableToTypeOf(0))         // Same values
Expect(5).Should(BeAssignableToTypeOf(-1))        // different values same type
Expect("foo").Should(BeAssignableToTypeOf("bar")) // different values same type
Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{}))

func BeClosed

func BeClosed() types.GomegaMatcher

BeClosed succeeds if actual is a closed channel. It is an error to pass a non-channel to BeClosed, it is also an error to pass nil

In order to check whether or not the channel is closed, Gomega must try to read from the channel (even in the `ShouldNot(BeClosed())` case). You should keep this in mind if you wish to make subsequent assertions about values coming down the channel.

Also, if you are testing that a *buffered* channel is closed you must first read all values out of the channel before 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).

Finally, as a corollary: it is an error to check whether or not a send-only channel is closed.

func BeComparableTo added in v1.20.0

func BeComparableTo(expected interface{}, opts ...cmp.Option) types.GomegaMatcher

BeComparableTo uses gocmp.Equal to compare. You can pass cmp.Option as options. It is an error for actual and expected to be nil. Use BeNil() instead.

func BeElementOf added in v1.6.0

func BeElementOf(elements ...interface{}) types.GomegaMatcher

BeElementOf succeeds if actual is contained in the passed in elements. BeElementOf() always uses Equal() to perform the match. When the passed in elements are comprised of a single element that is either an Array or Slice, BeElementOf() behaves as the reverse of ContainElement() that operates with Equal() to perform the match.

Expect(2).Should(BeElementOf([]int{1, 2}))
Expect(2).Should(BeElementOf([2]int{1, 2}))

Otherwise, BeElementOf() provides a syntactic sugar for Or(Equal(_), Equal(_), ...):

Expect(2).Should(BeElementOf(1, 2))

Actual must be typed.

func BeEmpty

func BeEmpty() types.GomegaMatcher

BeEmpty succeeds if actual is empty. Actual must be of type string, array, map, chan, or slice.

func BeEquivalentTo

func BeEquivalentTo(expected interface{}) types.GomegaMatcher

BeEquivalentTo is more lax than Equal, allowing equality between different types. This is done by converting actual to have the type of expected before attempting equality with reflect.DeepEqual. It is an error for actual and expected to be nil. Use BeNil() instead.

func BeFalse

func BeFalse() types.GomegaMatcher

BeFalse succeeds if actual is false

func BeIdenticalTo

func BeIdenticalTo(expected interface{}) types.GomegaMatcher

BeIdenticalTo uses the == operator to compare actual with expected. BeIdenticalTo is strict about types when performing comparisons. It is an error for both actual and expected to be nil. Use BeNil() instead.

func BeKeyOf added in v1.21.0

func BeKeyOf(element interface{}) types.GomegaMatcher

BeKeyOf succeeds if actual is contained in the keys of the passed in map. BeKeyOf() always uses Equal() to perform the match between actual and the map keys.

Expect("foo").Should(BeKeyOf(map[string]bool{"foo": true, "bar": false}))

func BeNil

func BeNil() types.GomegaMatcher

BeNil succeeds if actual is nil

func BeNumerically

func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatcher

BeNumerically performs numerical assertions in a type-agnostic way. Actual and expected should be numbers, though the specific type of number is irrelevant (float32, float64, uint8, etc...).

There are six, self-explanatory, supported comparators:

Expect(1.0).Should(BeNumerically("==", 1))
Expect(1.0).Should(BeNumerically("~", 0.999, 0.01))
Expect(1.0).Should(BeNumerically(">", 0.9))
Expect(1.0).Should(BeNumerically(">=", 1.0))
Expect(1.0).Should(BeNumerically("<", 3))
Expect(1.0).Should(BeNumerically("<=", 1.0))

func BeSent

func BeSent(arg interface{}) types.GomegaMatcher

BeSent succeeds if a value can be sent to actual. 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. In addition, actual must not be closed.

BeSent never blocks:

- If the channel `c` is not ready to receive then Expect(c).Should(BeSent("foo")) will fail immediately - 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 - If the channel `c` is closed then Expect(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both fail immediately

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). Rather, the point of `BeSent` is to make it possible to easily and expressively write tests that can timeout on blocked channel sends.

func BeTemporally

func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher

BeTemporally compares time.Time's like BeNumerically Actual and expected must be time.Time. The comparators are the same as for BeNumerically

Expect(time.Now()).Should(BeTemporally(">", time.Time{}))
Expect(time.Now()).Should(BeTemporally("~", time.Now(), time.Second))

func BeTrue

func BeTrue() types.GomegaMatcher

BeTrue succeeds if actual is true

func BeZero

func BeZero() types.GomegaMatcher

BeZero succeeds if actual is the zero value for its type or if actual is nil.

func ConsistOf

func ConsistOf(elements ...interface{}) types.GomegaMatcher

ConsistOf succeeds if actual contains precisely the elements passed into the matcher. The ordering of the elements does not matter. By default ConsistOf() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples:

Expect([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo"))
Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo"))
Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo")))

Actual must be an array, slice or map. For maps, ConsistOf matches against the map's values.

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 is the only element passed in to ConsistOf:

Expect([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"}))

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.

func ContainElement

func ContainElement(element interface{}, result ...interface{}) types.GomegaMatcher

ContainElement succeeds if actual contains the passed in element. By default ContainElement() uses Equal() to perform the match, however a matcher can be passed in instead:

Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar")))

Actual must be an array, slice or map. For maps, ContainElement searches through the map's values.

If you want to have a copy of the matching element(s) found you can pass a pointer to a variable of the appropriate type. If the variable isn't a slice or map, then exactly one match will be expected and returned. If the variable is a slice or map, then at least one match is expected and all matches will be stored in the variable.

var findings []string
Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubString("Bar", &findings)))

func ContainElements added in v1.9.0

func ContainElements(elements ...interface{}) types.GomegaMatcher

ContainElements succeeds if actual contains the passed in elements. The ordering of the elements does not matter. By default ContainElements() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples:

Expect([]string{"Foo", "FooBar"}).Should(ContainElements("FooBar"))
Expect([]string{"Foo", "FooBar"}).Should(ContainElements(ContainSubstring("Bar"), "Foo"))

Actual must be an array, slice or map. For maps, ContainElements searches through the map's values.

func ContainSubstring

func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher

ContainSubstring succeeds if actual is a string or stringer that contains the passed-in substring. Optional arguments can be provided to construct the substring via fmt.Sprintf().

func Equal

func Equal(expected interface{}) types.GomegaMatcher

Equal uses reflect.DeepEqual to compare actual with expected. Equal is strict about types when performing comparisons. It is an error for both actual and expected to be nil. Use BeNil() instead.

func HaveCap

func HaveCap(count int) types.GomegaMatcher

HaveCap succeeds if actual has the passed-in capacity. Actual must be of type array, chan, or slice.

func HaveEach added in v1.19.0

func HaveEach(element interface{}) types.GomegaMatcher

HaveEach succeeds if actual solely contains elements that match the passed in element. Please note that if actual is empty, HaveEach always will succeed. By default HaveEach() uses Equal() to perform the match, however a matcher can be passed in instead:

Expect([]string{"Foo", "FooBar"}).Should(HaveEach(ContainSubstring("Foo")))

Actual must be an array, slice or map. For maps, HaveEach searches through the map's values.

func HaveExistingField added in v1.20.0

func HaveExistingField(field string) types.GomegaMatcher

HaveExistingField succeeds if actual is a struct and the specified field exists.

HaveExistingField can be combined with HaveField in order to cover use cases with optional fields. HaveField alone would trigger an error in such situations.

Expect(MrHarmless).NotTo(And(HaveExistingField("Title"), HaveField("Title", "Supervillain")))

func HaveField added in v1.17.0

func HaveField(field string, expected interface{}) types.GomegaMatcher

HaveField succeeds if actual is a struct and the value at the passed in field matches the passed in matcher. By default HaveField used Equal() to perform the match, however a matcher can be passed in in stead.

The field must be a string that resolves to the name of a field in the struct. Structs can be traversed using the '.' delimiter. If the field ends with '()' a method named field is assumed to exist on the struct and is invoked. Such methods must take no arguments and return a single value:

type Book struct {
    Title string
    Author Person
}
type Person struct {
    FirstName string
    LastName string
    DOB time.Time
}
Expect(book).To(HaveField("Title", "Les Miserables"))
Expect(book).To(HaveField("Title", ContainSubstring("Les"))
Expect(book).To(HaveField("Author.FirstName", Equal("Victor"))
Expect(book).To(HaveField("Author.DOB.Year()", BeNumerically("<", 1900))

func HaveHTTPBody added in v1.16.0

func HaveHTTPBody(expected interface{}) types.GomegaMatcher

HaveHTTPBody matches if the body matches. Actual must be either a *http.Response or *httptest.ResponseRecorder. Expected must be either a string, []byte, or other matcher

func HaveHTTPHeaderWithValue added in v1.16.0

func HaveHTTPHeaderWithValue(header string, value interface{}) types.GomegaMatcher

HaveHTTPHeaderWithValue succeeds if the header is found and the value matches. Actual must be either a *http.Response or *httptest.ResponseRecorder. Expected must be a string header name, followed by a header value which can be a string, or another matcher.

func HaveHTTPStatus added in v1.10.0

func HaveHTTPStatus(expected ...interface{}) types.GomegaMatcher

HaveHTTPStatus succeeds if the Status or StatusCode field of an HTTP response matches. Actual must be either a *http.Response or *httptest.ResponseRecorder. Expected must be either an int or a string.

Expect(resp).Should(HaveHTTPStatus(http.StatusOK))   // asserts that resp.StatusCode == 200
Expect(resp).Should(HaveHTTPStatus("404 Not Found")) // asserts that resp.Status == "404 Not Found"
Expect(resp).Should(HaveHTTPStatus(http.StatusOK, http.StatusNoContent))   // asserts that resp.StatusCode == 200 || resp.StatusCode == 204

func HaveKey

func HaveKey(key interface{}) types.GomegaMatcher

HaveKey succeeds if actual is a map with the passed in key. By default HaveKey uses Equal() to perform the match, however a matcher can be passed in instead:

Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`)))

func HaveKeyWithValue

func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher

HaveKeyWithValue succeeds if actual is a map with the passed in key and value. By default HaveKeyWithValue uses Equal() to perform the match, however a matcher can be passed in instead:

Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar"))
Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar"))

func HaveLen

func HaveLen(count int) types.GomegaMatcher

HaveLen succeeds if actual has the passed-in length. Actual must be of type string, array, map, chan, or slice.

func HaveOccurred

func HaveOccurred() types.GomegaMatcher

HaveOccurred succeeds if actual is a non-nil error The typical Go error checking pattern looks like:

err := SomethingThatMightFail()
Expect(err).ShouldNot(HaveOccurred())

func HavePrefix

func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher

HavePrefix succeeds if actual is a string or stringer that contains the passed-in string as a prefix. Optional arguments can be provided to construct via fmt.Sprintf().

func HaveSuffix

func HaveSuffix(suffix string, args ...interface{}) types.GomegaMatcher

HaveSuffix succeeds if actual is a string or stringer that contains the passed-in string as a suffix. Optional arguments can be provided to construct via fmt.Sprintf().

func HaveValue added in v1.18.0

func HaveValue(matcher types.GomegaMatcher) types.GomegaMatcher

HaveValue applies the given matcher to the value of actual, optionally and repeatedly dereferencing pointers or taking the concrete value of interfaces. Thus, the matcher will always be applied to non-pointer and non-interface values only. HaveValue will fail with an error if a pointer or interface is nil. It will also fail for more than 31 pointer or interface dereferences to guard against mistakenly applying it to arbitrarily deep linked pointers.

HaveValue differs from gstruct.PointTo in that it does not expect actual to be a pointer (as gstruct.PointTo does) but instead also accepts non-pointer and even interface values.

actual := 42
Expect(actual).To(HaveValue(42))
Expect(&actual).To(HaveValue(42))

func InterceptGomegaFailure added in v1.14.0

func InterceptGomegaFailure(f func()) (err error)

InterceptGomegaFailure runs a given callback and returns the first failure message generated by any Gomega assertions within the callback, wrapped in an error.

The callback ceases execution as soon as the first failed assertion occurs, however Gomega does not register a failure with the FailHandler registered via RegisterFailHandler - it is up to the user to decide what to do with the returned error

func InterceptGomegaFailures

func InterceptGomegaFailures(f func()) []string

InterceptGomegaFailures runs a given callback and returns an array of failure messages generated by any Gomega assertions within the callback. Execution continues after the first failure allowing users to collect all failures in the callback.

This is most useful when testing custom matchers, but can also be used to check on a value using a Gomega assertion without causing a test failure.

func MatchError

func MatchError(expected interface{}) types.GomegaMatcher

MatchError succeeds if actual is a non-nil error that matches the passed in string/error.

These are valid use-cases:

Expect(err).Should(MatchError("an error")) //asserts that err.Error() == "an error"
Expect(err).Should(MatchError(SomeError)) //asserts that err == SomeError (via reflect.DeepEqual)

It is an error for err to be nil or an object that does not implement the Error interface

func MatchJSON

func MatchJSON(json interface{}) types.GomegaMatcher

MatchJSON succeeds if actual is a string or stringer of JSON that matches the expected JSON. The JSONs are decoded and the resulting objects are compared via reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter.

func MatchRegexp

func MatchRegexp(regexp string, args ...interface{}) types.GomegaMatcher

MatchRegexp succeeds if actual is a string or stringer that matches the passed-in regexp. Optional arguments can be provided to construct a regexp via fmt.Sprintf().

func MatchXML added in v1.2.0

func MatchXML(xml interface{}) types.GomegaMatcher

MatchXML succeeds if actual is a string or stringer of XML that matches the expected XML. The XMLs are decoded and the resulting objects are compared via reflect.DeepEqual so things like whitespaces shouldn't matter.

func MatchYAML

func MatchYAML(yaml interface{}) types.GomegaMatcher

MatchYAML succeeds if actual is a string or stringer of YAML that matches the expected YAML. The YAML's are decoded and the resulting objects are compared via reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter.

func Not

Not negates the given matcher; it succeeds if the given matcher fails.

Expect(1).To(Not(Equal(2))

And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.

func Or

Or succeeds if any of the given matchers succeed. The matchers are tried in order and will return immediately upon the first successful match.

Expect("hi").To(Or(HaveLen(3), HaveLen(2))

And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.

func Panic

func Panic() types.GomegaMatcher

Panic succeeds if actual is a function that, when invoked, panics. Actual must be a function that takes no arguments and returns no results.

func PanicWith added in v1.10.0

func PanicWith(expected interface{}) types.GomegaMatcher

PanicWith succeeds if actual is a function that, when invoked, panics with a specific value. Actual must be a function that takes no arguments and returns no results.

By default PanicWith uses Equal() to perform the match, however a matcher can be passed in instead:

Expect(fn).Should(PanicWith(MatchRegexp(`.+Foo$`)))

func Receive

func Receive(args ...interface{}) types.GomegaMatcher

Receive succeeds if there is a value to be received on actual. Actual must be a channel (and cannot be a send-only channel) -- anything else is an error.

Receive returns immediately and never blocks:

- If there is nothing on the channel `c` then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.

- If the channel `c` is closed then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.

- 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.

If you have a go-routine running in the background that will write to channel `c` you can:

Eventually(c).Should(Receive())

This will timeout if nothing gets sent to `c` (you can modify the timeout interval as you normally do with `Eventually`)

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`:

Consistently(c).ShouldNot(Receive())

You can pass `Receive` a matcher. If you do so, it will match the received object against the matcher. For example:

Expect(c).Should(Receive(Equal("foo")))

When given a matcher, `Receive` will always fail if there is nothing to be received on the channel.

Passing Receive a matcher is especially useful when paired with Eventually:

Eventually(c).Should(Receive(ContainSubstring("bar")))

will repeatedly attempt to pull values out of `c` until a value matching "bar" is received.

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:

var myThing thing
Eventually(thingChan).Should(Receive(&myThing))
Expect(myThing.Sprocket).Should(Equal("foo"))
Expect(myThing.IsValid()).Should(BeTrue())

func RegisterFailHandler

func RegisterFailHandler(fail types.GomegaFailHandler)

RegisterFailHandler connects Ginkgo to Gomega. When a matcher fails the fail handler passed into RegisterFailHandler is called.

func RegisterFailHandlerWithT added in v1.4.3

func RegisterFailHandlerWithT(_ types.GomegaTestingT, fail types.GomegaFailHandler)

RegisterFailHandlerWithT is deprecated and will be removed in a future release. users should use RegisterFailHandler, or RegisterTestingT

func RegisterTestingT

func RegisterTestingT(t types.GomegaTestingT)

RegisterTestingT connects Gomega to Golang's XUnit style Testing.T tests. It is now deprecated and you should use NewWithT() instead to get a fresh instance of Gomega for each test.

func Satisfy added in v1.12.0

func Satisfy(predicate interface{}) types.GomegaMatcher

Satisfy matches the actual value against the `predicate` function. The given predicate must be a function of one paramter that returns bool.

var isEven = func(i int) bool { return i%2 == 0 }
Expect(2).To(Satisfy(isEven))

func SatisfyAll

func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher

SatisfyAll is an alias for And().

Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi")))

func SatisfyAny

func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher

SatisfyAny is an alias for Or().

Expect("hi").SatisfyAny(Or(HaveLen(3), HaveLen(2))

func SetDefaultConsistentlyDuration

func SetDefaultConsistentlyDuration(t time.Duration)

SetDefaultConsistentlyDuration sets the default duration for Consistently. Consistently will verify that your condition is satisfied for this long.

func SetDefaultConsistentlyPollingInterval

func SetDefaultConsistentlyPollingInterval(t time.Duration)

SetDefaultConsistentlyPollingInterval sets the default polling interval for Consistently.

func SetDefaultEventuallyPollingInterval

func SetDefaultEventuallyPollingInterval(t time.Duration)

SetDefaultEventuallyPollingInterval sets the default polling interval for Eventually.

func SetDefaultEventuallyTimeout

func SetDefaultEventuallyTimeout(t time.Duration)

SetDefaultEventuallyTimeout sets the default timeout duration for Eventually. Eventually will repeatedly poll your condition until it succeeds, or until this timeout elapses.

func Succeed

func Succeed() types.GomegaMatcher

Succeed passes if actual is a nil error Succeed is intended to be used with functions that return a single error value. Instead of

err := SomethingThatMightFail()
Expect(err).ShouldNot(HaveOccurred())

You can write:

Expect(SomethingThatMightFail()).Should(Succeed())

It is a mistake to use Succeed with a function that has multiple return values. Gomega's Ω and Expect functions automatically trigger failure if any return values after the first return value are non-zero/non-nil. This means that Ω(MultiReturnFunc()).ShouldNot(Succeed()) can never pass.

func WithTransform

func WithTransform(transform interface{}, matcher types.GomegaMatcher) types.GomegaMatcher

WithTransform applies the `transform` to the actual value and matches it against `matcher`. The given transform must be either a function of one parameter that returns one value or a function of one parameter that returns two values, where the second value must be of the error type.

var plus1 = func(i int) int { return i + 1 }
Expect(1).To(WithTransform(plus1, Equal(2))

 var failingplus1 = func(i int) (int, error) { return 42, "this does not compute" }
 Expect(1).To(WithTransform(failingplus1, Equal(2)))

And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions.

Types

type Assertion added in v1.5.0

type Assertion = types.Assertion

Assertion is returned by Ω and Expect and compares the actual value to the matcher passed to the Should/ShouldNot and To/ToNot/NotTo methods.

Typically Should/ShouldNot are used with Ω and To/ToNot/NotTo are used with Expect though this is not enforced.

All methods take a variadic optionalDescription argument. This argument allows you to make your failure messages more descriptive. If a single argument of type `func() string` is passed, this function will be lazily evaluated if a failure occurs and the returned string is used to annotate the failure message. Otherwise, this argument is passed on to fmt.Sprintf() and then used to annotate the failure message.

All methods return a bool that is true if the assertion passed and false if it failed.

Example:

Ω(farm.HasCow()).Should(BeTrue(), "Farm %v should have a cow", farm)

func Expect

func Expect(actual interface{}, extra ...interface{}) Assertion

Expect wraps an actual value allowing assertions to be made on it:

Expect("foo").To(Equal("foo"))

If Expect is passed more than one argument it will pass the *first* argument to the matcher. All subsequent arguments will be required to be nil/zero.

This is convenient if you want to make an assertion on a method/function that returns a value and an error - a common patter in Go.

For example, given a function with signature:

func MyAmazingThing() (int, error)

Then:

Expect(MyAmazingThing()).Should(Equal(3))

Will succeed only if `MyAmazingThing()` returns `(3, nil)`

Expect and Ω are identical

func ExpectWithOffset

func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Assertion

ExpectWithOffset wraps an actual value allowing assertions to be made on it:

ExpectWithOffset(1, "foo").To(Equal("foo"))

Unlike `Expect` and `Ω`, `ExpectWithOffset` takes an additional integer argument that is used to modify the call-stack offset when computing line numbers. It is the same as `Expect(...).WithOffset`.

This is most useful in helper functions that make assertions. If you want Gomega's error message to refer to the calling line in the test (as opposed to the line in the helper function) set the first argument of `ExpectWithOffset` appropriately.

func Ω

func Ω(actual interface{}, extra ...interface{}) Assertion

Ω wraps an actual value allowing assertions to be made on it:

Ω("foo").Should(Equal("foo"))

If Ω is passed more than one argument it will pass the *first* argument to the matcher. All subsequent arguments will be required to be nil/zero.

This is convenient if you want to make an assertion on a method/function that returns a value and an error - a common patter in Go.

For example, given a function with signature:

func MyAmazingThing() (int, error)

Then:

Ω(MyAmazingThing()).Should(Equal(3))

Will succeed only if `MyAmazingThing()` returns `(3, nil)`

Ω and Expect are identical

type AsyncAssertion added in v1.5.0

type AsyncAssertion = types.AsyncAssertion

AsyncAssertion is returned by Eventually and Consistently and polls the actual value passed into Eventually against the matcher passed to the Should and ShouldNot methods.

Both Should and ShouldNot take a variadic optionalDescription argument. This argument allows you to make your failure messages more descriptive. If a single argument of type `func() string` is passed, this function will be lazily evaluated if a failure occurs and the returned string is used to annotate the failure message. Otherwise, this argument is passed on to fmt.Sprintf() and then used to annotate the failure message.

Both Should and ShouldNot return a boolean that is true if the assertion passed and false if it failed.

Example:

Eventually(myChannel).Should(Receive(), "Something should have come down the pipe.")
Consistently(myChannel).ShouldNot(Receive(), func() string { return "Nothing should have come down the pipe." })

func Consistently

func Consistently(args ...interface{}) AsyncAssertion

Consistently, like Eventually, enables making assertions on asynchronous behavior.

Consistently blocks when called for a specified duration. During that duration Consistently repeatedly polls its matcher and ensures that it is satisfied. If the matcher is consistently satisfied, then Consistently will pass. Otherwise Consistently will fail.

Both the total waiting duration and the polling interval are configurable as optional arguments. The first optional argument is the duration that Consistently will run for (defaults to 100ms), and the second argument is the polling interval (defaults to 10ms). As with Eventually, these intervals can be passed in as time.Duration, parsable duration strings or an integer or float number of seconds. You can also pass in an optional context.Context - Consistently will exit early (with a failure) if the context is cancelled before the waiting duration expires.

Consistently accepts the same three categories of actual as Eventually, check the Eventually docs to learn more.

Consistently is useful in cases where you want to assert that something *does not happen* for a period of time. For example, you may want to assert that a goroutine does *not* send data down a channel. In this case you could write:

Consistently(channel, "200ms").ShouldNot(Receive())

This will block for 200 milliseconds and repeatedly check the channel and ensure nothing has been received.

func ConsistentlyWithOffset

func ConsistentlyWithOffset(offset int, args ...interface{}) AsyncAssertion

ConsistentlyWithOffset operates like Consistently but takes an additional initial argument to indicate an offset in the call stack. This is useful when building helper functions that contain matchers. To learn more, read about `ExpectWithOffset`.

`ConsistentlyWithOffset` is the same as `Consistently(...).WithOffset` and optional `WithTimeout` and `WithPolling`.

func Eventually

func Eventually(args ...interface{}) AsyncAssertion

Eventually enables making assertions on asynchronous behavior.

Eventually checks that an assertion *eventually* passes. Eventually blocks when called and attempts an assertion periodically until it passes or a timeout occurs. Both the timeout and polling interval are configurable as optional arguments. The first optional argument is the timeout (which defaults to 1s), the second is the polling interval (which defaults to 10ms). Both intervals can be specified as time.Duration, parsable duration strings or floats/integers (in which case they are interpreted as seconds). In addition an optional context.Context can be passed in - Eventually will keep trying until either the timeout epxires or the context is cancelled, whichever comes first.

Eventually works with any Gomega compatible matcher and supports making assertions against three categories of actual value:

**Category 1: Making Eventually assertions on values**

There are several examples of values that can change over time. These can be passed in to Eventually and will be passed to the matcher repeatedly until a match occurs. For example:

c := make(chan bool)
go DoStuff(c)
Eventually(c, "50ms").Should(BeClosed())

will poll the channel repeatedly until it is closed. In this example `Eventually` will block until either the specified timeout of 50ms has elapsed or the channel is closed, whichever comes first.

Several Gomega libraries allow you to use Eventually in this way. For example, the gomega/gexec package allows you to block until a *gexec.Session exits successfully via:

Eventually(session).Should(gexec.Exit(0))

And the gomega/gbytes package allows you to monitor a streaming *gbytes.Buffer until a given string is seen:

Eventually(buffer).Should(gbytes.Say("hello there"))

In these examples, both `session` and `buffer` are designed to be thread-safe when polled by the `Exit` and `Say` matchers. This is not true in general of most raw values, so while it is tempting to do something like:

// THIS IS NOT THREAD-SAFE
var s *string
go mutateStringEventually(s)
Eventually(s).Should(Equal("I've changed"))

this will trigger Go's race detector as the goroutine polling via Eventually will race over the value of s with the goroutine mutating the string. For cases like this you can use channels or introduce your own locking around s by passing Eventually a function.

**Category 2: Make Eventually assertions on functions**

Eventually can be passed functions that **return at least one value**. When configured this way, Eventually will poll the function repeatedly and pass the first returned value to the matcher.

For example:

   Eventually(func() int {
   	return client.FetchCount()
   }).Should(BeNumerically(">=", 17))

will repeatedly poll client.FetchCount until the BeNumerically matcher is satisfied.  (Note that this example could have been written as Eventually(client.FetchCount).Should(BeNumerically(">=", 17)))

If multiple values are returned by the function, Eventually will pass the first value to the matcher and require that all others are zero-valued. This allows you to pass Eventually a function that returns a value and an error - a common pattern in Go.

For example, consider a method that returns a value and an error:

func FetchFromDB() (string, error)

Then

Eventually(FetchFromDB).Should(Equal("got it"))

will pass only if and when the returned error is nil *and* the returned string satisfies the matcher.

Eventually can also accept functions that take arguments, however you must provide those arguments using .WithArguments(). For example, consider a function that takes a user-id and makes a network request to fetch a full name:

func FetchFullName(userId int) (string, error)

You can poll this function like so:

Eventually(FetchFullName).WithArguments(1138).Should(Equal("Wookie"))

It is important to note that the function passed into Eventually is invoked *synchronously* when polled. Eventually does not (in fact, it cannot) kill the function if it takes longer to return than Eventually's configured timeout. A common practice here is to use a context. Here's an example that combines Ginkgo's spec timeout support with Eventually:

It("fetches the correct count", func(ctx SpecContext) {
	Eventually(ctx, func() int {
		return client.FetchCount(ctx, "/users")
	}).Should(BeNumerically(">=", 17))
}, SpecTimeout(time.Second))

you an also use Eventually().WithContext(ctx) to pass in the context. Passed-in contexts play nicely with paseed-in arguments as long as the context appears first. You can rewrite the above example as:

It("fetches the correct count", func(ctx SpecContext) {
	Eventually(client.FetchCount).WithContext(ctx).WithArguments("/users").Should(BeNumerically(">=", 17))
}, SpecTimeout(time.Second))

Either way the context passd to Eventually is also passed to the underlying funciton. Now, when Ginkgo cancels the context both the FetchCount client and Gomega will be informed and can exit.

**Category 3: Making assertions _in_ the function passed into Eventually**

When testing complex systems it can be valuable to assert that a _set_ of assertions passes Eventually. Eventually supports this by accepting functions that take a single Gomega argument and return zero or more values.

Here's an example that makes some assertions and returns a value and error:

Eventually(func(g Gomega) (Widget, error) {
	ids, err := client.FetchIDs()
	g.Expect(err).NotTo(HaveOccurred())
	g.Expect(ids).To(ContainElement(1138))
	return client.FetchWidget(1138)
}).Should(Equal(expectedWidget))

will pass only if all the assertions in the polled function pass and the return value satisfied the matcher.

Eventually also supports a special case polling function that takes a single Gomega argument and returns no values. Eventually assumes such a function is making assertions and is designed to work with the Succeed matcher to validate that all assertions have passed. For example:

Eventually(func(g Gomega) {
	model, err := client.Find(1138)
	g.Expect(err).NotTo(HaveOccurred())
	g.Expect(model.Reticulate()).To(Succeed())
	g.Expect(model.IsReticulated()).To(BeTrue())
	g.Expect(model.Save()).To(Succeed())
}).Should(Succeed())

will rerun the function until all assertions pass.

You can also pass additional arugments to functions that take a Gomega. The only rule is that the Gomega argument must be first. If you also want to pass the context attached to Eventually you must ensure that is the second argument. For example:

Eventually(func(g Gomega, ctx context.Context, path string, expected ...string){
	tok, err := client.GetToken(ctx)
	g.Expect(err).NotTo(HaveOccurred())

	elements, err := client.Fetch(ctx, tok, path)
	g.Expect(err).NotTo(HaveOccurred())
	g.Expect(elements).To(ConsistOf(expected))
}).WithContext(ctx).WithArguments("/names", "Joe", "Jane", "Sam").Should(Succeed())

Finally, in addition to passing timeouts and a context to Eventually you can be more explicit with Eventually's chaining configuration methods:

Eventually(..., "1s", "2s", ctx).Should(...)

is equivalent to

Eventually(...).WithTimeout(time.Second).WithPolling(2*time.Second).WithContext(ctx).Should(...)

func EventuallyWithOffset

func EventuallyWithOffset(offset int, args ...interface{}) AsyncAssertion

EventuallyWithOffset operates like Eventually but takes an additional initial argument to indicate an offset in the call stack. This is useful when building helper functions that contain matchers. To learn more, read about `ExpectWithOffset`.

`EventuallyWithOffset` is the same as `Eventually(...).WithOffset`.

`EventuallyWithOffset` specifying a timeout interval (and an optional polling interval) are the same as `Eventually(...).WithOffset(...).WithTimeout` or `Eventually(...).WithOffset(...).WithTimeout(...).WithPolling`.

type Gomega added in v1.10.0

type Gomega = types.Gomega

Gomega describes the essential Gomega DSL. This interface allows libraries to abstract between the standard package-level function implementations and alternatives like *WithT.

The types in the top-level DSL have gotten a bit messy due to earlier deprecations that avoid stuttering and due to an accidental use of a concrete type (*WithT) in an earlier release.

As of 1.15 both the WithT and Ginkgo variants of Gomega are implemented by the same underlying object however one (the Ginkgo variant) is exported as an interface (types.Gomega) whereas the other (the withT variant) is shared as a concrete type (*WithT, which is aliased to *internal.Gomega). 1.15 did not clean this mess up to ensure that declarations of *WithT in existing code are not broken by the upgrade to 1.15.

func NewGomega added in v1.15.0

func NewGomega(fail types.GomegaFailHandler) Gomega

NewGomega returns an instance of Gomega wired into the passed-in fail handler. You generally don't need to use this when using Ginkgo - RegisterFailHandler will wire up the global gomega However creating a NewGomega with a custom fail handler can be useful in contexts where you want to use Gomega's rich ecosystem of matchers without causing a test to fail. For example, to aggregate a series of potential failures or for use in a non-test setting.

type GomegaAssertion

type GomegaAssertion = types.Assertion

GomegaAssertion is deprecated in favor of Assertion, which does not stutter.

type GomegaAsyncAssertion

type GomegaAsyncAssertion = types.AsyncAssertion

GomegaAsyncAssertion is deprecated in favor of AsyncAssertion, which does not stutter.

type GomegaWithT added in v1.3.0

type GomegaWithT = WithT

GomegaWithT is deprecated in favor of gomega.WithT, which does not stutter.

type OmegaMatcher

type OmegaMatcher = types.GomegaMatcher

OmegaMatcher is deprecated in favor of the better-named and better-organized types.GomegaMatcher but sticks around to support existing code that uses it

type PollingSignalError added in v1.23.0

type PollingSignalError = internal.PollingSignalError

PollingSignalError is the error returned by StopTrying() and TryAgainAfter()

type WithT added in v1.5.0

type WithT = internal.Gomega

WithT wraps a *testing.T and provides `Expect`, `Eventually`, and `Consistently` methods. This allows you to leverage Gomega's rich ecosystem of matchers in standard `testing` test suites.

Use `NewWithT` to instantiate a `WithT`

As of 1.15 both the WithT and Ginkgo variants of Gomega are implemented by the same underlying object however one (the Ginkgo variant) is exported as an interface (types.Gomega) whereas the other (the withT variant) is shared as a concrete type (*WithT, which is aliased to *internal.Gomega). 1.15 did not clean this mess up to ensure that declarations of *WithT in existing code are not broken by the upgrade to 1.15.

func NewWithT added in v1.5.0

func NewWithT(t types.GomegaTestingT) *WithT

NewWithT takes a *testing.T and returns a `gomega.WithT` allowing you to use `Expect`, `Eventually`, and `Consistently` along with Gomega's rich ecosystem of matchers in standard `testing` test suits.

func TestFarmHasCow(t *testing.T) {
    g := gomega.NewWithT(t)

    f := farm.New([]string{"Cow", "Horse"})
    g.Expect(f.HasCow()).To(BeTrue(), "Farm should have cow")
 }

Directories

Path Synopsis
Package gbytes provides a buffer that supports incrementally detecting input.
Package gbytes provides a buffer that supports incrementally detecting input.
protobuf
Package protobuf is a generated protocol buffer package.
Package protobuf is a generated protocol buffer package.
package gleak complements the Gingko/Gomega testing and matchers framework with matchers for Goroutine leakage detection.
package gleak complements the Gingko/Gomega testing and matchers framework with matchers for Goroutine leakage detection.
goroutine
Package goroutine discovers and returns information about either all goroutines or only the caller's goroutine.
Package goroutine discovers and returns information about either all goroutines or only the caller's goroutine.
Package gomega/gmeasure provides support for benchmarking and measuring code.
Package gomega/gmeasure provides support for benchmarking and measuring code.
gutil
Package gutil is a replacement for ioutil, which should not be used in new code as of Go 1.16.
Package gutil is a replacement for ioutil, which should not be used in new code as of Go 1.16.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL