|
| 1 | +import os |
1 | 2 | import sys |
| 3 | +import time |
| 4 | +import socket |
| 5 | +import threading |
| 6 | +from contextlib import contextmanager |
2 | 7 | from pathlib import Path |
| 8 | +from typing import Generator, Iterator |
3 | 9 |
|
4 | 10 | import pytest |
5 | 11 |
|
6 | | - |
7 | 12 | PROJECT_ROOT = Path(__file__).resolve().parent.parent |
8 | 13 |
|
9 | 14 | if str(PROJECT_ROOT) not in sys.path: |
|
13 | 18 | @pytest.fixture |
14 | 19 | def anyio_backend() -> str: |
15 | 20 | return "asyncio" |
| 21 | + |
| 22 | + |
| 23 | +# --------------------------------------------------------------------------- |
| 24 | +# Playwright infrastructure — live server + environment helpers |
| 25 | +# --------------------------------------------------------------------------- |
| 26 | + |
| 27 | +# A fake API key that satisfies AsyncOpenAI()'s constructor without hitting |
| 28 | +# the real OpenAI API. Tests that need the page to behave as if there is NO |
| 29 | +# key write OPENAI_API_KEY= (empty) to .env; load_dotenv(override=True) in |
| 30 | +# the route body then sets the in-process env to "". The Depends lambda |
| 31 | +# runs *before* load_dotenv, so it always sees the fake key and doesn't raise. |
| 32 | +_FAKE_API_KEY = "sk-fake-playwright-test-key" |
| 33 | +_BASE_ENV: dict[str, str] = { |
| 34 | + "OPENAI_API_KEY": _FAKE_API_KEY, |
| 35 | + "RESPONSES_MODEL": "gpt-4o", |
| 36 | + "ENABLED_TOOLS": "", |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +@pytest.fixture(autouse=True) |
| 41 | +def _isolate_asyncio_running_loop(request: pytest.FixtureRequest) -> Iterator[None]: |
| 42 | + """ |
| 43 | + Save and restore asyncio._running_loop around anyio tests. |
| 44 | +
|
| 45 | + Playwright's sync API calls asyncio._set_running_loop(self._loop) after |
| 46 | + each sync operation to mark its paused greenlet loop as "running" from the |
| 47 | + main thread's perspective. anyio's asyncio.Runner raises "Cannot run the |
| 48 | + event loop while another loop is running" if that marker is non-None when |
| 49 | + it starts. |
| 50 | +
|
| 51 | + We therefore clear the marker before each anyio test and restore it |
| 52 | + afterwards so that Playwright's session teardown (browser.close) can still |
| 53 | + reach its paused loop. |
| 54 | + """ |
| 55 | + if not request.node.get_closest_marker("anyio"): |
| 56 | + yield |
| 57 | + return |
| 58 | + |
| 59 | + import asyncio.events as _aio_events |
| 60 | + |
| 61 | + saved = _aio_events._get_running_loop() |
| 62 | + _aio_events._set_running_loop(None) |
| 63 | + try: |
| 64 | + yield |
| 65 | + finally: |
| 66 | + # Clear any loop reference anyio left behind, then restore Playwright's. |
| 67 | + _aio_events._set_running_loop(None) |
| 68 | + if saved is not None: |
| 69 | + _aio_events._set_running_loop(saved) |
| 70 | + |
| 71 | + |
| 72 | +@pytest.fixture(scope="session") |
| 73 | +def app_server() -> Generator[int, None, None]: |
| 74 | + """Start the FastAPI app in a background thread on a free port.""" |
| 75 | + import uvicorn |
| 76 | + from main import app # imported here to avoid polluting the global scope |
| 77 | + |
| 78 | + # Seed the process environment so AsyncOpenAI() can always be instantiated |
| 79 | + # (it validates the key at construction time, before load_dotenv runs). |
| 80 | + os.environ.setdefault("OPENAI_API_KEY", _FAKE_API_KEY) |
| 81 | + os.environ.setdefault("RESPONSES_MODEL", "gpt-4o") |
| 82 | + |
| 83 | + with socket.socket() as s: |
| 84 | + s.bind(("127.0.0.1", 0)) |
| 85 | + port: int = s.getsockname()[1] |
| 86 | + |
| 87 | + config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error") |
| 88 | + server = uvicorn.Server(config) |
| 89 | + thread = threading.Thread(target=server.run, daemon=True) |
| 90 | + thread.start() |
| 91 | + |
| 92 | + # Wait until the server is actually accepting connections (up to 5 s). |
| 93 | + for _ in range(50): |
| 94 | + time.sleep(0.1) |
| 95 | + if server.started: |
| 96 | + break |
| 97 | + |
| 98 | + yield port |
| 99 | + |
| 100 | + server.should_exit = True |
| 101 | + thread.join(timeout=5) |
| 102 | + |
| 103 | + |
| 104 | +@pytest.fixture(scope="session") |
| 105 | +def base_url(app_server: int) -> str: # type: ignore[override] |
| 106 | + """Return the base URL of the running test server.""" |
| 107 | + return f"http://127.0.0.1:{app_server}" |
| 108 | + |
| 109 | + |
| 110 | +@contextmanager |
| 111 | +def _dotenv(overrides: dict[str, str]) -> Iterator[None]: |
| 112 | + """ |
| 113 | + Write a temporary .env for the duration of a single test, then restore. |
| 114 | +
|
| 115 | + Also keeps OPENAI_API_KEY set to the fake value in os.environ so that the |
| 116 | + FastAPI Depends(lambda: AsyncOpenAI()) in route signatures never raises |
| 117 | + before load_dotenv(override=True) has a chance to run inside the route body. |
| 118 | + """ |
| 119 | + env_path = PROJECT_ROOT / ".env" |
| 120 | + |
| 121 | + # Persist the original .env (may not exist). |
| 122 | + try: |
| 123 | + original_text = env_path.read_text() |
| 124 | + except FileNotFoundError: |
| 125 | + original_text = None |
| 126 | + |
| 127 | + # Track the os.environ state for every key we will touch. |
| 128 | + all_keys = set(overrides) | {"OPENAI_API_KEY"} |
| 129 | + original_osenv = {k: os.environ.get(k) for k in all_keys} |
| 130 | + |
| 131 | + # Always keep a fake key in the process env for the Depends constructor. |
| 132 | + os.environ["OPENAI_API_KEY"] = _FAKE_API_KEY |
| 133 | + |
| 134 | + # Write the test-specific .env; the route body's load_dotenv will read it. |
| 135 | + env_path.write_text( |
| 136 | + "\n".join(f"{k}={v}" for k, v in overrides.items()) + "\n" |
| 137 | + ) |
| 138 | + |
| 139 | + try: |
| 140 | + yield |
| 141 | + finally: |
| 142 | + # Restore .env. |
| 143 | + if original_text is not None: |
| 144 | + env_path.write_text(original_text) |
| 145 | + else: |
| 146 | + env_path.unlink(missing_ok=True) |
| 147 | + |
| 148 | + # Restore os.environ. |
| 149 | + for k, orig in original_osenv.items(): |
| 150 | + if orig is not None: |
| 151 | + os.environ[k] = orig |
| 152 | + elif k in os.environ: |
| 153 | + del os.environ[k] |
| 154 | + |
| 155 | + |
| 156 | +# --------------------------------------------------------------------------- |
| 157 | +# Environment fixtures used by test_setup_page_rendering.py |
| 158 | +# --------------------------------------------------------------------------- |
| 159 | + |
| 160 | +@pytest.fixture |
| 161 | +def env_no_api_key(app_server: int) -> Iterator[None]: |
| 162 | + """Setup page should show the API-key form (OPENAI_API_KEY empty).""" |
| 163 | + with _dotenv({"RESPONSES_MODEL": "gpt-4o", "OPENAI_API_KEY": ""}): |
| 164 | + yield |
| 165 | + |
| 166 | + |
| 167 | +@pytest.fixture |
| 168 | +def env_api_key_no_tools(app_server: int) -> Iterator[None]: |
| 169 | + with _dotenv(_BASE_ENV): |
| 170 | + yield |
| 171 | + |
| 172 | + |
| 173 | +@pytest.fixture |
| 174 | +def env_file_search_only(app_server: int) -> Iterator[None]: |
| 175 | + with _dotenv({**_BASE_ENV, "ENABLED_TOOLS": "file_search"}): |
| 176 | + yield |
| 177 | + |
| 178 | + |
| 179 | +@pytest.fixture |
| 180 | +def env_function_only(app_server: int) -> Iterator[None]: |
| 181 | + with _dotenv({**_BASE_ENV, "ENABLED_TOOLS": "function"}): |
| 182 | + yield |
| 183 | + |
| 184 | + |
| 185 | +@pytest.fixture |
| 186 | +def env_mcp_only(app_server: int) -> Iterator[None]: |
| 187 | + with _dotenv({**_BASE_ENV, "ENABLED_TOOLS": "mcp"}): |
| 188 | + yield |
| 189 | + |
| 190 | + |
| 191 | +@pytest.fixture |
| 192 | +def env_file_search_and_function(app_server: int) -> Iterator[None]: |
| 193 | + with _dotenv({**_BASE_ENV, "ENABLED_TOOLS": "file_search,function"}): |
| 194 | + yield |
| 195 | + |
| 196 | + |
| 197 | +@pytest.fixture |
| 198 | +def env_file_search_and_mcp(app_server: int) -> Iterator[None]: |
| 199 | + with _dotenv({**_BASE_ENV, "ENABLED_TOOLS": "file_search,mcp"}): |
| 200 | + yield |
| 201 | + |
| 202 | + |
| 203 | +@pytest.fixture |
| 204 | +def env_function_and_mcp(app_server: int) -> Iterator[None]: |
| 205 | + with _dotenv({**_BASE_ENV, "ENABLED_TOOLS": "function,mcp"}): |
| 206 | + yield |
| 207 | + |
| 208 | + |
| 209 | +@pytest.fixture |
| 210 | +def env_all_tools(app_server: int) -> Iterator[None]: |
| 211 | + with _dotenv({**_BASE_ENV, "ENABLED_TOOLS": "file_search,function,mcp"}): |
| 212 | + yield |
0 commit comments