pnuckowski / aioresponses

Aioresponses is a helper for mock/fake web requests in python aiohttp package.
MIT License
513 stars 86 forks source link

Do not mock all requests #259

Open Sanchoyzer opened 5 months ago

Sanchoyzer commented 5 months ago

I've found a bad side effect of using aioresponses: it tries to mock all requests (not just those with rules written). For example:

python 3.12
aioresponses==0.7.6
pytest==8.2.1
pytest-asyncio==0.23.7

Try to mock only a request to 'https://another.site' and don't mock a request to 'https://google.com':

@pytest.mark.asyncio
async def test_1():
    async def my_func():
        async with aiohttp.ClientSession() as session:
            async with session.get('https://google.com') as resp:
                assert resp.status == 200

    await my_func()
    with aioresponses() as mocked:
        mocked.get('https://another.site', status=200)
        await my_func()

But there is an error:

        response = await self.match(method, url, **kwargs)

        if response is None:
>           raise ClientConnectionError(
                'Connection refused: {} {}'.format(method, url)
            )
E           aiohttp.client_exceptions.ClientConnectionError: Connection refused: GET https://google.com

The thing is, aioresponses didn't find the match for 'https://google.com' and raise an exception instead of executing the request without mocking. This behavior may not be so good for general cases. For example, similar library for mocking (pytest-httpx) mocks according to written rules, not all requests.