前言
有时候我们需要一个完全定制的负载测试,而这并不能通过简单地设置或改变用户数量和刷出率而实现。例如,可能希望在自定义时间生成一个负载尖峰或上升或下降。通过使用 LoadTestShape
类,您可以在任何时候完全控制用户计数和生成速率。
基于时间峰值策略
有这样一个需求,一个登录接口每秒有10个用户同时登录,并持续180秒,这样我们需要这么设置呐?下面就要用到 LoadTestShape
类
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/26 10:11 上午
# @Name : peilun
# @File : Testshape_test.py
from locust import LoadTestShape, task, HttpUser, constant
import json
"""
自定义负载策略
每秒生成5个用户,持续时间180s
"""
class MyUser(HttpUser):
# 请求间隔时间
wait_time = constant(1)
host = 'https://www.baidu.com'
url = '/api/user/login'
headers = {'Content-Type': 'application/json'}
@task
def on_start(self):
global Authorization
# 登录只执行一次 获取token
print("用户初始化--登录后获取token")
self.data = {"username":"123456","password":"123456"}
respon = self.client.post(self.url, headers = self.headers, data=json.dumps(self.data), name='用户登录', verify=False, timeout=10)
resp_dict = respon.json()
# print(f'响应数据为:{resp_dict}')
if respon.status_code == 200:
# print(resp_dict['msg'])
print(f'响应数据为:{resp_dict}')
Authorization = respon.headers['Authorization']
return Authorization
else:
respon.failure(resp_dict['msg'])
# 每秒生成10个用户,持续时间180s
class MyCustomShape(LoadTestShape):
# 设置压测持续时长,单位秒
time_limit = 180
# 每秒启动/停止用户数
spawn_rate = 10
def tick(self):
"""
返回一个元组,包含两值:
user_count -- 总用户数
spawn_rate -- 每秒启动/停止用户数
返回None时,停止负载测试
"""
# 获取压测执行的时间
run_time = self.get_run_time()
# 运行时长在压测最大时长内,则继续执行
if run_time < self.time_limit:
user_count = round(run_time, -1)
return user_count, self.spawn_rate
return None
if __name__ == '__main__':
import os
os.system("locust -f Testshape_test.py")
基于步骤负载策略
每30秒增加5个用户,持续10分钟
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/26 10:11 上午
# @Name : peilun
# @File : Testshape_test2.py
from locust import LoadTestShape, task, HttpUser, constant
import json
import math
"""
自定义负载策略
每30秒增加5个用户,持续10分钟
"""
class MyUser(HttpUser):
# 请求间隔时间
wait_time = constant(1)
host = 'https://www.baidu.com'
url = '/api/user/login'
headers = {'Content-Type': 'application/json'}
@task
def on_start(self):
global Authorization
# 登录只执行一次 获取token
print("用户初始化--登录后获取token")
self.data = {"username":"123456","password":"123456"}
respon = self.client.post(self.url, headers = self.headers, data=json.dumps(self.data), name='用户登录', verify=False, timeout=10)
resp_dict = respon.json()
# print(f'响应数据为:{resp_dict}')
if respon.status_code == 200:
# print(resp_dict['msg'])
print(f'响应数据为:{resp_dict}')
Authorization = respon.headers['Authorization']
return Authorization
else:
respon.failure(resp_dict['msg'])
# 每秒生成10个用户,持续时间180s
class MyCustomShape(LoadTestShape):
"""
step_time -- 步骤之间的时间
step_load -- 用户在每一步增加数量
spawn_rate -- 用户在每一步式每秒停止/启动数量
time_limit -- 时间限制,以秒为单位
"""
step_time = 30
step_load = 5
spawn_rate = 10
time_limit = 600
def tick(self):
# 获取执行压测的时间
run_time = self.get_run_time()
# 运行时长在时间限制外,则不执行
if run_time > self.time_limit:
return None
current_step = math.floor(run_time / self.step_time) + 1
return current_step * self.step_load, self.spawn_rate
if __name__ == '__main__':
import os
os.system("locust -f Testshape_test2.py")
基于时间阶段负载策略
前10s和10-20s用户数为10;20-50s用户数为50;50-80s用户数为100;80s后用户数为30
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/26 10:11 上午
# @Name : peilun
# @File : Testshape_test3.py
from locust import LoadTestShape, task, HttpUser, constant
import json
"""
自定义负载策略
前10s和10-20s用户数为10;20-50s用户数为50;50-80s用户数为100;80s后用户数为30
"""
class MyUser(HttpUser):
# 请求间隔时间
wait_time = constant(1)
host = 'https://www.baidu.com'
url = '/api/user/login'
headers = {'Content-Type': 'application/json'}
@task
def on_start(self):
global Authorization
# 登录只执行一次 获取token
print("用户初始化--登录后获取token")
self.data = {"username":"123456","password":"123456"}
respon = self.client.post(self.url, headers = self.headers, data=json.dumps(self.data), name='用户登录', verify=False, timeout=10)
resp_dict = respon.json()
# print(f'响应数据为:{resp_dict}')
if respon.status_code == 200:
# print(resp_dict['msg'])
print(f'响应数据为:{resp_dict}')
Authorization = respon.headers['Authorization']
return Authorization
else:
respon.failure(resp_dict['msg'])
class MyCustomShape(LoadTestShape):
"""
duration -- 多少秒后进入下一个阶段
users -- 用户数
spawn_rate -- 每秒要启动/停止的用户数
"""
stages = [
{"duration": 10, "users": 10, "spawn_rate": 10},
{"duration": 20, "users": 50, "spawn_rate": 10},
{"duration": 50, "users": 100, "spawn_rate": 10},
{"duration": 80, "users": 30, "spawn_rate": 10}
]
def tick(self):
run_time = self.get_run_time()
for stage in self.stages:
if run_time < stage["duration"]:
tick_data = (stage["users"], stage["spawn_rate"])
return tick_data
if __name__ == '__main__':
import os
os.system("locust -f Testshape_test3.py")