Locust FastResponse 的失败属性未在报告中将请求设置为失败

Locust FastResponse's failure attribute doesn't set request as failed in report

我在 locustfile 中有这样的任务:

class Tasks(FastHttpUser):
    headers = {'content-type': 'application/json', 'Connection': 'close'}

    @task
    def task(self):
        payload = "some data"
        try:
            with self.client.post("/endpoint", data=payload, headers=self.headers,
                                  name="request", catch_response=True) as response:
                result = json.loads(response.content)
                if len(result["result"]) == 0:
                    response.failure(result)
                    log.error(result)
        except (TypeError, JSONDecodeError) as err:
            response.failure(response.text)
            log.error(f'{type(err).__name__} because of : {response.status_code} - {response.text}')

我预计如果响应不通过声明或会有一些意外的答案,此响应将被标记为失败并作为失败添加到统计信息中,但它没有发生,我在日志中只看到错误. 如果我想检查响应的内容,它是使用失败属性的正确方法还是使用不同的东西更好?

您需要在 with 块中执行 response.failure(...)。按照你的方式,由于 with-block 的意外终止,响应已经丢失。

使用这样的东西:

with self.client.post("/endpoint", data=payload, headers=self.headers,
                        name="request", catch_response=True) as response:
    try:
        result = json.loads(response.content)
        if len(result["result"]) == 0:
            response.failure(result)
            log.error(result)
    except (TypeError, JSONDecodeError) as err:
        response.failure(response.text)
        log.error(f'{type(err).__name__} because of : {response.status_code} - {response.text}')