Debian Codegraph @

internal/cmd/benchcheck/main_test.go

raw
1 package main
2
3 import (
4 "os"
5 "path/filepath"
6 "reflect"
7 "testing"
8 )
9
10 func TestParseBenchOutput(t *testing.T) {
11 output := `goos: darwin
12 goarch: arm64
13 pkg: benchmark
14 Benchmark_Decode_SmallStruct_Unmarshal_GoJson-8 5000000 250.5 ns/op 256 B/op 2 allocs/op
15 Benchmark_MarshalBytes_GoJson/32-8 10000000 100 ns/op
16 Benchmark_MarshalBytes_GoJson/32-8 10000000 90 ns/op
17 BenchmarkThroughput-8 1000 12.5 MB/s 2000 ns/op
18 BenchmarkNoTime-8 1000 12.5 MB/s
19 BenchmarkBelowTimerResolution-8 1
20 BenchmarkLogged-8
21 --- BENCH: BenchmarkLogged-8
22 bench_test.go:10: message
23 PASS
24 ok benchmark 10.000s
25 `
26 got := parseBenchOutput(output, 8)
27 want := measurement{
28 "Benchmark_Decode_SmallStruct_Unmarshal_GoJson": 250.5,
29 "Benchmark_MarshalBytes_GoJson/32": 90,
30 "BenchmarkThroughput": 2000,
31 // the testing package omits ns/op when it is zero.
32 "BenchmarkNoTime": 0,
33 "BenchmarkBelowTimerResolution": 0,
34 }
35 if !reflect.DeepEqual(got, want) {
36 t.Fatalf("unexpected result: got %v, want %v", got, want)
37 }
38 }
39
40 func TestParseBenchOutputSingleProc(t *testing.T) {
41 got := parseBenchOutput("BenchmarkFoo-8 \t 100 \t 10 ns/op\n", 1)
42 want := measurement{"BenchmarkFoo-8": 10}
43 if !reflect.DeepEqual(got, want) {
44 t.Fatalf("unexpected result: got %v, want %v", got, want)
45 }
46 }
47
48 // statusesOf returns the statuses of the results by the name.
49 func statusesOf(cmp *comparison) map[string]status {
50 statuses := map[string]status{}
51 for _, result := range cmp.sortedResults() {
52 statuses[result.Name] = result.Status
53 }
54 return statuses
55 }
56
57 func TestComparison(t *testing.T) {
58 t.Run("the fastest result of each side is compared", func(t *testing.T) {
59 cmp := newComparison(3, 15)
60 cmp.add("BenchmarkA", measurement{"BenchmarkA": 100}, measurement{"BenchmarkA": 130})
61 // the base happened to be slow in the second attempt: a degraded head must not pass with it.
62 cmp.add("BenchmarkA", measurement{"BenchmarkA": 500}, measurement{"BenchmarkA": 125})
63 want := []benchResult{{Name: "BenchmarkA", Func: "BenchmarkA", Status: statusRegressed, BaseNs: 100, HeadNs: 125, Attempts: 2, baseSeen: true}}
64 if got := cmp.sortedResults(); !reflect.DeepEqual(got, want) {
65 t.Fatalf("unexpected results:\n got %+v\nwant %+v", got, want)
66 }
67 if !cmp.degraded() {
68 t.Fatal("degradation must be detected")
69 }
70 })
71
72 t.Run("noise of a single benchmark is not a degradation", func(t *testing.T) {
73 cmp := newComparison(3, 15)
74 // one benchmark is 8% slower and the others are as fast as the base: the mean is about +0.8%.
75 cmp.add("BenchmarkNoise", measurement{"BenchmarkNoise": 100}, measurement{"BenchmarkNoise": 108})
76 for _, name := range []string{"BenchmarkB", "BenchmarkC", "BenchmarkD", "BenchmarkE", "BenchmarkF", "BenchmarkG", "BenchmarkH", "BenchmarkI", "BenchmarkJ"} {
77 cmp.add(name, measurement{name: 100}, measurement{name: 100})
78 }
79 if cmp.degraded() {
80 t.Fatalf("must not be degraded: mean %+.2f%%", cmp.meanDeltaPercent())
81 }
82 if got := cmp.pendingFuncs(); len(got) != 0 {
83 t.Fatalf("nothing must be measured again: %v", got)
84 }
85 })
86
87 t.Run("mean beyond the tolerance is a degradation", func(t *testing.T) {
88 cmp := newComparison(3, 15)
89 // every benchmark is 5% slower: none of them is beyond the tolerance of a single benchmark.
90 cmp.add("BenchmarkA", measurement{"BenchmarkA": 100}, measurement{"BenchmarkA": 105})
91 cmp.add("BenchmarkB", measurement{"BenchmarkB": 200}, measurement{"BenchmarkB": 210})
92 cmp.add("BenchmarkFast", measurement{"BenchmarkFast": 100}, measurement{"BenchmarkFast": 102})
93 if got, want := statusesOf(cmp), (map[string]status{"BenchmarkA": statusOK, "BenchmarkB": statusOK, "BenchmarkFast": statusOK}); !reflect.DeepEqual(got, want) {
94 t.Fatalf("unexpected statuses: got %v, want %v", got, want)
95 }
96 if !cmp.degraded() {
97 t.Fatalf("degradation must be detected: mean %+.2f%%", cmp.meanDeltaPercent())
98 }
99 // only what makes the mean slow is measured again.
100 if got, want := cmp.pendingFuncs(), []string{"BenchmarkA", "BenchmarkB"}; !reflect.DeepEqual(got, want) {
101 t.Fatalf("unexpected pending: got %v, want %v", got, want)
102 }
103 // the noise is gone in the next attempt.
104 cmp.add("BenchmarkA", measurement{"BenchmarkA": 100}, measurement{"BenchmarkA": 100})
105 cmp.add("BenchmarkB", measurement{"BenchmarkB": 200}, measurement{"BenchmarkB": 201})
106 if cmp.degraded() {
107 t.Fatalf("must not be degraded: mean %+.2f%%", cmp.meanDeltaPercent())
108 }
109 })
110
111 t.Run("degradation of a single benchmark is detected", func(t *testing.T) {
112 cmp := newComparison(3, 15)
113 cmp.add("BenchmarkDegraded", measurement{"BenchmarkDegraded": 100}, measurement{"BenchmarkDegraded": 130})
114 for _, name := range []string{"BenchmarkB", "BenchmarkC", "BenchmarkD", "BenchmarkE", "BenchmarkF", "BenchmarkG", "BenchmarkH", "BenchmarkI", "BenchmarkJ", "BenchmarkK", "BenchmarkL"} {
115 cmp.add(name, measurement{name: 100}, measurement{name: 100})
116 }
117 if mean := cmp.meanDeltaPercent(); mean > 3 {
118 t.Fatalf("the mean must be within the tolerance for this test: %+.2f%%", mean)
119 }
120 if got := statusesOf(cmp)["BenchmarkDegraded"]; got != statusRegressed {
121 t.Fatalf("unexpected status: %v", got)
122 }
123 if !cmp.degraded() {
124 t.Fatal("degradation must be detected")
125 }
126 if got, want := cmp.pendingFuncs(), []string{"BenchmarkDegraded"}; !reflect.DeepEqual(got, want) {
127 t.Fatalf("unexpected pending: got %v, want %v", got, want)
128 }
129 })
130
131 t.Run("benchmark which the base doesn't have", func(t *testing.T) {
132 cmp := newComparison(3, 15)
133 cmp.add("BenchmarkNew", measurement{}, measurement{"BenchmarkNew": 10})
134 cmp.add("BenchmarkSub", measurement{"BenchmarkSub/a": 100}, measurement{"BenchmarkSub/a": 100, "BenchmarkSub/new": 1000})
135 want := map[string]status{"BenchmarkNew": statusNew, "BenchmarkSub/a": statusOK, "BenchmarkSub/new": statusNew}
136 if got := statusesOf(cmp); !reflect.DeepEqual(got, want) {
137 t.Fatalf("unexpected statuses: got %v, want %v", got, want)
138 }
139 if cmp.degraded() {
140 t.Fatal("a new benchmark is not a degradation")
141 }
142 })
143 }
144
145 func TestCache(t *testing.T) {
146 c := &cache{dir: filepath.Join(t.TempDir(), "cache"), readable: true}
147 key := baselineKey{
148 Config: benchConfig{Dir: "benchmarks", Bench: "."},
149 Machine: machine{Hostname: "host", GOOS: "linux", GOARCH: "amd64", NumCPU: 4, GoVersion: "go1.21.0"},
150 BenchHash: "hash",
151 }
152 if got, err := c.loadBaseline("commit", key); err != nil || got != nil {
153 t.Fatalf("unexpected result for empty cache: %v, %v", got, err)
154 }
155 want := &baseline{Commit: "commit", Key: key, Results: measurement{"BenchmarkFoo": 1.5}}
156 if err := c.storeBaseline(want); err != nil {
157 t.Fatal(err)
158 }
159 got, err := c.loadBaseline("commit", key)
160 if err != nil {
161 t.Fatal(err)
162 }
163 if !reflect.DeepEqual(got, want) {
164 t.Fatalf("unexpected baseline: got %+v, want %+v", got, want)
165 }
166
167 otherMachine := key
168 otherMachine.Machine.Hostname = "other"
169 if got, err := c.loadBaseline("commit", otherMachine); err != nil || got != nil {
170 t.Fatalf("baseline of the other machine must not be used: %v, %v", got, err)
171 }
172 if got, err := c.loadBaseline("other-commit", key); err != nil || got != nil {
173 t.Fatalf("baseline of the other commit must not be used: %v, %v", got, err)
174 }
175
176 c.readable = false
177 if got, err := c.loadBaseline("commit", key); err != nil || got != nil {
178 t.Fatalf("cache must be ignored: %v, %v", got, err)
179 }
180 }
181
182 func TestHashDir(t *testing.T) {
183 dir := t.TempDir()
184 write := func(name, content string) {
185 t.Helper()
186 path := filepath.Join(dir, name)
187 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
188 t.Fatal(err)
189 }
190 if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
191 t.Fatal(err)
192 }
193 }
194 hash := func() string {
195 t.Helper()
196 h, err := hashDir(dir)
197 if err != nil {
198 t.Fatal(err)
199 }
200 return h
201 }
202 write("a_test.go", "package a")
203 write(filepath.Join("testdata", "a.json"), "{}")
204 first := hash()
205 if got := hash(); got != first {
206 t.Fatalf("hash must be stable: %s != %s", got, first)
207 }
208 write(filepath.Join("testdata", "a.json"), "[]")
209 second := hash()
210 if second == first {
211 t.Fatal("hash must change when a content is changed")
212 }
213 write("b_test.go", "")
214 if got := hash(); got == second {
215 t.Fatal("hash must change when a file is added")
216 }
217 }
218
219 func TestComparisonWithZeroMeasurement(t *testing.T) {
220 cmp := newComparison(3, 15)
221 cmp.add("BenchmarkBothZero", measurement{"BenchmarkBothZero": 0}, measurement{"BenchmarkBothZero": 0})
222 cmp.add("BenchmarkZeroBase", measurement{"BenchmarkZeroBase": 0}, measurement{"BenchmarkZeroBase": 20})
223 cmp.add("BenchmarkZeroBase", measurement{"BenchmarkZeroBase": 0}, measurement{"BenchmarkZeroBase": 10})
224 cmp.add("BenchmarkZeroHead", measurement{"BenchmarkZeroHead": 10}, measurement{"BenchmarkZeroHead": 0})
225
226 want := []benchResult{
227 {Name: "BenchmarkBothZero", Func: "BenchmarkBothZero", Status: statusOK, Attempts: 1, baseSeen: true},
228 {Name: "BenchmarkZeroBase", Func: "BenchmarkZeroBase", Status: statusRegressed, BaseNs: 0, HeadNs: 10, Attempts: 2, baseSeen: true},
229 {Name: "BenchmarkZeroHead", Func: "BenchmarkZeroHead", Status: statusOK, BaseNs: 10, HeadNs: 0, Attempts: 1, baseSeen: true},
230 }
231 if got := cmp.sortedResults(); !reflect.DeepEqual(got, want) {
232 t.Fatalf("unexpected results:\n got %+v\nwant %+v", got, want)
233 }
234 // the ratio to zero can't be represented, so such benchmarks are not a part of the mean.
235 if got := cmp.meanDeltaPercent(); got != 0 {
236 t.Fatalf("unexpected mean: %v", got)
237 }
238 if got := formatDelta(0, 10); got != "-" {
239 t.Fatalf("unexpected delta for zero base: %s", got)
240 }
241 if got := formatDelta(100, 110); got != "+10.00%" {
242 t.Fatalf("unexpected delta: %s", got)
243 }
244 }
245
246 func TestShardFuncs(t *testing.T) {
247 funcs := []string{"Benchmark_D", "Benchmark_A", "Benchmark_C", "Benchmark_B", "Benchmark_E"}
248 seen := map[string]int{}
249 for shard := 0; shard < 3; shard++ {
250 for _, fn := range shardFuncs(funcs, shard, 3) {
251 seen[fn]++
252 }
253 }
254 if len(seen) != len(funcs) {
255 t.Fatalf("the shards have %d functions, want %d", len(seen), len(funcs))
256 }
257 for fn, n := range seen {
258 if n != 1 {
259 t.Fatalf("%s is in %d shards", fn, n)
260 }
261 }
262 if got := shardFuncs(funcs, 0, 1); len(got) != len(funcs) {
263 t.Fatalf("one shard has %d functions", len(got))
264 }
265 }
266
267 func TestBenchmarkGroup(t *testing.T) {
268 for name, want := range map[string]string{
269 "BenchmarkCodeDecoder": groupDecode,
270 "BenchmarkUnmarshalFloat64": groupDecode,
271 "BenchmarkUnmarshalUnmapped": groupDecode,
272 "Benchmark_Decode_SmallStruct_Unmarshal_GoJson": groupDecode,
273 "Benchmark_Encode_SmallStruct_GoJson": groupEncode,
274 "Benchmark_MarshalBytes_GoJson": groupEncode,
275 "Benchmark_Compact_GoJson": groupEncode,
276 "BenchmarkCodeEncoder": groupEncode,
277 } {
278 if got := benchmarkGroup(name); got != want {
279 t.Errorf("%s: got %s, want %s", name, got, want)
280 }
281 }
282 funcs := []string{"Benchmark_Encode_A_GoJson", "Benchmark_Decode_A_GoJson", "BenchmarkUnmarshalX"}
283 if got := groupFuncs(funcs, groupDecode); len(got) != 2 {
284 t.Fatalf("decode: %v", got)
285 }
286 if got := groupFuncs(funcs, ""); len(got) != 3 {
287 t.Fatalf("no group: %v", got)
288 }
289 }