基于 LangChain 的自动化测试用例生成与执行
本文探讨了利用 LangChain 框架结合大语言模型实现自动化测试用例生成与执行的方案。通过封装自定义工具(Tool)并配置 Agent,系统能够根据源码信息自动生成 Python 测试文件,并利用 subprocess 调用 pytest 执行测试。文章详细阐述了工具定义、参数约束、提示词优化及 Agent 编排的实现细节,同时提供了代码示例与安全实践建议,旨在提升测试效率并降低人工成本。

本文探讨了利用 LangChain 框架结合大语言模型实现自动化测试用例生成与执行的方案。通过封装自定义工具(Tool)并配置 Agent,系统能够根据源码信息自动生成 Python 测试文件,并利用 subprocess 调用 pytest 执行测试。文章详细阐述了工具定义、参数约束、提示词优化及 Agent 编排的实现细节,同时提供了代码示例与安全实践建议,旨在提升测试效率并降低人工成本。

随着人工智能技术的发展,软件测试领域正经历着从传统自动化向智能化转变的过程。利用大语言模型(LLM)和 LangChain 框架,我们可以构建智能体(Agent)来辅助甚至自动完成测试用例的编写与执行。本文将深入探讨如何基于 LangChain 实现这一流程,包括工具封装、Agent 配置以及实际应用场景的结合。
引入 AI 驱动的自动化测试主要带来以下核心价值:
整个系统的核心在于让 Agent 理解需求并调用相应的工具来完成特定任务。基本流程如下:
在理解需求之后,我们需要让 Agent 具备两个核心功能:
为了实现上述需求,我们采取以下两个步骤:
为了让工具包更易被大模型理解,我们将注释调整为英文,提升准确率。同时为了传参的时候不出现格式错误问题,通过 args_schema 限制参数结构与格式。LangChain 支持使用 Pydantic 模型来定义工具的输入结构,这有助于 LLM 准确解析参数。
from langchain_core.tools import tool
from pydantic.v1 import BaseModel, Field
class PythonFileInput(BaseModel):
# 定义参数的描述
filename: str = Field(description="filename")
source_code: str = Field(description="source code data")
class PytestFileName(BaseModel):
# 定义参数的描述
filename: str = Field(description="The name of the file to be executed")
@tool(args_schema=PythonFileInput)
def write_file(filename, source_code):
"""
Generate python files based on input source code
"""
try:
with open(filename, "w", encoding="utf-8") as f:
f.write(source_code)
return f"File {filename} created successfully."
except Exception as e:
return f"Error creating file: {str(e)}"
@tool(args_schema=PytestFileName)
def execute_test_file(filename):
"""
Pass in the file name, execute the test case and return the execution result
"""
import subprocess
try:
# 使用 subprocess 模块执行 pytest 命令
result = subprocess.run(['pytest', filename], capture_output=True, text=True, timeout=60)
# 检查 pytest 的执行结果
if result.returncode == 0:
msg = "测试运行成功!"
else:
msg = "测试运行失败:"
print(result.stdout)
return f"{msg}\n{result.stdout}"
except Exception as e:
return f"Error executing test: {str(e)}"
注意事项:
write_file 中增加了异常捕获,防止因路径不存在等原因导致程序崩溃。execute_test_file 中增加了超时设置,避免测试挂起。structured-chat-agent 提示词基础之上修改的提示词,添加了一个 code 变量。目的是为了后面 code 可以由其他的 chain 的执行结果而来。# 注意:需要再原提示词的基础上添加 {code} 变量
# 实际项目中建议从 hub.pull 获取最新提示词模板
# prompt = hub.pull("hwchase17/structured-chat-agent")
from langchain.chat_models import ChatOpenAI
from langchain.agents import create_structured_chat_agent, AgentExecutor
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
tools_all = [write_file, execute_test_file]
agent1 = create_structured_chat_agent(llm, tools_all, prompt)
agent_executor = AgentExecutor(
agent=agent1,
tools=tools_all,
verbose=True,
return_intermediate_steps=True,
handle_parsing_errors=True)
if __name__ == '__main__':
# 模拟输入
response = agent_executor.invoke({
"input": "请根据以上源码生成文件",
"code": """def test_demo(): return True"""
})
print(response['output'])
执行上述代码后,Agent 会分析输入,调用 write_file 工具生成源码文件。生成的文件内容即为传入的 code 变量内容。
在生成源码文件后,可以继续补充提示词,要求 Agent 执行对应的测试用例。此时 Agent 会再次规划步骤,调用 execute_test_file 工具。
在前面的章节中,已经实现了自动生成接口自动化测试用例的操作。可以直接与前面的操作结合,自动生成接口自动化测试用例,并执行测试用例。
注意:load_case 如何实现在前面章节已有对应讲解,此处假设该函数已存在并返回接口的自动化测试用例代码。
# load_case 的返回结果是接口的自动化测试用例
chain = (
RunnablePassthrough.assign(code=load_case) | agent1
)
agent_executor = AgentExecutor(
agent=chain,
tools=tools_all,
verbose=True,
return_intermediate_steps=True,
handle_parsing_errors=True)
if __name__ == '__main__':
agent_executor.invoke({"input": """
请根据以下步骤完成我让你完成操作,没有完成所有步骤不能停止:
1. 先根据以上源码生成文件。
2. 根据上一步生成的源码文件,进行执行测试用例操作,并返回最终执行结果
"""})
执行之后,即可在控制台看到生成的接口自动化测试用例的执行记录。这种链式调用方式极大地增强了 Agent 的复杂任务处理能力。
在使用 Agent 执行代码时,安全性至关重要。
subprocess 命令,防止恶意代码破坏宿主系统。本文详细介绍了自动化测试用例的生成与执行的实现原理与思路。
通过这种方式,我们可以构建一个更加智能、高效的测试辅助系统,减少重复劳动,让测试人员专注于更高价值的测试设计工作。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online