| 1 |
""" |
| •2 |
Pytest plugin that manages the mock server lifecycle for wire tests. |
| 3 |
|
| 4 |
This plugin is loaded globally for the test suite and is responsible for |
| •5 |
starting and stopping the mock server exactly once per test run, |
| 6 |
including when running with pytest-xdist over the entire project. |
| 7 |
|
| 8 |
It lives under tests/ (as tests/conftest.py) and is discovered automatically |
| 9 |
by pytest's normal test collection rules. |
| 10 |
""" |
| 11 |
|
| •12 |
import json |
| 13 |
import os |
| •14 |
import re |
| 15 |
import threading |
| 16 |
from http.server import BaseHTTPRequestHandler, HTTPServer |
| 17 |
from socketserver import ThreadingMixIn |
| 18 |
from typing import Any |
| 19 |
from urllib.parse import parse_qs, urlparse |
| 20 |
|
| 21 |
import pytest |
| 22 |
|
| 23 |
_STARTED: bool = False |
| 24 |
_EXTERNAL: bool = False |
| 25 |
_WIREMOCK_URL: str = "http://localhost:8080" |
| 26 |
_PROJECT_NAME: str = "auth0-api" |
| 27 |
|
| 28 |
|
| 29 |
_PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) |
| •30 |
_MAPPINGS_FILE = os.path.join(_PROJECT_ROOT, "wiremock", "wiremock-mappings.json") |
| 31 |
|
| 32 |
_server: "ThreadedHTTPServer | None" = None |
| 33 |
_server_thread: "threading.Thread | None" = None |
| 34 |
_recorded_requests: "list[dict[str, Any]]" = [] |
| 35 |
_lock = threading.Lock() |
| 36 |
_routes: "list[dict[str, Any]]" = [] |
| 37 |
|
| 38 |
|
| 39 |
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): |
| 40 |
daemon_threads = True |
| 41 |
|
| 42 |
|
| 43 |
def _template_to_regex(template: str) -> "re.Pattern[str]": |
| 44 |
parts = re.split(r"(\{[^}]+\})", template) |
| 45 |
regex = "^" + "".join("[^/]+" if p.startswith("{") else re.escape(p) for p in parts) + "$" |
| 46 |
return re.compile(regex) |
| 47 |
|
| 48 |
|
| 49 |
def _load_routes() -> "list[dict[str, Any]]": |
| 50 |
with open(_MAPPINGS_FILE) as f: |
| 51 |
data = json.load(f) |
| 52 |
routes = [] |
| 53 |
for mapping in data.get("mappings", []): |
| 54 |
req = mapping.get("request", {}) |
| 55 |
resp = mapping.get("response", {}) |
| 56 |
template = req.get("urlPathTemplate") or req.get("urlPath", "") |
| 57 |
json_body = resp.get("jsonBody") |
| 58 |
if json_body is not None: |
| 59 |
body = json.dumps(json_body).encode() |
| 60 |
else: |
| 61 |
raw = resp.get("body", "") |
| 62 |
body = raw.encode() if isinstance(raw, str) else b"{}" |
| 63 |
routes.append({ |
| 64 |
"method": req.get("method", "ANY"), |
| 65 |
"pattern": _template_to_regex(template), |
| 66 |
"status": resp.get("status", 200), |
| 67 |
"body": body, |
| 68 |
"headers": resp.get("headers", {}), |
| 69 |
}) |
| 70 |
return routes |
| 71 |
|
| 72 |
|
| 73 |
class _MockHandler(BaseHTTPRequestHandler): |
| 74 |
def _read_body(self) -> bytes: |
| 75 |
length = int(self.headers.get("Content-Length", 0)) |
| 76 |
return self.rfile.read(length) if length else b"" |
| 77 |
|
| 78 |
def _send_response(self, status: int, body: bytes, headers: "dict[str, str]") -> None: |
| 79 |
self.send_response(status) |
| 80 |
content_type = headers.get("Content-Type", "application/json") |
| 81 |
self.send_header("Content-Type", content_type) |
| 82 |
self.send_header("Content-Length", str(len(body))) |
| 83 |
for key, value in headers.items(): |
| 84 |
if key != "Content-Type": |
| 85 |
self.send_header(key, value) |
| 86 |
self.end_headers() |
| 87 |
self.wfile.write(body) |
| 88 |
|
| 89 |
def do_POST(self) -> None: |
| 90 |
if urlparse(self.path).path == "/__admin/requests/find": |
| 91 |
self._admin_find() |
| 92 |
else: |
| 93 |
self._record_and_respond() |
| 94 |
|
| 95 |
def do_GET(self) -> None: |
| 96 |
self._record_and_respond() |
| 97 |
|
| 98 |
def do_PUT(self) -> None: |
| 99 |
self._record_and_respond() |
| 100 |
|
| 101 |
def do_PATCH(self) -> None: |
| 102 |
self._record_and_respond() |
| 103 |
|
| 104 |
def do_DELETE(self) -> None: |
| 105 |
self._record_and_respond() |
| 106 |
|
| 107 |
def _admin_find(self) -> None: |
| 108 |
criteria = json.loads(self._read_body() or b"{}") |
| 109 |
method = criteria.get("method", "") |
| 110 |
url_path = criteria.get("urlPath", "") |
| 111 |
header_criteria = criteria.get("headers", {}) |
| 112 |
query_criteria = criteria.get("queryParameters", {}) |
| 113 |
|
| 114 |
with _lock: |
| 115 |
matching = [ |
| 116 |
r for r in _recorded_requests |
| 117 |
if r["method"] == method |
| 118 |
and r["path"] == url_path |
| 119 |
and all( |
| 120 |
r["headers"].get(h.lower()) == spec.get("equalTo") |
| 121 |
for h, spec in header_criteria.items() |
| 122 |
) |
| 123 |
and all( |
| 124 |
r["query_params"].get(q) == spec.get("equalTo") |
| 125 |
for q, spec in query_criteria.items() |
| 126 |
) |
| 127 |
] |
| 128 |
|
| 129 |
self._send_response(200, json.dumps({"requests": matching}).encode(), {}) |
| 130 |
|
| 131 |
def _record_and_respond(self) -> None: |
| 132 |
self._read_body() |
| 133 |
parsed = urlparse(self.path) |
| 134 |
path = parsed.path |
| 135 |
query_params = {k: v[0] for k, v in parse_qs(parsed.query).items()} |
| 136 |
headers_lc = {k.lower(): v for k, v in self.headers.items()} |
| 137 |
|
| 138 |
with _lock: |
| 139 |
_recorded_requests.append({ |
| 140 |
"method": self.command, |
| 141 |
"path": path, |
| 142 |
"query_params": query_params, |
| 143 |
"headers": headers_lc, |
| 144 |
}) |
| 145 |
|
| 146 |
status, body, resp_headers = 200, b"{}", {} |
| 147 |
for route in _routes: |
| 148 |
if route["method"] in (self.command, "ANY") and route["pattern"].match(path): |
| 149 |
status, body, resp_headers = route["status"], route["body"], route["headers"] |
| 150 |
break |
| 151 |
|
| 152 |
self._send_response(status, body, resp_headers) |
| 153 |
|
| 154 |
def log_message(self, format: str, *args: Any) -> None: |
| 155 |
pass |
| 156 |
|
| 157 |
|
| 158 |
def _is_xdist_worker(config: pytest.Config) -> bool: |
| 159 |
""" |
| 160 |
Determines if the current process is an xdist worker. |
| 161 |
|
| 162 |
In pytest-xdist, worker processes have a 'workerinput' attribute |
| 163 |
on the config object, while the controller process does not. |
| 164 |
""" |
| 165 |
return hasattr(config, "workerinput") |
| 166 |
|
| 167 |
|
| 168 |
def _has_httpx_aiohttp() -> bool: |
| 169 |
"""Check if httpx_aiohttp is importable.""" |
| 170 |
try: |
| 171 |
import httpx_aiohttp |
| 172 |
|
| 173 |
return True |
| 174 |
except ImportError: |
| 175 |
return False |
| 176 |
|
| 177 |
|
| 178 |
def pytest_collection_modifyitems(config: pytest.Config, items: list) -> None: |
| 179 |
"""Auto-skip @pytest.mark.aiohttp tests when httpx_aiohttp is not installed.""" |
| 180 |
if _has_httpx_aiohttp(): |
| 181 |
return |
| 182 |
skip_aiohttp = pytest.mark.skip(reason="httpx_aiohttp not installed") |
| 183 |
for item in items: |
| 184 |
if "aiohttp" in item.keywords: |
| 185 |
item.add_marker(skip_aiohttp) |
| 186 |
|
| 187 |
|
| 188 |
def pytest_configure(config: pytest.Config) -> None: |
| 189 |
""" |
| 190 |
Pytest hook that runs during test session setup. |
| 191 |
|
| •192 |
Starts the mock server only from the controller process (xdist) |
| 193 |
or the single process (non-xdist). This ensures only one server |
| 194 |
is started regardless of the number of worker processes. |
| 195 |
""" |
| •196 |
global _server, _server_thread, _routes, _recorded_requests |
| 197 |
if _is_xdist_worker(config): |
| •198 |
|
| 199 |
return |
| 200 |
|
| •201 |
_routes = _load_routes() |
| 202 |
_recorded_requests = [] |
| 203 |
_server = ThreadedHTTPServer(("127.0.0.1", 0), _MockHandler) |
| 204 |
port = str(_server.server_address[1]) |
| 205 |
os.environ["WIREMOCK_PORT"] = port |
| 206 |
os.environ["WIREMOCK_URL"] = f"http://127.0.0.1:{port}" |
| 207 |
for var in ("no_proxy", "NO_PROXY"): |
| 208 |
existing = os.environ.get(var, "") |
| 209 |
if "127.0.0.1" not in existing: |
| 210 |
os.environ[var] = f"{existing},127.0.0.1" if existing else "127.0.0.1" |
| 211 |
_server_thread = threading.Thread(target=_server.serve_forever, daemon=True) |
| 212 |
_server_thread.start() |
| 213 |
print(f"\nMock HTTP server started on port {port}") |
| 214 |
|
| 215 |
|
| 216 |
def pytest_unconfigure(config: pytest.Config) -> None: |
| 217 |
""" |
| 218 |
Pytest hook that runs during test session teardown. |
| 219 |
|
| •220 |
Stops the mock server only from the controller process (xdist) |
| 221 |
or the single process (non-xdist). This ensures the server is |
| 222 |
cleaned up after all workers have finished. |
| 223 |
""" |
| •224 |
global _server, _server_thread |
| 225 |
if _is_xdist_worker(config): |
| •226 |
|
| 227 |
return |
| 228 |
|
| •229 |
if _server: |
| 230 |
_server.shutdown() |
| 231 |
_server = None |
| 232 |
if _server_thread: |
| 233 |
_server_thread.join(timeout=5) |
| 234 |
_server_thread = None |