Debian Codegraph @

tests/conftest.py

raw
1 import gc
2 import os
3 import sys
4 import signal
5 import subprocess
6 import atexit
7 import warnings
8
9 import pytest
10 import contextlib
11
12
13 @pytest.hookimpl(hookwrapper=True, tryfirst=True)
14 def pytest_runtest_call(item):
15 """A pytest hook which takes over sys.excepthook and raises any uncaught
16 exception (with PyGObject this happesn often when we get called from C,
17 like any signal handler, vfuncs tc).
18 """
19 exceptions = []
20
21 def on_hook(type_, value, tback):
22 exceptions.append((type_, value, tback))
23
24 orig_excepthook = sys.excepthook
25 sys.excepthook = on_hook
26 try:
27 outcome = yield
28 finally:
29 sys.excepthook = orig_excepthook
30 if exceptions:
31 tp, value, tb = exceptions[0]
32 outcome.force_exception(tp(value).with_traceback(tb))
33
34
35 def pytest_sessionfinish(session, exitstatus):
36 """Make sure to run GC a couple of times. This helps in memory analysis."""
37 gc.collect()
38 gc.collect()
39
40
41 def set_dll_search_path():
42 # Python 3.8 no longer searches for DLLs in PATH, so we have to add
43 # everything in PATH manually. Note that unlike PATH add_dll_directory
44 # has no defined order, so if there are two cairo DLLs in PATH we
45 # might get a random one.
46 if os.name != "nt" or not hasattr(os, "add_dll_directory"):
47 return
48 for p in os.environ.get("PATH", "").split(os.pathsep):
49 with contextlib.suppress(OSError):
50 os.add_dll_directory(p)
51
52
53 def os_environ_prepend(envvar, path):
54 current = os.environ.get(envvar)
55 os.environ[envvar] = os.path.pathsep.join([path, current] if current else [path])
56
57
58 def init_test_environ():
59 set_dll_search_path()
60
61 def dbus_launch_session():
62 if os.name == "nt" or sys.platform == "darwin":
63 return (-1, "")
64
65 try:
66 out = subprocess.check_output(
67 [
68 "dbus-daemon",
69 "--session",
70 "--fork",
71 "--print-address=1",
72 "--print-pid=1",
73 ]
74 )
75 except (subprocess.CalledProcessError, OSError):
76 return (-1, "")
77 else:
78 out = out.decode("utf-8")
79 addr, pid = out.splitlines()
80 return int(pid), addr
81
82 pid, addr = dbus_launch_session()
83 if pid >= 0:
84 os.environ["DBUS_SESSION_BUS_ADDRESS"] = addr
85 atexit.register(os.kill, pid, signal.SIGKILL)
86 else:
87 os.environ["DBUS_SESSION_BUS_ADDRESS"] = "."
88
89 # force untranslated messages, as we check for them in some tests
90 os.environ["LC_MESSAGES"] = "C"
91 if os.name != "nt":
92 os.environ["G_DEBUG"] = "fatal-warnings fatal-criticals"
93
94 # First add test directory, since we have a gi package there
95 tests_srcdir = os.path.abspath(os.path.dirname(__file__))
96 srcdir = os.path.dirname(tests_srcdir)
97
98 sys.path.insert(0, tests_srcdir)
99 sys.path.insert(0, srcdir)
100
101 import gi
102
103 gi_builddir = os.path.dirname(gi._gi.__file__)
104 builddir = os.path.dirname(gi_builddir)
105 tests_builddir = os.path.join(builddir, "tests")
106
107 sys.path.insert(0, tests_builddir)
108 sys.path.insert(0, builddir)
109
110 # make Gio able to find our gschemas.compiled in tests/. This needs to be set
111 # before importing Gio. Support a separate build tree, so look in build dir
112 # first.
113 os.environ["GSETTINGS_BACKEND"] = "memory"
114 os.environ["GSETTINGS_SCHEMA_DIR"] = os.pathsep.join(
115 [
116 tests_builddir,
117 os.environ.get("GSETTINGS_SCHEMA_DIR", ""),
118 ]
119 )
120 os.environ["G_FILENAME_ENCODING"] = "UTF-8"
121
122 # Avoid accessibility dbus warnings
123 os.environ["NO_AT_BRIDGE"] = "1"
124
125 # A workaround for https://gitlab.gnome.org/GNOME/glib/-/issues/2251
126 # The gtk4 a11y stack calls get_dbus_object_path() on the default app
127 os.environ["GTK_A11Y"] = "none"
128
129 # Force the default theme so broken themes don't affect the tests
130 os.environ["GTK_THEME"] = "Adwaita"
131
132 gi_gir_path = os.path.join(
133 builddir, "subprojects", "glib", "girepository", "introspection"
134 )
135 if os.path.exists(gi_gir_path):
136 os_environ_prepend("GI_TYPELIB_PATH", gi_gir_path)
137
138 gi.require_version("GIRepository", "3.0")
139 repo = gi.Repository.get_default()
140
141 gi_tests_path = os.path.join(builddir, "subprojects", "gobject-introspection-tests")
142 repo.prepend_library_path(gi_tests_path)
143 repo.prepend_search_path(gi_tests_path)
144
145 def try_require_version(namespace, version):
146 try:
147 gi.require_version(namespace, version)
148 except ValueError:
149 # prevent tests from running with the wrong version
150 sys.modules["gi.repository." + namespace] = None
151
152 # Optional
153 try_require_version("Gtk", os.environ.get("TEST_GTK_VERSION", "3.0"))
154 try_require_version("Gdk", os.environ.get("TEST_GTK_VERSION", "3.0"))
155 try_require_version("GdkPixbuf", "2.0")
156 try_require_version("Pango", "1.0")
157 try_require_version("PangoCairo", "1.0")
158 try_require_version("Atk", "1.0")
159
160 # Required
161 gi.require_versions(
162 {
163 "GIMarshallingTests": "1.0",
164 "Regress": "1.0",
165 "GLib": "2.0",
166 "Gio": "2.0",
167 "GObject": "2.0",
168 }
169 )
170
171 # It's disabled for stable releases by default, this makes sure it's
172 # always on for the tests.
173 warnings.simplefilter("default", gi.PyGIDeprecationWarning)
174
175 # Otherwise we crash on the first gtk use when e.g. DISPLAY isn't set
176 try:
177 from gi.repository import Gtk
178 except ImportError:
179 pass
180 else:
181 res = Gtk.init_check() if Gtk._version == "4.0" else Gtk.init_check([])[0]
182 if not res:
183 raise RuntimeError("Gtk available, but Gtk.init_check() failed")
184
185
186 init_test_environ()