import subprocess import time from typing import Generator import pytest from playwright.sync_api import Browser, Page, Playwright, sync_playwright # Use a different port for the test server to avoid conflicts TEST_PORT = 8001 BASE_URL = f"http://localhost:{TEST_PORT}" @pytest.fixture(scope="function") def live_server() -> Generator[str, None, None]: """Launch a live test server in a separate process.""" process = subprocess.Popen( ["uvicorn", "main:app", f"--port={TEST_PORT}"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) time.sleep(2) # Give the server a moment to start yield BASE_URL process.terminate() process.wait() @pytest.fixture(scope="session") def playwright_instance() -> Generator[Playwright, None, None]: """Provide a Playwright instance for the test session.""" with sync_playwright() as p: yield p @pytest.fixture(scope="session") def browser( playwright_instance: Playwright, ) -> Generator[Browser, None, None]: """Provide a browser instance for the test session.""" browser = playwright_instance.chromium.launch() yield browser browser.close() @pytest.fixture() def page(browser: Browser, live_server: str) -> Generator[Page, None, None]: """Provide a new page for each test.""" page = browser.new_page(base_url=live_server) yield page page.close()