From 320b12b34c2be74080bd6c1e2aed003e9edd1828 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 28 Oct 2026 19:33:26 -0700 Subject: [PATCH] feat(e2e): the new Platform members on the Windows guest spawn takes rename_to and after (the test window renames itself), temp_path, crash (kills the daemon), fullscreen and user_maximize (the user's own, by messages the window understands), with tests: a window that is not there raises, a program name Windows rejects is rejected. --- .../qemu_windows/tests/test_runner.py | 89 +++++++++++++++++++ .../qemu_windows/windows_platform.py | 83 ++++++++++++++++- 2 files changed, 170 insertions(+), 2 deletions(-) diff --git a/e2e/platforms/qemu_windows/tests/test_runner.py b/e2e/platforms/qemu_windows/tests/test_runner.py index 47bb9ac3..dadb322b 100644 --- a/e2e/platforms/qemu_windows/tests/test_runner.py +++ b/e2e/platforms/qemu_windows/tests/test_runner.py @@ -88,6 +88,26 @@ def test_a_step_wrapper_keeps_the_name_and_passes_keywords() -> None: assert step.__module__ == scenario.__module__ +def test_the_suite_keeps_how_long_each_step_took() -> None: + from komorebi_vm.core.suite import platform_only, shared + + def scenario() -> str: + return "opened" + + def extra() -> None: + return None + + checks = run.RecordedChecks() + results = run._suite(checks, shared(scenario), platform_only("windows", extra)) + + assert results == ["opened", None] + assert [s["step"] for s in checks.steps] == [ + "[shared] test_runner.scenario", + "[windows] test_runner.extra", + ] + assert all(isinstance(s["seconds"], float) for s in checks.steps) + + def test_the_state_key_follows_the_machine_and_not_the_run() -> None: first = state._machine() @@ -137,3 +157,72 @@ def test_the_result_file_names_a_known_json_shape(tmp_path: Path) -> None: checks.check("a", True) json.dumps(checks.results) + + +class _Agent: + """An agent that has one window and records what it is asked to run.""" + + def __init__(self, titles: list[str]) -> None: + self.titles = titles + self.spawned: list[tuple[str, ...]] = [] + self.executed: list[tuple[str, ...]] = [] + + def os_windows(self) -> list[dict]: + return [{"title": t, "hwnd": 7, "cloaked": False, + "frame": {"left": 0, "top": 0, "right": 1, "bottom": 1}} + for t in self.titles] + + def spawn(self, *args: str) -> None: + self.spawned.append(args) + + def exec(self, *args: str) -> dict: + self.executed.append(args) + return {"status": 0, "stdout": "", "stderr": ""} + + +def test_a_window_that_renames_itself_is_known_by_the_new_title() -> None: + agent = _Agent(["opens-as"]) + platform = WindowsPlatform(SimpleNamespace(), agent, Path(".")) + + client = platform.spawn("opens-as", rename_to="becomes", after=6) + + assert client.title == "becomes" + assert agent.spawned[0][-4:] == ("--rename-to", "becomes", "--after", "6") + + +def test_a_spawn_that_never_shows_raises() -> None: + platform = WindowsPlatform(SimpleNamespace(), _Agent([]), Path("."), scale=0.01) + + with pytest.raises(RuntimeError, match="no window titled 'ghost'"): + platform.spawn("ghost") + + +def test_a_program_name_windows_would_reject_is_rejected() -> None: + platform = WindowsPlatform(SimpleNamespace(), _Agent(["w"]), Path(".")) + + with pytest.raises(ValueError, match="not a program name"): + platform.spawn("w", exe="a b") + with pytest.raises(ValueError, match="not a program name"): + platform.spawn("w", exe="..\\evil") + + +def test_a_temp_path_is_in_the_guest_and_a_bad_name_is_rejected() -> None: + agent = _Agent([]) + platform = WindowsPlatform(SimpleNamespace(), agent, Path(".")) + + assert platform.temp_path("e2e-resize.json") == "C:\\e2e\\tmp\\e2e-resize.json" + with pytest.raises(ValueError): + platform.temp_path("..\\x") + + +def test_acting_on_a_window_that_is_not_there_raises_a_clear_error() -> None: + from komorebi_vm.core.platform import Client + + platform = WindowsPlatform(SimpleNamespace(), _Agent([]), Path(".")) + gone = Client("gone") + + for act in (platform.close, platform.minimize, platform.activate, + lambda c: platform.move_window(c, 1, 1), + platform.fullscreen, platform.user_maximize): + with pytest.raises(RuntimeError, match="no window titled 'gone'"): + act(gone) diff --git a/e2e/platforms/qemu_windows/windows_platform.py b/e2e/platforms/qemu_windows/windows_platform.py index 15c23f64..31be17d0 100644 --- a/e2e/platforms/qemu_windows/windows_platform.py +++ b/e2e/platforms/qemu_windows/windows_platform.py @@ -39,6 +39,12 @@ LAUNCHES = 3 POLICY_SYSTEM = "HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\System" # the account the image logs in to PASSWORD = "komorebi" +TEMP_DIR = "C:\\e2e\\tmp" +# the messages the test window and the title bar buttons understand +WM_FULLSCREEN = 0x8000 + 2 +WM_SYSCOMMAND = 0x0112 +SC_MAXIMIZE = 0xF030 +SC_RESTORE = 0xF120 DISPLAY_SCRIPT = "C:\\e2e\\display.ps1" CONFIG_PATH = "C:\\e2e\\komorebi.json" @@ -222,6 +228,71 @@ class WindowsPlatform: # the daemon watches the file it was started with and reads it again self._agent.put_file(local, CONFIG_PATH) + def temp_path(self, name: str) -> str: + if not re.fullmatch(r"[A-Za-z0-9_.-]+", name): + raise ValueError(f"not a file name: {name!r}") + self._agent.exec("cmd", "/c", f"mkdir {TEMP_DIR} 2>nul") + return f"{TEMP_DIR}\\{name}" + + def crash(self) -> None: + # a process that is killed puts nothing back: windows it cloaked stay so + self._agent.exec("taskkill", "/F", "/IM", "komorebi.exe") + if not self.wait_for(self._daemon_gone, timeout=20): + raise RuntimeError("komorebi did not go") + + def _daemon_gone(self) -> bool: + listing = self._agent.exec("tasklist", "/fi", "imagename eq komorebi.exe") + return "komorebi.exe" not in listing["stdout"] + + def _post(self, client: Client, message: int, wparam: int) -> int: + """Posts a message to the window and returns its handle.""" + window = self._find(client.title) + if window is None: + raise RuntimeError(f"no window titled {client.title!r}") + self._agent.exec( + "powershell", "-NoProfile", "-Command", + "Add-Type -Name P -Namespace K -MemberDefinition " + "'[DllImport(\"user32.dll\")] public static extern bool " + "PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);'; " + f"[void][K.P]::PostMessageW([IntPtr]{window['hwnd']}, {message}, " + f"[IntPtr]{wparam}, [IntPtr]::Zero)", + ) + return window["hwnd"] + + def fullscreen(self, client: Client, on: bool = True) -> None: + # the test window takes itself fullscreen on this message, borderless + # over its monitor, as a program's own key does + self._post(client, WM_FULLSCREEN, 1 if on else 0) + + def covers() -> bool: + window = self.os_window(client) + return window is not None and any( + window.frame == display for display in self.displays() + ) + + if not self.wait_for(lambda: covers() == on): + raise RuntimeError( + f"{client.title!r} did not go {'fullscreen' if on else 'back'}" + ) + + def user_maximize(self, client: Client, on: bool = True) -> None: + # what the maximize and restore buttons of the title bar send + hwnd = self._post(client, WM_SYSCOMMAND, SC_MAXIMIZE if on else SC_RESTORE) + + def zoomed() -> bool: + result = self._agent.exec( + "powershell", "-NoProfile", "-Command", + "Add-Type -Name Z -Namespace K -MemberDefinition " + "'[DllImport(\"user32.dll\")] public static extern bool " + f"IsZoomed(IntPtr h);'; [K.Z]::IsZoomed([IntPtr]{hwnd})", + ) + return result["stdout"].strip() == "True" + + if not self.wait_for(lambda: zoomed() == on): + raise RuntimeError( + f"{client.title!r} did not {'maximize' if on else 'restore'}" + ) + def resizable_display(self) -> int | None: """The index of a display whose mode can change: the second, which is a QXL display. The first is the basic display adapter, with one mode, and @@ -342,11 +413,19 @@ class WindowsPlatform: ) from e def spawn( - self, title: str, app_id: str | None = None, exe: str | None = None + self, + title: str, + app_id: str | None = None, + exe: str | None = None, + rename_to: str | None = None, + after: float = 0, ) -> Client: args = ["--title", title] if app_id is not None: args += ["--class", app_id] + if rename_to is not None: + # the window gives itself this title `after` seconds from now + args += ["--rename-to", rename_to, "--after", str(after)] program = f"{GUEST_BIN}\\komorebi-testwin.exe" if exe is not None: if not re.fullmatch(r"[A-Za-z0-9_-]+", exe): @@ -359,7 +438,7 @@ class WindowsPlatform: self._agent.spawn(program, *args) if not self.wait_for(lambda: self._find(title) is not None): raise RuntimeError(f"no window titled {title!r} appeared") - return Client(title) + return Client(rename_to if rename_to is not None else title) def _find(self, title: str) -> dict | None: for window in self._agent.os_windows():