| 1 |
# SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 |
# |
| 3 |
# This file is formatted with Python Black |
| 4 |
|
| 5 |
from typing import Callable, Dict, Optional, NamedTuple |
| 6 |
from gi.repository import GLib |
| 7 |
import dbus |
| 8 |
import dbusmock |
| 9 |
import logging |
| 10 |
|
| 11 |
|
| 12 |
def init_logger(name: str) -> logging.Logger: |
| 13 |
""" |
| 14 |
Common logging setup for the impl.portal templates. Use as: |
| 15 |
|
| 16 |
>>> from tests.templates import init_logger |
| 17 |
>>> logger = init_logger(__name__) |
| 18 |
>>> logger.debug("foo") |
| 19 |
|
| 20 |
""" |
| 21 |
logging.basicConfig( |
| 22 |
format="%(levelname).1s|%(name)s: %(message)s", level=logging.DEBUG |
| 23 |
) |
| 24 |
logger = logging.getLogger(f"templates.{name}") |
| 25 |
logger.setLevel(logging.DEBUG) |
| 26 |
return logger |
| 27 |
|
| 28 |
|
| 29 |
logger = init_logger("utils") |
| 30 |
|
| 31 |
|
| 32 |
class Response(NamedTuple): |
| 33 |
response: int |
| 34 |
results: Dict |
| 35 |
|
| 36 |
|
| 37 |
class ImplRequest: |
| 38 |
""" |
| 39 |
Implementation of an ``org.freedesktop.impl.portal.Request`` object exposed |
| 40 |
on the object path ``handle``. |
| 41 |
|
| 42 |
The dbus method implementations need to be invoked asynchronously and the |
| 43 |
async callbacks must be passed in ``cb_success`` and ``cb_error``. |
| 44 |
|
| 45 |
The request either waits until it is closed by x-d-p (``wait_for_close``) or |
| 46 |
responds to the request (``respond``). |
| 47 |
""" |
| 48 |
|
| 49 |
def __init__( |
| 50 |
self, |
| 51 |
mock: dbusmock.DBusMockObject, |
| 52 |
busname: str, |
| 53 |
handle: str, |
| 54 |
logger: logging.Logger, |
| 55 |
cb_success: Callable, |
| 56 |
cb_error: Callable, |
| 57 |
): |
| 58 |
self.mock = mock |
| 59 |
bus = mock.connection |
| 60 |
proxy = bus.get_object(busname, handle) |
| 61 |
self.mock_interface = dbus.Interface(proxy, dbusmock.MOCK_IFACE) |
| 62 |
self.handle = handle |
| 63 |
self.logger = logger |
| 64 |
self.cb_success = cb_success |
| 65 |
self.cb_error = cb_error |
| 66 |
|
| 67 |
def respond( |
| 68 |
self, |
| 69 |
response: Callable | Response, |
| 70 |
delay: int = 0, |
| 71 |
done_cb: Callable | None = None, |
| 72 |
) -> None: |
| 73 |
def reply(): |
| 74 |
nonlocal response |
| 75 |
res = None |
| 76 |
logger.debug(f"Request {self.handle}: trying to reply") |
| 77 |
if callable(response): |
| 78 |
try: |
| 79 |
res = response() |
| 80 |
except Exception as e: |
| 81 |
logger.critical( |
| 82 |
f"Request {self.handle}: failed getting response: {e}" |
| 83 |
) |
| 84 |
self.cb_error(e) |
| 85 |
self._unexport() |
| 86 |
return |
| 87 |
else: |
| 88 |
res = response |
| 89 |
|
| 90 |
assert res |
| 91 |
logger.debug(f"Request {self.handle}: replying {res}") |
| 92 |
|
| 93 |
self.cb_success(res.response, res.results) |
| 94 |
self._unexport() |
| 95 |
|
| 96 |
if done_cb: |
| 97 |
done_cb() |
| 98 |
|
| 99 |
self._export() |
| 100 |
|
| 101 |
if delay > 0: |
| 102 |
logger.debug(f"Request {self.handle}: scheduling delay of {delay}ms") |
| 103 |
GLib.timeout_add(delay, reply) |
| 104 |
else: |
| 105 |
reply() |
| 106 |
|
| 107 |
def wait_for_close( |
| 108 |
self, |
| 109 |
close_callback: Callable | None = None, |
| 110 |
) -> None: |
| 111 |
def closed(): |
| 112 |
logger.debug(f"Request {self.handle}: closed") |
| 113 |
|
| 114 |
self.mock.EmitSignal( |
| 115 |
"org.freedesktop.impl.portal.Mock", |
| 116 |
"RequestClosed", |
| 117 |
"s", |
| 118 |
(self.handle,), |
| 119 |
) |
| 120 |
|
| 121 |
if close_callback: |
| 122 |
try: |
| 123 |
close_callback() |
| 124 |
except Exception as e: |
| 125 |
logger.critical( |
| 126 |
f"Request {self.handle}: failed running close callback: {e}" |
| 127 |
) |
| 128 |
self.cb_error(e) |
| 129 |
self._unexport() |
| 130 |
return |
| 131 |
|
| 132 |
response = Response(2, {}) |
| 133 |
self.cb_success(response.response, response.results) |
| 134 |
self._unexport() |
| 135 |
|
| 136 |
def cb_methodcall(name, args): |
| 137 |
if name == "Close": |
| 138 |
closed() |
| 139 |
|
| 140 |
self._export() |
| 141 |
|
| 142 |
logger.debug(f"Request {self.handle}: waiting for x-d-p to call close") |
| 143 |
self.mock_interface.connect_to_signal("MethodCalled", cb_methodcall) |
| 144 |
|
| 145 |
def _export(self): |
| 146 |
# In the future we can pass a class extending |
| 147 |
# dbusmock.mockobject.DBusMockObject as mock_class to avoid going |
| 148 |
# through the mock MethodCalled signal |
| 149 |
self.mock.AddObject( |
| 150 |
path=self.handle, |
| 151 |
interface="org.freedesktop.impl.portal.Request", |
| 152 |
properties={}, |
| 153 |
methods=[ |
| 154 |
( |
| 155 |
"Close", |
| 156 |
"", |
| 157 |
"", |
| 158 |
"", |
| 159 |
) |
| 160 |
], |
| 161 |
) |
| 162 |
|
| 163 |
def _unexport(self): |
| 164 |
self.mock.RemoveObject(self.handle) |
| 165 |
|
| 166 |
def __str__(self): |
| 167 |
return f"ImplRequest {self.handle}" |
| 168 |
|
| 169 |
|
| 170 |
class ImplSession: |
| 171 |
""" |
| 172 |
Implementation of a org.freedesktop.impl.portal.Session object. Do not |
| 173 |
instantiate this directly, instead use ``ImplSession.export()``. Typically |
| 174 |
like this: |
| 175 |
|
| 176 |
>>> s = ImplSession.export(mock, "org.freedesktop.impl.portal.Test", "/path/foo") |
| 177 |
|
| 178 |
Where the test or the backend implementation relies on the Closed() method |
| 179 |
of the ImplSession, provide a callback to be invoked. |
| 180 |
|
| 181 |
>>> r.export(close_callback=my_callback) |
| 182 |
|
| 183 |
Note that the latter only works if the test invokes methods |
| 184 |
asynchronously. |
| 185 |
|
| 186 |
.. attribute:: closed |
| 187 |
|
| 188 |
Set to True if the Close() method on the Session was invoked |
| 189 |
|
| 190 |
.. attribute:: handle |
| 191 |
|
| 192 |
The session's object path |
| 193 |
|
| 194 |
""" |
| 195 |
|
| 196 |
def __init__( |
| 197 |
self, |
| 198 |
mock: dbusmock.DBusMockObject, |
| 199 |
busname: str, |
| 200 |
handle: str, |
| 201 |
app_id: str, |
| 202 |
): |
| 203 |
self.mock = mock # the main mock object |
| 204 |
self.handle = handle |
| 205 |
self.app_id = app_id |
| 206 |
self.closed = False |
| 207 |
self._close_callback: Optional[Callable] = None |
| 208 |
|
| 209 |
self.mock_object: Optional[dbusmock.DBusMockObject] = None |
| 210 |
|
| 211 |
bus = mock.connection |
| 212 |
proxy = bus.get_object(busname, handle) |
| 213 |
mock_interface = dbus.Interface(proxy, dbusmock.MOCK_IFACE) |
| 214 |
|
| 215 |
# Register for the Close() call on the impl.Session. If it gets |
| 216 |
# called, use the side-channel SessionClosed signal so we can notify |
| 217 |
# the test that the impl.Session was actually closed by the |
| 218 |
# xdg-desktop-portal |
| 219 |
def cb_methodcall(name, args): |
| 220 |
if name == "Close": |
| 221 |
self.closed = True |
| 222 |
logger.debug(f"Session.Close() on {self.handle}") |
| 223 |
if self._close_callback: |
| 224 |
self._close_callback() |
| 225 |
self.mock.EmitSignal( |
| 226 |
"org.freedesktop.impl.portal.Mock", |
| 227 |
"SessionClosed", |
| 228 |
"s", |
| 229 |
(self.handle,), |
| 230 |
) |
| 231 |
self._unexport() |
| 232 |
|
| 233 |
mock_interface.connect_to_signal("MethodCalled", cb_methodcall) |
| 234 |
|
| 235 |
def export( |
| 236 |
self, |
| 237 |
close_callback: Optional[Callable] = None, |
| 238 |
) -> "ImplSession": |
| 239 |
""" |
| 240 |
Create the session on the bus. If ``close_callback`` is not None, that |
| 241 |
callback will be invoked in response to the Close() method called on |
| 242 |
this object. |
| 243 |
""" |
| 244 |
self.mock.AddObject( |
| 245 |
path=self.handle, |
| 246 |
interface="org.freedesktop.impl.portal.Session", |
| 247 |
properties={}, |
| 248 |
methods=[ |
| 249 |
( |
| 250 |
"Close", |
| 251 |
"", |
| 252 |
"", |
| 253 |
"", |
| 254 |
) |
| 255 |
], |
| 256 |
) |
| 257 |
# This is a bit awkward. We need our session's DBusMockObject for |
| 258 |
# EmitSignal of impl.portal.Session.Close. This is available in |
| 259 |
# dbusmock.get_object() since our template runs as part of the server. |
| 260 |
# |
| 261 |
# In theory, EmitSignal should work on self.mock_interface but |
| 262 |
# it doesn't and I can't figure out why. |
| 263 |
self.mock_object = dbusmock.get_object(self.handle) |
| 264 |
self._close_callback = close_callback |
| 265 |
return self |
| 266 |
|
| 267 |
def _unexport(self): |
| 268 |
self.mock.RemoveObject(path=self.handle) |
| 269 |
|
| 270 |
def close(self): |
| 271 |
""" |
| 272 |
Send out Closed signal and remove this session from the bus. |
| 273 |
""" |
| 274 |
assert self.mock_object is not None, "Session was never exported" |
| 275 |
logger.debug(f"Signal Session.Closed on {self.handle}") |
| 276 |
self.mock_object.EmitSignal( |
| 277 |
interface="org.freedesktop.impl.portal.Session", |
| 278 |
name="Closed", |
| 279 |
signature="", |
| 280 |
sigargs=(), |
| 281 |
) |
| 282 |
self.closed = True |
| 283 |
self._unexport() |
| 284 |
|
| 285 |
def __str__(self): |
| 286 |
return f"ImplSession {self.handle}" |