#!/usr/bin/env python3 """Drive ia2_worker.exe against the Electron fixture and check its protocol. Run inside the same X display and wineserver as Electron (worker_session.sh does this). Prints PASS/FAIL lines and exits non-zero on any failure. """ import json import queue import subprocess import sys import threading import time TITLE = "Wine Access Electron Test" SECRET = "Zq7secret" # typed into the password field; must never appear in output failures = 0 allLines = [] def check(name, condition, detail=""): global failures if condition: print(f"PASS: {name}", flush=True) else: failures += 1 print(f"FAIL: {name} {detail}", flush=True) class Worker: def __init__(self, command): self.process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=open("worker.stderr.log", "wb")) self.messages = queue.Queue() self.nextRequestId = 1 threading.Thread(target=self._read, daemon=True).start() def _read(self): for raw in self.process.stdout: allLines.append(raw) try: self.messages.put(json.loads(raw)) except json.JSONDecodeError: self.messages.put({"type": "invalid-json", "raw": raw[:200]}) self.messages.put({"type": "eof"}) def receive(self, seconds): """All messages that arrive within the time limit.""" deadline = time.monotonic() + seconds received = [] while time.monotonic() < deadline: try: received.append(self.messages.get(timeout=max(0.01, deadline - time.monotonic()))) except queue.Empty: break return received def wait_for(self, predicate, seconds): deadline = time.monotonic() + seconds seen = [] while time.monotonic() < deadline: try: message = self.messages.get(timeout=max(0.01, deadline - time.monotonic())) except queue.Empty: break seen.append(message) if predicate(message): return message, seen return None, seen def request(self, op, **fields): requestId = self.nextRequestId self.nextRequestId += 1 message = {"type": "request", "requestId": requestId, "op": op, **fields} self.process.stdin.write((json.dumps(message, separators=(",", ":")) + "\n").encode()) self.process.stdin.flush() reply, seen = self.wait_for(lambda m: m.get("type") == "reply" and m.get("requestId") == requestId, 10) return reply, seen def walk(node): yield node for child in node.get("children", []): yield from walk(child) def find(root, predicate): return next((node for node in walk(root) if predicate(node)), None) def xdotool(*arguments): subprocess.run(["xdotool", *arguments], check=False, capture_output=True) def main(): worker = Worker(sys.argv[1:]) hello, _ = worker.wait_for(lambda m: m.get("type") == "hello", 40) check("hello received", hello is not None and hello.get("protocol") == 1, str(hello)) check("hello reports an X11 window", bool(hello and hello.get("x11Window")), str(hello)) tree, _ = worker.wait_for(lambda m: m.get("type") == "tree", 40) check("tree received", tree is not None) if tree is None: return 1 root = tree["root"] nodeCount = sum(1 for _ in walk(root)) check("tree has web content", nodeCount > 60, f"nodes={nodeCount}") ids = [node.get("id") for node in walk(root)] check("uniqueIDs are unique and non-zero", len(ids) == len(set(ids)) and 0 not in ids) userName = find(root, lambda n: n.get("msaaRole") == 42 and n.get("name") == "User name") password = find(root, lambda n: n.get("msaaRole") == 42 and n.get("name") == "Password") checkbox = find(root, lambda n: n.get("msaaRole") == 44) addButton = find(root, lambda n: n.get("msaaRole") == 43 and n.get("name") == "Add item") table = find(root, lambda n: n.get("msaaRole") == 24) emoji = find(root, lambda n: "Emoji" in (n.get("text") or "") and n.get("hyperlinks")) check("fixture objects found", all([userName, password, checkbox, addButton, table, emoji])) check("password node carries no text or value", password is not None and "text" not in password and "value" not in password) reply, _ = worker.request("boundary", id=emoji["id"], offset=0, granularity=1) check("word boundary at 0 is 0-6", reply and reply["ok"] and (reply["start"], reply["end"]) == (0, 6), str(reply)) reply, _ = worker.request("boundary", id=password["id"], offset=0, granularity=1) check("boundary on password is refused", reply and not reply["ok"], str(reply)) reply, _ = worker.request("extents", id=table["id"]) check("table extents returned", reply and reply["ok"] and len(reply["extents"]) == 4, str(reply)) reply, _ = worker.request("extents", id=123456789) check("unknown id reports gone", reply and not reply["ok"] and reply.get("gone"), str(reply)) reply, seen = worker.request("focus", id=userName["id"]) check("focus request succeeds", reply and reply["ok"], str(reply)) focus, more = worker.wait_for(lambda m: m.get("type") == "focus" and m.get("id") == userName["id"], 5) check("focus message names the input", focus and focus["id"] == userName["id"], str(focus)) xdotool("search", "--name", TITLE, "windowactivate", "--sync") xdotool("search", "--name", TITLE, "windowfocus", "--sync") xdotool("type", "--delay", "80", "abc") _, seen = worker.wait_for(lambda m: m.get("type") == "node" and m["node"].get("id") == userName["id"] and m["node"].get("text") == "abc", 8) typed = [m for m in seen if m.get("type") == "node" and m["node"].get("id") == userName["id"]] check("typing produced node updates ending in 'abc'", typed and typed[-1]["node"].get("text") == "abc", str([m["node"].get("text") for m in typed])) carets = [m for m in seen if m.get("type") == "caret" and m.get("id") == userName["id"]] extra = worker.receive(0.5) carets += [m for m in extra if m.get("type") == "caret" and m.get("id") == userName["id"]] check("caret messages end at 3", carets and carets[-1]["caret"] == 3, str(carets[-3:])) reply, seen = worker.request("setCaret", id=userName["id"], offset=1) caret, _ = worker.wait_for(lambda m: m.get("type") == "caret" and m.get("id") == userName["id"], 3) check("setCaret moves the caret to 1", reply and reply["ok"] and caret and caret["caret"] == 1, str(caret)) reply, _ = worker.request("setSelection", id=userName["id"], start=0, end=2) selection, _ = worker.wait_for(lambda m: m.get("type") in ("caret", "selection") and m.get("id") == userName["id"] and m.get("selection") == [0, 2], 3) check("setSelection selects 0-2", reply and reply["ok"] and selection is not None, str(reply)) reply, _ = worker.request("action", id=checkbox["id"], index=0) update, _ = worker.wait_for(lambda m: m.get("type") == "node" and m["node"].get("id") == checkbox["id"] and m["node"]["msaaStates"] & 0x10, 5) check("checkbox action checks it", reply and reply["ok"] and update is not None, str(reply)) reply, _ = worker.request("action", id=addButton["id"], index=0) _, seen = worker.wait_for(lambda m: m.get("type") == "subtree" and any( (n.get("name") or "").startswith("Item 2") for n in walk(m["node"])), 5) check("add item produces a subtree containing the new item", any(m.get("type") == "subtree" and any((n.get("name") or "").startswith("Item 2") for n in walk(m["node"])) for m in seen), str([m.get("type") for m in seen])) reply, _ = worker.request("scrollTo", id=table["id"], scrollType=2) layout, _ = worker.wait_for(lambda m: m.get("type") == "layout", 3) check("scrollTo produces a layout message", reply and reply["ok"] and layout is not None, str(reply)) reply, _ = worker.request("focus", id=password["id"]) worker.wait_for(lambda m: m.get("type") == "focus" and m.get("id") == password["id"], 5) xdotool("type", "--delay", "80", SECRET) seen = worker.receive(3) passwordUpdates = [m for m in seen if m.get("type") == "node" and m["node"].get("id") == password["id"]] check("typing into the password produces updates", len(passwordUpdates) > 0, str(len(passwordUpdates))) check("password updates report length only", passwordUpdates and all( "text" not in m["node"] and "value" not in m["node"] for m in passwordUpdates)) check("password length tracks typing", passwordUpdates and passwordUpdates[-1]["node"].get("textLength") == len(SECRET), str(passwordUpdates[-1]["node"].get("textLength") if passwordUpdates else None)) worker.process.stdin.close() try: worker.process.wait(timeout=10) check("worker exits when its input closes", True) except subprocess.TimeoutExpired: worker.process.kill() check("worker exits when its input closes", False) leaked = [line for line in allLines if SECRET.encode() in line] check("secret never appears in worker output", not leaked, f"{len(leaked)} lines") invalid = [line for line in allLines if not line.strip().startswith(b"{")] check("every output line is a JSON object", not invalid, str(invalid[:2])) with open("worker.stderr.log", "rb") as stderrFile: check("secret never appears in worker diagnostics", SECRET.encode() not in stderrFile.read()) print(f"messages={len(allLines)}") return 1 if failures else 0 if __name__ == "__main__": sys.exit(main())