包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
184 lines
6.8 KiB
Python
184 lines
6.8 KiB
Python
"""
|
||
知识库链路单元测试
|
||
==================
|
||
|
||
【功能说明】
|
||
覆盖文档解析、文本切分、知识服务入库与检索全链路,
|
||
用小型构造素材做确定性验证,不依赖外部模型服务。
|
||
|
||
【技术选型理由】
|
||
1. 用本地 ONNX 向量化(chromadb 内置)做测试:无需网络与 API 密钥,
|
||
测试可重复、可离线跑,符合 CI 友好原则。
|
||
2. 测试素材放 D 盘临时目录(pytest_tmp),与生产数据隔离。
|
||
|
||
【实现思路】
|
||
- 构造 md/docx 测试文件 → 验证解析与切分;
|
||
- 用小规模文本入库 → 验证检索能召回相关内容;
|
||
- 验证降级路径:空库检索、不存在目录入库。
|
||
|
||
【潜在风险与应对】
|
||
风险1:本地嵌入模型首次下载慢/无网。
|
||
应对:测试用例优先验证解析/切分等纯逻辑;向量检索用例标记
|
||
pytest.mark.slow,无网环境下可 -m 'not slow' 跳过。
|
||
风险2:测试污染生产 Chroma 目录。
|
||
应对:向量库路径指向 pytest_tmp,跑完即销毁。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import shutil
|
||
from pathlib import Path
|
||
from typing import Generator
|
||
from uuid import uuid4
|
||
|
||
import pytest
|
||
|
||
from app.knowledge.document_loader import load_directory, load_file
|
||
from app.knowledge.knowledge_service import KnowledgeService
|
||
from app.knowledge.text_splitter import split_documents
|
||
from app.knowledge.vector_store import KnowledgeVectorStore
|
||
|
||
|
||
# ---------- Fixtures ----------
|
||
|
||
|
||
@pytest.fixture()
|
||
def d_tmp_path() -> Generator[Path, None, None]:
|
||
"""测试专用临时目录(强制 D 盘,与硬约束 6 一致)。"""
|
||
base = Path(r"D:\Agent\pytest_tmp")
|
||
base.mkdir(parents=True, exist_ok=True)
|
||
work = base / uuid4().hex[:12]
|
||
work.mkdir(parents=True, exist_ok=True)
|
||
yield work
|
||
shutil.rmtree(work, ignore_errors=True)
|
||
|
||
|
||
@pytest.fixture()
|
||
def sample_materials(d_tmp_path: Path) -> Path:
|
||
"""构造一份小型知识库素材目录(含 md + txt 噪声文件)。"""
|
||
mats = d_tmp_path / "需向量化数据"
|
||
mats.mkdir(parents=True, exist_ok=True)
|
||
|
||
(mats / "网关离线排查.md").write_text(
|
||
"# 网关离线排查手册\n\n"
|
||
"## 现象\n\n网关设备显示离线,无法上报物模型数据。\n\n"
|
||
"## 排查步骤\n\n"
|
||
"1. 检查 MQTT 连接是否正常\n"
|
||
"2. 检查 NTP 时间同步是否偏差过大\n"
|
||
"3. 检查设备证书是否过期\n\n"
|
||
"## 处理方案\n\n重启网关进程并观察在线状态恢复情况。\n",
|
||
encoding="utf-8",
|
||
)
|
||
(mats / "物模型null排查.md").write_text(
|
||
"# 物模型值为 null 问题排查\n\n"
|
||
"## 常见原因\n\n"
|
||
"物模型值为 null 通常是数据采集链路中断或字段映射配置错误导致。\n\n"
|
||
"## 解决办法\n\n检查采集插件配置与字段映射表,确认数据源正常。\n",
|
||
encoding="utf-8",
|
||
)
|
||
# 噪声文件:应被跳过
|
||
(mats / "截图.png").write_bytes(b"\x89PNG_fake")
|
||
(mats / "部署包.zip").write_bytes(b"PK_fake")
|
||
return mats
|
||
|
||
|
||
# ---------- 文档解析 ----------
|
||
|
||
|
||
def test_load_markdown(sample_materials: Path) -> None:
|
||
"""Markdown 解析:能读出正文并带来源元数据。"""
|
||
docs = load_file(sample_materials / "网关离线排查.md")
|
||
assert len(docs) == 1
|
||
assert "网关离线排查手册" in docs[0].page_content
|
||
assert docs[0].metadata["file_type"] == "markdown"
|
||
assert docs[0].metadata["filename"] == "网关离线排查.md"
|
||
|
||
|
||
def test_load_directory_skips_unsupported(sample_materials: Path) -> None:
|
||
"""目录扫描:图片/压缩包被跳过并记 warning,md 被解析。"""
|
||
docs, warnings = load_directory(sample_materials)
|
||
assert len(docs) == 2 # 两篇 md
|
||
assert any("截图.png" in w for w in warnings)
|
||
assert any("部署包.zip" in w for w in warnings)
|
||
|
||
|
||
def test_load_directory_missing() -> None:
|
||
"""不存在的目录:返回空文档 + 告警,不抛异常(硬约束 5)。"""
|
||
docs, warnings = load_directory(Path(r"D:\Agent\agent\data\不存在的目录"))
|
||
assert docs == []
|
||
assert any("目录不存在" in w for w in warnings)
|
||
|
||
|
||
# ---------- 文本切分 ----------
|
||
|
||
|
||
def test_split_markdown_keeps_structure(sample_materials: Path) -> None:
|
||
"""Markdown 切分:按标题语义拆分,chunk 带 header 元数据。"""
|
||
docs = load_file(sample_materials / "网关离线排查.md")
|
||
chunks = split_documents(docs)
|
||
assert len(chunks) >= 2 # 至少拆出「现象/排查步骤/处理方案」若干块
|
||
# 所有 chunk 都应带来源信息
|
||
for c in chunks:
|
||
assert c.metadata.get("filename") == "网关离线排查.md"
|
||
assert "chunk_index" in c.metadata
|
||
|
||
|
||
def test_split_empty_text_no_chunks() -> None:
|
||
"""空文本不产生 chunk。"""
|
||
from app.knowledge.document_loader import LoadedDocument
|
||
|
||
chunks = split_documents([LoadedDocument(page_content="", metadata={})])
|
||
assert chunks == []
|
||
|
||
|
||
# ---------- 向量入库与检索(集成)----------
|
||
|
||
|
||
def _build_service(d_tmp_path: Path) -> KnowledgeService:
|
||
"""构造使用本地 ONNX 嵌入的测试用知识服务。"""
|
||
from app.knowledge.embeddings import LocalEmbeddingProvider
|
||
|
||
provider = LocalEmbeddingProvider(cache_dir=str(d_tmp_path / "emb_cache"))
|
||
vs = KnowledgeVectorStore(
|
||
persist_dir=d_tmp_path / "chroma",
|
||
collection_name="test_knowledge",
|
||
embedding_provider=provider,
|
||
)
|
||
return KnowledgeService(vs, provider)
|
||
|
||
|
||
def test_ingest_and_query(sample_materials: Path, d_tmp_path: Path) -> None:
|
||
"""入库后能用自然语言召回相关内容(集成,需本地嵌入模型)。"""
|
||
service = _build_service(d_tmp_path)
|
||
result = service.ingest_directory(sample_materials)
|
||
|
||
assert result["ingested_chunks"] > 0
|
||
assert result["scanned_files"] == 2
|
||
|
||
hits = service.query("网关离线怎么排查", top_k=3)
|
||
assert len(hits) > 0
|
||
# 命中结果应带回来源信息
|
||
assert hits[0].get("source")
|
||
assert hits[0].get("text")
|
||
|
||
|
||
def test_query_empty_collection(d_tmp_path: Path) -> None:
|
||
"""空库检索:返回空列表,不抛异常(硬约束 5)。"""
|
||
service = _build_service(d_tmp_path)
|
||
hits = service.query("任何问题")
|
||
assert hits == []
|
||
|
||
|
||
def test_ingest_file_incremental(sample_materials: Path, d_tmp_path: Path) -> None:
|
||
"""单文件增量入库:重复入库同文件不产生重复 chunk。"""
|
||
service = _build_service(d_tmp_path)
|
||
service.ingest_directory(sample_materials)
|
||
first_count = service.stats()["total_chunks"]
|
||
|
||
# 对同一文件再次入库(应先删旧再写新)
|
||
service.ingest_file(sample_materials / "网关离线排查.md")
|
||
second_count = service.stats()["total_chunks"]
|
||
|
||
# 总数不应显著增长(旧的已删,新的写入)
|
||
assert second_count <= first_count + 5
|