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 import tests.xdp_utils as xdp
6
7 from typing import Any, Dict, Iterator, Optional
8 from types import ModuleType
9
10 import pytest
11 import dbus
12 import dbusmock
13 import os
14 import sys
15 import tempfile
16 import subprocess
17 import time
18 import signal
19 import shutil
20
21 from pathlib import Path
22 from contextlib import chdir
23
24 import gi
25
26 gi.require_version("UMockdev", "1.0")
27 from gi.repository import UMockdev # noqa E402
28
29
30 def pytest_configure() -> None:
31 ensure_environment_set()
32 ensure_umockdev_loaded()
33
34
35 def pytest_sessionfinish(session, exitstatus):
36 # Meson and ginsttest-runner expect tests to exit with status 77 if all
37 # tests were skipped
38 if exitstatus == pytest.ExitCode.NO_TESTS_COLLECTED:
39 session.exitstatus = 77
40
41
42 def pytest_make_parametrize_id(config, val):
43 if isinstance(val, xdp.AppInfo):
44 return val.__class__.__name__
45 return None
46
47
48 def ensure_environment_set() -> None:
49 env_vars = [
50 "XDG_DESKTOP_PORTAL_PATH",
51 "XDG_PERMISSION_STORE_PATH",
52 "XDG_DOCUMENT_PORTAL_PATH",
53 ]
54
55 if not os.getenv("XDP_VALIDATE_AUTO"):
56 env_vars += [
57 "XDP_VALIDATE_ICON",
58 "XDP_VALIDATE_SOUND",
59 ]
60 else:
61 os.environ.pop("XDP_VALIDATE_ICON", None)
62 os.environ.pop("XDP_VALIDATE_SOUND", None)
63
64 for env_var in env_vars:
65 if not os.getenv(env_var):
66 raise Exception(f"{env_var} must be set")
67
68
69 def ensure_umockdev_loaded() -> None:
70 umockdev_preload = "libumockdev-preload.so"
71 preload = os.environ.get("LD_PRELOAD", "")
72 if umockdev_preload not in preload:
73 os.environ["LD_PRELOAD"] = f"{umockdev_preload}:{preload}"
74 os.execv(sys.executable, [sys.executable] + sys.argv)
75
76
77 def test_dir() -> Path:
78 return Path(__file__).resolve().parent
79
80
81 @pytest.fixture
82 def xdg_desktop_portal_path() -> Path:
83 return Path(os.environ["XDG_DESKTOP_PORTAL_PATH"])
84
85
86 @pytest.fixture
87 def xdg_permission_store_path() -> Path:
88 return Path(os.environ["XDG_PERMISSION_STORE_PATH"])
89
90
91 @pytest.fixture
92 def xdg_document_portal_path() -> Path:
93 return Path(os.environ["XDG_DOCUMENT_PORTAL_PATH"])
94
95
96 @pytest.fixture(autouse=True)
97 def create_test_dirs(umockdev: Optional[UMockdev.Testbed]) -> Iterator[None]:
98 # The umockdev argument is to make sure the testbed
99 # is created before we create the tmpdir
100 env_dirs = [
101 "HOME",
102 "TMPDIR",
103 "XDG_CACHE_HOME",
104 "XDG_CONFIG_HOME",
105 "XDG_DATA_HOME",
106 "XDG_RUNTIME_DIR",
107 "XDG_DESKTOP_PORTAL_DIR",
108 "XDP_BIN",
109 ]
110
111 test_root = tempfile.TemporaryDirectory(
112 prefix="xdp-testroot-", ignore_cleanup_errors=True
113 )
114
115 for env_dir in env_dirs:
116 directory = Path(test_root.name) / env_dir.lower()
117 directory.mkdir(mode=0o700, parents=True)
118 os.environ[env_dir] = directory.absolute().as_posix()
119
120 yield
121
122 test_root.cleanup()
123
124
125 @pytest.fixture
126 def xdp_mocked_executables(xdp_app_info_init: xdp.AppInfo) -> list[xdp.ExecutableMock]:
127 exe = None
128 if isinstance(xdp_app_info_init, xdp.AppInfoFlatpak):
129 exe = "flatpak"
130 elif isinstance(xdp_app_info_init, xdp.AppInfoSnap):
131 exe = "snap"
132 else:
133 return []
134
135 return [
136 xdp.ExecutableMock(
137 executable=exe,
138 access_mode=xdp.FileAccessMode.HIDDEN,
139 )
140 ]
141
142
143 @pytest.fixture
144 def xdp_available_executables() -> list[str]:
145 return [
146 "true",
147 "bwrap",
148 ]
149
150
151 @pytest.fixture
152 def xdp_bin_path(create_test_dirs) -> Path:
153 return Path(os.environ["XDP_BIN"])
154
155
156 @pytest.fixture(autouse=True)
157 def create_xdp_executables(
158 xdp_bin_path, xdp_mocked_executables, xdp_available_executables
159 ):
160 for mock in xdp_mocked_executables:
161 mock.create(xdp_bin_path)
162
163 for exe_name in xdp_available_executables:
164 exe_path = shutil.which(exe_name)
165 assert exe_path, f"{exe_name} is not installed or not in PATH"
166 (xdp_bin_path / exe_name).symlink_to(exe_path)
167
168
169 @pytest.fixture
170 def xdg_data_home_files() -> Dict[str, bytes]:
171 """
172 Default fixture which can be used to create files in the temporary
173 XDG_DATA_HOME directory of the test.
174 """
175 return {}
176
177
178 @pytest.fixture(autouse=True)
179 def ensure_xdg_data_home(
180 create_test_dirs: Any, xdg_data_home_files: Dict[str, bytes]
181 ) -> None:
182 files = xdg_data_home_files
183 for name, content in files.items():
184 file_path = Path(os.environ["XDG_DATA_HOME"]) / name
185 file_path.parent.mkdir(parents=True, exist_ok=True)
186 with open(file_path.absolute().as_posix(), "wb") as f:
187 f.write(content)
188
189
190 @pytest.fixture
191 def xdg_desktop_portal_dir_files() -> Dict[str, bytes]:
192 """
193 Default fixture which can be used to create files in the temporary
194 XDG_DESKTOP_PORTAL_DIR directory of the test.
195 """
196 return {}
197
198
199 @pytest.fixture
200 def xdg_desktop_portal_dir_default_files() -> Dict[str, bytes]:
201 files = {}
202
203 portals = [
204 "org.freedesktop.impl.portal.Access",
205 "org.freedesktop.impl.portal.Account",
206 "org.freedesktop.impl.portal.AppChooser",
207 "org.freedesktop.impl.portal.Background",
208 "org.freedesktop.impl.portal.Clipboard",
209 "org.freedesktop.impl.portal.DynamicLauncher",
210 "org.freedesktop.impl.portal.Email",
211 "org.freedesktop.impl.portal.FileChooser",
212 "org.freedesktop.impl.portal.GlobalShortcuts",
213 "org.freedesktop.impl.portal.Inhibit",
214 "org.freedesktop.impl.portal.InputCapture",
215 "org.freedesktop.impl.portal.Lockdown",
216 "org.freedesktop.impl.portal.Notification",
217 "org.freedesktop.impl.portal.Print",
218 "org.freedesktop.impl.portal.RemoteDesktop",
219 "org.freedesktop.impl.portal.Screenshot",
220 "org.freedesktop.impl.portal.Settings",
221 "org.freedesktop.impl.portal.Usb",
222 "org.freedesktop.impl.portal.Wallpaper",
223 ]
224
225 files["test-portals.conf"] = b"""
226 [preferred]
227 default=test;
228 """
229
230 files["test.portal"] = """
231 [portal]
232 DBusName=org.freedesktop.impl.portal.Test
233 Interfaces={}
234 """.format(";".join(portals)).encode("utf-8")
235
236 return files
237
238
239 @pytest.fixture(autouse=True)
240 def ensure_xdg_desktop_portal_dir(
241 create_test_dirs: Any,
242 xdg_desktop_portal_dir_files: Dict[str, bytes],
243 xdg_desktop_portal_dir_default_files: Dict[str, bytes],
244 ) -> None:
245 files = xdg_desktop_portal_dir_default_files | xdg_desktop_portal_dir_files
246 for name, content in files.items():
247 file_path = Path(os.environ["XDG_DESKTOP_PORTAL_DIR"]) / name
248 file_path.parent.mkdir(parents=True, exist_ok=True)
249 with open(file_path.absolute().as_posix(), "wb") as f:
250 f.write(content)
251
252
253 @pytest.fixture(autouse=True)
254 def create_test_dbus() -> Iterator[dbusmock.DBusTestCase]:
255 bus = dbusmock.DBusTestCase()
256 bus.setUp()
257 bus.start_session_bus()
258 bus.start_system_bus()
259
260 yield bus
261
262 bus.tearDown()
263 bus.tearDownClass()
264
265
266 @pytest.fixture(autouse=True)
267 def create_dbus_monitor(create_test_dbus) -> Iterator[Optional[subprocess.Popen]]:
268 if not os.getenv("XDP_DBUS_MONITOR"):
269 yield None
270 return
271
272 dbus_monitor = subprocess.Popen(["dbus-monitor", "--session"])
273
274 yield dbus_monitor
275
276 dbus_monitor.terminate()
277 dbus_monitor.wait()
278
279
280 def _get_server_for_module(
281 busses: dict[dbusmock.BusType, dict[str, dbusmock.SpawnedMock]],
282 module: ModuleType,
283 bustype: dbusmock.BusType,
284 ) -> dbusmock.SpawnedMock:
285 assert bustype in dbusmock.BusType
286
287 try:
288 return busses[bustype][module.BUS_NAME]
289 except KeyError:
290 server = dbusmock.SpawnedMock.spawn_for_name(
291 module.BUS_NAME,
292 "/dbusmock",
293 dbusmock.OBJECT_MANAGER_IFACE,
294 bustype,
295 stdout=None,
296 stderr=None,
297 )
298
299 busses[bustype][module.BUS_NAME] = server
300 return server
301
302
303 def _get_main_obj_for_module(
304 server: dbusmock.SpawnedMock, module: ModuleType, bustype: dbusmock.BusType
305 ) -> dbusmock.DBusMockObject:
306 try:
307 server.obj.AddObject(
308 module.MAIN_OBJ,
309 "com.example.EmptyInterface",
310 {},
311 [],
312 dbus_interface=dbusmock.MOCK_IFACE,
313 )
314 except Exception:
315 pass
316
317 bustype.wait_for_bus_object(module.BUS_NAME, module.MAIN_OBJ)
318 bus = bustype.get_connection()
319 return bus.get_object(module.BUS_NAME, module.MAIN_OBJ)
320
321
322 def _terminate_mock_p(process: subprocess.Popen) -> None:
323 process.terminate()
324 process.wait()
325
326
327 def _terminate_servers(
328 busses: dict[dbusmock.BusType, dict[str, dbusmock.SpawnedMock]],
329 ) -> None:
330 for server in busses[dbusmock.BusType.SYSTEM].values():
331 _terminate_mock_p(server.process)
332 for server in busses[dbusmock.BusType.SESSION].values():
333 _terminate_mock_p(server.process)
334
335
336 def _start_template(
337 busses: dict[dbusmock.BusType, dict[str, dbusmock.SpawnedMock]],
338 template: str,
339 bus_name: Optional[str],
340 params: Dict[str, Any] = {},
341 ) -> None:
342 """
343 Start the template and potentially start a server for it
344 """
345 module_path_dir = (test_dir()).parent.absolute().as_posix()
346 template_path = test_dir() / f"templates/{template.lower()}.py"
347 template = template_path.absolute().as_posix()
348
349 # we cd to the parent dir of the test_dir so that the module search path for
350 # the templates is the same as opening the modules from here
351 with chdir(module_path_dir):
352 module = dbusmock.mockobject.load_module(template)
353 bustype = (
354 dbusmock.BusType.SYSTEM if module.SYSTEM_BUS else dbusmock.BusType.SESSION
355 )
356
357 if bus_name:
358 module.BUS_NAME = bus_name
359
360 server = _get_server_for_module(busses, module, bustype)
361 main_obj = _get_main_obj_for_module(server, module, bustype)
362
363 main_obj.AddTemplate(
364 template,
365 dbus.Dictionary(params, signature="sv"),
366 dbus_interface=dbusmock.MOCK_IFACE,
367 )
368
369
370 @pytest.fixture
371 def template_params() -> dict[str, dict[str, Any]]:
372 """
373 Default fixture for overriding the parameters which should be passed to the
374 mocking templates. Use required_templates to specify the default parameters
375 and override it for specific test cases via
376
377 @pytest.mark.parametrize("template_params", ({"Template": {"foo": "bar"}},))
378
379 """
380 return {}
381
382
383 @pytest.fixture
384 def required_templates() -> dict[str, dict[str, Any]]:
385 """
386 Default fixture for enumerating the mocking templates the test case requires
387 to be started. This is a map from a template spec to the parameters which
388 should be passed to the template. The template spec is the name of a
389 template in the templates directory and an optional dbus bus name to start
390 the template at, separated by a colon.
391
392 This starts the `settings` and `email` templates on the bus names specified
393 with BUS_NAME in the templates and passes parameters to settings.
394
395 {
396 "settings": {
397 "some_param": true,
398 },
399 "email": {},
400 }
401
402 This starts two instances of the settings template with their own parameters
403 once on the bus name specified in BUS_NAME in the template, and once on the
404 bus name `org.freedesktop.impl.portal.OtherImpl`.
405
406 {
407 "settings": {
408 "some_param": true,
409 },
410 "settings:org.freedesktop.impl.portal.OtherImpl": {
411 "some_param": false,
412 },
413 }
414
415 """
416 return {}
417
418
419 @pytest.fixture
420 def templates(
421 required_templates: dict[str, dict[str, Any]],
422 template_params: dict[str, dict[str, Any]],
423 ) -> Iterator[None]:
424 """
425 Fixture which starts the required templates with their parameters. Usually
426 the `portals` fixture is what you're looking for because it also starts
427 the portal frontend and the permission store.
428 """
429 busses: dict[dbusmock.BusType, dict[str, dbusmock.SpawnedMock]] = {
430 dbusmock.BusType.SYSTEM: {},
431 dbusmock.BusType.SESSION: {},
432 }
433 for template_data, params in required_templates.items():
434 template, bus_name = (template_data.split(":") + [None])[:2]
435 assert template
436 params = template_params.get(template, params)
437 _start_template(busses, template, bus_name, params)
438 yield
439 _terminate_servers(busses)
440
441
442 @pytest.fixture
443 def xdp_overwrite_env() -> dict[str, str]:
444 """
445 Default fixture which can be used to override the environment that gets
446 passed to xdg-desktop-portal, xdg-document-portal and xdg-permission-store.
447 """
448 return {}
449
450
451 @pytest.fixture(
452 params=[
453 xdp.AppInfoHost(),
454 xdp.AppInfoFlatpak(),
455 ]
456 + (
457 [
458 xdp.AppInfoSnap(),
459 xdp.AppInfoLinyaps(),
460 ]
461 if xdp.run_long_tests()
462 else []
463 )
464 )
465 def xdp_app_info(
466 request,
467 ) -> xdp.AppInfo:
468 """
469 Default fixture which can be used to override the XdpAppInfo the portal
470 frontend will discover.
471 The default fixture is parametric and will run each test with all the
472 app info kinds.
473 """
474
475 return request.param
476
477
478 @pytest.fixture(autouse=True)
479 def xdp_app_info_init(create_test_dirs, xdp_app_info) -> None:
480 xdp_app_info._initialize()
481 return xdp_app_info
482
483
484 @pytest.fixture
485 def xdp_env(
486 xdp_overwrite_env: dict[str, str],
487 xdp_app_info_init: xdp.AppInfo,
488 xdp_bin_path: Path,
489 umockdev: Optional[UMockdev.Testbed],
490 ) -> dict[str, str]:
491 env = os.environ.copy()
492 env["G_DEBUG"] = "fatal-criticals"
493 env["XDG_CURRENT_DESKTOP"] = "test"
494 env["PATH"] = xdp_bin_path.as_posix()
495
496 for key, val in xdp_app_info_init.get_xdp_executable_env().items():
497 env[key] = val
498
499 if umockdev:
500 env["UMOCKDEV_DIR"] = umockdev.get_root_dir()
501
502 asan_suppression = test_dir() / "asan.suppression"
503 if not asan_suppression.exists():
504 raise FileNotFoundError(f"{asan_suppression} does not exist")
505 env["LSAN_OPTIONS"] = f"suppressions={asan_suppression}"
506
507 for key, val in xdp_overwrite_env.items():
508 env[key] = val
509
510 return env
511
512
513 def _maybe_add_asan_preload(executable: Path, env: dict[str, str]) -> None:
514 # ASAN really wants to be the first library to get loaded but we also
515 # LD_PRELOAD umockdev and LD_PRELOAD gets loaded before any "normally"
516 # linked libraries. This uses ldd to find the version of libasan.so that
517 # should be loaded and puts it in front of LD_PRELOAD.
518 # This way, LD_PRELOAD and ASAN can be used at the same time.
519 ldd = subprocess.check_output(["ldd", executable]).decode("utf-8")
520 libs = [line.split()[0] for line in ldd.splitlines()]
521 try:
522 libasan = next(filter(lambda lib: lib.startswith("libasan"), libs))
523 except StopIteration:
524 return
525
526 preload = env.get("LD_PRELOAD", "")
527 env["LD_PRELOAD"] = f"{libasan}:{preload}"
528
529
530 def _valgrind_glib_suppressions() -> str:
531 try:
532 import pkgconfig
533
534 return pkgconfig.variables("glib-2.0")["glib_valgrind_suppressions"]
535 except ImportError:
536 return "/usr/share/glib-2.0/valgrind/glib.supp"
537
538
539 @pytest.fixture
540 def xdp_valgrind_args() -> list[str]:
541 if not xdp.is_valgrind():
542 return []
543
544 valgrind = shutil.which("valgrind")
545 assert valgrind, "Valgrind is not installed or not in PATH"
546
547 xdp_suppression = test_dir() / "valgrind.suppression"
548 glib_suppression = _valgrind_glib_suppressions()
549
550 return [
551 valgrind,
552 "--tool=memcheck",
553 "--error-exitcode=1",
554 "--track-origins=yes",
555 "--leak-check=full",
556 "--leak-resolution=high",
557 "--num-callers=50",
558 "--show-leak-kinds=definite,possible",
559 "--show-error-list=yes",
560 "--show-realloc-size-zero=no",
561 f"--suppressions={glib_suppression}",
562 f"--suppressions={xdp_suppression}",
563 ]
564
565
566 @pytest.fixture
567 def xdg_desktop_portal(
568 dbus_con: dbus.Bus,
569 xdg_desktop_portal_path: Path,
570 xdp_env: dict[str, str],
571 xdp_valgrind_args: list[str],
572 ) -> Iterator[subprocess.Popen]:
573 """
574 Fixture which starts and eventually stops xdg-desktop-portal
575 """
576 if not xdg_desktop_portal_path.exists():
577 raise FileNotFoundError(f"{xdg_desktop_portal_path} does not exist")
578
579 env = xdp_env.copy()
580 _maybe_add_asan_preload(xdg_desktop_portal_path, env)
581
582 xdg_desktop_portal = subprocess.Popen(
583 xdp_valgrind_args + [xdg_desktop_portal_path], env=env
584 )
585
586 while not dbus_con.name_has_owner("org.freedesktop.portal.Desktop"):
587 returncode = xdg_desktop_portal.poll()
588 if returncode is not None:
589 raise subprocess.SubprocessError(
590 f"xdg-desktop-portal exited with {returncode}"
591 )
592 time.sleep(0.1)
593
594 yield xdg_desktop_portal
595
596 xdg_desktop_portal.send_signal(signal.SIGHUP)
597 returncode = xdg_desktop_portal.wait()
598 assert returncode == 0
599
600
601 @pytest.fixture
602 def xdg_permission_store(
603 dbus_con: dbus.Bus, xdg_permission_store_path: Path, xdp_env: dict[str, str]
604 ) -> Iterator[subprocess.Popen]:
605 """
606 Fixture which starts and eventually stops xdg-permission-store
607 """
608 if not xdg_permission_store_path.exists():
609 raise FileNotFoundError(f"{xdg_permission_store_path} does not exist")
610
611 env = xdp_env.copy()
612 _maybe_add_asan_preload(xdg_permission_store_path, env)
613
614 permission_store = subprocess.Popen([xdg_permission_store_path], env=env)
615
616 while not dbus_con.name_has_owner("org.freedesktop.impl.portal.PermissionStore"):
617 returncode = permission_store.poll()
618 if returncode is not None:
619 raise subprocess.SubprocessError(
620 f"xdg-permission-store exited with {returncode}"
621 )
622 time.sleep(0.1)
623
624 yield permission_store
625
626 permission_store.send_signal(signal.SIGHUP)
627 permission_store.wait()
628 # The permission store does not shut down cleanly currently
629 # returncode = permission_store.wait()
630 # assert returncode == 0
631
632
633 @pytest.fixture
634 def xdg_document_portal(
635 dbus_con: dbus.Bus, xdg_document_portal_path: Path, xdp_env: dict[str, str]
636 ) -> Iterator[subprocess.Popen]:
637 """
638 Fixture which starts and eventually stops xdg-document-portal
639 """
640 try:
641 xdp.ensure_fuse_supported()
642 except xdp.FuseNotSupportedException as e:
643 pytest.skip(f"No fuse support: {e}")
644
645 if not xdg_document_portal_path.exists():
646 raise FileNotFoundError(f"{xdg_document_portal_path} does not exist")
647
648 # FUSE and LD_PRELOAD don't like each other. Not sure what exactly is going
649 # wrong but it usually just results in a weird hang that needs SIGKILL
650 env = xdp_env.copy()
651 env.pop("LD_PRELOAD", None)
652
653 # The document portal also uses XdpAppInfos to figure out where a request
654 # is coming from. If we don't unset this, it might think the
655 # xdg-desktop-portal is a flatpak or snap app. Would be nice to find a
656 # better solution here.
657 env.pop("XDG_DESKTOP_PORTAL_TEST_APP_INFO_KIND", None)
658
659 document_portal = subprocess.Popen([xdg_document_portal_path], env=env)
660
661 while not dbus_con.name_has_owner("org.freedesktop.portal.Documents"):
662 returncode = document_portal.poll()
663 if returncode is not None:
664 raise subprocess.SubprocessError(
665 f"xdg-document-portal exited with {returncode}"
666 )
667 time.sleep(0.1)
668
669 yield document_portal
670
671 document_portal.send_signal(signal.SIGHUP)
672 returncode = document_portal.wait()
673 assert returncode == 0
674
675 fuse_mount = Path(os.environ["XDG_RUNTIME_DIR"]) / "doc"
676
677 def unmounted():
678 try:
679 next(fuse_mount.iterdir())
680 except StopIteration:
681 return True
682 return False
683
684 xdp.wait_for(unmounted)
685
686
687 @pytest.fixture
688 def portals(templates: Any, xdg_desktop_portal: Any, xdg_permission_store: Any) -> None:
689 """
690 Fixture which starts the required templates, xdg-desktop-portal,
691 xdg-document-portal and xdg-permission-store. Most tests require this.
692 """
693 return None
694
695
696 @pytest.fixture
697 def umockdev() -> Optional[UMockdev.Testbed]:
698 """
699 Default fixture providing a umockdev testbed
700 """
701 return None
702
703
704 @pytest.fixture
705 def dbus_con(create_test_dbus: dbusmock.DBusTestCase) -> dbus.Bus:
706 """
707 Default fixture which provides the python-dbus session bus of the test.
708 """
709 con = create_test_dbus.get_dbus(system_bus=False)
710 assert con
711 return con
712
713
714 @pytest.fixture
715 def dbus_con_sys(create_test_dbus: dbusmock.DBusTestCase) -> dbus.Bus:
716 """
717 Default fixture which provides the python-dbus system bus of the test.
718 """
719 con_sys = create_test_dbus.get_dbus(system_bus=True)
720 assert con_sys
721 return con_sys