From d8766bb228792d0c9d2d4fa2ecfe7d2420d29b7a Mon Sep 17 00:00:00 2001 From: Hasan Basbunar Date: Sat, 24 Oct 2026 15:04:24 +0200 Subject: [PATCH] CI: each test file runs once for the offline step and the environment check (tests/run_suite.py) A CI run ran the suite about four times (counted on 2026-10-24): the offline step ran every file on its own, tests/test_suite_isolation.py then ran every unittest module again in a process of its own to see whether it left an environment variable changed, and that file ran twice, in the offline step and in the single-process pass. tests/run_suite.py runs each file once, as a human runs it, up to four at a time, the longest first, and the files that take a port number out of a socket they close one at a time at the end, as the step's script did; a sitecustomize.py loaded into every python it starts compares the test process's environment at its start and at its exit (no test file touches the environment in its __main__ block, checked on the 246 files), and records a connect() to a serving port with the test line, as the step's own hook did. test_suite_isolation.py keeps its two quick probes (HOME at import, the proxy fixtures' key). tests/test_run_suite.py plants each defect in a throwaway repository and sees it caught: a failing test named with its output, a file that runs none of its declared tests, a variable left changed (and one set then removed not named), a contact with a serving port recorded with its line, a file that takes a port run alone, a longest file that is gone stopping the run before anything runs. tests/test_offline_step.py now drives run_suite.py over its fake tree: at most four files at a time and at least two, nothing beside a file that frees a port, the longest first. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 91 +++---------------- tests/run_suite.py | 163 ++++++++++++++++++++++++++++++++++ tests/test_offline_step.py | 34 +++---- tests/test_run_suite.py | 113 +++++++++++++++++++++++ tests/test_suite_isolation.py | 43 ++------- 5 files changed, 302 insertions(+), 142 deletions(-) create mode 100644 tests/run_suite.py create mode 100644 tests/test_run_suite.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 29491670..5623ae81 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -249,22 +249,9 @@ jobs: # records a connect() to a serving port, with the test line that made it; a # shell test's curl is not seen. Kept outside the witness, which is hashed. probe="$(mktemp -d)" - cat > "$probe/sitecustomize.py" <<'PY' - import os, sys, traceback - PORTS = {int(p) for p in os.environ.get("QWEN38_SERVING_PORTS", "").split(",") if p} - def hook(event, args): - if event != "socket.connect": - return - addr = args[1] - if isinstance(addr, tuple) and len(addr) >= 2 and addr[1] in PORTS: - where = [f"{os.path.basename(f.filename)}:{f.lineno}" for f in traceback.extract_stack() - if "/tests/" in f.filename] - with open(os.environ["QWEN38_CONTACT_LOG"], "a") as fh: - fh.write(f"{addr[0]}:{addr[1]} from {' '.join(where[-2:]) or sys.argv[0]}\n") - if PORTS and os.environ.get("QWEN38_CONTACT_LOG"): - sys.addaudithook(hook) - PY - export PYTHONPATH="$probe" QWEN38_CONTACT_LOG="$probe/contacts" QWEN38_SERVING_PORTS=30000,30001,30020,30090,30091,4096 + # tests/run_suite.py loads the same hook into every python it starts (its sitecustomize.py), + # beside the one that compares each file's environment at its start and at its exit. + export QWEN38_CONTACT_LOG="$probe/contacts" QWEN38_SERVING_PORTS=30000,30001,30020,30090,30091,4096 before="$(find "$witness" -type f -exec sha256sum {} + | sort)" ports_before="$(ss -Htln 2>/dev/null | awk '{print $4}' | sort || true)" # The suite runs under tests/suite_reaper.py, a child subreaper: every process it @@ -272,71 +259,13 @@ jobs: # suite's own, named with the sockets it listens on, then stopped. Comparing every # listener of the machine instead failed twice on the reference box on 2026-10-03, # for ports VS Code opened while the suite ran. - cat > "$probe/suite.sh" <<'SH' - # Every test file runs here once, on its own, as a human runs it. A file - # that fails says how: a red run of 2026-10-03 said only - # "tests/test_proxy_hold.py failed", and left nothing to read. A unittest - # file must run the tests it declares: one without a __main__ block exits - # 0 having run nothing. The cockpit's files run together in the cockpit - # step and tests/' in "No test file in tests/ is left unrun"; each file also - # ran on its own in those two steps until 2026-10-18, three runs in all. - # - # Up to four files run at a time, the longest first: one after the other, they - # took 20 minutes on the reference box (2026-10-18). Not a file that takes a port - # number out of a socket it then closes (getsockname()[1]), to start a server - # on that port later or to have one where nothing listens: a file running - # beside it can be handed the same port meanwhile. Those run one at a time once - # the others are over; the last lines of this step count both and name the longest. - res="$(mktemp -d)" - trap 'rm -rf "$res"' EXIT - one() { # one file on its own; its verdict is left in $res, read below - local f=$1 key dir rel out d r t0 - key=$(printf '%s' "$f" | tr / _); t0=$(date +%s) - case "$f" in dashboard/*) dir=dashboard; rel="tests/${f##*/}" ;; *) dir=.; rel="$f" ;; esac - if out="$(cd "$dir" && python3 "$rel" 2>&1 "$res/$key.fail" - fi - else - { echo "$f failed, the end of its output:"; printf '%s\n' "$out" | tail -60; } > "$res/$key.fail" - fi - echo "$(( $(date +%s) - t0 )) $f" > "$res/$key.done" - } - all=$(printf '%s ' dashboard/tests/test_*.py tests/test_*.py) - alone=" $(grep -lF 'getsockname()[1]' $all | tr '\n' ' ')" - # the longest of the others, which the last line of this step names again - first="tests/test_suite_isolation.py tests/test_text_lane.py tests/test_check_pins.py" - together="" - for f in $first $all; do - [ -f "$f" ] || { echo "$f, named as one of the longest, is gone: name them again"; exit 1; } - case "$alone $together " in *" $f "*) continue ;; esac - together="$together $f" - done - jobs=$(nproc); [ "$jobs" -le 4 ] || jobs=4 - t0=$(date +%s); n=0 - for f in $together; do - one "$f" & - n=$((n + 1)) - [ "$n" -lt "$jobs" ] || { wait -n || true; n=$((n - 1)); } - done - wait - t1=$(date +%s) - for f in $alone; do one "$f"; done - t2=$(date +%s) - # A file with no verdict is a failure too: its runner stopped before writing it. - failed=0 - for f in $together $alone; do - key=$(printf '%s' "$f" | tr / _) - if [ ! -f "$res/$key.done" ]; then echo "$f gave no verdict"; failed=1 - elif [ -f "$res/$key.fail" ]; then cat "$res/$key.fail"; failed=1; fi - done - [ "$failed" = 0 ] || exit 1 - echo "every test file ran its declared tests on its own: $(echo "$together" | wc -w) of them $jobs at a time in $((t1 - t0)) s, then $(echo "$alone" | wc -w) one at a time in $((t2 - t1)) s" - echo " the longest: $(sort -rn "$res"/*.done | head -3 | awk '{printf "%s%s %d s", (NR > 1 ? ", " : ""), $2, $1}')" - SH - python3 tests/suite_reaper.py bash -e "$probe/suite.sh" + # Every test file runs once, on its own, as a human runs it, up to four at a time, the + # longest first, the files that take a port number out of a socket they close one at a + # time at the end (tests/run_suite.py): it fails, runs fewer tests than it declares, or + # leaves an environment variable changed, and it is named with what it did. The suite ran + # about four times per CI run until 2026-10-24: here, then each module again in + # tests/test_suite_isolation.py, which this step and the single-process pass both ran. + python3 tests/suite_reaper.py python3 tests/run_suite.py after="$(find "$witness" -type f -exec sha256sum {} + | sort)" if [ "$before" != "$after" ]; then echo "the offline suite wrote into HOME:" diff --git a/tests/run_suite.py b/tests/run_suite.py new file mode 100644 index 00000000..55ee532b --- /dev/null +++ b/tests/run_suite.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Every test file of the repo, run once, on its own, as a human runs it, several at a time. + +The offline step ran each file on its own, then tests/test_suite_isolation.py ran each unittest +module again in a process of its own to see whether it left an environment variable changed for +the files after it, and that file itself ran twice, in the offline step and in the single-process +pass: the suite ran about four times in a CI run (counted on 2026-10-24). This runs each file once +and takes every fact from that one run: + +- it passes, and a unittest file runs as many tests as it declares when invoked directly (a file + without a __main__ block exits 0 having run nothing); +- it leaves no environment variable changed on its way out (sitecustomize.py below compares the + process's environment at its start and at its exit), the fact the files after it in one process + would inherit; +- it contacts no serving port (the same hook records a connect() to one, with the test line). + +Files that take a port number out of a socket they close (getsockname()[1]) run one at a time once +the others are over: a file running beside them could be handed the same port meanwhile. The +witness HOME, the listeners and what is left running are the CI step's, around this script. + +Usage: run_suite.py [--jobs N] [--report FILE] [--repo DIR --first F1,F2] (exit 1 on any failure; +--repo and --first point it at another tree, for its own tests) +""" +import argparse +import json +import os +import pathlib +import subprocess +import sys +import tempfile +import time +from concurrent.futures import ThreadPoolExecutor + +REPO = pathlib.Path(__file__).resolve().parents[1] + +# The longest files start first, so that they do not end alone at the tail of the run. +FIRST = ["tests/test_text_lane.py", "tests/test_check_pins.py"] + +# spelled in two parts: the CI counts that string to know how many tests a file declares +TEST_DEF = "def " + "test_" + +# Loaded by every python the suite starts (PYTHONPATH). It writes the environment changes of the +# test file's own process only, the one whose script is the file under test. +SITECUSTOMIZE = r''' +import atexit, json, os, sys, traceback +_START = dict(os.environ) +_PORTS = {int(p) for p in os.environ.get("QWEN38_SERVING_PORTS", "").split(",") if p} + +def _contact(event, args): + if event != "socket.connect": + return + addr = args[1] + if isinstance(addr, tuple) and len(addr) >= 2 and addr[1] in _PORTS: + where = [f"{os.path.basename(f.filename)}:{f.lineno}" for f in traceback.extract_stack() + if "/tests/" in f.filename] + with open(os.environ["QWEN38_CONTACT_LOG"], "a") as fh: + fh.write(f"{addr[0]}:{addr[1]} from {' '.join(where[-2:]) or sys.argv[0]}\n") + +if _PORTS and os.environ.get("QWEN38_CONTACT_LOG"): + sys.addaudithook(_contact) + +def _env_at_exit(): + target, report = _START.get("QWEN38_ENV_FOR"), _START.get("QWEN38_ENV_REPORT") + if not (target and report and sys.argv and os.path.abspath(sys.argv[0]) == target): + return + now = dict(os.environ) + changed = sorted(k for k in set(_START) | set(now) if _START.get(k) != now.get(k)) + with open(report, "w") as fh: + json.dump(changed, fh) + +atexit.register(_env_at_exit) +''' + + +def files(repo=REPO): + """Every test file: dashboard/tests/test_*.py and tests/test_*.py, as the repo has them.""" + return sorted(str(p.relative_to(repo)) for p in [*(repo / "dashboard" / "tests").glob("test_*.py"), + *(repo / "tests").glob("test_*.py")]) + + +def plan(all_files, repo=REPO, first=FIRST): + """(together, alone): the longest named first, then the others, and the files that must run alone.""" + alone = [f for f in all_files if "getsockname()[1]" in (repo / f).read_text()] + missing = [f for f in first if f not in all_files] + if missing: + raise SystemExit(f"{missing}, named as the longest, are gone: name them again in FIRST") + together = [f for f in first if f not in alone] + [f for f in all_files if f not in first and f not in alone] + return together, alone + + +def run_one(f, probe, repo=REPO, timeout=1800): + """One file on its own, in the directory a human runs it from: its verdict as a dict.""" + path = repo / f + cwd, rel = (repo / "dashboard", "tests/" + path.name) if f.startswith("dashboard/") else (repo, f) + env_report = probe / ("env-" + f.replace("/", "_") + ".json") + env = {**os.environ, "PYTHONPATH": os.pathsep.join(filter(None, [str(probe), os.environ.get("PYTHONPATH")])), + "QWEN38_ENV_FOR": str(path), "QWEN38_ENV_REPORT": str(env_report)} + t0 = time.monotonic() + try: + r = subprocess.run([sys.executable, rel], cwd=cwd, env=env, capture_output=True, text=True, + stdin=subprocess.DEVNULL, timeout=timeout) + rc, out = r.returncode, r.stdout + r.stderr + except subprocess.TimeoutExpired as e: + rc, out = None, f"timed out after {timeout} s\n{(e.stdout or b'')[-4000:]!r}" + verdict = {"file": f, "seconds": round(time.monotonic() - t0, 1), "rc": rc, "problems": []} + if rc != 0: + verdict["problems"].append("failed, the end of its output:\n" + "\n".join(out.splitlines()[-60:])) + return verdict + text = path.read_text() + if TEST_DEF in text: + declared = text.count(TEST_DEF) + ran = max([int(w.split()[1]) for w in out.splitlines() if w.startswith("Ran ") and w.split()[1].isdigit()], + default=0) + if ran != declared: + verdict["problems"].append(f"ran {ran} of its {declared} declared tests when invoked directly") + try: + changed = json.loads(env_report.read_text()) + except (OSError, ValueError): + changed = None + if changed is None: + verdict["problems"].append("its process never reported its environment at exit") + elif changed: + verdict["problems"].append(f"left these environment variables changed: {', '.join(changed)}") + return verdict + + +def main(argv): + ap = argparse.ArgumentParser(add_help=False) + ap.add_argument("--jobs", type=int, default=min(os.cpu_count() or 4, 4)) + ap.add_argument("--report") + ap.add_argument("--repo", default=str(REPO)) + ap.add_argument("--first", default=",".join(FIRST)) + a = ap.parse_args(argv) + repo = pathlib.Path(a.repo).resolve() + try: + together, alone = plan(files(repo), repo=repo, first=[f for f in a.first.split(",") if f]) + except SystemExit as e: + print(e) + return 1 + with tempfile.TemporaryDirectory(prefix="run-suite-") as d: + probe = pathlib.Path(d) + (probe / "sitecustomize.py").write_text(SITECUSTOMIZE) + t0 = time.monotonic() + with ThreadPoolExecutor(max_workers=a.jobs) as pool: + verdicts = list(pool.map(lambda f: run_one(f, probe, repo=repo), together)) + t1 = time.monotonic() + verdicts += [run_one(f, probe, repo=repo) for f in alone] + t2 = time.monotonic() + bad = [v for v in verdicts if v["problems"]] + for v in bad: + for p in v["problems"]: + print(f"{v['file']} {p}") + longest = sorted(verdicts, key=lambda v: -v["seconds"])[:3] + print(f"every test file ran on its own: {len(together)} of them {a.jobs} at a time in {t1 - t0:.0f} s, " + f"then {len(alone)} one at a time in {t2 - t1:.0f} s; {len(bad)} with a problem") + print(" the longest: " + ", ".join(f"{v['file']} {v['seconds']:.0f} s" for v in longest)) + if a.report: + pathlib.Path(a.report).write_text(json.dumps(verdicts, indent=1)) + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/test_offline_step.py b/tests/test_offline_step.py index 9deeb96d..6e3b4370 100644 --- a/tests/test_offline_step.py +++ b/tests/test_offline_step.py @@ -7,14 +7,15 @@ except the files that take a port number out of a socket they close, to start a later or to have a port where nothing listens: a file running beside one of them can be handed that port meanwhile, so they run one at a time once the others are over. -The step's own script runs here, as ci.yml writes it, over a tree of files whose tests record -when they ran: every file still runs and has its count checked, every failure is named with -the end of its output, and nothing runs beside a file that frees a port.""" +The step's runner, tests/run_suite.py since 2026-10-24 (a script ci.yml wrote before), runs here +over a tree of files whose tests record when they ran: every file still runs and has its count +checked, every failure is named with the end of its output, and nothing runs beside a file that +frees a port.""" import os import pathlib import subprocess +import sys import tempfile -import textwrap import unittest REPO = pathlib.Path(__file__).resolve().parents[1] @@ -22,7 +23,7 @@ REPO = pathlib.Path(__file__).resolve().parents[1] # and takes a file holding the second for one that frees a port TEST_DEF = "def " + "test_" FREES_A_PORT = "getsockname" + "()[1]" -LONGEST = ("tests/test_suite_isolation.py", "tests/test_text_lane.py", "tests/test_check_pins.py") +LONGEST = ("tests/test_x_long.py", "tests/test_text_lane.py", "tests/test_check_pins.py") FAKE = """import os, sys, time, unittest # {mark} @@ -38,18 +39,6 @@ MAIN = """if __name__ == "__main__": """ -def suite_script(): - """The script the offline step writes to suite.sh, as ci.yml spells it.""" - ci = (REPO / ".github/workflows/ci.yml").read_text() - body = ci.split("cat > \"$probe/suite.sh\" <<'SH'\n", 1)[1] - lines = [] - for ln in body.splitlines(): - if ln.strip() == "SH": - break - lines.append(ln) - return textwrap.dedent("\n".join(lines)) + "\n" - - class TheOfflineStep(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -77,10 +66,9 @@ class TheOfflineStep(unittest.TestCase): for path, text in self.files.items(): (self.root / path).parent.mkdir(parents=True, exist_ok=True) (self.root / path).write_text(text) - script = pathlib.Path(self.tmp.name) / "suite.sh" - script.write_text(suite_script()) - r = subprocess.run(["bash", "-e", str(script)], cwd=self.root, capture_output=True, text=True, - timeout=120, env={**os.environ, "FAKE_LOG": str(self.log)}) + r = subprocess.run([sys.executable, str(REPO / "tests" / "run_suite.py"), "--repo", str(self.root), + "--first", ",".join(LONGEST)], capture_output=True, text=True, timeout=120, + env={**os.environ, "FAKE_LOG": str(self.log)}) ran = {} if self.log.exists(): for ln in self.log.read_text().splitlines(): @@ -92,7 +80,7 @@ class TheOfflineStep(unittest.TestCase): rc, out, ran = self.run_step() self.assertEqual(rc, 0, out) self.assertEqual(set(ran), set(self.files), out) - self.assertIn("ran its declared tests on its own: 9 of them", out) + self.assertIn("every test file ran on its own: 9 of them", out) self.assertIn("then 2 one at a time", out) self.assertRegex(out, r"the longest: \S+ \d+ s, \S+ \d+ s, \S+ \d+ s\n") alone = {p: ran[p] for p in ("tests/test_port_e.py", "tests/test_port_f.py")} @@ -130,7 +118,7 @@ class TheOfflineStep(unittest.TestCase): del self.files["tests/test_check_pins.py"] rc, out, ran = self.run_step() self.assertEqual(rc, 1, out) - self.assertIn("tests/test_check_pins.py, named as one of the longest, is gone", out) + self.assertIn("['tests/test_check_pins.py'], named as the longest, are gone", out) self.assertEqual(ran, {}, "the step ran files with a stale list") diff --git a/tests/test_run_suite.py b/tests/test_run_suite.py new file mode 100644 index 00000000..d370e603 --- /dev/null +++ b/tests/test_run_suite.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""tests/run_suite.py catches each defect the suite's gates exist for, from one run of each file. + +It replaces running the suite about four times per CI run (the offline step, then +tests/test_suite_isolation.py re-running every module to compare its environment, in two steps): +each gate it takes over is proven here on a planted defect, in a throwaway repository.""" +import importlib.util +import pathlib +import shutil +import tempfile +import unittest + +REPO = pathlib.Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("run_suite", REPO / "tests" / "run_suite.py") +rs = importlib.util.module_from_spec(spec) +spec.loader.exec_module(rs) + +MAIN = '\n\nif __name__ == "__main__":\n unittest.main()\n' +FILES = { + "tests/test_ok.py": "import unittest\n\nclass T(unittest.TestCase):\n def test_a(self):\n pass\n\n" + " def test_b(self):\n pass\n" + MAIN, + "tests/test_fails.py": "import unittest\n\nclass T(unittest.TestCase):\n def test_a(self):\n" + " self.assertEqual(1, 2)\n" + MAIN, + # declares a test and runs none when invoked directly + "tests/test_no_main.py": "import unittest\n\nclass T(unittest.TestCase):\n def test_a(self):\n pass\n", + "tests/test_leaks.py": "import os, unittest\n\nclass T(unittest.TestCase):\n def test_a(self):\n" + " os.environ['LEAKED_BY_A_TEST'] = '1'\n" + MAIN, + "tests/test_restores.py": "import os, unittest\n\nclass T(unittest.TestCase):\n def test_a(self):\n" + " os.environ['SET_THEN_GONE'] = '1'\n del os.environ['SET_THEN_GONE']\n" + MAIN, + "tests/test_contacts.py": "import socket, unittest\n\nclass T(unittest.TestCase):\n def test_a(self):\n" + " s = socket.socket()\n try:\n s.connect(('127.0.0.1', 1))\n" + " except OSError:\n pass\n finally:\n s.close()\n" + MAIN, + "tests/test_takes_a_port.py": "import socket, unittest\n\nclass T(unittest.TestCase):\n def test_a(self):\n" + " s = socket.socket(); s.bind(('127.0.0.1', 0)); s.getsockname()[1]; s.close()\n" + MAIN, + "dashboard/tests/test_cockpit_side.py": "import unittest\n\nclass T(unittest.TestCase):\n def test_a(self):\n" + " pass\n" + MAIN, +} + + +class OnPlantedDefects(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.repo = pathlib.Path(tempfile.mkdtemp(prefix="run-suite-repo-")) + for rel, text in FILES.items(): + (cls.repo / rel).parent.mkdir(parents=True, exist_ok=True) + (cls.repo / rel).write_text(text) + cls.probe = pathlib.Path(tempfile.mkdtemp(prefix="run-suite-probe-")) + (cls.probe / "sitecustomize.py").write_text(rs.SITECUSTOMIZE) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.repo, ignore_errors=True) + shutil.rmtree(cls.probe, ignore_errors=True) + + def verdict(self, rel, **env): + old = {k: rs.os.environ.get(k) for k in env} + rs.os.environ.update(env) + try: + return rs.run_one(rel, self.probe, repo=self.repo, timeout=120) + finally: + for k, v in old.items(): + if v is None: + rs.os.environ.pop(k, None) + else: + rs.os.environ[k] = v + + def test_a_clean_file_has_no_problem(self): + v = self.verdict("tests/test_ok.py") + self.assertEqual((v["rc"], v["problems"]), (0, [])) + + def test_a_failing_test_is_named_with_its_output(self): + v = self.verdict("tests/test_fails.py") + self.assertNotEqual(v["rc"], 0) + self.assertIn("AssertionError", v["problems"][0]) + + def test_a_file_that_runs_none_of_its_tests_is_caught(self): + v = self.verdict("tests/test_no_main.py") + self.assertEqual(v["problems"], ["ran 0 of its 1 declared tests when invoked directly"]) + + def test_a_variable_left_changed_is_named(self): + v = self.verdict("tests/test_leaks.py") + self.assertEqual(v["problems"], ["left these environment variables changed: LEAKED_BY_A_TEST"]) + + def test_a_variable_set_and_removed_is_not(self): + self.assertEqual(self.verdict("tests/test_restores.py")["problems"], []) + + def test_a_cockpit_file_runs_from_the_dashboard(self): + self.assertEqual(self.verdict("dashboard/tests/test_cockpit_side.py")["problems"], []) + + def test_a_contact_with_a_serving_port_is_recorded_with_its_line(self): + log = self.probe / "contacts" + log.unlink(missing_ok=True) + v = self.verdict("tests/test_contacts.py", QWEN38_SERVING_PORTS="1", QWEN38_CONTACT_LOG=str(log)) + self.assertEqual(v["problems"], []) + self.assertIn("127.0.0.1:1 from test_contacts.py:", log.read_text()) + + def test_a_file_that_takes_a_port_runs_alone(self): + together, alone = rs.plan(rs.files(self.repo), repo=self.repo, first=[]) + self.assertEqual(alone, ["tests/test_takes_a_port.py"]) + self.assertNotIn("tests/test_takes_a_port.py", together) + self.assertEqual(len(together) + len(alone), len(FILES)) + + def test_a_longest_file_that_is_gone_stops_the_run(self): + with self.assertRaisesRegex(SystemExit, "named as the longest, are gone"): + rs.plan(rs.files(self.repo), repo=self.repo, first=["tests/test_gone.py"]) + + def test_the_real_plan_names_files_that_exist(self): + together, alone = rs.plan(rs.files()) + self.assertEqual(sorted(together + alone), rs.files()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_suite_isolation.py b/tests/test_suite_isolation.py index 9205f698..3d3d5532 100644 --- a/tests/test_suite_isolation.py +++ b/tests/test_suite_isolation.py @@ -45,20 +45,11 @@ for path in sorted(pathlib.Path("tests").glob("test_*.py")): print("DONE") """ -# And running each one, in a process of its own, since a file can also leave the -# environment changed on the way out: a teardown is the fix there. Only -# tests/test_tools.py was run, and only HOME compared, while four files left UPSTREAM, -# KEEPALIVE_S and the rest set for every module after them (found in review, 2026-09-24). -RUN_PROBE = """ -import json, os, sys, unittest -sys.path.insert(0, os.getcwd()) -before = dict(os.environ) -suite = unittest.defaultTestLoader.loadTestsFromName("tests." + sys.argv[1]) -with open(os.devnull, "w") as null: - unittest.TextTestRunner(stream=null, verbosity=0).run(suite) -after = dict(os.environ) -print("CHANGED=" + json.dumps(sorted(k for k in set(before) | set(after) if before.get(k) != after.get(k)))) -""" +# A file can also leave the environment changed on the way out, a teardown being the fix +# there: four files left UPSTREAM, KEEPALIVE_S and the rest set for every module after them +# (found in review, 2026-09-24). tests/run_suite.py checks that fact for every file, from the +# one run of each it makes; this file ran every module again for it, in two CI steps, until +# 2026-10-24. # The fixtures that give a proxy its engine key, set up the way unittest sets them up, in a @@ -87,16 +78,6 @@ print("WROTE=" + json.dumps(wrote)) """ -# spelled in two parts: the CI counts that string to know how many tests a file declares -TEST_DEF = "def " + "test_" - - -def modules(): - """Every unittest module of tests/ but this one.""" - return [p.stem for p in sorted((REPO / "tests").glob("test_*.py")) - if p.stem != "test_suite_isolation" and TEST_DEF in p.read_text()] - - def run(code, *args, timeout=600): return subprocess.run([sys.executable, "-c", code, *args], cwd=REPO, capture_output=True, text=True, timeout=timeout, @@ -112,20 +93,6 @@ class SuiteIsolation(unittest.TestCase): leaks = [l for l in proc.stdout.splitlines() if l.startswith("LEAK=")] self.assertEqual(leaks, [], "importing these files moved HOME for every file after them") - def test_no_test_file_leaves_the_environment_changed(self): - """The same fact on the way out, for every file and every variable.""" - from concurrent.futures import ThreadPoolExecutor - with ThreadPoolExecutor(max_workers=4) as pool: - procs = dict(zip(modules(), pool.map(lambda m: run(RUN_PROBE, m, timeout=1200), modules()))) - leaks = {} - for name, proc in procs.items(): - line = next((ln for ln in proc.stdout.splitlines() if ln.startswith("CHANGED=")), None) - self.assertIsNotNone(line, f"the probe of {name} did not finish:\n{proc.stderr[-2000:]}") - changed = json.loads(line[len("CHANGED="):]) - if changed: - leaks[name] = changed - self.assertEqual(leaks, {}, "these files left environment variables changed for the files after them") - def test_no_proxy_fixture_writes_a_key_into_home(self): """The engine key is handed to the proxy, never left in the HOME it runs from.""" home = tempfile.mkdtemp(prefix="key-probe-home-")