Debian Codegraph @

tests/test_xvfb.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import os
4 from typing import Iterator
5
6 import pytest
7 import pyvirtualdisplay
8
9 import pytest_xvfb
10
11 xauth_available = any(
12 os.access(os.path.join(path, "xauth"), os.X_OK)
13 for path in os.environ.get("PATH", "").split(os.pathsep)
14 )
15
16
17 @pytest.fixture(autouse=True, scope="session")
18 def ensure_xvfb() -> None:
19 if not pytest_xvfb.has_executable("Xvfb"):
20 raise Exception("Tests need Xvfb to run.")
21
22
23 needs_xephyr = pytest.mark.skipif(
24 not pytest_xvfb.has_executable("Xephyr"), reason="Needs Xephyr"
25 )
26 needs_xvnc = pytest.mark.skipif(
27 not pytest_xvfb.has_executable("Xvnc"), reason="Needs Xvnc"
28 )
29
30
31 @pytest.fixture(
32 params=[
33 None,
34 "xvfb",
35 pytest.param("xephyr", marks=needs_xephyr),
36 pytest.param("xvnc", marks=needs_xvnc),
37 ]
38 )
39 def backend_args(
40 request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch
41 ) -> Iterator[list[str]]:
42 monkeypatch.delenv("DISPLAY")
43 args = [] if request.param is None else ["--xvfb-backend", request.param]
44 if request.param == "xephyr":
45 # we need a host display for it... PyVirtualDisplay and Xvfb to the
46 # rescue!
47 display = pyvirtualdisplay.Display() # type: ignore[attr-defined]
48 display.start()
49 yield args
50 display.stop()
51 else:
52 yield args
53
54
55 def test_xvfb_available(pytester: pytest.Pytester, backend_args: list[str]) -> None:
56 pytester.makepyfile(
57 """
58 import os
59
60 def test_display():
61 assert 'DISPLAY' in os.environ
62 """
63 )
64 result = pytester.runpytest(*backend_args)
65 assert result.ret == 0
66
67
68 def test_empty_display(
69 pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch, backend_args: list[str]
70 ) -> None:
71 if backend_args == ["--xvfb-backend", "xephyr"]:
72 pytest.skip("Xephyr needs a host display")
73
74 monkeypatch.setenv("DISPLAY", "")
75 pytester.makepyfile(
76 """
77 import os
78
79 def test_display():
80 assert 'DISPLAY' in os.environ
81 """
82 )
83 result = pytester.runpytest(*backend_args)
84 assert os.environ["DISPLAY"] == ""
85 assert result.ret == 0
86
87
88 def test_xvfb_unavailable(
89 pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch
90 ) -> None:
91 monkeypatch.setenv("PATH", "")
92 monkeypatch.setenv("DISPLAY", ":42")
93 pytester.makepyfile(
94 """
95 import os
96
97 def test_display():
98 assert os.environ['DISPLAY'] == ':42'
99 """
100 )
101 assert os.environ["DISPLAY"] == ":42"
102 result = pytester.runpytest()
103 result.stdout.fnmatch_lines("* could not find Xvfb.*")
104 assert result.ret == 0
105
106
107 def test_xvfb_unavailable_explicit(
108 pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch, backend_args: list[str]
109 ) -> None:
110 """If an explicitly chosen backend is unavailable: Hard error."""
111 if not backend_args:
112 pytest.skip("Already tested above")
113
114 monkeypatch.setenv("PATH", "")
115 monkeypatch.setenv("DISPLAY", ":42")
116 pytester.makepyfile(
117 """
118 import os
119
120 def test_display():
121 assert False # never run
122 """
123 )
124 assert os.environ["DISPLAY"] == ":42"
125 result = pytester.runpytest(*backend_args)
126 result.stderr.fnmatch_lines("*xvfb backend * requested but not installed.")
127 assert result.ret == pytest.ExitCode.USAGE_ERROR
128
129
130 def test_no_xvfb_arg(
131 pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch, backend_args: list[str]
132 ) -> None:
133 monkeypatch.setenv("DISPLAY", ":42")
134 pytester.makepyfile(
135 """
136 import os
137
138 def test_display():
139 assert os.environ['DISPLAY'] == ':42'
140 """
141 )
142 assert os.environ["DISPLAY"] == ":42"
143 result = pytester.runpytest("--no-xvfb", *backend_args)
144 assert result.ret == 0
145
146
147 @pytest.mark.parametrize("configured", [True, False])
148 def test_screen_size(
149 pytester: pytest.Pytester, configured: bool, backend_args: list[str]
150 ) -> None:
151 if backend_args == ["--xvfb-backend", "xvnc"]:
152 pytest.skip("Seems to be unsupported with Xvnc")
153
154 try:
155 import tkinter # noqa
156 except ImportError:
157 pytest.importorskip("Tkinter")
158
159 if configured:
160 pytester.makeini(
161 """
162 [pytest]
163 xvfb_width = 1024
164 xvfb_height = 768
165 xvfb_colordepth = 8
166 """
167 )
168 expected_width = 1024
169 expected_height = 768
170 expected_depth = 8
171 else:
172 expected_width = 800
173 expected_height = 600
174 expected_depth = 16
175
176 pytester.makepyfile(
177 """
178 try:
179 import tkinter as tk
180 except ImportError:
181 import Tkinter as tk
182
183 def test_screen_size():
184 root = tk.Tk()
185 assert root.winfo_screenwidth() == {width}
186 assert root.winfo_screenheight() == {height}
187 assert root.winfo_screendepth() == {depth}
188 """.format(
189 width=expected_width, height=expected_height, depth=expected_depth
190 )
191 )
192 result = pytester.runpytest(*backend_args)
193 assert result.ret == 0
194
195
196 def test_failing_start(
197 pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch, backend_args: list[str]
198 ) -> None:
199 pytester.makeini(
200 """
201 [pytest]
202 xvfb_args = -foo
203 """
204 )
205 pytester.makepyfile(
206 """
207 def test_none():
208 pass
209 """
210 )
211 result = pytester.runpytest(*backend_args)
212 result.stderr.fnmatch_lines(
213 [
214 "INTERNALERROR> *.XStartError: X* program closed. *",
215 ]
216 )
217 assert "OSError" not in str(result.stderr)
218
219
220 @pytest.mark.parametrize(
221 "args, outcome",
222 [
223 ([], "1 passed, 1 skipped"),
224 (["--no-xvfb"], "2 passed"),
225 ],
226 )
227 def test_no_xvfb_marker(
228 pytester: pytest.Pytester, args: list[str], outcome: str, backend_args: list[str]
229 ) -> None:
230 pytester.makepyfile(
231 """
232 import pytest
233
234 @pytest.mark.no_xvfb
235 def test_marked():
236 pass
237
238 def test_unmarked():
239 pass
240 """
241 )
242 res = pytester.runpytest(*args, *backend_args)
243 res.stdout.fnmatch_lines(f"*= {outcome}*")
244
245
246 def test_xvfb_fixture(pytester: pytest.Pytester, backend_args: list[str]) -> None:
247 pytester.makepyfile(
248 """
249 import os
250
251 def test_display(xvfb):
252 assert ':{}'.format(xvfb.display) == os.environ['DISPLAY']
253
254 def test_screen(xvfb):
255 assert xvfb.width == 800
256 assert xvfb.height == 600
257 assert xvfb.colordepth == 16
258
259 def test_args(xvfb):
260 assert xvfb.args == []
261 """
262 )
263 result = pytester.runpytest(*backend_args)
264 assert result.ret == 0
265
266
267 def test_early_display(
268 monkeypatch: pytest.MonkeyPatch, pytester: pytest.Pytester, backend_args: list[str]
269 ) -> None:
270 """Make sure DISPLAY is set in a session-scoped fixture already."""
271 pytester.makepyfile(
272 """
273 import os
274 import pytest
275
276 @pytest.yield_fixture(scope='session', autouse=True)
277 def fixt():
278 assert 'DISPLAY' in os.environ
279 yield
280
281 def test_foo():
282 pass
283 """
284 )
285 result = pytester.runpytest(*backend_args)
286 assert result.ret == 0
287
288
289 def test_strict_markers(pytester: pytest.Pytester) -> None:
290 pytester.makepyfile(
291 """
292 import pytest
293
294 @pytest.mark.no_xvfb
295 def test_marked():
296 pass
297 """
298 )
299 result = pytester.runpytest("--strict")
300 assert result.ret == 0
301
302
303 def test_xvfb_session_fixture(pytester: pytest.Pytester) -> None:
304 """Make sure the xvfb fixture can be used from a session-wide one."""
305 pytester.makepyfile(
306 """
307 import pytest
308
309 @pytest.fixture(scope='session')
310 def fixt(xvfb):
311 pass
312
313 def test_fixt(fixt):
314 pass
315 """
316 )
317 result = pytester.runpytest()
318 assert result.ret == 0
319
320
321 @pytest.mark.skipif(not xauth_available, reason="no xauth")
322 def test_xvfb_with_xauth(pytester: pytest.Pytester, backend_args: list[str]) -> None:
323 original_auth = os.environ.get("XAUTHORITY")
324 pytester.makeini(
325 """
326 [pytest]
327 xvfb_xauth = True
328 """
329 )
330 pytester.makepyfile(
331 """
332 import os
333
334 def test_xauth():
335 print('\\nXAUTHORITY: ' + os.environ['XAUTHORITY'])
336 assert os.path.isfile(os.environ['XAUTHORITY'])
337 assert os.access(os.environ['XAUTHORITY'], os.R_OK)
338 """
339 )
340 result = pytester.runpytest("-s", *backend_args)
341 # Get and parse the XAUTHORITY: line
342 authline = next(l for l in result.outlines if l.startswith("XAUTHORITY:"))
343 authfile = authline.split(" ", 1)[1]
344
345 assert result.ret == 0
346 # Make sure the authfile is deleted
347 assert not os.path.exists(authfile)
348 assert os.environ.get("XAUTHORITY") == original_auth