diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 514e781330..7def5f36f6 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py @@ -18,7 +18,8 @@ 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. -The count of tests comes from unittest's own result object, not from its output: a module that writes a line shaped like unittest's summary to stderr - a nested runner, or an atexit handler that runs after unittest's own summary - cannot change it. +The test count and verdict come from unittest's result, not from printed summaries. A child exiting with status 0 +without a completed result, or after unittest reported failure, fails the run. `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. @@ -94,13 +95,10 @@ def _terminate_active_processes(): "import json, os, sys, unittest\n" "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" "result = program.result\n" - "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n" - " json.dump({'testsRun': result.testsRun}, handle)\n" - "if not result.wasSuccessful():\n" - " sys.exit(1)\n" - "elif result.testsRun == 0 and len(result.skipped) == 0:\n" - " sys.exit(5)\n" - "sys.exit(0)\n") + "code = 1 if not result.wasSuccessful() else 5 if not result.testsRun and not result.skipped else 0\n" + "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8', newline='\\n') as handle:\n" + " json.dump({'testsRun': result.testsRun, 'exitCode': code}, handle)\n" + "sys.exit(code)\n") def module_path(directory, module): @@ -139,14 +137,64 @@ def positive_seconds(value): return seconds -def read_count(path): - """The number of tests the child ran, as unittest's own result object reported it.""" +def read_result(path, process_code): + """Return the effective exit code, completed test count, and any diagnostic.""" try: with open(path, encoding="utf-8") as handle: - return int(json.load(handle)["testsRun"]) + result = json.load(handle) + count, test_code = result["testsRun"], result["exitCode"] + if type(count) is not int or count < 0 or type(test_code) is not int or test_code not in (0, 1, 5): + raise ValueError("invalid unittest result") except (OSError, ValueError, KeyError, TypeError): - # The child wrote no result: it did not finish, so no test is known to have run. - return 0 + if process_code == 0: + return 1, 0, "process exited without a unittest result" + return process_code, None, "" + if process_code in (0, 5) and process_code != test_code: + return 1, count, f"process exited with status {process_code} but unittest reported {test_code}" + return process_code, count, "" + + +def result_environment(scratch): + result_path = os.path.join(scratch, "count.json") + return result_path, dict(os.environ, LEONIDA_TEST_COUNT=result_path) + + +def run_discover(directory, pattern, verbose, timeout): + args = ["discover", "-s", directory, "-p", pattern, *(["-v"] if verbose else [])] + with tempfile.TemporaryDirectory() as scratch: + path, env = result_environment(scratch) + proc = subprocess.Popen([sys.executable, "-c", CHILD_PROGRAM, *args], env=env) + _register_process(proc) + start_time = time.monotonic() + try: + while True: + try: + code = proc.wait(timeout=0.2) + break + except subprocess.TimeoutExpired: + if timeout is not None and time.monotonic() - start_time >= timeout: + raise + except subprocess.TimeoutExpired: + _kill_process_tree(proc) + print(f"TIMED OUT after {timeout:g} s: unittest discover in {directory}", file=sys.stderr) + return 1 + except KeyboardInterrupt: + _kill_process_tree(proc) + try: + proc.wait(timeout=0.5) + except (subprocess.TimeoutExpired, OSError): + pass + print("interrupted", file=sys.stderr) + return 130 + except BaseException: + _kill_process_tree(proc) + raise + finally: + _unregister_process(proc) + code, _, diagnostic = read_result(path, code) + if diagnostic: + print(f"unittest discover in {directory}: {diagnostic}", file=sys.stderr) + return code def run_module(directory, module, verbose, timeout=None): @@ -157,8 +205,7 @@ def run_module(directory, module, verbose, timeout=None): target = module[:-len(".__init__")] if module.endswith(".__init__") else module cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] with tempfile.TemporaryDirectory() as scratch: - count_path = os.path.join(scratch, "count.json") - env = dict(os.environ, LEONIDA_TEST_COUNT=count_path) + result_path, env = result_environment(scratch) proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors="replace") _register_process(proc) @@ -181,13 +228,14 @@ def run_module(directory, module, verbose, timeout=None): raise finally: _unregister_process(proc) - count = read_count(count_path) + code, count, diagnostic = read_result(result_path, proc.returncode) out = stdout + stderr - # Discover imports every package initializer, but an empty one has no tests to run. It is included in the - # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. - if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr: + if diagnostic: + out += f"\n{diagnostic}\n" + # A package initializer that completed with no tests isn't a failed module. + if code == 5 and count == 0 and module.endswith(".__init__"): return 0, 0, out - return proc.returncode, count, out + return code, count or 0, out def main(argv=None): @@ -206,35 +254,7 @@ def main(argv=None): print(f"no {a.pattern} files in {directory}") return 1 if a.jobs <= 1: - cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory, - "-p", a.pattern, *(["-v"] if a.verbose else [])] - proc = subprocess.Popen(cmd) - _register_process(proc) - start_time = time.monotonic() - try: - while True: - try: - return proc.wait(timeout=0.2) - except subprocess.TimeoutExpired: - if a.timeout is not None and time.monotonic() - start_time >= a.timeout: - raise - except subprocess.TimeoutExpired: - _kill_process_tree(proc) - print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) - return 1 - except KeyboardInterrupt: - _kill_process_tree(proc) - try: - proc.wait(timeout=0.5) - except (subprocess.TimeoutExpired, OSError): - pass - print("interrupted", file=sys.stderr) - return 130 - except BaseException: - _kill_process_tree(proc) - raise - finally: - _unregister_process(proc) + return run_discover(directory, a.pattern, a.verbose, a.timeout) # Largest files first: they tend to run longest, and one started last would set the wall time alone. modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) start, total, failed = time.monotonic(), 0, [] diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py index 7fc75e3722..0e74040a30 100644 --- a/tests/test_run_semantic_tests.py +++ b/tests/test_run_semantic_tests.py @@ -109,6 +109,51 @@ def test_the_count_comes_from_the_result_object_not_from_a_late_summary(self): self.assertIn("1 files, 1 tests, 0 files failed", result.stdout) self.assertNotIn("no tests ran", result.stdout) + def test_a_successful_exit_without_a_unittest_result_fails_the_run(self): + # A module aborts the child before unittest can run the suite or report a result. + early_exit = "import os\nprint('before-exit', flush=True)\nos._exit(0)\n" + for jobs in (1, 2): + with self.subTest(jobs=jobs), tempfile.TemporaryDirectory() as tmp: + suite(tmp, {"helper.py": "X = 1\n", "test_abort.py": early_exit, "test_ok.py": PASS}) + result = cli(tmp, "-j", str(jobs)) + out = result.stdout + result.stderr + self.assertEqual(result.returncode, 1, out) + self.assertIn("before-exit", out) + self.assertIn("exited without a unittest result", out) + if jobs == 2: + self.assertIn("==== FAILED: test_abort", out) + self.assertIn("2 files, 2 tests, 1 files failed", out) + + def test_parallel_worker_exit_mid_test_fails_even_when_another_module_passes(self): + abort_mid_test = ( + "import os, unittest\n" + "class AbruptExit(unittest.TestCase):\n" + " def test_exits_after_starting(self):\n" + " print('mid-test-exit', flush=True)\n" + " os._exit(0)\n" + ) + with tempfile.TemporaryDirectory() as tmp: + suite(tmp, {"helper.py": "X = 1\n", "test_abort.py": abort_mid_test, "test_ok.py": PASS}) + result = cli(tmp, "-j", "2") + out = result.stdout + result.stderr + self.assertEqual(result.returncode, 1, out) + self.assertIn("mid-test-exit", out) + self.assertIn("==== FAILED: test_abort", out) + self.assertIn("exited without a unittest result", out) + self.assertIn("2 files, 2 tests, 1 files failed", out) + + def test_successful_process_exit_does_not_hide_a_failed_unittest_result(self): + # This module fails a test; its teardown of the process must not erase the result. + late_exit = "import atexit, os\natexit.register(lambda: os._exit(0))\n" + FAIL + for jobs in (1, 2): + with self.subTest(jobs=jobs), tempfile.TemporaryDirectory() as tmp: + suite(tmp, {"helper.py": "X = 1\n", "test_ok.py": PASS, "test_wrong.py": late_exit}) + result = cli(tmp, "-j", str(jobs)) + out = result.stdout + result.stderr + self.assertEqual(result.returncode, 1, out) + self.assertIn("boom-msg", out) + self.assertIn("exited with status 0 but unittest reported 1", out) + def test_serial_timeout_keeps_discover_output_and_names_the_suite(self): with tempfile.TemporaryDirectory() as tmp: suite(tmp, {"test_hang.py": HANG})