-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconftest.py
More file actions
72 lines (52 loc) · 2.4 KB
/
conftest.py
File metadata and controls
72 lines (52 loc) · 2.4 KB
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
"""Shared pytest fixtures for the test suite."""
from __future__ import annotations
import asyncio
import importlib.util
import inspect
from collections.abc import Generator
import pytest
from tools.metrics import metrics_registry
def pytest_addoption(parser: pytest.Parser) -> None:
"""Register configuration options consumed by pytest-asyncio."""
parser.addini("asyncio_mode", "Configure asyncio support", default="auto")
if importlib.util.find_spec("pytest_asyncio") is None: # pragma: no cover - used in constrained environments
@pytest.hookimpl(tryfirst=True)
def pytest_pyfunc_call(pyfuncitem: pytest.Function) -> bool | None:
"""Execute async tests using asyncio when pytest-asyncio is unavailable."""
test_function = pyfuncitem.obj
if inspect.iscoroutinefunction(test_function):
loop = asyncio.new_event_loop()
try:
signature = inspect.signature(test_function)
kwargs = {
name: pyfuncitem.funcargs[name]
for name in signature.parameters
if name in pyfuncitem.funcargs
}
loop.run_until_complete(test_function(**kwargs))
finally:
loop.close()
return True
return None
@pytest.fixture(autouse=True)
def reset_metrics_registry() -> Generator[None, None, None]:
"""Ensure each test starts with a clean metrics registry."""
metrics_registry.reset()
yield
metrics_registry.reset()
@pytest.fixture(autouse=True)
def clear_api_key_environment(monkeypatch: pytest.MonkeyPatch) -> None:
"""Prevent API key configuration from leaking between tests."""
for variable in ("THEMIS_API_KEY", "THEMIS_API_KEY_PREVIOUS", "THEMIS_API_KEYS"):
monkeypatch.delenv(variable, raising=False)
@pytest.fixture(autouse=True)
def restore_rate_limit_state(monkeypatch: pytest.MonkeyPatch) -> None:
"""Reset SlowAPI's request state between tests to avoid cross-test leakage."""
# SlowAPI stores a thread-local state that can retain previous request contexts.
# Clearing the state ensures isolated behaviour in API tests.
try:
from slowapi import context
except Exception: # pragma: no cover - best effort cleanup
return
context._thread_local = context.ThreadLocalState()
monkeypatch.setattr(context, "_thread_local", context.ThreadLocalState())