"""测试共用夹具。""" import pytest from fastapi.testclient import TestClient @pytest.fixture(scope="session") def client() -> TestClient: """构造应用测试客户端(会话级复用,避免重复构建应用)。 注意:测试环境未必有 MySQL/Redis 在跑,健康检查会如实返回 false, 因此断言应聚焦于响应结构而非依赖的连通性。 """ from app.main import app with TestClient(app) as test_client: yield test_client @pytest.fixture def fake_redis(monkeypatch: pytest.MonkeyPatch): """把 Redis 客户端替换为进程内假实现。 验证码的 GETDEL、限流的 INCR/EXPIRE/TTL、黑名单的 SETEX——都只用到 基础字符串命令,fakeredis 能完整覆盖,因此这些逻辑无需起容器即可测试, 单测得以保持秒级。 替换的是 `app.core.redis_client` 的模块级单例,各 service 通过 `get_redis()` 取用,故一处替换即全局生效。 """ import fakeredis from app.core import redis_client fake = fakeredis.FakeRedis(decode_responses=True) monkeypatch.setattr(redis_client, "_client", fake) yield fake fake.close()