Golden File Test Helper
Write and compare golden files with trailing whitespace tolerance, producing a compact line diff when output drifts.
Code
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
)
func WriteGolden(target string, data []byte) error {
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return fmt.Errorf("create golden dir: %w", err)
}
return os.WriteFile(target, data, 0o644)
}
func diffLines(want, got string) string {
wantLines := strings.Split(strings.TrimSpace(want), "\n")
gotLines := strings.Split(strings.TrimSpace(got), "\n")
limit := len(wantLines)
if len(gotLines) < limit {
limit = len(gotLines)
}
var builder strings.Builder
for i := 0; i < limit; i++ {
if wantLines[i] != gotLines[i] {
fmt.Fprintf(&builder, "- %s\n+ %s\n", wantLines[i], gotLines[i])
}
}
if len(wantLines) != len(gotLines) {
fmt.Fprintf(&builder, "line count: want %d got %d\n", len(wantLines), len(gotLines))
}
return builder.String()
}
func CompareGolden(target string, got []byte) error {
want, err := os.ReadFile(target)
if err != nil {
return fmt.Errorf("read golden: %w", err)
}
if !bytes.Equal(bytes.TrimSpace(got), bytes.TrimSpace(want)) {
return fmt.Errorf("golden mismatch for %s\n%s", filepath.Base(target), diffLines(string(want), string(got)))
}
return nil
}
func main() {
dir, err := os.MkdirTemp("", "golden-*")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
target := filepath.Join(dir, "report.golden")
report := []byte("users=3\norders=5\n")
if err := WriteGolden(target, report); err != nil {
panic(err)
}
if err := CompareGolden(target, report); err != nil {
fmt.Println("unexpected mismatch:", err)
} else {
fmt.Println("match: ok")
}
if err := CompareGolden(target, []byte("users=4\norders=5\n")); err != nil {
fmt.Println("mismatch detected:")
fmt.Println(err)
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.