在Locust中,如何从一个任务获取响应并将其传递给另一个任务?

18

我已经开始使用Locust做性能测试。我想向两个不同的端点发送两个post请求。但第二个post请求需要第一个请求的响应。有什么便捷的方法可以实现这一点?我尝试了以下方法但没有成功。

from locust import HttpLocust, TaskSet, task

class GetDeliveryDateTasks(TaskSet):

    request_list = []

    @task
    def get_estimated_delivery_date(self):
        self.client.headers['Content-Type'] = "application/json"
        response = self.client.post("/api/v1/estimated-delivery-date/", json=
        {
            "xx": "yy"

        }
          )
        json_response_dict = response.json()
        request_id = json_response_dict['requestId']
        self.request_list.append(request_id)


    @task
    def store_estimated_delivery_date(self):
        self.client.headers['Content-Type'] = "application/json"
        response = self.client.post("/api/v1/estimated-delivery-date/" + str(self.request_list.pop(0)) + "/assign-order?orderId=1")


class EDDApiUser(HttpLocust):
    task_set = GetDeliveryDateTasks
    min_wait = 1000
    max_wait = 1000
    host = "http://localhost:8080"

在我看来,你应该创建一个单一的任务,在这个任务中你既可以获取交货日期,也可以存储它。 - matusko
1个回答

20

在将数据传递到task列表之前,您可以调用on_start(self)函数来为您准备数据。请参见以下示例:

from locust import HttpLocust, TaskSet, task

class GetDeliveryDateTasks(TaskSet):

    request_list = []

    def get_estimated_delivery_date(self):
        self.client.headers['Content-Type'] = "application/json"
        response = self.client.post("/api/v1/estimated-delivery-date/", json=
        {
            "xx": "yy"

        }
          )
        json_response_dict = response.json()
        request_id = json_response_dict['requestId']
        self.request_list.append(request_id)

    def on_start(self):
        self.get_estimated_delivery_date()


    @task
    def store_estimated_delivery_date(self):
        self.client.headers['Content-Type'] = "application/json"
        response = self.client.post("/api/v1/estimated-delivery-date/" + str(self.request_list.pop(0)) + "/assign-order?orderId=1")


class EDDApiUser(HttpLocust):
    task_set = GetDeliveryDateTasks
    min_wait = 1000
    max_wait = 1000
    host = "http://localhost:8080"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接