pytest-asyncio is a pytest plugin that runs async def test functions and async fixtures inside an asyncio event loop, so you can await coroutines directly in your tests. The example above shows the minimal pattern. This page adds a project layout that imports correctly, the expected output, strict vs auto mode, async fixtures, mocking, event loop scope and fixes for the most common errors.
Why pytest needs a plugin for async tests
Calling an async def function does not run it. The call returns a coroutine object, and something has to drive it on an event loop. Pytest on its own does not do that. Without a plugin, an async test is either skipped with a warning or reported as a failure, depending on your pytest version, with a message saying that async def functions are not natively supported. In both cases your assertions never run.
pytest-asyncio provides the event loop. When a test carries the @pytest.mark.asyncio marker, or auto mode is on, the plugin runs the coroutine to completion on a loop it manages. Anything raised inside the coroutine, including a failed assert, is reported like a normal test failure.
A project layout that imports correctly
The example above puts my_module.py in the project root and the test in tests/. If you then run a bare pytest, the import often fails with ModuleNotFoundError: No module named 'my_module'. Pytest's default import mode adds the test file's own directory (tests/) to sys.path, not the project root. The cleanest fix is to tell pytest where your code lives.
project/
โโโ my_module.py
โโโ pyproject.toml
โโโ tests/
โโโ test_async_code.py
# pyproject.toml
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
asyncio_mode = "strict"
asyncio_default_fixture_loop_scope = "function"Code language: PHP (php)
pythonpathadds the project root tosys.path, sofrom my_module import async_operationworks no matter where pytest is started.testpathslimits test collection totests/.asyncio_mode = "strict"makes the default mode explicit (see the next sections).asyncio_default_fixture_loop_scopesets the event loop scope for async fixtures. Recent plugin versions print a deprecation warning when this option is not set.
Another option is to run python -m pytest, which also adds the current directory to sys.path. For larger projects, a src/ layout installed with pip install -e . is more robust.
Setting up and running the example
- Create and activate a virtual environment:
python3 -m venv .venv && source .venv/bin/activate. - Install the tools:
pip install pytest pytest-asyncio. - Create
my_module.pyandtests/test_async_code.pyfrom the example above, plus thepyproject.tomlshown earlier. - Run the tests from the project root:
pytest -v.
The output should look roughly like this. Version numbers and the exact header lines depend on what you installed:
============================= test session starts ==============================
platform linux -- Python 3.12.x, pytest-8.x.x, pluggy-1.x.x
rootdir: /home/user/project
configfile: pyproject.toml
testpaths: tests
plugins: asyncio-x.y.z
collected 1 item
tests/test_async_code.py::test_async_operation PASSED [100%]
============================== 1 passed in 1.02s ===============================Code language: JavaScript (javascript)
Note: The test takes about one second because async_operation really sleeps for one second. Across hundreds of tests, real sleeps add up quickly. Mock slow I/O or use very short delays in tests, as shown below.
Strict mode vs auto mode
pytest-asyncio has two modes, set with asyncio_mode in your configuration or with --asyncio-mode on the command line.
| Strict mode (default) | Auto mode | |
|---|---|---|
| Async tests | Need @pytest.mark.asyncio | Every async def test runs automatically |
| Async fixtures | Need @pytest_asyncio.fixture | A plain @pytest.fixture works |
| Works alongside other async plugins (for example anyio, trio) | Yes | Can conflict, because it claims every coroutine |
| Best for | Libraries and mixed codebases | Projects that use only asyncio |
# Auto mode: no marker needed
# pyproject.toml -> asyncio_mode = "auto"
from my_module import async_operation
async def test_async_operation():
assert await async_operation() == "Async operation completed"Code language: PHP (php)
To mark every test in a module without switching modes, set a module-level marker: pytestmark = pytest.mark.asyncio.
Async fixtures for setup and teardown
Real tests often need async setup, such as opening a client session, a database connection or a queue. In strict mode, declare these fixtures with pytest_asyncio.fixture. Code before yield is setup and code after it is teardown. Teardown still runs if the test fails.
# tests/test_queue.py
import asyncio
import pytest
import pytest_asyncio
@pytest_asyncio.fixture
async def job_queue():
queue = asyncio.Queue()
await queue.put("job-1")
yield queue
# Teardown: drain anything the test left behind
while not queue.empty():
queue.get_nowait()
@pytest.mark.asyncio
async def test_consume_job(job_queue):
job = await job_queue.get()
assert job == "job-1"
assert job_queue.empty()Code language: PHP (php)
Note: If you decorate an async fixture with plain @pytest.fixture in strict mode, the test receives a coroutine or async generator object instead of the value. Assertions then fail in confusing ways. Recent pytest versions also warn about this.
Testing exceptions, timeouts, concurrency and mocks
The patterns below cover most real async code. pytest.raises works around await just as it does around normal calls. unittest.mock.AsyncMock (standard library, Python 3.8+) builds awaitable fakes, so a test can replace a slow network call without any real waiting.
# tests/test_patterns.py
import asyncio
from unittest.mock import AsyncMock, patch
import pytest
import my_module
@pytest.mark.asyncio
async def test_timeout_is_raised():
# async_operation sleeps 1s, so a 0.1s timeout must fire
with pytest.raises(asyncio.TimeoutError):
await asyncio.wait_for(my_module.async_operation(), timeout=0.1)
@pytest.mark.asyncio
async def test_runs_concurrently():
loop = asyncio.get_running_loop()
start = loop.time()
results = await asyncio.gather(*(my_module.async_operation() for _ in range(3)))
elapsed = loop.time() - start
assert results == ["Async operation completed"] * 3
assert elapsed < 2 # three 1s sleeps overlap instead of taking 3s
@pytest.mark.asyncio
async def test_sleep_is_mocked():
with patch("my_module.asyncio.sleep", new=AsyncMock()) as fake_sleep:
result = await my_module.async_operation()
assert result == "Async operation completed"
fake_sleep.assert_awaited_once_with(1)Code language: PHP (php)
asyncio.get_running_loop()is the correct way to reach the current loop from inside a coroutine. Avoid the deprecated pattern of callingasyncio.get_event_loop()in tests.- Patch the name where it is looked up (
my_module.asyncio.sleep), not where it is defined. assert_awaited_once_withchecks that the coroutine was actually awaited. A plainassert_calledonly checks that it was called.
Event loop scope and the removed event_loop fixture
By default, each test gets a fresh event loop. Tests stay isolated that way, but you cannot share an async resource, such as a connection pool, across tests. To share one, widen the loop scope of both the fixture and the tests that use it:
import pytest
import pytest_asyncio
@pytest_asyncio.fixture(loop_scope="module", scope="module")
async def shared_resource():
resource = {"connections": 0}
yield resource
@pytest.mark.asyncio(loop_scope="module")
async def test_one(shared_resource):
shared_resource["connections"] += 1
assert shared_resource["connections"] == 1Code language: JavaScript (javascript)
Older tutorials override a custom event_loop fixture to get a module-scoped or session-scoped loop. That approach was deprecated and then removed in recent pytest-asyncio releases. Use the loop_scope argument shown above instead. If you upgrade the plugin and see errors about event_loop, this is usually why.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
| Message that async def functions are not natively supported, with the test skipped or failed | pytest-asyncio is not installed in the active environment, or the marker is missing in strict mode | Run pip install pytest-asyncio in the same venv as pytest. Add @pytest.mark.asyncio or use auto mode |
ModuleNotFoundError: No module named 'my_module' | The project root is not on sys.path | Set pythonpath = ["."] or run python -m pytest |
Test receives a coroutine or async_generator object | Async fixture declared with @pytest.fixture in strict mode | Use @pytest_asyncio.fixture |
RuntimeError: ... attached to a different loop | A resource created on one event loop is used on another | Give the fixture and its tests the same loop_scope |
Deprecation warning about asyncio_default_fixture_loop_scope | The option is unset | Add it to your pytest configuration |
| Test suite is slow | Real sleep calls or real network I/O | Mock them with AsyncMock |
Note: Pin pytest and pytest-asyncio versions in your requirements file or lock file. Behaviour around modes and loop scope has changed between plugin releases, and pinning keeps CI results reproducible.
Frequently asked questions
Do I need @pytest.mark.asyncio on every async test?
Only in strict mode, which is the default. Set asyncio_mode = "auto" to run every async def test automatically, or add pytestmark = pytest.mark.asyncio at the top of a module to mark all of its tests.
What is the difference between pytest.fixture and pytest_asyncio.fixture?
pytest_asyncio.fixture tells the plugin to run an async fixture on its event loop and pass the resulting value to the test. In strict mode, a plain pytest.fixture on an async function hands the test an unawaited coroutine instead.
Can I use pytest-asyncio with Python's unittest.IsolatedAsyncioTestCase?
You do not need to. Pytest can already run IsolatedAsyncioTestCase classes because they manage their own loop. pytest-asyncio is for plain pytest-style async def test functions and fixtures.
Why was the event_loop fixture removed?
Overriding event_loop was an error-prone way to control loop lifetime, and it clashed with newer asyncio APIs. Recent pytest-asyncio releases replace it with the loop_scope argument on the marker and on pytest_asyncio.fixture.
How do I test async code without waiting for real delays?
Replace the slow call with unittest.mock.AsyncMock using patch, then check it with assert_awaited_once_with. The test then runs in milliseconds and still checks the logic.
Related tutorials
- More Python tutorials
- TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-
- Top 50 Python Interview Questions and Answers
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals