Debian Codegraph @

tests/conftest.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """
2 Pytest plugin that manages the WireMock container lifecycle for wire tests.
3
4 This plugin is loaded globally for the test suite and is responsible for
5 starting and stopping the WireMock container 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 os
13 import subprocess
14
15 import pytest
16
17 _STARTED: bool = False
18 _EXTERNAL: bool = False # True when using an external WireMock instance (skip container lifecycle)
19 _WIREMOCK_URL: str = "http://localhost:8080" # Default, will be updated after container starts
20 _PROJECT_NAME: str = "auth0-api"
21
22 # This file lives at tests/conftest.py, so the project root is one level up.
23 _PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
24 _COMPOSE_FILE = os.path.join(_PROJECT_ROOT, "wiremock", "docker-compose.test.yml")
25
26
27 def _get_wiremock_port() -> str:
28 """Gets the dynamically assigned port for the WireMock container."""
29 try:
30 result = subprocess.run(
31 ["docker", "compose", "-f", _COMPOSE_FILE, "-p", _PROJECT_NAME, "port", "wiremock", "8080"],
32 check=True,
33 capture_output=True,
34 text=True,
35 )
36 # Output is like "0.0.0.0:32768" or "[::]:32768"
37 port = result.stdout.strip().split(":")[-1]
38 return port
39 except subprocess.CalledProcessError:
40 return "8080" # Fallback to default
41
42
43 def _start_wiremock() -> None:
44 """Starts the WireMock container using docker-compose."""
45 global _STARTED, _EXTERNAL, _WIREMOCK_URL
46 if _STARTED:
47 return
48
49 # If WIREMOCK_URL is already set (e.g., by CI/CD pipeline), skip container management
50 existing_url = os.environ.get("WIREMOCK_URL")
51 if existing_url:
52 _WIREMOCK_URL = existing_url
53 _EXTERNAL = True
54 _STARTED = True
55 print(f"\nUsing external WireMock at {_WIREMOCK_URL} (container management skipped)")
56 return
57
58 print(f"\nStarting WireMock container (project: {_PROJECT_NAME})...")
59 try:
60 subprocess.run(
61 ["docker", "compose", "-f", _COMPOSE_FILE, "-p", _PROJECT_NAME, "up", "-d", "--wait"],
62 check=True,
63 capture_output=True,
64 text=True,
65 )
66 _WIREMOCK_PORT = _get_wiremock_port()
67 _WIREMOCK_URL = f"http://localhost:{_WIREMOCK_PORT}"
68 os.environ["WIREMOCK_URL"] = _WIREMOCK_URL
69 print(f"WireMock container is ready at {_WIREMOCK_URL}")
70 _STARTED = True
71 except subprocess.CalledProcessError as e:
72 print(f"Failed to start WireMock: {e.stderr}")
73 raise
74
75
76 def _stop_wiremock() -> None:
77 """Stops and removes the WireMock container."""
78 if _EXTERNAL:
79 # Container is managed externally; nothing to tear down.
80 return
81
82 print("\nStopping WireMock container...")
83 subprocess.run(
84 ["docker", "compose", "-f", _COMPOSE_FILE, "-p", _PROJECT_NAME, "down", "-v"],
85 check=False,
86 capture_output=True,
87 )
88
89
90 def _is_xdist_worker(config: pytest.Config) -> bool:
91 """
92 Determines if the current process is an xdist worker.
93
94 In pytest-xdist, worker processes have a 'workerinput' attribute
95 on the config object, while the controller process does not.
96 """
97 return hasattr(config, "workerinput")
98
99
100 def _has_httpx_aiohttp() -> bool:
101 """Check if httpx_aiohttp is importable."""
102 try:
103 import httpx_aiohttp # type: ignore[import-not-found] # noqa: F401
104
105 return True
106 except ImportError:
107 return False
108
109
110 def pytest_collection_modifyitems(config: pytest.Config, items: list) -> None:
111 """Auto-skip @pytest.mark.aiohttp tests when httpx_aiohttp is not installed."""
112 if _has_httpx_aiohttp():
113 return
114 skip_aiohttp = pytest.mark.skip(reason="httpx_aiohttp not installed")
115 for item in items:
116 if "aiohttp" in item.keywords:
117 item.add_marker(skip_aiohttp)
118
119
120 def pytest_configure(config: pytest.Config) -> None:
121 """
122 Pytest hook that runs during test session setup.
123
124 Starts WireMock container only from the controller process (xdist)
125 or the single process (non-xdist). This ensures only one container
126 is started regardless of the number of worker processes.
127 """
128 if _is_xdist_worker(config):
129 # Workers never manage the container lifecycle.
130 return
131
132 _start_wiremock()
133
134
135 def pytest_unconfigure(config: pytest.Config) -> None:
136 """
137 Pytest hook that runs during test session teardown.
138
139 Stops WireMock container only from the controller process (xdist)
140 or the single process (non-xdist). This ensures the container is
141 cleaned up after all workers have finished.
142 """
143 if _is_xdist_worker(config):
144 # Workers never manage the container lifecycle.
145 return
146
147 _stop_wiremock()