""" Pytest plugin that manages the mock server lifecycle for wire tests. This plugin is loaded globally for the test suite and is responsible for starting and stopping the mock server exactly once per test run, including when running with pytest-xdist over the entire project. It lives under tests/ (as tests/conftest.py) and is discovered automatically by pytest's normal test collection rules. """ import json import os import re import threading from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn from typing import Any from urllib.parse import parse_qs, urlparse import pytest _STARTED: bool = False _EXTERNAL: bool = False # True when using an external WireMock instance (skip container lifecycle) _WIREMOCK_URL: str = "http://localhost:8080" # Default, will be updated after container starts _PROJECT_NAME: str = "auth0-api" # This file lives at tests/conftest.py, so the project root is one level up. _PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) _MAPPINGS_FILE = os.path.join(_PROJECT_ROOT, "wiremock", "wiremock-mappings.json") _server: "ThreadedHTTPServer | None" = None _server_thread: "threading.Thread | None" = None _recorded_requests: "list[dict[str, Any]]" = [] _lock = threading.Lock() _routes: "list[dict[str, Any]]" = [] class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): daemon_threads = True def _template_to_regex(template: str) -> "re.Pattern[str]": parts = re.split(r"(\{[^}]+\})", template) regex = "^" + "".join("[^/]+" if p.startswith("{") else re.escape(p) for p in parts) + "$" return re.compile(regex) def _load_routes() -> "list[dict[str, Any]]": with open(_MAPPINGS_FILE) as f: data = json.load(f) routes = [] for mapping in data.get("mappings", []): req = mapping.get("request", {}) resp = mapping.get("response", {}) template = req.get("urlPathTemplate") or req.get("urlPath", "") json_body = resp.get("jsonBody") if json_body is not None: body = json.dumps(json_body).encode() else: raw = resp.get("body", "") body = raw.encode() if isinstance(raw, str) else b"{}" routes.append({ "method": req.get("method", "ANY"), "pattern": _template_to_regex(template), "status": resp.get("status", 200), "body": body, "headers": resp.get("headers", {}), }) return routes class _MockHandler(BaseHTTPRequestHandler): def _read_body(self) -> bytes: length = int(self.headers.get("Content-Length", 0)) return self.rfile.read(length) if length else b"" def _send_response(self, status: int, body: bytes, headers: "dict[str, str]") -> None: self.send_response(status) content_type = headers.get("Content-Type", "application/json") self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) for key, value in headers.items(): if key != "Content-Type": self.send_header(key, value) self.end_headers() self.wfile.write(body) def do_POST(self) -> None: if urlparse(self.path).path == "/__admin/requests/find": self._admin_find() else: self._record_and_respond() def do_GET(self) -> None: self._record_and_respond() def do_PUT(self) -> None: self._record_and_respond() def do_PATCH(self) -> None: self._record_and_respond() def do_DELETE(self) -> None: self._record_and_respond() def _admin_find(self) -> None: criteria = json.loads(self._read_body() or b"{}") method = criteria.get("method", "") url_path = criteria.get("urlPath", "") header_criteria = criteria.get("headers", {}) query_criteria = criteria.get("queryParameters", {}) with _lock: matching = [ r for r in _recorded_requests if r["method"] == method and r["path"] == url_path and all( r["headers"].get(h.lower()) == spec.get("equalTo") for h, spec in header_criteria.items() ) and all( r["query_params"].get(q) == spec.get("equalTo") for q, spec in query_criteria.items() ) ] self._send_response(200, json.dumps({"requests": matching}).encode(), {}) def _record_and_respond(self) -> None: self._read_body() # consume to keep connection clean parsed = urlparse(self.path) path = parsed.path query_params = {k: v[0] for k, v in parse_qs(parsed.query).items()} headers_lc = {k.lower(): v for k, v in self.headers.items()} with _lock: _recorded_requests.append({ "method": self.command, "path": path, "query_params": query_params, "headers": headers_lc, }) status, body, resp_headers = 200, b"{}", {} for route in _routes: if route["method"] in (self.command, "ANY") and route["pattern"].match(path): status, body, resp_headers = route["status"], route["body"], route["headers"] break self._send_response(status, body, resp_headers) def log_message(self, format: str, *args: Any) -> None: pass # suppress per-request log noise def _is_xdist_worker(config: pytest.Config) -> bool: """ Determines if the current process is an xdist worker. In pytest-xdist, worker processes have a 'workerinput' attribute on the config object, while the controller process does not. """ return hasattr(config, "workerinput") def _has_httpx_aiohttp() -> bool: """Check if httpx_aiohttp is importable.""" try: import httpx_aiohttp # type: ignore[import-not-found] # noqa: F401 return True except ImportError: return False def pytest_collection_modifyitems(config: pytest.Config, items: list) -> None: """Auto-skip @pytest.mark.aiohttp tests when httpx_aiohttp is not installed.""" if _has_httpx_aiohttp(): return skip_aiohttp = pytest.mark.skip(reason="httpx_aiohttp not installed") for item in items: if "aiohttp" in item.keywords: item.add_marker(skip_aiohttp) def pytest_configure(config: pytest.Config) -> None: """ Pytest hook that runs during test session setup. Starts the mock server only from the controller process (xdist) or the single process (non-xdist). This ensures only one server is started regardless of the number of worker processes. """ global _server, _server_thread, _routes, _recorded_requests if _is_xdist_worker(config): # Workers never manage the server lifecycle. return _routes = _load_routes() _recorded_requests = [] _server = ThreadedHTTPServer(("127.0.0.1", 0), _MockHandler) port = str(_server.server_address[1]) os.environ["WIREMOCK_PORT"] = port os.environ["WIREMOCK_URL"] = f"http://127.0.0.1:{port}" for var in ("no_proxy", "NO_PROXY"): existing = os.environ.get(var, "") if "127.0.0.1" not in existing: os.environ[var] = f"{existing},127.0.0.1" if existing else "127.0.0.1" _server_thread = threading.Thread(target=_server.serve_forever, daemon=True) _server_thread.start() print(f"\nMock HTTP server started on port {port}") def pytest_unconfigure(config: pytest.Config) -> None: """ Pytest hook that runs during test session teardown. Stops the mock server only from the controller process (xdist) or the single process (non-xdist). This ensures the server is cleaned up after all workers have finished. """ global _server, _server_thread if _is_xdist_worker(config): # Workers never manage the server lifecycle. return if _server: _server.shutdown() _server = None if _server_thread: _server_thread.join(timeout=5) _server_thread = None