HTML_TAG_79_ HTML_TAG_82_📄 Generare Locust PDF Guide_HTML_TAG_83 __HTML_TAG_84_
Locust Load Testing Cheatsheet¶
Installazione¶
Tabella_95_
Comandi di base¶
Tabella_96_
Uso avanzato¶
TABELLA
Configurazione¶
Configuration File (locust.conf)¶
# locust.conf - Configuration file format
locustfile = locustfile.py
host = https://api.example.com
users = 1000
spawn-rate = 100
run-time = 30m
headless = true
csv = results
html = report.html
loglevel = INFO
logfile = locust.log
Profilo di base Struttura¶
# locustfile.py - Minimal example
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 5) # Wait 1-5 seconds between tasks
@task
def index_page(self):
self.client.get("/")
@task(3) # 3x more likely than other tasks
def view_item(self):
self.client.get("/item/123")
Advanced Locustfile with Authentication¶
from locust import HttpUser, task, between
import random
class AuthenticatedUser(HttpUser):
wait_time = between(1, 3)
def on_start(self):
"""Called when user starts - login here"""
response = self.client.post("/login", json={
"username": "testuser",
"password": "password123"
})
self.token = response.json()["token"]
@task
def protected_endpoint(self):
headers = {"Authorization": f"Bearer {self.token}"}
self.client.get("/api/protected", headers=headers)
@task(2)
def create_resource(self):
headers = {"Authorization": f"Bearer {self.token}"}
self.client.post("/api/items",
json={"name": "Test", "value": random.randint(1, 100)},
headers=headers)
# Forma personalizzata del carico¶
from locust import LoadTestShape
class StagesLoadShape(LoadTestShape):
"""
Custom load pattern with stages:
- Ramp to 100 users over 60s
- Hold at 100 for 120s
- Ramp to 500 over 60s
- Hold at 500 for 180s
"""
stages = [
{"duration": 60, "users": 100, "spawn_rate": 10},
{"duration": 180, "users": 100, "spawn_rate": 10},
{"duration": 240, "users": 500, "spawn_rate": 50},
{"duration": 420, "users": 500, "spawn_rate": 50},
]
def tick(self):
run_time = self.get_run_time()
for stage in self.stages:
if run_time < stage["duration"]:
return (stage["users"], stage["spawn_rate"])
return None
Docker Compose Configuration¶
# docker-compose.yml - Distributed testing setup
version: '3'
services:
master:
image: locustio/locust
ports:
- "8089:8089"
volumes:
- ./:/mnt/locust
command: -f /mnt/locust/locustfile.py --master --expect-workers=4
worker:
image: locustio/locust
volumes:
- ./:/mnt/locust
command: -f /mnt/locust/locustfile.py --worker --master-host=master
Variabili ambientali¶
# Set environment variables for Locust
export LOCUST_LOCUSTFILE=locustfile.py
export LOCUST_HOST=https://api.example.com
export LOCUST_USERS=1000
export LOCUST_SPAWN_RATE=100
export LOCUST_RUN_TIME=30m
export LOCUST_HEADLESS=true
# Run with environment variables
locust
Common Use Cases¶
Use Case 1: API Load Testing with Authentication¶
# Create locustfile for API testing
cat > api_test.py << 'EOF'
from locust import HttpUser, task, between
class APIUser(HttpUser):
wait_time = between(1, 2)
def on_start(self):
# Authenticate once per user
response = self.client.post("/api/auth/login", json={
"username": "testuser",
"password": "testpass"
})
self.token = response.json()["access_token"]
@task(3)
def get_users(self):
self.client.get("/api/users",
headers={"Authorization": f"Bearer {self.token}"})
@task(1)
def create_user(self):
self.client.post("/api/users",
json={"name": "New User", "email": "test@example.com"},
headers={"Authorization": f"Bearer {self.token}"})
EOF
# Run the test
locust -f api_test.py --headless --host=https://api.example.com \
-u 500 -r 50 -t 10m --html=api_report.html
Use Case 2: Distributed Load Testing Across Multiple Machines¶
# On master machine (192.168.1.100)
locust -f locustfile.py --master --master-bind-host=0.0.0.0 \
--expect-workers=3 --web-host=0.0.0.0
# On worker machine 1
locust -f locustfile.py --worker --master-host=192.168.1.100
# On worker machine 2
locust -f locustfile.py --worker --master-host=192.168.1.100
# On worker machine 3
locust -f locustfile.py --worker --master-host=192.168.1.100
# Access web UI from any machine
# http://192.168.1.100:8089
Use Case 3: Integrazione CI/CD con Test automatizzati¶
# Create test script for CI/CD pipeline
cat > run_load_test.sh << 'EOF'
#!/bin/bash
# Run load test and capture exit code
locust -f locustfile.py --headless \
--host=https://staging.example.com \
-u 1000 -r 100 -t 5m \
--html=report.html \
--csv=results \
--exit-code-on-error 1
# Check if test passed
if [ $? -eq 0 ]; then
echo "Load test passed"
exit 0
else
echo "Load test failed"
exit 1
fi
EOF
chmod +x run_load_test.sh
./run_load_test.sh
Use Case 4: Testing with Multiple User Scenarios¶
# Create multi-scenario locustfile
cat > multi_scenario.py << 'EOF'
from locust import HttpUser, task, between
class BrowserUser(HttpUser):
weight = 3 # 75% of users
wait_time = between(2, 5)
@task
def browse_pages(self):
self.client.get("/")
self.client.get("/products")
self.client.get("/about")
class MobileUser(HttpUser):
weight = 1 # 25% of users
wait_time = between(1, 3)
@task
def mobile_api(self):
self.client.get("/api/mobile/products")
class AdminUser(HttpUser):
weight = 0.1 # Very few admin users
wait_time = between(5, 10)
def on_start(self):
self.client.post("/admin/login", json={
"username": "admin", "password": "admin123"
})
@task
def admin_dashboard(self):
self.client.get("/admin/dashboard")
EOF
# Run with all user types
locust -f multi_scenario.py --headless -u 1000 -r 100 -t 15m
Use Case 5: Step Load Testing with Progressive Ramps¶
# Create step load configuration
cat > step_load.py << 'EOF'
from locust import HttpUser, task, between, LoadTestShape
class WebUser(HttpUser):
wait_time = between(1, 3)
@task
def load_page(self):
self.client.get("/")
class StepLoadShape(LoadTestShape):
step_time = 120 # 2 minutes per step
step_load = 100 # Add 100 users per step
spawn_rate = 10
time_limit = 600 # 10 minutes total
def tick(self):
run_time = self.get_run_time()
if run_time > self.time_limit:
return None
current_step = run_time // self.step_time
return (current_step + 1) * self.step_load, self.spawn_rate
EOF
# Run step load test
locust -f step_load.py --headless --host=https://example.com \
--html=step_load_report.html
Migliori Pratiche¶
- Utilizzare i tempi di attesa realistici: Impostare
wait_time = between(1, 5)per simulare il comportamento reale dell'utente con pause tra le azioni, evitando irrealistiche costanti martellanti - Attuazione corretta autenticazione Utilizzare il metodo
on_start()_ per autenticare una volta per utente piuttosto che su ogni richiesta, riducendo le sessioni reali overhead e mimicking - Si'. Utilizzare
@tag('critical', 'api')decoratori per organizzare test e eseguire sottoinsiemi specifici durante lo sviluppo o test mirati - ** Uso delle risorse motorie** Guarda la CPU e la memoria sia sulle macchine Locust che sui server target; i lavoratori Locust dovrebbero usare la CPU <80% per risultati accurati
- Start with small loads: Iniziare i test con 1050 utenti per verificare la logica di test funziona correttamente prima di scagliare a migliaia di utenti concorrenti
- ** Utilizzare la modalità distribuita per scala**: Macchina singola limitata a ~5000-10000 utenti; utilizzare la configurazione master-worker per simulare carichi più grandi su più macchine
- Implementare un corretto trattamento degli errori Utilizzare
response.failure()per contrassegnare le richieste fallite e catturare le eccezioni per evitare crash del test di arresto della generazione del carico - Controlla le prove. Memorizzare locustfiles in Git accanto al codice di applicazione, trattando test di prestazioni come cittadini di prima classe nella vostra strategia di test
- ** Tassi realistici delle uova**: Non deporre immediatamente tutti gli utenti; utilizzare ramp-up graduale (10-100 utenti/sec) per evitare sistemi schiaccianti e ottenere falsi guasti
- ** Rapporti generici per analisi ** Utilizzare sempre le bandiere
--htmle--csv_ per catturare i risultati dell'analisi post-test e del confronto storico
Risoluzione dei problemi¶
Traduzione: Compiti non in esecuzione nell'ordine previsto | Usa __INLINE_CODE_78_ per l'esecuzione ordinata invece di selezione casuale delle attività, o implementare la logica di pianificazione delle attività personalizzate |