Debian Codegraph @

tests/__init__.py

raw
1 #!/usr/bin/env python3
2 #
3 # SPDX-License-Identifier: LGPL-2.1-or-later
4 #
5 # This file is formatted with Python Black
6
7 from dbus.mainloop.glib import DBusGMainLoop
8 from gi.repository import GLib, Gio
9 from itertools import count
10 from typing import Any, Dict, Optional, NamedTuple, Callable, List
11
12 import os
13 import dbus
14 import dbus.proxies
15 import dbusmock
16 import logging
17 import subprocess
18
19
20 DBusGMainLoop(set_as_default=True)
21
22 # Anything that takes longer than 5s needs to fail
23 DBUS_TIMEOUT = int(os.environ.get("XDP_DBUS_TIMEOUT", "5000"))
24
25 _counter = count()
26
27 ASV = Dict[str, Any]
28
29
30 def init_logger(name: str) -> logging.Logger:
31 """
32 Common logging setup for tests. Use as:
33
34 >>> import tests as xdp
35 >>> logger = xdp.init_logger(__name__)
36 >>> logger.debug("foo")
37
38 """
39 logging.basicConfig(
40 format="%(levelname).1s|%(name)s: %(message)s", level=logging.DEBUG
41 )
42 logger = logging.getLogger(f"xdp.{name}")
43 logger.setLevel(logging.DEBUG)
44 return logger
45
46
47 logger = init_logger("utils")
48
49
50 def is_in_ci() -> bool:
51 return os.environ.get("XDP_TEST_IN_CI") is not None
52
53
54 def is_in_container() -> bool:
55 return is_in_ci() or (
56 "container" in os.environ
57 and (os.environ["container"] == "docker" or os.environ["container"] == "podman")
58 )
59
60
61 def run_long_tests() -> bool:
62 return os.environ.get("XDP_TEST_RUN_LONG") is not None
63
64
65 def check_program_success(cmd) -> bool:
66 proc = subprocess.Popen(
67 cmd, stdout=None, stderr=None, shell=True, universal_newlines=True
68 )
69 _ = proc.communicate()
70 return proc.returncode == 0
71
72
73 class FuseNotSupportedException(Exception):
74 pass
75
76
77 def ensure_fuse_supported() -> None:
78 if not check_program_success("fusermount3 --version"):
79 raise FuseNotSupportedException("no fusermount3")
80
81 if not check_program_success(
82 "capsh --print | grep -q 'Bounding set.*[^a-z]cap_sys_admin'"
83 ):
84 raise FuseNotSupportedException(
85 "No cap_sys_admin in bounding set, can't use FUSE"
86 )
87
88 if not check_program_success("[ -w /dev/fuse ]"):
89 raise FuseNotSupportedException("no write access to /dev/fuse")
90
91 if not check_program_success("[ -e /etc/mtab ]"):
92 raise FuseNotSupportedException("no /etc/mtab")
93
94
95 def wait(ms: int):
96 """
97 Waits for the specified amount of milliseconds.
98 """
99 mainloop = GLib.MainLoop()
100 GLib.timeout_add(ms, mainloop.quit)
101 mainloop.run()
102
103
104 def wait_for(fn: Callable[[], bool]):
105 """
106 Waits and dispatches to mainloop until the function fn returns true. This is
107 useful in combination with a lambda which captures a variable:
108
109 my_var = False
110 def callback():
111 my_var = True
112 do_something_later(callback)
113 xdp.wait_for(lambda: my_var)
114 """
115 mainloop = GLib.MainLoop()
116 while not fn():
117 GLib.timeout_add(50, mainloop.quit)
118 mainloop.run()
119
120
121 def get_permission_store_iface(bus: dbus.Bus) -> dbus.Interface:
122 """
123 Returns the dbus interface of the xdg-permission-store.
124 """
125 obj = bus.get_object(
126 "org.freedesktop.impl.portal.PermissionStore",
127 "/org/freedesktop/impl/portal/PermissionStore",
128 )
129 return dbus.Interface(obj, "org.freedesktop.impl.portal.PermissionStore")
130
131
132 def get_document_portal_iface(bus: dbus.Bus) -> dbus.Interface:
133 """
134 Returns the dbus interface of the xdg-document-portal.
135 """
136 obj = bus.get_object(
137 "org.freedesktop.portal.Documents",
138 "/org/freedesktop/portal/documents",
139 )
140 return dbus.Interface(obj, "org.freedesktop.portal.Documents")
141
142
143 def get_mock_iface(bus: dbus.Bus, bus_name: Optional[str] = None) -> dbus.Interface:
144 """
145 Returns the mock interface of the xdg-desktop-portal.
146 """
147 if not bus_name:
148 bus_name = "org.freedesktop.impl.portal.Test"
149
150 obj = bus.get_object(bus_name, "/org/freedesktop/portal/desktop")
151 return dbus.Interface(obj, dbusmock.MOCK_IFACE)
152
153
154 def portal_interface_name(portal_name: str, domain: Optional[str] = None) -> str:
155 """
156 Returns the fully qualified interface for a portal name.
157 """
158 if domain:
159 return f"org.freedesktop.{domain}.portal.{portal_name}"
160 else:
161 return f"org.freedesktop.portal.{portal_name}"
162
163
164 def get_portal_iface(
165 bus: dbus.Bus, name: str, domain: Optional[str] = None
166 ) -> dbus.Interface:
167 """
168 Returns the dbus interface for a portal name.
169 """
170 name = portal_interface_name(name, domain)
171 return get_iface(bus, name)
172
173
174 def get_iface(bus: dbus.Bus, name: str) -> dbus.Interface:
175 """
176 Returns a named interface of the main portal object.
177 """
178 try:
179 ifaces = bus._xdp_portal_ifaces
180 except AttributeError:
181 ifaces = bus._xdp_portal_ifaces = {}
182
183 try:
184 intf = ifaces[name]
185 except KeyError:
186 intf = dbus.Interface(get_xdp_dbus_object(bus), name)
187 assert intf
188 ifaces[name] = intf
189 return intf
190
191
192 def get_xdp_dbus_object(bus: dbus.Bus) -> dbus.proxies.ProxyObject:
193 """
194 Returns the main portal object.
195 """
196 try:
197 obj = getattr(bus, "_xdp_dbus_object")
198 except AttributeError:
199 obj = bus.get_object(
200 "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop"
201 )
202 assert obj
203 bus._xdp_dbus_object = obj
204 return obj
205
206
207 def check_version(bus: dbus.Bus, portal_name: str, expected_version: int):
208 """
209 Checks that the portal_name portal version is equal to expected_version.
210 """
211 properties_intf = dbus.Interface(
212 get_xdp_dbus_object(bus), "org.freedesktop.DBus.Properties"
213 )
214 portal_iface_name = portal_interface_name(portal_name)
215 try:
216 portal_version = properties_intf.Get(portal_iface_name, "version")
217 assert int(portal_version) == expected_version
218 except dbus.exceptions.DBusException as e:
219 logger.critical(e)
220 assert e is None, str(e)
221
222
223 class Response(NamedTuple):
224 """
225 Response as returned by a completed :class:`Request`
226 """
227
228 response: int
229 results: ASV
230
231
232 class ResponseTimeout(Exception):
233 """
234 Exception raised by :meth:`Request.call` if the Request did not receive a
235 Response in time.
236 """
237
238 pass
239
240
241 class Closable:
242 """
243 Parent class for both Session and Request. Both of these have a Close()
244 method.
245 """
246
247 def __init__(self, bus: dbus.Bus, objpath: str):
248 self.objpath = objpath
249 # GLib makes assertions in callbacks impossible, so we wrap all
250 # callbacks into a try: except and store the error on the request to
251 # be raised later when we're back in the main context
252 self.error: Optional[Exception] = None
253
254 self._mainloop: Optional[GLib.MainLoop] = None
255 self._impl_closed = False
256 self._bus = bus
257
258 self._closable = type(self).__name__
259 assert self._closable in ("Request", "Session")
260 proxy = bus.get_object("org.freedesktop.portal.Desktop", objpath)
261 self._closable_interface = dbus.Interface(
262 proxy, f"org.freedesktop.portal.{self._closable}"
263 )
264
265 @property
266 def bus(self) -> dbus.Bus:
267 return self._bus
268
269 @property
270 def closed(self) -> bool:
271 """
272 True if the impl.portal was closed
273 """
274 return self._impl_closed
275
276 def close(self) -> None:
277 signal_match = None
278
279 def cb_impl_closed_by_portal(handle) -> None:
280 if handle == self.objpath:
281 logger.debug(f"Impl{self._closable} {self.objpath} was closed")
282 signal_match.remove() # type: ignore
283 self._impl_closed = True
284 if self.closed and self._mainloop:
285 self._mainloop.quit()
286
287 # See :class:`ImplRequest`, this signal is a side-channel for the
288 # impl.portal template to notify us when the impl.Request was really
289 # closed by the portal.
290 signal_match = self._bus.add_signal_receiver(
291 cb_impl_closed_by_portal,
292 f"{self._closable}Closed",
293 dbus_interface="org.freedesktop.impl.portal.Mock",
294 )
295
296 logger.debug(f"Closing {self._closable} {self.objpath}")
297 self._closable_interface.Close()
298
299 def schedule_close(self, timeout_ms=300):
300 """
301 Schedule an automatic Close() on the given timeout in milliseconds.
302 """
303 assert 0 < timeout_ms < DBUS_TIMEOUT
304 GLib.timeout_add(timeout_ms, self.close)
305
306
307 class Request(Closable):
308 """
309 Helper class for executing methods that use Requests. This calls takes
310 care of subscribing to the signals and invokes the method on the
311 interface with the expected behaviors. A typical invocation is:
312
313 >>> response = Request(connection, interface).call("Foo", bar="bar")
314 >>> assert response.response == 0
315
316 Requests can only be used once, to call a second method you must
317 instantiate a new Request object.
318 """
319
320 def __init__(self, bus: dbus.Bus, interface: dbus.Interface):
321 def sanitize(name):
322 return name.lstrip(":").replace(".", "_")
323
324 sender_token = sanitize(bus.get_unique_name())
325 self._handle_token = f"request{next(_counter)}"
326 self.handle = f"/org/freedesktop/portal/desktop/request/{sender_token}/{self._handle_token}"
327 # The Closable
328 super().__init__(bus, self.handle)
329
330 self.interface = interface
331 self.response: Optional[Response] = None
332 self.used = False
333 # GLib makes assertions in callbacks impossible, so we wrap all
334 # callbacks into a try: except and store the error on the request to
335 # be raised later when we're back in the main context
336 self.error: Optional[Exception] = None
337
338 proxy = bus.get_object("org.freedesktop.portal.Desktop", self.handle)
339 self.mock_interface = dbus.Interface(proxy, dbusmock.MOCK_IFACE)
340 self._proxy = bus.get_object("org.freedesktop.portal.Desktop", self.handle)
341
342 def cb_response(response: int, results: ASV) -> None:
343 try:
344 logger.debug(f"Response received on {self.handle}")
345 assert self.response is None
346 self.response = Response(response, results)
347 if self._mainloop:
348 self._mainloop.quit()
349 except Exception as e:
350 self.error = e
351
352 self.request_interface = dbus.Interface(proxy, "org.freedesktop.portal.Request")
353 self.request_interface.connect_to_signal("Response", cb_response)
354
355 @property
356 def handle_token(self) -> dbus.String:
357 """
358 Returns the dbus-ready handle_token, ready to be put into the options
359 """
360 return dbus.String(self._handle_token, variant_level=1)
361
362 def call(self, methodname: str, **kwargs) -> Optional[Response]:
363 """
364 Semi-synchronously call method ``methodname`` on the interface given
365 in the Request's constructor. The kwargs must be specified in the
366 order the DBus method takes them but the handle_token is automatically
367 filled in.
368
369 >>> response = Request(connection, interface).call("Foo", bar="bar")
370 >>> if response.response != 0:
371 ... print("some error occured")
372
373 The DBus call itself is asynchronous (required for signals to work)
374 but this method does not return until the Response is received, the
375 Request is closed or an error occurs. If the Request is closed, the
376 Response is None.
377
378 If the "reply_handler" and "error_handler" keywords are present, those
379 callbacks are called just like they would be as dbus.service.ProxyObject.
380 """
381 assert not self.used
382 self.used = True
383
384 # Make sure options exists and has the handle_token set
385 try:
386 options = kwargs["options"]
387 except KeyError:
388 options = dbus.Dictionary({}, signature="sv")
389
390 if "handle_token" not in options:
391 options["handle_token"] = self.handle_token
392
393 # Anything that takes longer than 5s needs to fail
394 self._mainloop = GLib.MainLoop()
395 GLib.timeout_add(DBUS_TIMEOUT, self._mainloop.quit)
396
397 method = getattr(self.interface, methodname)
398 assert method
399
400 reply_handler = kwargs.pop("reply_handler", None)
401 error_handler = kwargs.pop("error_handler", None)
402
403 # Handle the normal method reply which returns is the Request object
404 # path. We don't exit the mainloop here, we're waiting for either the
405 # Response signal on the Request itself or the Close() handling
406 def reply_cb(handle):
407 try:
408 logger.debug(f"Reply to {methodname} with {self.handle}")
409 assert handle == self.handle
410
411 if reply_handler:
412 reply_handler(handle)
413 except Exception as e:
414 self.error = e
415
416 # Handle any exceptions during the actual method call (not the Request
417 # handling itself). Can exit the mainloop if that happens
418 def error_cb(error):
419 try:
420 logger.debug(f"Error after {methodname} with {error}")
421 if error_handler:
422 error_handler(error)
423 self.error = error
424 except Exception as e:
425 self.error = e
426 finally:
427 if self._mainloop:
428 self._mainloop.quit()
429
430 # Method is invoked async, otherwise we can't mix and match signals
431 # and other calls. It's still sync as seen by the caller in that we
432 # have a mainloop that waits for us to finish though.
433 method(
434 *list(kwargs.values()),
435 reply_handler=reply_cb,
436 error_handler=error_cb,
437 )
438
439 self._mainloop.run()
440
441 if self.error:
442 raise self.error
443 elif not self.closed and self.response is None:
444 raise ResponseTimeout(f"Timed out waiting for response from {methodname}")
445
446 return self.response
447
448
449 class Session(Closable):
450 """
451 Helper class for a Session created by a portal. This class takes care of
452 subscribing to the `Closed` signals. A typical invocation is:
453
454 >>> response = Request(connection, interface).call("CreateSession")
455 >>> session = Session.from_response(response)
456 # Now run the main loop and do other stuff
457 # Check if the session was closed
458 >>> if session.closed:
459 ... pass
460 # or close the session explicitly
461 >>> session.close() # to close the session or
462 """
463
464 def __init__(self, bus: dbus.Bus, handle: str):
465 assert handle
466 super().__init__(bus, handle)
467
468 self.handle = handle
469 self.details = None
470 # GLib makes assertions in callbacks impossible, so we wrap all
471 # callbacks into a try: except and store the error on the request to
472 # be raised later when we're back in the main context
473 self.error = None
474 self._closed_sig_received = False
475
476 def cb_closed(details: ASV) -> None:
477 try:
478 logger.debug(f"Session.Closed received on {self.handle}")
479 assert not self._closed_sig_received
480 self._closed_sig_received = True
481 self.details = details
482 if self._mainloop:
483 self._mainloop.quit()
484 except Exception as e:
485 self.error = e
486
487 proxy = bus.get_object("org.freedesktop.portal.Desktop", handle)
488 self.session_interface = dbus.Interface(proxy, "org.freedesktop.portal.Session")
489 self.session_interface.connect_to_signal("Closed", cb_closed)
490
491 @property
492 def closed(self):
493 """
494 Returns True if the session was closed by the backend
495 """
496 return self._closed_sig_received or super().closed
497
498 @classmethod
499 def from_response(cls, bus: dbus.Bus, response: Response) -> "Session":
500 return cls(bus, response.results["session_handle"])
501
502
503 class GDBusIfaceSignal:
504 """
505 Helper class which represents a connected signal on a GDBusIface and can be
506 used to disconnect from the signal.
507 """
508
509 def __init__(self, signal_id: int, proxy: Gio.DBusProxy):
510 self.signal_id = signal_id
511 self.proxy = proxy
512
513 def disconnect(self):
514 """
515 Disconnects the signal
516 """
517 self.proxy.disconnect(self.signal_id)
518
519
520 class GDBusIface:
521 """
522 Helper class for calling dbus interfaces with complex arguments.
523 Usually you want to use python-dbus on the dbus_con fixture with
524 get_portal_iface , get_mock_iface or get_iface. This is convenient but
525 might not be sufficient for complex arguments or for asynchronously calling
526 a method.
527 """
528
529 def __init__(self, bus: str, obj: str, iface: str):
530 """
531 Creates a GDBusIface for a specific bus, object and interface on the
532 session bus.
533 """
534 address = Gio.dbus_address_get_for_bus_sync(Gio.BusType.SESSION, None)
535 session_bus = Gio.DBusConnection.new_for_address_sync(
536 address,
537 Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT
538 | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION,
539 None,
540 None,
541 )
542 assert session_bus
543 self._proxy = Gio.DBusProxy.new_sync(
544 session_bus,
545 Gio.DBusProxyFlags.NONE,
546 None,
547 bus,
548 obj,
549 iface,
550 None,
551 )
552
553 def _call(
554 self, method_name: str, args_variant: GLib.Variant, fds: List[int] = []
555 ) -> GLib.Variant:
556 """
557 Calls a method synchronously with the arguments passed in args_variant,
558 passing the file descriptors specified in fds.
559 Returns the result of the dbus call.
560 """
561 fdlist = Gio.UnixFDList.new()
562 for fd in fds:
563 fdlist.append(fd)
564
565 return self._proxy.call_with_unix_fd_list_sync(
566 method_name,
567 args_variant,
568 0,
569 -1,
570 fdlist,
571 None,
572 )
573
574 def _call_async(
575 self,
576 method_name: str,
577 args_variant: GLib.Variant,
578 fds: List[int] = [],
579 cb: Optional[Callable[[GLib.Variant], None]] = None,
580 ) -> None:
581 """
582 Calls a method asynchronously with the arguments passed in args_variant,
583 passing the file descriptors specified in fds.
584 Invokes the callback cb when the call finished.
585 """
586 fdlist = Gio.UnixFDList.new()
587 for fd in fds:
588 fdlist.append(fd)
589
590 def internal_cb(s, res, _):
591 res = s.call_finish(res)
592 if cb:
593 cb(res)
594
595 self._proxy.call_with_unix_fd_list(
596 method_name,
597 args_variant,
598 0,
599 -1,
600 fdlist,
601 None,
602 internal_cb,
603 None,
604 )
605
606 def connect_to_signal(
607 self, name: str, cb: Callable[[GLib.Variant], None]
608 ) -> GDBusIfaceSignal:
609 """
610 Connects to the dbus signal name to the callback cb. Returns an object
611 representing the connection which can be used to disconnect it again.
612 """
613
614 def internal_cb(proxy, sender_name, signal_name, parameters):
615 if signal_name != name:
616 return
617 cb(parameters)
618
619 signal_id = self._proxy.connect("g-signal", internal_cb)
620 return GDBusIfaceSignal(signal_id, self._proxy)