首页 > 其他分享 >三、locust --事件

三、locust --事件

时间:2024-12-11 10:57:34浏览次数:4  
标签:users -- locust environment runner 事件 test response

from locust.runners import (MasterRunner, WorkerRunner, STATE_STOPPING, STATE_STOPPED,
                            STATE_CLEANUP, LocalRunner)
from locust import HttpUser, TaskSet, task, events, LoadTestShape, run_single_user
from gevent._semaphore import Semaphore
import json
import traceback
import gevent
import time

'''请求成功时触发'''
def on_request_success(request_type, name, response_time, response_length):
    print( 'success  Type: {}, Name: {}, Time: {}ms, length: {}'
           .format(request_type, name, response_time,response_length))

'''请求失败时触发'''
def on_request_failure(request_type, name, response_time, response_length, exception):
    print('failure  Type: {}, Name: {}, Time: {}ms, exception: {}, response_length:{}'
          .format(request_type, name, response_time, exception, response_length))

'''在执行locust类内发生异常时触发'''
def on_locust_error(locust_instance, exception, tb):
    print("error  locust_instance: {}, exception: {}, traceback: {}"
          .format(locust_instance, exception, traceback.format_tb(tb)))

'''退出进程时回调'''
def on_quitting(environment, **kwargs):
    print("Test quit")

'''停止测试的时候客户端会调这个方法发送数据到主节点这边'''
def on_test_stop(environment, **kwargs):
    if not isinstance(environment.runner, MasterRunner):
        print("Cleaning up test data")
        # 节点往主节点发送的数据
        environment.runner.send_message('acknowledge_users', f"Thanks for the Cleaning up test data users!")
    else:
        users = [
            {"name": "User1"},
            {"name": "User2"},
            {"name": "User3"},
        ]
        environment.runner.send_message('test_users', users)

'''#定义worker节点注册的消息'''
def setup_test_users(environment, msg, **kwargs):
    for user in msg.data:
        print(f"User {user['name']} received")
    environment.runner.send_message('acknowledge_users', f"Thanks for the {len(msg.data)} users!")

'''定义matser节点注册的消息'''
def on_acknowledge(msg, **kwargs):
    print("recv worker data :{}".format(msg.data))

'''
#主动退出进程时:environment.process_exit_code = 0
#判断错误率大于多少N主动退出进程
#判断响应时间大于多少N主动退出进程
#判断响应时间
'''
def checker(environment):
    while not environment.runner.state in [STATE_STOPPING, STATE_STOPPED, STATE_CLEANUP]:
        time.sleep(1)
        if environment.stats.total.fail_ratio > 0.01:
            print("Test failed due to failure ratio > 1%,code=1")
            environment.process_exit_code = 1
            '''这个语句是退出'''
            environment.runner.quit()
        elif environment.stats.total.avg_response_time > 200:
            print("Test failed due to average response time ratio > 200 ms,code=1")
            environment.process_exit_code = 1
        elif environment.stats.total.get_response_time_percentile(0.95) > 300:
            print("Test failed due to 95th percentile response time > 800 ms,code=1")
            environment.process_exit_code = 1
        else:
            environment.process_exit_code = 0
            pass
            # print("Test Normal task exit code=0")


'''
#初始化时绑定的重写方法,该类中进行了worler和master节点的消息注册
'''
def on_locust_init(environment, **kwargs):
    if not isinstance(environment.runner, MasterRunner):
        '''
        #初始化的时候注册消息,客户端的消息,往客户端的往这个类型发就行
        '''
        environment.runner.register_message('test_users', setup_test_users)
    if not isinstance(environment.runner, WorkerRunner):
        '''
        #初始化的时候注册消息,服务端的消息,往后服务端往这个类型发就行
        '''
        environment.runner.register_message('acknowledge_users', on_acknowledge)

    if isinstance(environment.runner, MasterRunner) or isinstance(environment.runner, LocalRunner):
        gevent.spawn(checker, environment)


def on_test_start(environment, **kwargs):
    '''如果运行环境不是主节点'''
    if not isinstance(environment.runner, MasterRunner):
        users = [
            {"name": "User1"},
            {"name": "User2"},
            {"name": "User3"},
        ]
        environment.runner.send_message('test_users', users)


'''''''''
#创建集合点,当locust实例产生完成时触发
'''
all_locusts_spawned = Semaphore()
# 上锁
all_locusts_spawned.acquire()
'''
#生成所有locust用户时触发
'''
def on_hatch_complete(**kwargs):
    # 释放锁
    all_locusts_spawned.release()
'''
#事件回调绑定
'''
events.spawning_complete.add_listener(on_hatch_complete)
events.request_success.add_listener(on_request_success)
events.request_failure.add_listener(on_request_failure)
events.user_error.add_listener(on_locust_error)
events.quitting.add_listener(on_quitting)
events.init.add_listener(on_locust_init)
'''
#主节点才触发
'''
events.test_start.add_listener(on_test_start)
events.test_stop.add_listener(on_test_stop)
header = {"Content-Type": "application/json;charset=UTF-8"}

 

标签:users,--,locust,environment,runner,事件,test,response
From: https://www.cnblogs.com/Mr-Simple001/p/18598879

相关文章

  • 二、locust --locust_demo
    #*_*coding:utf-8*_*#@Author:zyb#HttpUser:保持会话。FastHttpUser:高性能fromlocustimportTaskSet,task,HttpUser,FastHttpUser,between,constant_throughput,constant_pacing,constant#argument_parser这个可以修改执行参数的fromgevent._semaphoreimpo......
  • OpenAI:o1模型的安全评估报告
    ......
  • 一、locust --events常用
    #*_*coding:utf-8*_*#@Author:zybfromlocustimportTaskSet,task,FastHttpUser,between,events#定义任务集类@events.request.add_listenerdefon_request(request_type,name,context,response,exception,**kwargs):ifrequest_type=="GET"......
  • 中国ICD行业PLM市场研究报告
    导读:作为电子产业的工业粮食,ICD(集成电路设计)是一个高度专业化的领域,当前已广泛应用于计算机、通信、消费电子、汽车、医疗设备等多个行业。近年来,国家发布多项积极政策,助推行业快速发展来提升自主可控技术及国际市场竞争力,以解决“卡脖子”问题。而“绿色+智能”时代的到来,则......
  • AtCoder Beginner Contest 383
    AtCoderBeginnerContest383//前三题都很水,只能写写这种题骗自己了A-Humidifier1​ 直接模拟#include<bits/stdc++.h>usingnamespacestd;#defineintlonglong#defineinfINT32_MAX#definePIIpair<int,int>#defineendl'\n'inlinevoidsolve(){......
  • GitHub 正式收录 MoonBit 作为一门通用编程语言!核心用户突破三万!
    MoonBit 编程语言正式被Github收录!这对于一个仅有两年发展时间的编程语言来说是一种高度认可,期待未来由MoonBit编写的项目数量快速增长,早日成为首个由国人研发迈进10万➕用户的编程语言。最近用户数已经接近3万(数据统计来源综合VisualStudioMarketplac......
  • 五、locust -- 顺序执行 SequentialTaskSet
    #*_*coding:utf-8*_*#@Author:zybimportqueueq=queue.Queue()foriinrange(100):q.put(i)fromlocustimportFastHttpUser,task,between,SequentialTaskSetclassMySequentialTasks(SequentialTaskSet):@taskdeftask_one(self):......
  • 气动接头厂家前十
    气动元件德国FESTO德国Festo是世界领先的自动化技术供应商,也是世界气动行业第一家通过ISO9001认证的企业。FESTO的品牌质量包含许多方面,主要表现在智能化和易操作的产品设计、使用寿命长的产品、持久的效率优化。Festo公司不仅提供气动元件、组件和预装配的子系统,下设的工程部......
  • 如何通过看板方法提高团队协作?5个实用技巧!
    一、看板方法概述什么是看板方法看板方法源于丰田生产系统,是一种通过可视化方式管理任务和工作流程的强大工具。它将工作流程中的任务、进度、问题等直观地展示出来,帮助团队成员更好地理解和掌控工作。看板方法可以看作是将一个软件开发流程或其他工作流程类比为一段自......
  • springboot和spring对应版本的介绍
    SpringBoot、Spring、JDK版本对应关系:SpringBoot版本对应Spring版本JDK版本SpringBoot特性描述3.2.x6.1.x17,21增强的云本地支持,新的架构优化,支持Java213.1.x6.0.x17,20加入新的架构组件,性能优化增强,支持Java203.0.x6.0.x17+支持Java17,移......