mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:18:37 +00:00
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)
This commit is contained in:
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@ -191,7 +191,7 @@ jobs:
|
||||
- name: Translator semantic tests
|
||||
env:
|
||||
LEONIDA_REQUIRE_SPIRV_TOOLS: ${{ runner.os == 'Linux' && '1' || '0' }}
|
||||
run: python -m unittest discover -s tests/semantic -v
|
||||
run: python -I scripts/run_semantic_tests.py tests/semantic -v
|
||||
|
||||
# The Python suites on an Apple Silicon Mac: the standard-library loop of the check job, the translator semantic
|
||||
# tests and the pytest files of the translator-tests job, with Homebrew's llvm-mc and SPIRV-Tools. macos-26, not
|
||||
|
||||
@ -64,7 +64,7 @@ These need no game files and run in seconds:
|
||||
```powershell
|
||||
python -m compileall -q make_game.py tools tests
|
||||
python -I make_game.py --help
|
||||
python -m unittest discover -s tests/semantic -v # translator regression suite; no LLVM, SPIR-V tools or GPU needed
|
||||
python -I scripts/run_semantic_tests.py tests/semantic # translator regression suite, one file per core; no LLVM, SPIR-V tools or GPU needed
|
||||
python -I tests/test_<name>.py # standalone standard-library unit test
|
||||
node --test tests/test_viewer_streaming.cjs # viewer streaming; needs Node 22+
|
||||
dotnet build tools/rpf9dump/rpf9dump.csproj -c Release
|
||||
|
||||
@ -54,5 +54,5 @@ methods are still open.
|
||||
A new test gets its expected values in the comment at its top and a check in `check.py`.
|
||||
[docs/testing.md](docs/testing.md) covers setup per OS, including native Windows options, and known problems.
|
||||
- Say what you tested and on which GPU in the pull request.
|
||||
- Run the translator tests with `python -m unittest discover -s tests/semantic -v` (see `tests/semantic/README.md`). A new
|
||||
- Run the translator tests with `python -I scripts/run_semantic_tests.py tests/semantic` (see `tests/semantic/README.md`). A new
|
||||
translator rule should come with a small hand-written `.asm` fixture and its expected output words.
|
||||
|
||||
82
scripts/run_semantic_tests.py
Normal file
82
scripts/run_semantic_tests.py
Normal file
@ -0,0 +1,82 @@
|
||||
r"""Run the translator regression suite (tests/semantic) one process per test file, several files at a time.
|
||||
|
||||
python -I scripts/run_semantic_tests.py tests/semantic # one file per core
|
||||
python -I scripts/run_semantic_tests.py tests/semantic -j 4 # four at a time
|
||||
python -I scripts/run_semantic_tests.py tests/semantic -v # also print the output of the files that pass
|
||||
|
||||
It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py`, and packages below it), each as
|
||||
`python -m unittest <module>` from that folder, so a file sees the same import path as under discover. 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,
|
||||
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 or none is found. Standard library only.
|
||||
"""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import fnmatch
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
def test_modules(directory):
|
||||
"""Dotted names of the test modules unittest discover finds under `directory` (it enters packages only)."""
|
||||
names = []
|
||||
for base, dirs, files in os.walk(directory):
|
||||
dirs[:] = sorted(d for d in dirs if os.path.isfile(os.path.join(base, d, "__init__.py")))
|
||||
prefix = os.path.relpath(base, directory).replace(os.sep, ".")
|
||||
for name in sorted(files):
|
||||
if fnmatch.fnmatchcase(name, "test*.py"):
|
||||
names.append(name[:-3] if prefix == "." else f"{prefix}.{name[:-3]}")
|
||||
return names
|
||||
|
||||
|
||||
def run_module(directory, module, verbose):
|
||||
"""(return code, tests run, output) of `python -m unittest <module>` run from `directory`."""
|
||||
cmd = [sys.executable, "-m", "unittest", *(["-v"] if verbose else []), module]
|
||||
p = subprocess.run(cmd, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
|
||||
errors="replace")
|
||||
ran = re.search(r"^Ran (\d+) tests? in", p.stdout, re.M)
|
||||
return p.returncode, int(ran.group(1)) if ran else 0, p.stdout
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument("directory", help="the suite's folder, tests/semantic")
|
||||
ap.add_argument("-j", "--jobs", type=int, default=os.cpu_count() or 1, help="files at a time (default: cores)")
|
||||
ap.add_argument("-v", "--verbose", action="store_true", help="unittest -v, and print passing files' output")
|
||||
a = ap.parse_args(argv)
|
||||
directory = os.path.abspath(a.directory)
|
||||
if a.jobs <= 1:
|
||||
return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory,
|
||||
*(["-v"] if a.verbose else [])])
|
||||
modules = test_modules(directory)
|
||||
if not modules:
|
||||
print(f"no test*.py files in {directory}")
|
||||
return 1
|
||||
# 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(os.path.join(directory, *m.split(".")) + ".py"))
|
||||
start, total, failed = time.monotonic(), 0, []
|
||||
with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool:
|
||||
jobs = {pool.submit(run_module, directory, m, a.verbose): m for m in modules}
|
||||
for job in concurrent.futures.as_completed(jobs):
|
||||
code, ran, out = job.result()
|
||||
total += ran
|
||||
if code:
|
||||
failed.append(jobs[job])
|
||||
print(f"==== FAILED: {jobs[job]}\n{out}", flush=True)
|
||||
elif a.verbose:
|
||||
print(f"==== {jobs[job]}\n{out}", flush=True)
|
||||
took = time.monotonic() - start
|
||||
summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs"
|
||||
print(summary + (": " + ", ".join(sorted(failed)) if failed else ""))
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
|
||||
sys.stdout.reconfigure(errors="replace")
|
||||
except (AttributeError, ValueError, OSError):
|
||||
pass
|
||||
sys.exit(main())
|
||||
@ -2,7 +2,13 @@
|
||||
|
||||
Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files.
|
||||
|
||||
python -m unittest discover -s tests/semantic -v
|
||||
python -I scripts/run_semantic_tests.py tests/semantic # one file per core: 26 s instead of 253 s on 16 cores
|
||||
python -m unittest discover -s tests/semantic -v # the same tests, one file after another
|
||||
|
||||
The runner starts `python -m unittest <file>` for each file, several at a time, prints the output of the files that
|
||||
fail and one summary line; `-j N` sets how many run at once (`-j 1` is the discover command above) and `-v` prints
|
||||
every file's output. Files run side by side, so a test writes only into its own temporary folder (`tempfile`), never
|
||||
to a fixed path, and does not rely on another file having run first.
|
||||
|
||||
Every file here must call `tools/rdna2spirv.py` (directly, through `support.py`, or by running the tool) and assert
|
||||
on what it emitted. A test that reimplements the instruction in Python passes whatever the translator does, so it is
|
||||
|
||||
@ -68,7 +68,9 @@ def ci_rules(root):
|
||||
# The check loop and the translator list share this one find expression.
|
||||
pruned, loop_glob = find(r"-path\s+'([^']+)'\s+-prune\s+-o\s+-type\s+f\s+-name\s+'([^']+)'",
|
||||
"the tests/test_*.py scan")
|
||||
(semantic,) = find(r"python\s+-m\s+unittest\s+discover\s+-s\s+(\S+)", "unittest discover -s")
|
||||
# scripts/run_semantic_tests.py runs the files unittest discover would find, one process each
|
||||
(semantic,) = find(r"(?:python\s+-m\s+unittest\s+discover\s+-s|python\s+-I\s+scripts/run_semantic_tests\.py)\s+(\S+)",
|
||||
"the semantic suite's folder")
|
||||
(viewer,) = find(r"node\s+--test\s+(\S+)", "node --test")
|
||||
if re.search(r"unittest\s+discover[^\n]*-p\s", text):
|
||||
raise AssertionError("unittest discover now passes -p; this test assumes its default 'test*.py' pattern")
|
||||
|
||||
82
tests/test_run_semantic_tests.py
Normal file
82
tests/test_run_semantic_tests.py
Normal file
@ -0,0 +1,82 @@
|
||||
"""scripts/run_semantic_tests.py on a throwaway suite: it finds what unittest discover finds, and a failing, crashing
|
||||
or unimportable file always makes it exit 1 with that file named, in parallel and with -j 1.
|
||||
|
||||
python -I tests/test_run_semantic_tests.py
|
||||
"""
|
||||
import contextlib
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(ROOT, "scripts"))
|
||||
|
||||
import run_semantic_tests as r # noqa: E402
|
||||
|
||||
PASS = "import unittest\nimport helper\nclass T(unittest.TestCase):\n def test_a(self): self.assertEqual(helper.X, 1)\n" \
|
||||
" def test_b(self): pass\n"
|
||||
FAIL = "import unittest\nclass T(unittest.TestCase):\n def test_a(self): self.assertEqual(1, 2, 'boom-msg')\n"
|
||||
BROKEN = "import no_such_module_anywhere\n"
|
||||
|
||||
|
||||
def suite(tmp, files):
|
||||
for rel, text in files.items():
|
||||
path = os.path.join(tmp, *rel.split("/"))
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
return tmp
|
||||
|
||||
|
||||
def run(*argv):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
|
||||
code = r.main(list(argv))
|
||||
return code, out.getvalue()
|
||||
|
||||
|
||||
class RunnerTest(unittest.TestCase):
|
||||
def test_finds_what_discover_finds(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
suite(tmp, {"test_one.py": "", "helper.py": "", "pkg/__init__.py": "", "pkg/test_two.py": "",
|
||||
"plain_dir/test_three.py": "", "testx.py": ""})
|
||||
# discover enters packages only, and its pattern is test*.py
|
||||
self.assertEqual(r.test_modules(tmp), ["test_one", "testx", "pkg.test_two"])
|
||||
|
||||
def test_all_pass(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
suite(tmp, {"helper.py": "X = 1\n", "test_p1.py": PASS, "test_p2.py": PASS})
|
||||
code, out = run(tmp, "-j", "2")
|
||||
self.assertEqual(code, 0, out)
|
||||
self.assertIn("2 files, 4 tests, 0 files failed", out)
|
||||
|
||||
def test_a_failure_or_import_error_is_reported_and_fails_the_run(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
suite(tmp, {"helper.py": "X = 1\n", "test_p.py": PASS, "test_f.py": FAIL, "test_b.py": BROKEN})
|
||||
code, out = run(tmp, "-j", "3")
|
||||
self.assertEqual(code, 1, out)
|
||||
self.assertIn("==== FAILED: test_f", out)
|
||||
self.assertIn("boom-msg", out) # the failing file's own output is shown
|
||||
self.assertIn("==== FAILED: test_b", out)
|
||||
self.assertIn("2 files failed", out)
|
||||
self.assertTrue(out.rstrip().endswith("test_b, test_f"), out)
|
||||
|
||||
def test_one_job_runs_discover_and_keeps_its_exit_code(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
suite(tmp, {"helper.py": "X = 1\n", "test_p.py": PASS, "test_f.py": FAIL})
|
||||
self.assertEqual(run(tmp, "-j", "1")[0], 1)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
suite(tmp, {"helper.py": "X = 1\n", "test_p.py": PASS})
|
||||
self.assertEqual(run(tmp, "-j", "1")[0], 0)
|
||||
|
||||
def test_an_empty_suite_fails(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
code, out = run(tmp, "-j", "2")
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("no test*.py files", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user