Locust 是python编写的一个简单易用的压力测试工具,官方网站
安装
使用pypi安装非常简单,一条命令即可:1
pip install locustio
一个简单的demo
1 | from locust import HttpLocust, TaskSet |
一个Locust示例包括一个 User类WebsiteUser继承自HttpLocust,主要是针对模拟用户的一些设置,task_set任务集,
min_wait和max_wait两次请求之间的间隔设置等。还有一个UserBehavior 定义了每个模拟用户的行为。
也可以用装饰器@task来简化上面的写法:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22from locust import HttpLocust, TaskSet, task
class UserBehavior(TaskSet):
def on_start(self):
""" on_start is called when a Locust start before any task is scheduled """
self.login()
def login(self):
self.client.post("/login", {"username":"ellen_key", "password":"education"})
@task(2)
def index(self):
self.client.get("/")
@task(1)
def profile(self):
self.client.get("/profile")
class WebsiteUser(HttpLocust):
task_set = UserBehavior
min_wait = 5000
max_wait = 9000
task接受一个参数,weight:权重,权重越高,方法被调用的可能性也就越高。
开始测试
在命令行输入一下命令开始:1
locust -f locust_files/my_locust_file.py --host=http://example.com
然后可以在本地可以一个Web界面开始测试: