OpenClaw 实战:利用 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=),
Parameter(name=, =, description=, required=)
]
() -> :
prompt =
llm = OpenAILLM(model=, temperature=)
response = llm.chat.completions.create(
messages=[{:,: prompt}],
model=
)
test_cases = json.loads(response.choices[].message.content.strip())
i, (test_cases, ):
[] =
json.dumps(test_cases, ensure_ascii=)
():
name =
description =
parameters = [
Parameter(name=, =, description=, required=),
Parameter(name=, =, description=, required=)
]
() -> :
:
cases = json.loads(test_cases)
wb = openpyxl.Workbook()
ws = wb.active
ws.title =
headers = [, , , , , , ]
col, header (headers, ):
cell = ws.cell(row=, column=col, value=header)
cell.font = Font(bold=, color=)
cell.fill = PatternFill(start_color=, end_color=, fill_type=)
cell.alignment = Alignment(horizontal=)
row, (cases, ):
col, header (headers, ):
cell_value = .get(header, )
ws.cell(row=row, column=col, value=cell_value)
ws.cell(row=row, column=col).alignment = Alignment(horizontal=)
col_widths = [, , , , , , ]
i, width (col_widths, ):
ws.column_dimensions[(+i)].width = width
wb.save(file_path)
Exception e:
():
llm = OpenAILLM(model=, temperature=)
tools = [TestCaseGenerateTool(), ExcelWriteTool()]
agent = Agent(
llm=llm,
tools=tools,
system_prompt=,
verbose=
)
agent
__name__ == :
agent = init_openclaw_agent()
user_task =
result = agent.run(user_task)
()
(result)


