I am using aiohttp to make asynchronous requests and I want to test my code. I want to mock out requests sent by aiohttp.ClientSession. I am looking for something similar to the way responses handles mocking for the requests lib.
How can I mock out responses made by aiohttp.ClientSession?
# sample method
async def get_resource(self, session):
    async with aiohttp.ClientSession() as session:
        response = await self.session.get("some-external-api.com/resource")
        if response.status == 200:
            result = await response.json()
            return result
        return {...}
# I want to do something like ...
aiohttp_responses.add(
    method='GET', 
    url="some-external-api.com/resource", 
    status=200, 
    json={"message": "this worked"}
)
async def test_get_resource(self):
    result = await get_resource()
    assert result == {"message": "this worked"}
Edit
I've used https://github.com/pnuckowski/aioresponses on a few projects and it has worked well for my needs.
class MockResponse:
    def __init__(self, text, status):
        self._text = text
        self.status = status
    async def text(self):
        return self._text
    async def __aexit__(self, exc_type, exc, tb):
        pass
    async def __aenter__(self):
        return self
@pytest.mark.asyncio
async def test_exchange_access_token(self, mocker):
    data = {}
    resp = MockResponse(json.dumps(data), 200)
    mocker.patch('aiohttp.ClientSession.post', return_value=resp)
    resp_dict = await account_api.exchange_access_token('111')
Since I posted this question, I have used this library for mocking out aiohttp requests: https://github.com/pnuckowski/aioresponses and it has worked well for my needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With