asyncmock

0.4.2 · active · verified Thu Apr 16

asyncmock is a Python library that extends the standard `unittest.mock` framework to provide robust support for mocking asynchronous functions and coroutines. It's particularly useful for testing async codebases in Python versions prior to 3.8 (where `unittest.mock.AsyncMock` was introduced). The current version is 0.4.2, and while stable, the project has a slow release cadence, with the latest significant updates being several years ago.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an `AsyncMock`, set its `return_value` and `side_effect`, and then await it. It also shows how to use `assert_awaited_once()` to verify that the mock was called asynchronously. In real tests, you would typically use `unittest.mock.patch` to replace the actual dependency.

import asyncio
from asyncmock import AsyncMock

async def my_async_function_to_test():
    return await some_external_async_call()

async def some_external_async_call():
    # This would be an actual external async call in a real app
    await asyncio.sleep(0.01)
    return "original result"

async def test_my_async_function():
    # Create an AsyncMock instance
    mocked_external_call = AsyncMock(return_value="mocked result")

    # Temporarily replace the actual async call with the mock
    # For this example, let's just use the mock directly for simplicity.
    # In a real test, you'd typically use unittest.mock.patch.
    # For quickstart, let's redefine the async function to use the mock directly

    async def my_async_function_with_mock():
        return await mocked_external_call()

    print(f"Calling function with mock...")
    result = await my_async_function_with_mock()

    print(f"Received result: {result}")
    assert result == "mocked result"

    # Assert that the mock was awaited exactly once
    mocked_external_call.assert_awaited_once()
    print("Mocked function was awaited once successfully.")

    # Demonstrate side_effect
    mocked_external_call.reset_mock()
    mocked_external_call.side_effect = ["first", "second", RuntimeError("Async error!")]

    try:
        print(f"Side effect 1: {await my_async_function_with_mock()}")
        print(f"Side effect 2: {await my_async_function_with_mock()}")
        await my_async_function_with_mock() # This will raise an exception
    except RuntimeError as e:
        print(f"Caught expected error: {e}")

asyncio.run(test_my_async_function())

view raw JSON →