generating-api-load-tests
/generating-api-load-tests
Tworzy skrypty testów obciążeniowych k6 dla API HTTP REST, usług gRPC i połączeń WebSocket.
- Autor
- kimdoubleb ↗
- Repozytorium
- grafana-k6-skills ↗
- Licencja
- MIT
- Ostatnia zmiana repozytorium
- 26.10.2026
Ocena i bezpieczeństwo
- Pliki w paczce
- 5
- Skrypty
- 0
- Komentarze HTML
- 0
- Adresy URL w SKILL.md
- 11
Brak sygnałów. Repozytorium zmienione 26.10.2026, bez odwołań do wycofanych modeli i API.
MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.
Co robi i kiedy
Tworzy skrypty testów obciążeniowych k6 dla API HTTP REST, usług gRPC i połączeń WebSocket.
Oryginalny opis (EN)
Use when creating k6 load test scripts for HTTP REST APIs, gRPC services, or WebSocket connections. Use when the user mentions load testing, performance testing, stress testing, API testing, or k6 script generation for protocol-level endpoints.
Jak działa
- k6 Version Compatibility
- Quick Start — HTTP Load Test
- Test Lifecycle
- Protocol-Specific Guides
- Data Parameterization
- Checks
- Basic Thresholds
- Common Patterns
- Script Generation Workflow
- Related Skills
Podgląd SKILL.md
---
name: generating-api-load-tests
description: Use when creating k6 load test scripts for HTTP REST APIs, gRPC services, or WebSocket connections. Use when the user mentions load testing, performance testing, stress testing, API testing, or k6 script generation for protocol-level endpoints.
---
# Generating API Load Tests with k6
Generate k6 load test scripts for protocol-level APIs. Covers HTTP/REST, gRPC, and WebSocket protocols with authentication, data parameterization, checks, and thresholds.
## k6 Version Compatibility
Written for **k6 v2.3.0** (current stable). The v1.8.x maintenance line is supported where noted; differences are marked `v1.x:` inline. Before generating, determine the version of the environment that will run the test:
1. Run `k6 version` where the test will execute (prints `k6 v2.3.0 (...)`). For Docker, CI, or k6-operator, read the pinned image tag, the `setup-k6-action` `k6-version` input, or `spec.runner.image` instead.
2. If no version is visible, ask the user. Otherwise assume v2.x and record the assumption in a header comment of the generated script, for example `// Target: k6 v2.3.0`.
3. Apply the notes below when the target is v1.x.
**Version notes for this skill:**
- `Params.auth: 'basic'` has no effect on any supported version. Basic auth is applied automatically when the URL carries credentials (`https://user:pass@host/`) or set the `Authorization` header yourself. Only `'digest'` and `'ntlm'` are meaningful values.
- gRPC streaming needs an `async` default function that awaits a `Promise` resolved on `end`; event handlers only run when the call stack is empty (all versions).
- `http.query()` (HTTP QUERY, RFC 10008) is documented for v2.3.x. `tlsAIAFetch` (fetch missing intermediate CA certificates) and the `WebSocket.OPEN`-style ready-state constants need v2.3.0+.
- `TextEncoder`/`TextDecoder` globals need v2.2.0+. `v1.x:` use `k6/encoding`.
- `k6/experimental/redis` was removed in v2.0.0; import `k6/x/redis` (auto-resolved). `v1.x:` community extensions also need `K6_ENABLE_COMMUNITY_EXTENSIONS=true`.
- Validate generated scripts with `k6 inspect script.js`, then `k6 run --once script.js` (v2.3.0+; `v1.x:` `--vus 1 --iterations 1`).
For the full feature/version matrix see `/k6:operating-k6-in-ci-cd` (reference/version-compatibility.md).
## Quick Start — HTTP Load Test
```javascript
// Target: k6 v2.3.0
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 10,
duration: '30s',
thresholds: {
http_req_duration: ['p(95)<500'],
http_req_failed: ['rate<0.01'],
},
};
export default function () {
const res = http.get('https://quickpizza.grafana.com/api/json');
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
'body is JSON': (r) => r.headers['Content-Type'].includes('application/json'),
});
sleep(1);
}
```
`https://quickpizza.grafana.com` is the public k6 demo service (`/api/json`, `/api/post`, `/api/users/token/login`, `/api/ratings`). The older `test.k6.io` and `test-api.k6.io` hosts redirect there.
## Test Lifecycle
Every k6 script follows a 4-stage lifecycle:
```
1. init — Runs once per VU. Import modules, load files, define options.
Cannot make HTTP requests.
2. setup() — Runs once before VU stage. Prepare test data, authenticate.
Can make HTTP requests. Return value passed to default() and teardown().
3. default — Runs repeatedly per VU. The main test logic.
Each iteration resets cookies and tears down connections.
4. teardown — Runs once after all VUs finish. Cleanup resources.
```
```javascript
import http from 'k6/http';
export const options = { vus: 5, duration: '10s' };
export function setup() {
const loginRes = http.post('https://api.example.com/login', JSON.stringify({
username: 'testuser', password: 'testpass',
}), { headers: { 'Content-Type': 'application/json' } });
return { token: loginRes.json('token') };
}
export default function (data) {
http.get('https://api.example.com/items', {
headers: { Authorization: `Bearer ${data.token}` },
});
}
export function teardown(data) {
http.post('https://api.example.com/logout', null, {
headers: { Authorization: `Bearer ${data.token}` },
});
}
```
## Protocol-Specific Guides
Choose the protocol matching your API:
- **HTTP/REST API**: See [reference/http.md](reference/http.md) — GET/POST/PUT/DELETE/QUERY, authentication (Basic, Bearer, OAuth, API Key), CRUD patterns, batch requests, file uploads, form encoding rules, correlation, cookie handling, HTML forms, TLS options
- **gRPC**: See [reference/grpc.md](reference/grpc.md) — Client setup, proto loading, unary calls, async streaming pattern, metadata, status codes
- **WebSocket**: See [reference/websocket.md](reference/websocket.md) — Connection lifecycle, ready-state constants, message handling, event-driven patterns, binary data
- **Raw TCP**: the official `k6/x/tcp` extension (auto-resolved on import) offers a Node-style `Socket` with `connect()`, `write()`, `on('data')`, TLS, and `tcp_*` metrics for non-HTTP protocols. See `/k6:operating-k6-in-ci-cd` (reference/extensions.md) for the extension table
## Data Parameterization
For loading test data from external files and generating dynamic data:
See [reference/data-parameterization.md](reference/data-parameterization.md) — SharedArray, CSV/JSON loading, per-VU data, environment variables, secrets (`k6/secrets`), binary/text encoding, dynamic data generation
## Checks
Checks are assertions that do not stop execution on failure. They track pass/fail rates as metrics.
```javascript
import { check } from 'k6';
check(res, {
'status is 200': (r) => r.status === 200,
'body contains expected': (r) => r.body.includes('success'),
'response is JSON': (r) => r.headers['Content-Type'].includes('application/json'),
'has required field': (r) => r.json('data.id') !== undefined,
});
```
Combine checks with thresholds to enforce pass/fail:
```javascript
export const options = {
thresholds: {
checks: ['rate>0.99'], // 99% of checks must pass
},
};
```
## Basic Thresholds
```javascript
export const options = {
thresholds: {
http_req_duration: ['p(95)<500', 'p(99)<1000'], // 95th percentile < 500ms
http_req_failed: ['rate<0.01'], // Error rate < 1%
http_reqs: ['rate>100'], // At least 100 RPS
checks: ['rate>0.99'], // 99% checks pass
},
};
```
## Common Patterns
### Tags for Filtering
```javascript
const res = http.get('https://api.example.com/users', {
tags: { name: 'GetUsers', type: 'api' },
});
```
### Groups for Organization
```javascript
import { group } from 'k6';
export default function () {
group('User API', function () {
http.get('https://api.example.com/users');
http.get('https://api.example.com/users/1');
});
group('Product API', function () {
http.get('https://api.example.com/products');
});
}
```
### Sleep Between Iterations
```javascript
import { sleep } from 'k6';
export default function () {
// test logic...
sleep(Math.random() * 3 + 1); // Random 1-4 second pause (realistic user think time)
}
```
### Custom Metrics
```javascript
import { Trend, Counter, Rate } from 'k6/metrics';
const apiLatency = new Trend('api_latency');
const apiErrors = new Counter('api_errors');
const apiSuccessRate = new Rate('api_success_rate');
export default function () {
const res = http.get('https://api.example.com/data');
apiLatency.add(res.timings.duration);
apiSuccessRate.add(res.status === 200);
if (res.status !== 200) apiErrors.add(1);
}
```
## Script Generation Workflow
When generating a k6 test script, follow this process:
1. **Identify the target**: URL, protocol (HTTP/gRPC/WebSocket), endpoints
2. **Determine authentication**: Does the API require auth? What type? Generate setup() for token/session acquisition
3. **Define test data**: What parameters vary? Load from CSV/JSON or generate dynamically
4. **Write the default function**: Main test logic with requests, checks, and sleeps
5. **Configure options**: VUs, duration, thresholds based on test goals
6. **Add organization**: Use groups, tags, and custom metrics as needed
7. **Validate**: `k6 inspect script.js` parses the script and prints the resolved options; `k6 run --once script.js` (v2.3.0+) runs one iteration without touching the scenario definition. `v1.x:` `k6 run --vus 1 --iterations 1 script.js`
## Related Skills
- For advanced load profile configuration (executors, VU patterns, multi-scenario): `/k6:designing-test-scenarios`
- For interpreting test output and optimizing performance: `/k6:analyzing-test-results`
- To generate tests from existing API source code: `/k6:generating-tests-from-code`
- To generate tests from OpenAPI specifications: `/k6:generating-tests-from-openapi`
- For the k6 version matrix, extensions, and CI execution: `/k6:operating-k6-in-ci-cd`
Pliki w paczce (5)
- SKILL.md 9 KB
- reference/data-parameterization.md 11 KB
- reference/grpc.md 10 KB
- reference/http.md 13 KB
- reference/websocket.md 9 KB
Wersje
W bazie nie ma innych skilli o nazwie generating-api-load-tests.
Migawka bazy z 13.11.2026 · wersja paczki f9a0541924b8 (skrót SHA-256 całej paczki)
Pobrania w ostatnich 30 dniach: 0 · ranking
Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.
Podobne skille
- 100k6
Generuje, sprawdza i przegląda skrypty k6 do testów obciążeniowych, szczytowych, długotrwałych i funkcjonalnych dla HTTP, WebSocket i gRPC. - 90proof-api
Buduje zestawy testów API: testy endpointów, kontraktowe i obciążeniowe dla REST, GraphQL i gRPC. - 100k6
Generuje, waliduje i przegląda skrypty k6 do testów obciążeniowych, funkcjonalnych i protokołowych dla HTTP, WebSocket, gRPC i przeglądarki, uruchamiając każdy skrypt przed oddaniem. - 100api-design
Pomaga projektować API REST, GraphQL, gRPC i WebSocket z nazewnictwem zasobów, wersjonowaniem, paginacją, obsługą błędów i wzorcami bramek API. - 100generating-grpc-services
Generuje definicje usług gRPC, stuby i implementacje z Protocol Buffers dla wydajnych usług gRPC. - 100generating-grpc-services
Generuje definicje usług gRPC, stuby i implementacje z Protocol Buffers dla wydajnych usług gRPC.