"""pytest 夹具。 单元测试(``test_calc_*``)不碰数据库,纯算公式,跑得快也不依赖环境。 接口测试要连库,用的是配置文件里那台测试库;连不上就整组 skip, 不让"没连上内网"伪装成"代码有 bug"。 """ from __future__ import annotations import os import sys import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from app.config import settings # noqa: E402 # 测试默认不把账号口令送去问真 Hub:hubtest 在不在、这个账号有没有、口令对不对, # 都不该成为本地用例的前提。要验这条路本身,用 test_hub_integration 里的 hub_on # 加假 httpx 自己把它打开。 settings.hub.login_mode = "local" def _database_reachable() -> bool: try: from app.db import ensure_database, get_engine ensure_database() with get_engine().connect() as connection: connection.exec_driver_sql("SELECT 1") return True except Exception: return False DB_READY = _database_reachable() @pytest.fixture(scope="session") def client(): if not DB_READY: pytest.skip(f"测试库 {settings.database.host}:{settings.database.port} 连不上") from fastapi.testclient import TestClient from app.main import app with TestClient(app) as test_client: yield test_client @pytest.fixture(scope="session", autouse=True) def _admin_not_left_locked(): """收尾把内置超管的失败计数与锁定状态清干净。 用例里有专门试错口令的那类,一次给 ``login_failed_count`` 加一点;攒够 ``login_max_errors`` 就是锁号 ``login_lock_minutes`` 分钟,下一轮连 ``admin_headers`` 都登不进去,报出来是满屏 429 locked,看着像代码坏了。 开发库上这个账号只服务于用例,跑完清零;中途手滑锁的号也顺手解开。 """ yield if not DB_READY: return from sqlalchemy import select from app.db import SessionFactory from app.models import Account session = SessionFactory()() try: names = {settings.seed.admin_account or "admin", (settings.seed.emergency_account or "").strip()} for name in {n for n in names if n}: row = session.execute( select(Account).where(Account.account == name) ).scalars().first() if row is not None and (row.login_failed_count or row.locked_until): row.login_failed_count = 0 row.locked_until = None session.commit() finally: session.close() @pytest.fixture(scope="session") def admin_headers(client): response = client.post("/api/v1/auth/login", json={ "account": settings.seed.admin_account or "admin", "password": settings.seed.admin_password or "Admin@12345", }) assert response.status_code == 200, ( f"{response.text}(内置超管 {settings.seed.admin_account} 登不上,整组接口用例都会 " f"ERROR;先确认这个账号没被锁、口令还是配置档里的 [seed] admin_password)" ) return {"Authorization": "Bearer " + response.json()["data"]["accessToken"]}