如何重命名python蝗虫操作?

2024-10-06 11:21:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有来自locustio文档的下一个代码:

from locust import HttpLocust, TaskSet, between

def login(l):
    l.client.post("/login", {"username":"ellen_key", "password":"education"})

def logout(l):
    l.client.post("/logout", {"username":"ellen_key", "password":"education"})

def index(l):
    l.client.get("/")

def profile(l):
    l.client.get("/profile")

class UserBehavior(TaskSet):
    tasks = {index: 2, profile: 1}

    def on_start(self):
        login(self)

    def on_stop(self):
        logout(self)

class WebsiteUser(HttpLocust):
    task_set = UserBehavior
    wait_time = between(5.0, 9.0)

在蝗虫日志和蝗虫网络(localhost:8089)中,我看到了接下来的任务

- /login
- /logout
- /
- /profile

但是,如果我需要在一个任务中有几个请求,并从完整的任务(而不是一个请求)中获取度量值,该怎么办呢

- login
- logout
- index
- profile

我想查看任务的名称,而不是请求url。 在Jmeter中,我可以在一个操作中插入几个请求,并获得操作时间(不是请求)


Tags: keyselfclientindexdefusernameloginpassword
2条回答

可以通过每个请求的name属性设置名称,请参见示例:

def index(l):
  l.client.get("/", name="index")

def profile(l):
  l.client.get("/profile", name="my-profile")

您可以通过实现一个定制的execute_task()方法来实现这一点,在该方法中触发request\u success事件

像这样的方法应该会奏效:

import time

class TaskReportingTaskSet(TaskSet):
    def execute_task(self, task, *args, **kwargs):
        start = time.time()
        try:
            super().execute_task(task, *args, **kwargs)
        except:
            events.request_failure.fire(
                request_type="task",  
                name=task.__name__, 
                response_time=(time.time()-start)*1000, 
                response_length=0,
            )
            raise
        else:
            events.request_success.fire(
                request_type="task",  
                name=task.__name__, 
                response_time=(time.time()-start)*1000, 
                response_length=0,
            )

class UserBehavior(TaskReportingTaskSet):
    tasks = ...

使用上述代码,如果任务集从TaskReportingTaskSet继承,则将报告所有任务的运行时^如果要包含on_starton_stop,则必须分别激发{}事件

如果您不想报告HTTP请求,只需使用一个HTTP客户端,它不是内置的蝗虫HTTP客户端之一。例如,您可以直接使用python请求:

import requests

def index(l):
    requests.get("/")

相关问题 更多 >