"""Native Qt tests on a private Windows desktop without switching desktops.""" import argparse import ctypes as ct from ctypes import wintypes as w from dataclasses import replace import hashlib import json import os from pathlib import Path import shutil import struct import subprocess import sys import tempfile from time import monotonic, sleep from uuid import uuid4 from zipfile import ZipFile ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) USER = ct.WinDLL("user32", use_last_error=True) KERNEL = ct.WinDLL("kernel32", use_last_error=True) def bind(dll, name, result, *args): fn = getattr(dll, name) fn.restype, fn.argtypes = result, args return fn class Startup(ct.Structure): _fields_ = [("cb", w.DWORD), ("reserved", w.LPWSTR), ("desktop", w.LPWSTR), ("title", w.LPWSTR)] + [(key, w.DWORD) for key in ( "x", "y", "width", "height", "cols", "rows", "fill", "flags")] + [ ("show", w.WORD), ("reserved2_size", w.WORD), ("reserved2", ct.c_void_p), ("stdin", w.HANDLE), ("stdout", w.HANDLE), ("stderr", w.HANDLE), ] class ProcessInfo(ct.Structure): _fields_ = [("process", w.HANDLE), ("thread", w.HANDLE), ("pid", w.DWORD), ("tid", w.DWORD)] def start_isolated(argv, desktop_name, timeout=210): create_desktop = bind(USER, "CreateDesktopW", w.HANDLE, w.LPCWSTR, w.LPCWSTR, ct.c_void_p, w.DWORD, w.DWORD, ct.c_void_p) close_desktop = bind(USER, "CloseDesktop", w.BOOL, w.HANDLE) desktop = create_desktop(desktop_name, None, None, 0, 0x01ff, None) if not desktop: raise ct.WinError(ct.get_last_error()) close = bind(KERNEL, "CloseHandle", w.BOOL, w.HANDLE) create = bind(KERNEL, "CreateProcessW", w.BOOL, w.LPCWSTR, w.LPWSTR, ct.c_void_p, ct.c_void_p, w.BOOL, w.DWORD, ct.c_void_p, w.LPCWSTR, ct.POINTER(Startup), ct.POINTER(ProcessInfo)) wait = bind(KERNEL, "WaitForSingleObject", w.DWORD, w.HANDLE, w.DWORD) status = bind(KERNEL, "GetExitCodeProcess", w.BOOL, w.HANDLE, ct.POINTER(w.DWORD)) terminate = bind(KERNEL, "TerminateProcess", w.BOOL, w.HANDLE, w.UINT) launch = Startup() launch.cb, launch.desktop = ct.sizeof(Startup), f"WinSta0\\{desktop_name}" process = ProcessInfo() try: command = ct.create_unicode_buffer(subprocess.list2cmdline(argv)) if not create(str(argv[0]), command, None, None, False, 0x08000000, None, str(ROOT), ct.byref(launch), ct.byref(process)): raise ct.WinError(ct.get_last_error()) try: if wait(process.process, timeout * 1000): terminate(process.process, 30) wait(process.process, 10_000) raise TimeoutError("Isolated Windows GUI test exceeded its time allowance") exit_code = w.DWORD() if not status(process.process, ct.byref(exit_code)): raise ct.WinError(ct.get_last_error()) return exit_code.value finally: close(process.thread) close(process.process) finally: close_desktop(desktop) def verify_desktop(expected): current_tid = bind(KERNEL, "GetCurrentThreadId", w.DWORD)() desk = bind(USER, "GetThreadDesktop", w.HANDLE, w.DWORD)(current_tid) get = bind(USER, "GetUserObjectInformationW", w.BOOL, w.HANDLE, ct.c_int, ct.c_void_p, w.DWORD, ct.POINTER(w.DWORD)) buf, required = ct.create_unicode_buffer(256), w.DWORD() if not get(desk, 2, buf, ct.sizeof(buf), ct.byref(required)) or buf.value != expected: raise RuntimeError("Application test is not on the requested private desktop") return buf.value def window_process(hwnd): pid = w.DWORD() thread = bind(USER, "GetWindowThreadProcessId", w.DWORD, w.HWND, ct.POINTER(w.DWORD))(hwnd, ct.byref(pid)) return thread, pid.value def run_frozen(exe, profile_root, output): from arm.config import ConfigStore, Settings, Target from arm.version import NAME, VERSION # Separate settings and logs for each run. Existing profiles stay untouched. appdir = profile_root / NAME env = dict(os.environ, LOCALAPPDATA=str(profile_root)) for key in ("PYTHONPATH", "QT_QPA_PLATFORM", "QT_SCALE_FACTOR"): env.pop(key, None) config = ConfigStore(appdir / "settings.json") if not config.path.is_file(): config.save(Settings(minimized=False, mode="Composite", targets=[ Target(name="Saved test profile", host="127.0.0.1", enabled=False, credential="test-reference") ])) original = config.path.read_bytes() find = bind(USER, "FindWindowW", w.HWND, w.LPCWSTR, w.LPCWSTR) visible = bind(USER, "IsWindowVisible", w.BOOL, w.HWND) post = bind(USER, "PostMessageW", w.BOOL, w.HWND, w.UINT, w.WPARAM, w.LPARAM) post_thread = bind(USER, "PostThreadMessageW", w.BOOL, w.DWORD, w.UINT, w.WPARAM, w.LPARAM) send = bind(USER, "SendMessageTimeoutW", ct.c_size_t, w.HWND, w.UINT, w.WPARAM, w.LPARAM, w.UINT, w.UINT, ct.POINTER(ct.c_size_t)) for iteration in range(2): with subprocess.Popen([str(exe)], env=env, cwd=exe.parent) as proc: try: deadline, hwnd = monotonic() + 25, None while monotonic() < deadline and proc.poll() is None: found = find(None, NAME) if found: thread, pid = window_process(found) if pid == proc.pid and visible(found): hwnd = found break sleep(.15) assert hwnd, f"Frozen application did not open its native window, exit {proc.poll()}" sleep(2.5) replacement = find(None, NAME) if replacement and window_process(replacement)[1] == proc.pid: hwnd = replacement assert proc.poll() is None, f"Frozen application exited before close, code {proc.returncode}" icon = ct.c_size_t() assert send(hwnd, 0x7f, 1, 0, 2, 2000, ct.byref(icon)) and icon.value, "Missing window icon" if not post(hwnd, 0x10, 0, 0): raise ct.WinError(ct.get_last_error()) sleep(.45) assert proc.poll() is None and not visible(hwnd), "Window close should leave tray running" assert post_thread(thread, 0x12, 0, 0), "Posting WM_QUIT failed" assert proc.wait(10) == 0 finally: if proc.poll() is None: proc.terminate() proc.wait(8) assert config.path.read_bytes() == original data = (appdir / "arm.log").read_text(encoding="utf-8") assert data.count(f"{NAME} {VERSION} starting") == iteration + 1 assert data.count(f"{NAME} stopped") == iteration + 1 assert all(word in data for word in ("Initializing provider CPU", "Initializing provider GPU")) assert " ERROR " not in data, data output["frozen_launches"] = 2 output["frozen_version"] = VERSION def verify_executable(path, version): import pefile from arm.branding import COPYRIGHT, ICON_SIZES, PUBLISHER pe = pefile.PE(str(path)) try: assert pe.FILE_HEADER.Machine == 0x8664 fields = next(node.StringTable[0].entries for block in pe.FileInfo for node in block if hasattr(node, "StringTable")) assert fields[b"CompanyName"].decode().strip() == PUBLISHER assert fields[b"LegalCopyright"].decode().strip() == COPYRIGHT assert fields[b"ProductVersion"].decode().strip() == version group = next(entry for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries if entry.id == 14) sizes = set() for ident in group.directory.entries: ref = ident.directory.entries[0].data.struct data = pe.get_data(ref.OffsetToData, ref.Size) count = struct.unpack_from(" 20 assert session.expanded.device.count() > 10 assert app.primaryScreen().availableGeometry().contains(session.popup.frameGeometry()) if not short: measure("expanded") session.expanded.close() assert not session.expanded.isVisible() and session.icons[LOCAL].isVisible() if not short: prefs, connections = SettingsDialog(session), ConnectionsDialog(session) prefs.show() connections.show() assert prefs.isVisible() and connections.isVisible() assert prefs.tabs.count() == 7 and connections.table.rowCount() == 0 prefs.close() connections.close() prefs.deleteLater() connections.deleteLater() with ExitStack() as stack: servers = [stack.enter_context(Fixture()) for _ in range(1 if short else 2)] targets = [] for i, server in enumerate(servers, 1): target = Target(name=f"Loopback {i}", host="127.0.0.1", port=server.port, username="tester", interval=2, timeout=6, tray=True) update_host_key(session.hosts, f"[127.0.0.1]:{server.port}", server.key) session.save_target(target, SECRET, False) targets.append(target) try: wait_for(lambda: session.dashboard.state(target.identifier) == Connection.ONLINE, 15) except AssertionError as exc: raise AssertionError(f"SSH fixture {i}: {server.connections} TCP sessions, " f"{len(server.commands)} commands, {server.samples} frames, " f"{session.dashboard.state(target.identifier)}") from exc assert "Connected" in menu.remote_entries[target.identifier].text() from arm.graphs import tray_icon with patch("arm.application.tray_icon", wraps=tray_icon) as draw: menu.remote_entries[target.identifier].trigger() assert draw.call_args.args[1] == target.identifier assert session.popup.selected_machine == target.identifier menu.local.trigger() session.popup.hide() if i == 1 and not short: measure("one_loopback_ssh") if not short: measure("two_loopback_ssh") session.apply(replace(session.settings, tray_mode="Separate", persistent=True)) assert set(session.icons) == {LOCAL, *(target.identifier for target in targets)} results["loopback_frame_counts"] = [server.samples for server in servers] for target in targets: session.collectors.disconnect(target.identifier) assert all(session.dashboard.state(t.identifier) == Connection.OFFLINE for t in targets) session.apply(replace(session.settings, tray_mode="Local", persistent=False)) if not short: measure("disconnected_remotes") session.apply(replace(session.settings, tray_mode="Consolidated")) assert len(session.icons) == 1 for target in list(session.settings.targets): session.remove_target(target) exit_action = next(action for action in next(iter(session.menus.values())).actions() if action.text().startswith("Exit Adaptive Resource Monitor")) QTimer.singleShot(0, exit_action.trigger) assert app.exec() == 0 finally: for target in list(session.settings.targets): session.remove_target(target) session.close() assert not session.collectors.workers data = (root / "arm.log").read_text(encoding="utf-8") assert "Adaptive Resource Monitor stopped" in data and " ERROR " not in data, data def child(args): result = {"desktop": verify_desktop(args.desktop)} try: if args.package: validate_packages(args.package, args.work, result, args.upgrade_from, args.captures) else: evaluate_app(args.work, result, args.short, args.captures) except Exception: import traceback result["traceback"] = traceback.format_exc() log = args.work / "app" / "arm.log" if log.is_file(): result["application_log"] = log.read_text(encoding="utf-8").splitlines()[-35:] for name in ("portable-profile", "installed-profile"): log = args.work / name / "Adaptive Resource Monitor" / "arm.log" if log.is_file(): result[name] = log.read_text(encoding="utf-8").splitlines()[-35:] return 1 finally: (args.work / "result.json").write_text(json.dumps(result, indent=2), encoding="utf-8") return 0 def parent(args): desktop = f"ARM_Validation_{uuid4().hex[:10]}" with tempfile.TemporaryDirectory(prefix="arm-desktop-test-") as directory: work = Path(directory) command = [sys.executable, str(Path(__file__).resolve()), "--desktop", desktop, "--work", str(work)] if args.package: command.extend(("--package", str(args.package.resolve()))) if args.upgrade_from: command.extend(("--upgrade-from", str(args.upgrade_from.resolve()))) if args.captures: command.extend(("--captures", str(args.captures.resolve(strict=True)))) if args.short: command.append("--short") exit_code = start_isolated(command, desktop) data = work / "result.json" if data.is_file(): print(data.read_text(encoding="utf-8")) elif exit_code == 0: raise RuntimeError("Isolated Windows process did not publish test evidence") staged = sum(path.stat().st_size for path in work.rglob("*") if path.is_file()) print(f"Isolated Windows test exit {exit_code}. Removed {staged:,} bytes of temporary QA data.") return exit_code if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--desktop") parser.add_argument("--work", type=Path) parser.add_argument("--package", type=Path) parser.add_argument("--upgrade-from", type=Path) parser.add_argument("--captures", type=Path) parser.add_argument("--short", action="store_true") args = parser.parse_args() if args.desktop: raise SystemExit(child(args)) raise SystemExit(parent(args))