Locust 官方网站:https://www.locust.io/
1. Locust 介绍
An open source load testing tool.
一个开源性能测试工具。
define user behaviour with python code, and swarm your system with millions of simultaneous users.
使用 Python 代码来定义用户行为。用它可以模拟百万计的并发用户访问你的系统。
1.1 性能工具对比
-
LoadRunner 是非常有名的商业性能测试工具,功能非常强大。使用也比较复杂,目前大多介绍性能测试的书籍都以该工具为基础,甚至有些书整本都在介绍 LoadRunner 的使用。
-
Jmeter 同样是非常有名的开源性能测试工具,功能也很完善,在本书中介绍了它作为接口测试工具的使用。但实际上,它是一个标准的性能测试工具。关于Jmeter相关的资料也非常丰富,它的官方文档也很完善。
-
Locust 同样是性能测试工具,虽然官方这样来描述它 “An open source load testing tool.” 。但其它和前面两个工具有着较大的不同。相比前面两个工具,功能上要差上不少,但它也并非优点全无。
-
Locust 完全基本 Python 编程语言,采用 Pure Python 描述测试脚本,并且 HTTP 请求完全基于 Requests 库。除了 HTTP/HTTPS 协议,Locust 也可以测试其它协议的系统,只需要采用Python调用对应的库进行请求描述即可。
-
LoadRunner 和 Jmeter 这类采用进程和线程的测试工具,都很难在单机上模拟出较高的并发压力。Locust 的并发机制摒弃了进程和线程,采用协程(gevent)的机制。协程避免了系统级资源调度,由此可以大幅提高单机的并发能力。
2. 安装
2.1 方式一:通过 pip 命令安装
pip install locust
- 1
2.2 方式二:GitHub下载安装
将项目克隆下来,通过Python 执行 setup.py 文件
最后,检查是否安装成功。在命令行中输入 “locust --help” 回车。
3. Locust 创建性能测试
3.1 编写性能测试脚本
创建 locustfile.py 文件
from locust import HttpUser, between, task
class WebsiteUser(HttpUser):
wait_time = between(5, 15)
@task
def index(self):
self.client.get("/")
@task
def keyword(self):
self.client.get("/s?wd=locust")
self.client.get("/s?wd=测试")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
3.2 执行性能测试脚本
locust -f .\locustfile.py --host=https://www.baidu.com
- 1
-f 指定性能测试脚本文件。
–host 指定被测试应用的URL的地址
输出:
[2020-06-20 11:16:09,859] WINDOWS-8TS3PNG/WARNING/locust.main: System open file limit setting is not high enough for load testing, and the OS wouldnt allow locust to increase it by itself. See https://docs.locust.io/en/stable/installation.html#increasing-maximum-number-of-open-files-limit for more info.
[2020-06-20 11:16:09,860] WINDOWS-8TS3PNG/INFO/locust.main: Starting web interface at http://:8089
[2020-06-20 11:16:09,874] WINDOWS-8TS3PNG/INFO/locust.main: Starting Locust 1.0.3
- 1
- 2
- 3
3.3 运行测试
通过浏览器访问:http://localhost:8089(Locust启动网络监控器,默认为端口号为: 8089)
3.3.1 设置并发参数、并启动测试
- Number of users to simulate 设置模拟用户数。
- Hatch rate(users spawned/second) 每秒启动的虚拟用户数(小于总用户数,以便看到用户数增长相关趋势变化)。
- 点击 “Start swarming” 按钮,开始运行性能测试。
4. 性能测试/界面参数说明
4.1 Top
4.2 Statistics
参数 | 说明 |
---|---|
Type | 请求的类型,例如GET/POST |
Name | 请求的路径。 |
request | 当前请求的数量 |
fails | 当前请求失败的数量 |
Median | 中间值,单位毫秒,一半的服务器响应时间低于该值,而另一半高于该值 |
Average | 平均值,单位毫秒,所有请求的平均响应时间 |
Min | 请求的最小服务器响应时间,单位毫秒 |
Max | 请求的最大服务器响应时间,单位毫秒 |
Content Size | 单个请求的大小,单位字节 |
reqs/sec | 是每秒钟请求的个数 |