package testci_test import ( "encoding/json" "os" "os/exec" "path/filepath" "reflect" "strings" "testing" "amadan.net/oficina/equipo/internal/testci" ) // loadCITest is a python prelude that loads scripts/ci-test.py as m. const loadCITest = ` import importlib.util, json, sys spec = importlib.util.spec_from_file_location("citest", "../../scripts/ci-test.py") m = importlib.util.module_from_spec(spec) spec.loader.exec_module(m) ` func python(t *testing.T, env []string, args ...string) string { t.Helper() cmd := exec.Command("python3", args...) cmd.Env = append(os.Environ(), env...) out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("python3 %v: %v: %s", args, err, out) } return string(out) } // The retry reads which tests failed from what rastrillo budget test // prints, and retries the deepest failed subtests: a parent fails only // because one of them did. A test that never finished counts; go test's // own "--- FAIL:" lines inside a test's output do not name a package and // are not read as failures. func TestRetryNamesTheFailedTests(t *testing.T) { testci.Files(t, "../../scripts/ci-test.py") report := strings.Join([]string{ "--- FAIL amadan.net/oficina/equipo/internal/headless TestHeadless", "--- FAIL: TestHeadless (45.10s)", "--- FAIL amadan.net/oficina/equipo/internal/headless TestHeadless/1_first_token", " --- FAIL: TestHeadless/1_first_token (45.02s)", "--- FAIL amadan.net/oficina/equipo/internal/runner TestStuck (never finished)", "--- FAIL amadan.net/oficina/equipo/internal/runner (package output)", "panic: test timed out", "--- FAIL amadan.net/oficina/equipo/internal/wire (package output)", "setup failed", "", }, "\n") out := python(t, nil, "-c", loadCITest+` out = json.loads(sys.argv[1]) found = {p: m.leaves(ts) for p, ts in m.failures(out).items()} print(json.dumps({"found": found, "seconds": m.failed_seconds(out, "TestHeadless/1_first_token"), "unknown": m.failed_seconds(out, "TestStuck")})) `, mustJSON(t, report)) var got struct { Found map[string][]string Seconds, Unknown string } if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("%v: %s", err, out) } want := map[string][]string{ "./internal/headless": {"TestHeadless/1_first_token"}, "./internal/runner": {"TestStuck"}, "./internal/wire": {}, } if !reflect.DeepEqual(got.Found, want) { t.Errorf("failed tests = %v, want %v", got.Found, want) } if got.Seconds != "45.02s" || got.Unknown != "unknown" { t.Errorf("failed attempt took %q and %q, want 45.02s and unknown", got.Seconds, got.Unknown) } } func mustJSON(t *testing.T, v any) string { t.Helper() raw, err := json.Marshal(v) if err != nil { t.Fatal(err) } return string(raw) } // A FLAKE line as scripts/ci-test.py prints it is what // scripts/ci-flakes.py reads back. Three flakes of one test inside the // week make it a repeat offender, with the quarantine line and the amadan // commands to file; two do not. func TestFlakeLinesAreReadBack(t *testing.T) { testci.Files(t, "../../scripts/ci-test.py", "../../scripts/ci-flakes.py", "../../scripts/ci-quarantine.txt") dir := t.TempDir() var logs []string for i, commit := range []string{strings.Repeat("a", 40), strings.Repeat("b", 40), strings.Repeat("c", 40)} { line := python(t, []string{"AMADAN_COMMIT=" + commit}, "-c", loadCITest+` print("some output before") print(m.flake_line("./internal/headless", "TestHeadless/1_first_token", "headless-rest", "45.02s", "31.50")) print(m.flake_line("./internal/thintest", "TestOnce", "thintest", "unknown", "unknown")) if sys.argv[1] == "0" else None `, string(rune('0'+i))) if !strings.Contains(line, "\nFLAKE ./internal/headless:TestHeadless/1_first_token headless-rest "+commit+" 45.02s 31.50\n") { t.Fatalf("the FLAKE line is not on a line of its own with its five fields:\n%s", line) } path := filepath.Join(dir, "run"+string(rune('0'+i))+".log") if err := os.WriteFile(path, []byte(line), 0o644); err != nil { t.Fatal(err) } logs = append(logs, "-log", path) } base := []string{"../../scripts/ci-flakes.py", "-no-fetch", "-history", filepath.Join(dir, "history.jsonl")} out := python(t, nil, append(base, logs...)...) for _, want := range []string{ "3 ./internal/headless TestHeadless/1_first_token", "1 ./internal/thintest TestOnce", "REPEAT OFFENDER ./internal/headless TestHeadless/1_first_token: 3 flakes in 7 days", "amadan discuss new oficina/equipo -title 'Flaky test: ./internal/headless TestHeadless/1_first_token' -body -", "amadan discuss type oficina/equipo -type Issue", "testci.Quarantine(t)", } { if !strings.Contains(out, want) { t.Errorf("three flakes: output lacks %q:\n%s", want, out) } } if strings.Contains(out, "REPEAT OFFENDER ./internal/thintest") { t.Errorf("one flake made a repeat offender:\n%s", out) } // The history holds what was read: the same logs again add nothing. again := python(t, nil, append(base, logs...)...) if !strings.Contains(again, "3 ./internal/headless TestHeadless/1_first_token") { t.Errorf("reading the same runs twice changed the count:\n%s", again) } two := python(t, nil, append([]string{"../../scripts/ci-flakes.py", "-no-fetch", "-history", filepath.Join(dir, "two.jsonl")}, logs[:4]...)...) if !strings.Contains(two, "2 ./internal/headless TestHeadless/1_first_token") || strings.Contains(two, "REPEAT OFFENDER") { t.Errorf("two flakes: want the count and no repeat offender:\n%s", two) } } // A test process that prints PASS for every test and then exits non-zero // (a panic in a cleanup, a TestMain that fails after m.Run) has failed. // The retry is green only when its process exits 0 and every test it was // asked for passed; otherwise the test failed twice and the step is red. func TestRetryNeedsACleanExit(t *testing.T) { testci.Files(t, "../../scripts/ci-test.py") bin := t.TempDir() // A fake go: every test passes, then the process dies as $FAKE_GO_EXIT says. script := "#!/bin/sh\necho '=== RUN TestTeardown'\necho '--- PASS: TestTeardown (0.01s)'\necho PASS\nif [ \"$FAKE_GO_EXIT\" != 0 ]; then echo 'panic: cleanup failed after the test passed'; fi\nexit \"$FAKE_GO_EXIT\"\n" if err := os.WriteFile(filepath.Join(bin, "go"), []byte(script), 0700); err != nil { t.Fatal(err) } report := "--- FAIL amadan.net/oficina/equipo/internal/wire TestTeardown\n" run := func(exit string) (int, string) { out := python(t, []string{"PATH=" + bin + string(os.PathListSeparator) + os.Getenv("PATH"), "FAKE_GO_EXIT=" + exit}, "-c", loadCITest+` import contextlib, io buf = io.StringIO() with contextlib.redirect_stdout(buf): status = m.retry_failures(sys.argv[1], dict(__import__("os").environ), "rest", []) _, _, passed, failed, _ = m.go_test("./internal/wire", ["TestTeardown"], dict(__import__("os").environ), []) print(json.dumps({"status": status, "log": buf.getvalue(), "passed": sorted(passed), "failed": sorted(failed)})) `, report) var got struct { Status int Log string Passed, Failed []string } if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("%v: %s", err, out) } if exit != "0" && (len(got.Passed) != 0 || !reflect.DeepEqual(got.Failed, []string{"TestTeardown"})) { t.Errorf("exit %s: go_test passed %v failed %v, want the test failed", exit, got.Passed, got.Failed) } return got.Status, got.Log } if status, log := run("0"); status != 0 || !strings.Contains(log, "FLAKE ./internal/wire:TestTeardown rest ") { t.Fatalf("a clean retry is not a flake: status %d\n%s", status, log) } for _, exit := range []string{"1", "2"} { status, log := run(exit) if status == 0 || strings.Contains(log, "FLAKE ") || !strings.Contains(log, "FAILED TWICE ./internal/wire:TestTeardown rest") || !strings.Contains(log, "panic: cleanup failed after the test passed") { t.Fatalf("exit %s: a retry whose process failed went green: status %d\n%s", exit, status, log) } } } // TestMacWorker's subtests share one instance and run in order (M9b // needs what M9a left), so one of them alone fails every time: a failed // subtest of it is retried as the whole test. func TestRetryOrderedSubtestsAsWhole(t *testing.T) { testci.Files(t, "../../scripts/ci-test.py") report := strings.Join([]string{ "--- FAIL amadan.net/oficina/equipo/internal/headless TestMacWorker", "--- FAIL: TestMacWorker (138.37s)", "--- FAIL amadan.net/oficina/equipo/internal/headless TestMacWorker/M9b", " --- FAIL: TestMacWorker/M9b (4.92s)", "--- FAIL amadan.net/oficina/equipo/internal/headless TestHeadless/1_first_token", " --- FAIL: TestHeadless/1_first_token (45.02s)", "", }, "\n") out := python(t, nil, "-c", loadCITest+` out = json.loads(sys.argv[1]) print(json.dumps({p: m.leaves(ts) for p, ts in m.failures(out).items()})) `, mustJSON(t, report)) var got map[string][]string if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("%v: %s", err, out) } if want := map[string][]string{"./internal/headless": {"TestHeadless/1_first_token", "TestMacWorker"}}; !reflect.DeepEqual(got, want) { t.Errorf("retried %v, want %v", got, want) } }