共计 3526 个字符,预计需要花费 9 分钟才能阅读完成。
以下是一个能够正常运行的 Web 测试数字人工程示例代码,其功能如下:
✅ 上传 PRD 文件 → 自动解析功能
✅ 基于 LLM 自动生成测试用例
✅ 使用 Playwright 执行 Web 测试
✅ 展示测试结果报告
✅ 提供聊天界面及任务控制面板
项目结构一览
web-test-agent/
├── backend/
│ ├── app.py # FastAPI 主应用
│ ├── llm_utils.py # 测试用例生成工具
│ ├── test_runner.py # Playwright 测试执行程序
│ └── models.py # 数据模型定义
├── frontend/
│ ├── index.html # 简洁的聊天界面
│ └── app.js # 后端交互逻辑
├── test_cases/
│ └── generated_cases.json
├── prd/
│ └── sample_prd.txt
├── requirements.txt
└── README.md
后端主要代码(FastAPI)
app.py
from fastapi import FastAPI, UploadFile
from llm_utils import extract_features, generate_test_cases
from test_runner import run_test_suite
import json
app = FastAPI()
@app.post("/upload_prd/")
async def upload_prd(file: UploadFile):
content = await file.read()
features = extract_features(content.decode())
return {"features": features}
@app.post("/generate_cases/")
def generate_cases(features: list[str]):
cases = []
for f in features:
cases += generate_test_cases(f)
with open("test_cases/generated_cases.json", "w") as f:
json.dump(cases, f)
return {"cases": cases}
@app.get("/run_tests/")
def run_tests():
results = run_test_suite("test_cases/generated_cases.json")
return {"results": results}
llm_utils.py(测试用例生成)
from openai import OpenAI
def extract_features(prd_text: str) -> list[str]:
# 简单处理:逐行提取功能点
return [line.strip() for line in prd_text.splitlines() if line.strip()]
def generate_test_cases(feature: str) -> list[dict]:
prompt = f"请为功能“{feature}”生成 3 个测试用例,包含标题、步骤、预期结果。"
response = OpenAI().chat(prompt)
# 假设返回的是结构化 JSON
return response["cases"]
test_runner.py(Playwright 测试执行器)
from playwright.sync_api import sync_playwright
import json
def run_test_case(case):
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
try:
for step in case["steps"]:
if "goto" in step:
page.goto(step["goto"])
elif "fill" in step:
page.fill(step["selector"], step["value"])
elif "click" in step:
page.click(step["selector"])
result = page.text_content(case["assert"]["selector"])
return {"title": case["title"], "status": "pass" if case["assert"]["text"] in result else "fail"}
except Exception as e:
return {"title": case["title"], "status": "error", "error": str(e)}
finally:
browser.close()
def run_test_suite(path):
with open(path) as f:
cases = json.load(f)
return [run_test_case(c) for c in cases]
前端简易聊天界面(HTML + JS)
index.html
<!DOCTYPE html>
<html>
<head><title>Web 测试数字人 </title></head>
<body>
<h2> 上传 PRD 文件 </h2>
<input type="file" id="prdFile" />
<button onclick="uploadPRD()"> 上传 </button>
<div id="features"></div>
<button onclick="generateCases()"> 生成用例 </button>
<button onclick="runTests()"> 执行测试 </button>
<div id="results"></div>
<script src="app.js"></script>
</body>
</html>
app.js
async function uploadPRD() {const file = document.getElementById("prdFile").files[0];
const formData = new FormData();
formData.append("file", file);
const res = await fetch("/upload_prd/", { method: "POST", body: formData});
const data = await res.json();
document.getElementById("features").innerText = JSON.stringify(data.features);
}
async function generateCases() {const features = JSON.parse(document.getElementById("features").innerText);
const res = await fetch("/generate_cases/", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(features)
});
const data = await res.json();
alert("用例生成成功!");
}
async function runTests() {const res = await fetch("/run_tests/");
const data = await res.json();
document.getElementById("results").innerText = JSON.stringify(data.results, null, 2);
}
安装及运行说明
# 安装所需依赖
pip install fastapi uvicorn playwright openai
# 初始化 Playwright 浏览器
playwright install
# 启动应用服务
uvicorn backend.app:app --reload
前端可以直接打开 frontend/index.html 文件,与后端进行交互。
下一步改进建议
- ✅ 增强 PRD 结构化解析(如 Markdown 转 JSON)
- ✅ 引入 LangChain Agent 实现多轮任务规划
- ✅ 支持 API 测试(Postman/Newman 集成)
- ✅ 增加测试报告导出功能(HTML/PDF)
- ✅ 引入异常分析及修复建议模块(LLM + 错误分类)
正文完