Python压力测试工具——Locust

发布时间:2024-11-22 00:09

Python程序员认证:通过学习Python语言并通过编程测试 #生活技巧# #工作学习技巧# #技能认证指南#

Python压力测试工具——Locust

最新推荐文章于 2024-10-21 15:46:12 发布

XerCis 于 2020-08-25 16:05:05 发布

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

简介

Locust一款开源性能测试工具,易于使用、脚本化、可扩展,对开发者非常友好。

特性:

代码定义用户行为
不用笨重的UI或膨胀的XML,只要简单的代码。分布式和可扩展
Locust支持在多台机器上运行分布式的负载测试,可以用来模拟数百万个并发用户。深受考验
Locust已被用来模拟数百万个并发用户。Battlelog是一个通过网页发送游戏连接请求的应用,它使用Locust进行了负载测试,所以说Locust是Battletested (久经沙场)。

在这里插入图片描述

安装

pip install locust 1

初试

app.py

import json import tornado.web import tornado.ioloop LOGIN = False # 是否登录 def fib(n): """计算斐波那契数列的第n项""" if n < 2: return n return fib(n - 1) + fib(n - 2) class LoginHandler(tornado.web.RequestHandler): def post(self): body = self.request.body body = json.loads(body) username = body.get("username") password = body.get("password") if username == "foo" and password == "bar": global LOGIN LOGIN = True self.write("Welcome!") else: self.set_status(400) class IndexHandler(tornado.web.RequestHandler): def get(self): if LOGIN: self.write("Hello World!") else: self.set_status(400) class ItemHandler(tornado.web.RequestHandler): def get(self): id = self.get_argument("id") id = int(id) self.write(str(fib(id))) if __name__ == "__main__": print("http://localhost:8888") app = tornado.web.Application([ (r"/login", LoginHandler), (r"/hello", IndexHandler), (r"/world", IndexHandler), (r"/item", ItemHandler), ]) app.listen(8888) tornado.ioloop.IOLoop.instance().start()

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253

locustfile.py

import time from locust import HttpUser, task, between class QuickstartUser(HttpUser): host = "http://localhost:8888" # 访问的站点,最后不要加斜杠 wait_time = between(1, 2) @task def index_page(self): self.client.get("/hello") self.client.get("/world") @task(3) def view_item(self): for item_id in range(10): self.client.get(f"/item?id={item_id}", name="/item") time.sleep(1) def on_start(self): self.client.post("/login", json={"username": "foo", "password": "bar"})

123456789101112131415161718192021

启动Locust:locust

若需指定路径:locust -f locust_files/my_locust_file.py

访问http://localhost:8089/,模拟用户数设为100,每秒产生用户设为10,开始
在这里插入图片描述

结果
在这里插入图片描述

遇到的坑

无法访问http://0.0.0.0:8089/
关闭科学上网工具,尝试访问http://localhost:8089/。接口运行正确但没有图表出来
如本人使用360浏览器,切换至极速模式即可。

参考文献

Locust 官网Locust 文档Locust GitHubLocust Examples性能测试工具Locust

网址:Python压力测试工具——Locust https://www.yuejiaxmz.com/news/view/182240

相关内容

主流压力测试工具推荐
推荐10个开源的压力/负载测试工具
测试工具之压力测试工具推荐
CPU压力测试工具cpuburn
DNS压力测试工具
系统性能测试
websocket压力测试小工具
Apache 压力测试工具ab
接口压力测试工具(推荐)
【redis】redis压力测试工具

随便看看