2

Trying to mock the response of a aiohttp.ClientSession for testing purposes

My code looks like this:

async def run_request(endpoint: str, **kwargs) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.post(endpoint, **kwargs) as response:
            response_json = await response.json()

            return {"response": response, "response_json": response_json}

I would like to test my code with something that I image looks like this:

@patch("aiohttp.ClientSession.post", <something>)
def test_run_request(self):

How can I do that?

1 Answers1

3

There are a lot different solutions for that issue, I think the easiest way is use aioresponses lib. (https://github.com/pnuckowski/aioresponses)

But this will work correctly only if you are using ONLY ClientSession without aiohttp.web.Application. If you are using CS as a part of aiohttp.web.Application you will broke application test_client (pytest-aiohttp).

Also see this question How to mock aiohttp.client.ClientSession.get async context manager. There is some useful examples there.

Yurii Kramarenko
  • 1,025
  • 6
  • 16