testing-perf
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePerformance & Load Testing Patterns
性能与负载测试模式
Focused skill for performance testing, load testing, and pytest execution optimization. Covers k6, Locust, pytest-xdist parallel execution, custom plugins, and test type classification.
专注于性能测试、负载测试以及pytest执行优化的技能内容。涵盖k6、Locust、pytest-xdist并行执行、自定义插件以及测试类型分类。
Quick Reference
快速参考
| Area | File | Purpose |
|---|---|---|
| k6 Load Testing | | Thresholds, stages, custom metrics, CI integration |
| Locust Testing | | Python load tests, task weighting, auth flows |
| Test Types | | Load, stress, spike, soak test patterns |
| Execution | | Coverage reporting, parallel execution, failure analysis |
| Pytest Markers | | Custom markers, xdist parallel, worker isolation |
| Pytest Plugins | | Factory fixtures, plugin hooks, anti-patterns |
| k6 Patterns | | Staged ramp-up, authenticated requests, test types |
| xdist Parallel | | Distribution modes, worker isolation, CI config |
| Custom Plugins | | conftest plugins, installable plugins, hook reference |
| Perf Checklist | | Planning, setup, metrics, load patterns, analysis |
| Pytest Checklist | | Config, markers, parallel, fixtures, CI/CD |
| Test Template | | Full test case documentation template |
| 领域 | 文件 | 用途 |
|---|---|---|
| k6负载测试 | | 阈值、阶段、自定义指标、CI集成 |
| Locust测试 | | Python负载测试、任务权重分配、认证流程 |
| 测试类型 | | 负载、压力、突增、浸泡测试模式 |
| 执行配置 | | 覆盖率报告、并行执行、失败分析 |
| Pytest标记 | | 自定义标记、xdist并行、工作进程隔离 |
| Pytest插件 | | 工厂夹具、插件钩子、反模式 |
| k6模式 | | 分阶段扩容、认证请求、测试类型 |
| xdist并行 | | 分发模式、工作进程隔离、CI配置 |
| 自定义插件 | | conftest插件、可安装插件、钩子参考 |
| 性能检查清单 | | 规划、搭建、指标、负载模式、分析 |
| Pytest生产环境检查清单 | | 配置、标记、并行、夹具、CI/CD |
| 测试用例模板 | | 完整测试用例文档模板 |
k6 Quick Start
k6快速入门
Set up a load test with thresholds and staged ramp-up:
javascript
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '30s', target: 20 }, // Ramp up
{ duration: '1m', target: 20 }, // Steady state
{ duration: '30s', target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: ['p(95)<500'], // 95th percentile under 500ms
http_req_failed: ['rate<0.01'], // Less than 1% error rate
},
};
export default function () {
const res = http.get('http://localhost:8000/api/health');
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 200ms': (r) => r.timings.duration < 200,
});
sleep(1);
}Run:
k6 run --out json=results.json tests/load/api.js设置带有阈值和分阶段扩容的负载测试:
javascript
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '30s', target: 20 }, // Ramp up
{ duration: '1m', target: 20 }, // Steady state
{ duration: '30s', target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: ['p(95)<500'], // 95th percentile under 500ms
http_req_failed: ['rate<0.01'], // Less than 1% error rate
},
};
export default function () {
const res = http.get('http://localhost:8000/api/health');
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 200ms': (r) => r.timings.duration < 200,
});
sleep(1);
}运行命令:
k6 run --out json=results.json tests/load/api.jsPerformance Test Types
性能测试类型
| Type | Duration | VUs | Purpose | When to Use |
|---|---|---|---|---|
| Load | 5-10 min | Expected traffic | Validate normal conditions | Every release |
| Stress | 10-20 min | 2-3x expected | Find breaking point | Pre-launch |
| Spike | 5 min | Sudden 10x surge | Test auto-scaling | Before events |
| Soak | 4-12 hours | Normal load | Detect memory leaks | Weekly/nightly |
| 测试类型 | 持续时间 | 虚拟用户数 | 测试目的 | 适用场景 |
|---|---|---|---|---|
| 负载测试 | 5-10分钟 | 预期流量规模 | 验证正常业务场景下的系统表现 | 每次版本发布时 |
| 压力测试 | 10-20分钟 | 预期流量的2-3倍 | 寻找系统崩溃临界点 | 上线前 |
| 突增测试 | 5分钟 | 突发10倍流量激增 | 测试自动扩容能力 | 大型活动前 |
| 浸泡测试 | 4-12小时 | 正常负载水平 | 检测内存泄漏问题 | 每周/夜间执行 |
pytest Parallel Execution
pytest并行执行
Speed up test suites with pytest-xdist:
toml
undefined使用pytest-xdist加速测试套件执行:
toml
undefinedpyproject.toml
pyproject.toml
[tool.pytest.ini_options]
addopts = ["-n", "auto", "--dist", "loadscope"]
markers = [
"slow: marks tests as slow",
"smoke: critical path tests for CI/CD",
]
```bash[tool.pytest.ini_options]
addopts = ["-n", "auto", "--dist", "loadscope"]
markers = [
"slow: marks tests as slow",
"smoke: critical path tests for CI/CD",
]
```bashRun with parallel workers and coverage
Run with parallel workers and coverage
pytest -n auto --dist loadscope --cov=app --cov-report=term-missing --maxfail=3
pytest -n auto --dist loadscope --cov=app --cov-report=term-missing --maxfail=3
CI fast path — skip slow tests
CI fast path — skip slow tests
pytest -m "not slow" -n auto
pytest -m "not slow" -n auto
Debug mode — single worker
Debug mode — single worker
pytest -n 0 -x --tb=long
undefinedpytest -n 0 -x --tb=long
undefinedWorker Database Isolation
工作进程数据库隔离
When running parallel tests with databases, isolate per worker:
python
@pytest.fixture(scope="session")
def db_engine(worker_id):
db_name = f"test_db_{worker_id}" if worker_id != "master" else "test_db"
engine = create_engine(f"postgresql://localhost/{db_name}")
yield engine
engine.dispose()在使用数据库运行并行测试时,为每个工作进程实现隔离:
python
@pytest.fixture(scope="session")
def db_engine(worker_id):
db_name = f"test_db_{worker_id}" if worker_id != "master" else "test_db"
engine = create_engine(f"postgresql://localhost/{db_name}")
yield engine
engine.dispose()Key Thresholds
核心阈值指标
| Metric | Target | Tool |
|---|---|---|
| p95 response time | < 500ms | k6 |
| p99 response time | < 1000ms | k6 |
| Error rate | < 1% | k6 / Locust |
| Business logic coverage | 90% | pytest-cov |
| Critical path coverage | 100% | pytest-cov |
| 指标 | 目标值 | 工具 |
|---|---|---|
| p95响应时间 | < 500ms | k6 |
| p99响应时间 | < 1000ms | k6 |
| 错误率 | < 1% | k6 / Locust |
| 业务逻辑覆盖率 | 90% | pytest-cov |
| 核心路径覆盖率 | 100% | pytest-cov |
Decision Guide
决策指南
| Scenario | Recommendation |
|---|---|
| JavaScript/TypeScript team | k6 for load testing |
| Python team | Locust for load testing |
| Need CI thresholds | k6 (built-in threshold support) |
| Need distributed testing | Locust (built-in distributed mode) |
| Slow test suite | pytest-xdist with |
| Flaky parallel tests | |
| DB-heavy tests | Worker-isolated databases with |
| 场景 | 推荐方案 |
|---|---|
| JavaScript/TypeScript团队 | 使用k6进行负载测试 |
| Python团队 | 使用Locust进行负载测试 |
| 需要CI集成阈值 | k6(内置阈值支持) |
| 需要分布式测试 | Locust(内置分布式模式) |
| 测试套件运行缓慢 | 使用pytest-xdist并设置 |
| 并行测试存在不稳定问题 | 使用 |
| 数据库密集型测试 | 结合 |
Related Skills
相关技能
- — Unit testing patterns, pytest fixtures
ork:testing-unit - — End-to-end performance testing with Playwright
ork:testing-e2e - — Core Web Vitals and optimization patterns
ork:performance
- —— 单元测试模式、pytest夹具
ork:testing-unit - —— 基于Playwright的端到端性能测试
ork:testing-e2e - —— 核心Web指标与优化模式
ork:performance