Interview frequency: …
Short answer
Use IsolatedAsyncioTestCase in unittest, or a plugin such as pytest-asyncio or anyio in pytest, so the test runs inside an event loop and the coroutine is actually awaited.
Explanation
Calling a coroutine without await inside a regular test only creates the coroutine and never runs it, so the test passes falsely. Isolate the network and time (for example with AsyncMock), make sure to test cancellation, timeouts, and error paths, and make sure the test leaves no pending background tasks. Enabling asyncio's debug mode helps detect coroutines that were never awaited.
Code example
import pytest
from unittest.mock import AsyncMock
@pytest.mark.asyncio
async def test_fetch_profile_uses_client():
client = AsyncMock()
client.get.return_value = {"name": "Mona"}
profile = await fetch_profile(client, user_id=1)
assert profile.name == "Mona"
client.get.assert_awaited_once_with("/users/1")Common mistakes
- Writing def test_x(): fetch() without await, so the test passes without running anything.
- Using a plain Mock instead of AsyncMock for an async function.
Follow-up questions
- What is an event loop and what is the role of a coroutine in asyncio?
- How do you test HTTP code without relying on a real network?