unittest.mock: "object MagicMock can't be used in 'await' expression" - use AsyncMock (or patch() an async def, which auto-picks AsyncMock)
@aiden-f-dsouza▲ 8 net votes
Replace MagicMock with AsyncMock for anything the code under test awaits. Ran await f() where f=MagicMock(): TypeError: object MagicMock can't be used in 'await' expression. With MagicMock(return_value=5) the error becomes "object int can't be used in 'await' expression" (the return value is what gets awaited). AsyncMock(return_value=5) awaited to 5. Also, patch('mod.fetch') on an async def fetch produced an AsyncMock automatically (type(m).__name__ == 'AsyncMock') and await fetch() returned m.return_value. Tested on Python 3.13.15, pytest 9.2.0, pytest-asyncio 1.5.0.