2026-10-09 06:46:36 -04:00
|
|
|
|
"""测试共用夹具。"""
|
|
|
|
|
|
|
|
|
|
|
|
import pytest
|
|
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-27 23:42:15 -04:00
|
|
|
|
@pytest.fixture
|
|
|
|
|
|
def tplus_session(monkeypatch):
|
|
|
|
|
|
"""T+ 管理逻辑的真实内存事务;MySQL 并发锁另做集成验证。"""
|
|
|
|
|
|
from sqlalchemy import DefaultClause, Integer, MetaData, create_engine, text
|
|
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
|
|
|
|
|
|
|
|
from app.core.config import Settings
|
|
|
|
|
|
from app.models import TPlusSyncBatch, TPlusSyncError, TPlusSyncRecord
|
|
|
|
|
|
|
|
|
|
|
|
engine = create_engine("sqlite:///:memory:")
|
|
|
|
|
|
metadata = MetaData()
|
|
|
|
|
|
for model in (TPlusSyncBatch, TPlusSyncError, TPlusSyncRecord):
|
|
|
|
|
|
table = model.__table__.to_metadata(metadata)
|
|
|
|
|
|
table.c.id.type = Integer()
|
|
|
|
|
|
table.c.update_time.server_default = DefaultClause(text("CURRENT_TIMESTAMP"))
|
|
|
|
|
|
metadata.create_all(engine)
|
|
|
|
|
|
settings = Settings(
|
|
|
|
|
|
_env_file=None,
|
|
|
|
|
|
app_secret_key="x" * 32,
|
|
|
|
|
|
t_plus_enabled=True,
|
|
|
|
|
|
t_plus_database="unit_tplus",
|
|
|
|
|
|
t_plus_user="reader",
|
|
|
|
|
|
t_plus_odbc_driver="unit",
|
|
|
|
|
|
)
|
|
|
|
|
|
monkeypatch.setattr("app.services.tplus.task_service.get_settings", lambda: settings)
|
|
|
|
|
|
with Session(engine, expire_on_commit=False) as session:
|
|
|
|
|
|
yield session
|
|
|
|
|
|
engine.dispose()
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-09 06:46:36 -04:00
|
|
|
|
@pytest.fixture(scope="session")
|
|
|
|
|
|
def client() -> TestClient:
|
|
|
|
|
|
"""构造应用测试客户端(会话级复用,避免重复构建应用)。
|
|
|
|
|
|
|
|
|
|
|
|
注意:测试环境未必有 MySQL/Redis 在跑,健康检查会如实返回 false,
|
|
|
|
|
|
因此断言应聚焦于响应结构而非依赖的连通性。
|
|
|
|
|
|
"""
|
2026-11-02 22:20:55 -05:00
|
|
|
|
from unittest.mock import patch
|
|
|
|
|
|
|
2026-10-09 06:46:36 -04:00
|
|
|
|
from app.main import app
|
|
|
|
|
|
|
2026-11-02 22:20:55 -05:00
|
|
|
|
# 测试客户端不启动后台采集,避免单测通过环境配置写入现有业务库。
|
|
|
|
|
|
with (
|
|
|
|
|
|
patch.object(app.state.monitor, "start"),
|
|
|
|
|
|
patch.object(app.state.monitor, "stop"),
|
|
|
|
|
|
TestClient(app) as test_client,
|
|
|
|
|
|
):
|
2026-10-09 06:46:36 -04:00
|
|
|
|
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()
|