locust基础demo
# 示例1
最小demo脚本(以shortcoder的index页面为例)
from locust import HttpUser, task, between # 定义压测用户类 TestIndex, 继承 HttpUser → 表示这是模拟HTTP请求的用户 class TestIndex(HttpUser): # 等待时间配置:每个用户在执行任务后,随机等待 1 秒再发起下一次请求 wait_time = between(1, 1) # @task 标记:表示下面这个方法是一个压测任务 # Locust 会自动循环执行这个任务 @task def getIndex(self): # self.client:自带的HTTP客户端,自动保持会话(cookie、登录态) self.client.get("/login") #print("接口请求执行成功") #1. locust -f testIndex.py --host=http://localhost:5000 #2. http://http://127.0.0.1:8089 #监控页面 #3. 设置 用户数,ramp up(逐步增加)
配置并执行

压测数据
RPS 接近用户数,说明响应及时
99分位值为78ms,同样印证响应迅速

七分钟后的图标:
RPS依然接近用户数
95分位响应时间28ms,依然迅速

示例2,多任务,共10个用户,每个用户先登录鉴权成功后执行 getjobs 和 getcurrentuser
from locust import HttpUser, task, between # 定义压测用户类 TestIndex # 继承 HttpUser → 表示这是模拟HTTP请求的用户 class TestIndex(HttpUser): # 等待时间配置:每个用户在执行任务后,随机等待 1~3 秒再发起下一次请求 wait_time = between(1, 3) def on_start(self): """ VU初始化阶段:仅在VU启动时执行一次 步骤: 1. GET访问/login页面 2. POST调用 /users/authenticate 登录,获取token 3. 全局header注入Authorization,后续接口自动携带token 完成之后,才会循环执行 @task 业务接口 """ self.client.get("/login") #打开login页面 self.my_account={"username": "admin", "password": "@dm1nlstrat0R", "mode": "", "domain": ""} with self.client.post( "/users/authenticate", # 登录接口路径 json=self.my_account, # 用专属账号的JSON数据 catch_response=True, # 开启手动断言 timeout=10 # 超时时间10秒 ) as response: try: # 从登录返回的 JSON 中取出 token self.token = response.json()["token"] # 给这个用户的所有后续请求自动带上 Authorization 请求头 self.client.headers["Authorization"] = f"Bearer {self.token}" if response.json()["userName"] == "admin": response.success() print(f"登录成功!用户名:{self.my_account['username']}") else: fail_msg = f"登录失败!响应内容:{response.text[:200]}" response.failure(fail_msg) print(fail_msg) except Exception as e: err_msg = f"请求异常:{str(e)}" response.failure(err_msg) print(err_msg) @task(4) def getjobs(self): with self.client.get("/api/jobs", catch_response=True) as response: if response.json()[0]["name"] == "Job 1": response.success() print("获取jobs成功") else: response.failure("getcurrentuser fail") @task(6) def getcurrentuser(self): with self.client.get("/users/getcurrentuser", catch_response=True) as response: if response.json()["userName"] == "admin": response.success() print("getcurrentuser成功") else: response.failure("getcurrentuser fail")
执行:
locust -f demo.py --host=http://localhost:5000
测试结果


浙公网安备 33010602011771号