Debian Codegraph @

tests/integration_tests/dbus_fixtures.py

raw
1 # Orca
2 #
3 # Copyright 2025 Valve Corporation
4 # Author: Joanmarie Diggs <[email protected]>
5 #
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License, or (at your option) any later version.
10 #
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the
18 # Free Software Foundation, Inc., Franklin Street, Fifth Floor,
19 # Boston MA 02110-1301 USA.
20
21 # pylint: disable=unused-argument
22
23 """D-Bus fixtures for integration tests."""
24
25 import os
26 import threading
27 from collections.abc import Callable
28 from typing import Any
29
30 import pytest
31 from dasbus.connection import SessionMessageBus
32 from dasbus.error import DBusError
33
34
35 @pytest.fixture(scope="session", name="dbus_service_proxy")
36 def _dbus_service_proxy() -> Any:
37 """Get a dasbus proxy for the main Orca service."""
38
39 try:
40 bus = SessionMessageBus()
41 proxy = bus.get_proxy("org.gnome.Orca.Service", "/org/gnome/Orca/Service")
42 proxy.GetVersion()
43 return proxy
44 except (DBusError, AttributeError, TypeError) as error:
45 pytest.skip(f"Orca D-Bus service not available: {error!s}")
46 return None
47
48
49 @pytest.fixture(scope="session", name="module_proxy_factory")
50 def _module_proxy_factory(dbus_service_proxy: Any) -> Callable[[str], Any]:
51 """Factory for creating module-specific D-Bus proxies."""
52
53 def _create_proxy(module_name: str):
54 # If we got here, dbus_service_proxy succeeded, so Orca is running
55 try:
56 bus = SessionMessageBus()
57 return bus.get_proxy("org.gnome.Orca.Service", f"/org/gnome/Orca/Service/{module_name}")
58 except (DBusError, AttributeError, TypeError) as error:
59 pytest.skip(f"Could not create proxy for {module_name}: {error!s}")
60 return None
61
62 return _create_proxy
63
64
65 @pytest.fixture(name="dbus_timeout")
66 def dbus_timeout_fixture() -> int:
67 """Default timeout for D-Bus operations (configurable via environment)."""
68
69 return int(os.environ.get("ORCA_DBUS_TIMEOUT", "5"))
70
71
72 @pytest.fixture
73 def run_with_timeout(
74 dbus_timeout: int,
75 ) -> Callable[[Callable[[], Any], int | None], dict[str, Any]]:
76 """Run a test function with timeout handling using threading (thread-safe)."""
77
78 def _run_test(test_func: Callable[[], Any], timeout: int | None = None) -> dict[str, Any]:
79 timeout_value = timeout if timeout is not None else dbus_timeout
80
81 result_container = {}
82 exception_container = {}
83
84 def target():
85 """Target function to run in the thread."""
86 try:
87 result = test_func()
88 result_container["result"] = result
89 except (DBusError, AttributeError, TypeError, ValueError) as error:
90 exception_container["error"] = error
91
92 thread = threading.Thread(target=target)
93 thread.daemon = True # Allow program to exit even if thread is still running
94 thread.start()
95 thread.join(timeout_value if timeout_value > 0 else None)
96
97 if thread.is_alive():
98 # Thread is still running, so it timed out
99 return {
100 "success": False,
101 "result": None,
102 "error": f"TIMEOUT: Test timed out after {timeout_value} seconds",
103 }
104
105 if "error" in exception_container:
106 error = exception_container["error"]
107 if isinstance(error, (DBusError, AttributeError, TypeError, ValueError)):
108 return {"success": False, "result": None, "error": str(error)}
109 # Re-raise unexpected exceptions
110 raise error
111
112 return {"success": True, "result": result_container.get("result"), "error": None}
113
114 return _run_test