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:
authorAwkGrep256 <samsepi0l1111@proton.me>2026-11-23 17:10:57 +0300
committerGitHub <noreply@github.com>2026-11-23 08:10:57 -0600
commitc2cc4bfe7f2e037c424cfcf3ad236a417df7b1b5 (patch)
tree803e8b244156708d4a0e334726d4b157e717ed2e /scripts/run_semantic_tests.py
parent9bde996b6bd3811c903d0262607a05fc0bee4c3d (diff)
scripts/run_semantic_tests.py: run tests/semantic one process per file, in parallel (253 s -> 26 s) (#4961)
Squash-merged after review of PR #4961 - scripts/run_semantic_tests.py: run tests/semantic one process per file, in parallel (253 s -> 26 s)
Diffstat (limited to 'scripts/run_semantic_tests.py')
-rw-r--r--scripts/run_semantic_tests.py82
1 files changed, 82 insertions, 0 deletions
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py
new file mode 100644
index 000000000..78cfde01a
--- /dev/null
+++ b/scripts/run_semantic_tests.py
@@ -0,0 +1,82 @@
1r"""Run the translator regression suite (tests/semantic) one process per test file, several files at a time.
2
3 python -I scripts/run_semantic_tests.py tests/semantic # one file per core
4 python -I scripts/run_semantic_tests.py tests/semantic -j 4 # four at a time
5 python -I scripts/run_semantic_tests.py tests/semantic -v # also print the output of the files that pass
6
7It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py`, and packages below it), each as
8`python -m unittest <module>` from that folder, so a file sees the same import path as under discover. The files can
9run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1,
10or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary
11line, and exits 1 if a file fails or none is found. Standard library only.
12"""
13import argparse
14import concurrent.futures
15import fnmatch
16import os
17import re
18import subprocess
19import sys
20import time
21
22
23def test_modules(directory):
24 """Dotted names of the test modules unittest discover finds under `directory` (it enters packages only)."""
25 names = []
26 for base, dirs, files in os.walk(directory):
27 dirs[:] = sorted(d for d in dirs if os.path.isfile(os.path.join(base, d, "__init__.py")))
28 prefix = os.path.relpath(base, directory).replace(os.sep, ".")
29 for name in sorted(files):
30 if fnmatch.fnmatchcase(name, "test*.py"):
31 names.append(name[:-3] if prefix == "." else f"{prefix}.{name[:-3]}")
32 return names
33
34
35def run_module(directory, module, verbose):
36 """(return code, tests run, output) of `python -m unittest <module>` run from `directory`."""
37 cmd = [sys.executable, "-m", "unittest", *(["-v"] if verbose else []), module]
38 p = subprocess.run(cmd, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
39 errors="replace")
40 ran = re.search(r"^Ran (\d+) tests? in", p.stdout, re.M)
41 return p.returncode, int(ran.group(1)) if ran else 0, p.stdout
42
43
44def main(argv=None):
45 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
46 ap.add_argument("directory", help="the suite's folder, tests/semantic")
47 ap.add_argument("-j", "--jobs", type=int, default=os.cpu_count() or 1, help="files at a time (default: cores)")
48 ap.add_argument("-v", "--verbose", action="store_true", help="unittest -v, and print passing files' output")
49 a = ap.parse_args(argv)
50 directory = os.path.abspath(a.directory)
51 if a.jobs <= 1:
52 return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory,
53 *(["-v"] if a.verbose else [])])
54 modules = test_modules(directory)
55 if not modules:
56 print(f"no test*.py files in {directory}")
57 return 1
58 # Largest files first: they tend to run longest, and one started last would set the wall time alone.
59 modules.sort(key=lambda m: -os.path.getsize(os.path.join(directory, *m.split(".")) + ".py"))
60 start, total, failed = time.monotonic(), 0, []
61 with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool:
62 jobs = {pool.submit(run_module, directory, m, a.verbose): m for m in modules}
63 for job in concurrent.futures.as_completed(jobs):
64 code, ran, out = job.result()
65 total += ran
66 if code:
67 failed.append(jobs[job])
68 print(f"==== FAILED: {jobs[job]}\n{out}", flush=True)
69 elif a.verbose:
70 print(f"==== {jobs[job]}\n{out}", flush=True)
71 took = time.monotonic() - start
72 summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs"
73 print(summary + (": " + ", ".join(sorted(failed)) if failed else ""))
74 return 1 if failed else 0
75
76
77if __name__ == "__main__":
78 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
79 sys.stdout.reconfigure(errors="replace")
80 except (AttributeError, ValueError, OSError):
81 pass
82 sys.exit(main())