Locust - retry certain status code but default-handle all others

Viewed 336

I have a Locust task that might end up in a 401 if my access token expires. In that case I will renew it and then retry the task. This works all perfectly (based on this):

@task
def list_claims(self):
    with self.client.get("/api/1.0/claim/", name="LIST claims", headers=self.headers, catch_response=True) as response:
        if response.status_code == 401:
            logging.info("401 - Need to fetch a new access token!") # usually happens when the access tokens expires after an hour
            self.aad_b2c_auth()
            raise RescheduleTaskImmediately() # re-run this task with the newly refreshed token

The problem is that this seems to suck up all other status codes, so the task will never show up as failed, even it it, for example, returns a 503 etc. I assume that's because of the catch_response=True?! So ideally I would only like to special-handle the 401 and leave the rest to the default handler (2xx = success, 4xx/5xx = failure). Is there a built-in way to achieve that?

1 Answers

You should be able to just add an else statement after your 401 check and fire off the request event. An example of that can be seen here in the context of manually firing request events when testing other systems. The API documented here. Essentially just something like this should work:

else:
    environment.events.request.fire(**response.request_meta)

Alternatively, you could try marking the request has not having a manual result and Locust might do the firing for you.

else:
    response._manual_result = False

Not sure if doing it this way is technically supported so it may not always function properly and thus could require additional maintenance down the road.

Related