前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >基于 LangChain 的自动化测试用例的生成与执行

基于 LangChain 的自动化测试用例的生成与执行

原创
作者头像
霍格沃兹测试开发Muller老师
发布2024-09-27 16:58:22
410
发布2024-09-27 16:58:22
举报
文章被收录于专栏:muller的测试分享

在前面的章节中,分别介绍了 Web、App、接口自动化测试用例的生成。但是在前文中实现的效果均为在控制台打印自动化测试的用例。用例需要手动粘贴,调整之后再执行。

那么其实这个手动粘贴、执行的过程,也是可以直接通过人工智能完成的。

应用价值

  • 通过人工智能代替人工操作的部分,节省时间,提升效率。
  • 通过封装更多的 Tools,让 Agent 更为智能。

实践演练

实现原理
实现思路

在理解需求之后,我们可以了解到我们需要让 Agent 具备两个功能:

  1. 输入源码信息,生成 python 文件。
  2. 输入文件名,执行 pytest 测试文件功能。

如此,可以通过如下两个步骤实现需求:

  1. 工具包封装。
  2. 实现 Agent。
工具包封装

为了让工具包更易被大模型理解,我们将注释调整为英文,提升准确率。同时为了传参的时候不出现格式错误问题,通过args_schema限制参数结构与格式(tools 章节有具体讲解)。

代码语言:python
代码运行次数:0
复制
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
    """
    with open(filename, "w") as f:
        f.write(source_code)


@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
    # 使用subprocess模块执行pytest命令
    result = subprocess.run(['pytest', filename], capture_output=True, text=True)
    # 检查pytest的执行结果
    if result.returncode == 0:
        print("测试运行成功!")
    else:
        print("测试运行失败:")
    print(result.stdout)
    return result.stdout
通过 AGENT 实现需求
  1. 首先封装 Agent,绑定工具,输入提示词。在示例中,是在 LangChain 官方提供的 structured-chat-agent提示词基础之上修改的提示词,添加了一个code变量。目的是为了后面 code 可以由其他的 chain 的执行结果而来。
代码语言:python
代码运行次数:0
复制
#  注意:需要再原提示词的基础上添加 {code} 变量
# prompt = hub.pull("hwchase17/structured-chat-agent")
llm = ChatOpenAI()

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__':
    agent_executor.invoke({"input": "请根据以上源码生成文件", "code": """def test_demo(): return True"""})

由以上的步骤,即可生成一个源码文件:

  1. 在生成源码文件后,可以继续补充提示词,要求Agent 执行对应的测试用例:
代码语言:python
代码运行次数:0
复制
if __name__ == '__main__':
    agent_executor.invoke({"input": """
               请根据以下步骤完成我让你完成操作,没有完成所有步骤不能停止:
                1. 先根据以上源码生成文件。
                2. 根据上一步生成的源码文件,进行执行测试用例操作,并返回终的执行结果
                """,
               "code": """def test_demo(): return True"""})

到这里,通过 Agent 就能自动生成测试用例文件执行测试用例了。

与其他的场景结合

在前面的章节中,已经实现了自动生成接口自动化测试用例的操作。可以直接与前面的操作结合,自动生成接口自动化测试用例,并执行测试用用例。

注意:load_case 如何实现在前面章节:《基于LangChain手工测试用例转接口自动化测试生成工具》,已有对应讲解

代码语言:python
代码运行次数:0
复制
# 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. 根据上一步生成的源码文件,进行执行测试用例操作,并返回终的执行结果
                """})

执行之后,即可在控制台看到生成的接口自动化测试用例的执行记录。

总结

  1. 自动化测试用例的生成与执行的实现原理。
  2. 自动化测试用例的生成与执行的实现思路。
  3. 利用 Agent 实现自动化测试用例的生成与执行。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 应用价值
  • 实践演练
    • 实现原理
      • 实现思路
        • 工具包封装
        • 通过 AGENT 实现需求
        • 与其他的场景结合
    • 总结
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档