gomega

package
v0.0.0-...-3f44578 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2022 License: BSD-2-Clause Imports: 8 Imported by: 0

README

Build Status

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

To discuss Gomega and get updates, join the google group.

Ginkgo: a BDD Testing Framework for Golang

Learn more about Ginkgo here

License

Gomega is MIT-Licensed

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/pivotal/gumshoe/repos/gomega

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

Ginkgo on Github: http://github.com/pivotal/gumshoe/repos/ginkgo

Gomega is MIT-Licensed

Index

Constants

View Source
const GOMEGA_VERSION = "0.9"

Variables

This section is empty.

Functions

func RegisterFailHandler

func RegisterFailHandler(handler OmegaFailHandler)

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

func RegisterTestingT

func RegisterTestingT(t GomegaTestingT)

RegisterTestingT connects Gomega to Golang's XUnit style Testing.T tests. You'll need to call this at the top of each XUnit style test:

func TestFarmHasCow(t *testing.T) {
    RegisterTestingT(t)

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

Note that this *testing.T is registered *globally* by Gomega (this is why you don't have to pass `t` down to the matcher itself). This means that you cannot run the XUnit style tests in parallel as the global fail handler cannot point to more than one testing.T at a time.

(As an aside: Ginkgo gets around this limitation by running parallel tests in different *processes*).

Types

type Actual

type Actual interface {
	Should(matcher OmegaMatcher, optionalDescription ...interface{}) bool
	ShouldNot(matcher OmegaMatcher, optionalDescription ...interface{}) bool

	To(matcher OmegaMatcher, optionalDescription ...interface{}) bool
	ToNot(matcher OmegaMatcher, optionalDescription ...interface{}) bool
	NotTo(matcher OmegaMatcher, optionalDescription ...interface{}) bool
}

Actual 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 is passed on to fmt.Sprintf() and is used to annotate failure messages.

All methods return a bool that is true if hte 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{}) Actual

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{}) Actual

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 this is used to modify the call-stack offset when computing line numbers.

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{}) Actual

Ω 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 AsyncActual

type AsyncActual interface {
	Should(matcher OmegaMatcher, optionalDescription ...interface{}) bool
	ShouldNot(matcher OmegaMatcher, optionalDescription ...interface{}) bool
}

AsyncActual 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 is passed on to fmt.Sprintf() and is used to annotate failure messages. This allows you to make your failure messages more descriptive

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(), "Nothing should have come down the pipe.")

func Consistently

func Consistently(actual interface{}, intervals ...float64) AsyncActual

Consistently wraps an actual value allowing assertions to be made on it. The assertion is tried periodically and is required to pass for a period of time.

Both the total time and polling interval are configurable as optional arguments: The first optional argument is the duration, in seconds expressed as a float64, that Consistently will run for. The second optional argument is the polling interval in seconds expressd as a float64.

If Consistently is passed an actual that is a function taking no arguments and returning at least one value, then Consistently will call the function periodically and try the matcher against the function's first return value.

If the function returns more than one value, then Consistently will pass the first value to the matcher and assert that all other values are nil/zero. This allows you to pass Consistently a function that returns a value and an error - a common pattern in Go.

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

Consistently(channel).ShouldNot(Receive())

Consistently's default duration is 100ms, and its default polling interval is 10ms

func ConsistentlyWithOffset

func ConsistentlyWithOffset(offset int, actual interface{}, intervals ...float64) AsyncActual

ConsistentlyWithOffset operates like Consistnetly 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`.

func Eventually

func Eventually(actual interface{}, intervals ...float64) AsyncActual

Eventually wraps an actual value allowing assertions to be made on it. The assertion is tried 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 in seconds expressed as a float64. The second optional argument is the polling interval in seconds expressd as a float64.

If Eventually is passed an actual that is a function taking no arguments and returning at least one value, then Eventually will call the function periodically and try the matcher against the function's first return value.

Example:

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

Note that this example could be rewritten:

Eventually(thingImPolling.Count).Should(BeNumerically(">=", 17))

If the function returns more than one value, then Eventually will pass the first value to the matcher and assert that all other values are nil/zero. 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("hasselhoff"))

Will pass only if the the returned error is nil and the returned string passes the matcher.

Eventually's default timeout is 1 second, and its default polling interval is 10ms

func EventuallyWithOffset

func EventuallyWithOffset(offset int, actual interface{}, intervals ...float64) AsyncActual

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

type GomegaTestingT

type GomegaTestingT interface {
	Errorf(format string, args ...interface{})
}

A simple *testing.T interface wrapper

type OmegaFailHandler

type OmegaFailHandler func(message string, callerSkip ...int)

type OmegaMatcher

type OmegaMatcher interface {
	Match(actual interface{}) (success bool, message string, err error)
}

All Gomega matchers must implement the OmegaMatcher interface

For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding_your_own_matchers

func BeAssignableToTypeOf

func BeAssignableToTypeOf(expected interface{}) OmegaMatcher

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

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

func BeClosed

func BeClosed() OmegaMatcher

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 BeEmpty

func BeEmpty() OmegaMatcher

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

func BeEquivalentTo

func BeEquivalentTo(expected interface{}) OmegaMatcher

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() OmegaMatcher

BeFalse succeeds if actual is false

func BeNil

func BeNil() OmegaMatcher

BeNil succeeds if actual is nil

func BeNumerically

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

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

There are six, self-explanatory, supported comparators:

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

func BeTrue

func BeTrue() OmegaMatcher

BeTrue succeeds if actual is true

func BeZero

func BeZero() OmegaMatcher

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

func ContainElement

func ContainElement(element interface{}) OmegaMatcher

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:

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

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

func ContainSubstring

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

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

func Equal

func Equal(expected interface{}) OmegaMatcher

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 HaveKey

func HaveKey(key interface{}) OmegaMatcher

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:

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

func HaveLen

func HaveLen(count int) OmegaMatcher

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

func HaveOccured

func HaveOccured() OmegaMatcher

Legacy misspelling, provided for backwards compatibility.

func HaveOccurred

func HaveOccurred() OmegaMatcher

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

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

func MatchJSON

func MatchJSON(json interface{}) OmegaMatcher

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

func MatchRegexp

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

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 Panic

func Panic() OmegaMatcher

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 Receive

func Receive(args ...interface{}) OmegaMatcher

Receive succeeds if there is a message 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 Ω(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass.

- If the channel `c` is closed then *both* Ω(c).Should(Receive()) and Ω(c).ShouldNot(Receive()) will error.

- If there is something on the channel `c` ready to be read, then Ω(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())

Finally, you often want to make assertions on the value *sent* to the channel. You can ask the Receive matcher for the value passed to the channel by passing it a pointer to a variable of the appropriate type:

var receivedString string
Eventually(stringChan).Should(Receive(&receivedString))
Ω(receivedString).Shoudl(Equal("foo"))

Directories

Path Synopsis
Gomega matchers
Gomega matchers

Jump to

Keyboard shortcuts

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