diff --git a/tests/test_trading_api.py b/tests/test_trading_api.py index fae4ff5..eba05e7 100644 --- a/tests/test_trading_api.py +++ b/tests/test_trading_api.py @@ -11,7 +11,8 @@ from fastapi.testclient import TestClient from app.shared.config import get_settings from app.shared.errors import CartOperationError, NotLoggedInError -from app.trading.main import create_app +from app.trading import main as trading_main +from app.trading.container import TradingContainer from app.trading.services.auth_session import AuthStatus TOKEN = get_settings().bearer_token @@ -68,6 +69,9 @@ class StubAuthSession: if not self.logged_in: raise NotLoggedInError(site=site, detail="stub") + async def start(self) -> None: + """模拟 lifespan 启动;桩不持有真实客户端。""" + async def close(self) -> None: """lifespan 收尾会调用;桩没有真实客户端要关""" @@ -139,18 +143,30 @@ class StubSiteInteractor: "detail": "连接正常" if self.browser_alive else "浏览器已掉线", } + async def start(self) -> None: + """模拟 lifespan 启动;桩不启动 Playwright。""" + async def close(self) -> None: """lifespan 收尾会调用;桩没有真实浏览器要关""" @pytest.fixture -def client_and_stubs(): - app = create_app() +def client_and_stubs(monkeypatch): + """在 lifespan 之前注入桩,确保离线 API 测试不启动 Playwright。""" + stub = StubAuthSession() + stub_site = StubSiteInteractor() + settings = get_settings().model_copy(update={"auto_login_on_start": False}) + + def build_test_container() -> TradingContainer: + return TradingContainer( + settings=settings, + auth_session=stub, # type: ignore[arg-type] + site=stub_site, + ) + + monkeypatch.setattr(trading_main, "build_container", build_test_container) + app = trading_main.create_app() with TestClient(app) as client: - stub = StubAuthSession() - stub_site = StubSiteInteractor() - app.state.container.auth_session = stub - app.state.container.site = stub_site yield client, stub, stub_site