New 42-day free trial
Smarty

Testing in Go by example: Part 4

Smarty header pin graphic
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 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 set up.

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 icon
Subscribe Now
Read our recent posts
Falling out of love with your address data solution?
Arrow Icon
There are plenty of address data solutions in the sea. You might need to let them off the hook if:Their data accuracy is sufferingToo many false positivesSpotty data availability (lack of international support? Beuller?)Off-the-mark geocoding (not truly rooftop-level accurate)Missing data enrichment (RDI, FIPS, unique ID, secondary addresses, etc. )They don’t flirt nicely (or at all) with your existing systemsThey don’t have an accurate address autocomplete solutionYour relationship with them has become robotic and mundane (When you need help, you have to talk to a robot instead of a real person for support… ew.
Global game-changer: Level up your customer retention in 2025
Arrow Icon
In 2024, it’s estimated that online purchases, or ecommerce, made up more than 20% of global retail, with 2. 77 billion people shopping online, and those numbers will only get bigger in the following years. With so much online shopping, more goods and services are being shipped than ever before—including during the height of the Sears catalog in 1970. Side note: If you’re reading this and you don’t know what the Sears catalog was or how much it impacted the average home, it’s worth taking a trip down memory lane and seeing how your elders used to shop.
Shipping optimization: Boosting your bottom line
Arrow Icon
Shipping optimization is rapidly evolving the retail landscape with advancements in shipping technology. From using robotics to increase efficiency and protect workers from dangerous jobs to autonomous vehicles and drones taking items to hard-to-reach areas, shipping has drastically evolved from the infancy of ecommerce in the 1990s. Sure, the 90s are currently having a pop culture resurgence, but your customers don’t want their shipping experience to go retro. One of the most impactful ways to ship effectively is to use a Shipping Execution System (SES).

Ready to get started?