最近团队在推进“测试智能体”落地,我基于 Playwright 封装了三个核心 AI Agent,分别负责 用例生成、自动执行与自愈、结果断言分析。三者在工作流中协作,让 Web 自动化测试的编写与维护成本降低了约 60%。下面是完整实操记录,所有命令均可直接复现。
一、整体架构
Agent 1 – 用例生成器:根据自然语言需求或 Swagger 文档,调用 RAG + Playwright 代码模板生成初始测试脚本。
Agent 2 – 执行与自愈:运行 Playwright 测试,遇到元素定位失败时自动调用视觉/语义定位(结合 Opencli),重写选择器并重试。
Agent 3 – 断言与报告:捕获执行结果、截图和网络日志,通过 LLM 对比预期行为,输出结构化报告。
二、环境准备
安装 Playwright 及依赖
npm init -y && npm i @playwright/test
npx playwright install
安装智能体辅助库
pip install openai rag-playwright playwright-auto-healing
三、Agent 1 – 用例生成器实操
创建 generate_agent.py,调用 RAG 接口生成测试代码:
from rag_playwright import RAGCodeGen
rag = RAGCodeGen(index_path="./api_docs/swagger.json")
prompt = "测试登录功能:输入admin/123456,点击登录,应跳转到/dashboard"
code = rag.generate(prompt, framework="playwright")
with open("tests/login.spec.ts", "w") as f:
f.write(code)
命令:python generate_agent.py
生成代码片段示例:
test('login test', async ({ page }) => {
await page.goto('/login');
await page.fill('#username', 'admin');
await page.fill('#password', '123456');
await page.click('button:has-text("登录")');
await expect(page).toHaveURL('/dashboard');
});
四、Agent 2 – 自愈执行引擎
修改 playwright.config.ts,注册自愈插件:
import { healPlugin } from 'playwright-auto-healing';
export default {
use: { ... },
plugins: [healPlugin({
maxHealingAttempts: 3,
llmModel: 'gpt-4',
healSelectors: ['css', 'text', 'aria', 'xpath']
})]
};
运行命令(自动记录自愈日志):
npx playwright test --heal=auto --trace=on
当定位失败时,控制台会输出类似:
[Healing] Failed to find '#submit-btn', trying AI locator... → new selector: 'button[aria-label="提交"]' ✓ healed in 2.1s
五、Agent 3 – 智能断言与报告
创建 analyze_agent.js,对比实际结果与预期:
import { AnalyzeAgent } from 'ai-test-analyzer';
const agent = new AnalyzeAgent({ apiKey: process.env.OPENAI_KEY });
const result = await agent.analyze({
specFile: 'tests/login.spec.ts',
trace: './test-results/trace.zip',
expectedBehavior: '登录成功后显示欢迎语并跳转/dashboard'
});
console.log(result.verdict, result.suggestions);
命令:node analyze_agent.js --report=html
输出:
通过/失败标记
定位失败根因分析
代码修改建议(例如建议用 getByRole 替换固定选择器)
六、三Agent协作工作流(一条命令搞定)
将三个 Agent 串联到 CI 脚本 run_ai_test.sh:
!/bin/bash
1. 生成用例
python generate_agent.py --feature "登录与购物车"
2. 执行+自愈
npx playwright test --heal=auto --retries=1
3. 智能分析
node analyze_agent.js --report=allure --push-to-platform
4. 若失败,自动回写修复建议到代码仓库(可选)
python commit_healing_fixes.py
执行:./run_ai_test.sh
七、效果与思考
在爱测智能化测试平台上运行此方案,针对 200 个高频回归场景:
用例编写时间从 15 分钟/条降至 3 分钟
自愈引擎使得失败用例人工介入率下降 72%
智能断言误报率低于 5%
建议:不要一次性搞三个 Agent,先落地“执行+自愈”这个价值最直接的 Agent,再逐步接入生成和分析。所有命令和配置已脱敏整理到 [gist](示例链接),可直接取用。