RSS Amplifier

Rida Ayed · Jul 26, 2025

Patch the async json response of a mocked aiohttp clientsession in pytest

0
Sign in to vote or save

This page cannot be shown here. You can still read it on the original site — the toolbar below keeps your place in the directory.

Haven’t found a short concise example covering pytest whilst focussing the patched json method of a mocked async session, hence this snippet. First install pytest-asyncio . pipenv install -d pytest-asyncio Now use it as highlighted. from unittest.mock import patch, AsyncMock import aiohttp import pytest async def request_async (): async with aiohttp . ClientSession(headers = {}) as session:…

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

First install pytest-asyncio.

pipenv install -d pytest-asyncio

Now use it as highlighted.

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

Read on /posts/mock-patch-aiohttp-clientsession-json-pytest/

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.