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
Inside Smarty® - Irina O'hara
Arrow Icon
Irina O'Hara is one of our uniquely clever, expert frontend developers. She’s immensely talented and has had a vital impact on our website redesign. When it came time to spotlight her, Irina was a joy to sit down with and get to know a little better. To get to the basics, she writes code and creates awesome websites, and she’s darn good at both. BackgroundIrina was born and raised in St. Petersburg, Russia. However, she wasn't born a development expert and had other aspirations from the start.
How I reduced my returned mail from 27% to 1% using address autocomplete
Arrow Icon
The following is based on a true story. Some of the names and relationships have been changed to protect the anonymity of individuals and companies. However, the numbers are 100% accurate. In 2023, I wanted to mail some really fancy cards to 165 businesses. I collected their addresses by asking for them or finding them in their online listing and collected them all in a neat little row. Then, I went a step further and ran these addresses through Smarty's bulk address validation tool. Everything was set and perfect.
The ROI of accurate healthcare address validation: Stop hemorrhaging red on your financial statements
Arrow Icon
In healthcare, the havoc an inaccurate address can wreak on your financial results is significant in more ways than one, and the boost in overall profitability from maintaining a clean address database is equally worth noting. Accurate healthcare address validation improves operational efficiency, patient engagement, and compliance and builds revenue to heights that couldn’t be met without it. Here’s what we’ll be covering:Healthcare address validation pros and consCon: Increased claim denials and organizational costsPro: Reduced claim denials and reprocessing costsCon: Increasing patient match error ratesPro: Improved patient matching and data qualityCon: Complicated billing and collections processesPro: Streamlined billing and collections capabilitiesCon: Exposure to legal liabilitiesPro: Enhanced regulatory compliance and risk aversionCon: Misplaced market strategyPro: Data-driven decision-making and market insightsEpilogue: Avoiding the pain (see our summarized financial savings)Healthcare address validation pros and consThere’s a pro and a con associated with having (or not having 🫣) accurate address data in your healthcare systems.

Ready to get started?