|
| 1 | +""" |
| 2 | +Pytest configuration for wire tests. |
| 3 | +
|
| 4 | +This module manages the WireMock container lifecycle for integration tests. |
| 5 | +It is compatible with pytest-xdist parallelization by ensuring only the |
| 6 | +controller process (or the single process in non-xdist runs) starts and |
| 7 | +stops the WireMock container. |
| 8 | +""" |
| 9 | + |
| 10 | +import os |
| 11 | +import subprocess |
| 12 | +from typing import Any, Dict, Optional |
| 13 | + |
| 14 | +import pytest |
| 15 | +import requests |
| 16 | + |
| 17 | +from deepgram.client import DeepgramApi |
| 18 | + |
| 19 | + |
| 20 | +def _compose_file() -> str: |
| 21 | + """Returns the path to the docker-compose file for WireMock.""" |
| 22 | + test_dir = os.path.dirname(__file__) |
| 23 | + project_root = os.path.abspath(os.path.join(test_dir, "..", "..")) |
| 24 | + wiremock_dir = os.path.join(project_root, "wiremock") |
| 25 | + return os.path.join(wiremock_dir, "docker-compose.test.yml") |
| 26 | + |
| 27 | + |
| 28 | +def _start_wiremock() -> None: |
| 29 | + """Starts the WireMock container using docker-compose.""" |
| 30 | + compose_file = _compose_file() |
| 31 | + print("\nStarting WireMock container...") |
| 32 | + try: |
| 33 | + subprocess.run( |
| 34 | + ["docker", "compose", "-f", compose_file, "up", "-d", "--wait"], |
| 35 | + check=True, |
| 36 | + capture_output=True, |
| 37 | + text=True, |
| 38 | + ) |
| 39 | + print("WireMock container is ready") |
| 40 | + except subprocess.CalledProcessError as e: |
| 41 | + print(f"Failed to start WireMock: {e.stderr}") |
| 42 | + raise |
| 43 | + |
| 44 | + |
| 45 | +def _stop_wiremock() -> None: |
| 46 | + """Stops and removes the WireMock container.""" |
| 47 | + compose_file = _compose_file() |
| 48 | + print("\nStopping WireMock container...") |
| 49 | + subprocess.run( |
| 50 | + ["docker", "compose", "-f", compose_file, "down", "-v"], |
| 51 | + check=False, |
| 52 | + capture_output=True, |
| 53 | + ) |
| 54 | + |
| 55 | + |
| 56 | +def _is_xdist_worker(config: pytest.Config) -> bool: |
| 57 | + """ |
| 58 | + Determines if the current process is an xdist worker. |
| 59 | +
|
| 60 | + In pytest-xdist, worker processes have a 'workerinput' attribute |
| 61 | + on the config object, while the controller process does not. |
| 62 | + """ |
| 63 | + return hasattr(config, "workerinput") |
| 64 | + |
| 65 | + |
| 66 | +def pytest_configure(config: pytest.Config) -> None: |
| 67 | + """ |
| 68 | + Pytest hook that runs during test session setup. |
| 69 | +
|
| 70 | + Starts WireMock container only from the controller process (xdist) |
| 71 | + or the single process (non-xdist). This ensures only one container |
| 72 | + is started regardless of the number of worker processes. |
| 73 | + """ |
| 74 | + if not _is_xdist_worker(config): |
| 75 | + _start_wiremock() |
| 76 | + |
| 77 | + |
| 78 | +def pytest_unconfigure(config: pytest.Config) -> None: |
| 79 | + """ |
| 80 | + Pytest hook that runs during test session teardown. |
| 81 | +
|
| 82 | + Stops WireMock container only from the controller process (xdist) |
| 83 | + or the single process (non-xdist). This ensures the container is |
| 84 | + cleaned up after all workers have finished. |
| 85 | + """ |
| 86 | + if not _is_xdist_worker(config): |
| 87 | + _stop_wiremock() |
| 88 | + |
| 89 | + |
| 90 | +def get_client(test_id: str) -> DeepgramApi: |
| 91 | + """ |
| 92 | + Creates a configured client instance for wire tests. |
| 93 | +
|
| 94 | + Args: |
| 95 | + test_id: Unique identifier for the test, used for request tracking. |
| 96 | +
|
| 97 | + Returns: |
| 98 | + A configured client instance with all required auth parameters. |
| 99 | + """ |
| 100 | + return DeepgramApi( |
| 101 | + base_url="http://localhost:8080", |
| 102 | + headers={"X-Test-Id": test_id}, |
| 103 | + api_key="test_api_key", |
| 104 | + ) |
| 105 | + |
| 106 | + |
| 107 | +def verify_request_count( |
| 108 | + test_id: str, |
| 109 | + method: str, |
| 110 | + url_path: str, |
| 111 | + query_params: Optional[Dict[str, str]], |
| 112 | + expected: int, |
| 113 | +) -> None: |
| 114 | + """Verifies the number of requests made to WireMock filtered by test ID for concurrency safety""" |
| 115 | + wiremock_admin_url = "http://localhost:8080/__admin" |
| 116 | + request_body: Dict[str, Any] = { |
| 117 | + "method": method, |
| 118 | + "urlPath": url_path, |
| 119 | + "headers": {"X-Test-Id": {"equalTo": test_id}}, |
| 120 | + } |
| 121 | + if query_params: |
| 122 | + query_parameters = {k: {"equalTo": v} for k, v in query_params.items()} |
| 123 | + request_body["queryParameters"] = query_parameters |
| 124 | + response = requests.post(f"{wiremock_admin_url}/requests/find", json=request_body) |
| 125 | + assert response.status_code == 200, "Failed to query WireMock requests" |
| 126 | + result = response.json() |
| 127 | + requests_found = len(result.get("requests", [])) |
| 128 | + assert requests_found == expected, f"Expected {expected} requests, found {requests_found}" |
0 commit comments