简介
Locust是一款易于使用的分布式用户负载测试工具。它用于对网站(或其他系统)进行负载测试,并确定系统可以处理多少并发用户。
特点
- 使用python编写测试脚本
- 支持模拟数十万用户
- 基于web的操作界面
- 可以测试任何网站
安装
系统centos 7
pip install locustio
示例代码
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 on_stop(self):
""" on_stop is called when the TaskSet is stopping """
self.logout()
def login(self):
self.client.post("/login", {"username":"ellen_key", "password":"education"})
def logout(self):
self.client.post("/logout", {"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):
weight = 1
task_set = UserBehavior
min_wait = 5000
max_wait = 9000
host=https://google.com
class MobileUserLocust(HttpLocust):
weight = 3
task_set = UserBehavior
min_wait = 5000
max_wait = 9000
host=https://google.com
Locust类参数(MobileUserLocust)
- task_set:指定定义用户行为的类,包含一组任务
- min_wait:最小的等待时间,毫秒
- max_wait:最大的等待时间,毫秒 两者为声明则默认为1秒
- host:加载的主机的URL前缀
- weight:运行的次数比例
TaskSet类参数
@task(1):任务装饰器,参数为运行次数的比例
TaskSequence类
TaskSequence类是一个TaskSet,但它的任务将按顺序执行.
from locust import TaskSequence, task
class MyTaskSequence(TaskSequence):
@seq_task(1)
def first_task(self):
pass
@seq_task(2)
def second_task(self):
pass
@seq_task(3)
@task(10)
def third_task(self):
pass
在上面的示例中,顺序被定义为执行first_task,然后执行second_task,最后执行third_task 10次
启动测试
//启动指定文件
locust -f ./locust_test.py
//启用2个locust
locust -f locust_file.py WebUserLocust MobileUserLocust
打开测试界面
http://127.0.0.1:8089 你的服务器IP,本地则为localhost或者127.0.0.1
登录 | 立即注册