HTML_TAG_79_ HTML_TAG_82_📄 Generare k6 PDF Guide_HTML_TAG_83 __HTML_TAG_84_
k6 Load Testing Cheatsheet¶
Installazione¶
Tabella_86_
Comandi di base¶
Tabella_87_
Uso avanzato¶
TABELLA
Configurazione¶
Script Configuration (opzioni oggetto)¶
// Basic load test configuration
export let options = {
vus: 10, // Number of virtual users
duration: '30s', // Test duration
iterations: 1000, // Total iterations (alternative to duration)
};
export default function() {
// Test logic here
}
Stages Configuration (Ramping)¶
export let options = {
stages: [
{ duration: '2m', target: 10 }, // Ramp up to 10 VUs over 2 minutes
{ duration: '5m', target: 10 }, // Stay at 10 VUs for 5 minutes
{ duration: '2m', target: 50 }, // Ramp up to 50 VUs over 2 minutes
{ duration: '5m', target: 50 }, // Stay at 50 VUs for 5 minutes
{ duration: '2m', target: 0 }, // Ramp down to 0 VUs
],
};
Configurazione delle soglie¶
export let options = {
thresholds: {
http_req_duration: ['p(95)<500'], // 95% of requests must complete below 500ms
http_req_failed: ['rate<0.01'], // Error rate must be below 1%
http_reqs: ['rate>100'], // Request rate must be above 100 req/s
checks: ['rate>0.95'], // 95% of checks must pass
'http_req_duration{status:200}': ['p(99)<1000'], // Tagged threshold
},
};
Scenarios Configuration (Advanced)¶
export let options = {
scenarios: {
// Constant VUs scenario
constant_load: {
executor: 'constant-vus',
vus: 10,
duration: '5m',
gracefulStop: '30s',
},
// Ramping VUs scenario
ramping_load: {
executor: 'ramping-vus',
startVUs: 0,
stages: [
{ duration: '2m', target: 50 },
{ duration: '5m', target: 50 },
{ duration: '2m', target: 0 },
],
gracefulRampDown: '30s',
},
// Per-VU iterations
per_vu_iterations: {
executor: 'per-vu-iterations',
vus: 10,
iterations: 100, // Each VU runs 100 iterations
maxDuration: '10m',
},
// Shared iterations
shared_iterations: {
executor: 'shared-iterations',
vus: 10,
iterations: 1000, // 1000 iterations shared across 10 VUs
maxDuration: '10m',
},
// Constant arrival rate
constant_arrival_rate: {
executor: 'constant-arrival-rate',
rate: 100, // 100 iterations per timeUnit
timeUnit: '1s', // per second
duration: '5m',
preAllocatedVUs: 50,
maxVUs: 100,
},
},
};
Variabili ambientali¶
// Access environment variables in script
import { check } from 'k6';
import http from 'k6/http';
const API_URL = __ENV.API_URL || 'https://default-api.com';
const API_KEY = __ENV.API_KEY;
export default function() {
let response = http.get(`${API_URL}/endpoint`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
});
check(response, {
'status is 200': (r) => r.status === 200,
});
}
Metriche personalizzate¶
import { Counter, Gauge, Rate, Trend } from 'k6/metrics';
// Define custom metrics
let myCounter = new Counter('my_custom_counter');
let myGauge = new Gauge('my_custom_gauge');
let myRate = new Rate('my_custom_rate');
let myTrend = new Trend('my_custom_trend');
export default function() {
myCounter.add(1); // Increment counter
myGauge.add(100); // Set gauge value
myRate.add(true); // Add success to rate
myTrend.add(250); // Add value to trend
}
Common Use Cases¶
Use Case: Basic API Load Test¶
# Create a simple test script
cat > api-test.js << 'EOF'
import http from 'k6/http';
import { check, sleep } from 'k6';
export let options = {
vus: 10,
duration: '30s',
};
export default function() {
let response = http.get('https://api.example.com/users');
check(response, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
sleep(1);
}
EOF
# Run the test
k6 run api-test.js
# Run with custom VUs and duration
k6 run --vus 50 --duration 5m api-test.js
Use Case: Spike Testing¶
# Create spike test with sudden load increase
cat > spike-test.js << 'EOF'
import http from 'k6/http';
import { sleep } from 'k6';
export let options = {
stages: [
{ duration: '1m', target: 10 }, // Normal load
{ duration: '30s', target: 100 }, // Spike to 100 users
{ duration: '1m', target: 100 }, // Sustain spike
{ duration: '30s', target: 10 }, // Return to normal
{ duration: '1m', target: 10 }, // Recovery
],
thresholds: {
http_req_duration: ['p(95)<2000'], // Relaxed threshold for spike
http_req_failed: ['rate<0.05'], // Allow 5% error rate during spike
},
};
export default function() {
http.get('https://api.example.com/products');
sleep(1);
}
EOF
# Run spike test
k6 run spike-test.js
Use Case: API Authentication & Data Posting¶
# Test with authentication and POST requests
cat > auth-test.js << 'EOF'
import http from 'k6/http';
import { check } from 'k6';
export let options = {
vus: 20,
duration: '2m',
};
export default function() {
// Login and get token
let loginRes = http.post('https://api.example.com/auth/login',
JSON.stringify({
username: 'testuser',
password: 'testpass',
}),
{ headers: { 'Content-Type': 'application/json' } }
);
let token = loginRes.json('token');
// Use token for authenticated request
let response = http.post('https://api.example.com/data',
JSON.stringify({ name: 'test', value: 123 }),
{ headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
}}
);
check(response, {
'authenticated request successful': (r) => r.status === 201,
});
}
EOF
# Run with environment variables
k6 run -e USERNAME=myuser -e PASSWORD=mypass auth-test.js
Use Case: Soak Testing (durata estesa)¶
# Long-running stability test
cat > soak-test.js << 'EOF'
import http from 'k6/http';
import { check, sleep } from 'k6';
export let options = {
stages: [
{ duration: '5m', target: 20 }, // Ramp up
{ duration: '4h', target: 20 }, // Soak for 4 hours
{ duration: '5m', target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: ['p(95)<500', 'p(99)<1000'],
http_req_failed: ['rate<0.01'],
},
};
export default function() {
let response = http.get('https://api.example.com/health');
check(response, {
'status is 200': (r) => r.status === 200,
});
sleep(Math.random() * 5 + 3); // Random sleep 3-8 seconds
}
EOF
# Run soak test with metrics export
k6 run --out json=soak-results.json soak-test.js
Use Case: Multi-Scenario Prova con diversi endpoint¶
# Complex test with multiple user behaviors
cat > multi-scenario.js << 'EOF'
import http from 'k6/http';
import { sleep } from 'k6';
export let options = {
scenarios: {
// Scenario 1: Browse products
browsers: {
executor: 'constant-vus',
exec: 'browseProducts',
vus: 30,
duration: '5m',
},
// Scenario 2: Search functionality
searchers: {
executor: 'constant-vus',
exec: 'searchProducts',
vus: 10,
duration: '5m',
},
// Scenario 3: Checkout process
buyers: {
executor: 'constant-arrival-rate',
exec: 'checkoutFlow',
rate: 5,
timeUnit: '1s',
duration: '5m',
preAllocatedVUs: 10,
},
},
};
export function browseProducts() {
http.get('https://shop.example.com/products');
sleep(2);
}
export function searchProducts() {
http.get('https://shop.example.com/search?q=laptop');
sleep(3);
}
export function checkoutFlow() {
http.post('https://shop.example.com/cart/add', { productId: 123 });
sleep(1);
http.post('https://shop.example.com/checkout', { cartId: 456 });
sleep(2);
}
EOF
# Run multi-scenario test
k6 run multi-scenario.js
Migliori Pratiche¶
-
Inizio piccolo, scala gradualmente: Inizia con bassi conteggi VU e brevi durate per convalidare il tuo script funziona correttamente prima di eseguire test su larga scala. Utilizzare
--vus 1 --iterations 1per la validazione iniziale. -
Usa Realistic Think Time: Aggiungi
sleep()tra le richieste di simulare il comportamento reale dell'utente. I tempi di sonno casuale (INLINE_CODE_62_) creano modelli più realistici degli intervalli fissi. -
Set Appropriate Thresholds: Definire i criteri di passaggio/fallimento chiari utilizzando le soglie. Monitorare entrambi i tempi di risposta (p95, p99) e i tassi di errore per catturare il degrado delle prestazioni in anticipo.
-
Tag Your Requests: Utilizza i tag per le richieste relative al gruppo per una migliore analisi: - Ok. Questo consente di filtrare le metriche mediante operazioni specifiche.
-
Monitor System Resources: Guarda CPU, memoria e rete sia sul generatore di carico k6 che sul sistema di destinazione. k6 stesso può diventare un collo di bottiglia con risorse insufficienti.
-
Utilizzare Scenarios for Complex Tests: Scenari di leva invece di semplice VU/duration quando avete bisogno di diversi modelli di carico, comportamenti utente multipli, o controllo preciso sui tassi di richiesta.
-
Esporta metriche per analisi: esportare sempre risultati in sistemi esterni (InfluxDB, JSON, CSV) per il confronto storico e l'analisi dettagliata. Il riassunto terminale è utile ma limitato.
-
Version Control Your Tests: memorizzare gli script di prova in Git accanto al codice dell'applicazione. Questo consente di monitorare i cambiamenti delle prestazioni attraverso le versioni e l'esecuzione dei test nelle tubazioni CI/CD.
-
** Dati separati da Scripts**: Utilizzare variabili di ambiente (bandiera_
-e) o file di dati esterni per la configurazione del test. Questo rende gli script riutilizzabili in ambienti (dev, staging, produzione). -
Run da CI/CD Pipelines: Integrare i test k6 nella pipeline di distribuzione per catturare automaticamente le regressioni delle prestazioni. Utilizzare le soglie per fallire costruisce quando le prestazioni si degradano.
Risoluzione dei problemi¶
Traduzione: **k6 processo si blocca o non termina ** | Usa --grace-stop per consentire ai VU di terminare le iterazioni in modo pulito, controllare i loop infiniti negli script di prova, garantire che le dipendenze esterne (API) siano reattive, o utilizzare --max-duration_ come arresto duro. #