16.1 确定性轨迹与失败测试
本节使用标准库 unittest,不要求 pytest。测试应验证工具顺序、模型实际收到的消息、受控停止和错误回灌,而不是只检查最终一句话。
实现选择
max_tokens 是截断失败,应断言 AgentLoopError.reason,不把空文本算成功 final。max_steps 测试控制脚本与参数,使它不会先撞上 repeated_action 或脚本耗尽。
四个 BookTests 是教学入门用例;完整项目另有基础和扩展回归,覆盖并行、预算、恢复、批准、幂等与日志。测试通过只针对这些路径,不承诺不误报或没有其他缺陷。
tests/test_book.py
# file: tests/test_book.py | write
import unittest
from minagent.fake import FakeModel
from minagent.types import Message,ModelResponse,ToolCall
from minagent.tools import Tool,ToolRegistry
from minagent.loop import run,AgentLoopError
def make_registry():
reg=ToolRegistry()
schema={"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}
reg.add(Tool("add","相加",schema,lambda a,b:a+b))
reg.add(Tool("mul","相乘",schema,lambda a,b:a*b))
return reg
def tool_calls_of(result):
return [(tc.name,tc.arguments) for m in result.messages for tc in m.tool_calls]
class BookTests(unittest.TestCase):
def test_order_and_inputs(self):
model=FakeModel([[ToolCall("a","add",{"a":2,"b":3})],[ToolCall("b","mul",{"a":5,"b":4})],"20"])
result=run(model,make_registry(),"(2+3)*4",system="计算")
self.assertEqual(result.final,"20")
self.assertEqual([name for name,_ in tool_calls_of(result)],["add","mul"])
self.assertEqual(len(model.calls[0][0]),2)
self.assertEqual(len(model.calls[1][0]),4)
def test_unknown_tool_feedback(self):
result=run(FakeModel([[ToolCall("a","unknown",{})],"换方法"]),make_registry(),"测试")
self.assertIn("error",result.messages[-2].content)
def test_max_tokens_is_failure(self):
model=FakeModel([ModelResponse(Message("assistant","半句"),"max_tokens")])
with self.assertRaises(AgentLoopError) as error: run(model,make_registry(),"测试")
self.assertEqual(error.exception.reason,"max_tokens")
def test_step_limit(self):
with self.assertRaises(AgentLoopError): run(FakeModel([[ToolCall("a","add",{"a":1,"b":1})]]),make_registry(),"测试",max_steps=1)
if __name__=="__main__": unittest.main()
运行与练习
FakeModel 固定工具动作和回答,不验证真实模型能力。真实模型冒烟、质量评测、负载和安全验证应分开记录。
下载全卷项目 。在项目根运行本节 demo 文件;练习检查与故障用例见 tests/test_book.py、tests/test_extensions.py 和附录 B。
阅读导航:上一节:15.3 成本与用量核算 · 下一节:16.2 评测集与打分 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。