"""测试配置:每个测试用例使用隔离的内存 SQLite(不依赖远程 MySQL)。""" import pytest from sqlalchemy import create_engine, event from sqlalchemy.orm import sessionmaker from app.core import db as db_module from app.models import Base @pytest.fixture(autouse=True) def _isolate_db(tmp_path, monkeypatch): """每个测试用例:创建独立内存 SQLite → 建表 → 替换全局引擎 → 测试结束自动清理。""" test_db_url = f"sqlite:///{tmp_path}/test.db" engine = create_engine(test_db_url, connect_args={"check_same_thread": False}) @event.listens_for(engine, "connect") def _set_pragma(dbapi_conn, _): cursor = dbapi_conn.cursor() cursor.execute("PRAGMA journal_mode=WAL") cursor.execute("PRAGMA foreign_keys=ON") cursor.close() Base.metadata.create_all(engine) test_factory = sessionmaker(bind=engine, expire_on_commit=False) # 替换全局引擎和 session 工厂 monkeypatch.setattr(db_module, "_engine", engine) monkeypatch.setattr(db_module, "_session_factory", test_factory) # Mock settings 让 is_mysql 返回 False from app.core.config import get_settings, Settings original_settings = get_settings() class TestSettings: """测试用 settings mock,保持 SQLite 行为。""" environment = "local" database_url = test_db_url storage_root = str(tmp_path) default_storage_quota = 104_857_600 default_max_file_size = 20_971_520 rate_limit_per_token_per_min = 60 rate_limit_per_ip_per_min = 30 frontend_origin = "http://localhost:5173" is_production = False is_mysql = False is_sqlite = True @property def storage_root_path(self): from pathlib import Path return Path(self.storage_root) monkeypatch.setattr("app.core.config.get_settings", lambda: TestSettings()) # 清空内存 session 存储 from app.core import session as session_module session_module._store.clear() yield engine.dispose()