PayrollManagementSystem/backend/tests/conftest.py

69 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""测试共用夹具。"""
import pytest
from fastapi.testclient import TestClient
@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()
@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()