# locustfile.py - Minimal examplefromlocustimportHttpUser,task,betweenclassWebsiteUser(HttpUser):wait_time=between(1,5)# Wait 1-5 seconds between tasks@taskdefindex_page(self):self.client.get("/")@task(3)# 3x more likely than other tasksdefview_item(self):self.client.get("/item/123")
fromlocustimportHttpUser,task,betweenimportrandomclassAuthenticatedUser(HttpUser):wait_time=between(1,3)defon_start(self):"""Called when user starts - login here"""response=self.client.post("/login",json={"username":"testuser","password":"password123"})self.token=response.json()["token"]@taskdefprotected_endpoint(self):headers={"Authorization":f"Bearer {self.token}"}self.client.get("/api/protected",headers=headers)@task(2)defcreate_resource(self):headers={"Authorization":f"Bearer {self.token}"}self.client.post("/api/items",json={"name":"Test","value":random.randint(1,100)},headers=headers)
fromlocustimportLoadTestShapeclassStagesLoadShape(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},]deftick(self):run_time=self.get_run_time()forstageinself.stages:ifrun_time<stage["duration"]:return(stage["users"],stage["spawn_rate"])returnNone
# Set environment variables for LocustexportLOCUST_LOCUSTFILE=locustfile.py
exportLOCUST_HOST=https://api.example.com
exportLOCUST_USERS=1000exportLOCUST_SPAWN_RATE=100exportLOCUST_RUN_TIME=30m
exportLOCUST_HEADLESS=true# Run with environment variableslocust
# Create locustfile for API testingcat>api_test.py<< 'EOF'from locust import HttpUser, task, betweenclass 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 testlocust-fapi_test.py--headless--host=https://api.example.com\-u500-r50-t10m--html=api_report.html
Use Case 2: Distributed Load Testing Across Multiple Machines¶
# On master machine (192.168.1.100)locust-flocustfile.py--master--master-bind-host=0.0.0.0\--expect-workers=3--web-host=0.0.0.0
# On worker machine 1locust-flocustfile.py--worker--master-host=192.168.1.100
# On worker machine 2locust-flocustfile.py--worker--master-host=192.168.1.100
# On worker machine 3locust-flocustfile.py--worker--master-host=192.168.1.100
# Access web UI from any machine# http://192.168.1.100:8089
Use Case 3: CI/CD Integration with Automated Testing¶
# Create test script for CI/CD pipelinecat>run_load_test.sh<< 'EOF'#!/bin/bash# Run load test and capture exit codelocust -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 passedif [ $? -eq 0 ]; then echo "Load test passed" exit 0else echo "Load test failed" exit 1fiEOFchmod+xrun_load_test.sh
./run_load_test.sh
Use tiempos de espera realistas: Set wait_time = between(1, 5) para simular el comportamiento real del usuario con pausas entre acciones, evitando el martillo constante irrealista
Aplicar la autenticación adecuada: Uso on_start() método para autenticar una vez por usuario en lugar de cada solicitud, reduciendo las sesiones generales y imitando las sesiones reales
**Toma tus tareas* Use @tag('critical', 'api')_ decoradores para organizar pruebas y ejecutar subconjuntos específicos durante el desarrollo o pruebas específicas
** Utilización de los recursos de monitor**: Vea la CPU y la memoria tanto en máquinas de Locust como en servidores de destino; Los trabajadores de Locust deben utilizar <80% CPU para resultados precisos
Empieza con pequeñas cargas. Comience pruebas con 10-50 usuarios para verificar que la lógica de prueba funciona correctamente antes de escalar a miles de usuarios concurrentes
Utilice el modo distribuido para la escala: Máquina única limitada a ~5000-10000 usuarios; utilice la configuración de master-worker para simular cargas más grandes a través de múltiples máquinas
Ejecución correcta de errores: Usar response.failure() para marcar solicitudes fallidas y capturar excepciones para evitar fallos de prueba para detener la generación de carga
Control de verificación tus pruebas: Almacene los locustfiles en Git junto con el código de aplicación, tratando las pruebas de rendimiento como ciudadanos de primera clase en su estrategia de pruebas
Set realista spawn rates: No desperdicies a todos los usuarios al instante; utilice rampa gradual (10-100 usuarios/seg) para evitar sistemas abrumadores y obtener falsos fracasos
** Informes genéricos de análisis**: Utilice siempre --html y --csv_ banderas para capturar resultados para el análisis post-test y la comparación histórica
Ensure virtual environment is activated: INLINE_CODE_67 then reinstall: INLINE_CODE_68
Workers not connecting to master
Check firewall allows port 5557, verify master IP address is correct, ensure both master and worker use same locustfile
INLINE_CODE_69 errors during test
Target server may be down or blocking requests; check server logs, verify host URL is correct, ensure firewall allows traffic
Locust using 100% CPU on worker
Reduce number of users per worker (max ~5000), add more worker machines, or optimize locustfile to reduce processing overhead
Statistics not updating in web UI
Check browser console for errors, try different browser, ensure no proxy/firewall blocking WebSocket connections on port 8089
INLINE_CODE_70 installation fails on Windows
Install Visual C++ Build Tools from Microsoft, or use pre-compiled wheels: INLINE_CODE_71
Test results inconsistent/unreliable
Ensure workers have sufficient resources, check network latency between workers and target, verify spawn rate isn't too aggressive
INLINE_CODE_72 errors
Disable SSL verification (testing only): INLINE_CODE_73 in INLINE_CODE_74, or provide certificate bundle path
Memory usage grows continuously
Check for memory leaks in locustfile (storing too much data), restart workers periodically, or reduce test duration
Cannot bind to port 8089
Port already in use; use INLINE_CODE_75 to use different port, or kill existing Locust process: INLINE_CODE_76
Docker container exits immediately
Ensure locustfile path is correct in volume mount, check container logs: INLINE_CODE_77, verify command syntax
Tareas que no se ejecutan en el orden esperado tención Uso SequentialTaskSet para la ejecución ordenada en lugar de la selección de tareas aleatorias, o implementar la lógica de programación de tareas personalizada