Golden files and property tests
Golden files and property tests
A golden file is a reviewed expected output stored beside a test, useful for reports and serialization. A property test checks a rule over many inputs instead of listing an exact expected result for each. Use the two approaches together: a golden example protects format, and properties protect general invariants.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "os" "testing")
func render(name string) string { return "Hello, " + name + "!\n" }func TestLesson(t *testing.T) { got := render("Ada") want, err := os.ReadFile("testdata/greeting.golden") if err != nil { t.Fatal(err) } if got != string(want) { t.Fatalf("got %q; want %q", got, want) }}
--- testdata/greeting.golden ---Hello, Ada!Go ignores testdata as a package but the test can read its files. The trailing newline is part of the contract. Keep output stable: sort keys if needed and inject time or IDs. Review the diff before intentionally updating a golden file; never automatically overwrite it on failure. Do not store real secrets or personal data in snapshots.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonCheck a round-trip property
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "bytes" "encoding/hex" "math/rand" "testing" "testing/quick")
func TestLesson(t *testing.T) { property := func(data []byte) bool { decoded, err := hex.DecodeString(hex.EncodeToString(data)) return err == nil && bytes.Equal(decoded, data) } cfg := &quick.Config{MaxCount: 200, Rand: rand.New(rand.NewSource(42))} if err := quick.Check(property, cfg); err != nil { t.Fatal(err) }}quick.Check generates inputs and reports a counterexample when the boolean function returns false. The fixed random seed makes this run reproducible on the same toolchain. bytes.Equal treats nil and empty slices as equal, matching the byte-content contract. A round trip alone could miss two implementations with matching bugs, so add known examples and independent invariants. testing/quick is frozen; native fuzzing is another option.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Check that strings.TrimSpace is idempotent on 200 generated strings with a fixed seed; add a known example containing a tab and newline. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced testing 03: Golden files and property tests
Check the lesson objective before moving on.
When should a golden file be updated?
What does a property test check?