Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
178: Golden File Testing Pattern
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 healthimport ( "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 healthimport ( "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 healthimport ( "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) stringthat returns a pretty-printed JSON string usingjson.MarshalIndent. - Implement a test
TestGenerateConfigthat compares the output against a file located attestdata/config.golden. - Add a
-updateflag to the test suite. When this flag is set totrue, the test should write the current output ofGenerateConfigto the golden file instead of comparing it. - Ensure the test handles the case where the
testdatadirectory does not yet exist.
There are no comments for now.