Python 压力测试工具 Locust

Locust 是python编写的一个简单易用的压力测试工具,官方网站

安装

使用pypi安装非常简单,一条命令即可:

1
pip install locustio

一个简单的demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from locust import HttpLocust, TaskSet

def test_shop(l):
l.client.post("/v1/stage/?apikey=43aae2d0-625e-11e7-901c-a1891b15059c",data=json.dumps({'shop_id':str(random.randint(88327646,88337646)),'is_standard':'2'}),headers=headers,timeout=3000)

def test_stock(l):
l.client.get('/v1/stock/stock/getStockInfoByCode?shop_id=246&code=123&pack=1')


class UserBehavior(TaskSet):
tasks = {test_shop:10}

def on_start(self):
test_shop(self)

class WebsiteUser(HttpLocust):
task_set = UserBehavior
min_wait = 100
max_wait = 1000

一个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
22
from 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界面开始测试:
locust

你的支持我的动力