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