安装
pip install locust
测试脚本 locustfile.py
from locust import TaskSet,HttpUser,task
# 定义一个类
class WebsitUser(HttpUser):
# 设置一个随机时间间隔
wait_time = between(3, 5)
def on_start(self):
self.client.post('/login', {
'username': 'test',
'password': ''
})
# 设置任务,@task装饰器用于声明函数是一个测试任务,@task(权重)
@task(1)
def index(self):
self.client.get('/index')
执行
locust -f locustfile.py
打开浏览器http://localhost:8089/,输入参数。有时候不会自动打开。
一大堆参数,可以用locust -h看示例
-f <filename>, --locustfile <filename>
指定测试脚本文件(如 locustfile.py),可用多个文件或目录。
-H <base url>, --host <base url>
被测系统的基础 URL(如 https://www.example.com)。
-u <int>, --users <int>
并发用户数(虚拟用户数),用于 headless 或 autostart 模式。
-r <float>, --spawn-rate <float>
用户启动速率(每秒启动多少用户)。
-t <time string>, --run-time <time string>
测试持续时间(如 1m、30s、2h)。
--headless
无 Web UI,直接命令行运行测试(适合自动化/CI)。
--autostart
启动后自动开始测试,但保留 Web UI。
--web-host <ip>
Web UI 绑定的主机地址,默认所有网卡。
--web-port <port>
Web UI 端口,默认 8089。
--html <filename>
生成 HTML 格式的测试报告。
--csv <filename>
生成 CSV 格式的测试报告。
分布式相关
--master
以 Master 节点启动(分布式压测)。
--worker
以 Worker 节点启动(分布式压测)。
--master-host <hostname>
Worker 连接的 Master 节点 IP。
--master-port <port>
Worker 连接的 Master 节点端口。
--expect-workers <int>
Master 等待多少 Worker 连接后再开始测试。
其他常用参数
-h, --help
显示帮助信息。
-l, --list
列出所有可用的 User 类。
--loglevel <level>
日志级别(DEBUG/INFO/WARNING/ERROR/CRITICAL)。
--config <filename>
读取额外的配置文件。
-T, --tags
只运行带指定 tag 的任务。
-E, --exclude-tags
排除带指定 tag 的任务。
--show-task-ratio
显示各 User 类的任务比例。
使用示例
单机 Web UI 模式:
locust -f locustfile.py --host=https://www.example.com
命令行无 UI,100 用户,10秒启动,1分钟压测:
locust -f locustfile.py --headless -u 100 -r 10 -t 1m --host=https://www.example.com
分布式 Master:
locust -f locustfile.py --master --host=https://www.example.com
分布式 Worker:
locust -f locustfile.py --worker --master-host=192.168.1.100