安装
pip install locust
官方案例
# locustfile.py
import time
from locust import HttpUser, task, between
class QuickstartUser(HttpUser):
wait_time = between(1, 2.5)
@task
def hello_world(self):
self.client.get("/hello")
self.client.get("/world")
@task(3)
def view_items(self):
for item_id in range(10):
self.client.get(f"/item?id={item_id}", name="/item")
time.sleep(1)
def on_start(self):
self.client.post("/login", json={"username":"foo", "password":"bar"})
说明
class QuickstartUser(HttpUser):
这里我们为要模拟的用户定义一个类。它继承自HttpUser,这个类包含了get,post等http请求方法,它给每个用户一个client属性,它是HttpSession的一个实例,可以用来向我们要加载测试的目标系统发出HTTP请求。当一个测试开始时,locust将为它模拟的每个用户创建一个这个类的实例,并且这些用户中的每个人都将开始在他们自己的gevent线程中运行。
wait_time = between(1, 2.5)
我们的类定义了一个等待时间,它将使模拟用户在每个任务执行后等待1到2.5秒。
有三种可选:
constant: for a fixed amount of time
between: for a random time between a min and max value
constant_pacing: for an adaptive time that ensures the task runs (at most) once every X seconds
@task
def hello_world(self):
self.client.get("/hello")
self.client.get("/world")
@task(3)
def view_items(self):
...
只有用@task修饰的方法才会在每个运行的用户中被随机调用,在多个被修饰的方法中,配置的权重的@task(3),则会比没有配置的高出三倍的调用率。
def on_start(self):
self.client.post("/login", json={"username":"foo", "password":"bar"})
每个用户启动时都会调用on_start,可以在这里搞登陆之类操作
启动
上面的代码存为locustfile.py的话,直接在当前目录执行locust就行
如果文件名字是自定义的, 可以locust -f 指定文件
–host 指定要测试的域名
–web-port 指定web界面的端口,默认是8089
locust --host=http://xxapi.xxx.net --web-port=8000
web界面
http://localhost:6011
Number of total users to simulate设置一个最大用户数
Spawn rate每秒开启的用户数,方便递增的查看系统压力临界值
Hosthost在这配置也行
参考;
https://docs.locust.io/en/stable/what-is-locust.html