Vitest Testing
提供 Vitest 单元测试与集成测试的模式与最佳实践,涵盖断言、异步测试与模拟方法。
下载 36
AI辅助设计测试策略、生成单元/集成/E2E测试用例并实现自动化框架。
openclaw skills install @gechengling/ai-test-strategy-architect命令、参数、文件名以原文为准
构建能在用户发现问题之前就发现缺陷的测试体系。本 AI 驱动的测试助手可设计稳健的测试策略,生成全面的测试用例,并实现自动化框架——将质量保障从瓶颈转变为竞争优势。
测试策略、单元测试、集成测试、E2E测试、自动化测试、测试用例、TDD、BDD、Playwright测试、Selenium、测试覆盖率test strategy、unit testing、integration testing、e2e testing、automated testing、test cases、TDD、BDD、Playwright、Selenium、test coverage、CI/CD testing阶段 1:评估
├── 分析项目架构
├── 识别关键用户流程
├── 评估技术风险
├── 定义质量指标
└── 选择测试工具
阶段 2:设计
├── 设计测试金字塔
├── 明确各层级测试范围
├── 制定测试数据策略
├── 文档化测试环境需求
└── 规划测试自动化方案
阶段 3:实施
├── 搭建测试项目结构
├── 实现单元测试
├── 构建集成测试套件
├── 创建 E2E 测试场景
└── 配置测试运行器
阶段 4:自动化
├── 集成至 CI/CD
├── 设置测试报告
├── 配置并行执行
├── 实现测试监控
└── 创建质量看板
阶段 5:维护
├── 审查测试有效性
├── 优化耗时测试
├── 针对新功能更新测试
└── 归档过时测试1. 输入:源代码或功能描述
↓
2. 分析:识别可测试单元
- 函数/方法
- 用户交互
- API 接口
↓
3. 生成:创建测试用例
- 正常流程场景
- 边界情况
- 错误场景
- 边界条件
↓
4. 验证:运行测试,修复失败项
↓
5. 优化:提升覆盖率与执行速度输入代码:
def calculate_discount(price: float, discount_percent: float, is_loyal: bool) -> float:
"""
计算折扣后的最终价格。
参数:
price: 原始价格
discount_percent: 折扣百分比(0-100)
is_loyal: 是否为忠诚会员
返回:
折扣后的最终价格
"""
if price < 0:
raise ValueError("Price cannot be negative")
if discount_percent < 0 or discount_percent > 100:
raise ValueError("Discount must be between 0 and 100")
discount_multiplier = 1 - (discount_percent / 100)
if is_loyal:
# 忠诚会员额外享受 5% 折扣
final_multiplier = discount_multiplier * 0.95
else:
final_multiplier = discount_multiplier
return round(price * final_multiplier, 2)生成的测试用例:
import pytest
from your_module import calculate_discount
class TestCalculateDiscount:
"""calculate_discount 函数的单元测试"""
# 正常流程测试
def test_no_discount_returns_original_price(self):
"""无折扣时应返回原价"""
assert calculate_discount(100.00, 0, False) == 100.00
def test_standard_discount(self):
"""基础折扣计算"""
assert calculate_discount(100.00, 20, False) == 80.00
def test_loyal_customer_extra_discount(self):
"""忠诚客户额外享受 5% 折扣"""
result = calculate_discount(100.00, 20, True)
expected = round(100 * 0.80 * 0.95, 2) # 76.00
assert result == expected
def test_full_discount(self):
"""100% 折扣应返回 0"""
assert calculate_discount(100.00, 100, False) == 0.00
# 边界情况测试
def test_zero_price(self):
"""价格为零时应返回零"""
assert calculate_discount(0.00, 50, False) == 0.00
def test_rounding_to_cents(self):
"""价格应四舍五入到小数点后两位"""
result = calculate_discount(99.99, 33, False)
assert result == round(99.99 * 0.67, 2)
# 错误情况测试
def test_negative_price_raises_error(self):
"""负价格应抛出 ValueError"""
with pytest.raises(ValueError, match="Price cannot be negative"):
calculate_discount(-10.00, 10, False)
def test_negative_discount_raises_error(self):
"""负折扣应抛出 ValueError"""
with pytest.raises(ValueError, match="Discount must be between"):
calculate_discount(100.00, -5, False)
def test_over_100_discount_raises_error(self):
"""折扣超过 100% 应抛出 ValueError"""
with pytest.raises(ValueError, match="Discount must be between"):
calculate_discount(100.00, 150, False)
# 边界值测试
def test_boundary_zero_percent_discount(self):
"""0% 折扣是有效的"""
assert calculate_discount(50.00, 0, False) == 50.00
def test_boundary_hundred_percent_discount(self):
"""100% 折扣是有效的"""
assert calculate_discount(50.00, 100, False) == 0.00输入: OpenAPI 端点定义
paths:
/api/v1/users/{userId}/orders:
get:
summary: 获取用户订单
parameters:
- name: userId
in: path
required: true
schema:
type: string
- name: status
in: query
schema:
type: string
enum: [pending, shipped, delivered]
responses:
'200':
description: 订单列表
'401':
description: 未授权
'404':
description: 用户不存在生成的集成测试:
import pytest
import requests
from typing import Dict
BASE_URL = "https://api.example.com"
HEADERS = {"Authorization": "Bearer <test_token>"}
class TestUserOrdersAPI:
"""用户订单接口的集成测试"""
@pytest.fixture
def test_user_id(self):
"""提供一个已知订单的测试用户"""
return "user_123"
def test_get_orders_success(self, test_user_id: str):
"""应返回 200 状态码及订单列表"""
response = requests.get(
f"{BASE_URL}/api/v1/users/{test_user_id}/orders",
headers=HEADERS
)
assert response.status_code == 200
data = response.json()
assert "orders" in data
assert isinstance(data["orders"], list)
def test_get_orders_with_status_filter(self, test_user_id: str):
"""应按状态过滤订单"""
response = requests.get(
f"{BASE_URL}/api/v1/users/{test_user_id}/orders",
params={"status": "pending"},
headers=HEADERS
)
assert response.status_code == 200
orders = response.json()["orders"]
assert all(order["status"] == "pending" for order in orders)
def test_get_orders_unauthorized(self, test_user_id: str):
"""无有效 token 时应返回 401"""
response = requests.get(
f"{BASE_URL}/api/v1/users/{test_user_id}/orders"
)
assert response.status_code == 401
def test_get_orders_user_not_found(self):
"""非存在用户应返回 404"""
response = requests.get(
f"{BASE_URL}/api/v1/users/nonexistent_user/orders",
headers=HEADERS
)
assert response.status_code == 404
assert "error" in response.json()输入: 用户操作流程描述
用户流程:登录 -> 添加商品到购物车 -> 结账 -> 验证订单确认生成的端到端测试:
import pytest
from playwright.sync_api import Page, expect
@pytest.fixture
def logged_in_page(page: Page):
"""在每个测试前登录用户"""
page.goto("https://shop.example.com/login")
page.fill('[name="email"]', "test@example.com")
page.fill('[name="password"]', "testpassword123")
page.click('[type="submit"]')
page.wait_for_url("**/dashboard")
return page
def test_complete_checkout_flow(logged_in_page: Page):
"""端到端测试:登录 -> 加入购物车 -> 结账 -> 确认订单"""
page = logged_in_page
# 步骤 1:浏览商品页面
page.goto("https://shop.example.com/products/widget-pro")
page.click('[data-testid="add-to-cart"]')
# 步骤 2:验证购物车
page.click('[data-testid="cart-icon"]')
expect(page.locator('[data-testid="cart-item"]')).toHaveCount(1)
# 步骤 3:进入结账流程
page.click('[data-testid="checkout-button"]')
page.fill('[name="shipping_address"]', "123 Test Street")
page.fill('[name="zip_code"]', "12345")
page.click('[data-testid="continue-payment"]')
# 步骤 4:完成支付
page.fill('[name="card_number"]', "4242424242424242")
page.fill('[name="expiry"]', "12/28")
page.fill('[name="cvv"]', "123")
page.click('[data-testid="place-order"]')
# 步骤 5:验证订单确认
expect(page.locator('[data-testid="order-confirmation"]')).toBeVisible()
expect(page.locator('[data-testid="order-number"]')).not_toBeEmpty()# 测试策略文档
## 项目概述
- 项目名称:[名称]
- 版本:[版本]
- 测试范围:[包含/不包含的内容]
## 质量目标
| 指标 | 目标值 | 度量方式 |
|------|--------|----------|
| 代码覆盖率 | >80% | Codecov |
| 缺陷逃逸率 | <5% | 缺陷追踪系统 |
| 测试执行时间 | <10 分钟 | CI 流水线 |
## 测试金字塔
╱╲
╱ ╲
╱ E2E ╲ [少量 - 10%]
╱──────╲
╱集成测试╲ [中等 - 30%]
╱────────────╲
╱ 单元测试 ╲ [大量 - 60%]
╱────────────────╲
## 测试工具
| 层级 | 工具 | 语言 |
|------|------|------|
| 单元测试 | Pytest | Python |
| 集成测试 | pytest | Python |
| 端到端测试 | Playwright | TypeScript |
| API 测试 | REST Assured | Java |
## 测试环境
- 开发环境:https://dev.example.com
- 预发布环境:https://staging.example.com
- 生产环境:https://example.com
## 测试数据策略
- [策略说明]
## 发布标准
- [ ] 所有关键测试通过
- [ ] 覆盖率达到目标
- [ ] 无 P0 级别缺陷开放test_user_cannot_login_with_invalid_password| 框架 | 适用场景 | 支持语言 |
|---|---|---|
| Pytest | Python API、单元测试 | Python |
| Jest | JavaScript/TypeScript 项目 | JS/TS |
| JUnit 5 | Java 应用程序 | Java |
| Playwright | Web 端到端测试 | TS、Python |
| Cypress | Web 端到端测试 | JS/TS |
| Selenium | 旧版浏览器测试 | 多语言 |
| REST Assured | API 测试 | Java、Groovy |
| SuperTest | Node.js API 测试 | JavaScript |
- 测试策略设计框架
- 单元测试生成能力
- 集成测试脚手架
- 端到端测试模式(Playwright)
- CI/CD 集成指导
已收录 5 个 Skill