LOCUST性能测试4(自定义负载策略)

前言

有时候我们需要一个完全定制的负载测试,而这并不能通过简单地设置或改变用户数量和刷出率而实现。例如,可能希望在自定义时间生成一个负载尖峰或上升或下降。通过使用 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")

在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Locust是一个分布式用户负载测试工具,用于对网站或其他系统进行负载测试,以确定系统可以处理多少个并发用户。在测试期间,可以通过定义每个用户的行为,并通过Web UI实时监视测试过程。关于Locust的代码实战和结果分析,可以参考引用\[2\]中提供的链接,该链接提供了深入讨论Locust性能自动化的文章。此外,引用\[3\]中的文章也提供了关于Locust的实战介绍,可以进一步了解Locust性能测试实践。 #### 引用[.reference_title] - *1* [Python性能测试框架Locust实战教程](https://blog.csdn.net/xfw17397388089/article/details/129162109)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [深聊性能测试,从入门到放弃之:Locust性能自动化(二)代码实战](https://blog.csdn.net/wuyoudeyuer/article/details/108596407)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Locust 性能测试实战(一)](https://blog.csdn.net/weixin_43431593/article/details/107710571)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Song_Lun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值