Skip to main content

Async mock HTTP server for pytest, built on top of aiohttp.

Project description

async-pytest-httpserver

PyPI PyPI Downloads

No AI was used in the creation of this library.

async-pytest-httpserver is a fully asynchronous mock HTTP server for pytest, built on top of aiohttp.

It is designed for testing code that makes HTTP requests (via aiohttp, httpx, requests, etc.) without depending on real external services.

Features

  • Fully asynchronous — implemented using aiohttp
  • Dynamic runtime mocking — add or modify mock routes while the server is running
  • Seamless pytest integration — works smoothly with pytest-aiohttp and pytest-asyncio
  • Real TCP server — compatible with any HTTP client (aiohttp, httpx, requests, etc.)
  • Supports async handlers — easily define coroutine-based responses
  • Flexible mock responses — either return a Response object or a handler that produces one

How to use

1. fixture for start mock server

from async_pytest_httpserver import (
    MockData,
    AddMockDataFunc,
)

@pytest_asyncio.fixture
async def some_service_mock(
    external_service_mock: Callable[
        [], Awaitable[tuple[str, AddMockDataFunc]]
    ],
) -> AsyncGenerator[AddMockDataFunc, None]:
    url, add_mock_data = await external_service_mock()
    old_url = settings.EXTERNAL_SERVICE_URL
    settings.EXTERNAL_SERVICE_URL = url
    try:
        yield add_mock_data
    finally:
        settings.EXTERNAL_SERVICE_URL = old_url

2. mock and test it

static mock

import pytest
from http import HTTPStatus
from async_pytest_httpserver import (
    MockData,
)
from aiohttp.web import json_response, Request, Response


@pytest.mark.asyncio
async def test_static_mock(client, some_service_mock):
    # Arrange
    response = json_response(
        {"result": "some_result"},
        status=HTTPStatus.OK,
    )
    calls_info = some_service_mock(MockData("POST", "/some_api", response))

    # Act
    response = await client.post(
        f"{settings.EXTERNAL_SERVICE_URL}/some_api",
        json={"text": "text"},
    )

    # Assert
    assert response.ok
    data = await response.json()
    assert data["result"] == "some_result"

    assert len(calls_info) == 1
    call_info = calls_info[0]
    assert call_info["json"] == {"text": "text"}

dynamic async mock

import pytest
from http import HTTPStatus
from async_pytest_httpserver import (
    MockData,
)
from aiohttp.web import json_response, Request, Response


async def async_mock_handler(request: Request) -> Response:
    return json_response(
        {"result": "some_result"},
        status=HTTPStatus.OK,
    )


@pytest.mark.asyncio
async def test_async_handler(client, some_service_mock):
    # Arrange
    calls_info = some_service_mock(
        MockData("POST", "/some_api", async_mock_handler)
    )

    # Act
    response = await client.post(
        f"{settings.EXTERNAL_SERVICE_URL}/some_api",
        json={"text": "text"},
    )

    # Assert
    assert response.ok
    data = await response.json()
    assert data["result"] == "some_result"

    assert len(calls_info) == 1
    call_info = calls_info[0]
    assert call_info["json"] == {"text": "text"}

dynamic sync mock

import pytest
from http import HTTPStatus
from async_pytest_httpserver import (
    MockData,
)
from aiohttp.web import json_response, Request, Response

def sync_mock_handler(request: Request) -> Response:
    return json_response(
        {"result": "some_result"},
        status=HTTPStatus.OK,
    )


@pytest.mark.asyncio
async def test_sync_handler(client, some_service_mock):
    # Arrange
    calls_info = some_service_mock(
        MockData("POST", "/some_api", sync_mock_handler)
    )

    # Act
    response = await client.post(
        f"{settings.EXTERNAL_SERVICE_URL}/some_api",
        json={"text": "text"},
    )

    # Assert
    assert response.ok
    data = await response.json()
    assert data["result"] == "some_result"

    assert len(calls_info) == 1
    call_info = calls_info[0]
    assert call_info["json"] == {"text": "text"}

mock data types

1. just aiohttp.web.Response

for example:

from aiohttp.web import json_response

json_response(
    {"result": "some_result"},
    status=HTTPStatus.OK,
)

2. callable

If you need custom behavior instead of a static response, you can provide a callable (func or async func) that returns a aiohttp.web.Response.

It must match the following signature:

ResponseHandler = Callable[
    [web.Request], web.Response | Awaitable[web.Response]
]

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

async_pytest_httpserver-1.0.1.tar.gz (68.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

async_pytest_httpserver-1.0.1-py3-none-any.whl (5.6 kB view details)

Uploaded Python 3

File details

Details for the file async_pytest_httpserver-1.0.1.tar.gz.

File metadata

File hashes

Hashes for async_pytest_httpserver-1.0.1.tar.gz
Algorithm Hash digest
SHA256 6fe632d71ab60b483b152e1a794522fd2ded85e8ba6f928bbb14098eb89dc5f2
MD5 3e8b52c43bb3f31721d529748ada594a
BLAKE2b-256 610f09b33d2c7f7a6e2b0c2480b35403fd38ddd5b6c162c540186b79e9931cae

See more details on using hashes here.

File details

Details for the file async_pytest_httpserver-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for async_pytest_httpserver-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 3283005a8a17668449d3a2c9080722a41bcaf00e6a5dab154956d25dfee9b40d
MD5 aceb6e68cafc94037970fc5cc9f65c73
BLAKE2b-256 38ed434810d4b807411c96d87d6239b7dc6da88474fa7866feac9b8858f3a5a3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page