Debian Codegraph @

tests/conftest.py

raw
1 # SPDX-License-Identifier: LGPL-2.1-or-later
2 #
3 # This file is formatted with Python Black
4
5 from typing import Any, Dict, Iterator, Optional
6 from types import ModuleType
7
8 import pytest
9 import dbus
10 import dbusmock
11 import os
12 import sys
13 import tempfile
14 import subprocess
15 import time
16 import signal
17 from pathlib import Path
18 from contextlib import chdir
19
20 import gi
21
22 gi.require_version("UMockdev", "1.0")
23 from gi.repository import UMockdev # noqa E402
24
25
26 def pytest_configure() -> None:
27 ensure_environment_set()
28 ensure_umockdev_loaded()
29
30
31 def pytest_sessionfinish(session, exitstatus):
32 # Meson and ginsttest-runner expect tests to exit with status 77 if all
33 # tests were skipped
34 if exitstatus == pytest.ExitCode.NO_TESTS_COLLECTED:
35 session.exitstatus = 77
36
37
38 def ensure_environment_set() -> None:
39 env_vars = [
40 "XDG_DESKTOP_PORTAL_PATH",
41 "XDG_PERMISSION_STORE_PATH",
42 "XDG_DOCUMENT_PORTAL_PATH",
43 ]
44
45 if not os.getenv("XDP_VALIDATE_AUTO"):
46 env_vars += [
47 "XDP_VALIDATE_ICON",
48 "XDP_VALIDATE_SOUND",
49 ]
50 else:
51 os.environ.pop("XDP_VALIDATE_ICON", None)
52 os.environ.pop("XDP_VALIDATE_SOUND", None)
53
54 for env_var in env_vars:
55 if not os.getenv(env_var):
56 raise Exception(f"{env_var} must be set")
57
58
59 def ensure_umockdev_loaded() -> None:
60 umockdev_preload = "libumockdev-preload.so"
61 preload = os.environ.get("LD_PRELOAD", "")
62 if umockdev_preload not in preload:
63 os.environ["LD_PRELOAD"] = f"{umockdev_preload}:{preload}"
64 os.execv(sys.executable, [sys.executable] + sys.argv)
65
66
67 def test_dir() -> Path:
68 return Path(__file__).resolve().parent
69
70
71 @pytest.fixture
72 def xdg_desktop_portal_path() -> Path:
73 return Path(os.environ["XDG_DESKTOP_PORTAL_PATH"])
74
75
76 @pytest.fixture
77 def xdg_permission_store_path() -> Path:
78 return Path(os.environ["XDG_PERMISSION_STORE_PATH"])
79
80
81 @pytest.fixture
82 def xdg_document_portal_path() -> Path:
83 return Path(os.environ["XDG_DOCUMENT_PORTAL_PATH"])
84
85
86 @pytest.fixture(autouse=True)
87 def create_test_dirs(umockdev: Optional[UMockdev.Testbed]) -> Iterator[None]:
88 # The umockdev argument is to make sure the testbed
89 # is created before we create the tmpdir
90 env_dirs = [
91 "HOME",
92 "TMPDIR",
93 "XDG_CACHE_HOME",
94 "XDG_CONFIG_HOME",
95 "XDG_DATA_HOME",
96 "XDG_RUNTIME_DIR",
97 "XDG_DESKTOP_PORTAL_DIR",
98 ]
99
100 test_root = tempfile.TemporaryDirectory(
101 prefix="xdp-testroot-", ignore_cleanup_errors=True
102 )
103
104 for env_dir in env_dirs:
105 directory = Path(test_root.name) / env_dir.lower()
106 directory.mkdir(mode=0o700, parents=True)
107 os.environ[env_dir] = directory.absolute().as_posix()
108
109 yield
110
111 test_root.cleanup()
112
113
114 @pytest.fixture
115 def xdg_data_home_files() -> Dict[str, bytes]:
116 """
117 Default fixture which can be used to create files in the temporary
118 XDG_DATA_HOME directory of the test.
119 """
120 return {}
121
122
123 @pytest.fixture(autouse=True)
124 def ensure_xdg_data_home(
125 create_test_dirs: Any, xdg_data_home_files: Dict[str, bytes]
126 ) -> None:
127 files = xdg_data_home_files
128 for name, content in files.items():
129 file_path = Path(os.environ["XDG_DATA_HOME"]) / name
130 file_path.parent.mkdir(parents=True, exist_ok=True)
131 with open(file_path.absolute().as_posix(), "wb") as f:
132 f.write(content)
133
134
135 @pytest.fixture
136 def xdg_desktop_portal_dir_files() -> Dict[str, bytes]:
137 """
138 Default fixture which can be used to create files in the temporary
139 XDG_DESKTOP_PORTAL_DIR directory of the test.
140 """
141 return {}
142
143
144 @pytest.fixture
145 def xdg_desktop_portal_dir_default_files() -> Dict[str, bytes]:
146 files = {}
147
148 portals = [
149 "org.freedesktop.impl.portal.Access",
150 "org.freedesktop.impl.portal.Account",
151 "org.freedesktop.impl.portal.AppChooser",
152 "org.freedesktop.impl.portal.Background",
153 "org.freedesktop.impl.portal.Clipboard",
154 "org.freedesktop.impl.portal.DynamicLauncher",
155 "org.freedesktop.impl.portal.Email",
156 "org.freedesktop.impl.portal.FileChooser",
157 "org.freedesktop.impl.portal.GlobalShortcuts",
158 "org.freedesktop.impl.portal.Inhibit",
159 "org.freedesktop.impl.portal.InputCapture",
160 "org.freedesktop.impl.portal.Lockdown",
161 "org.freedesktop.impl.portal.Notification",
162 "org.freedesktop.impl.portal.Print",
163 "org.freedesktop.impl.portal.RemoteDesktop",
164 "org.freedesktop.impl.portal.Screenshot",
165 "org.freedesktop.impl.portal.Settings",
166 "org.freedesktop.impl.portal.Usb",
167 "org.freedesktop.impl.portal.Wallpaper",
168 ]
169
170 files["test-portals.conf"] = b"""
171 [preferred]
172 default=test;
173 """
174
175 files["test.portal"] = """
176 [portal]
177 DBusName=org.freedesktop.impl.portal.Test
178 Interfaces={}
179 """.format(";".join(portals)).encode("utf-8")
180
181 return files
182
183
184 @pytest.fixture(autouse=True)
185 def ensure_xdg_desktop_portal_dir(
186 create_test_dirs: Any,
187 xdg_desktop_portal_dir_files: Dict[str, bytes],
188 xdg_desktop_portal_dir_default_files: Dict[str, bytes],
189 ) -> None:
190 files = xdg_desktop_portal_dir_default_files | xdg_desktop_portal_dir_files
191 for name, content in files.items():
192 file_path = Path(os.environ["XDG_DESKTOP_PORTAL_DIR"]) / name
193 file_path.parent.mkdir(parents=True, exist_ok=True)
194 with open(file_path.absolute().as_posix(), "wb") as f:
195 f.write(content)
196
197
198 @pytest.fixture(autouse=True)
199 def create_test_dbus() -> Iterator[dbusmock.DBusTestCase]:
200 bus = dbusmock.DBusTestCase()
201 bus.setUp()
202 bus.start_session_bus()
203 bus.start_system_bus()
204
205 yield bus
206
207 bus.tearDown()
208 bus.tearDownClass()
209
210
211 @pytest.fixture(autouse=True)
212 def create_dbus_monitor(create_test_dbus) -> Iterator[Optional[subprocess.Popen]]:
213 if not os.getenv("XDP_DBUS_MONITOR"):
214 yield None
215 return
216
217 dbus_monitor = subprocess.Popen(["dbus-monitor", "--session"])
218
219 yield dbus_monitor
220
221 dbus_monitor.terminate()
222 dbus_monitor.wait()
223
224
225 def _get_server_for_module(
226 busses: dict[dbusmock.BusType, dict[str, dbusmock.SpawnedMock]],
227 module: ModuleType,
228 bustype: dbusmock.BusType,
229 ) -> dbusmock.SpawnedMock:
230 assert bustype in dbusmock.BusType
231
232 try:
233 return busses[bustype][module.BUS_NAME]
234 except KeyError:
235 server = dbusmock.SpawnedMock.spawn_for_name(
236 module.BUS_NAME,
237 "/dbusmock",
238 dbusmock.OBJECT_MANAGER_IFACE,
239 bustype,
240 stdout=None,
241 stderr=None,
242 )
243
244 busses[bustype][module.BUS_NAME] = server
245 return server
246
247
248 def _get_main_obj_for_module(
249 server: dbusmock.SpawnedMock, module: ModuleType, bustype: dbusmock.BusType
250 ) -> dbusmock.DBusMockObject:
251 try:
252 server.obj.AddObject(
253 module.MAIN_OBJ,
254 "com.example.EmptyInterface",
255 {},
256 [],
257 dbus_interface=dbusmock.MOCK_IFACE,
258 )
259 except Exception:
260 pass
261
262 bustype.wait_for_bus_object(module.BUS_NAME, module.MAIN_OBJ)
263 bus = bustype.get_connection()
264 return bus.get_object(module.BUS_NAME, module.MAIN_OBJ)
265
266
267 def _terminate_mock_p(process: subprocess.Popen) -> None:
268 process.terminate()
269 process.wait()
270
271
272 def _terminate_servers(
273 busses: dict[dbusmock.BusType, dict[str, dbusmock.SpawnedMock]],
274 ) -> None:
275 for server in busses[dbusmock.BusType.SYSTEM].values():
276 _terminate_mock_p(server.process)
277 for server in busses[dbusmock.BusType.SESSION].values():
278 _terminate_mock_p(server.process)
279
280
281 def _start_template(
282 busses: dict[dbusmock.BusType, dict[str, dbusmock.SpawnedMock]],
283 template: str,
284 bus_name: Optional[str],
285 params: Dict[str, Any] = {},
286 ) -> None:
287 """
288 Start the template and potentially start a server for it
289 """
290 module_path_dir = (test_dir()).parent.absolute().as_posix()
291 template_path = test_dir() / f"templates/{template.lower()}.py"
292 template = template_path.absolute().as_posix()
293
294 # we cd to the parent dir of the test_dir so that the module search path for
295 # the templates is the same as opening the modules from here
296 with chdir(module_path_dir):
297 module = dbusmock.mockobject.load_module(template)
298 bustype = (
299 dbusmock.BusType.SYSTEM if module.SYSTEM_BUS else dbusmock.BusType.SESSION
300 )
301
302 if bus_name:
303 module.BUS_NAME = bus_name
304
305 server = _get_server_for_module(busses, module, bustype)
306 main_obj = _get_main_obj_for_module(server, module, bustype)
307
308 main_obj.AddTemplate(
309 template,
310 dbus.Dictionary(params, signature="sv"),
311 dbus_interface=dbusmock.MOCK_IFACE,
312 )
313
314
315 @pytest.fixture
316 def template_params() -> dict[str, dict[str, Any]]:
317 """
318 Default fixture for overriding the parameters which should be passed to the
319 mocking templates. Use required_templates to specify the default parameters
320 and override it for specific test cases via
321
322 @pytest.mark.parametrize("template_params", ({"Template": {"foo": "bar"}},))
323
324 """
325 return {}
326
327
328 @pytest.fixture
329 def required_templates() -> dict[str, dict[str, Any]]:
330 """
331 Default fixture for enumerating the mocking templates the test case requires
332 to be started. This is a map from a template spec to the parameters which
333 should be passed to the template. The template spec is the name of a
334 template in the templates directory and an optional dbus bus name to start
335 the template at, separated by a colon.
336
337 This starts the `settings` and `email` templates on the bus names specified
338 with BUS_NAME in the templates and passes parameters to settings.
339
340 {
341 "settings": {
342 "some_param": true,
343 },
344 "email": {},
345 }
346
347 This starts two instances of the settings template with their own parameters
348 once on the bus name specified in BUS_NAME in the template, and once on the
349 bus name `org.freedesktop.impl.portal.OtherImpl`.
350
351 {
352 "settings": {
353 "some_param": true,
354 },
355 "settings:org.freedesktop.impl.portal.OtherImpl": {
356 "some_param": false,
357 },
358 }
359
360 """
361 return {}
362
363
364 @pytest.fixture
365 def templates(
366 required_templates: dict[str, dict[str, Any]],
367 template_params: dict[str, dict[str, Any]],
368 ) -> Iterator[None]:
369 """
370 Fixture which starts the required templates with their parameters. Usually
371 the `portals` fixture is what you're looking for because it also starts
372 the portal frontend and the permission store.
373 """
374 busses: dict[dbusmock.BusType, dict[str, dbusmock.SpawnedMock]] = {
375 dbusmock.BusType.SYSTEM: {},
376 dbusmock.BusType.SESSION: {},
377 }
378 for template_data, params in required_templates.items():
379 template, bus_name = (template_data.split(":") + [None])[:2]
380 assert template
381 params = template_params.get(template, params)
382 _start_template(busses, template, bus_name, params)
383 yield
384 _terminate_servers(busses)
385
386
387 @pytest.fixture
388 def xdp_overwrite_env() -> dict[str, str]:
389 """
390 Default fixture which can be used to override the environment that gets
391 passed to xdg-desktop-portal, xdg-document-portal and xdg-permission-store.
392 """
393 return {}
394
395
396 @pytest.fixture
397 def app_id() -> str:
398 """
399 Default fixture which can be used to override the app id that the portal
400 frontend will discover for incoming connections.
401 """
402 return "org.example.Test"
403
404
405 @pytest.fixture
406 def xdp_env(
407 xdp_overwrite_env: dict[str, str],
408 app_id: str,
409 usb_queries: Optional[str],
410 umockdev: Optional[UMockdev.Testbed],
411 ) -> dict[str, str]:
412 env = os.environ.copy()
413 env["G_DEBUG"] = "fatal-criticals"
414 env["XDG_CURRENT_DESKTOP"] = "test"
415
416 # Workaround for the backport branch. The portal uses this as a signal
417 # to know that it's running in the tests. Specifically the trash portal
418 # needs this to get tested correctly.
419 env["XDG_DESKTOP_PORTAL_TEST_APP_INFO_KIND"] = "foobar"
420
421 if app_id:
422 env["XDG_DESKTOP_PORTAL_TEST_APP_ID"] = app_id
423
424 if usb_queries:
425 env["XDG_DESKTOP_PORTAL_TEST_USB_QUERIES"] = usb_queries
426
427 if umockdev:
428 env["UMOCKDEV_DIR"] = umockdev.get_root_dir()
429
430 asan_suppression = test_dir() / "asan.suppression"
431 if not asan_suppression.exists():
432 raise FileNotFoundError(f"{asan_suppression} does not exist")
433 env["LSAN_OPTIONS"] = f"suppressions={asan_suppression}"
434
435 for key, val in xdp_overwrite_env.items():
436 env[key] = val
437
438 return env
439
440
441 def _maybe_add_asan_preload(executable: Path, env: dict[str, str]) -> None:
442 # ASAN really wants to be the first library to get loaded but we also
443 # LD_PRELOAD umockdev and LD_PRELOAD gets loaded before any "normally"
444 # linked libraries. This uses ldd to find the version of libasan.so that
445 # should be loaded and puts it in front of LD_PRELOAD.
446 # This way, LD_PRELOAD and ASAN can be used at the same time.
447 ldd = subprocess.check_output(["ldd", executable]).decode("utf-8")
448 libs = [line.split()[0] for line in ldd.splitlines()]
449 try:
450 libasan = next(filter(lambda lib: lib.startswith("libasan"), libs))
451 except StopIteration:
452 return
453
454 preload = env.get("LD_PRELOAD", "")
455 env["LD_PRELOAD"] = f"{libasan}:{preload}"
456
457
458 @pytest.fixture
459 def xdg_desktop_portal(
460 dbus_con: dbus.Bus, xdg_desktop_portal_path: Path, xdp_env: dict[str, str]
461 ) -> Iterator[subprocess.Popen]:
462 """
463 Fixture which starts and eventually stops xdg-desktop-portal
464 """
465 if not xdg_desktop_portal_path.exists():
466 raise FileNotFoundError(f"{xdg_desktop_portal_path} does not exist")
467
468 env = xdp_env.copy()
469 _maybe_add_asan_preload(xdg_desktop_portal_path, env)
470
471 xdg_desktop_portal = subprocess.Popen([xdg_desktop_portal_path], env=env)
472
473 while not dbus_con.name_has_owner("org.freedesktop.portal.Desktop"):
474 returncode = xdg_desktop_portal.poll()
475 if returncode is not None:
476 raise subprocess.SubprocessError(
477 f"xdg-desktop-portal exited with {returncode}"
478 )
479 time.sleep(0.1)
480
481 yield xdg_desktop_portal
482
483 xdg_desktop_portal.send_signal(signal.SIGHUP)
484 returncode = xdg_desktop_portal.wait()
485 assert returncode == 0
486
487
488 @pytest.fixture
489 def xdg_permission_store(
490 dbus_con: dbus.Bus, xdg_permission_store_path: Path, xdp_env: dict[str, str]
491 ) -> Iterator[subprocess.Popen]:
492 """
493 Fixture which starts and eventually stops xdg-permission-store
494 """
495 if not xdg_permission_store_path.exists():
496 raise FileNotFoundError(f"{xdg_permission_store_path} does not exist")
497
498 env = xdp_env.copy()
499 _maybe_add_asan_preload(xdg_permission_store_path, env)
500
501 permission_store = subprocess.Popen([xdg_permission_store_path], env=env)
502
503 while not dbus_con.name_has_owner("org.freedesktop.impl.portal.PermissionStore"):
504 returncode = permission_store.poll()
505 if returncode is not None:
506 raise subprocess.SubprocessError(
507 f"xdg-permission-store exited with {returncode}"
508 )
509 time.sleep(0.1)
510
511 yield permission_store
512
513 permission_store.send_signal(signal.SIGHUP)
514 permission_store.wait()
515 # The permission store does not shut down cleanly currently
516 # returncode = permission_store.wait()
517 # assert returncode == 0
518
519
520 @pytest.fixture
521 def xdg_document_portal(
522 dbus_con: dbus.Bus, xdg_document_portal_path: Path, xdp_env: dict[str, str]
523 ) -> Iterator[subprocess.Popen]:
524 """
525 Fixture which starts and eventually stops xdg-document-portal
526 """
527 if not xdg_document_portal_path.exists():
528 raise FileNotFoundError(f"{xdg_document_portal_path} does not exist")
529
530 # FUSE and LD_PRELOAD don't like each other. Not sure what exactly is going
531 # wrong but it usually just results in a weird hang that needs SIGKILL
532 env = xdp_env.copy()
533 env.pop("LD_PRELOAD", None)
534
535 document_portal = subprocess.Popen([xdg_document_portal_path], env=env)
536
537 while not dbus_con.name_has_owner("org.freedesktop.portal.Documents"):
538 returncode = document_portal.poll()
539 if returncode is not None:
540 raise subprocess.SubprocessError(
541 f"xdg-document-portal exited with {returncode}"
542 )
543 time.sleep(0.1)
544
545 yield document_portal
546
547 document_portal.send_signal(signal.SIGHUP)
548 returncode = document_portal.wait()
549 assert returncode == 0
550
551
552 @pytest.fixture
553 def portals(templates: Any, xdg_desktop_portal: Any, xdg_permission_store: Any) -> None:
554 """
555 Fixture which starts the required templates, xdg-desktop-portal,
556 xdg-document-portal and xdg-permission-store. Most tests require this.
557 """
558 return None
559
560
561 @pytest.fixture
562 def usb_queries() -> Optional[str]:
563 """
564 Default fixture providing the usb queries the connecting process can
565 enumerate
566 """
567 return None
568
569
570 @pytest.fixture
571 def umockdev() -> Optional[UMockdev.Testbed]:
572 """
573 Default fixture providing a umockdev testbed
574 """
575 return None
576
577
578 @pytest.fixture
579 def dbus_con(create_test_dbus: dbusmock.DBusTestCase) -> dbus.Bus:
580 """
581 Default fixture which provides the python-dbus session bus of the test.
582 """
583 con = create_test_dbus.get_dbus(system_bus=False)
584 assert con
585 return con
586
587
588 @pytest.fixture
589 def dbus_con_sys(create_test_dbus: dbusmock.DBusTestCase) -> dbus.Bus:
590 """
591 Default fixture which provides the python-dbus system bus of the test.
592 """
593 con_sys = create_test_dbus.get_dbus(system_bus=True)
594 assert con_sys
595 return con_sys