Jake Trent

Mark All Tests as Async in pytest

To run an async test in pytest, it must be marked. It can be a pain to mark them all individually. Here’s how to mark them all async at once.

Asynchronous tests

You’d need an asynchronous test for asynchronous code under test. For instance, Quart is an app server where all the endpoints are asynchronous. If you were testing that Quart app, you might create a test like:

from quart import Quart
async def test_thing():
    client = Quart("appname", static_folder=None).test_client()
    response = await client.get("/api/thing")
    assert response.status_code == 200

When running pytest, the use of async and await keywords will fail, reporting that a plugin is needed.

Plugin

The plugin that enables async testing in pytest is pytest-asyncio. To install:

poetry add pytest-asyncio

Or instead of poetry, use the package manager of your choice.

Mark individually

Now you’d be able to mark a test individually. In your test file, write:

import pytest

@pytest.mark.asyncio
async def test_1():
    # ...

@pytest.mark.asyncio
async def test_2():
    # ...

Mark all tests async

But if you have many tests in a single module, this can be annoying to repeat the decorator. To mark all tests in the module async, you mark a special module-global variable called pytestmark. At the top of your test file add:

import pytest

pytestmark = pytest.mark.asyncio

Now you have no more need to decorate every test function.