authentik.root.test_plugin

  1import math
  2from os import environ
  3from ssl import OPENSSL_VERSION
  4from time import monotonic
  5from typing import TextIO
  6
  7import pytest
  8from cryptography.hazmat.backends.openssl.backend import backend
  9from pytest import Config, Item, TerminalReporter
 10
 11from authentik import authentik_full_version
 12from tests.decorators import get_local_ip
 13
 14IS_CI = "CI" in environ
 15
 16
 17@pytest.hookimpl(hookwrapper=True)
 18def pytest_sessionstart(*_, **__):
 19    """Clear the console ahead of the pytest output starting"""
 20    if not IS_CI:
 21        print("\x1b[2J\x1b[H")
 22    # Pre-warm cryptography's PyO3 PyDateTime type cache with the real
 23    # datetime class. If the first extraction happens under @freeze_time
 24    # (e.g. in MTLSStageTests), PyO3 caches freezegun's FakeDatetime,
 25    # which breaks every later test that passes a real datetime into
 26    # cryptography ("TypeError: 'datetime' object is not an instance
 27    # of 'FakeDatetime'"). The discard is intentional — only side
 28    # effect needed is the type-cache initialization.
 29    from datetime import UTC, datetime
 30
 31    from cryptography.x509.verification import PolicyBuilder
 32
 33    PolicyBuilder().time(datetime.now(tz=UTC))
 34    yield
 35
 36
 37@pytest.hookimpl(trylast=True)
 38def pytest_report_header(*_, **__):
 39    """Add authentik version to pytest output"""
 40    return [
 41        f"authentik version: {authentik_full_version()}",
 42        f"OpenSSL version: {OPENSSL_VERSION}, FIPS: {backend._fips_enabled}",
 43        f"Local IP: {get_local_ip()} (Detected as {get_local_ip(override=False)})",
 44    ]
 45
 46
 47@pytest.hookimpl(trylast=True)
 48def pytest_runtest_setup(item: Item):
 49    """In-memory caches outlive each test's transaction rollback, so start every test empty.
 50    This runs after fixture setup."""
 51    from authentik.admin.utils import get_system_settings
 52    from authentik.brands.utils import get_brand_for_request
 53    from authentik.enterprise.license import LicenseKey
 54
 55    get_brand_for_request.cache_clear()
 56    get_system_settings.cache_clear()
 57    LicenseKey.cached_summary.cache_clear()
 58
 59
 60def pytest_collection_modifyitems(config: Config, items: list[Item]) -> None:
 61    current_id = int(environ.get("CI_RUN_ID", "0")) - 1
 62    total_ids = int(environ.get("CI_TOTAL_RUNS", "0"))
 63
 64    if total_ids:
 65        num_tests = len(items)
 66        matrix_size = math.ceil(num_tests / total_ids)
 67
 68        start = current_id * matrix_size
 69        end = (current_id + 1) * matrix_size
 70
 71        deselected_items = items[:start] + items[end:]
 72        config.hook.pytest_deselected(items=deselected_items)
 73        items[:] = items[start:end]
 74        print(f" Executing {start} - {end} tests")
 75
 76
 77@pytest.hookimpl(trylast=True)
 78def pytest_configure(config: Config):
 79    # Replace the default terminal reporter
 80    reporter = config.pluginmanager.get_plugin("terminalreporter")
 81    if reporter:
 82        config.pluginmanager.unregister(reporter)
 83        config.pluginmanager.register(
 84            RelativeTimeTerminalReporter(config),
 85            "terminalreporter",
 86        )
 87
 88
 89class RelativeTimeTerminalReporter(TerminalReporter):
 90    _start_time: None | float
 91
 92    def __init__(self, config: Config, file: TextIO | None = None):
 93        super().__init__(config, file)
 94        self._start_time = None
 95
 96    def pytest_runtest_logstart(self, nodeid, location):
 97        # Set start time on the first test
 98        if self._start_time is None:
 99            self._start_time = monotonic()
100        super().pytest_runtest_logstart(nodeid, location)
101
102    def _locationline(self, nodeid, fspath, lineno, domain):
103        original = super()._locationline(nodeid, fspath, lineno, domain)
104        if self._start_time is None:
105            return original
106        elapsed = monotonic() - self._start_time
107        minutes, seconds = divmod(elapsed, 60)
108        timestamp = f"{int(minutes):02d}:{seconds:06.3f}"
109        return f"[+{timestamp}] {original}"
IS_CI = True
@pytest.hookimpl(hookwrapper=True)
def pytest_sessionstart(*_, **__):
18@pytest.hookimpl(hookwrapper=True)
19def pytest_sessionstart(*_, **__):
20    """Clear the console ahead of the pytest output starting"""
21    if not IS_CI:
22        print("\x1b[2J\x1b[H")
23    # Pre-warm cryptography's PyO3 PyDateTime type cache with the real
24    # datetime class. If the first extraction happens under @freeze_time
25    # (e.g. in MTLSStageTests), PyO3 caches freezegun's FakeDatetime,
26    # which breaks every later test that passes a real datetime into
27    # cryptography ("TypeError: 'datetime' object is not an instance
28    # of 'FakeDatetime'"). The discard is intentional — only side
29    # effect needed is the type-cache initialization.
30    from datetime import UTC, datetime
31
32    from cryptography.x509.verification import PolicyBuilder
33
34    PolicyBuilder().time(datetime.now(tz=UTC))
35    yield

Clear the console ahead of the pytest output starting

@pytest.hookimpl(trylast=True)
def pytest_report_header(*_, **__):
38@pytest.hookimpl(trylast=True)
39def pytest_report_header(*_, **__):
40    """Add authentik version to pytest output"""
41    return [
42        f"authentik version: {authentik_full_version()}",
43        f"OpenSSL version: {OPENSSL_VERSION}, FIPS: {backend._fips_enabled}",
44        f"Local IP: {get_local_ip()} (Detected as {get_local_ip(override=False)})",
45    ]

Add authentik version to pytest output

@pytest.hookimpl(trylast=True)
def pytest_runtest_setup(item: _pytest.nodes.Item):
48@pytest.hookimpl(trylast=True)
49def pytest_runtest_setup(item: Item):
50    """In-memory caches outlive each test's transaction rollback, so start every test empty.
51    This runs after fixture setup."""
52    from authentik.admin.utils import get_system_settings
53    from authentik.brands.utils import get_brand_for_request
54    from authentik.enterprise.license import LicenseKey
55
56    get_brand_for_request.cache_clear()
57    get_system_settings.cache_clear()
58    LicenseKey.cached_summary.cache_clear()

In-memory caches outlive each test's transaction rollback, so start every test empty. This runs after fixture setup.

def pytest_collection_modifyitems(config: _pytest.config.Config, items: list[_pytest.nodes.Item]) -> None:
61def pytest_collection_modifyitems(config: Config, items: list[Item]) -> None:
62    current_id = int(environ.get("CI_RUN_ID", "0")) - 1
63    total_ids = int(environ.get("CI_TOTAL_RUNS", "0"))
64
65    if total_ids:
66        num_tests = len(items)
67        matrix_size = math.ceil(num_tests / total_ids)
68
69        start = current_id * matrix_size
70        end = (current_id + 1) * matrix_size
71
72        deselected_items = items[:start] + items[end:]
73        config.hook.pytest_deselected(items=deselected_items)
74        items[:] = items[start:end]
75        print(f" Executing {start} - {end} tests")
@pytest.hookimpl(trylast=True)
def pytest_configure(config: _pytest.config.Config):
78@pytest.hookimpl(trylast=True)
79def pytest_configure(config: Config):
80    # Replace the default terminal reporter
81    reporter = config.pluginmanager.get_plugin("terminalreporter")
82    if reporter:
83        config.pluginmanager.unregister(reporter)
84        config.pluginmanager.register(
85            RelativeTimeTerminalReporter(config),
86            "terminalreporter",
87        )
class RelativeTimeTerminalReporter(_pytest.terminal.TerminalReporter):
 90class RelativeTimeTerminalReporter(TerminalReporter):
 91    _start_time: None | float
 92
 93    def __init__(self, config: Config, file: TextIO | None = None):
 94        super().__init__(config, file)
 95        self._start_time = None
 96
 97    def pytest_runtest_logstart(self, nodeid, location):
 98        # Set start time on the first test
 99        if self._start_time is None:
100            self._start_time = monotonic()
101        super().pytest_runtest_logstart(nodeid, location)
102
103    def _locationline(self, nodeid, fspath, lineno, domain):
104        original = super()._locationline(nodeid, fspath, lineno, domain)
105        if self._start_time is None:
106            return original
107        elapsed = monotonic() - self._start_time
108        minutes, seconds = divmod(elapsed, 60)
109        timestamp = f"{int(minutes):02d}:{seconds:06.3f}"
110        return f"[+{timestamp}] {original}"
RelativeTimeTerminalReporter(config: _pytest.config.Config, file: TextIO | None = None)
93    def __init__(self, config: Config, file: TextIO | None = None):
94        super().__init__(config, file)
95        self._start_time = None
def pytest_runtest_logstart(self, nodeid, location):
 97    def pytest_runtest_logstart(self, nodeid, location):
 98        # Set start time on the first test
 99        if self._start_time is None:
100            self._start_time = monotonic()
101        super().pytest_runtest_logstart(nodeid, location)