PythiloLesson 5 of 10 · progress kept in this browser

Verify awaited dependencies

Calling an async function produces an awaitable; the work does not necessarily happen until it is awaited. AsyncMock therefore distinguishes a call from an await. Its await assertions check the interaction that an async consumer actually needs.

Use an injected dependency so the test can supply AsyncMock without contacting a remote service. Configure a return value and inspect await arguments. A consumer that forgets await can otherwise appear to have called its dependency while returning a coroutine object or skipping the intended result. Standalone examples enter the event loop with asyncio.run.

import asyncio
from unittest.mock import AsyncMock
async def demo():
    fetch = AsyncMock(return_value=7)
    print(await fetch("key"))
    fetch.assert_awaited_once_with("key")
asyncio.run(demo())
Your task

Implement async fetch_twice(fetch,key): await fetch(key) twice and return the two results as a list. Preserve the order of results and propagate an exception from the dependency.