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

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

应用价值
  • 通过人工智能代替人工操作的部分,节省时间,提升效率。
  • 通过封装更多的 Tools,让 Agent 更为智能。
实践演练
实现原理

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

实现思路

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

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

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

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

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

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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
通过 AGENT 实现需求
  1. 首先封装 Agent,绑定工具,输入提示词。在示例中,是在 LangChain 官方提供的 structured-chat-agent提示词基础之上修改的提示词,添加了一个code变量。目的是为了后面 code 可以由其他的 chain 的执行结果而来。
#  注意:需要再原提示词的基础上添加 {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.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

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

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

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

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

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

与其他的场景结合

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

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

# 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.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

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

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

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