test(scripts): restore real websockets module before repro smoke test

Some earlier tests in the suite replace sys.modules['websockets'] with
a stub. When the smoke test ran after those, uvicorn's
websockets-sansio backend tried to import websockets.server at connect
time, resolved through the stub, and failed with
'No module named websockets.server; websockets is not a package',
preventing the mock proxy from starting.

Add an autouse fixture that drops stub websockets.* entries from
sys.modules, re-imports the real package + websockets.asyncio.server,
and restores prior state on teardown. Keeps the smoke test
deterministic regardless of collection order.
This commit is contained in:
Adryan Eka Vandra 2026-04-17 16:01:24 +07:00
parent ea0d519677
commit 30e7b7c498
No known key found for this signature in database
GPG key ID: A46A577A26A97682

View file

@ -13,6 +13,7 @@ from __future__ import annotations
import asyncio
import contextlib
import importlib
import io
import socket
import sys
@ -24,6 +25,30 @@ import pytest
import uvicorn
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
@pytest.fixture(autouse=True)
def _restore_real_websockets_module() -> Iterator[None]:
"""Some earlier tests replace ``sys.modules['websockets']`` with a stub.
uvicorn's websockets-sansio backend imports ``websockets.server`` at
connect time; if a stub is installed the import fails and the mock
proxy never starts. Force-reload the real package before this test.
"""
originals = {
name: sys.modules.pop(name, None)
for name in list(sys.modules)
if name == "websockets" or name.startswith("websockets.")
}
importlib.import_module("websockets")
importlib.import_module("websockets.asyncio.server")
yield
for name in list(sys.modules):
if name == "websockets" or name.startswith("websockets."):
del sys.modules[name]
for name, mod in originals.items():
if mod is not None:
sys.modules[name] = mod
# Make sure `scripts/` is importable when running via pytest from repo root.
ROOT = Path(__file__).resolve().parents[2]
SCRIPTS_DIR = ROOT / "scripts"