Files
alzeo/tests/test_suite_isolation.py
T
Hasan BasbunarandClaude Opus 5.5 d8766bb228 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 <noreply@anthropic.com>
2026-10-30 11:51:55 +01:00

113 lines
5.0 KiB
Python

#!/usr/bin/env python3
"""A test file must hand the process back the environment it borrowed.
`tests/test_tools.py` points HOME at a throwaway directory, and it has to: the
scripts it loads read the serving API key at module level, so importing one on a
machine without `~/.config/qwen38/api-key` raises before a single test runs.
Doing it at module level is subtly worse than it looks, because unittest imports
every module of a run before executing any of them: the assignment reached files
that run long before that one. `test_install_sudo` replays install.sh for real,
and install.sh sizes its disk preflight from whether the checkpoints are cached
(10 GB when they are, 230 GB when they are not). Under the borrowed HOME it saw
an empty cache, died at step 1 for lack of space, and reported that as a failure
of the step 8 refusal it never reached. Full-suite runs only, on a box that has
the cache, which is the kind of failure that gets called a flake and muted
(2026-09-18).
Two gates, for the two moments a file can leak: importing, and running.
"""
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import unittest
REPO = pathlib.Path(__file__).resolve().parents[1]
# Imports every module the way a suite run does, and names the first one that
# leaves HOME somewhere else.
IMPORT_PROBE = """
import importlib, os, pathlib
before = os.environ.get("HOME")
for path in sorted(pathlib.Path("tests").glob("test_*.py")):
name = path.stem
if name == "test_suite_isolation":
continue
importlib.import_module("tests." + name)
now = os.environ.get("HOME")
if now != before:
print("LEAK=" + name + " " + str(before) + " -> " + str(now))
before = now
print("DONE")
"""
# 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
# HOME that has no key: nothing may appear there. They used to write "test-key" into
# ~/.config/qwen38/api-key when it was missing and delete it at tearDownClass, which a Ctrl-C
# skips, and install.sh keeps a key it finds (found in review, 2026-09-24). The check runs
# between setUpClass and tearDownClass, which is where an interrupted run stops.
KEY_FIXTURES = {"tests.test_proxy_guard": ("ProxyGuard", "ProxyInFrontOfLoadingEngine",
"RefusalIsRecognisableAsOverflow",
"TopLogprobsCeilingEndToEnd"),
"tests.test_proxy_systemone": ("SystemOne",)}
KEY_PROBE = """
import importlib, json, os, pathlib, sys
home = pathlib.Path(os.environ["HOME"])
wrote = []
for name, classes in json.loads(sys.argv[1]).items():
mod = importlib.import_module(name)
for cls_name in classes:
cls = getattr(mod, cls_name)
cls.setUpClass()
try:
wrote += [f"{cls_name}: {p.relative_to(home)}" for p in sorted(home.rglob("*"))]
finally:
cls.tearDownClass()
print("WROTE=" + json.dumps(wrote))
"""
def run(code, *args, timeout=600):
return subprocess.run([sys.executable, "-c", code, *args], cwd=REPO,
capture_output=True, text=True, timeout=timeout,
env=dict(os.environ))
class SuiteIsolation(unittest.TestCase):
def test_no_test_file_moves_home_at_import(self):
"""unittest imports them all first, so an import-time move hits everyone."""
proc = run(IMPORT_PROBE)
self.assertIn("DONE", proc.stdout,
f"the import probe did not finish:\n{proc.stdout}\n{proc.stderr[-2000:]}")
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_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-")
try:
proc = subprocess.run([sys.executable, "-c", KEY_PROBE, json.dumps(KEY_FIXTURES)],
cwd=REPO, capture_output=True, text=True, timeout=300,
env={**os.environ, "HOME": home})
line = next((l for l in proc.stdout.splitlines() if l.startswith("WROTE=")), None)
self.assertIsNotNone(line, f"the probe did not finish:\n{proc.stdout}\n{proc.stderr[-2000:]}")
self.assertEqual(json.loads(line[len("WROTE="):]), [],
"a fixture wrote into HOME, where an interrupted run leaves it")
finally:
shutil.rmtree(home, ignore_errors=True)
if __name__ == "__main__":
unittest.main(verbosity=2)