diff --git a/docs/testing.md b/docs/testing.md index f8246f8885..4c15f08c70 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -218,6 +218,49 @@ and `vk_presenter_sync`, `xbox_present` and `dxgi_swapchain` pass, while they fa compositor for those three. Six still failed with a real display: `device_proxy`, `d3d12_xs_root_signature`, `xdxr_build`, `d3d12_xdxr_rt`, `d3d12_present` and `d3d12_compute`. +Run one after another as above, the suite takes several seconds per test, although a test started by hand takes 0.1 to +1 second. Four settings make a local run of the cross-build much faster: + +```sh +export WINEPREFIX="$HOME/.local/share/leonida-wine" WINEDEBUG=-all \ + WINEDLLOVERRIDES="winedbg.exe=d;winemenubuilder.exe=d" +mkdir -p "$WINEPREFIX" +xvfb-run -a sh -c 'wineserver -p; wine wineboot -u /dev/null 2>&1 + ctest --test-dir runtime/build/windows -j 6 --timeout 120; wineserver -k' +``` + +Start the server before `wineboot`: `wineserver -p` does nothing while another server runs for the prefix. Run +`wineboot` after it, with its output thrown away: the first Wine program a server runs starts the prefix's services, +which keep that program's output open for as long as the server lives, so a first test that started them would wait +for the end of its output until the timeout. + +- `wineserver -p` keeps one Wine server for the whole run; without it a new one starts for each test. +- `winedbg.exe=d`: a test that crashes otherwise waits in Wine's debugger until its timeout. +- `winemenubuilder.exe=d`: without it `wineboot` on a fresh prefix writes `wine-extension-*.desktop` files and the MIME + cache into `~/.local/share/applications`, pointing your file associations at the test prefix. Set it before the + prefix is first made. +- `ctest -j 6` runs six tests at a time. The tests that share files under the temp directory (see "Known problems") + can then fail now and then; rerun such a failure on its own before you count it. + +Measured with Wine 11.22 on llvmpipe, 40 tests of a clang-cl build (`ctest -R '^(d3d12_[a-c]|vk_[a-d]|xg)'`), adding +one setting at a time: + +| Settings | Seconds | +|---|---| +| As above: one test after another | 179 | +| `wineserver -p` (and `wineboot` after it) | 35 | +| and `WINEDEBUG=-all` | 35 | +| and `winedbg.exe=d` | 35 | +| and `ctest -j 6` | 5.6 | +| `ctest -j 6` and the overrides, without `wineserver -p` | 18 | + +The kept server is most of it: a test that takes 0.05 seconds with it took about 3.4 without, the time of a server +starting and stopping. `WINEDEBUG=-all` and `winedbg.exe=d` changed nothing here because no test crashed; with a crash, +`winedbg.exe=d` saves the rest of that test's timeout. The full suite (about 310 tests) took about 28 minutes run one +after another, and 67 seconds with all four settings for two devices (llvmpipe and an integrated GPU) run at the same +time. `scripts/run_wine_tests.py` (below) does the same: 32 seconds for those 40 tests with `--jobs 1`, 6 with +`--jobs 6`, and 19 seconds for all 312 tests with `--jobs 6`. + The build type defaults to `RelWithDebInfo`: xwin leaves out the debug CRT, so `Debug` needs `--include-debug-libs`. `make_game.py`'s `runtime` stage makes this same build on Linux when the tools and the SDK are there (`--runtime-build runtime/build/windows` takes a folder made by hand like a Windows build). CMake packages are @@ -290,7 +333,12 @@ WINE=wine WINEPREFIX="$(mktemp -d)" WINEDLLOVERRIDES="mscoree,mshtml=" WINEDEBUG The session script initializes a dedicated prefix and stops its Wine processes at exit. On a headless host, put `xvfb-run -a` before `bash` so prefix initialization and the tests share one virtual display. The test runner -maps the recorded Windows drive to the Linux checkout for shaders referenced by absolute Windows paths. It prints +maps the recorded Windows drive to the Linux checkout for shaders referenced by absolute Windows paths. It keeps one +wineserver alive for the run and stops it at the end, and adds `winedbg.exe=d;winemenubuilder.exe=d` to each test's +`WINEDLLOVERRIDES` (an entry of yours for the same program wins). `--jobs N` runs N tests at a time (default 1): tests +marked `RUN_SERIAL` run alone, tests that share a `RESOURCE_LOCK` never overlap, and the verdicts are printed in the +same order as with `--jobs 1`; the tests that share temp files can fail now and then in parallel (see "Known +problems"). It prints every verdict and returns a failure status if any required test fails, skips or is missing. Check the printed verdicts for failures outside the required set. diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py index 8435f7fb99..d360114303 100644 --- a/scripts/run_wine_tests.py +++ b/scripts/run_wine_tests.py @@ -2,7 +2,7 @@ Usage: python -I scripts/run_wine_tests.py --tests ctest.json --windows-root D:/a/Leonida/Leonida - [--root DIR] [--wine CMD] [--require NAME ...] [--timeout SECONDS] [--summary FILE] [--label TEXT] + [--root DIR] [--wine CMD] [--require NAME ...] [--timeout SECONDS] [--jobs N] [--summary FILE] [--label TEXT] --tests is the output of `ctest --show-only=json-v1` from the Windows build, and --windows-root the checkout it was made in (forward slashes, as `cygpath -m` prints it). Paths under it are mapped to --root, the Linux checkout (default: @@ -16,8 +16,16 @@ others show what does and doesn't work under Wine yet without failing the job. --timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test. Relative executable paths in --wine or WINE are read from the directory where you start this runner. + +Each test gets WINEDLLOVERRIDES with winedbg.exe and winemenubuilder.exe disabled, so a crash fails at once instead of +waiting in the debugger until the timeout; an entry of the caller's or the test's for the same program wins. One +wineserver is kept alive for the whole run (`wineserver -p`: $WINESERVER, else the one next to the --wine command, +else the one on PATH) and stopped at the end, instead of a new one starting for every test. +--jobs N runs N tests at a time. Tests marked RUN_SERIAL run alone, tests sharing a RESOURCE_LOCK never overlap, and +DEPENDS and fixtures are kept; the report is in the same order as with --jobs 1 (the default). """ import argparse +from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait from graphlib import CycleError, TopologicalSorter import json import math @@ -30,6 +38,7 @@ import subprocess import sys import tempfile +import threading import time ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -120,6 +129,97 @@ def __exit__(self, *exc): return False +# A crashed test would wait in winedbg until the timeout; winemenubuilder writes file associations and menu entries +# into the user's profile when a fresh prefix is set up. +DEFAULT_DLL_OVERRIDES = ("winedbg.exe=d", "winemenubuilder.exe=d") + + +def _override_names(entry: str) -> set[str]: + """The programs one WINEDLLOVERRIDES entry ("a,b.exe=n") names, lower case and without .dll/.exe.""" + names = set() + for name in entry.partition("=")[0].split(","): + name = name.strip().lower() + for suffix in (".dll", ".exe"): + if name.endswith(suffix): + name = name[:-len(suffix)] + if name: + names.add(name) + return names + + +def merge_dll_overrides(given: str | None) -> str: + """WINEDLLOVERRIDES with the defaults added, leaving out a default for a program the given value already names.""" + entries = [e for e in (given or "").split(";") if e.strip()] + named = set().union(*(_override_names(e) for e in entries)) + return ";".join([d for d in DEFAULT_DLL_OVERRIDES if not _override_names(d) & named] + entries) + + +def find_wineserver(wine: list[str]) -> str | None: + """The wineserver the --wine command uses: $WINESERVER, else the one next to it, else the one on PATH.""" + given = os.environ.get("WINESERVER") + if given and shutil.which(given): + return shutil.which(given) + for part in wine: + resolved = shutil.which(part) + if resolved and os.path.basename(resolved).lower() in ("wine", "wine64"): + for folder in (os.path.dirname(resolved), os.path.dirname(os.path.realpath(resolved))): + sibling = shutil.which(os.path.join(folder, "wineserver")) + if sibling: + return sibling + return shutil.which("wineserver") + + +class KeptServer: + """Keeps one wineserver alive for the run instead of one starting and stopping for every test. + + `wineserver -p` starts a persistent server for $WINEPREFIX; `wineserver -k` stops it and the prefix's Wine + processes at the end, also after a failure or Ctrl+C. A server still shutting down (wineboot's lingers a few + seconds) is waited for first; one that stays (started by hand with -p) is used and left running. + The first Wine program a server runs starts the prefix's services, which inherit its output and live as long as + the server: `wine wineboot` starts them with no output, or the first test would wait for the end of its output + until the timeout. + """ + + def __init__(self, command: str | None, wine: list[str]): + self.command, self.wine, self.started, self.note = command, wine, False, "" + + def _run(self, *flags, timeout=30.0) -> int | None: + try: + return subprocess.run([self.command, *flags], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, timeout=timeout).returncode + except (OSError, subprocess.TimeoutExpired): + return None + + def __enter__(self): + if not self.command: + self.note = "no wineserver found: each test starts its own" + return self + code = self._run("-p") + if code == 2: # one is already running for this prefix + if self._run("-w", timeout=15.0) == 0: + code = self._run("-p") + else: + self.note = "a wineserver already runs for this prefix: used and left running" + return self + self.started = code == 0 + if not self.started: + self.note = f"could not start {self.command} -p: each test starts its own server" + return self + self.note = "wineserver kept alive for the run" + env = dict(os.environ, WINEDLLOVERRIDES=merge_dll_overrides(os.environ.get("WINEDLLOVERRIDES"))) + try: + subprocess.run(self.wine + ["wineboot"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, env=env, timeout=120) + except (OSError, subprocess.TimeoutExpired): + pass # the tests start the services then, as without a kept server + return self + + def __exit__(self, *exc): + if self.started: + self._run("-k") + return False + + def wine_path(path: str) -> str: """Wine's Z: drive is the Unix root, so a Windows program reads /x/y as Z:\\x\\y.""" return "Z:" + os.path.abspath(path).replace("/", "\\") @@ -194,6 +294,7 @@ def run_test(test: dict, args, wine: list[str], *, failed_setups: tuple[str, ... if not key or not equals or "\0" in assignment: return "fail", "invalid CTest ENVIRONMENT entry: expected NAME=value" env[key] = value + env["WINEDLLOVERRIDES"] = merge_dll_overrides(env.get("WINEDLLOVERRIDES")) timeout = args.timeout if "TIMEOUT" in props: try: @@ -257,19 +358,42 @@ def run_test_process(argv: list[str], *, cwd: str, env: dict[str, str], # Wine's Windows children and launcher wrappers can outlive the immediate child. with subprocess.Popen(argv, **options, start_new_session=True) as proc: + with _running_lock: + _running.add(proc.pid) try: out, _ = proc.communicate(timeout=timeout) except (subprocess.TimeoutExpired, KeyboardInterrupt): # The launcher may have exited while a helper still holds the output pipe. - try: - os.killpg(proc.pid, signal.SIGKILL) - except ProcessLookupError: - pass + _kill_group(proc.pid) proc.wait() raise + finally: + with _running_lock: + _running.discard(proc.pid) return subprocess.CompletedProcess(argv, proc.returncode, out) +# The process groups of the tests running now: with --jobs, Ctrl+C reaches only the main thread, which stops them. +_running: set[int] = set() +_running_lock = threading.Lock() + + +def _kill_group(pid: int) -> None: + try: + os.killpg(pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + + +def stop_running_tests() -> None: + if os.name != "posix": + return + with _running_lock: + pids = list(_running) + for pid in pids: + _kill_group(pid) + + def positive_seconds(text: str) -> float: """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on.""" try: @@ -283,6 +407,17 @@ def positive_seconds(text: str) -> float: return value +def positive_int(text: str) -> int: + """--jobs: a whole number of at least 1.""" + try: + value = int(text) + except ValueError: + raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None + if value < 1: + raise argparse.ArgumentTypeError("must be at least 1") + return value + + def wine_command(text: str) -> list[str]: """--wine: split into a command the way a shell would, refusing blank or malformed values up front.""" try: @@ -331,6 +466,48 @@ def read_tests(path: str) -> list[dict] | None: return tests +def run_parallel(tests: list[dict], order: list[int], before: dict[int, set[int]], jobs: int, run_one, outcomes: dict, + results_by_index: dict, report) -> None: + """Run up to `jobs` tests at a time and report them in `order`, as the serial loop does. + + A test starts once the tests it depends on have finished. A RUN_SERIAL test runs alone, and two tests that share + a RESOURCE_LOCK never run at the same time. + """ + serial = {index for index, test in enumerate(tests) if truthy(properties(test).get("RUN_SERIAL"))} + locks = {index: set(regex_list(properties(test).get("RESOURCE_LOCK", []))) for index, test in enumerate(tests)} + waiting, running, held = list(order), {}, set() + next_report = 0 + with ThreadPoolExecutor(max_workers=jobs) as pool: + try: + while waiting or running: + for index in list(waiting): + if len(running) >= jobs or any(r in serial for r in running.values()): + break + if before[index] - results_by_index.keys() or locks[index] & held: + continue + if index in serial and running: + continue + waiting.remove(index) + held |= locks[index] + running[pool.submit(run_one, index)] = index + if index in serial: + break + done, _ = wait(running, return_when=FIRST_COMPLETED) + for future in done: + index = running.pop(future) + outcomes[index] = future.result() + results_by_index[index] = outcomes[index][0] + held -= locks[index] + while next_report < len(order) and order[next_report] in outcomes: + report(order[next_report]) + next_report += 1 + except BaseException: + # Ctrl+C reaches this thread only: stop the tests the workers are waiting on, start no more. + pool.shutdown(wait=False, cancel_futures=True) + stop_running_tests() + raise + + def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--tests", required=True, help="ctest --show-only=json-v1 output from the Windows build") @@ -341,6 +518,8 @@ def main() -> int: ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)") ap.add_argument("--timeout", type=positive_seconds, default=120.0, help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)") + ap.add_argument("--jobs", type=positive_int, default=1, + help="tests run at a time; RUN_SERIAL and RESOURCE_LOCK are kept (default 1)") ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") ap.add_argument("--label", help="named in the summary's heading, e.g. the Wine version") args = ap.parse_args() @@ -352,9 +531,12 @@ def main() -> int: indices = {name: index for index, name in enumerate(names)} setups = fixture_dependencies(tests) sorter = TopologicalSorter(setups) + before = {index: set(setups[index]) for index in range(len(tests))} for index, test in enumerate(tests): # DEPENDS controls order. Only failed fixture setups block a consumer. - sorter.add(index, *(indices[name] for name in properties(test).get("DEPENDS", []) if name in indices)) + depends = [indices[name] for name in properties(test).get("DEPENDS", []) if name in indices] + sorter.add(index, *depends) + before[index].update(depends) try: order = list(sorter.static_order()) except CycleError: @@ -367,18 +549,30 @@ def main() -> int: results = {} results_by_index: dict[int, str] = {} prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") - with DriveMap(args.windows_root, args.root, prefix) as drive: + outcomes: dict[int, tuple[str, str]] = {} + + def run_one(index: int) -> tuple[str, str]: + failed_setups = tuple(names[setup] for setup in setups[index] if results_by_index[setup] == "fail") + return run_test(tests[index], args, wine, failed_setups=failed_setups) + + def report(index: int) -> None: + status, detail = outcomes[index] + results[names[index]] = status + print(f"[{status.upper()}] {names[index]}", flush=True) + if status != "pass": + for line in detail.rstrip().splitlines()[-40:]: + print(f" {line}") + + with DriveMap(args.windows_root, args.root, prefix) as drive, KeptServer(find_wineserver(wine), wine) as server: print(drive.note, flush=True) - for index in order: - name = names[index] - failed_setups = tuple(names[setup] for setup in setups[index] if results_by_index[setup] == "fail") - status, detail = run_test(tests[index], args, wine, failed_setups=failed_setups) - results_by_index[index] = status - results[name] = status - print(f"[{status.upper()}] {name}", flush=True) - if status != "pass": - for line in detail.rstrip().splitlines()[-40:]: - print(f" {line}") + print(server.note, flush=True) + if args.jobs == 1: + for index in order: + outcomes[index] = run_one(index) + results_by_index[index] = outcomes[index][0] + report(index) + else: + run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report) missing = list(dict.fromkeys(n for n in args.require if n not in results)) failed_required = [n for n in args.require if results.get(n) != "pass"] diff --git a/tests/test_run_wine_tests.py b/tests/test_run_wine_tests.py index 93870b9d6c..7ba55d2f8e 100644 --- a/tests/test_run_wine_tests.py +++ b/tests/test_run_wine_tests.py @@ -195,6 +195,29 @@ def test_ctest_environment_is_applied_only_to_its_child(self) -> None: self.assertEqual(status, "pass", detail) self.assertEqual(detail.splitlines()[1:], ["'inherited'", "'keep'", "None", "None"]) + def test_wine_dll_overrides_reach_the_test_and_merge_with_the_callers(self) -> None: + exe = self.program("show_overrides.py", "import os\nprint(os.environ.get('WINEDLLOVERRIDES'))\n") + command = self.command_for(exe) + cases = ( + (None, {}, {"winedbg.exe=d", "winemenubuilder.exe=d"}), + ("mscoree,mshtml=", {}, {"winedbg.exe=d", "winemenubuilder.exe=d", "mscoree,mshtml="}), + # The caller's entry for the same program wins, with or without its .exe. + ("winedbg=b;d3d12=n", {}, {"winedbg=b", "d3d12=n", "winemenubuilder.exe=d"}), + # So does the test's own CTest ENVIRONMENT. + ("mscoree=", {"ENVIRONMENT": ["WINEDLLOVERRIDES=winemenubuilder.exe,dxgi=n"]}, + {"winedbg.exe=d", "winemenubuilder.exe,dxgi=n"}), + ) + for given, props, expected in cases: + with self.subTest(given=given, props=props), mock.patch.dict(os.environ, {}): + os.environ.pop("WINEDLLOVERRIDES", None) + if given is not None: + os.environ["WINEDLLOVERRIDES"] = given + status, detail = self.run_entry(ctest_entry("overrides", command, props)) + self.assertEqual(status, "pass", detail) + self.assertEqual(set(detail.splitlines()[1].split(";")), expected) + # The runner's own environment is left as it was. + self.assertEqual(os.environ.get("WINEDLLOVERRIDES"), given) + def test_malformed_ctest_environment_fails_before_launch(self) -> None: command = self.command_for(self.exiting(0)) props = {"ENVIRONMENT": ["missing_equals"]} @@ -463,6 +486,7 @@ def test_main_maps_the_drive_while_the_tests_run(self): "--require", "compiled_in_path"] out = io.StringIO() with mock.patch.dict(os.environ, {"WINEPREFIX": str(self.prefix)}), \ + mock.patch.object(rwt, "find_wineserver", return_value=None, create=True), \ mock.patch.object(sys, "argv", argv), contextlib.redirect_stdout(out): code = rwt.main() self.assertEqual(code, 0, out.getvalue()) @@ -482,6 +506,11 @@ def setUp(self): env = mock.patch.dict(os.environ, {"WINEPREFIX": str(self.root / "no-prefix")}) env.start() self.addCleanup(env.stop) + # Never start the machine's real wineserver; the tests that need one give a fake. + self.real_find_wineserver = getattr(rwt, "find_wineserver", None) + server = mock.patch.object(rwt, "find_wineserver", return_value=None, create=True) + server.start() + self.addCleanup(server.stop) def tearDown(self): self._tmp.cleanup() @@ -511,6 +540,149 @@ def test_a_required_test_that_passes_exits_zero(self): self.assertEqual(code, 0) self.assertIn("1 passed, 0 failed, 0 skipped under Wine (1 tests)", out) + def fake_wineserver(self, *, first_code=0): + """An executable `wineserver` that logs its arguments; `-p` exits with first_code the first time.""" + log = self.root / "wineserver.log" + path = self.root / "bin" / "wineserver" + path.parent.mkdir() + path.write_text(f"#!{sys.executable}\nimport os, sys\n" + f"log = {str(log)!r}\n" + "first = not os.path.exists(log)\n" + "open(log, 'a').write(' '.join(sys.argv[1:]) + '\\n')\n" + f"sys.exit({first_code} if first and sys.argv[1:] == ['-p'] else 0)\n", + encoding="utf-8", newline="\n") + path.chmod(0o755) + return path, log + + @unittest.skipUnless(os.name == "posix", "the fake wineserver is a script with a #! line") + def test_one_wineserver_is_kept_alive_and_stopped_after_the_run(self): + server, log = self.fake_wineserver() + # A "wine" that logs `wineboot` (the services start-up, which must not hold a test's output open) and runs + # everything else. + wine = self.root / "fake_wine.py" + wine.write_text("import runpy, sys\n" + "if sys.argv[1:] == ['wineboot']:\n" + f" open({str(log)!r}, 'a').write('wine wineboot %s\\n' % sys.stdout.isatty())\n" + " sys.exit(0)\n" + "sys.argv = sys.argv[1:]\n" + "runpy.run_path(sys.argv[0], run_name='__main__')\n", encoding="utf-8", newline="\n") + entries = [ctest_entry("ok", self.command("ok.py")), ctest_entry("bad", self.command("bad.py"))] + with mock.patch.dict(os.environ, {"WINESERVER": str(server)}), \ + mock.patch.object(rwt, "find_wineserver", self.real_find_wineserver): + code, out, _ = self.run_main(entries, "--require", "bad", wine=f"{sys.executable} {wine}") + self.assertEqual(code, 1) + self.assertIn("[PASS] ok", out) + self.assertEqual(log.read_text(encoding="utf-8").splitlines(), ["-p", "wine wineboot False", "-k"]) + self.assertIn("wineserver kept alive for the run", out) + + @unittest.skipUnless(os.name == "posix", "the fake wineserver is a script with a #! line") + def test_the_wineserver_is_stopped_when_the_run_is_interrupted(self): + server, log = self.fake_wineserver() + with mock.patch.dict(os.environ, {"WINESERVER": str(server)}), \ + mock.patch.object(rwt, "find_wineserver", self.real_find_wineserver), \ + mock.patch.object(rwt, "run_test", side_effect=KeyboardInterrupt), \ + self.assertRaises(KeyboardInterrupt): + self.run_main([ctest_entry("ok", self.command("ok.py"))]) + self.assertEqual(log.read_text(encoding="utf-8").splitlines(), ["-p", "-k"]) + + @unittest.skipUnless(os.name == "posix", "the fake wineserver is a script with a #! line") + def test_a_server_still_shutting_down_is_waited_for(self): + server, log = self.fake_wineserver(first_code=2) + with mock.patch.dict(os.environ, {"WINESERVER": str(server)}), \ + mock.patch.object(rwt, "find_wineserver", self.real_find_wineserver): + code, _, _ = self.run_main([ctest_entry("ok", self.command("ok.py"))]) + self.assertEqual(code, 0) + self.assertEqual(log.read_text(encoding="utf-8").splitlines(), ["-p", "-w", "-p", "-k"]) + + def test_no_wineserver_is_one_line_and_the_run_goes_on(self): + code, out, _ = self.run_main([ctest_entry("ok", self.command("ok.py"))], "--require", "ok") + self.assertEqual(code, 0) + self.assertIn("no wineserver found: each test starts its own\n", out) + self.assertIn("[PASS] ok", out) + + def timed(self, name, *, props=None, code=0, sleep=0.3): + """A test that logs when it starts and ends, to see which tests overlapped.""" + (self.artifact / f"{name}.py").write_text( + "import os, sys, time\n" + "log = os.environ['TIMING_LOG']\n" + f"open(log, 'a').write('{name} start %r\\n' % time.monotonic())\n" + f"time.sleep({sleep})\n" + f"open(log, 'a').write('{name} end %r\\n' % time.monotonic())\n" + f"sys.exit({code})\n", encoding="utf-8", newline="\n") + props = dict(props or {}) + props["ENVIRONMENT"] = ["TIMING_LOG=" + str(self.root / "timing.log")] + return ctest_entry(name, self.command(f"{name}.py"), props) + + def intervals(self): + spans: dict[str, list[float]] = {} + for line in (self.root / "timing.log").read_text(encoding="utf-8").splitlines(): + name, _, when = line.split() + spans.setdefault(name, []).append(float(when)) + return spans + + @staticmethod + def overlap(a, b): + return a[0] < b[1] and b[0] < a[1] + + @staticmethod + def most_at_once(spans): + events = sorted([(s, 1) for s, _ in spans.values()] + [(e, -1) for _, e in spans.values()]) + level = peak = 0 + for _, step in events: + level += step + peak = max(peak, level) + return peak + + def test_jobs_runs_that_many_tests_at_a_time(self): + entries = [self.timed(f"t{i}") for i in range(6)] + code, out, _ = self.run_main(entries, "--jobs", "3") + self.assertEqual(code, 0, out) + self.assertEqual(self.most_at_once(self.intervals()), 3) + self.assertIn("6 passed, 0 failed, 0 skipped under Wine (6 tests)", out) + + def test_jobs_keeps_locks_serial_tests_and_dependencies(self): + entries = [ + self.timed("lock_a", props={"RESOURCE_LOCK": ["shader_library"]}), + self.timed("lock_b", props={"RESOURCE_LOCK": ["other", "shader_library"]}), + self.timed("free_1"), self.timed("free_2"), + self.timed("alone", props={"RUN_SERIAL": "ON"}), + self.timed("after", props={"DEPENDS": ["free_1"]}), + ] + code, out, _ = self.run_main(entries, "--jobs", "4") + self.assertEqual(code, 0, out) + spans = self.intervals() + self.assertFalse(self.overlap(spans["lock_a"], spans["lock_b"]), spans) + for name in spans: + if name != "alone": + self.assertFalse(self.overlap(spans["alone"], spans[name]), (name, spans)) + self.assertGreaterEqual(spans["after"][0], spans["free_1"][1]) + self.assertGreater(self.most_at_once(spans), 1) + + def test_jobs_one_and_parallel_runs_report_as_before(self): + entries = [self.timed("slow", sleep=0.5), self.timed("fails", code=3, sleep=0.0), + self.timed("fast", sleep=0.0)] + outputs, summaries = [], [] + for extra in ((), ("--jobs", "1"), ("--jobs", "3")): + summary = self.root / f"summary{len(summaries)}.md" + code, out, _ = self.run_main(entries, "--summary", str(summary), *extra) + self.assertEqual(code, 0) + # Leave out the indented detail lines, which carry each run's own timing. + outputs.append([line for line in out.splitlines() if not line.startswith(" ")]) + summaries.append(summary.read_text(encoding="utf-8")) + self.assertEqual(outputs[0][-5:], ["[PASS] slow", "[FAIL] fails", "[PASS] fast", "", + "2 passed, 1 failed, 0 skipped under Wine (3 tests)"]) + self.assertEqual(outputs[1], outputs[0]) + self.assertEqual(outputs[2], outputs[0]) + self.assertEqual(summaries[1], summaries[0]) + self.assertEqual(summaries[2], summaries[0]) + + def test_jobs_must_be_a_positive_whole_number(self): + self.assertEqual(self.run_main([ctest_entry("ok", self.command("ok.py"))], "--jobs", "2")[0], 0) + for value in ("0", "-2", "two", "1.5"): + with self.subTest(value=value), self.assertRaises(SystemExit), \ + contextlib.redirect_stderr(io.StringIO()): + self.run_main([ctest_entry("ok", self.command("ok.py"))], "--jobs", value) + def test_child_sees_eof_even_when_the_runner_has_input(self): (self.artifact / "stdin.py").write_text( "import sys\nassert sys.stdin.read() == ''\n", encoding="utf-8", newline="\n")