Skip to Content
Course content

178: Golden File Testing Pattern

Click on the "Edit" button in the top corner of the screen to edit your slide content.

We've all been there: you're testing a function that returns a massive blob of text—maybe a JSON response, a generated YAML config, or a complex HTML email. If you try to put that expected output directly into your _test.go file as a string literal, your test file becomes a nightmare to read. One tiny change to the output format, and you're staring at a 500-line diff in your PR, trying to figure out if a single space is the culprit.

That's where the Golden File pattern comes in. Instead of hardcoding the expectation, we store it in a separate file (the "golden" version). The test reads that file, compares it to the actual output, and fails if they don't match. The magic happens when we add a way to update those files automatically when we intentionally change the output.

Building a System Health Report generator

Let's build a tool that generates a formatted system health report. It's the perfect candidate for this because as we add more metrics, the output grows, and manually updating a string in a test would be tedious.

package health

import (
	"fmt"
	"strings"
)

type Stats struct {
	CPUUsage    float64
	MemoryUsage float64
	DiskSpace   float64
	Services    []string
}

func GenerateReport(s Stats) string {
	var sb strings.Builder
	sb.WriteString("--- SYSTEM HEALTH REPORT ---\n")
	sb.WriteString(fmt.Sprintf("CPU: %.2f%%\n", s.CPUUsage))
	sb.WriteString(fmt.Sprintf("MEM: %.2f%%\n", s.MemoryUsage))
	sb.WriteString(fmt.Sprintf("DSK: %.2f%%\n", s.DiskSpace))
	sb.WriteString("Services:\n")
	for _, svc := range s.Services {
		sb.WriteString(fmt.Sprintf(" - %s\n", svc))
	}
	return sb.String()
}

Wiring up the file comparison

Now, I want to test this without cluttering my test file. I'll create a testdata directory. Go tools generally ignore this folder, making it a great place to stash our golden files.

package health

import (
	"bytes"
	"os"
	"path/filepath"
	"testing"
)

func TestGenerateReport(t *testing.T) {
	stats := Stats{
		CPUUsage:    45.2,
		MemoryUsage: 60.1,
		DiskSpace:   12.5,
		Services:    []string{"nginx", "postgresql", "redis"},
	}
	
	got := GenerateReport(stats)
	goldenPath := filepath.Join("testdata", "report.golden")
	
	want, err := os.ReadFile(goldenPath)
	if err != nil {
		t.Fatalf("could not read golden file: %v", err)
	}

	if !bytes.Equal(got[]byte(got), want) {
		t.Errorf("output did not match golden file")
	}
}

Handling the "first run" failure

I just ran this test and, unsurprisingly, it failed immediately with could not read golden file: open testdata/report.golden: no such file or directory. I made a classic mistake: I wrote the test to require the file, but I haven't actually created the file yet. I could manually copy-paste the output into a file, but that's exactly the manual toil we're trying to avoid.

The proper way to handle this is to implement an "update" mechanism. I'll use a command-line flag. This way, when I know the current output is correct, I can just tell Go to overwrite the golden file.

Implementing the update flag

We need to use the flag package. Since init() functions in tests can be tricky with how go test handles flags, I'll define a global variable and use a custom flag. Note that when running tests with custom flags, you have to pass them after the test name or use -args.

package health

import (
	"bytes"
	"flag"
	"os"
	"path/filepath"
	"testing"
)

var update = flag.Bool("update", false, "update golden files")

func TestGenerateReport(t *testing.T) {
	stats := Stats{
		CPUUsage:    45.2,
		MemoryUsage: 60.1,
		DiskSpace:   12.5,
		Services:    []string{"nginx", "postgresql", "redis"},
	}
	
	got := GenerateReport(stats)
	goldenPath := filepath.Join("testdata", "report.golden")
	
	if *update {
		// Ensure the directory exists before writing
		os.MkdirAll(filepath.Dir(goldenPath), 0755)
		err := os.WriteFile(goldenPath, []byte(got), 0644)
		if err != nil {
			t.Fatalf("could not write golden file: %v", err)
		}
		t.Logf("updated golden file: %s", goldenPath)
		return
	}

	want, err := os.ReadFile(goldenPath)
	if err != nil {
		t.Fatalf("could not read golden file: %v", err)
	}

	if !bytes.Equal([]byte(got), want) {
		t.Errorf("output did not match golden file")
	}
}

Now, the workflow is seamless. To initialize the test, I run: go test ./... -update. This creates the testdata/report.golden file. From then on, I just run go test ./.... If I change the report format—say, I decide to change "DSK" to "Disk"—the test will fail. I can then verify the change is what I wanted and run the -update flag again to commit the new "truth".




📋 Practical Task

Implement Golden File Testing for a JSON Config Generator

You are tasked with testing a function that converts a Go struct into a pretty-printed JSON configuration string. Because the JSON is large, you must implement the Golden File pattern.

Requirements:

  • Create a function GenerateConfig(cfg Config) string that returns a pretty-printed JSON string using json.MarshalIndent.
  • Implement a test TestGenerateConfig that compares the output against a file located at testdata/config.golden.
  • Add a -update flag to the test suite. When this flag is set to true, the test should write the current output of GenerateConfig to the golden file instead of comparing it.
  • Ensure the test handles the case where the testdata directory does not yet exist.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.