diff options
| author | titoreinaldo <62819886+titoreinaldo@users.noreply.github.com> | 2026-11-27 23:41:32 +0000 |
|---|---|---|
| committer | titoreinaldo <62819886+titoreinaldo@users.noreply.github.com> | 2026-11-27 23:41:32 +0000 |
| commit | 13127c76dbd0bb1cd69a6310ae65e7e8abc514b7 (patch) | |
| tree | f82f1cda31a320a845583466ad765c0df0fbe2e4 /scripts | |
| parent | d44285197237cfe331684aa150fb9dec4b1d08b5 (diff) | |
Fail semantic runs without a completed unittest verdict
Retain process tracking and interrupt/timeout handling from main.
Diffstat (limited to 'scripts')
| -rw-r--r-- | scripts/run_semantic_tests.py | 118 |
1 files changed, 69 insertions, 49 deletions
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 514e78133..7def5f36f 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py | |||
| @@ -18,7 +18,8 @@ The files can run side by side because each one writes only into its own tempora | |||
| 18 | or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary | 18 | or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary |
| 19 | line, and exits 1 if a file fails, none is found, or no test ran. Standard library only. | 19 | line, and exits 1 if a file fails, none is found, or no test ran. Standard library only. |
| 20 | 20 | ||
| 21 | 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. | 21 | The test count and verdict come from unittest's result, not from printed summaries. A child exiting with status 0 |
| 22 | without a completed result, or after unittest reported failure, fails the run. | ||
| 22 | 23 | ||
| 23 | `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with | 24 | `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with |
| 24 | `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. | 25 | `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. |
| @@ -94,13 +95,10 @@ CHILD_PROGRAM = ( | |||
| 94 | "import json, os, sys, unittest\n" | 95 | "import json, os, sys, unittest\n" |
| 95 | "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" | 96 | "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" |
| 96 | "result = program.result\n" | 97 | "result = program.result\n" |
| 97 | "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n" | 98 | "code = 1 if not result.wasSuccessful() else 5 if not result.testsRun and not result.skipped else 0\n" |
| 98 | " json.dump({'testsRun': result.testsRun}, handle)\n" | 99 | "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8', newline='\\n') as handle:\n" |
| 99 | "if not result.wasSuccessful():\n" | 100 | " json.dump({'testsRun': result.testsRun, 'exitCode': code}, handle)\n" |
| 100 | " sys.exit(1)\n" | 101 | "sys.exit(code)\n") |
| 101 | "elif result.testsRun == 0 and len(result.skipped) == 0:\n" | ||
| 102 | " sys.exit(5)\n" | ||
| 103 | "sys.exit(0)\n") | ||
| 104 | 102 | ||
| 105 | 103 | ||
| 106 | def module_path(directory, module): | 104 | def module_path(directory, module): |
| @@ -139,14 +137,64 @@ def positive_seconds(value): | |||
| 139 | return seconds | 137 | return seconds |
| 140 | 138 | ||
| 141 | 139 | ||
| 142 | def read_count(path): | 140 | def read_result(path, process_code): |
| 143 | """The number of tests the child ran, as unittest's own result object reported it.""" | 141 | """Return the effective exit code, completed test count, and any diagnostic.""" |
| 144 | try: | 142 | try: |
| 145 | with open(path, encoding="utf-8") as handle: | 143 | with open(path, encoding="utf-8") as handle: |
| 146 | return int(json.load(handle)["testsRun"]) | 144 | result = json.load(handle) |
| 145 | count, test_code = result["testsRun"], result["exitCode"] | ||
| 146 | if type(count) is not int or count < 0 or type(test_code) is not int or test_code not in (0, 1, 5): | ||
| 147 | raise ValueError("invalid unittest result") | ||
| 147 | except (OSError, ValueError, KeyError, TypeError): | 148 | except (OSError, ValueError, KeyError, TypeError): |
| 148 | # The child wrote no result: it did not finish, so no test is known to have run. | 149 | if process_code == 0: |
| 149 | return 0 | 150 | return 1, 0, "process exited without a unittest result" |
| 151 | return process_code, None, "" | ||
| 152 | if process_code in (0, 5) and process_code != test_code: | ||
| 153 | return 1, count, f"process exited with status {process_code} but unittest reported {test_code}" | ||
| 154 | return process_code, count, "" | ||
| 155 | |||
| 156 | |||
| 157 | def result_environment(scratch): | ||
| 158 | result_path = os.path.join(scratch, "count.json") | ||
| 159 | return result_path, dict(os.environ, LEONIDA_TEST_COUNT=result_path) | ||
| 160 | |||
| 161 | |||
| 162 | def run_discover(directory, pattern, verbose, timeout): | ||
| 163 | args = ["discover", "-s", directory, "-p", pattern, *(["-v"] if verbose else [])] | ||
| 164 | with tempfile.TemporaryDirectory() as scratch: | ||
| 165 | path, env = result_environment(scratch) | ||
| 166 | proc = subprocess.Popen([sys.executable, "-c", CHILD_PROGRAM, *args], env=env) | ||
| 167 | _register_process(proc) | ||
| 168 | start_time = time.monotonic() | ||
| 169 | try: | ||
| 170 | while True: | ||
| 171 | try: | ||
| 172 | code = proc.wait(timeout=0.2) | ||
| 173 | break | ||
| 174 | except subprocess.TimeoutExpired: | ||
| 175 | if timeout is not None and time.monotonic() - start_time >= timeout: | ||
| 176 | raise | ||
| 177 | except subprocess.TimeoutExpired: | ||
| 178 | _kill_process_tree(proc) | ||
| 179 | print(f"TIMED OUT after {timeout:g} s: unittest discover in {directory}", file=sys.stderr) | ||
| 180 | return 1 | ||
| 181 | except KeyboardInterrupt: | ||
| 182 | _kill_process_tree(proc) | ||
| 183 | try: | ||
| 184 | proc.wait(timeout=0.5) | ||
| 185 | except (subprocess.TimeoutExpired, OSError): | ||
| 186 | pass | ||
| 187 | print("interrupted", file=sys.stderr) | ||
| 188 | return 130 | ||
| 189 | except BaseException: | ||
| 190 | _kill_process_tree(proc) | ||
| 191 | raise | ||
| 192 | finally: | ||
| 193 | _unregister_process(proc) | ||
| 194 | code, _, diagnostic = read_result(path, code) | ||
| 195 | if diagnostic: | ||
| 196 | print(f"unittest discover in {directory}: {diagnostic}", file=sys.stderr) | ||
| 197 | return code | ||
| 150 | 198 | ||
| 151 | 199 | ||
| 152 | def run_module(directory, module, verbose, timeout=None): | 200 | def run_module(directory, module, verbose, timeout=None): |
| @@ -157,8 +205,7 @@ def run_module(directory, module, verbose, timeout=None): | |||
| 157 | target = module[:-len(".__init__")] if module.endswith(".__init__") else module | 205 | target = module[:-len(".__init__")] if module.endswith(".__init__") else module |
| 158 | cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] | 206 | cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] |
| 159 | with tempfile.TemporaryDirectory() as scratch: | 207 | with tempfile.TemporaryDirectory() as scratch: |
| 160 | count_path = os.path.join(scratch, "count.json") | 208 | result_path, env = result_environment(scratch) |
| 161 | env = dict(os.environ, LEONIDA_TEST_COUNT=count_path) | ||
| 162 | proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, | 209 | proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 163 | text=True, errors="replace") | 210 | text=True, errors="replace") |
| 164 | _register_process(proc) | 211 | _register_process(proc) |
| @@ -181,13 +228,14 @@ def run_module(directory, module, verbose, timeout=None): | |||
| 181 | raise | 228 | raise |
| 182 | finally: | 229 | finally: |
| 183 | _unregister_process(proc) | 230 | _unregister_process(proc) |
| 184 | count = read_count(count_path) | 231 | code, count, diagnostic = read_result(result_path, proc.returncode) |
| 185 | out = stdout + stderr | 232 | out = stdout + stderr |
| 186 | # Discover imports every package initializer, but an empty one has no tests to run. It is included in the | 233 | if diagnostic: |
| 187 | # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. | 234 | out += f"\n{diagnostic}\n" |
| 188 | if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr: | 235 | # A package initializer that completed with no tests isn't a failed module. |
| 236 | if code == 5 and count == 0 and module.endswith(".__init__"): | ||
| 189 | return 0, 0, out | 237 | return 0, 0, out |
| 190 | return proc.returncode, count, out | 238 | return code, count or 0, out |
| 191 | 239 | ||
| 192 | 240 | ||
| 193 | def main(argv=None): | 241 | def main(argv=None): |
| @@ -206,35 +254,7 @@ def main(argv=None): | |||
| 206 | print(f"no {a.pattern} files in {directory}") | 254 | print(f"no {a.pattern} files in {directory}") |
| 207 | return 1 | 255 | return 1 |
| 208 | if a.jobs <= 1: | 256 | if a.jobs <= 1: |
| 209 | cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory, | 257 | return run_discover(directory, a.pattern, a.verbose, a.timeout) |
| 210 | "-p", a.pattern, *(["-v"] if a.verbose else [])] | ||
| 211 | proc = subprocess.Popen(cmd) | ||
| 212 | _register_process(proc) | ||
| 213 | start_time = time.monotonic() | ||
| 214 | try: | ||
| 215 | while True: | ||
| 216 | try: | ||
| 217 | return proc.wait(timeout=0.2) | ||
| 218 | except subprocess.TimeoutExpired: | ||
| 219 | if a.timeout is not None and time.monotonic() - start_time >= a.timeout: | ||
| 220 | raise | ||
| 221 | except subprocess.TimeoutExpired: | ||
| 222 | _kill_process_tree(proc) | ||
| 223 | print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) | ||
| 224 | return 1 | ||
| 225 | except KeyboardInterrupt: | ||
| 226 | _kill_process_tree(proc) | ||
| 227 | try: | ||
| 228 | proc.wait(timeout=0.5) | ||
| 229 | except (subprocess.TimeoutExpired, OSError): | ||
| 230 | pass | ||
| 231 | print("interrupted", file=sys.stderr) | ||
| 232 | return 130 | ||
| 233 | except BaseException: | ||
| 234 | _kill_process_tree(proc) | ||
| 235 | raise | ||
| 236 | finally: | ||
| 237 | _unregister_process(proc) | ||
| 238 | # Largest files first: they tend to run longest, and one started last would set the wall time alone. | 258 | # Largest files first: they tend to run longest, and one started last would set the wall time alone. |
| 239 | modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) | 259 | modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) |
| 240 | start, total, failed = time.monotonic(), 0, [] | 260 | start, total, failed = time.monotonic(), 0, [] |