Type stubs for the mock library providing comprehensive type annotations for Mock, MagicMock, patch decorators, and other testing utilities
Specialized mock class for testing asynchronous code with await-specific assertions and async-aware call tracking. AsyncMock provides comprehensive support for testing coroutines, async context managers, and async iterators with full type safety.
Mock class specifically designed for testing asynchronous code with await tracking and async-specific assertion methods.
class AsyncMock(Mock):
def __init__(self, *args, **kwargs) -> None:
"""
Create an async mock that can be awaited and tracks await calls.
Inherits all Mock parameters and adds async-specific functionality.
"""
# Async assertion methods
def assert_awaited(self) -> None:
"""Assert the mock has been awaited at least once."""
def assert_awaited_once(self) -> None:
"""Assert the mock has been awaited exactly once."""
def assert_awaited_with(self, *args, **kwargs) -> None:
"""Assert the mock was last awaited with specified arguments."""
def assert_awaited_once_with(self, *args, **kwargs) -> None:
"""Assert the mock was awaited exactly once with specified arguments."""
def assert_any_await(self, *args, **kwargs) -> None:
"""Assert the mock was awaited with specified arguments at some point."""
def assert_has_awaits(self, calls, any_order: bool = False) -> None:
"""Assert the mock has been awaited with specified call sequence."""
def assert_not_awaited(self) -> None:
"""Assert the mock has never been awaited."""
def reset_mock(
self,
visited=None,
*,
return_value: bool = False,
side_effect: bool = False
) -> None:
"""Reset mock state including await tracking."""
# Async state attributes
await_count: int # Number of times mock was awaited
await_args: call | None # Arguments from last await
await_args_list: list[call] # All await arguments
# Function metadata for better integration
__name__: str
__defaults__: tuple[Any, ...]
__kwdefaults__: dict[str, Any]
__annotations__: dict[str, Any] | NoneUsage examples:
import asyncio
from mock import AsyncMock
# Basic async mock usage
async def test_async_function():
async_mock = AsyncMock(return_value="async_result")
# Await the mock
result = await async_mock("arg1", key="value")
assert result == "async_result"
# Assert await behavior
async_mock.assert_awaited_once_with("arg1", key="value")
assert async_mock.await_count == 1
# Mock async context manager
async def test_async_context_manager():
async_mock = AsyncMock()
async_mock.__aenter__.return_value = "context_value"
async_mock.__aexit__.return_value = None
async with async_mock as ctx:
assert ctx == "context_value"
async_mock.__aenter__.assert_awaited_once()
async_mock.__aexit__.assert_awaited_once()
# Mock async iterator
async def test_async_iterator():
async_mock = AsyncMock()
async_mock.__aiter__.return_value = async_mock
async_mock.__anext__.side_effect = ["item1", "item2", StopAsyncIteration]
items = []
async for item in async_mock:
items.append(item)
assert items == ["item1", "item2"]
async_mock.__aiter__.assert_called_once()AsyncMock supports both synchronous and asynchronous side effects:
# Async side effect function
async def async_side_effect(*args, **kwargs):
await asyncio.sleep(0.1)
return f"processed: {args}"
async_mock = AsyncMock(side_effect=async_side_effect)
result = await async_mock("test")
assert result == "processed: ('test',)"
# Exception side effect
async_mock = AsyncMock(side_effect=ValueError("async error"))
try:
await async_mock()
except ValueError as e:
assert str(e) == "async error"
# Multiple return values
async_mock = AsyncMock(side_effect=["first", "second", "third"])
assert await async_mock() == "first"
assert await async_mock() == "second"
assert await async_mock() == "third"AsyncMock integrates seamlessly with the patching system:
from mock import patch, AsyncMock
# Patch async function
@patch('module.async_function', new_callable=AsyncMock)
async def test_with_async_patch(mock_async_func):
mock_async_func.return_value = "mocked_result"
# Test code that calls module.async_function
result = await module.async_function("arg")
assert result == "mocked_result"
mock_async_func.assert_awaited_once_with("arg")
# Context manager patching
async def test_with_context_patch():
with patch('module.async_function', new_callable=AsyncMock) as mock_func:
mock_func.return_value = "mocked"
result = await module.async_function()
assert result == "mocked"AsyncMock supports specification-based mocking for async objects:
class AsyncService:
async def fetch_data(self, query: str) -> dict:
# Real implementation
pass
async def process_data(self, data: dict) -> str:
# Real implementation
pass
# Create mock with async specification
async_service_mock = AsyncMock(spec=AsyncService)
async_service_mock.fetch_data.return_value = {"result": "data"}
async_service_mock.process_data.return_value = "processed"
# Use the mock
data = await async_service_mock.fetch_data("query")
result = await async_service_mock.process_data(data)
async_service_mock.fetch_data.assert_awaited_once_with("query")
async_service_mock.process_data.assert_awaited_once_with({"result": "data"})# Async-specific call tracking extends regular call functionality
# call objects work the same for both sync and async contexts
# Coroutine function type checking (from backports)
def iscoroutinefunction(func) -> bool:
"""Check if a function is a coroutine function."""
# Async test case base class (from backports)
class IsolatedAsyncioTestCase:
"""Base class for async test cases with isolated event loops."""Install with Tessl CLI
npx tessl i tessl/pypi-types-mock