from unittest.mock import AsyncMock async def foo(): return 42 async def test_foo(): mock_foo = AsyncMock(return_value=42) result = await mock_foo() mock_foo.assert_awaited_once() assert result == 42
from unittest.mock import AsyncMock async def bar(): raise ValueError("Some Error") async def test_bar_error(): mock_bar = AsyncMock(side_effect=ValueError("Some Error")) try: await mock_bar() except ValueError as ex: assert str(ex) == "Some Error" mock_bar.assert_awaited_once()In this example, we create an AsyncMock object that simulates the behavior of the bar() function, raising a ValueError exception. The AsyncMock is called with the await keyword, and we catch the exception raised by the mock. We assert that the exception has the expected message and use the assert_awaited_once method to assert that the mock was called only once. The unittest.mock package is part of the Python standard library, and it is available from Python 3.3 onwards.