Search RU
Tasks / pytest / Async tests, timeout, and cancellation
Statement medium

Async tests, timeout, and cancellation

`fetch_json(fetch, *, timeout=0.5)` is an async request with a time limit.

`fetch` is a function with no arguments that returns an awaitable.

Rules:

- a successful awaitable is returned as is;
- if the awaitable does not finish within `timeout` seconds — `FetchTimeout`;
- on timeout the inner coroutine **is cancelled**, and its `finally` still runs;
- an outer cancellation (`task.cancel()`) does not turn into `FetchTimeout`:
`CancelledError` propagates;
- any other exception from `fetch` propagates unchanged;
- `timeout <= 0` — `ValueError`.

Run tests through `asyncio.run` inside ordinary synchronous functions: the
`pytest-asyncio` plugin is not installed in the environment. Every `asyncio.run`
creates its own event loop, so tests must not rely on a shared loop or global
state.

Write tests for: success, timeout, cancellation of the inner coroutine, outer
cancellation, exception propagation, isolation between two runs, and an invalid
`timeout`.

pytestasynciotimeoutcancellation
test_solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

What is the difference between cancelling a task and a timeout, if both arrive
as an exception inside `await`?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts