Skip to content

Automatically update your Go tests

License

Unknown and 2 other licenses found

Licenses found

Unknown
LICENSE
Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

hexops/autogold

Repository files navigation

autogold - automated Go golden file testing Hexops logo

Go Reference

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.

Example usage

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.

When should golden files be used?

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.

Custom formatting

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:

Changing formatting for a specific sub-value

If your type implements the fmt.GoStringer interface, it will be used to convert your type to a string.

Include unexported fields

autogold.Equal(t, got, autogold.Unexported())

Use your own custom format (JSON, etc.)

Simply pass a string value to autogold.Equal, doing the formatting yourself. It'll be written to the golden file as-is.

Provide custom go-cmp options

You can provide any go-cmp option which will affect formatting by providing the autogold.CmpOptions(...) option to autogold.Equal.

Alternatives

Before writing autogold, I considered the following alternatives but was left wanting a better API:

About

Automatically update your Go tests

Topics

Resources

License

Unknown and 2 other licenses found

Licenses found

Unknown
LICENSE
Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Sponsor this project

Languages