locust性能测试入门
好文推荐:https://blog.csdn.net/JOJOY_tester/article/details/77926470
单个cpu运行:locust -f my_locust_file.py
分布式多cpu运行:
1、启动locust:locust -f my_locust_file.py --master &
2、一个slave表示启动一个cpu:locust -f my_locust_file.py --slave --master-host=127.0.0.1 &
3、locust -f 被执行的文件.py --step-load 逐步增加 "Number of users to increase by step" 逐步增加用户数; "Step duration"步长持续运行时间
图中第一个参数是指递增之后的最大用户数,默认端口8089
no-web方式运行,主要用于调试脚本:locust -f locust_files/my_locust_file.py --no-web --csv=locust -c10 -r2 --run-time 1h30m
event的例子通俗易懂:https://www.cnblogs.com/lovesoo/p/7719070.html
基础http接口示例:
#coding:utf-8 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 host='http://example.com' min_wait = 5000 max_wait = 9000
通用协议接口示例:
TestHttpbin是测试人员是将待测的接口封装成测试类,CustomClient是一个会触发request_success和request_failure事件的自定义客户端,CustomLocust继承了Locust的类,将Locust中的client实例化成我们的自定义客户端CustomClient
import time from locust import Locust, TaskSet, events, task import requests class TestHttpbin(object): def status(self): try: r = requests.get('http://httpbin.org/status/200') status_code = r.status_code print status_code assert status_code == 200, 'Test Index Error: {0}'.format(status_code) except Exception as e: print e class CustomClient(object): def test_custom(self): start_time = time.time() try: # add your custom test function here TestHttpbin().status() name = TestHttpbin().status.__name__ except Exception as e: total_time = int((time.time() - start_time) * 1000) events.request_failure.fire(request_type="Custom", name=name, response_time=total_time, exception=e) else: total_time = int((time.time() - start_time) * 1000) events.request_success.fire(request_type="Custom", name=name, response_time=total_time, response_length=0) class CustomLocust(Locust): def __init__(self, *args, **kwargs): super(CustomLocust, self).__init__(*args, **kwargs) self.client = CustomClient() class ApiUser(CustomLocust): min_wait = 100 max_wait = 1000 class task_set(TaskSet): @task(1) def test_custom(self): self.client.test_custom()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南