testing-perf

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Performance & 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

快速参考

AreaFilePurpose
k6 Load Testing
rules/perf-k6.md
Thresholds, stages, custom metrics, CI integration
Locust Testing
rules/perf-locust.md
Python load tests, task weighting, auth flows
Test Types
rules/perf-types.md
Load, stress, spike, soak test patterns
Execution
rules/execution.md
Coverage reporting, parallel execution, failure analysis
Pytest Markers
rules/pytest-execution.md
Custom markers, xdist parallel, worker isolation
Pytest Plugins
rules/pytest-plugins.md
Factory fixtures, plugin hooks, anti-patterns
k6 Patterns
references/k6-patterns.md
Staged ramp-up, authenticated requests, test types
xdist Parallel
references/xdist-parallel.md
Distribution modes, worker isolation, CI config
Custom Plugins
references/custom-plugins.md
conftest plugins, installable plugins, hook reference
Perf Checklist
checklists/performance-checklist.md
Planning, setup, metrics, load patterns, analysis
Pytest Checklist
checklists/pytest-production-checklist.md
Config, markers, parallel, fixtures, CI/CD
Test Template
scripts/test-case-template.md
Full test case documentation template
领域文件用途
k6负载测试
rules/perf-k6.md
阈值、阶段、自定义指标、CI集成
Locust测试
rules/perf-locust.md
Python负载测试、任务权重分配、认证流程
测试类型
rules/perf-types.md
负载、压力、突增、浸泡测试模式
执行配置
rules/execution.md
覆盖率报告、并行执行、失败分析
Pytest标记
rules/pytest-execution.md
自定义标记、xdist并行、工作进程隔离
Pytest插件
rules/pytest-plugins.md
工厂夹具、插件钩子、反模式
k6模式
references/k6-patterns.md
分阶段扩容、认证请求、测试类型
xdist并行
references/xdist-parallel.md
分发模式、工作进程隔离、CI配置
自定义插件
references/custom-plugins.md
conftest插件、可安装插件、钩子参考
性能检查清单
checklists/performance-checklist.md
规划、搭建、指标、负载模式、分析
Pytest生产环境检查清单
checklists/pytest-production-checklist.md
配置、标记、并行、夹具、CI/CD
测试用例模板
scripts/test-case-template.md
完整测试用例文档模板

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.js

Performance Test Types

性能测试类型

TypeDurationVUsPurposeWhen to Use
Load5-10 minExpected trafficValidate normal conditionsEvery release
Stress10-20 min2-3x expectedFind breaking pointPre-launch
Spike5 minSudden 10x surgeTest auto-scalingBefore events
Soak4-12 hoursNormal loadDetect memory leaksWeekly/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
undefined

pyproject.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", ]

```bash

Run 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
undefined
pytest -n 0 -x --tb=long
undefined

Worker 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

核心阈值指标

MetricTargetTool
p95 response time< 500msk6
p99 response time< 1000msk6
Error rate< 1%k6 / Locust
Business logic coverage90%pytest-cov
Critical path coverage100%pytest-cov
指标目标值工具
p95响应时间< 500msk6
p99响应时间< 1000msk6
错误率< 1%k6 / Locust
业务逻辑覆盖率90%pytest-cov
核心路径覆盖率100%pytest-cov

Decision Guide

决策指南

ScenarioRecommendation
JavaScript/TypeScript teamk6 for load testing
Python teamLocust for load testing
Need CI thresholdsk6 (built-in threshold support)
Need distributed testingLocust (built-in distributed mode)
Slow test suitepytest-xdist with
-n auto
Flaky parallel tests
--dist loadscope
for fixture grouping
DB-heavy testsWorker-isolated databases with
worker_id
场景推荐方案
JavaScript/TypeScript团队使用k6进行负载测试
Python团队使用Locust进行负载测试
需要CI集成阈值k6(内置阈值支持)
需要分布式测试Locust(内置分布式模式)
测试套件运行缓慢使用pytest-xdist并设置
-n auto
并行测试存在不稳定问题使用
--dist loadscope
进行夹具分组
数据库密集型测试结合
worker_id
实现工作进程级数据库隔离

Related Skills

相关技能

  • ork:testing-unit
    — Unit testing patterns, pytest fixtures
  • ork:testing-e2e
    — End-to-end performance testing with Playwright
  • ork:performance
    — Core Web Vitals and optimization patterns
  • ork:testing-unit
    —— 单元测试模式、pytest夹具
  • ork:testing-e2e
    —— 基于Playwright的端到端性能测试
  • ork:performance
    —— 核心Web指标与优化模式