Files
wine-access/orca/tests/integration_test.py
Devin PraterandClaude Opus 5.5 418f671066 Add Orca extension for Wine accessibility
Publish the Wine Access protocol on Orca’s service connection and manage helpers per active Wine prefix. Add presentation, dialog capture, documentation, and tests.

Preserve the Cthulhu default and shared helper code. Document the single-reader limit and verify Orca cleanup leaves Cthulhu-managed helpers alone. Retain integration artifacts on exceptional failures.

Validation: 45 Orca unit tests passed; 11 existing test-environment checks passed; version metadata checks, Python compilation, and staged whitespace checks passed. Full Wine integration and live speech/braille remain unverified here because MinGW, Xvfb, and Orca are unavailable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:42:13 -04:00

222 lines
10 KiB
Python

# SPDX-License-Identifier: LGPL-2.1-or-later
"""End-to-end test: real Wine, real wine-access helper, this extension's code.
Run from the repository root after building, inside a private display and bus:
dbus-run-session -- xvfb-run -a python3 orca/tests/integration_test.py --build-dir build
The extension's D-Bus interface and presenter are hosted under Orca's service
name with Orca's output replaced by a recorder. The extension's manager finds
the Wine prefix and launches the helper itself. Upstream's Notepad fixture
then drives actual Wine Notepad, and the controller fixture sends NVDA
Controller speech. Assertions check what Orca would have presented.
"""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "wine_access"))
from dasbus.connection import SessionMessageBus # noqa: E402
from gi.repository import GLib # noqa: E402
from manager import HelperManager # noqa: E402
from presenter import WineEvent, WineEventPresenter # noqa: E402
from review import DialogReader, gio_capture # noqa: E402
from service import INTERFACE, OBJECT_PATH, WineAccessInterface # noqa: E402
READER_ARGUMENTS = ["--reader", "orca", "--reader-path", OBJECT_PATH,
"--reader-interface", INTERFACE]
class RecordingOrca:
"""Stands in for the extension's Orca backend and records its output."""
def __init__(self, connection):
self.output = []
self.presenter = WineEventPresenter(
lambda message, interrupt: self.output.append(("present", message, interrupt)),
lambda text, inserted: self.output.append(("echo", text, inserted)),
GLib.timeout_add, GLib.source_remove)
self.dialogs = DialogReader(gio_capture(connection), self.presenter.present_after_focus)
def register_review(self, sender, path, version):
self.output.append(("review-registered", sender))
return self.dialogs.register(sender, path, version)
def review_focus(self, sender, window, focus, revision, title, role):
return self.dialogs.focus(sender, window, focus, revision, title, role)
def speak_text(self, text, interrupt):
self.output.append(("speak", text, interrupt))
return bool(text)
def cancel_speech(self):
self.output.append(("cancel",))
return True
def braille_message(self, text):
self.output.append(("braille", text))
return bool(text)
def present_event(self, *arguments):
return self.presenter.handle(WineEvent(*arguments))
def pump(seconds, until=lambda: False):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline and not until():
while GLib.MainContext.default().iteration(False):
pass
time.sleep(0.01)
def windows_path(path):
return "Z:" + str(path).replace("/", "\\")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--build-dir", default="build", type=Path)
args = parser.parse_args()
args.source = Path(__file__).resolve().parents[2]
build = args.build_dir.resolve()
args.helper = str(build / "wine-access.exe")
args.generated = build / "generated"
bus = SessionMessageBus()
orca = RecordingOrca(bus.connection)
bus.publish_object(OBJECT_PATH, WineAccessInterface(orca))
bus.register_service("org.gnome.Orca1.Service")
temporary = Path(tempfile.mkdtemp(prefix="orca-wine-access-"))
env = os.environ.copy()
env.update(WINEPREFIX=str(temporary / "prefix"), WINEDEBUG="-all",
WINEDLLOVERRIDES="mscoree,mshtml=")
env.pop("ORCA_WINE_ACCESS_MANAGED", None)
processes = []
manager = HelperManager(READER_ARGUMENTS, helper=args.helper,
log_directory=temporary / "logs")
# Only manage this test's prefix, never the user's own Wine programs.
own_prefix = os.path.realpath(env["WINEPREFIX"])
discover = manager.discover
manager.discover = lambda: {p: v for p, v in discover().items() if p == own_prefix}
failures = []
succeeded = False
print("Test files:", temporary, flush=True)
def check(condition, message):
print(("PASS: " if condition else "FAIL: ") + message)
if not condition:
failures.append(message)
try:
fixtures = {name: temporary / f"{name}-fixture.exe" for name in ("notepad", "controller")}
tests = args.source / "tests"
subprocess.run(["x86_64-w64-mingw32-gcc", "-Wall", "-mwindows", "-o", str(fixtures["notepad"]),
str(tests / "notepad_fixture.c"), "-luser32"], check=True)
# Like upstream's controller test: a client stub with an explicit binding.
idl = temporary / "nvdaController.idl"
idl.write_text((args.source / "nvdaController.idl").read_text().replace(
"\n uuid(", "\n implicit_handle(handle_t controllerBinding),\n uuid("))
subprocess.run(["widl", "--win64", "-c", "-o", str(temporary / "nvdaController_c.c"),
str(idl)], check=True)
subprocess.run(["x86_64-w64-mingw32-gcc", "-Wall", "-I" + str(temporary),
"-I" + str(args.generated), "-o", str(fixtures["controller"]),
str(tests / "controller_fixture.c"), "-lrpcrt4"], check=True)
subprocess.run(["wineboot", "-u"], env=env, check=True, timeout=120)
# An idle Wine program makes the prefix active before the fixtures run.
idle = subprocess.Popen(["wine", "cmd.exe"], env=env, stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
processes.append(idle)
prefix = os.path.realpath(env["WINEPREFIX"])
pump(20, lambda: (manager.poll(), prefix in manager.prefixes
and manager.prefixes[prefix].process is not None)[1])
state = manager.prefixes.get(prefix)
check(state is not None and state.process is not None,
"manager discovered the Wine prefix and started the helper")
if state is None or state.process is None:
return 1
pump(3)
check(state.process.poll() is None,
"helper accepted the extension's interface (introspection check passed)")
ready = temporary / "ready"
fixture_env = dict(env, WINE_ACCESS_FIXTURE_READY=windows_path(ready))
notepad = subprocess.Popen(["wine", str(fixtures["notepad"])], env=fixture_env)
processes.append(notepad)
pump(60, lambda: (manager.poll(), notepad.poll() is not None)[1])
pump(1)
check(notepad.returncode == 0, f"Notepad fixture finished ({notepad.returncode})")
echoes = [(text, inserted) for kind, text, inserted in
(o for o in orca.output if o[0] == "echo")]
typed = [text for text, inserted in echoes if inserted]
navigation = [text for text, inserted in echoes if not inserted]
presented = [o[1] for o in orca.output if o[0] == "present"]
check(typed == ["z", "z", "space", "new line"], f"typed characters echoed: {typed}")
for expected in ("e", "l", "beta", "Notepad second line", "N selected",
"N unselected", "N deleted"):
check(expected in navigation, f"editor feedback {expected!r}")
check(navigation.count("l") == 2, "repeated characters both presented")
check(any("Notepad" in message for message in presented),
f"window title presented: {[m for m in presented if 'Notepad' in m][:3]}")
for button in ("Yes", "No", "Cancel"):
check(any(message.startswith(button) for message in presented),
f"save dialog button {button!r} presented")
print("Presented:", presented)
check(any(o[0] == "review-registered" for o in orca.output),
"helper registered as a review provider")
buttons = [i for i, m in enumerate(presented) if m.startswith("Yes, button")]
message = presented[buttons[0] + 1] if buttons and buttons[0] + 1 < len(presented) else ""
check("untitled" in message.lower() or "save" in message.lower(),
f"save dialog message read after its button: {message!r}")
dialog_reads = [m for m in presented if m == message]
check(len(dialog_reads) == 1, "dialog message read once, not on every Tab")
before = len(orca.output)
controller = subprocess.Popen(["wine", str(fixtures["controller"])], env=env)
processes.append(controller)
pump(30, lambda: (manager.poll(), controller.poll() is not None)[1])
pump(1)
calls = orca.output[before:]
print("Controller calls:", calls)
check(controller.returncode == 0, "controller fixture got the expected replies, SSML 120 included")
check(("speak", "Controller speech", False) in calls, "NVDA speakText reached SpeakText")
check(("cancel",) in calls, "NVDA cancelSpeech reached CancelSpeech")
check(("braille", "Controller braille") in calls, "NVDA brailleMessage reached BrailleMessage")
check(state.process.poll() is None, "helper still running after both fixtures")
idle.stdin.close()
for process in processes:
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
subprocess.run(["wineserver", "-k"], env=env, timeout=30)
manager.prefixes[prefix].last_seen -= 60
manager.poll()
check(prefix not in manager.prefixes, "helper stopped once the prefix went idle")
succeeded = not failures
return 1 if failures else 0
finally:
manager.shutdown()
for process in processes:
if process.poll() is None:
process.kill()
subprocess.run(["wineserver", "-k"], env=env, timeout=30)
if not succeeded:
print("Logs and prefix kept in", temporary)
else:
shutil.rmtree(temporary, ignore_errors=True)
if __name__ == "__main__":
sys.exit(main())