"""pytest 全局夹具:覆盖 JWT 认证依赖,让现有 API 测试默认以 admin 身份运行 业务接口(search/document/knowledge)已加 Depends(get_current_user)、 DELETE /documents 加了 Depends(require_admin)。这里通过 autouse 夹具把两个依赖 统一替换为返回固定 admin AuthUser 的 lambda,使现有 API 测试无需改动即可通过认证。 单个测试需要走真实认证逻辑时(如 tests/test_auth.py),可在测试函数内 pop 掉对应 override,autouse fixture yield 后会统一 clear。 另外清理 LLM 客户端 / 解析插件 / 去重策略三处进程级缓存,避免跨测试串扰 (不同测试可能注入不同的 redis/ollama 实例,缓存按配置签名而非实例区分)。 """ from datetime import UTC, datetime import pytest from app.core.auth import get_current_user, require_admin from app.main import app from app.models.auth import AuthUser TEST_USER = AuthUser(username="testuser", role="admin", created_at=datetime.now(UTC)) @pytest.fixture(autouse=True) def override_auth(): """所有测试默认以 admin 身份运行;测试结束清理 dependency_overrides""" app.dependency_overrides[get_current_user] = lambda: TEST_USER app.dependency_overrides[require_admin] = lambda: TEST_USER yield app.dependency_overrides.clear() @pytest.fixture(autouse=True) def _invalidate_runtime_caches(): """每个测试前后清理 LLM/解析插件/去重策略进程级缓存 这三处缓存按 runtime_settings 配置签名而非实例区分,跨测试若配置相同 会复用旧实例(绑定到上个测试的 redis/ollama 替身),导致串扰。 """ # 延迟导入避免循环依赖 from app.core.dedup import invalidate_dedup_strategy_cache from app.core.file_parser import invalidate_parser_plugin_cache from app.services.llm import invalidate_llm_client_cache invalidate_llm_client_cache() invalidate_parser_plugin_cache() invalidate_dedup_strategy_cache() yield invalidate_llm_client_cache() invalidate_parser_plugin_cache() invalidate_dedup_strategy_cache()