Files
mvdbeekandClaude Opus 5.5 5bde2ef797 Fix navigate_to flake under Playwright when the page navigates itself
test_navigate_to_outlasts_a_competing_navigation failed two ways, both
reproduced in Docker on Python 3.14 under CPU load:

- The fixture server handled one connection at a time. Chrome sometimes
  opens a connection and never sends a request on it; the server then
  blocked reading it and every later request, including the retried goto,
  queued until Chrome closed the socket - the 30s timeout seen in CI.
  Serve each connection on its own thread.

- navigate_to only treated ERR_ABORTED as losing the race to the page's own
  navigation. When the page's navigation commits first, Playwright instead
  reports goto as "interrupted by another navigation", and Chrome lets ours
  carry on and commit afterwards - interrupting a blind retry in turn.
  Treat both as a lost race, and stop as soon as a navigation of ours lands
  rather than starting another.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 05:17:44 +01:00

106 lines
3.2 KiB
Python

"""Test server infrastructure for running selenium tests locally."""
import http.server
import socketserver
import threading
import time
from pathlib import Path
SLOW_PREFIX = "/slow"
SLOW_DELAY = 0.5
class TestHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
"""Custom request handler for serving test HTML files."""
def __init__(self, *args, directory: str | None = None, **kwargs):
"""Initialize handler with custom directory."""
super().__init__(*args, directory=directory, **kwargs)
def log_message(self, format: str, *args):
"""Suppress log messages during tests."""
pass
def do_GET(self):
"""Serve `/slow/<path>` after a delay, leaving room to race a navigation."""
if self.path.startswith(f"{SLOW_PREFIX}/"):
time.sleep(SLOW_DELAY)
self.path = self.path[len(SLOW_PREFIX) :]
super().do_GET()
def end_headers(self):
"""Override to add test cookies to all responses."""
self.send_header("Set-Cookie", "test_cookie=test_value; Path=/")
super().end_headers()
class ThreadingTestServer(socketserver.ThreadingTCPServer):
"""Handle each connection in its own thread.
A browser can open a connection and never send a request on it - a socket
left over from a navigation it cancelled, say. Served one connection at a
time, every later request would queue behind that one until the browser
closes it.
"""
daemon_threads = True
class TestHTTPServer:
"""Simple HTTP server for serving test HTML pages."""
def __init__(self, port: int = 0, directory: Path | None = None):
"""
Initialize test HTTP server.
Args:
port: Port to bind to (0 for random available port)
directory: Directory to serve files from
"""
self.port = port
self.directory = directory or Path(__file__).parent / "fixtures"
self.server: socketserver.TCPServer | None = None
self.thread: threading.Thread | None = None
def start(self):
"""Start the HTTP server in a background thread."""
def handler(*args, **kwargs):
return TestHTTPRequestHandler(*args, directory=str(self.directory), **kwargs)
self.server = ThreadingTestServer(("localhost", self.port), handler)
self.port = self.server.server_address[1] # Get actual port if 0 was specified
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
def stop(self):
"""Stop the HTTP server."""
if self.server:
self.server.shutdown()
self.server.server_close()
if self.thread:
self.thread.join(timeout=5)
def get_url(self, path: str = "") -> str:
"""
Get full URL for a given path.
Args:
path: Path relative to served directory
Returns:
Full URL including protocol, host, port, and path
"""
path = path.lstrip("/")
return f"http://localhost:{self.port}/{path}"
def __enter__(self):
"""Context manager entry."""
self.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit."""
self.stop()