AI Agent测试自动化:从单元测试到端到端验证
Agent测试的困境 传统软件测试基于"输入→确定输出"的假设。但Agent的输出由LLM驱动,具有非确定性——同一输入可能产生不同输出。这要求我们重新思考测试方法论。 测试分层架构 第一层:确定性单元测试 测试Agent中确定性的组件: def test_tool_schema_validation(): """测试工具参数验证""" tool = SearchTool() # 有效参数 assert tool.validate({"query": "test"}) == True # 无效参数 assert tool.validate({}) == False # 缺少必需参数 assert tool.validate({"query": 123}) == False # 类型错误 def test_state_management(): """测试状态管理逻辑""" state = AgentState() state.update({"intent": "qa", "slots": {"topic": "AI"}}) assert state.intent == "qa" assert state.missing_slots == [] 覆盖率目标: 90%+(这些组件与普通软件无异) 第二层:Prompt单元测试 测试特定Prompt的输出质量: def test_classification_prompt(): """测试分类Prompt的准确性""" test_cases = [ ("帮我订机票", "booking"), ("今天天气", "weather"), ("写一首诗", "creative"), ("什么是量子力学", "qa"), ] for query, expected_intent in test_cases: result = llm.classify(query) assert result.intent == expected_intent 挑战: LLM输出非确定,可能偶尔失败 解决: 设置通过率阈值(如95%通过即算PASS) def test_with_pass_rate(test_cases, threshold=0.95): passed = sum(1 for tc in test_cases if run_test(tc)) rate = passed / len(test_cases) assert rate >= threshold, f"通过率{rate}低于阈值{threshold}" 第三层:工具集成测试 测试LLM+工具的组合行为: async def test_tool_selection(): """测试Agent能否选择正确的工具""" agent = Agent(tools=[search_tool, calc_tool, file_tool]) # 应选择search_tool result = await agent.run("搜索AI最新新闻") assert result.tool_used == "search_tool" # 应选择calc_tool result = await agent.run("计算17乘以23") assert result.tool_used == "calc_tool" 第四层:端到端测试 测试完整Agent行为: async def test_e2e_qa_agent(): """端到端测试问答Agent""" agent = QAAgent(knowledge_base=test_kb) test_cases = [ { "question": "公司的年假政策是什么?", "must_contain": ["年假", "天"], # 答案必须包含的关键词 "must_not_contain": ["不知道", "无法回答"], # 不应包含 }, { "question": "病假怎么申请?", "must_contain": ["病假", "申请"], "must_not_contain": [], } ] for tc in test_cases: answer = await agent.run(tc["question"]) for keyword in tc["must_contain"]: assert keyword in answer, f"答案应包含'{keyword}'" for keyword in tc["must_not_contain"]: assert keyword not in answer, f"答案不应包含'{keyword}'" 第五层:回归测试 确保Agent更新后不退化: ...