Golang testing — gotest.tools golden
Let’s continue the
gotest.tools serie, this time with the
golden package. This is a
quick follow-up on a previous
golden post, but focused on the
implementation. I’m gonna be quicker, please read that one if
golden files is a new
concept for you.
goldenprovides tools for comparing large mutli-line strings.
Golden files are files in the
./testdata/sub-directory of the package under test.
In the previous article, we described the problem, and how to fix it by writing a small
helper. Well, that small helper is in
gotest.tools/golden now, and it has a tiny bit
One of the difference between the
gotest.tools implementation and the previous post is
the flag name. In
gotest.tools/golden, the flag is
-test.update-golden (was just
-test.update before). Just as before, if the
-test.update-golden flag is set then the
actual content is written to the golden file, before reading it and comparing.
There is two ways to use the
- on it’s own, using
- as a
Assert functions should be straightforward. Both
Assert function compares the
actual content to the expected content in the golden file and returns whether the
assertion was successful (true) or not (false).
Assertuses string. Note that this one removes carriage return before comparing to depend as less as possible of the system (
AssertBytesuses raw data (in the form of
golden.Assert(t, "foo", "foo-content.golden") // Could also be used to check some binary format golden.AssertBytes(t, byte("foo"), "foo-content.golden")
As written in a previous post (about the
assert package), I prefer to use
All those helper functions have a equivalent function in the
cmppackage that returns a
Comparison. I, personally, prefer to use
assert.Assertin combination with
cmp.Comparisonas it allows me to write all my assertions the same way, with built-ins comparison or with my own — i.e.
assert.Assert(t, is.Equal(…), "message"or
assert.Assert(t, stackIsUp(c, time…), "another message").
golden package gives us that too, in the form of
String. Using the
assert.Assert functions with those is equivalent to their helper
assert.Assert(t, golden.String("foo", "foo-content.golden")) // Could also be used to check some binary format assert.Assert(t, golden.Bytes(byte("foo"), "foo-content.golden"))
… that’s a wrap. As for
skip, this is a small package, so the post was going to be
golden package just solve a specific problem (read Golang testing — golden file)
in a simple way.