diff options
Diffstat (limited to 'scripts')
| -rw-r--r-- | scripts/build_runtime.ps1 | 4 | ||||
| -rw-r--r-- | scripts/check_no_game_data.py | 20 | ||||
| -rw-r--r-- | scripts/ci_expected_failures.py | 18 | ||||
| -rw-r--r-- | scripts/merge_check.py | 7 | ||||
| -rw-r--r-- | scripts/run_gpu_tests.py | 28 | ||||
| -rw-r--r-- | scripts/run_semantic_tests.py | 68 |
6 files changed, 109 insertions, 36 deletions
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 63acb7ce3..f24cc073f 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 | |||
| @@ -83,10 +83,10 @@ $build || exit /b 1 | |||
| 83 | } else { | 83 | } else { |
| 84 | # Keep this list in step with runtime\CMakeLists.txt. Optional parts that need a dependency are left out here: | 84 | # Keep this list in step with runtime\CMakeLists.txt. Optional parts that need a dependency are left out here: |
| 85 | # the GameInput shim (SDL3), so controllers go through the host's GameInput.dll, if any, as without the shim. | 85 | # the GameInput shim (SDL3), so controllers go through the host's GameInput.dll, if any, as without the shim. |
| 86 | Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3). Install CMake + Ninja or VS's CMake tools component to get it." | 86 | Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it." |
| 87 | $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" | 87 | $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" |
| 88 | $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } | 88 | $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } |
| 89 | $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } | 89 | $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } |
| 90 | $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" | 90 | $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" |
| 91 | $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } | 91 | $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } |
| 92 | $body = @" | 92 | $body = @" |
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py index a5b65e242..bccee5e68 100644 --- a/scripts/check_no_game_data.py +++ b/scripts/check_no_game_data.py | |||
| @@ -21,7 +21,8 @@ under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb | |||
| 21 | reported as archives that can't be checked. | 21 | reported as archives that can't be checked. |
| 22 | 22 | ||
| 23 | Prints one line per match, `<path>: <format>` (`<format> in <archive> (<member>)` for a match inside an archive), and | 23 | Prints one line per match, `<path>: <format>` (`<format> in <archive> (<member>)` for a match inside an archive), and |
| 24 | exits 1 if there is any. Standard library only, no game files. | 24 | exits 1 if there is any. It exits 2 when a file cannot be read or git cannot list the tracked files (outside a |
| 25 | repository, or git not installed). Standard library only, no game files. | ||
| 25 | """ | 26 | """ |
| 26 | import bz2 | 27 | import bz2 |
| 27 | import gzip | 28 | import gzip |
| @@ -257,6 +258,14 @@ def tracked_files(root): | |||
| 257 | return [os.path.join(root, p) for p in out.decode("utf-8", "surrogateescape").split("\0") if p] | 258 | return [os.path.join(root, p) for p in out.decode("utf-8", "surrogateescape").split("\0") if p] |
| 258 | 259 | ||
| 259 | 260 | ||
| 261 | def git_error(e): | ||
| 262 | """One line on why git could not list the files: the first line git printed, or the OS error.""" | ||
| 263 | if isinstance(e, subprocess.CalledProcessError): | ||
| 264 | lines = (e.stderr or b"").decode("utf-8", "replace").splitlines() | ||
| 265 | return next((line.strip() for line in lines if line.strip()), f"exit status {e.returncode}") | ||
| 266 | return e.strerror or str(e) | ||
| 267 | |||
| 268 | |||
| 260 | def check(paths, unreadable=None): | 269 | def check(paths, unreadable=None): |
| 261 | """[(path, format)] for every regular file in `paths` that starts like game data. | 270 | """[(path, format)] for every regular file in `paths` that starts like game data. |
| 262 | 271 | ||
| @@ -285,7 +294,14 @@ def display(path): | |||
| 285 | 294 | ||
| 286 | 295 | ||
| 287 | def main(argv): | 296 | def main(argv): |
| 288 | paths = argv or tracked_files(os.getcwd()) | 297 | if argv: |
| 298 | paths = argv | ||
| 299 | else: | ||
| 300 | try: | ||
| 301 | paths = tracked_files(os.getcwd()) | ||
| 302 | except (OSError, subprocess.CalledProcessError) as e: | ||
| 303 | print(f"check_no_game_data: cannot list the tracked files with git: {git_error(e)}", file=sys.stderr) | ||
| 304 | return 2 # not 1: that is the 'game data found' code | ||
| 289 | unreadable = [] | 305 | unreadable = [] |
| 290 | found = check(paths, unreadable) | 306 | found = check(paths, unreadable) |
| 291 | for path, name in found: | 307 | for path, name in found: |
diff --git a/scripts/ci_expected_failures.py b/scripts/ci_expected_failures.py index 8112dcf4b..f398020f7 100644 --- a/scripts/ci_expected_failures.py +++ b/scripts/ci_expected_failures.py | |||
| @@ -2,11 +2,13 @@ | |||
| 2 | 2 | ||
| 3 | python -I scripts/ci_expected_failures.py FAILED_LIST EXIT_STATUS [EXPECTED ...] | 3 | python -I scripts/ci_expected_failures.py FAILED_LIST EXIT_STATUS [EXPECTED ...] |
| 4 | 4 | ||
| 5 | FAILED_LIST is a file with one failed test name per line, EXIT_STATUS the test runner's exit status, and each | 5 | FAILED_LIST is a UTF-8 file with one failed test name per line and an optional BOM. |
| 6 | EXPECTED argument one or more whitespace-separated test names (so a workflow can pass one quoted list). Exits 1 when a | 6 | EXIT_STATUS is the test runner's exit status. Each EXPECTED argument is one or more whitespace-separated |
| 7 | test outside EXPECTED failed, the runner failed without naming a test, or the runner was terminated by a signal | 7 | test names, so a workflow can pass one quoted list. |
| 8 | (its failure list can be incomplete); 2 on a usage error. `--help` prints this text. An expected failure absent | 8 | |
| 9 | from a completed run gets a GitHub Actions notice so the list in the workflow can shrink. | 9 | Exits 1 when an unexpected test failed, the runner failed without naming a test, or a signal terminated the runner. |
| 10 | Exits 2 on a usage error. `--help` prints this text. An expected failure absent from a completed run gets a GitHub | ||
| 11 | Actions notice so the list in the workflow can shrink. | ||
| 10 | """ | 12 | """ |
| 11 | 13 | ||
| 12 | import sys | 14 | import sys |
| @@ -43,10 +45,10 @@ def main(argv: list[str]) -> int: | |||
| 43 | print(f"ci_expected_failures: EXIT_STATUS {argv[1]!r} is not an integer", file=sys.stderr) | 45 | print(f"ci_expected_failures: EXIT_STATUS {argv[1]!r} is not an integer", file=sys.stderr) |
| 44 | return 2 | 46 | return 2 |
| 45 | try: | 47 | try: |
| 46 | with open(argv[0], encoding="utf-8") as f: | 48 | with open(argv[0], encoding="utf-8-sig") as f: |
| 47 | failed = [line.strip() for line in f if line.strip()] | 49 | failed = [line.strip() for line in f if line.strip()] |
| 48 | except OSError as e: | 50 | except (OSError, UnicodeDecodeError) as e: |
| 49 | print(f"ci_expected_failures: {argv[0]}: {e.strerror or e}", file=sys.stderr) | 51 | print(f"ci_expected_failures: {argv[0]}: {getattr(e, 'strerror', None) or e}", file=sys.stderr) |
| 50 | return 2 | 52 | return 2 |
| 51 | expected = [name for arg in argv[2:] for name in arg.split()] | 53 | expected = [name for arg in argv[2:] for name in arg.split()] |
| 52 | code, lines = judge(failed, status, expected) | 54 | code, lines = judge(failed, status, expected) |
diff --git a/scripts/merge_check.py b/scripts/merge_check.py index c4cbdceca..81bb3368a 100644 --- a/scripts/merge_check.py +++ b/scripts/merge_check.py | |||
| @@ -42,7 +42,10 @@ class GitError(Exception): | |||
| 42 | 42 | ||
| 43 | 43 | ||
| 44 | def git(repo, *args, check=True): | 44 | def git(repo, *args, check=True): |
| 45 | r = subprocess.run(["git", "-C", repo, *args], capture_output=True) | 45 | try: |
| 46 | r = subprocess.run(["git", "-C", repo, *args], capture_output=True) | ||
| 47 | except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback | ||
| 48 | raise GitError(f"cannot run git: {e.strerror or e}") from None | ||
| 46 | # Decode without universal-newline translation: a bare CR inside a Git line is content. | 49 | # Decode without universal-newline translation: a bare CR inside a Git line is content. |
| 47 | r.stdout = r.stdout.decode("utf-8", "replace") | 50 | r.stdout = r.stdout.decode("utf-8", "replace") |
| 48 | r.stderr = r.stderr.decode("utf-8", "replace") | 51 | r.stderr = r.stderr.decode("utf-8", "replace") |
| @@ -64,7 +67,7 @@ def _merged_pr_number(subject): | |||
| 64 | def prior_merges(repo, main, numbers, depth): | 67 | def prior_merges(repo, main, numbers, depth): |
| 65 | out = git(repo, "log", main, "--first-parent", f"-n{depth}", "--format=%H%x09%s").stdout | 68 | out = git(repo, "log", main, "--first-parent", f"-n{depth}", "--format=%H%x09%s").stdout |
| 66 | hits = {number: [] for number in numbers} | 69 | hits = {number: [] for number in numbers} |
| 67 | for line in out.splitlines(): | 70 | for line in out.split("\n"): |
| 68 | sha, _, subject = line.partition("\t") | 71 | sha, _, subject = line.partition("\t") |
| 69 | number = _merged_pr_number(subject) | 72 | number = _merged_pr_number(subject) |
| 70 | if number in hits: | 73 | if number in hits: |
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index a075c876a..e8fce4277 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py | |||
| @@ -36,6 +36,7 @@ from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_ | |||
| 36 | from check import SIGNED_MIP_TEST, UINT_MIP_TEST | 36 | from check import SIGNED_MIP_TEST, UINT_MIP_TEST |
| 37 | from check import cbv_modulate_test | 37 | from check import cbv_modulate_test |
| 38 | from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT | 38 | from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT |
| 39 | from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations | ||
| 39 | from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan) | 40 | from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan) |
| 40 | from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py | 41 | from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py |
| 41 | from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 | 42 | from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 |
| @@ -149,8 +150,13 @@ def spirv_as(asm_text: str, out_spv: str, assembler: str = "spirv-as") -> None: | |||
| 149 | with open(out_spv, "wb") as f: | 150 | with open(out_spv, "wb") as f: |
| 150 | f.write(spv_bytes) | 151 | f.write(spv_bytes) |
| 151 | return | 152 | return |
| 152 | p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"], | 153 | try: |
| 153 | input=asm_text, capture_output=True, text=True) | 154 | p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"], |
| 155 | input=asm_text, capture_output=True, text=True) | ||
| 156 | except FileNotFoundError: | ||
| 157 | raise RuntimeError("spirv-as not found on PATH (use --assembler python to assemble with tools/spirv_asm.py)") from None | ||
| 158 | except OSError as exc: | ||
| 159 | raise RuntimeError(f"spirv-as could not be started: {exc.strerror or exc}") from None | ||
| 154 | if p.returncode != 0: | 160 | if p.returncode != 0: |
| 155 | raise RuntimeError(f"spirv-as failed for {out_spv}:\n{p.stderr}") | 161 | raise RuntimeError(f"spirv-as failed for {out_spv}:\n{p.stderr}") |
| 156 | 162 | ||
| @@ -258,6 +264,8 @@ def read_raw_u32(path: str) -> list[tuple[int, int, int, int]]: | |||
| 258 | return [struct.unpack_from("<4I", data, 16 * i) for i in range(n)] | 264 | return [struct.unpack_from("<4I", data, 16 * i) for i in range(n)] |
| 259 | 265 | ||
| 260 | 266 | ||
| 267 | # cs_div_fmas_f64_rt's operands a = 1 + 2^-30, c = -(1 + 2^-29) as s4..s7 (low word first). | ||
| 268 | DIV_FMAS_F64_SGPRS = "0x00400000,0x3ff00000,0x00800000,0xbff00000" | ||
| 261 | UNSUPPORTED = 77 # vk_harness: the device lacks a stage the test draws with (geometry or mesh shaders) | 269 | UNSUPPORTED = 77 # vk_harness: the device lacks a stage the test draws with (geometry or mesh shaders) |
| 262 | 270 | ||
| 263 | 271 | ||
| @@ -975,6 +983,10 @@ def run_suite(a, work: str) -> int: | |||
| 975 | if name in CLIP_CASES: | 983 | if name in CLIP_CASES: |
| 976 | detail = clip_test(a.build, spirv_dir, name) | 984 | detail = clip_test(a.build, spirv_dir, name) |
| 977 | results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact")) | 985 | results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact")) |
| 986 | elif name == "cs_w32_shift64": | ||
| 987 | detail = shift64_test(a.build, spirv_dir, cs_env) | ||
| 988 | results.append((name, None if isinstance(detail, Skip) else not detail, | ||
| 989 | detail or "640 words exact (64 shift cases and unchanged inputs)")) | ||
| 978 | elif name == "cs_workgroup_yz": | 990 | elif name == "cs_workgroup_yz": |
| 979 | rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env) | 991 | rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env) |
| 980 | results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches" | 992 | results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches" |
| @@ -1092,10 +1104,12 @@ def run_suite(a, work: str) -> int: | |||
| 1092 | ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, | 1104 | ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, |
| 1093 | hexwords=True) | 1105 | hexwords=True) |
| 1094 | results.append((name, ok, detail)) | 1106 | results.append((name, ok, detail)) |
| 1095 | elif name == "cs_div_fmas_f64": | 1107 | elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"): |
| 1096 | # One-rounding binary64 FMA: strict where the translator emitted OpFmaKHR on doubles (shaderFmaFloat64, | 1108 | # One-rounding binary64 FMA: strict where the translator emitted OpFmaKHR on doubles (shaderFmaFloat64, |
| 1097 | # --fma khr); under the default GLSL Fma the split result (0) is allowed, as cs_fma_fused allows it. | 1109 | # --fma khr); under the default GLSL Fma the split result (0) is allowed, as cs_fma_fused allows it. |
| 1098 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) | 1110 | # The _rt fixture reads the same operands from s4..s7, so the driver cannot fold the Fma at compile time. |
| 1111 | env = dict(cs_env or os.environ, VKC_SGPRS=DIV_FMAS_F64_SGPRS) if name.endswith("_rt") else cs_env | ||
| 1112 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=env) | ||
| 1099 | if rc == UNSUPPORTED: # no shaderFloat64, or (--fma khr) no shaderFmaFloat64 | 1113 | if rc == UNSUPPORTED: # no shaderFloat64, or (--fma khr) no shaderFmaFloat64 |
| 1100 | results.append((name, None, unsupported_skip(msg))) | 1114 | results.append((name, None, unsupported_skip(msg))) |
| 1101 | else: | 1115 | else: |
| @@ -1105,7 +1119,8 @@ def run_suite(a, work: str) -> int: | |||
| 1105 | ok = rc == 0 and (words == fused or (not strict and words == split)) | 1119 | ok = rc == 0 and (words == fused or (not strict and words == split)) |
| 1106 | detail = " ".join(hex(x) for x in words) if words else msg | 1120 | detail = " ".join(hex(x) for x in words) if words else msg |
| 1107 | if ok and words == split: | 1121 | if ok and words == split: |
| 1108 | detail += " (split: the driver rounds GLSL Fma on doubles twice; --fma khr fixes it)" | 1122 | detail += (" (split: the driver rounded GLSL Fma on doubles twice%s; --fma khr fixes it)" |
| 1123 | % ("" if name.endswith("_rt") else " when folding the constants")) | ||
| 1109 | results.append((name, ok, detail)) | 1124 | results.append((name, ok, detail)) |
| 1110 | elif name == "cs_cvt_f32_sat": | 1125 | elif name == "cs_cvt_f32_sat": |
| 1111 | # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS). | 1126 | # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS). |
| @@ -1320,6 +1335,9 @@ def run_suite(a, work: str) -> int: | |||
| 1320 | elif name == "cs_imgstore": | 1335 | elif name == "cs_imgstore": |
| 1321 | rc, msg = run_cmd([vk_store, spv]) | 1336 | rc, msg = run_cmd([vk_store, spv]) |
| 1322 | results.append((name, *helper_result(rc, msg))) | 1337 | results.append((name, *helper_result(rc, msg))) |
| 1338 | elif name == "cs_imgstore_cube": # GPU-CUBE-STORE: six-layer 2D-array views at bindings 11/12/13 | ||
| 1339 | rc, msg = run_cmd([vk_store, spv, "cube"]) | ||
| 1340 | results.append((name, *helper_result(rc, msg))) | ||
| 1323 | elif name in ("cs_imgload", "cs_imgload_tfe", "cs_imgload_d16", "cs_imgload_d16_tfe", "cs_sample_lz_int_d16"): | 1341 | elif name in ("cs_imgload", "cs_imgload_tfe", "cs_imgload_d16", "cs_imgload_d16_tfe", "cs_sample_lz_int_d16"): |
| 1324 | rc, msg = run_cmd([vk_store, spv, "load" if name in ("cs_imgload", "cs_imgload_tfe") else "load-d16"]) | 1342 | rc, msg = run_cmd([vk_store, spv, "load" if name in ("cs_imgload", "cs_imgload_tfe") else "load-d16"]) |
| 1325 | results.append((name, *helper_result(rc, msg))) | 1343 | results.append((name, *helper_result(rc, msg))) |
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): |