当前位置:网站首页>Locust performance test 4 (custom load Policy)
Locust performance test 4 (custom load Policy)
2022-07-07 09:08:00 【Song_ Lun】
Preface
Sometimes we need a fully customized load test , This cannot be achieved by simply setting or changing the number of users and the brush out rate . for example , You may want to generate a load spike or rise or fall at a custom time . By using LoadTestShape class , You can completely control the user count and generation rate at any time .
Time based peak strategy
There is such a need , A login interface has 10 Users log in at the same time , And continue 180 second , So we need to set it like this ? I'm going to use LoadTestShape class
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/26 10:11 In the morning
# @Name : peilun
# @File : Testshape_test.py
from locust import LoadTestShape, task, HttpUser, constant
import json
""" Custom load policy Generate every second 5 Users , The duration of the 180s """
class MyUser(HttpUser):
# Request interval
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
# Login is performed only once obtain token
print(" User initialization -- Log in and get token")
self.data = {
"username":"123456","password":"123456"}
respon = self.client.post(self.url, headers = self.headers, data=json.dumps(self.data), name=' The user login ', verify=False, timeout=10)
resp_dict = respon.json()
# print(f' The response data is :{resp_dict}')
if respon.status_code == 200:
# print(resp_dict['msg'])
print(f' The response data is :{
resp_dict}')
Authorization = respon.headers['Authorization']
return Authorization
else:
respon.failure(resp_dict['msg'])
# Generate every second 10 Users , The duration of the 180s
class MyCustomShape(LoadTestShape):
# Set the duration of pressure measurement , Unit second
time_limit = 180
# Start every second / Number of users stopped
spawn_rate = 10
def tick(self):
""" Returns a tuple , Contains two values : user_count -- Total users spawn_rate -- Start every second / Number of users stopped return None when , Stop the load test """
# Get the execution time of pressure test
run_time = self.get_run_time()
# The operation duration is within the maximum duration of pressure measurement , Then continue
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")

Step based load policy
Every time 30 Second increase 5 Users , continued 10 minute
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/26 10:11 In the morning
# @Name : peilun
# @File : Testshape_test2.py
from locust import LoadTestShape, task, HttpUser, constant
import json
import math
""" Custom load policy Every time 30 Second increase 5 Users , continued 10 minute """
class MyUser(HttpUser):
# Request interval
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
# Login is performed only once obtain token
print(" User initialization -- Log in and get token")
self.data = {
"username":"123456","password":"123456"}
respon = self.client.post(self.url, headers = self.headers, data=json.dumps(self.data), name=' The user login ', verify=False, timeout=10)
resp_dict = respon.json()
# print(f' The response data is :{resp_dict}')
if respon.status_code == 200:
# print(resp_dict['msg'])
print(f' The response data is :{
resp_dict}')
Authorization = respon.headers['Authorization']
return Authorization
else:
respon.failure(resp_dict['msg'])
# Generate every second 10 Users , The duration of the 180s
class MyCustomShape(LoadTestShape):
""" step_time -- Time between steps step_load -- Users increase the number at each step spawn_rate -- The user stops every second in every step / Number of starts time_limit -- The time limit , In seconds """
step_time = 30
step_load = 5
spawn_rate = 10
time_limit = 600
def tick(self):
# Get the time to perform the pressure test
run_time = self.get_run_time()
# The running time is beyond the time limit , Do not perform
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")

Load policy based on time period
front 10s and 10-20s The number of users is 10;20-50s The number of users is 50;50-80s The number of users is 100;80s The number of subsequent users is 30
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/26 10:11 In the morning
# @Name : peilun
# @File : Testshape_test3.py
from locust import LoadTestShape, task, HttpUser, constant
import json
""" Custom load policy front 10s and 10-20s The number of users is 10;20-50s The number of users is 50;50-80s The number of users is 100;80s The number of subsequent users is 30 """
class MyUser(HttpUser):
# Request interval
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
# Login is performed only once obtain token
print(" User initialization -- Log in and get token")
self.data = {
"username":"123456","password":"123456"}
respon = self.client.post(self.url, headers = self.headers, data=json.dumps(self.data), name=' The user login ', verify=False, timeout=10)
resp_dict = respon.json()
# print(f' The response data is :{resp_dict}')
if respon.status_code == 200:
# print(resp_dict['msg'])
print(f' The response data is :{
resp_dict}')
Authorization = respon.headers['Authorization']
return Authorization
else:
respon.failure(resp_dict['msg'])
class MyCustomShape(LoadTestShape):
""" duration -- How many seconds to enter the next stage users -- The number of users spawn_rate -- Start every second / Number of users stopped """
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")

边栏推荐
- GoLand set goproxy
- 2022-06-30 Unity核心8——模型导入
- 【istio简介、架构、组件】
- Recommended by Alibaba P8, the test coverage tool - Jacobo is very practical
- 模拟卷Leetcode【普通】1609. 奇偶树
- Simulation volume leetcode [general] 1609 Parity tree
- Unity shader beginner's Essentials (I) -- basic lighting notes
- LeetCode 715. Range module
- Interpretation of MySQL optimization principle
- RuntimeError: Calculated padded input size per channel: (1 x 1). Kernel size: (5 x 5). Kernel size c
猜你喜欢

STM32 clock system

Three updates to build applications for different types of devices | 2022 i/o key review

数字三角形模型 AcWing 1027. 方格取数

2022-06-30 unity core 8 - model import

LED模拟与数字调光

Reflections on the way of enterprise IT architecture transformation (Alibaba's China Taiwan strategic thought and architecture practice)

Hard core sharing: a common toolkit for hardware engineers

Expérience de port série - simple réception et réception de données

串口实验——简单数据收发

2021 year end summary
随机推荐
模拟卷Leetcode【普通】1557. 可以到达所有点的最少点数目
Systick tick timer
阿里p8推荐,测试覆盖率工具—Jacoco,实用性极佳
PMP examination experience sharing
LeetCode 715. Range 模块
Original collection of hardware bear (updated on June 2022)
9c09730c0eea36d495c3ff6efe3708d8
Mountaineering team (DFS)
Output all composite numbers between 6 and 1000
STM32串口寄存器库函数配置方法
Reflections on the way of enterprise IT architecture transformation (Alibaba's China Taiwan strategic thought and architecture practice)
面试题:高速PCB一般布局、布线原则
【ChaosBlade:根据标签删除POD、Pod 域名访问异常场景、Pod 文件系统 I/O 故障场景】
【istio简介、架构、组件】
Recommended by Alibaba P8, the test coverage tool - Jacobo is very practical
[chaosblade: node CPU load, node network delay, node network packet loss, node domain name access exception]
个人力扣题目分类记录
go mod module declares its path as: gtihub. com/xxx-xx but was required as:xx-xx
2022-06-30 Unity核心8——模型导入
What are the conditions for applying for NPDP?