Your first Gomega matcher
If you write tests in Go, you may have come across the Gomega assertion library, Ginkgo’s preferred matcher. I’ve seen a few examples where engineers have written a convoluted series of assertions, when what they really wanted was a custom matcher to express intent.
I’ve spent the last few years working on the garden container manager for Cloud Foundry, Concourse and BOSH. Albeit trivial, it’s often useful to check whether a process with a certain pid exists or not, so let’s write a matcher for that!
Let’s start from a test that doesn’t have a custom pid matcher:
Ok so, it’s contrived, but in this test, we start a process that will sleep for 10 seconds, and then wait on it. We can then use the Consistently matcher to assert every second, for 5 seconds, that the process is still running (The 0 signal doesn’t actually send a signal but does do existence and permission checks: http://man7.org/linux/man-pages/man2/kill.2.html).
Functionally, this works great. However, I think there are two unfortunate issues with this code. Firstly, let’s look at the failure output (when the process doesn’t run for at least 5 seconds):
It doesn’t indicate why this test failed at all! Ok, so Gomega provides the ability to annotate assertions with a message:
and the associated failure output:
Better, but still a lot of excess information, and the boolean output doesn’t really fit within our domain of pids, so it’s just noise — let’s come back to this later.
Get William Martin’s stories in your inbox
Join Medium for free to get updates from this writer.
The second issue I have is that a reader must understand the intent of sending the 0signal, it sure would be nice if we could be more expressive by capturing this as an abstraction. In fact, it would be really nice if we could write something like:
Fortunately, this is super simple, as a custom Gomega matcher only needs to satisfy the GomegaMatcher (go figure!) interface:
type GomegaMatcher interface {
Match(actual interface{}) (success bool, err error)
FailureMessage(actual interface{}) (message string)
NegatedFailureMessage(actual interface{}) (message string)
}So here’s our desired matcher come to life:
This is super simple, we type assert the actual value to an integer, check it using our aforementioned 0 signal (which a reader no longer needs to understand) and write some error messages to handle To/Should vs NotTo/ShouldNot.
Let’s see how that failure message looks now:
Ship it.
As noted at the start, this is a trivial example, but I’ve seen various snippets of code that get lengthy and convoluted that would be far better abstracted as a custom matcher. Can you think of any in your codebases?
Thanks for reading!









