Testing
As we learned in Chapter 3, Coding, Testing, and Documentation: the Virtuous Cycle, the biggest challenge when writing functional tests for a service that calls other services is to isolate all network calls. In this section, we'll see how we can mock asynchronous calls made using aiohttp
.
Testing aiohttp
and its outgoing web requests involves a different approach to traditional synchronous tests. The aioresponses
project (https://github.com/pnuckowski/aioresponses) allows you to easily create mocked responses to web requests made using an aiohttp
ClientSession
:
# test_aiohttp_fixture.py
import asyncio
import aiohttp
import pytest
from aioresponses import aioresponses
@pytest.fixture
def mock_aioresponse():
with aioresponses() as m:
yield m
@pytest.mark.asyncio
async def test_ctx(mock_aioresponse):
async with aiohttp.ClientSession() as session:
mock_aioresponse.get("http://test.example.com", payload={"foo": "bar...