Colin-b/pytest_httpx

Dynamic callback mock is not called when there were matching already used static responses.

Closed this issue · 4 comments

Adding a callback mock for an URL which matched previously to any static response mock has no effect.
Seems that pytext-httpx chooses to use last (even already used) static response, even though there is an unused callback mock waiting to be picked.
This is counter-intuitive and incompatible at least with aioresponses.

@pytest.mark.asyncio
async def test_callback_order(httpx_mock: HTTPXMock):
    async with httpx.AsyncClient() as client:
        httpx_mock.add_response(url='http://localhost/api', json={'response': 'first'})
        assert 'first' == (await client.get('http://localhost/api')).json()['response']

        httpx_mock.add_response(url='http://localhost/api', json={'response': 'second'})
        assert 'second' == (await client.get('http://localhost/api')).json()['response']

        def _callback(req: httpx.Request):
            return httpx.Response(status_code=200, json={'response': 'third'})

        httpx_mock.add_callback(_callback, url='http://localhost/api')
        assert 'third' == (await client.get('http://localhost/api')).json()['response']

The result:

>           assert 'third' == (await client.get('http://localhost/api')).json()['response']
E           AssertionError: assert 'third' == 'second'
E             - second
E             + third

Hello @alex-kowalczyk ,

I was not planning on someone using both response and callbacks matching the same URL in the same test function. Your use case is valid of course. I will see what I can do to fix this.

Thanks again for reporting.

Release 0.18.0 is now available on pypi and should fix your issue.

@Colin-b , I confirm 0.18.0 solves the issue. This was a lightning fast fix!

Glad to hear :) Note that in your sample you are using matching on url when registering responses and callbacks. This is not mandatory (if you are coming from aioresponses, where it might be a requirement)