upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts/run_semantic_tests.py
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 18:48:12 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 18:48:12 -0500
commitfb2afdccc2314d7b5a59fac10e6d6df7f5df35ab (patch)
tree9e0b7e2e39b42823f148d135ce781e57fab52155 /scripts/run_semantic_tests.py
parent862890c893eb19eb39eb2fd95e7786e42ff4b18c (diff)
parent864337351bc11a250db77c2fcdd3ba6f1d0f455f (diff)
Merge main into RT-QUEUE18 (#403)
Merged on top of the merge made for #396 (main 507029d1e plus RT-QUEUE35, RT-ALLOC9 and RT-LIST139). No conflicts. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'scripts/run_semantic_tests.py')
-rw-r--r--scripts/run_semantic_tests.py68
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`
12because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an 12because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an
13error in serial and parallel runs. 13error in serial and parallel runs.
14 14
15It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each as 15It 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
17run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1, 17The 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,
18or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary 18or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary
19line, and exits 1 if a file fails, none is found, or no test ran. Standard library only. 19line, and exits 1 if a file fails, none is found, or no test ran. Standard library only.
20 20
21The 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.
23A timeout fails the run and reports any output already produced; other parallel modules keep running. 25A 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
26import argparse 28import argparse
27import concurrent.futures 29import concurrent.futures
28import fnmatch 30import fnmatch
31import json
29import locale 32import locale
30import math 33import math
31import os 34import os
32import re 35import re
33import subprocess 36import subprocess
34import sys 37import sys
38import tempfile
35import time 39import time
36 40
37MAX_TIMEOUT_SECONDS = 24 * 60 * 60 41MAX_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.
47CHILD_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
40def module_path(directory, module): 60def 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
96def 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
76def run_module(directory, module, verbose, timeout=None): 106def 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
100def main(argv=None): 134def main(argv=None):