Webinar
Smarty

Testing in Go by example: Part 4

Our approach to assertions in Go code
Michael Whatcott
Michael Whatcott
 • 
August 11, 2015
Tags

I think it's time for a slight detour. In part 1 we covered the basics of testing in go. In part 2 we covered a few slick ways to execute tests. In part 3 we covered some of our recent endeavors at Smarty to build on the basics. Toward the end of that post we went into some detail regarding our approach to assertions. The assertions referenced in the GoConvey project are actually their own separate project that are imported into GoConvey. The nice thing about separating the assertions into their own separate project is that they can be used, well, separately. In this post I'll show you some of the the different ways we use the assertions project in our code outside of the GoConvey project.

In GoConvey, the So function exported by the convey package is void. All results of calling So() are swallowed by the convey functionality and passed to the reporting mechanisms. The assertions package (in the assertions project) exports its own version of the So() function, but it returns 2 parameters:

func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string)

Here's the GoDoc comment:

So is a convenience function (as opposed to an inconvenience function?) for running assertions on arbitrary arguments in any context, be it for testing or even application logging. It allows you to perform assertion-like behavior (and get nicely formatted messages detailing discrepancies) but without the program blowing up or panicking. All that is required is to import this package and call So with one of the assertions exported by this package as the second parameter. The first return parameter is a boolean indicating if the assertion was true. The second return parameter is the well-formatted message showing why an assertion was incorrect, or blank if the assertion was correct.

You probably noticed the unexported type assertion in the So() signature above. Here's what it looks like:

// assertion is an alias for a function with a signature that the So()
// function can handle. Any future or custom assertions should conform to this
// method signature. The return value should be an empty string if the assertion
// passes and a well-formed failure message if not.
type assertion func(actual interface{}, expected ...interface{}) string

Each of the Should assertion functions in the assertions package can be used as an assertion func when calling So().

Here's a simple example of how to use So() with an assertion function in your code:

x, y := 99, 100
if ok, message := So(x, ShouldBeGreaterThan, y); !ok {
    log.Println(message)
    // or log.Fatal(message) if you're feeling unforgiving...
}

Notice that this example makes no reference to the "testing" package's *testing.T, but it could:

x, y := 99, 100
if ok, message := So(x, ShouldBeGreaterThan, y); !ok {
    t.Error(message)
}

If you know you're going to be using So within your test functions and calling t.Error() and the like, here's another way to use the assertions package:

func TestSomething(t *testing.T) {
	x, y := 99, 100
	assertions.New(t).So(x, ShouldBeGreaterThan, y)
}

Did you notice how we passed in t in the assertions.New() function? The nice thing about this approach is you don't actually have to call t.Error() in failure scenarios. That is handled by the Assertion.So() function because it is given a reference to t.

You can actually call .So() multiple times on an Assertion instance:

assert := assertions.New(t)
assert.So(1, ShouldBeGreaterThan, 2)
assert.So(true, ShouldBeFalse)
assert.So(time.Now(), ShouldHappenBefore, time.Now())
// etc...

You can find out if any of those assertions failed and act accordingly:

if assert.Failed() {
	log.Fatal("Ouch")
}

You've probably noticed that to be able to reference assertions.New and ShouldEqual you'll need an import statement like this:

import (
	"github.com/smartystreets/assertions"
	. "github.com/smartystreets/assertions"
)

func TestSomething(t *testing.T) {
	assert := assertions.New(t)
	assert.So(1, ShouldBeGreaterThan, 2)
	assert.So(true, ShouldBeFalse)
	assert.So(time.Now(), ShouldHappenBefore, time.Now())
}

That's somewhat awkward so we created an alias package for the assertion functions called should:

import (
	"github.com/smartystreets/assertions"
	"github.com/smartystreets/assertions/should"
)

func TestSomething(t *testing.T) {
	assert := assertions.New(t)
	assert.So(1, should.BeGreaterThan, 2)
	assert.So(true, should.BeFalse)
	assert.So(time.Now(), should.HappenBefore, time.Now())
}

Did you catch the difference? ShouldBeGreaterThan becomes should.BeGreaterThan. If you're using goimports then this approach works out really smoothly. If you're not using goimports, why not? It's easy to setup.

The moral of the story is that it should be easy to check that a value is what you expect it to be. We prefer not to write if statements and hand-crafted log statements whenever possible so we've created the assertions package that helps us in various contexts, both in testing and otherwise. In the next post we'll talk about yet another use of the assertions package as we talk about our newest test library called gunit.

Before signing off, I would be remiss if I didn't give credit to Aaron Jacobs, the creator of the oglematchers package, which many of the assertion functions use internally to do their jobs.

Subscribe to our blog!
Learn more about RSS feeds here.
rss feed iconSubscribe Now
Read our recent posts
Santa uses Smarty® 
Arrow Icon
HO HO HO! Merry Christmas, my dear friends,I’m taking a minute from my busy toy-making and list-checking (twice) schedule to write you a letter. I know, I know, usually, it’s you and your lovely children writing ME letters, but I’ve loved seeing your efforts to get on the nice list this year and want to give you a peek into how I make the magic happen. Because you made my heart feel warm even at the North Pole, I’m sharing the answer to my most asked question: "How do I deliver billions of gifts to people all over the world?” The magic behind my sleigh rides? Hint: it's not the reindeer… I use Smarty.
2025 and beyond: The future of CX
Arrow Icon
The customer experience (CX) landscape is changing faster than a squirrel on espresso 🐿️☕, driven by technological advancements, consumer expectation evolution, and the need for all things to become digital. Maybe you wanna keep up with the change. That’s great. Or even better, you want to get ahead of all the other guys. That’s where Smarty comes in. Looking at what the future of customer experience will be like in 2025 and beyond (supported by relevant statistics and insights from various studies we’ve collected), address autocomplete and verification play a bigger role than you might suspect.
Get more Black Friday & Cyber Monday sales using address data
Arrow Icon
Webinar recap: The holiday sales race is almost on, and if you’re not prepared with your checkout game plan, you might be left behind with a sea of cart abandonments and “Where’s my order?” calls. But fear not! We recently held a webinar with address data experts Caroline Roweton and Brent Francom to talk about the ways bad address data can WRECK your holliday sales bump. They covered 7 ways you can use address data tools like autocomplete and address verification to crush the competition faster than a Black Friday doorbuster crowd will crush your beautiful holiday displays.