Files

95 lines
3.3 KiB
Python

"""AppState 和依赖注入测试."""
import pytest
from src.server.deps import AppState
@pytest.fixture(autouse=True)
def _clean_env(monkeypatch):
"""清除环境变量防止其他测试污染."""
monkeypatch.delenv("MD_VECTOR_DB_COLLECTION", raising=False)
monkeypatch.delenv("MD_VECTOR_DB_DATA_DIR", raising=False)
class TestAppState:
"""AppState 类测试."""
def test_init_with_config(self):
"""使用默认配置初始化."""
state = AppState()
assert state.config is not None
assert state.db is not None
assert state.embedder is not None
assert state.default_collection == state.config.chroma.collection_name
def test_get_searcher_returns_cached(self):
"""同一 collection 多次调用返回同一实例."""
state = AppState()
s1 = state.get_searcher("test_coll")
s2 = state.get_searcher("test_coll")
assert s1 is s2
def test_get_searcher_different_collections(self):
"""不同 collection 返回不同实例."""
state = AppState()
s1 = state.get_searcher("coll_a")
s2 = state.get_searcher("coll_b")
assert s1 is not s2
def test_get_searcher_uses_default_when_none(self):
"""collection 为 None 时使用默认值."""
state = AppState()
s = state.get_searcher(None)
assert s.collection_name == state.default_collection
def test_get_ingestor_returns_cached(self):
"""同一 collection 多次调用返回同一实例."""
state = AppState()
i1 = state.get_ingestor("test_coll")
i2 = state.get_ingestor("test_coll")
assert i1 is i2
def test_default_collection_from_config(self):
"""默认 collection 名从配置读取."""
state = AppState()
assert isinstance(state.default_collection, str)
assert len(state.default_collection) > 0
def test_list_collections_with_stats(self):
"""列出集合统计."""
state = AppState()
result = state.list_collections_with_stats()
assert isinstance(result, list)
def test_is_healthy_returns_status(self):
"""健康检查返回正确结构."""
state = AppState()
result = state.is_healthy()
assert "status" in result
assert "checks" in result
assert "chromadb" in result["checks"]
assert "embedder" in result["checks"]
def test_is_healthy_chromadb_ok(self):
"""健康检查 ChromaDB 正常."""
state = AppState()
result = state.is_healthy()
assert result["checks"]["chromadb"]["status"] == "ok"
def test_is_healthy_embedder_ok(self):
"""健康检查 Embedder 正常."""
state = AppState()
result = state.is_healthy()
assert result["checks"]["embedder"]["status"] == "ok"
def test_is_healthy_no_detail_leak(self):
"""健康检查不泄露内部详情."""
state = AppState()
result = state.is_healthy()
for component in ("chromadb", "embedder"):
detail = result["checks"][component].get("detail", "")
if detail:
# 如果出错,detail 应该是通用消息,不是异常堆栈
assert "unavailable" in str(detail).lower() or len(detail) < 100