diff options
Diffstat (limited to 'scripts')
| -rw-r--r-- | scripts/run_wine_tests.py | 228 |
1 files changed, 211 insertions, 17 deletions
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py index 8435f7fb9..d36011430 100644 --- a/scripts/run_wine_tests.py +++ b/scripts/run_wine_tests.py | |||
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | Usage: | 3 | Usage: |
| 4 | python -I scripts/run_wine_tests.py --tests ctest.json --windows-root D:/a/Leonida/Leonida | 4 | python -I scripts/run_wine_tests.py --tests ctest.json --windows-root D:/a/Leonida/Leonida |
| 5 | [--root DIR] [--wine CMD] [--require NAME ...] [--timeout SECONDS] [--summary FILE] [--label TEXT] | 5 | [--root DIR] [--wine CMD] [--require NAME ...] [--timeout SECONDS] [--jobs N] [--summary FILE] [--label TEXT] |
| 6 | 6 | ||
| 7 | --tests is the output of `ctest --show-only=json-v1` from the Windows build, and --windows-root the checkout it was | 7 | --tests is the output of `ctest --show-only=json-v1` from the Windows build, and --windows-root the checkout it was |
| 8 | made in (forward slashes, as `cygpath -m` prints it). Paths under it are mapped to --root, the Linux checkout (default: | 8 | made in (forward slashes, as `cygpath -m` prints it). Paths under it are mapped to --root, the Linux checkout (default: |
| @@ -16,8 +16,16 @@ Every test is reported. The exit code is 1 if a test named by --require fails or | |||
| 16 | others show what does and doesn't work under Wine yet without failing the job. | 16 | others show what does and doesn't work under Wine yet without failing the job. |
| 17 | --timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test. | 17 | --timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test. |
| 18 | Relative executable paths in --wine or WINE are read from the directory where you start this runner. | 18 | Relative executable paths in --wine or WINE are read from the directory where you start this runner. |
| 19 | |||
| 20 | Each test gets WINEDLLOVERRIDES with winedbg.exe and winemenubuilder.exe disabled, so a crash fails at once instead of | ||
| 21 | waiting in the debugger until the timeout; an entry of the caller's or the test's for the same program wins. One | ||
| 22 | wineserver is kept alive for the whole run (`wineserver -p`: $WINESERVER, else the one next to the --wine command, | ||
| 23 | else the one on PATH) and stopped at the end, instead of a new one starting for every test. | ||
| 24 | --jobs N runs N tests at a time. Tests marked RUN_SERIAL run alone, tests sharing a RESOURCE_LOCK never overlap, and | ||
| 25 | DEPENDS and fixtures are kept; the report is in the same order as with --jobs 1 (the default). | ||
| 19 | """ | 26 | """ |
| 20 | import argparse | 27 | import argparse |
| 28 | from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait | ||
| 21 | from graphlib import CycleError, TopologicalSorter | 29 | from graphlib import CycleError, TopologicalSorter |
| 22 | import json | 30 | import json |
| 23 | import math | 31 | import math |
| @@ -30,6 +38,7 @@ import signal | |||
| 30 | import subprocess | 38 | import subprocess |
| 31 | import sys | 39 | import sys |
| 32 | import tempfile | 40 | import tempfile |
| 41 | import threading | ||
| 33 | import time | 42 | import time |
| 34 | 43 | ||
| 35 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 44 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| @@ -120,6 +129,97 @@ class DriveMap: | |||
| 120 | return False | 129 | return False |
| 121 | 130 | ||
| 122 | 131 | ||
| 132 | # A crashed test would wait in winedbg until the timeout; winemenubuilder writes file associations and menu entries | ||
| 133 | # into the user's profile when a fresh prefix is set up. | ||
| 134 | DEFAULT_DLL_OVERRIDES = ("winedbg.exe=d", "winemenubuilder.exe=d") | ||
| 135 | |||
| 136 | |||
| 137 | def _override_names(entry: str) -> set[str]: | ||
| 138 | """The programs one WINEDLLOVERRIDES entry ("a,b.exe=n") names, lower case and without .dll/.exe.""" | ||
| 139 | names = set() | ||
| 140 | for name in entry.partition("=")[0].split(","): | ||
| 141 | name = name.strip().lower() | ||
| 142 | for suffix in (".dll", ".exe"): | ||
| 143 | if name.endswith(suffix): | ||
| 144 | name = name[:-len(suffix)] | ||
| 145 | if name: | ||
| 146 | names.add(name) | ||
| 147 | return names | ||
| 148 | |||
| 149 | |||
| 150 | def merge_dll_overrides(given: str | None) -> str: | ||
| 151 | """WINEDLLOVERRIDES with the defaults added, leaving out a default for a program the given value already names.""" | ||
| 152 | entries = [e for e in (given or "").split(";") if e.strip()] | ||
| 153 | named = set().union(*(_override_names(e) for e in entries)) | ||
| 154 | return ";".join([d for d in DEFAULT_DLL_OVERRIDES if not _override_names(d) & named] + entries) | ||
| 155 | |||
| 156 | |||
| 157 | def find_wineserver(wine: list[str]) -> str | None: | ||
| 158 | """The wineserver the --wine command uses: $WINESERVER, else the one next to it, else the one on PATH.""" | ||
| 159 | given = os.environ.get("WINESERVER") | ||
| 160 | if given and shutil.which(given): | ||
| 161 | return shutil.which(given) | ||
| 162 | for part in wine: | ||
| 163 | resolved = shutil.which(part) | ||
| 164 | if resolved and os.path.basename(resolved).lower() in ("wine", "wine64"): | ||
| 165 | for folder in (os.path.dirname(resolved), os.path.dirname(os.path.realpath(resolved))): | ||
| 166 | sibling = shutil.which(os.path.join(folder, "wineserver")) | ||
| 167 | if sibling: | ||
| 168 | return sibling | ||
| 169 | return shutil.which("wineserver") | ||
| 170 | |||
| 171 | |||
| 172 | class KeptServer: | ||
| 173 | """Keeps one wineserver alive for the run instead of one starting and stopping for every test. | ||
| 174 | |||
| 175 | `wineserver -p` starts a persistent server for $WINEPREFIX; `wineserver -k` stops it and the prefix's Wine | ||
| 176 | processes at the end, also after a failure or Ctrl+C. A server still shutting down (wineboot's lingers a few | ||
| 177 | seconds) is waited for first; one that stays (started by hand with -p) is used and left running. | ||
| 178 | The first Wine program a server runs starts the prefix's services, which inherit its output and live as long as | ||
| 179 | the server: `wine wineboot` starts them with no output, or the first test would wait for the end of its output | ||
| 180 | until the timeout. | ||
| 181 | """ | ||
| 182 | |||
| 183 | def __init__(self, command: str | None, wine: list[str]): | ||
| 184 | self.command, self.wine, self.started, self.note = command, wine, False, "" | ||
| 185 | |||
| 186 | def _run(self, *flags, timeout=30.0) -> int | None: | ||
| 187 | try: | ||
| 188 | return subprocess.run([self.command, *flags], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, | ||
| 189 | stderr=subprocess.DEVNULL, timeout=timeout).returncode | ||
| 190 | except (OSError, subprocess.TimeoutExpired): | ||
| 191 | return None | ||
| 192 | |||
| 193 | def __enter__(self): | ||
| 194 | if not self.command: | ||
| 195 | self.note = "no wineserver found: each test starts its own" | ||
| 196 | return self | ||
| 197 | code = self._run("-p") | ||
| 198 | if code == 2: # one is already running for this prefix | ||
| 199 | if self._run("-w", timeout=15.0) == 0: | ||
| 200 | code = self._run("-p") | ||
| 201 | else: | ||
| 202 | self.note = "a wineserver already runs for this prefix: used and left running" | ||
| 203 | return self | ||
| 204 | self.started = code == 0 | ||
| 205 | if not self.started: | ||
| 206 | self.note = f"could not start {self.command} -p: each test starts its own server" | ||
| 207 | return self | ||
| 208 | self.note = "wineserver kept alive for the run" | ||
| 209 | env = dict(os.environ, WINEDLLOVERRIDES=merge_dll_overrides(os.environ.get("WINEDLLOVERRIDES"))) | ||
| 210 | try: | ||
| 211 | subprocess.run(self.wine + ["wineboot"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, | ||
| 212 | stderr=subprocess.DEVNULL, env=env, timeout=120) | ||
| 213 | except (OSError, subprocess.TimeoutExpired): | ||
| 214 | pass # the tests start the services then, as without a kept server | ||
| 215 | return self | ||
| 216 | |||
| 217 | def __exit__(self, *exc): | ||
| 218 | if self.started: | ||
| 219 | self._run("-k") | ||
| 220 | return False | ||
| 221 | |||
| 222 | |||
| 123 | def wine_path(path: str) -> str: | 223 | def wine_path(path: str) -> str: |
| 124 | """Wine's Z: drive is the Unix root, so a Windows program reads /x/y as Z:\\x\\y.""" | 224 | """Wine's Z: drive is the Unix root, so a Windows program reads /x/y as Z:\\x\\y.""" |
| 125 | return "Z:" + os.path.abspath(path).replace("/", "\\") | 225 | return "Z:" + os.path.abspath(path).replace("/", "\\") |
| @@ -194,6 +294,7 @@ def run_test(test: dict, args, wine: list[str], *, failed_setups: tuple[str, ... | |||
| 194 | if not key or not equals or "\0" in assignment: | 294 | if not key or not equals or "\0" in assignment: |
| 195 | return "fail", "invalid CTest ENVIRONMENT entry: expected NAME=value" | 295 | return "fail", "invalid CTest ENVIRONMENT entry: expected NAME=value" |
| 196 | env[key] = value | 296 | env[key] = value |
| 297 | env["WINEDLLOVERRIDES"] = merge_dll_overrides(env.get("WINEDLLOVERRIDES")) | ||
| 197 | timeout = args.timeout | 298 | timeout = args.timeout |
| 198 | if "TIMEOUT" in props: | 299 | if "TIMEOUT" in props: |
| 199 | try: | 300 | try: |
| @@ -257,19 +358,42 @@ def run_test_process(argv: list[str], *, cwd: str, env: dict[str, str], | |||
| 257 | 358 | ||
| 258 | # Wine's Windows children and launcher wrappers can outlive the immediate child. | 359 | # Wine's Windows children and launcher wrappers can outlive the immediate child. |
| 259 | with subprocess.Popen(argv, **options, start_new_session=True) as proc: | 360 | with subprocess.Popen(argv, **options, start_new_session=True) as proc: |
| 361 | with _running_lock: | ||
| 362 | _running.add(proc.pid) | ||
| 260 | try: | 363 | try: |
| 261 | out, _ = proc.communicate(timeout=timeout) | 364 | out, _ = proc.communicate(timeout=timeout) |
| 262 | except (subprocess.TimeoutExpired, KeyboardInterrupt): | 365 | except (subprocess.TimeoutExpired, KeyboardInterrupt): |
| 263 | # The launcher may have exited while a helper still holds the output pipe. | 366 | # The launcher may have exited while a helper still holds the output pipe. |
| 264 | try: | 367 | _kill_group(proc.pid) |
| 265 | os.killpg(proc.pid, signal.SIGKILL) | ||
| 266 | except ProcessLookupError: | ||
| 267 | pass | ||
| 268 | proc.wait() | 368 | proc.wait() |
| 269 | raise | 369 | raise |
| 370 | finally: | ||
| 371 | with _running_lock: | ||
| 372 | _running.discard(proc.pid) | ||
| 270 | return subprocess.CompletedProcess(argv, proc.returncode, out) | 373 | return subprocess.CompletedProcess(argv, proc.returncode, out) |
| 271 | 374 | ||
| 272 | 375 | ||
| 376 | # The process groups of the tests running now: with --jobs, Ctrl+C reaches only the main thread, which stops them. | ||
| 377 | _running: set[int] = set() | ||
| 378 | _running_lock = threading.Lock() | ||
| 379 | |||
| 380 | |||
| 381 | def _kill_group(pid: int) -> None: | ||
| 382 | try: | ||
| 383 | os.killpg(pid, signal.SIGKILL) | ||
| 384 | except (ProcessLookupError, PermissionError): | ||
| 385 | pass | ||
| 386 | |||
| 387 | |||
| 388 | def stop_running_tests() -> None: | ||
| 389 | if os.name != "posix": | ||
| 390 | return | ||
| 391 | with _running_lock: | ||
| 392 | pids = list(_running) | ||
| 393 | for pid in pids: | ||
| 394 | _kill_group(pid) | ||
| 395 | |||
| 396 | |||
| 273 | def positive_seconds(text: str) -> float: | 397 | def positive_seconds(text: str) -> float: |
| 274 | """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on.""" | 398 | """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on.""" |
| 275 | try: | 399 | try: |
| @@ -283,6 +407,17 @@ def positive_seconds(text: str) -> float: | |||
| 283 | return value | 407 | return value |
| 284 | 408 | ||
| 285 | 409 | ||
| 410 | def positive_int(text: str) -> int: | ||
| 411 | """--jobs: a whole number of at least 1.""" | ||
| 412 | try: | ||
| 413 | value = int(text) | ||
| 414 | except ValueError: | ||
| 415 | raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None | ||
| 416 | if value < 1: | ||
| 417 | raise argparse.ArgumentTypeError("must be at least 1") | ||
| 418 | return value | ||
| 419 | |||
| 420 | |||
| 286 | def wine_command(text: str) -> list[str]: | 421 | def wine_command(text: str) -> list[str]: |
| 287 | """--wine: split into a command the way a shell would, refusing blank or malformed values up front.""" | 422 | """--wine: split into a command the way a shell would, refusing blank or malformed values up front.""" |
| 288 | try: | 423 | try: |
| @@ -331,6 +466,48 @@ def read_tests(path: str) -> list[dict] | None: | |||
| 331 | return tests | 466 | return tests |
| 332 | 467 | ||
| 333 | 468 | ||
| 469 | def run_parallel(tests: list[dict], order: list[int], before: dict[int, set[int]], jobs: int, run_one, outcomes: dict, | ||
| 470 | results_by_index: dict, report) -> None: | ||
| 471 | """Run up to `jobs` tests at a time and report them in `order`, as the serial loop does. | ||
| 472 | |||
| 473 | A test starts once the tests it depends on have finished. A RUN_SERIAL test runs alone, and two tests that share | ||
| 474 | a RESOURCE_LOCK never run at the same time. | ||
| 475 | """ | ||
| 476 | serial = {index for index, test in enumerate(tests) if truthy(properties(test).get("RUN_SERIAL"))} | ||
| 477 | locks = {index: set(regex_list(properties(test).get("RESOURCE_LOCK", []))) for index, test in enumerate(tests)} | ||
| 478 | waiting, running, held = list(order), {}, set() | ||
| 479 | next_report = 0 | ||
| 480 | with ThreadPoolExecutor(max_workers=jobs) as pool: | ||
| 481 | try: | ||
| 482 | while waiting or running: | ||
| 483 | for index in list(waiting): | ||
| 484 | if len(running) >= jobs or any(r in serial for r in running.values()): | ||
| 485 | break | ||
| 486 | if before[index] - results_by_index.keys() or locks[index] & held: | ||
| 487 | continue | ||
| 488 | if index in serial and running: | ||
| 489 | continue | ||
| 490 | waiting.remove(index) | ||
| 491 | held |= locks[index] | ||
| 492 | running[pool.submit(run_one, index)] = index | ||
| 493 | if index in serial: | ||
| 494 | break | ||
| 495 | done, _ = wait(running, return_when=FIRST_COMPLETED) | ||
| 496 | for future in done: | ||
| 497 | index = running.pop(future) | ||
| 498 | outcomes[index] = future.result() | ||
| 499 | results_by_index[index] = outcomes[index][0] | ||
| 500 | held -= locks[index] | ||
| 501 | while next_report < len(order) and order[next_report] in outcomes: | ||
| 502 | report(order[next_report]) | ||
| 503 | next_report += 1 | ||
| 504 | except BaseException: | ||
| 505 | # Ctrl+C reaches this thread only: stop the tests the workers are waiting on, start no more. | ||
| 506 | pool.shutdown(wait=False, cancel_futures=True) | ||
| 507 | stop_running_tests() | ||
| 508 | raise | ||
| 509 | |||
| 510 | |||
| 334 | def main() -> int: | 511 | def main() -> int: |
| 335 | ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | 512 | ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 336 | ap.add_argument("--tests", required=True, help="ctest --show-only=json-v1 output from the Windows build") | 513 | ap.add_argument("--tests", required=True, help="ctest --show-only=json-v1 output from the Windows build") |
| @@ -341,6 +518,8 @@ def main() -> int: | |||
| 341 | ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)") | 518 | ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)") |
| 342 | ap.add_argument("--timeout", type=positive_seconds, default=120.0, | 519 | ap.add_argument("--timeout", type=positive_seconds, default=120.0, |
| 343 | help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)") | 520 | help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)") |
| 521 | ap.add_argument("--jobs", type=positive_int, default=1, | ||
| 522 | help="tests run at a time; RUN_SERIAL and RESOURCE_LOCK are kept (default 1)") | ||
| 344 | ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") | 523 | ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") |
| 345 | ap.add_argument("--label", help="named in the summary's heading, e.g. the Wine version") | 524 | ap.add_argument("--label", help="named in the summary's heading, e.g. the Wine version") |
| 346 | args = ap.parse_args() | 525 | args = ap.parse_args() |
| @@ -352,9 +531,12 @@ def main() -> int: | |||
| 352 | indices = {name: index for index, name in enumerate(names)} | 531 | indices = {name: index for index, name in enumerate(names)} |
| 353 | setups = fixture_dependencies(tests) | 532 | setups = fixture_dependencies(tests) |
| 354 | sorter = TopologicalSorter(setups) | 533 | sorter = TopologicalSorter(setups) |
| 534 | before = {index: set(setups[index]) for index in range(len(tests))} | ||
| 355 | for index, test in enumerate(tests): | 535 | for index, test in enumerate(tests): |
| 356 | # DEPENDS controls order. Only failed fixture setups block a consumer. | 536 | # DEPENDS controls order. Only failed fixture setups block a consumer. |
| 357 | sorter.add(index, *(indices[name] for name in properties(test).get("DEPENDS", []) if name in indices)) | 537 | depends = [indices[name] for name in properties(test).get("DEPENDS", []) if name in indices] |
| 538 | sorter.add(index, *depends) | ||
| 539 | before[index].update(depends) | ||
| 358 | try: | 540 | try: |
| 359 | order = list(sorter.static_order()) | 541 | order = list(sorter.static_order()) |
| 360 | except CycleError: | 542 | except CycleError: |
| @@ -367,18 +549,30 @@ def main() -> int: | |||
| 367 | results = {} | 549 | results = {} |
| 368 | results_by_index: dict[int, str] = {} | 550 | results_by_index: dict[int, str] = {} |
| 369 | prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") | 551 | prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") |
| 370 | with DriveMap(args.windows_root, args.root, prefix) as drive: | 552 | outcomes: dict[int, tuple[str, str]] = {} |
| 553 | |||
| 554 | def run_one(index: int) -> tuple[str, str]: | ||
| 555 | failed_setups = tuple(names[setup] for setup in setups[index] if results_by_index[setup] == "fail") | ||
| 556 | return run_test(tests[index], args, wine, failed_setups=failed_setups) | ||
| 557 | |||
| 558 | def report(index: int) -> None: | ||
| 559 | status, detail = outcomes[index] | ||
| 560 | results[names[index]] = status | ||
| 561 | print(f"[{status.upper()}] {names[index]}", flush=True) | ||
| 562 | if status != "pass": | ||
| 563 | for line in detail.rstrip().splitlines()[-40:]: | ||
| 564 | print(f" {line}") | ||
| 565 | |||
| 566 | with DriveMap(args.windows_root, args.root, prefix) as drive, KeptServer(find_wineserver(wine), wine) as server: | ||
| 371 | print(drive.note, flush=True) | 567 | print(drive.note, flush=True) |
| 372 | for index in order: | 568 | print(server.note, flush=True) |
| 373 | name = names[index] | 569 | if args.jobs == 1: |
| 374 | failed_setups = tuple(names[setup] for setup in setups[index] if results_by_index[setup] == "fail") | 570 | for index in order: |
| 375 | status, detail = run_test(tests[index], args, wine, failed_setups=failed_setups) | 571 | outcomes[index] = run_one(index) |
| 376 | results_by_index[index] = status | 572 | results_by_index[index] = outcomes[index][0] |
| 377 | results[name] = status | 573 | report(index) |
| 378 | print(f"[{status.upper()}] {name}", flush=True) | 574 | else: |
| 379 | if status != "pass": | 575 | run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report) |
| 380 | for line in detail.rstrip().splitlines()[-40:]: | ||
| 381 | print(f" {line}") | ||
| 382 | 576 | ||
| 383 | missing = list(dict.fromkeys(n for n in args.require if n not in results)) | 577 | missing = list(dict.fromkeys(n for n in args.require if n not in results)) |
| 384 | failed_required = [n for n in args.require if results.get(n) != "pass"] | 578 | failed_required = [n for n in args.require if results.get(n) != "pass"] |