-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgolden_test.go
139 lines (118 loc) · 2.55 KB
/
golden_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package main
import (
"flag"
"io/ioutil"
"path/filepath"
"strings"
"testing"
"unicode"
)
var update = flag.Bool("update", false, "update golden files")
type TestCase struct {
Name string
Input string
Golden string
}
func LoadTestCases(tb testing.TB) []TestCase {
tb.Helper()
ext := ".in"
inputs, err := filepath.Glob("testdata/*" + ext)
if err != nil {
tb.Fatal(err)
}
var cases []TestCase
for _, input := range inputs {
noext := strings.TrimSuffix(input, ext)
cases = append(cases, TestCase{
Input: input,
Name: filepath.Base(noext),
Golden: noext + ".golden",
})
}
return cases
}
func TestFormatGolden(t *testing.T) {
for _, c := range LoadTestCases(t) {
c := c // scopelint
t.Run(c.Name, func(t *testing.T) {
// Read input.
b, err := ioutil.ReadFile(c.Input)
if err != nil {
t.Fatal(err)
}
// Format.
got, err := Format(b)
if err != nil {
t.Fatal(err)
}
// Update golden file if requested.
if *update {
if err := ioutil.WriteFile(c.Golden, got, 0o666); err != nil {
t.Fatal(err)
}
}
// Read golden file.
expect, err := ioutil.ReadFile(c.Golden)
if err != nil {
t.Fatal(err)
}
// Compare.
AssertLinesEqual(t, expect, got)
})
}
}
func TestInputsASCII(t *testing.T) {
for _, c := range LoadTestCases(t) {
c := c // scopelint
t.Run(c.Name, func(t *testing.T) {
// Read input.
b, err := ioutil.ReadFile(c.Input)
if err != nil {
t.Fatal(err)
}
// Check for non-ASCII.
line := 1
for _, r := range string(b) {
switch {
case r == '\n':
line++
case r > unicode.MaxASCII:
t.Errorf("%d: non-ascii character %c", line, r)
}
}
})
}
}
func BenchmarkFormatGolden(b *testing.B) {
for _, c := range LoadTestCases(b) {
c := c // scopelint
b.Run(c.Name, func(b *testing.B) {
// Read input.
src, err := ioutil.ReadFile(c.Input)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _ = Format(src)
}
})
}
}
func AssertLinesEqual(t *testing.T, expect, got []byte) {
t.Helper()
// Break into lines.
expectlines := Lines(string(expect))
gotlines := Lines(string(got))
if len(expectlines) != len(gotlines) {
t.Fatalf("line number mismatch: got %v expect %v", len(gotlines), len(expectlines))
}
for i := range expectlines {
if expectlines[i] != gotlines[i] {
t.Errorf("line %d:\n\tgot = %q\n\texpect = %q", i+1, gotlines[i], expectlines[i])
}
}
}
func Lines(s string) []string {
return strings.Split(strings.ReplaceAll(s, "\r\n", "\n"), "\n")
}