Patch the json response of a mocked aiohttp clientsession in pytest | Rida Ayed

Patch the json response of a mocked aiohttp clientsession in pytest

Haven’t found a short concise example covering pytest whilst focussing the patched json method of a mocked async session, hence this snippet.

pipenv install pytest-asyncio
test.py
from unittest.mock import patch, AsyncMock
import aiohttp
import pytest


async def request_async():
    async with aiohttp.ClientSession(headers={}) as session:
        async with session.get("foo.bar") as response:
            jsn = await response.json()
    return jsn


@pytest.mark.asyncio
@patch('aiohttp.ClientSession.get')
async def test_get_request(mock_get):
    expected = {"a": "b"}
    mock_response = AsyncMock()
    mock_response.json.return_value = expected
    mock_get.return_value.__aenter__.return_value =\
         mock_response
    result = await request_async()
    assert result == expected