Instead of writing your desired test output as a large Go structure / string in your code, simply write:
autogold.Equal(t, got)
The test output (nested Go struct, string, etc.) will be formatted using google/go-cmp. If the testdata/<test name>.golden
snapshot file is different, the test will fail with a nice multi-line diff and go test -update
will update the file if you like the changes.
Import the package:
import "github.com/hexops/autogold"
Write a test that produces any Go value (got
):
func TestFoo(t *testing.T) {
got := Bar()
autogold.Equal(t, got)
}
Run go test
and you'll see the test fails:
--- FAIL: TestFoo (0.00s)
autogold.go:148: mismatch (-want +got):
--- want
+++ got
@@ -1 +1,2 @@
+{*example.Baz}.Name:"Jane"
+{*example.Baz}.Age:31
We see a diff showing what our test produced and what we expected (nothing, because testdata/TestFoobar.golden
does not exist.)
Rerun the test with go test -update
and testdata/TestFoobar.golden
will be created/updated with the output we got.
Golden files are used by the Go authors for testing the standard library, the gofmt
tool, etc. and are a common pattern in the Go community for snapshot testing. See also "Testing with golden files in Go" - Chris Reeves
Golden files make the most sense when you'd otherwise have to write a complex multi-line string or large Go structure inline in your test.
google/go-cmp is used to produce a text description of the Go value you provide to autogold.Equal
. If the default output is not suitable for your test, you have options:
If your type implements the fmt.GoStringer
interface, it will be used to convert your type to a string.
autogold.Equal(t, got, autogold.Unexported())
Simply pass a string
value to autogold.Equal
, doing the formatting yourself. It'll be written to the golden file as-is.
You can provide any go-cmp option which will affect formatting by providing the autogold.CmpOptions(...)
option to autogold.Equal
.
Before writing autogold, I considered the following alternatives but was left wanting a better API:
- github.com/xorcare/golden: only works on
[]byte
inputs. - github.com/sebdah/goldie: doesn't have a minimal API, only works on
[]byte
inputs (but provides helpers for JSON, XML, etc.) - github.com/bradleyjkemp/cupaloy less minimal API, works on any inputs but uses inactive go-spew project to format Go structs.