【问题标题】:How to rename python locust actions?如何重命名python蝗虫动作?
【发布时间】:2020-04-14 08:15:19
【问题描述】:

我有来自 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)

在 locust 日志和 locust web (localhost:8089) 我看到了下一个任务

- /login
- /logout
- /
- /profile

但是,如果我需要在一项任务中处理少量请求并从完整任务(而不是 1 个请求)中获取衡量标准。
我想看到的是:

- login
- logout
- index
- profile

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

【问题讨论】:

    标签: python performance-testing locust taurus


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以通过实现自定义 execute_task() 方法来触发 request_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 = ...
      

      如果TaskSet继承自TaskReportingTaskSet,上面的代码会报告所有任务的运行时间。如果您想包含on_starton_stop,则必须单独触发request_success 事件。

      如果您不想报告 HTTP 请求,您可以简单地使用不是内置 Locust HTTP 客户端之一的 HTTP 客户端。例如,您可以直接使用 python 请求:

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

      【讨论】:

      • 我可以在装饰器@task(weight) 上使用这种方法吗?例如@task(2) def execute_task...
      • 优秀的方法!谢谢。但是如果execute_task 失败了怎么办?在这种情况下,event.request_success 也会被解雇
      • 如果任务引发任何异常,我已更新答案以触发request_failure 事件。
      猜你喜欢
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      相关资源
      最近更新 更多