|
| 1 | +""" |
| 2 | +Shared test fixtures for violetear. |
| 3 | +
|
| 4 | +Most of the suite runs against `TestClient` (sync, in-process). The e2e tests |
| 5 | +(marked `@pytest.mark.e2e`) need a real port-bound server because Playwright |
| 6 | +drives a real Chromium that fetches HTTP/WS resources from a URL. |
| 7 | +""" |
| 8 | + |
| 9 | +import importlib.util |
| 10 | +import os |
| 11 | +import socket |
| 12 | +import sys |
| 13 | +import threading |
| 14 | +import time |
| 15 | +from pathlib import Path |
| 16 | +from typing import Callable |
| 17 | + |
| 18 | +import httpx |
| 19 | +import pytest |
| 20 | +import uvicorn |
| 21 | + |
| 22 | +REPO_ROOT = Path(__file__).resolve().parent.parent |
| 23 | +EXAMPLES_DIR = REPO_ROOT / "examples" |
| 24 | + |
| 25 | + |
| 26 | +# ---- Playwright browser-launch override ------------------------------------ |
| 27 | +# pytest-playwright defaults to the `chromium_headless_shell-<rev>` binary for |
| 28 | +# headless mode. On systems where that variant isn't installed (e.g. the full |
| 29 | +# `chromium-<rev>` was installed but the headless-shell wasn't), we fall back |
| 30 | +# to launching the full chromium binary in headless mode. This avoids the |
| 31 | +# common "Executable doesn't exist at .../chrome-headless-shell" error when |
| 32 | +# CI or dev has only one of the two variants on disk. |
| 33 | + |
| 34 | + |
| 35 | +def _find_full_chromium() -> str | None: |
| 36 | + """Locate a usable full chromium binary under PLAYWRIGHT_BROWSERS_PATH.""" |
| 37 | + root = Path( |
| 38 | + os.environ.get("PLAYWRIGHT_BROWSERS_PATH") |
| 39 | + or (Path.home() / ".cache" / "ms-playwright") |
| 40 | + ) |
| 41 | + if not root.exists(): |
| 42 | + return None |
| 43 | + # Pick the newest chromium-<rev>/chrome-linux64/chrome on disk. |
| 44 | + candidates = sorted(root.glob("chromium-*/chrome-linux64/chrome"), reverse=True) |
| 45 | + return str(candidates[0]) if candidates else None |
| 46 | + |
| 47 | + |
| 48 | +@pytest.fixture(scope="session") |
| 49 | +def browser_type_launch_args(browser_type_launch_args): |
| 50 | + """Override pytest-playwright's launch args to use the full chromium |
| 51 | + binary instead of the headless_shell variant. |
| 52 | +
|
| 53 | + pytest-playwright defaults to a `chromium_headless_shell-<rev>` binary |
| 54 | + that often isn't installed (the standard `playwright install chromium` |
| 55 | + sometimes only fetches the full chromium). Pointing executable_path at |
| 56 | + the full chromium with headless launch produces equivalent behavior |
| 57 | + without the version-mismatch error. |
| 58 | +
|
| 59 | + Set VIOLETEAR_PLAYWRIGHT_USE_HEADLESS_SHELL=1 to opt out of the override. |
| 60 | + """ |
| 61 | + args = dict(browser_type_launch_args) |
| 62 | + if os.environ.get("VIOLETEAR_PLAYWRIGHT_USE_HEADLESS_SHELL"): |
| 63 | + return args |
| 64 | + chromium = _find_full_chromium() |
| 65 | + if chromium: |
| 66 | + args["executable_path"] = chromium |
| 67 | + return args |
| 68 | + |
| 69 | + |
| 70 | +def _free_port() -> int: |
| 71 | + """Bind to port 0, get the OS-assigned port, release. Standard race-tolerant |
| 72 | + pattern — there's a tiny window between release and uvicorn binding but |
| 73 | + uvicorn errors loudly if it can't bind.""" |
| 74 | + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
| 75 | + s.bind(("127.0.0.1", 0)) |
| 76 | + return s.getsockname()[1] |
| 77 | + |
| 78 | + |
| 79 | +def _load_example(filename: str): |
| 80 | + """Import an example module by filename, registering in sys.modules first |
| 81 | + so violetear's bundle generator can call inspect.getsource on its state |
| 82 | + classes (see issues/7.5).""" |
| 83 | + name = filename.removesuffix(".py").replace(".", "_") |
| 84 | + spec = importlib.util.spec_from_file_location(name, EXAMPLES_DIR / filename) |
| 85 | + module = importlib.util.module_from_spec(spec) |
| 86 | + sys.modules[name] = module |
| 87 | + spec.loader.exec_module(module) |
| 88 | + return module |
| 89 | + |
| 90 | + |
| 91 | +@pytest.fixture(scope="session", autouse=True) |
| 92 | +def _pyodide_cache_prewarm(): |
| 93 | + """Pre-warm the Pyodide local cache once per test session. |
| 94 | +
|
| 95 | + Without this, the first e2e test that loads a real page triggers a ~14MB |
| 96 | + download from jsDelivr — fine in dev but flaky in CI and slow on a cold |
| 97 | + runner. Calling _ensure_pyodide_cached() here populates the cache early |
| 98 | + (or no-ops if it already exists from a prior run / a CI cache restore). |
| 99 | +
|
| 100 | + Marked autouse so any e2e test inherits a warm cache without opting in. |
| 101 | + """ |
| 102 | + from violetear.app import _ensure_pyodide_cached |
| 103 | + |
| 104 | + _ensure_pyodide_cached() |
| 105 | + |
| 106 | + |
| 107 | +@pytest.fixture |
| 108 | +def example_server() -> Callable[[str], str]: |
| 109 | + """Boot one of the canonical examples on a free port via uvicorn-in-thread, |
| 110 | + yield a factory that returns the base URL. The server tears down at end of |
| 111 | + test.""" |
| 112 | + servers: list[tuple[uvicorn.Server, threading.Thread]] = [] |
| 113 | + |
| 114 | + def _start(filename: str) -> str: |
| 115 | + port = _free_port() |
| 116 | + module = _load_example(filename) |
| 117 | + |
| 118 | + config = uvicorn.Config( |
| 119 | + module.app.api, |
| 120 | + host="127.0.0.1", |
| 121 | + port=port, |
| 122 | + log_level="warning", |
| 123 | + lifespan="on", |
| 124 | + ) |
| 125 | + server = uvicorn.Server(config) |
| 126 | + thread = threading.Thread(target=server.run, daemon=True) |
| 127 | + thread.start() |
| 128 | + servers.append((server, thread)) |
| 129 | + |
| 130 | + # Wait for the server to actually accept connections. |
| 131 | + base = f"http://127.0.0.1:{port}" |
| 132 | + deadline = time.monotonic() + 10.0 |
| 133 | + while time.monotonic() < deadline: |
| 134 | + try: |
| 135 | + httpx.get(base + "/", timeout=0.4) |
| 136 | + return base |
| 137 | + except httpx.HTTPError: |
| 138 | + time.sleep(0.05) |
| 139 | + raise RuntimeError(f"Example server {filename} did not start within 10s") |
| 140 | + |
| 141 | + yield _start |
| 142 | + |
| 143 | + # Teardown — request graceful exit, give it a moment, then drop the threads. |
| 144 | + for server, _thread in servers: |
| 145 | + server.should_exit = True |
| 146 | + for _server, thread in servers: |
| 147 | + thread.join(timeout=3.0) |
0 commit comments