Debian Codegraph @

dump_golden_test.go

raw symbols SCIP
1 package check //nolint:testpackage // Testing unexported identifiers.
2
3 import (
4 "encoding/json"
5 "flag"
6 "os"
7 "path/filepath"
8 "strings"
9 "testing"
10 "time"
11 )
12
13 var update = flag.Bool("update", false, "update golden files")
14
15 type nested struct {
16 Name string
17 Values map[string]any
18 Items []int
19 Pointer *string
20 }
21
22 // TestDumpGolden captures current dump/diff output as golden data
23 // and checks it remains byte-identical after vendoring.
24 func TestDumpGolden(tt *testing.T) {
25 tt.Parallel()
26 t := T(tt)
27
28 s := "world"
29 j := json.RawMessage(`{"key":"value"}`)
30
31 vals := map[string]any{
32 "nil": nil,
33 "byte": byte(10),
34 "rune": '€',
35 "multilineString": "line1\nline2\nline3",
36 "invalidUtf8Str": "\x01\x02\x03\n\xff\xff",
37 "utf8Bytes": []byte("hello €"),
38 "invalidUtf8Bytes": []byte{0xff, 0xfe, 0x00},
39 "jsonRawMessage": j,
40 "jsonRawMessagePtr": &j,
41 "timeTime": time.Date(2024, time.January, 15, 10, 30, 0, 0, time.UTC),
42 "nestedStruct": nested{
43 Name: "test",
44 Values: map[string]any{"a": 1, "b": true, "c": "hi"},
45 Items: []int{1, 2, 3},
46 Pointer: &s,
47 },
48 }
49
50 names := []string{
51 "nil", "byte", "rune", "multilineString", "invalidUtf8Str",
52 "utf8Bytes", "invalidUtf8Bytes", "jsonRawMessage",
53 "jsonRawMessagePtr", "timeTime", "nestedStruct",
54 }
55
56 var b strings.Builder
57 for _, name := range names {
58 b.WriteString("=== newDump: ")
59 b.WriteString(name)
60 b.WriteString(" ===\n")
61 b.WriteString(newDump(vals[name]).String())
62 }
63
64 // Also test diff between two similar but different values
65 dumpA := newDump(nested{Name: "a", Items: []int{1, 2}})
66 dumpB := newDump(nested{Name: "b", Items: []int{1, 3}})
67 b.WriteString("=== diff between two nested structs ===\n")
68 b.WriteString(dumpA.diff(dumpB))
69 got := b.String()
70
71 golden := filepath.Join("testdata", "dump_golden.txt")
72
73 if *update {
74 err := os.WriteFile(golden, []byte(got), 0o644)
75 if err != nil {
76 t.Fatal(err)
77 }
78 return
79 }
80
81 want, err := os.ReadFile(golden)
82 if err != nil {
83 t.Fatal(err)
84 }
85 t.Equal(got, string(want))
86 }