最新版本0.7.2文档:http://docs.locust.io/en/latest/quickstart.html
Locust简介
Locust是一个简单易用的分布式负载测试工具,主要用来对网站进行负载压力测试。
Locust特性
- 使用Python编写模拟用户行为的代码,无需繁琐的配置
- 分布式可扩展,能够支持上百万用户
- 自带Web界面
- 不仅能测试web系统,也可以测试其它系统
Locust思想
在测试过程中,一群用户将访问你的网站。每个用户的行为由你编写的Python代码定义,同时可以从Web界面中实时观察到用户的行为。
Locust完全是事件驱动的,因此在单台机器上能够支持几千并发用户访问。与其它许多基于事件的应用相比,Locust并不使用回调,而是使用gevent,而gevent是基于协程的,可以用同步的方式来编写异步执行的代码。每个用户实际上运行在自己的greenlet中。
Locust安装
Locust可以通过pip或者easy_install安装:
pip install locustio 或者 easy_install locustio
安装完Locust后,shell命令locust就可以使用了,可以查看locust命令有哪些选项:
locust --help
如果打算以分布式模式运行Locust,建议同时安装pyzmq:
pip install pyzmq 或者 easy_install pyzmq
Locust初步使用
locustfile.py例子
下面是一个简单的locustfile.py文件。
from locust import HttpLocust, TaskSet def login(l): l.client.post("/login", {"username":"ellen_key", "password":"education"}) def index(l): l.client.get("/") def profile(l): l.client.get("/profile") class UserBehavior(TaskSet): tasks = {index:2, profile:1} def on_start(self): login(self) class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait=5000 max_wait=9000
在上面的代码中,定义了一些locust任务,这些任务是用Python函数定义的。这些函数传入一个参数,也就是Locust类的实例。这些任务然后被聚集在TaskSet类的tasks属性中,用来表示一个用户访问网站的行为。接着,HttpLocust类表示一个用户,这个用户具有哪些行为,以及该用户在执行下一个任务之前应该等待多长时间。
HttpLocust类继承于Locust类,它增加了一个client属性,这个client实际上是HttpSession实例,可以用来发起HTTP请求。
上面的代码示例了一种定义任务的方式,下面是一种更方便的方式,该方式使用了task装饰器。
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
启动Locust
在shell中执行locust命令即可启动Locust。如果locustfile.py文件在当前目录,那么直接执行locust命令即可。如果locustfile.py文件在别的地方,可以执行
locust -f /path/to/locustfile.py --host=http://www.aaa.com/ #要测试的网站
至于如何在分布式模式下运行Locust,请参考Running Locust distributed
打开Web界面
在shell中执行locust命令,如果没有问题的话,命令输出会提示可以在浏览器中打开Locust的Web界面,访问地址默认是http://127.0.0.1:8089。在浏览器中打开该地址,就可以看到像下面这样的Web界面:
原文:http://maslino.website/post/locust-load-testing-tool.html