Pytest Asyncio Test Not Running Fix
In this tutorial, you'll learn about Pytest Asyncio Test Not Running Fix. We cover key concepts, practical examples, and best practices.
Your async test passes a coroutine object instead of running it — RuntimeWarning: coroutine was never awaited — pytest doesn't know how to handle async def test functions without the asyncio plugin.
The Problem
# WRONG — async test without the asyncio plugin
import pytest
async def test_fetch_user():
user = await fetch_user(1)
assert user.name == "Alice"
RuntimeWarning: coroutine 'test_fetch_user' was never awaited
pytest treats async def as a regular function returning a coroutine object. It never awaits it, so the test body never executes.
Step-by-Step Fix
1. Install and enable pytest-asyncio
pip install pytest-asyncio
2. Mark async tests
import pytest
@pytest.mark.asyncio
async def test_fetch_user():
user = await fetch_user(1)
assert user.name == "Alice"
3. Use the asyncio_mode flag
# pyproject.toml
[tool.pytest.ini_options]
asyncio_mode = "auto"
Or:
# pytest.ini
[pytest]
asyncio_mode = auto
With asyncio_mode = auto, every async def test automatically uses the asyncio event loop without the @pytest.mark.asyncio decorator.
4. Share fixtures between async and sync tests
import pytest
@pytest.fixture
def db():
return create_test_db()
@pytest.fixture
async def async_db():
db = await create_async_test_db()
yield db
await db.close()
@pytest.mark.asyncio
async def test_async_query(async_db):
result = await async_db.query("SELECT 1")
assert result == 1
5. Use different event loop scopes
# conftest.py
import pytest
@pytest.fixture(scope="session")
def event_loop():
import asyncio
loop = asyncio.new_event_loop()
yield loop
loop.close()
Expected output:
collected 2 items
test_async.py::test_fetch_user PASSED
test_async.py::test_async_query PASSED
Prevention Tips
- Install
pytest-asynciofrom the start - Set
asyncio_mode = autoinpytest.inifor all-async projects - Mark individual tests with
@pytest.mark.asynciofor mixed projects - Use async fixtures with
async def+@pytest.fixture - Scope the event loop to
sessionfor faster test suites
Common Mistakes with asyncio error
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world PYTEST code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro