diff options
| author | DadaCap <167002618+DadaCap@users.noreply.github.com> | 2026-11-24 21:09:02 +0100 |
|---|---|---|
| committer | DadaCap <167002618+DadaCap@users.noreply.github.com> | 2026-11-24 21:09:02 +0100 |
| commit | bc245e5046124941bbdc7bb5c3bd7c739da4e03e (patch) | |
| tree | 5b780fbcbc1dd131ee635980dfe3e996ac72928f /scripts/run_semantic_tests.py | |
| parent | 30450e0e96e1df700bbfa9505433c9b9940e8694 (diff) | |
| parent | 58be9cdf8df9a31bc7f6c068991f1aed381f7f4d (diff) | |
Merge remote-tracking branch 'origin/main' into vcc-tuple-resync
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'scripts/run_semantic_tests.py')
| -rw-r--r-- | scripts/run_semantic_tests.py | 68 |
1 files changed, 51 insertions, 17 deletions
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index c364bb35d..03e0ddab4 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py | |||
| @@ -12,12 +12,14 @@ the pattern matches their basenames, not directory paths. Package `__init__.py` | |||
| 12 | because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an | 12 | because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an |
| 13 | error in serial and parallel runs. | 13 | error in serial and parallel runs. |
| 14 | 14 | ||
| 15 | It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each as | 15 | It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each in its own process from that folder, so a file sees the same import path as under discover. |
| 16 | `python -m unittest <module>` from that folder, so a file sees the same import path as under discover. The files can | 16 | |
| 17 | run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1, | 17 | 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, |
| 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. | ||
| 22 | |||
| 21 | `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with | 23 | `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with |
| 22 | `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. | 24 | `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. |
| 23 | A timeout fails the run and reports any output already produced; other parallel modules keep running. | 25 | A timeout fails the run and reports any output already produced; other parallel modules keep running. |
| @@ -26,16 +28,34 @@ The default has no time limit. This stops the direct test subprocess, not any de | |||
| 26 | import argparse | 28 | import argparse |
| 27 | import concurrent.futures | 29 | import concurrent.futures |
| 28 | import fnmatch | 30 | import fnmatch |
| 31 | import json | ||
| 29 | import locale | 32 | import locale |
| 30 | import math | 33 | import math |
| 31 | import os | 34 | import os |
| 32 | import re | 35 | import re |
| 33 | import subprocess | 36 | import subprocess |
| 34 | import sys | 37 | import sys |
| 38 | import tempfile | ||
| 35 | import time | 39 | import time |
| 36 | 40 | ||
| 37 | MAX_TIMEOUT_SECONDS = 24 * 60 * 60 | 41 | MAX_TIMEOUT_SECONDS = 24 * 60 * 60 |
| 38 | 42 | ||
| 43 | # The child runs the module through unittest's own program and writes the result to a file, so the count of tests | ||
| 44 | # comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1 | ||
| 45 | # when a test failed, 5 when nothing ran at all, 0 otherwise. The module is left unset, as `python -m unittest` leaves it, so | ||
| 46 | # the name is imported and not looked up as an attribute of the program itself. | ||
| 47 | CHILD_PROGRAM = ( | ||
| 48 | "import json, os, sys, unittest\n" | ||
| 49 | "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" | ||
| 50 | "result = program.result\n" | ||
| 51 | "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n" | ||
| 52 | " json.dump({'testsRun': result.testsRun}, handle)\n" | ||
| 53 | "if not result.wasSuccessful():\n" | ||
| 54 | " sys.exit(1)\n" | ||
| 55 | "elif result.testsRun == 0 and len(result.skipped) == 0:\n" | ||
| 56 | " sys.exit(5)\n" | ||
| 57 | "sys.exit(0)\n") | ||
| 58 | |||
| 39 | 59 | ||
| 40 | def module_path(directory, module): | 60 | def module_path(directory, module): |
| 41 | """Source path of a dotted module name, including a package's `__init__.py`.""" | 61 | """Source path of a dotted module name, including a package's `__init__.py`.""" |
| @@ -73,28 +93,42 @@ def positive_seconds(value): | |||
| 73 | return seconds | 93 | return seconds |
| 74 | 94 | ||
| 75 | 95 | ||
| 96 | def read_count(path): | ||
| 97 | """The number of tests the child ran, as unittest's own result object reported it.""" | ||
| 98 | try: | ||
| 99 | with open(path, encoding="utf-8") as handle: | ||
| 100 | return int(json.load(handle)["testsRun"]) | ||
| 101 | except (OSError, ValueError, KeyError, TypeError): | ||
| 102 | # The child wrote no result: it did not finish, so no test is known to have run. | ||
| 103 | return 0 | ||
| 104 | |||
| 105 | |||
| 76 | def run_module(directory, module, verbose, timeout=None): | 106 | def run_module(directory, module, verbose, timeout=None): |
| 77 | """(return code, tests run, output) of `python -m unittest <target>` run from `directory`.""" | 107 | """(return code, tests run, output) of `python -m unittest <target>` run from `directory`.""" |
| 78 | # `python -m unittest pkg.__init__` imports pkg and then runs the same file again as pkg.__init__, so a | 108 | # `python -m unittest pkg.__init__` imports pkg and then runs the same file again as pkg.__init__, so a |
| 79 | # registration in the initializer happens twice. Running the package itself imports it once; module_path() is | 109 | # registration in the initializer happens twice. Running the package itself imports it once; module_path() is |
| 80 | # still the initializer's path, so the jobs stay sorted by the file they run. | 110 | # still the initializer's path, so the jobs stay sorted by the file they run. |
| 81 | target = module[:-len(".__init__")] if module.endswith(".__init__") else module | 111 | target = module[:-len(".__init__")] if module.endswith(".__init__") else module |
| 82 | cmd = [sys.executable, "-m", "unittest", *(["-v"] if verbose else []), target] | 112 | cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] |
| 83 | try: | 113 | with tempfile.TemporaryDirectory() as scratch: |
| 84 | p = subprocess.run(cmd, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, | 114 | count_path = os.path.join(scratch, "count.json") |
| 85 | errors="replace", timeout=timeout) | 115 | env = dict(os.environ, LEONIDA_TEST_COUNT=count_path) |
| 86 | except subprocess.TimeoutExpired as exc: | 116 | try: |
| 87 | out = exc.stdout or "" | 117 | p = subprocess.run(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 88 | if isinstance(out, bytes): # TimeoutExpired retains bytes even when text=True. | 118 | text=True, errors="replace", timeout=timeout) |
| 89 | out = out.decode(locale.getpreferredencoding(False), errors="replace") | 119 | except subprocess.TimeoutExpired as exc: |
| 90 | return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" | 120 | # TimeoutExpired retains bytes even when text=True. |
| 91 | ran = re.search(r"^Ran (\d+) tests? in", p.stdout, re.M) | 121 | parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) |
| 92 | count = int(ran.group(1)) if ran else 0 | 122 | else chunk for chunk in (exc.stdout, exc.stderr) if chunk] |
| 123 | out = "".join(parts) | ||
| 124 | return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" | ||
| 125 | count = read_count(count_path) | ||
| 126 | out = p.stdout + p.stderr | ||
| 93 | # Discover imports every package initializer, but an empty one has no tests to run. It is included in the | 127 | # Discover imports every package initializer, but an empty one has no tests to run. It is included in the |
| 94 | # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. | 128 | # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. |
| 95 | if p.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in p.stdout: | 129 | if p.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in p.stderr: |
| 96 | return 0, 0, p.stdout | 130 | return 0, 0, out |
| 97 | return p.returncode, count, p.stdout | 131 | return p.returncode, count, out |
| 98 | 132 | ||
| 99 | 133 | ||
| 100 | def main(argv=None): | 134 | def main(argv=None): |