conftest.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Shared conftest for all integration tests."""
  2. import os
  3. import re
  4. from pathlib import Path
  5. import pytest
  6. DISPLAY = None
  7. XVFB_DIMENSIONS = (800, 600)
  8. @pytest.fixture(scope="session", autouse=True)
  9. def xvfb():
  10. """Create virtual X display.
  11. This function is a no-op unless GITHUB_ACTIONS is set in the environment.
  12. Yields:
  13. the pyvirtualdisplay object that the browser will be open on
  14. """
  15. if os.environ.get("GITHUB_ACTIONS"):
  16. from pyvirtualdisplay.smartdisplay import ( # pyright: ignore [reportMissingImports]
  17. SmartDisplay,
  18. )
  19. global DISPLAY
  20. with SmartDisplay(visible=0, size=XVFB_DIMENSIONS) as DISPLAY:
  21. yield DISPLAY
  22. DISPLAY = None
  23. else:
  24. yield None
  25. def pytest_exception_interact(node, call, report):
  26. """Take and upload screenshot when tests fail.
  27. Args:
  28. node: The pytest item that failed.
  29. call: The pytest call describing when/where the test was invoked.
  30. report: The pytest log report object.
  31. """
  32. screenshot_dir = os.environ.get("SCREENSHOT_DIR")
  33. if DISPLAY is None or screenshot_dir is None:
  34. return
  35. screenshot_dir = Path(screenshot_dir)
  36. screenshot_dir.mkdir(parents=True, exist_ok=True)
  37. safe_filename = re.sub(
  38. r"(?u)[^-\w.]",
  39. "_",
  40. str(node.nodeid).strip().replace(" ", "_").replace(":", "_"),
  41. )
  42. DISPLAY.waitgrab().save(
  43. (Path(screenshot_dir) / safe_filename).with_suffix(".png"),
  44. )