包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
342 lines
12 KiB
Python
342 lines
12 KiB
Python
"""
|
||
M3 编排骨架测试
|
||
===============
|
||
|
||
【功能说明】
|
||
覆盖状态契约、主图节点逻辑、Worker 子图、任务生命周期与 API。
|
||
模型调用用 mock,不依赖真实模型服务,保证测试确定性与可重复。
|
||
|
||
【技术选型理由】
|
||
1. 节点单测 mock 模型:真实模型有延迟与不确定性,
|
||
单元测试必须验证「逻辑正确」而非「模型正确」。
|
||
2. 图集成测试用 MemorySaver:验证拓扑连通与状态流转,不落盘。
|
||
3. API 测试用 TestClient:全链路但不启动真实服务。
|
||
|
||
【实现思路】
|
||
- 纯逻辑节点(gate_check/dispatch)直接真跑;
|
||
- 模型节点(intake/plan/evaluate/finalize)mock 模型返回;
|
||
- 任务 API 测试用临时 SQLite 隔离。
|
||
|
||
【潜在风险与应对】
|
||
风险1:模型 mock 不当导致假通过。
|
||
应对:mock 返回故意「不完整」的 JSON,验证字段补全逻辑。
|
||
风险2:LangGraph 版本升级 API 变化。
|
||
应对:测试即文档,API 不兼容时第一时间暴露。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import shutil
|
||
from pathlib import Path
|
||
from typing import Generator
|
||
from unittest.mock import MagicMock, patch
|
||
from uuid import uuid4
|
||
|
||
import pytest
|
||
|
||
from app.graph.nodes import (
|
||
gate_check_node,
|
||
human_gate_node,
|
||
intake_node,
|
||
plan_node,
|
||
)
|
||
from app.graph.state import (
|
||
RISK_HIGH,
|
||
RISK_NORMAL,
|
||
OrchestratorState,
|
||
WorkerState,
|
||
)
|
||
from app.graph.worker import (
|
||
build_worker_graph,
|
||
locate_node,
|
||
modify_node,
|
||
repair_node,
|
||
verify_node,
|
||
)
|
||
|
||
|
||
# ---------- Fixtures ----------
|
||
|
||
|
||
@pytest.fixture()
|
||
def d_tmp_path() -> Generator[Path, None, None]:
|
||
"""D 盘测试临时目录。"""
|
||
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)
|
||
|
||
|
||
def _mock_model(content: str) -> MagicMock:
|
||
"""构造返回指定内容的 mock 模型。"""
|
||
mock = MagicMock()
|
||
mock.invoke.return_value = MagicMock(content=content)
|
||
return mock
|
||
|
||
|
||
# ---------- 状态契约 ----------
|
||
|
||
|
||
def test_state_fields_exist() -> None:
|
||
"""状态契约关键字段必须齐全(与蓝图 4.3 对齐)。"""
|
||
required = [
|
||
"task_id", "project_id", "raw_requirement", "requirement",
|
||
"knowledge_hits", "plan", "risk_level", "approval",
|
||
"worker_results", "evaluation", "report", "error", "status",
|
||
]
|
||
# TypedDict 的 __annotations__ 包含全部字段
|
||
annotations = OrchestratorState.__annotations__
|
||
for field in required:
|
||
assert field in annotations, f"状态缺少字段:{field}"
|
||
|
||
|
||
# ---------- 节点:gate_check(纯逻辑)----------
|
||
|
||
|
||
def test_gate_check_normal_risk() -> None:
|
||
"""常规步骤 → 风险等级 normal。"""
|
||
state: OrchestratorState = {
|
||
"plan": {"steps": [{"step_id": "step_1", "description": "实现登录功能"}]},
|
||
"requirement": {"boundaries": ["用户模块"]},
|
||
}
|
||
result = gate_check_node(state)
|
||
assert result["risk_level"] == RISK_NORMAL
|
||
|
||
|
||
def test_gate_check_high_risk_on_destructive() -> None:
|
||
"""含删除类关键词 → 风险等级 high。"""
|
||
state: OrchestratorState = {
|
||
"plan": {"steps": [{"step_id": "step_1", "description": "删除过期的临时文件"}]},
|
||
"requirement": {"boundaries": []},
|
||
}
|
||
result = gate_check_node(state)
|
||
assert result["risk_level"] == RISK_HIGH
|
||
assert "破坏性" in result["error"]
|
||
|
||
|
||
def test_gate_check_high_risk_on_cross_module() -> None:
|
||
"""跨模块影响 → 风险等级 high。"""
|
||
state: OrchestratorState = {
|
||
"plan": {"steps": [{"step_id": "step_1", "description": "重构工具类"}]},
|
||
"requirement": {"boundaries": ["公共组件", "认证模块"]},
|
||
}
|
||
result = gate_check_node(state)
|
||
assert result["risk_level"] == RISK_HIGH
|
||
|
||
|
||
def test_gate_check_soft_warning_on_too_many_steps() -> None:
|
||
"""步骤数 > 5 → 软警告(不触发中断,仅报告提示)。"""
|
||
steps = [{"step_id": f"s{i}", "description": f"步骤{i}"} for i in range(6)]
|
||
state: OrchestratorState = {"plan": {"steps": steps}, "requirement": {"boundaries": []}}
|
||
result = gate_check_node(state)
|
||
assert result["risk_level"] == RISK_NORMAL # 软警告不升级为 high
|
||
assert len(result["risk_warnings"]) == 1
|
||
assert "步骤数" in result["risk_warnings"][0]
|
||
|
||
|
||
# ---------- 节点:human_gate(HITL)----------
|
||
|
||
|
||
def test_human_gate_auto_approves_normal() -> None:
|
||
"""低风险自动放行,不触发 interrupt。"""
|
||
state: OrchestratorState = {"risk_level": RISK_NORMAL}
|
||
result = human_gate_node(state)
|
||
assert result["approval"]["decision"] == "auto_approved"
|
||
|
||
|
||
def test_human_gate_triggers_interrupt_on_high_risk() -> None:
|
||
"""高风险触发 interrupt(HITL 中断)。"""
|
||
state: OrchestratorState = {"risk_level": RISK_HIGH, "error": "含破坏性操作"}
|
||
# interrupt() 在非图上下文中会抛 RuntimeError,此处验证「确实被触发」
|
||
with pytest.raises(RuntimeError):
|
||
human_gate_node(state)
|
||
|
||
|
||
# ---------- 节点:intake(mock 模型)----------
|
||
|
||
|
||
def test_intake_parses_model_json() -> None:
|
||
"""模型返回标准 JSON → 正确解析。"""
|
||
with patch("app.graph.nodes.get_model_for_task") as mock_get:
|
||
mock_get.return_value = _mock_model(
|
||
'{"type": "bugfix", "summary": "修复空指针", "boundaries": ["service层"], "acceptance": ["编译通过"]}'
|
||
)
|
||
result = intake_node({"raw_requirement": "修复订单查询空指针"})
|
||
assert result["requirement"]["type"] == "bugfix"
|
||
assert result["requirement"]["summary"] == "修复空指针"
|
||
|
||
|
||
def test_intake_fallback_on_bad_json() -> None:
|
||
"""模型返回乱码 → 使用兜底结构(硬约束 5 降级)。"""
|
||
with patch("app.graph.nodes.get_model_for_task") as mock_get:
|
||
mock_get.return_value = _mock_model("这不是JSON,是自由文本")
|
||
result = intake_node({"raw_requirement": "实现导出功能"})
|
||
assert result["requirement"]["summary"] # 兜底有摘要
|
||
assert "acceptance" in result["requirement"]
|
||
|
||
|
||
def test_intake_completes_missing_fields() -> None:
|
||
"""模型漏字段 → 自动补全。"""
|
||
with patch("app.graph.nodes.get_model_for_task") as mock_get:
|
||
mock_get.return_value = _mock_model('{"type": "feature"}')
|
||
result = intake_node({"raw_requirement": "实现A功能"})
|
||
req = result["requirement"]
|
||
assert "summary" in req and req["summary"]
|
||
assert "acceptance" in req and req["acceptance"]
|
||
|
||
|
||
# ---------- 节点:plan(mock 模型)----------
|
||
|
||
|
||
def test_plan_limits_steps() -> None:
|
||
"""步骤超限 → 截断到 8 步。"""
|
||
steps = [{"step_id": f"s{i}", "description": f"步骤{i}"} for i in range(12)]
|
||
with patch("app.graph.nodes.get_model_for_task") as mock_get:
|
||
mock_get.return_value = _mock_model(
|
||
'{"steps": ' + str(steps).replace("'", '"') + "}"
|
||
)
|
||
result = plan_node(
|
||
{
|
||
"requirement": {"summary": "大需求", "type": "feature"},
|
||
"knowledge_hits": [],
|
||
}
|
||
)
|
||
assert len(result["plan"]["steps"]) <= 8
|
||
|
||
|
||
# ---------- Worker 子图 ----------
|
||
|
||
|
||
def test_locate_finds_files(d_tmp_path: Path) -> None:
|
||
"""locate 能按线索定位文件。"""
|
||
code_root = Path(r"D:\Agent\code")
|
||
code_root.mkdir(parents=True, exist_ok=True)
|
||
# 在 D:\Agent\code 下造一个测试文件
|
||
test_file = code_root / "m3_test_file_demo.txt"
|
||
test_file.write_text("test", encoding="utf-8")
|
||
try:
|
||
state: WorkerState = {
|
||
"step": {"step_id": "s1", "description": "定位", "target_hints": ["m3_test_file_demo"]},
|
||
"project_id": "proj_test",
|
||
}
|
||
result = locate_node(state)
|
||
assert any("m3_test_file_demo" in f for f in result["located_files"])
|
||
finally:
|
||
test_file.unlink(missing_ok=True)
|
||
|
||
|
||
def test_locate_no_hints_returns_empty() -> None:
|
||
"""无线索 → 返回空列表,不抛异常。"""
|
||
state: WorkerState = {"step": {"step_id": "s1", "target_hints": []}, "project_id": "p"}
|
||
result = locate_node(state)
|
||
assert result["located_files"] == []
|
||
|
||
|
||
def test_modify_records_edit() -> None:
|
||
"""modify 产出结构化修改记录(M3 桩)。"""
|
||
state: WorkerState = {
|
||
"step": {"step_id": "s1", "description": "改代码"},
|
||
"located_files": ["a.java"],
|
||
"retry_count": 0,
|
||
}
|
||
result = modify_node(state)
|
||
assert len(result["edits"]) == 1
|
||
assert result["edits"][0]["step_id"] == "s1"
|
||
|
||
|
||
def test_verify_passes_with_results() -> None:
|
||
"""有定位/修改结果 → 验证通过。"""
|
||
state: WorkerState = {
|
||
"step": {"step_id": "s1"},
|
||
"located_files": ["a.java"],
|
||
"edits": [{"x": 1}],
|
||
"retry_count": 0,
|
||
}
|
||
result = verify_node(state)
|
||
assert result["verify_result"]["passed"] is True
|
||
|
||
|
||
def test_repair_increments_retry() -> None:
|
||
"""repair 递增重试计数。"""
|
||
state: WorkerState = {"retry_count": 1}
|
||
result = repair_node(state)
|
||
assert result["retry_count"] == 2
|
||
|
||
|
||
def test_worker_graph_compiles() -> None:
|
||
"""Worker 子图能成功编译(拓扑合法)。"""
|
||
graph = build_worker_graph()
|
||
assert graph is not None
|
||
|
||
|
||
# ---------- 任务 API ----------
|
||
|
||
|
||
def test_task_api_create_and_get(d_tmp_path: Path) -> None:
|
||
"""任务创建与查询 API 全链路。"""
|
||
from fastapi.testclient import TestClient
|
||
|
||
from app.api.task_api import get_task_service
|
||
from app.main import create_app
|
||
from app.tasks.task_service import TaskService
|
||
from app.tasks.task_store import SqliteTaskStore
|
||
|
||
store = SqliteTaskStore(d_tmp_path / "task.db")
|
||
service = TaskService(store)
|
||
|
||
app = create_app()
|
||
app.dependency_overrides[get_task_service] = lambda: service
|
||
with TestClient(app) as client:
|
||
# 创建任务(不真正跑图——create_and_run 会 create_task,但图可能失败,属预期降级)
|
||
resp = client.post(
|
||
"/api/tasks",
|
||
json={
|
||
"project_id": "proj_test",
|
||
"requirement_text": "实现测试功能",
|
||
"task_type": "feature",
|
||
},
|
||
)
|
||
body = resp.json()
|
||
assert body["code"] == 0, f"任务创建失败:{body['message']}"
|
||
task_id = body["data"]["id"]
|
||
assert body["data"]["status"] == "running"
|
||
|
||
# 查询任务
|
||
resp2 = client.get(f"/api/tasks/{task_id}")
|
||
assert resp2.json()["code"] == 0
|
||
|
||
# 查询不存在的任务
|
||
resp3 = client.get("/api/tasks/task_notexist")
|
||
assert resp3.json()["code"] == 404
|
||
|
||
app.dependency_overrides.clear()
|
||
|
||
|
||
def test_task_status_transition_valid(d_tmp_path: Path) -> None:
|
||
"""状态迁移合法性:running → waiting_approval 合法。"""
|
||
from app.schemas.task import TaskCreate
|
||
from app.tasks.task_store import SqliteTaskStore
|
||
|
||
store = SqliteTaskStore(d_tmp_path / "t.db")
|
||
task = store.create(
|
||
TaskCreate(project_id="p", requirement_text="需求"), thread_id="th1"
|
||
)
|
||
updated = store.update_status(task.id, status="waiting_approval")
|
||
assert updated is not None and updated.status == "waiting_approval"
|
||
|
||
|
||
def test_task_status_transition_invalid(d_tmp_path: Path) -> None:
|
||
"""非法状态迁移被拒绝:done 不能回到 waiting_approval。"""
|
||
from app.schemas.task import TaskCreate
|
||
from app.tasks.task_store import SqliteTaskStore
|
||
|
||
store = SqliteTaskStore(d_tmp_path / "t.db")
|
||
task = store.create(
|
||
TaskCreate(project_id="p", requirement_text="需求"), thread_id="th1"
|
||
)
|
||
store.update_status(task.id, status="done")
|
||
with pytest.raises(ValueError):
|
||
store.update_status(task.id, status="waiting_approval")
|