clerk/internal/testutil/golden/golden.go (view raw)
| 1 | package golden |
| 2 | |
| 3 | import ( |
| 4 | "flag" |
| 5 | "io/fs" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "olexsmir.xyz/clerk/internal/testutil/txtar" |
| 12 | ) |
| 13 | |
| 14 | var update = flag.Bool("golden.update", false, "update golden files") |
| 15 | |
| 16 | var normalizer = strings.NewReplacer("/", "__", " ", "_") |
| 17 | |
| 18 | func txtarPath(name string) string { |
| 19 | return filepath.Join("testdata", normalizer.Replace(name)+".txtar") |
| 20 | } |
| 21 | |
| 22 | // Archive wraps a txtar.Archive with its on-disk path for efficient updates. |
| 23 | type Archive struct { |
| 24 | *txtar.Archive |
| 25 | path string |
| 26 | } |
| 27 | |
| 28 | // Read parses testdata/<name>.txtar and returns the archive. |
| 29 | // Fails the test if the file doesn't exist or the archive is empty. |
| 30 | func Read(t testing.TB, name string) *Archive { |
| 31 | t.Helper() |
| 32 | path := txtarPath(name) |
| 33 | data, err := os.ReadFile(path) |
| 34 | if err != nil { |
| 35 | t.Fatalf("loading %s: %v", name+".txtar", err) |
| 36 | } |
| 37 | a := txtar.Parse(data) |
| 38 | if len(a.Files) == 0 { |
| 39 | t.Fatalf("txtar %s: no files", name) |
| 40 | } |
| 41 | return &Archive{Archive: a, path: path} |
| 42 | } |
| 43 | |
| 44 | func (a *Archive) FS() (fs.FS, error) { return txtar.FS(a.Archive) } |
| 45 | |
| 46 | // Assert compares got against the "expect" file in a txtar archive. |
| 47 | // With -golden.update, rewrites the expect section in-place, preserving other files. |
| 48 | func Assert(t testing.TB, a *Archive, got string) { |
| 49 | t.Helper() |
| 50 | |
| 51 | if *update { |
| 52 | for i, f := range a.Files { |
| 53 | if f.Name == "expect" { |
| 54 | a.Files[i].Data = []byte(got) |
| 55 | goto write |
| 56 | } |
| 57 | } |
| 58 | a.Files = append(a.Files, txtar.File{Name: "expect", Data: []byte(got)}) |
| 59 | write: |
| 60 | if err := os.WriteFile(a.path, txtar.Format(a.Archive), 0o644); err != nil { |
| 61 | t.Fatalf("writing updated txtar: %v", err) |
| 62 | } |
| 63 | return |
| 64 | } |
| 65 | |
| 66 | for _, f := range a.Files { |
| 67 | if f.Name == "expect" { |
| 68 | if string(f.Data) != got { |
| 69 | t.Fatalf("golden mismatch for %s\nwant:\n%s\ngot:\n%s", a.path, string(f.Data), got) |
| 70 | } |
| 71 | return |
| 72 | } |
| 73 | } |
| 74 | t.Fatalf("txtar %s: no 'expect' file", a.path) |
| 75 | } |