OpenClaw 实战:5 分钟用 AI Agent 自动生成规范测试用例并写入 Excel

一、核心前提

OpenClaw 是轻量级 Agent 框架,核心聚焦:
Skill 注册 → 工具选择 → 任务执行

  • 没有 Dify 的可视化界面
  • 没有知识库、没有复杂工作流
  • 代码极简洁、上手极快
  • 适合:测试开发 / 有编程能力的测试工程师

一句话定位:
OpenClaw = 极简、轻量、只专注做工具调用的小 Agent 引擎

二、环境准备

1. 安装 OpenClaw 及依赖

# 安装 OpenClaw 核心框架
pip install openclaw
# Excel 操作 + LLM 调用
pip install openpyxl openai requests

2.配置 LLM 密钥

import os
# 替换成你的 OpenAI API Key
os.environ["OPENAI_API_KEY"] = "你的API Key"

三、完整实现代码(测试用例生成 + 写入 Excel)

import json
import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill
from openclaw import Agent, Tool, Parameter
from openclaw.llms import OpenAILLM

# ===================== Skill 1:生成测试用例 =====================
class TestCaseGenerateTool(Tool):
    name = "test_case_generator"
    description = """
    软件测试专用工具:根据产品需求生成结构化测试用例,包含用例ID、模块、用例标题、前置条件、操作步骤、预期结果、优先级
    必须返回JSON数组格式的用例数据,每个用例是字典
    """
    parameters = [
        Parameter(
            name="requirement",
            type="str",
            description="产品需求描述",
            required=True
        ),
        Parameter(
            name="module",
            type="str",
            description="测试模块名称",
            required=True
        ),
        Parameter(
            name="priority",
            type="str",
            description="用例优先级(高/中/低)",
            required=True
        )
    ]

    def run(self, requirement: str, module: str, priority: str) -> str:
        prompt = f"""
        作为资深软件测试工程师,根据以下需求生成{priority}优先级的{module}测试用例:
        需求描述:{requirement}
        要求:
        1. 用例字段:用例ID、模块、用例标题、前置条件、操作步骤、预期结果、优先级
        2. 用例ID格式:模块缩写+序号(比如登录模块→DL001)
        3. 覆盖所有功能点、边界条件、异常场景
        4. 返回纯JSON数组,无多余文字
        """
        llm = OpenAILLM(model="gpt-3.5-turbo", temperature=0.3)
        response = llm.chat.completions.create(
            messages=[{"role": "user", "content": prompt}],
            model="gpt-3.5-turbo"
        )
        test_cases = json.loads(response.choices[0].message.content.strip())
        for i, case in enumerate(test_cases, 1):
            case["用例ID"] = f"{module[:2].upper()}00{i}"
        return json.dumps(test_cases, ensure_ascii=False)

# ===================== Skill 2:写入Excel =====================
class ExcelWriteTool(Tool):
    name = "excel_writer"
    description = """
    软件测试专用工具:把JSON格式的测试用例列表写入Excel,生成规范的测试用例文档
    支持字段:用例ID、模块、用例标题、前置条件、操作步骤、预期结果、优先级
    """
    parameters = [
        Parameter(
            name="test_cases",
            type="str",
            description="JSON格式的测试用例列表",
            required=True
        ),
        Parameter(
            name="file_path",
            type="str",
            description="Excel保存路径",
            required=True
        )
    ]

    def run(self, test_cases: str, file_path: str) -> str:
        try:
            cases = json.loads(test_cases)
            wb = openpyxl.Workbook()
            ws = wb.active
            ws.title = "功能测试用例"

            headers = ["用例ID", "模块", "用例标题", "前置条件", "操作步骤", "预期结果", "优先级"]
            for col, header in enumerate(headers, 1):
                cell = ws.cell(row=1, column=col, value=header)
                cell.font = Font(bold=True, color="FFFFFF")
                cell.fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
                cell.alignment = Alignment(horizontal="center")

            for row, case in enumerate(cases, 2):
                for col, header in enumerate(headers, 1):
                    cell_value = case.get(header, "无")
                    ws.cell(row=row, column=col, value=cell_value)
                    ws.cell(row=row, column=col).alignment = Alignment(horizontal="center")

            col_widths = [10, 15, 30, 20, 40, 30, 10]
            for i, width in enumerate(col_widths, 1):
                ws.column_dimensions[chr(64+i)].width = width

            wb.save(file_path)
            return f"成功!测试用例已写入 {file_path},共 {len(cases)} 条用例"
        except Exception as e:
            return f"失败:{str(e)}"

# ===================== 初始化 Agent =====================
def init_openclaw_agent():
    llm = OpenAILLM(model="gpt-3.5-turbo", temperature=0.3)
    tools = [TestCaseGenerateTool(), ExcelWriteTool()]
    agent = Agent(
        llm=llm,
        tools=tools,
        system_prompt="""
        你是软件测试专属Agent,负责:
        1. 先调用 test_case_generator 生成测试用例
        2. 再调用 excel_writer 把用例写入Excel
        3. 最终返回Excel生成结果
        """,
        verbose=True
    )
    return agent

# ===================== 执行 =====================
if __name__ == "__main__":
    agent = init_openclaw_agent()
    user_task = """
    请生成登录模块的高优先级测试用例,需求:
    用户登录功能支持手机号+验证码登录,手机号非11位提示「请输入正确手机号」,
    验证码错误3次后账号锁定10分钟,登录成功跳转到首页。
    生成后把用例写入 ./登录模块测试用例.xlsx
    """
    result = agent.run(user_task)
    print("\n===== 最终结果 =====")
    print(result)

四、核心代码解释

  1. Skill 定义核心:
Tool = 技能 / 函数
name:工具名
descriptionAgent 判断什么时候调用该工具
parameters:告诉 AI 需要什么参数
 run ():真正执行逻辑

2. Agent 执行逻辑:

 思考:用户需要生成测试用例 → 调用 test_case_generator
参数提取成功 → 生成用例
再思考:需要写入 Excel → 调用 excel_writer
最终返回结果

五、运行效果

控制台输出

===== 最终结果 =====
成功!测试用例已写入 ./登录模块测试用例.xlsx,共 5 条用例

Excel 文件内容

标准 7 列测试用例
美观规范,可直接提交评审
可直接导入测试平台

六、OpenClaw 进阶扩展

1. 解析 PDF/Word 需求文档

class DocumentParseTool(Tool):
    name = "document_parser"
    description = "解析PDF/Word格式的产品需求文档,提取核心需求文本"
    parameters = [Parameter(name="file_path", type="str", description="文档路径", required=True)]
    
    def run(self, file_path: str) -> str:
        import PyPDF2
        with open(file_path, "rb") as f:
            reader = PyPDF2.PdfReader(f)
            content = "\n".join([page.extract_text() for page in reader.pages])
        return content

2. 对接 TestLink

class TestLinkUploadTool(Tool):
    name = "testlink_uploader"
    description = "把测试用例导入TestLink测试管理平台"
    parameters = [Parameter(name="test_cases", type="str", description="JSON用例列表", required=True)]
    
    def run(self, test_cases: str) -> str:
        # 调用 TestLink API 实现导入
        return "用例已成功导入TestLink"

七、总结

OpenClaw 核心流程:
定义 Tool(技能)
注册给 Agent
输入一句话任务
Agent 自动选择工具、自动执行、自动输出结果
优势:
轻量、无冗余
代码完全可控
适合嵌入自动化脚本、CI/CD
比可视化平台更灵活、更适合测试开发

Logo

小龙虾开发者社区是 CSDN 旗下专注 OpenClaw 生态的官方阵地,聚焦技能开发、插件实践与部署教程,为开发者提供可直接落地的方案、工具与交流平台,助力高效构建与落地 AI 应用

更多推荐