Generating k6 Tests from Code
Analyze an existing API codebase to automatically generate k6 load test scripts. Detects endpoints, authentication patterns, request/response shapes, and generates comprehensive test suites.
Workflow
Follow this workflow strictly in order:
Step 1: Security & Authentication Analysis (Prerequisite)
Before analyzing routes, always detect the authentication mechanism first.
Scan for auth middleware/decorators:
- Look for authentication middleware, guards, decorators, or filters
- Identify the auth type: JWT, session, OAuth2, API Key, Basic Auth
- Determine which endpoints are protected vs public
Extract the authentication flow:
- Find login/token endpoints
- Identify how tokens are obtained, refreshed, and passed
- Check for CSRF protection patterns
Generate k6 auth setup:
- Create
setup() function for authentication
- Configure token/session handling for
default() function
- Handle token refresh if needed
See reference/auth-analysis.md for auth detection patterns per framework.
Step 2: Route & Controller Analysis
Scan route definitions:
- Map all endpoints with HTTP methods
- Extract URL parameters, query parameters, request body schemas
- Identify middleware chain per route
Extract request/response shapes:
- Analyze request body types/validation
- Identify required vs optional fields
- Note content types (JSON, form-data, multipart)
Categorize endpoints:
- Group by resource/domain (users, products, orders, etc.)
- Identify CRUD patterns
- Note rate-limited or special endpoints
See reference/framework-patterns.md for framework-specific analysis patterns.
Step 3: Scenario Design
Map endpoints to test scenarios:
- High-traffic endpoints → higher iteration rate
- CRUD sequences → grouped in order (create → read → update → delete)
- Background/admin endpoints → lower priority
Design realistic user flows:
- Login → browse → select → purchase
- Weighted distribution matching production traffic
Step 4: Script Generation
Generate the k6 test script with:
setup() for authentication
default() with grouped endpoint calls
- Checks for each response
- Appropriate thresholds
- Data parameterization where needed
- Tags for per-endpoint metrics
Supported Frameworks
Node.js
- Express —
app.get(), router.get(), route files
- Fastify —
fastify.get(), route plugins, schemas
- NestJS —
@Controller(), @Get(), @Post() decorators, Guards
Java
- Spring Boot —
@RestController, @GetMapping, @PostMapping, @RequestMapping, Security config
Python
- FastAPI —
@app.get(), @router.get(), Pydantic models, Depends()
- Django REST Framework —
ViewSet, @api_view, urlpatterns, permissions
Output Structure
The generated script should follow this structure:
import http from 'k6/http';
import { check, group, sleep } from 'k6';
import { SharedArray } from 'k6/data';
// Test data (if applicable)
const testData = new SharedArray('data', function () {
return JSON.parse(open('./test-data.json'));
});
export const options = {
scenarios: { /* ... */ },
thresholds: { /* ... */ },
};
// Authentication setup
export function setup() {
// Login and return auth token/session
}
// Main test function
export default function (data) {
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${data.token}`,
};
group('Resource A', () => {
// CRUD operations for Resource A
});
group('Resource B', () => {
// CRUD operations for Resource B
});
sleep(1);
}
export function teardown(data) {
// Cleanup if needed
}
Related Skills
- For HTTP/gRPC/WebSocket API patterns:
/k6:generating-api-load-tests
- For scenario and threshold design:
/k6:designing-test-scenarios
- For OpenAPI spec-based generation:
/k6:generating-tests-from-openapi
1---2name: generating-tests-from-code3description: Use when analyzing an existing API codebase to auto-generate k6 load test scripts. Use when the user wants to create k6 tests from source code, route definitions, controllers, or middleware in frameworks like Express, NestJS, Spring Boot, FastAPI, or Django.4---56# Generating k6 Tests from Code78Analyze an existing API codebase to automatically generate k6 load test scripts. Detects endpoints, authentication patterns, request/response shapes, and generates comprehensive test suites.910## Workflow1112Follow this workflow strictly in order:1314### Step 1: Security & Authentication Analysis (Prerequisite)1516**Before analyzing routes, always detect the authentication mechanism first.**17181. **Scan for auth middleware/decorators:**19 - Look for authentication middleware, guards, decorators, or filters20 - Identify the auth type: JWT, session, OAuth2, API Key, Basic Auth21 - Determine which endpoints are protected vs public22232. **Extract the authentication flow:**24 - Find login/token endpoints25 - Identify how tokens are obtained, refreshed, and passed26 - Check for CSRF protection patterns27283. **Generate k6 auth setup:**29 - Create `setup()` function for authentication30 - Configure token/session handling for `default()` function31 - Handle token refresh if needed3233See [reference/auth-analysis.md](reference/auth-analysis.md) for auth detection patterns per framework.3435### Step 2: Route & Controller Analysis36371. **Scan route definitions:**38 - Map all endpoints with HTTP methods39 - Extract URL parameters, query parameters, request body schemas40 - Identify middleware chain per route41422. **Extract request/response shapes:**43 - Analyze request body types/validation44 - Identify required vs optional fields45 - Note content types (JSON, form-data, multipart)46473. **Categorize endpoints:**48 - Group by resource/domain (users, products, orders, etc.)49 - Identify CRUD patterns50 - Note rate-limited or special endpoints5152See [reference/framework-patterns.md](reference/framework-patterns.md) for framework-specific analysis patterns.5354### Step 3: Scenario Design55561. **Map endpoints to test scenarios:**57 - High-traffic endpoints → higher iteration rate58 - CRUD sequences → grouped in order (create → read → update → delete)59 - Background/admin endpoints → lower priority60612. **Design realistic user flows:**62 - Login → browse → select → purchase63 - Weighted distribution matching production traffic6465### Step 4: Script Generation6667Generate the k6 test script with:68- `setup()` for authentication69- `default()` with grouped endpoint calls70- Checks for each response71- Appropriate thresholds72- Data parameterization where needed73- Tags for per-endpoint metrics7475## Supported Frameworks7677### Node.js78- **Express** — `app.get()`, `router.get()`, route files79- **Fastify** — `fastify.get()`, route plugins, schemas80- **NestJS** — `@Controller()`, `@Get()`, `@Post()` decorators, Guards8182### Java83- **Spring Boot** — `@RestController`, `@GetMapping`, `@PostMapping`, `@RequestMapping`, Security config8485### Python86- **FastAPI** — `@app.get()`, `@router.get()`, Pydantic models, Depends()87- **Django REST Framework** — `ViewSet`, `@api_view`, `urlpatterns`, permissions8889## Output Structure9091The generated script should follow this structure:9293```javascript94import http from 'k6/http';95import { check, group, sleep } from 'k6';96import { SharedArray } from 'k6/data';9798// Test data (if applicable)99const testData = new SharedArray('data', function () {100 return JSON.parse(open('./test-data.json'));101});102103export const options = {104 scenarios: { /* ... */ },105 thresholds: { /* ... */ },106};107108// Authentication setup109export function setup() {110 // Login and return auth token/session111}112113// Main test function114export default function (data) {115 const headers = {116 'Content-Type': 'application/json',117 'Authorization': `Bearer ${data.token}`,118 };119120 group('Resource A', () => {121 // CRUD operations for Resource A122 });123124 group('Resource B', () => {125 // CRUD operations for Resource B126 });127128 sleep(1);129}130131export function teardown(data) {132 // Cleanup if needed133}134```135136## Related Skills137138- For HTTP/gRPC/WebSocket API patterns: `/k6:generating-api-load-tests`139- For scenario and threshold design: `/k6:designing-test-scenarios`140- For OpenAPI spec-based generation: `/k6:generating-tests-from-openapi`