Chapter 9 · Parametrization and Data-Driven Testing
Chapter goals: Learn to drive tests with environment variables, CSV/JSON files, and per-virtual-user independent data — avoiding hard-coded values.
9.1 Environment Variable Injection
The simplest parametrization: control target host and concurrency via environment variables:
python
import os
from locust import HttpUser, task, between
class ApiUser(HttpUser):
host = os.getenv("TARGET_HOST", "https://httpbin.org")
wait_time = between(
float(os.getenv("MIN_WAIT", "1")),
float(os.getenv("MAX_WAIT", "3"))
)
@task
def get_data(self):
self.client.get("/get")Override at runtime:
bash
TARGET_HOST=https://staging.example.com locust -f locustfile.py9.2 CSV Data Loading
python
import csv
from locust import HttpUser, task, between
# Load all test data at startup
with open("users.csv") as f:
USERS = list(csv.DictReader(f))
class LoginUser(HttpUser):
wait_time = between(1, 3)
def on_start(self):
# Each virtual user pops one account from the queue (avoid duplicate logins)
self.user_data = USERS.pop() if USERS else {"username": "default", "password": "test"}
@task
def login_and_browse(self):
self.client.post("/login", json=self.user_data)
self.client.get("/dashboard")9.3 JSON Configuration Files
python
import json
from locust import HttpUser, task, between
with open("config.json") as f:
config = json.load(f)
class ConfigurableUser(HttpUser):
host = config["target_url"]
wait_time = between(*config["wait_range"])
@task
def hit_endpoint(self):
for ep in config["endpoints"]:
self.client.get(ep)9.4 Per-Virtual-User Independent Data
Use queue.Queue to ensure each virtual user gets unique test data:
python
import queue
from locust import HttpUser, task, between
class QueueUser(HttpUser):
wait_time = between(1, 3)
def on_start(self):
# Each user pops one item — no two users share the same data
self.account = data_queue.get()
@task
def login(self):
self.client.post("/login", json=self.account)9.5 Chapter Summary
- Environment variables for external config (host, timeouts, flags);
- CSV/JSON files for bulk test data loaded at startup;
queue.Queuefor per-user unique data allocation;- Keep test data separate from test code for maintainability.
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. What is the simplest way to override the target host without changing code?
2. Why use queue.Queue for per-user data instead of a plain list?
3. Where should you load CSV/JSON test data in a locustfile?
4. What is the trade-off between CSV and JSON for test data?
🛠️ Hands-On Exercises
- Create a
users.csvwith 100 accounts; write a locustfile that assigns one account per virtual user viaon_start(). - Replace the CSV approach with a JSON config file containing nested endpoint definitions; verify all endpoints are hit.
- Use
queue.Queueto allocate unique accounts; run 10 users and verify no two users share the same account.
Proceed to Chapter 10: Distributed Load Testing.