diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index c364bb35df..6fb4e03615 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py @@ -12,8 +12,9 @@ because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an error in serial and parallel runs. -It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each as -`python -m unittest ` from that folder, so a file sees the same import path as under discover. The files can +It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each in +an isolated Python process. A small bootstrap adds only the suite directory to `sys.path` before loading the module, so +host `PYTHONPATH` and user site-packages cannot supply test imports. The files can run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1, or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary line, and exits 1 if a file fails, none is found, or no test ran. Standard library only. @@ -74,12 +75,15 @@ def positive_seconds(value): def run_module(directory, module, verbose, timeout=None): - """(return code, tests run, output) of `python -m unittest ` run from `directory`.""" + """(return code, tests run, output) of an isolated unittest process loading target from directory.""" # `python -m unittest pkg.__init__` imports pkg and then runs the same file again as pkg.__init__, so a # registration in the initializer happens twice. Running the package itself imports it once; module_path() is # still the initializer's path, so the jobs stay sorted by the file they run. target = module[:-len(".__init__")] if module.endswith(".__init__") else module - cmd = [sys.executable, "-m", "unittest", *(["-v"] if verbose else []), target] + cmd = [sys.executable, "-I", "-c", + "import sys, unittest; sys.path.insert(0, sys.argv[1]); " + "unittest.main(module=sys.argv[2], argv=['unittest', *sys.argv[3:]])", + directory, target, *(["-v"] if verbose else [])] try: p = subprocess.run(cmd, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace", timeout=timeout) @@ -114,7 +118,7 @@ def main(argv=None): return 1 if a.jobs <= 1: try: - return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory, + return subprocess.call([sys.executable, "-I", "-m", "unittest", "discover", "-s", directory, "-p", a.pattern, *(["-v"] if a.verbose else [])], timeout=a.timeout) except subprocess.TimeoutExpired: # Inherited stdout/stderr have already emitted any partial test output. diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py index 6cf2d9d310..0e28bfdbd4 100644 --- a/tests/test_run_semantic_tests.py +++ b/tests/test_run_semantic_tests.py @@ -39,12 +39,31 @@ def run(*argv): return code, out.getvalue() -def cli(*argv): +def cli(*argv, env=None): return subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "run_semantic_tests.py"), *argv], - capture_output=True, text=True, timeout=15) + capture_output=True, text=True, timeout=15, env=env) class RunnerTest(unittest.TestCase): + def test_child_workers_ignore_host_pythonpath(self): + with tempfile.TemporaryDirectory() as tmp: + poison = os.path.join(tmp, "host_injected.py") + with open(poison, "w", encoding="utf-8") as f: + f.write("VALUE = True\n") + suite_dir = os.path.join(tmp, "suite") + os.mkdir(suite_dir) + suite(suite_dir, {"test_isolated.py": + "import unittest\n" + "try:\n import host_injected\n" + "except ImportError:\n pass\n" + "else:\n raise AssertionError('host PYTHONPATH leaked into worker')\n" + "class T(unittest.TestCase):\n def test_ok(self): pass\n"}) + env = dict(os.environ, PYTHONPATH=tmp) + for jobs in (1, 2): + with self.subTest(jobs=jobs): + result = cli(suite_dir, "-j", str(jobs), env=env) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + def test_parallel_timeout_reports_partial_output_and_keeps_healthy_modules(self): with tempfile.TemporaryDirectory() as tmp: suite(tmp, {"helper.py": "X = 1\n", "test_hang.py": HANG, diff --git a/tests/test_semantic_mutants.py b/tests/test_semantic_mutants.py index 42ac9917aa..cb53d0780b 100644 --- a/tests/test_semantic_mutants.py +++ b/tests/test_semantic_mutants.py @@ -5,6 +5,7 @@ import tempfile import textwrap import unittest +from unittest.mock import patch ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) @@ -178,6 +179,25 @@ def test_file_with_no_tests_is_a_baseline_error(self): class RunTestEncoding(unittest.TestCase): + def test_worker_ignores_host_pythonpath(self): + with tempfile.TemporaryDirectory() as tmp: + poison_dir = os.path.join(tmp, "poison") + test_dir = os.path.join(tmp, "suite") + os.mkdir(poison_dir) + os.mkdir(test_dir) + with open(os.path.join(poison_dir, "host_injected.py"), "w", encoding="utf-8") as f: + f.write("VALUE = True\n") + test = os.path.join(test_dir, "test_isolated.py") + with open(test, "w", encoding="utf-8", newline="\n") as f: + f.write("import unittest\n" + "try:\n import host_injected\n" + "except ImportError:\n pass\n" + "else:\n raise AssertionError('host PYTHONPATH leaked into worker')\n" + "class T(unittest.TestCase):\n def test_ok(self): pass\n") + with patch.dict(os.environ, {"PYTHONPATH": poison_dir}): + ok, last = sm.run_test(test, os.path.join(ROOT, "tools"), 30) + self.assertTrue(ok, last) + def test_utf8_bytes_outside_windows_codepage_do_not_crash(self): with tempfile.TemporaryDirectory() as tmp: test = os.path.join(tmp, "test_utf8_out.py") diff --git a/tools/semantic_mutants.py b/tools/semantic_mutants.py index 2350e0b8b0..57063b2a37 100644 --- a/tools/semantic_mutants.py +++ b/tools/semantic_mutants.py @@ -184,15 +184,18 @@ def add(i: int, label: str, new: str) -> None: def run_test(test_file: str, tools_dir: str, timeout: int) -> tuple[bool, str]: """True when the test file passes against tools_dir.""" here = os.path.dirname(os.path.abspath(test_file)) - path = os.pathsep.join(filter(None, [here, os.path.join(ROOT, "tests", "semantic"), os.environ.get("PYTHONPATH")])) - env = dict(os.environ, LEONIDA_TOOLS_DIR=os.path.abspath(tools_dir), PYTHONDONTWRITEBYTECODE="1", - PYTHONPATH=path) + semantic_dir = os.path.join(ROOT, "tests", "semantic") + path = os.pathsep.join(dict.fromkeys([here, semantic_dir])) + env = dict(os.environ, LEONIDA_TOOLS_DIR=os.path.abspath(tools_dir), PYTHONDONTWRITEBYTECODE="1") # Through unittest, as tests/semantic/test_mutations.py does: a file with no `__main__` block runs nothing when - # started as a script, which would pass the baseline and let every mutant survive. + # started as a script, which would pass the baseline and let every mutant survive. The isolated bootstrap adds + # only the test directories needed for imports; host PYTHONPATH and user site-packages are excluded. module = os.path.splitext(os.path.basename(test_file))[0] + bootstrap = ("import os, sys, unittest; sys.path[:0] = sys.argv[1].split(os.pathsep); " + "unittest.main(module=sys.argv[2], argv=['unittest', *sys.argv[3:]])") try: - p = subprocess.run([sys.executable, "-m", "unittest", module], cwd=here, env=env, capture_output=True, - encoding="utf-8", errors="replace", timeout=timeout) + p = subprocess.run([sys.executable, "-I", "-c", bootstrap, path, module], cwd=here, env=env, + capture_output=True, encoding="utf-8", errors="replace", timeout=timeout) except subprocess.TimeoutExpired: return False, f"timed out after {timeout} s" if p.returncode == 5: # unittest's exit status when it found no tests (Python 3.12+)