oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1// Package testci keeps go test's result cache honest, and holds the
2// quarantine of known flaky tests.
3//
4// make test reuses a cached pass for a package whose inputs have not
5// changed. go test keys that result on the test binary, on the files and
6// directories the test process itself opened or stat'ed inside the module
7// (by size and modification time), and on the environment variables it
8// read. Three kinds of input escape that key:
9//
10// - repository files a child process reads: a go build of a command, a
11// Python fixture run by python3;
12// - programs installed outside the module, such as codex or bwrap;
13// - which tests CI has quarantined.
14//
15// A test with one of those declares it here, and a change to it then
16// reruns the test instead of replaying an old pass.
17package testci
18
19import (
20 "bufio"
21 "io/fs"
22 "os"
23 "os/exec"
24 "path/filepath"
25 "slices"
26 "strings"
27 "sync"
28 "testing"
29)
30
31// Files declares repository files a child process reads: a script it
32// runs, a fixture it is handed. Paths are relative to the test's package
33// directory, as the test itself names them. A directory declares every
34// file under it.
35func Files(t testing.TB, paths ...string) {
36 t.Helper()
37 for _, p := range paths {
38 err := filepath.WalkDir(p, func(path string, _ fs.DirEntry, err error) error {
39 if err != nil {
40 return err
41 }
42 return open(path)
43 })
44 if err != nil {
45 t.Fatalf("testci: declare %s: %v", p, err)
46 }
47 }
48}
49
50// open records path as an input. For a directory go test hashes the
51// listing, with each entry's size and modification time.
52func open(path string) error {
53 f, err := os.Open(path)
54 if err != nil {
55 return err
56 }
57 return f.Close()
58}
59
60// goValueFlags are the go build and go test flags that take their value
61// as the next argument, so that argument is not a package pattern.
62var goValueFlags = map[string]bool{
63 "-o": true, "-tags": true, "-overlay": true, "-ldflags": true, "-gcflags": true,
64 "-asmflags": true, "-p": true, "-run": true, "-skip": true, "-count": true,
65 "-timeout": true, "-C": true, "-mod": true, "-modfile": true, "-pkgdir": true,
66 "-toolexec": true, "-exec": true, "-f": true, "-coverprofile": true,
67}
68
69// GoCommand declares the source a child go command compiles: cmd is a
70// `go build`, `go test`, `go list` or `go vet` the test is about to run.
71// Every package it names, every package of this module those import (as
72// its -tags select them), their embedded files, go.mod and go.sum become
73// inputs, so editing the command's source reruns the test.
74func GoCommand(t testing.TB, cmd *exec.Cmd) {
75 t.Helper()
76 args := cmd.Args[1:]
77 if len(args) == 0 {
78 t.Fatalf("testci: %v is not a go command", cmd.Args)
79 }
80 var tags string
81 var patterns []string
82 for i := 1; i < len(args); i++ {
83 a := args[i]
84 switch {
85 case a == "--":
86 i = len(args)
87 case !strings.HasPrefix(a, "-"):
88 patterns = append(patterns, a)
89 case strings.HasPrefix(a, "-tags="):
90 tags = strings.TrimPrefix(a, "-tags=")
91 case a == "-tags" && i+1 < len(args):
92 tags = args[i+1]
93 i++
94 case !strings.Contains(a, "=") && goValueFlags[a]:
95 i++
96 }
97 }
98 if len(patterns) == 0 {
99 patterns = []string{"."}
100 }
101 GoPackages(t, cmd.Dir, cmd.Env, tags, patterns...)
102}
103
104// GoPackages declares the source of packages a child go command compiles
105// from dir (the test's package directory when empty), as GoCommand does.
106// The go list behind it runs once per process for the same arguments.
107func GoPackages(t testing.TB, dir string, env []string, tags string, patterns ...string) {
108 t.Helper()
109 key := strings.Join(append([]string{dir, tags}, patterns...), "\x00")
110 listed.Lock()
111 paths, ok := listed.paths[key]
112 listed.Unlock()
113 if !ok {
114 format := `{{if .Module}}{{if .Module.Main}}{{.Dir}}{{range .EmbedFiles}}
115{{$.Dir}}/{{.}}{{end}}
116{{.Module.GoMod}}{{end}}{{end}}`
117 list := exec.Command("go", append([]string{"list", "-deps", "-tags=" + tags, "-f", format}, patterns...)...)
118 list.Dir, list.Env = dir, env
119 out, err := list.Output()
120 if err != nil {
121 t.Fatalf("testci: go list %v: %v", patterns, err)
122 }
123 seen := map[string]bool{}
124 for _, path := range strings.Split(string(out), "\n") {
125 if path == "" || seen[path] {
126 continue
127 }
128 seen[path] = true
129 paths = append(paths, path)
130 if filepath.Base(path) == "go.mod" {
131 paths = append(paths, filepath.Join(filepath.Dir(path), "go.sum"))
132 }
133 }
134 listed.Lock()
135 listed.paths[key] = paths
136 listed.Unlock()
137 }
138 for _, path := range paths {
139 if err := open(path); err != nil && !os.IsNotExist(err) {
140 t.Fatalf("testci: %v", err)
141 }
142 }
143}
144
145var listed = struct {
146 sync.Mutex
147 paths map[string][]string
148}{paths: map[string][]string{}}
149
150// fingerprinted are the programs make test fingerprints into
151// EQUIPO_TEST_TOOLS (TEST_TOOLS in scripts/ci-test.py). Keep the two lists the
152// same.
153var fingerprinted = []string{"bwrap", "claude", "codex", "git", "gofmt", "python3", "sh", "srt", "tar",
154 // try-bin is the directory of pinned provider binaries the replay
155 // tests run (~/.local/share/equipo/try/bin), every file in it.
156 "try-bin",
157 // pi is the pinned Pi install the real-Pi tests run (EQUIPO_PI_ROOT).
158 "pi",
159 // opencode is the pinned OpenCode install the real-OpenCode tests run
160 // (EQUIPO_OPENCODE_ROOT).
161 "opencode"}
162
163// Tools declares programs installed outside the module that the test
164// runs. Their bytes are outside what go test hashes, so make test hands
165// the test a fingerprint of each one's resolved path, size and
166// modification time in EQUIPO_TEST_TOOLS, and reading it here puts that
167// fingerprint in the cache key: upgrading codex reruns the codex tests.
168func Tools(t testing.TB, names ...string) {
169 t.Helper()
170 for _, name := range names {
171 if !slices.Contains(fingerprinted, name) {
172 t.Fatalf("testci: %s is not fingerprinted; add it to TEST_TOOLS in scripts/ci-test.py and to fingerprinted in testci", name)
173 }
174 }
175 _ = os.Getenv("EQUIPO_TEST_TOOLS")
176}
177
178// RepoFiles declares the whole repository: every tracked or untracked,
179// not ignored, file. For a test whose child reads the tree as git lists
180// it, such as the dead-reference scan.
181func RepoFiles(t testing.TB) {
182 t.Helper()
183 root, err := moduleRoot()
184 if err != nil {
185 t.Fatalf("testci: %v", err)
186 }
187 // git -C, not a working directory: go test records the directory a
188 // child starts in, and the root's would put its mtime in the key.
189 ls := exec.Command("git", "-C", root, "ls-files", "-z", "--cached", "--others", "--exclude-standard")
190 out, err := ls.Output()
191 if err != nil {
192 t.Fatalf("testci: git ls-files: %v", err)
193 }
194 // Every directory but the root is declared, so a file added anywhere
195 // below it reruns the test. The root's own modification time moves on
196 // every CI job (the runner and the gate's tools touch it), which would
197 // make the test uncacheable; its tracked files are declared one by one.
198 dirs := map[string]bool{root: true}
199 for _, name := range strings.Split(string(out), "\x00") {
200 if name == "" {
201 continue
202 }
203 path := filepath.Join(root, name)
204 if err := open(path); err != nil && !os.IsNotExist(err) {
205 t.Fatalf("testci: %v", err)
206 }
207 for d := filepath.Dir(path); !dirs[d]; d = filepath.Dir(d) {
208 dirs[d] = true
209 }
210 }
211 delete(dirs, root)
212 for d := range dirs {
213 if err := open(d); err != nil {
214 t.Fatalf("testci: %v", err)
215 }
216 }
217}
218
219// moduleRoot is the nearest directory above the working directory that
220// holds go.mod.
221func moduleRoot() (string, error) {
222 dir, err := os.Getwd()
223 if err != nil {
224 return "", err
225 }
226 for {
227 if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
228 return dir, nil
229 }
230 parent := filepath.Dir(dir)
231 if parent == dir {
232 return "", os.ErrNotExist
233 }
234 dir = parent
235 }
236}
237
238// QuarantineFile lists the quarantined tests, relative to the module root.
239const QuarantineFile = "scripts/ci-quarantine.txt"
240
241// Quarantine skips the calling test or subtest in the normal CI test
242// lanes (EQUIPO_QUARANTINE=skip) when QuarantineFile lists it: a known
243// flake, which make test-quarantine runs on its own, retrying a failure
244// once and reporting a pass on the retry as a flake. A test the file does
245// not list, and any test outside those lanes, runs as usual, so the file
246// alone decides what is quarantined. Call it first; a loop of subtests
247// can call it in every subtest.
248func Quarantine(t testing.TB) {
249 t.Helper()
250 if os.Getenv("EQUIPO_QUARANTINE") != "skip" {
251 return
252 }
253 listed, err := quarantineListed(t.Name())
254 if err != nil {
255 t.Fatalf("testci: %v", err)
256 }
257 if listed {
258 t.Skip("quarantined flake: runs in the test-quarantine step (" + QuarantineFile + ")")
259 }
260}
261
262// quarantineListed reports whether the quarantine file names test in
263// this package (the working directory go test runs it in).
264func quarantineListed(test string) (bool, error) {
265 pkg, err := os.Getwd()
266 if err != nil {
267 return false, err
268 }
269 dir, err := moduleRoot()
270 if err != nil {
271 return false, err
272 }
273 rel, err := filepath.Rel(dir, pkg)
274 if err != nil {
275 return false, err
276 }
277 f, err := os.Open(filepath.Join(dir, QuarantineFile))
278 if err != nil {
279 return false, err
280 }
281 defer f.Close()
282 s := bufio.NewScanner(f)
283 for s.Scan() {
284 fields := strings.Fields(s.Text())
285 if len(fields) >= 2 && fields[0] == "./"+filepath.ToSlash(rel) && fields[1] == test {
286 return true, nil
287 }
288 }
289 return false, s.Err()
290}
291
292// ToolsRequired is the environment variable CI sets to 1 on a machine it
293// has given every pinned program the tests run (make ci-box does).
294const ToolsRequired = "EQUIPO_TEST_TOOLS_REQUIRED"
295
296// Absent reports that a pinned program the test runs is not installed.
297// On a developer's machine that skips the test. Where ToolsRequired is 1
298// it fails it: a skip there would be a green run that tested nothing.
299func Absent(t testing.TB, what string) {
300 t.Helper()
301 if os.Getenv(ToolsRequired) == "1" {
302 t.Fatalf("%s, and %s=1 says this machine has it", what, ToolsRequired)
303 return
304 }
305 t.Skip(what)
306}
307