// Package testci keeps go test's result cache honest, and holds the // quarantine of known flaky tests. // // make test reuses a cached pass for a package whose inputs have not // changed. go test keys that result on the test binary, on the files and // directories the test process itself opened or stat'ed inside the module // (by size and modification time), and on the environment variables it // read. Three kinds of input escape that key: // // - repository files a child process reads: a go build of a command, a // Python fixture run by python3; // - programs installed outside the module, such as codex or bwrap; // - which tests CI has quarantined. // // A test with one of those declares it here, and a change to it then // reruns the test instead of replaying an old pass. package testci import ( "bufio" "io/fs" "os" "os/exec" "path/filepath" "slices" "strings" "sync" "testing" ) // Files declares repository files a child process reads: a script it // runs, a fixture it is handed. Paths are relative to the test's package // directory, as the test itself names them. A directory declares every // file under it. func Files(t testing.TB, paths ...string) { t.Helper() for _, p := range paths { err := filepath.WalkDir(p, func(path string, _ fs.DirEntry, err error) error { if err != nil { return err } return open(path) }) if err != nil { t.Fatalf("testci: declare %s: %v", p, err) } } } // open records path as an input. For a directory go test hashes the // listing, with each entry's size and modification time. func open(path string) error { f, err := os.Open(path) if err != nil { return err } return f.Close() } // goValueFlags are the go build and go test flags that take their value // as the next argument, so that argument is not a package pattern. var goValueFlags = map[string]bool{ "-o": true, "-tags": true, "-overlay": true, "-ldflags": true, "-gcflags": true, "-asmflags": true, "-p": true, "-run": true, "-skip": true, "-count": true, "-timeout": true, "-C": true, "-mod": true, "-modfile": true, "-pkgdir": true, "-toolexec": true, "-exec": true, "-f": true, "-coverprofile": true, } // GoCommand declares the source a child go command compiles: cmd is a // `go build`, `go test`, `go list` or `go vet` the test is about to run. // Every package it names, every package of this module those import (as // its -tags select them), their embedded files, go.mod and go.sum become // inputs, so editing the command's source reruns the test. func GoCommand(t testing.TB, cmd *exec.Cmd) { t.Helper() args := cmd.Args[1:] if len(args) == 0 { t.Fatalf("testci: %v is not a go command", cmd.Args) } var tags string var patterns []string for i := 1; i < len(args); i++ { a := args[i] switch { case a == "--": i = len(args) case !strings.HasPrefix(a, "-"): patterns = append(patterns, a) case strings.HasPrefix(a, "-tags="): tags = strings.TrimPrefix(a, "-tags=") case a == "-tags" && i+1 < len(args): tags = args[i+1] i++ case !strings.Contains(a, "=") && goValueFlags[a]: i++ } } if len(patterns) == 0 { patterns = []string{"."} } GoPackages(t, cmd.Dir, cmd.Env, tags, patterns...) } // GoPackages declares the source of packages a child go command compiles // from dir (the test's package directory when empty), as GoCommand does. // The go list behind it runs once per process for the same arguments. func GoPackages(t testing.TB, dir string, env []string, tags string, patterns ...string) { t.Helper() key := strings.Join(append([]string{dir, tags}, patterns...), "\x00") listed.Lock() paths, ok := listed.paths[key] listed.Unlock() if !ok { format := `{{if .Module}}{{if .Module.Main}}{{.Dir}}{{range .EmbedFiles}} {{$.Dir}}/{{.}}{{end}} {{.Module.GoMod}}{{end}}{{end}}` list := exec.Command("go", append([]string{"list", "-deps", "-tags=" + tags, "-f", format}, patterns...)...) list.Dir, list.Env = dir, env out, err := list.Output() if err != nil { t.Fatalf("testci: go list %v: %v", patterns, err) } seen := map[string]bool{} for _, path := range strings.Split(string(out), "\n") { if path == "" || seen[path] { continue } seen[path] = true paths = append(paths, path) if filepath.Base(path) == "go.mod" { paths = append(paths, filepath.Join(filepath.Dir(path), "go.sum")) } } listed.Lock() listed.paths[key] = paths listed.Unlock() } for _, path := range paths { if err := open(path); err != nil && !os.IsNotExist(err) { t.Fatalf("testci: %v", err) } } } var listed = struct { sync.Mutex paths map[string][]string }{paths: map[string][]string{}} // fingerprinted are the programs make test fingerprints into // EQUIPO_TEST_TOOLS (TEST_TOOLS in scripts/ci-test.py). Keep the two lists the // same. var fingerprinted = []string{"bwrap", "claude", "codex", "git", "gofmt", "python3", "sh", "srt", "tar", // try-bin is the directory of pinned provider binaries the replay // tests run (~/.local/share/equipo/try/bin), every file in it. "try-bin", // pi is the pinned Pi install the real-Pi tests run (EQUIPO_PI_ROOT). "pi", // opencode is the pinned OpenCode install the real-OpenCode tests run // (EQUIPO_OPENCODE_ROOT). "opencode"} // Tools declares programs installed outside the module that the test // runs. Their bytes are outside what go test hashes, so make test hands // the test a fingerprint of each one's resolved path, size and // modification time in EQUIPO_TEST_TOOLS, and reading it here puts that // fingerprint in the cache key: upgrading codex reruns the codex tests. func Tools(t testing.TB, names ...string) { t.Helper() for _, name := range names { if !slices.Contains(fingerprinted, name) { t.Fatalf("testci: %s is not fingerprinted; add it to TEST_TOOLS in scripts/ci-test.py and to fingerprinted in testci", name) } } _ = os.Getenv("EQUIPO_TEST_TOOLS") } // RepoFiles declares the whole repository: every tracked or untracked, // not ignored, file. For a test whose child reads the tree as git lists // it, such as the dead-reference scan. func RepoFiles(t testing.TB) { t.Helper() root, err := moduleRoot() if err != nil { t.Fatalf("testci: %v", err) } // git -C, not a working directory: go test records the directory a // child starts in, and the root's would put its mtime in the key. ls := exec.Command("git", "-C", root, "ls-files", "-z", "--cached", "--others", "--exclude-standard") out, err := ls.Output() if err != nil { t.Fatalf("testci: git ls-files: %v", err) } // Every directory but the root is declared, so a file added anywhere // below it reruns the test. The root's own modification time moves on // every CI job (the runner and the gate's tools touch it), which would // make the test uncacheable; its tracked files are declared one by one. dirs := map[string]bool{root: true} for _, name := range strings.Split(string(out), "\x00") { if name == "" { continue } path := filepath.Join(root, name) if err := open(path); err != nil && !os.IsNotExist(err) { t.Fatalf("testci: %v", err) } for d := filepath.Dir(path); !dirs[d]; d = filepath.Dir(d) { dirs[d] = true } } delete(dirs, root) for d := range dirs { if err := open(d); err != nil { t.Fatalf("testci: %v", err) } } } // moduleRoot is the nearest directory above the working directory that // holds go.mod. func moduleRoot() (string, error) { dir, err := os.Getwd() if err != nil { return "", err } for { if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { return dir, nil } parent := filepath.Dir(dir) if parent == dir { return "", os.ErrNotExist } dir = parent } } // QuarantineFile lists the quarantined tests, relative to the module root. const QuarantineFile = "scripts/ci-quarantine.txt" // Quarantine skips the calling test or subtest in the normal CI test // lanes (EQUIPO_QUARANTINE=skip) when QuarantineFile lists it: a known // flake, which make test-quarantine runs on its own, retrying a failure // once and reporting a pass on the retry as a flake. A test the file does // not list, and any test outside those lanes, runs as usual, so the file // alone decides what is quarantined. Call it first; a loop of subtests // can call it in every subtest. func Quarantine(t testing.TB) { t.Helper() if os.Getenv("EQUIPO_QUARANTINE") != "skip" { return } listed, err := quarantineListed(t.Name()) if err != nil { t.Fatalf("testci: %v", err) } if listed { t.Skip("quarantined flake: runs in the test-quarantine step (" + QuarantineFile + ")") } } // quarantineListed reports whether the quarantine file names test in // this package (the working directory go test runs it in). func quarantineListed(test string) (bool, error) { pkg, err := os.Getwd() if err != nil { return false, err } dir, err := moduleRoot() if err != nil { return false, err } rel, err := filepath.Rel(dir, pkg) if err != nil { return false, err } f, err := os.Open(filepath.Join(dir, QuarantineFile)) if err != nil { return false, err } defer f.Close() s := bufio.NewScanner(f) for s.Scan() { fields := strings.Fields(s.Text()) if len(fields) >= 2 && fields[0] == "./"+filepath.ToSlash(rel) && fields[1] == test { return true, nil } } return false, s.Err() } // ToolsRequired is the environment variable CI sets to 1 on a machine it // has given every pinned program the tests run (make ci-box does). const ToolsRequired = "EQUIPO_TEST_TOOLS_REQUIRED" // Absent reports that a pinned program the test runs is not installed. // On a developer's machine that skips the test. Where ToolsRequired is 1 // it fails it: a skip there would be a green run that tested nothing. func Absent(t testing.TB, what string) { t.Helper() if os.Getenv(ToolsRequired) == "1" { t.Fatalf("%s, and %s=1 says this machine has it", what, ToolsRequired) return } t.Skip(what) }