Debian Codegraph @

internal/cmd/benchcheck/check_test.go

raw
1 package main
2
3 import (
4 "context"
5 "errors"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10 "testing"
11 )
12
13 // The durations are far longer than the resolution of the timer of any platform
14 // ( about 16ms at worst ), so that a single iteration is always measured as a positive time
15 // and the slow one is always distinguishable from the fast one.
16 const (
17 testLibFast = `package lib
18
19 import "time"
20
21 func Work() int {
22 time.Sleep(20 * time.Millisecond)
23 return 0
24 }
25 `
26 testLibFastRefactored = `package lib
27
28 import "time"
29
30 const workDuration = 20 * time.Millisecond
31
32 func Work() int {
33 time.Sleep(workDuration)
34 return 0
35 }
36 `
37 testLibSlow = `package lib
38
39 import "time"
40
41 func Work() int {
42 time.Sleep(100 * time.Millisecond)
43 return 0
44 }
45 `
46 testLibWithNewAPI = testLibFast + `
47 func Extra() int {
48 return Work() + 1
49 }
50 `
51 testBench = `package bench
52
53 import (
54 "testing"
55
56 "example.com/lib"
57 )
58
59 func BenchmarkWork(b *testing.B) {
60 for i := 0; i < b.N; i++ {
61 lib.Work()
62 }
63 }
64
65 func BenchmarkSub(b *testing.B) {
66 for _, name := range []string{"a", "b"} {
67 b.Run(name, func(b *testing.B) {
68 for i := 0; i < b.N; i++ {
69 lib.Work()
70 }
71 })
72 }
73 }
74 `
75 // testRecordDirEnv is the directory where a benchmark records the name of the binary which ran it.
76 testRecordDirEnv = "BENCHCHECK_TEST_RECORD_DIR"
77 testBenchRecordingBinary = `package bench
78
79 import (
80 "os"
81 "path/filepath"
82 "testing"
83
84 "example.com/lib"
85 )
86
87 func BenchmarkWork(b *testing.B) {
88 name := filepath.Join(os.Getenv("` + testRecordDirEnv + `"), filepath.Base(os.Args[0]))
89 if err := os.WriteFile(name, nil, 0o600); err != nil {
90 b.Fatal(err)
91 }
92 for i := 0; i < b.N; i++ {
93 lib.Work()
94 }
95 }
96 `
97 testBenchWithComparedLibrary = `package bench
98
99 import (
100 "testing"
101
102 "example.com/lib"
103 )
104
105 func BenchmarkWork(b *testing.B) {
106 for i := 0; i < b.N; i++ {
107 lib.Work()
108 }
109 }
110
111 func Benchmark_Work_GoJson(b *testing.B) {
112 for i := 0; i < b.N; i++ {
113 lib.Work()
114 }
115 }
116
117 func Benchmark_Work_EncodingJson(b *testing.B) {
118 b.Fatal("benchmark of the compared library must not run")
119 }
120 `
121 testBenchWithNewAPI = testBench + `
122 func BenchmarkExtra(b *testing.B) {
123 for i := 0; i < b.N; i++ {
124 lib.Extra()
125 }
126 }
127 `
128 )
129
130 type testRepo struct {
131 t *testing.T
132 dir string
133 // layouts is the number of the function layouts ( and of the rounds ) of a measurement.
134 layouts int
135 }
136
137 func newTestRepo(t *testing.T) *testRepo {
138 t.Helper()
139 for _, command := range []string{"git", "go"} {
140 if _, err := exec.LookPath(command); err != nil {
141 t.Skipf("%s command is required: %v", command, err)
142 }
143 }
144 r := &testRepo{t: t, dir: t.TempDir(), layouts: 1}
145 r.git("init", "-q")
146 r.git("symbolic-ref", "HEAD", "refs/heads/master")
147 r.write("go.mod", "module example.com/lib\n\ngo 1.19\n")
148 r.write("lib.go", testLibFast)
149 r.write(filepath.Join("benchmarks", "go.mod"), "module bench\n\ngo 1.19\n\nrequire example.com/lib v0.0.0\n\nreplace example.com/lib => ../\n")
150 r.write(filepath.Join("benchmarks", "bench_test.go"), testBench)
151 r.commit("initial commit")
152 return r
153 }
154
155 func (r *testRepo) git(args ...string) string {
156 r.t.Helper()
157 args = append([]string{"-c", "user.name=test", "-c", "[email protected]", "-c", "commit.gpgsign=false"}, args...)
158 cmd := exec.Command("git", args...)
159 cmd.Dir = r.dir
160 out, err := cmd.CombinedOutput()
161 if err != nil {
162 r.t.Fatalf("failed to run git %s: %v: %s", strings.Join(args, " "), err, out)
163 }
164 return string(out)
165 }
166
167 func (r *testRepo) write(name, content string) {
168 r.t.Helper()
169 path := filepath.Join(r.dir, name)
170 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
171 r.t.Fatal(err)
172 }
173 if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
174 r.t.Fatal(err)
175 }
176 }
177
178 func (r *testRepo) commit(message string) {
179 r.t.Helper()
180 r.git("add", "go.mod", "lib.go", "benchmarks")
181 r.git("commit", "-q", "-m", message)
182 }
183
184 func (r *testRepo) check(tolerance float64) *outcome {
185 r.t.Helper()
186 c := &checker{
187 opt: &options{
188 config: benchConfig{Dir: "benchmarks", Bench: ".", BenchTime: "1x", Rounds: r.layouts, Layouts: r.layouts},
189 attempts: defaultAttempts,
190 // the tests slow the library down several times, which is beyond both of the tolerances.
191 tolerance: tolerance,
192 singleTolerance: tolerance,
193 },
194 repo: &repository{root: r.dir},
195 cache: &cache{dir: filepath.Join(r.dir, ".git", "benchcheck"), readable: true},
196 }
197 out, err := c.check(context.Background())
198 if err != nil {
199 r.t.Fatal(err)
200 }
201 // the temporary worktree of the base commit must always be removed.
202 if got := strings.Count(r.git("worktree", "list", "--porcelain"), "worktree "); got != 1 {
203 r.t.Fatalf("temporary worktree is left: %d worktrees exist", got)
204 }
205 return out
206 }
207
208 func statusOf(t *testing.T, v *verdict) map[string]status {
209 t.Helper()
210 if v == nil {
211 t.Fatal("verdict is required")
212 }
213 statuses := map[string]status{}
214 for _, result := range v.Benchmarks {
215 statuses[result.Name] = result.Status
216 }
217 return statuses
218 }
219
220 func assertStatuses(t *testing.T, v *verdict, want map[string]status) {
221 t.Helper()
222 got := statusOf(t, v)
223 if len(got) != len(want) {
224 t.Fatalf("unexpected statuses: got %v, want %v", got, want)
225 }
226 for name, s := range want {
227 if got[name] != s {
228 t.Fatalf("unexpected statuses: got %v, want %v", got, want)
229 }
230 }
231 }
232
233 func TestCheck(t *testing.T) {
234 // the tolerance to make the verdict independent of the measurement noise.
235 const ignoreNoise = 1e12
236
237 allOK := map[string]status{
238 "BenchmarkWork": statusOK,
239 "BenchmarkSub/a": statusOK,
240 "BenchmarkSub/b": statusOK,
241 }
242 r := newTestRepo(t)
243
244 t.Run("HEAD is the base commit", func(t *testing.T) {
245 if out := r.check(ignoreNoise); out.verdict != nil {
246 t.Fatalf("nothing must be compared: %+v", out.verdict)
247 }
248 })
249
250 t.Run("uncommitted changes on the base commit are measured", func(t *testing.T) {
251 r.write("lib.go", testLibFastRefactored)
252 out := r.check(ignoreNoise)
253 if out.cachedVerdict || out.cachedBaseline {
254 t.Fatalf("nothing must be cached yet: %+v", out)
255 }
256 assertStatuses(t, out.verdict, allOK)
257 })
258
259 r.git("checkout", "-q", "-b", "feature")
260 r.commit("refactor")
261
262 t.Run("committed changes are measured with the cached result of the base", func(t *testing.T) {
263 out := r.check(ignoreNoise)
264 if out.cachedVerdict {
265 t.Fatal("verdict of uncommitted changes must not be cached")
266 }
267 if !out.cachedBaseline {
268 t.Fatal("result of the base must be cached")
269 }
270 assertStatuses(t, out.verdict, allOK)
271 })
272
273 t.Run("verdict of the same commit is cached", func(t *testing.T) {
274 out := r.check(ignoreNoise)
275 if !out.cachedVerdict {
276 t.Fatal("verdict must be cached")
277 }
278 assertStatuses(t, out.verdict, allOK)
279 })
280
281 t.Run("verdict is not shared between different options", func(t *testing.T) {
282 if out := r.check(ignoreNoise / 10); out.cachedVerdict {
283 t.Fatal("verdict of the other options must not be used")
284 }
285 })
286
287 t.Run("uncommitted changes are always measured", func(t *testing.T) {
288 r.write("lib.go", testLibSlow)
289 for i := 0; i < 2; i++ {
290 out := r.check(defaultTolerance)
291 if out.cachedVerdict {
292 t.Fatal("verdict must not be cached")
293 }
294 if !out.cachedBaseline {
295 t.Fatal("result of the base must be cached")
296 }
297 assertStatuses(t, out.verdict, map[string]status{
298 "BenchmarkWork": statusRegressed,
299 "BenchmarkSub/a": statusRegressed,
300 "BenchmarkSub/b": statusRegressed,
301 })
302 for _, result := range out.verdict.Benchmarks {
303 if result.Attempts != defaultAttempts {
304 t.Fatalf("all attempts must be used: %+v", result)
305 }
306 }
307 if err := report(out.verdict); !errors.Is(err, errDegraded) {
308 t.Fatalf("degradation must be reported: %v", err)
309 }
310 }
311 })
312
313 t.Run("degraded commit is cached as degraded", func(t *testing.T) {
314 r.commit("degrade")
315 if out := r.check(defaultTolerance); out.cachedVerdict {
316 t.Fatal("verdict must not be cached yet")
317 }
318 out := r.check(defaultTolerance)
319 if !out.cachedVerdict {
320 t.Fatal("verdict must be cached")
321 }
322 if err := report(out.verdict); !errors.Is(err, errDegraded) {
323 t.Fatalf("degradation must be reported: %v", err)
324 }
325 })
326
327 t.Run("benchmark of the API which the base doesn't have", func(t *testing.T) {
328 r.write("lib.go", testLibWithNewAPI)
329 r.write(filepath.Join("benchmarks", "bench_test.go"), testBenchWithNewAPI)
330 out := r.check(ignoreNoise)
331 if out.cachedBaseline {
332 t.Fatal("result of the base measured by the other benchmarks must not be used")
333 }
334 assertStatuses(t, out.verdict, map[string]status{
335 "BenchmarkWork": statusOK,
336 "BenchmarkSub/a": statusOK,
337 "BenchmarkSub/b": statusOK,
338 "BenchmarkExtra": statusNew,
339 })
340 })
341 }
342
343 func TestCheckIgnoresComparedLibraries(t *testing.T) {
344 // the tolerance to make the verdict independent of the measurement noise.
345 const ignoreNoise = 1e12
346
347 r := newTestRepo(t)
348 r.write("lib.go", testLibFastRefactored)
349 r.write(filepath.Join("benchmarks", "bench_test.go"), testBenchWithComparedLibrary)
350 out := r.check(ignoreNoise)
351 assertStatuses(t, out.verdict, map[string]status{
352 "Benchmark_Work_GoJson": statusOK,
353 "BenchmarkWork": statusOK,
354 })
355 }
356
357 func TestIsComparedLibraryBenchmark(t *testing.T) {
358 for name, want := range map[string]bool{
359 "Benchmark_Encode_SmallStruct_EncodingJson": true,
360 "Benchmark_Decode_SmallStruct_GoJayUnsafe": true,
361 "Benchmark_Encode_SmallStruct_GoJson": false,
362 "Benchmark_Encode_SmallStruct_GoJsonNoEscape": false,
363 "Benchmark_Encode_FilterByMap": false,
364 "BenchmarkUnmarshalString": false,
365 // the library is only the part after the last underscore.
366 "Benchmark_EncodingJson_Compatible_GoJson": false,
367 } {
368 if got := isComparedLibraryBenchmark(name); got != want {
369 t.Errorf("%s: got %v, want %v", name, got, want)
370 }
371 }
372 }