Colin-b / pytest_httpx

pytest fixture to mock HTTPX
https://colin-b.github.io/pytest_httpx/
MIT License
344 stars 32 forks source link

How can I send multiple responses matching the same request? #119

Closed finswimmer closed 11 months ago

finswimmer commented 11 months ago

Hello,

thanks a lot for this project :pray:

The only thing I miss until now, is an option to define a response list, like it exists for requests-mock.

I need it to simulate a retry. Unlike in #75 my requests are identical, so unfortunately I have no header or something like that, which I can use to distinguish the requests.

fin swimmer

finswimmer commented 11 months ago

Using a callback which pops items from a list, seems to be a way to do it :thinking:

responses = [
    httpx.Response(status_code=401),
    httpx.Response(status_code=200, content="some response"),
]

def response_list(_: httpx.Request) -> httpx.Response:
    return responses.pop(0)

httpx_mock.add_callback(response_list, method="POST", url=re.compile(".+/some/endpoint"))
Colin-b commented 11 months ago

Hello @finswimmer ,

You can call httpx_mock.add_response as many times as you want. As explained in the documentation, the order of registration will be respected.

Your sample could then be something like the following:

httpx_mock.add_response(status_code=401, method="POST", url=re.compile(".+/some/endpoint"))
httpx_mock.add_response(status_code=200, content="some response", method="POST", url=re.compile(".+/some/endpoint"))

Does it solve your issue or did I miss something?

finswimmer commented 11 months ago

Awesome :+1: Works perfectly fine :partying_face:

(Now I have to go and buy some glasses to find it in the docs the next time :grin: )