MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Python Test Runners – pytest-trio

pytest-trio is a pytest plugin that runs async def tests and fixtures inside a Trio event loop, so you can test Trio code without calling trio.run() yourself. This page explains the example above, fixes its weak points (no assertions, an unneeded nursery, a likely import error and a real one-second sleep), and covers trio mode, async fixtures, the built-in nursery and autojump_clock fixtures, exception groups and common errors.


What pytest-trio does

pytest cannot run coroutine functions by itself. If it finds an async def test and no plugin claims it, the test does not run. pytest-trio claims tests marked with @pytest.mark.trio (or every async test, if trio mode is on). It starts a Trio run, sets up any async fixtures inside it, awaits the test and then tears everything down in the same run.

So the test body is already running inside Trio's event loop. You never call trio.run() in a test, and you don't need a nursery just to call an async function. await it directly.

  • @pytest.mark.trio runs one async test under Trio.
  • trio_mode = true in the pytest config runs every async test and fixture under Trio, with no markers needed.
  • The nursery fixture gives a test a nursery for background tasks. Those tasks are cancelled when the test ends.
  • The mock_clock and autojump_clock fixtures replace real time with a virtual clock, so tests that sleep or use timeouts finish almost instantly.

Corrected and runnable version of the example

The gist above puts three files into one text file. Its test also has no assertion, so it only proves that nothing raised an exception. Here is the same idea as a real project layout:

project/
โ”œโ”€โ”€ my_module.py
โ”œโ”€โ”€ pyproject.toml
โ””โ”€โ”€ tests/
    โ””โ”€โ”€ test_trio_code.py

my_module.py now returns a result, which gives the test something to check:

import trio


async def trio_async_task(results: list, value: int) -> None:
    await trio.sleep(1)  # simulate I/O
    results.append(value)


async def trio_async_operation(count: int = 3) -> list:
    results = []
    async with trio.open_nursery() as nursery:
        for i in range(count):
            nursery.start_soon(trio_async_task, results, i)
    # the nursery block exits only after every child task has finished
    return sorted(results)Code language: PHP (php)

tests/test_trio_code.py awaits the function directly and checks the result:

import pytest
import trio

from my_module import trio_async_operation


@pytest.mark.trio
async def test_returns_all_results():
    assert await trio_async_operation(3) == [0, 1, 2]


@pytest.mark.trio
async def test_tasks_run_concurrently(autojump_clock):
    start = trio.current_time()
    await trio_async_operation(5)
    # five 1-second sleeps that run concurrently take about 1 virtual second
    assert trio.current_time() - start == pytest.approx(1)Code language: CSS (css)

pyproject.toml puts the project root on sys.path, which lets from my_module import ... work when pytest collects files under tests/:

[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]Code language: JavaScript (javascript)
pip install pytest pytest-trio
pytest -v
tests/test_trio_code.py::test_returns_all_results PASSED
tests/test_trio_code.py::test_tasks_run_concurrently PASSED

============ 2 passed in ...s ============Code language: PHP (php)

The first test takes about one real second because it really sleeps. The second test uses autojump_clock, so it finishes almost instantly even though the code sleeps.

Trio mode: drop the markers

If a project uses only Trio, turn on trio mode. pytest-trio then handles every async def test and fixture, and you can remove @pytest.mark.trio.

[tool.pytest.ini_options]
trio_mode = true
pythonpath = ["."]Code language: JavaScript (javascript)
# pytest.ini equivalent
[pytest]
trio_mode = true
pythonpath = .Code language: PHP (php)

Note: Don't enable trio mode alongside pytest-asyncio in auto mode. Both plugins will try to claim the same async tests. If both plugins must be installed, keep pytest-asyncio in strict mode and use explicit markers.

Async fixtures and the nursery fixture

With pytest-trio, fixtures can be async def, including async generator fixtures that use yield for teardown. They run in the same Trio run as the test. The built-in nursery fixture is the right place to start background services that a test needs:

import pytest
import trio


@pytest.fixture
async def upper_service(nursery):
    send_in, recv_in = trio.open_memory_channel(0)
    send_out, recv_out = trio.open_memory_channel(0)

    async def worker():
        async for msg in recv_in:
            await send_out.send(msg.upper())

    nursery.start_soon(worker)  # cancelled automatically after the test
    return send_in, recv_out


@pytest.mark.trio
async def test_upper_service(upper_service):
    send_in, recv_out = upper_service
    await send_in.send("hello")
    assert await recv_out.receive() == "HELLO"Code language: PHP (php)

If an async fixture needs cleanup, write it as async def with yield and put the cleanup code after the yield, for example closing a client or a channel. Async fixtures work only for tests that pytest-trio runs. A plain synchronous test cannot use them.

Testing timeouts and exceptions

Use trio.fail_after() to stop a test that might hang. Pair it with autojump_clock so the timeout costs no real time:

@pytest.mark.trio
async def test_slow_call_times_out(autojump_clock):
    with pytest.raises(trio.TooSlowError):
        with trio.fail_after(5):
            await trio.sleep(60)Code language: JavaScript (javascript)

Current Trio versions use strict exception groups by default. If a task inside a nursery raises, the error comes out of the nursery wrapped in an ExceptionGroup, so a plain pytest.raises(ValueError) will not match. Catch the group and check what it contains:

async def failing_operation():
    async def boom():
        raise ValueError("bad input")
    async with trio.open_nursery() as nursery:
        nursery.start_soon(boom)


@pytest.mark.trio
async def test_failure_is_reported():
    with pytest.raises(ExceptionGroup) as excinfo:
        await failing_operation()
    assert excinfo.group_contains(ValueError, match="bad input")Code language: JavaScript (javascript)

Note: ExceptionGroup is built into Python 3.11 and later. On older Python versions, import it from the exceptiongroup backport package.

Common errors and fixes

SymptomCauseFix
"async def functions are not natively supported" and the test is skipped or failsNo plugin claimed the testInstall pytest-trio and add @pytest.mark.trio, or set trio_mode = true
ModuleNotFoundError: No module named 'my_module'The project root is not on sys.path when tests live in tests/Add pythonpath = ["."] to the pytest config, or run python -m pytest from the project root
Test expects ValueError but gets ExceptionGroupTrio wraps errors raised by nursery childrenUse pytest.raises(ExceptionGroup) with excinfo.group_contains(...)
The suite is slow because of trio.sleep callsReal time is passingRequest the autojump_clock fixture
The test hangs foreverIt awaits something that never happens, such as a channel with no senderWrap the code in trio.fail_after(...)
Async tests behave oddly when pytest-asyncio is also installedBoth plugins are claiming async testsUse pytest-asyncio strict mode, or uninstall the plugin you don't need

Best practices

  • Assert on return values or side effects. A test that only awaits a function catches crashes and nothing else.
  • Await the code under test directly. Add a nursery only when the test itself must run tasks concurrently, and prefer the nursery fixture for background services.
  • Use autojump_clock for any code that sleeps, retries or times out. It keeps tests fast and deterministic.
  • Turn on trio_mode in Trio-only projects so you don't forget a marker.
  • Pin pytest, pytest-trio and trio in your dev requirements. Exception group behaviour and plugin hooks have changed between releases.
  • If your library supports both asyncio and Trio through AnyIO, consider AnyIO's own pytest plugin (@pytest.mark.anyio), which can run the same test on both backends.

For more Python testing and scripting guides, see the Python tutorials category.

Frequently asked questions

What is the difference between pytest-trio and pytest-asyncio?

pytest-trio runs async tests under the Trio event loop. pytest-asyncio runs them under asyncio. Choose the plugin that matches the library your code uses, because Trio code cannot run on the asyncio loop.

Do I need @pytest.mark.trio on every test?

Only if trio mode is off. Set trio_mode = true in pytest.ini or under [tool.pytest.ini_options] in pyproject.toml, and every async test and fixture runs under Trio without a marker.

Does pytest-trio support async fixtures?

Yes. Fixtures can be async def, and async generator fixtures can use yield for teardown. They run in the same Trio run as the test, and only tests that pytest-trio runs can use them.

How do I make Trio tests with sleeps run fast?

Request the autojump_clock fixture. It installs a virtual clock that skips ahead whenever all tasks are waiting, so trio.sleep(60) finishes almost instantly.

Should I call trio.run() inside a pytest-trio test?

No. pytest-trio already runs the test inside Trio. Calling trio.run() from inside a running Trio loop raises an error. Just await the code you are testing.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Python Test Runners – multiprocessing-testrunner

Python tests can run in several processes at once so that a suite of slow, independent tests finishes faster on a multi-core machine. This page explains the…

Read More

Python Test Runners – gevent-testrunner

This page shows how to run Python unittest tests concurrently with gevent greenlets, so that I/O-bound tests overlap instead of running one after another. Below the original…

Read More

Python Test Runners – Pytest-xdist

pytest-xdist is a pytest plugin that splits a test suite across several worker processes so the tests run in parallel, and the -n option sets how many…

Read More

Python Test Runners – unittest-parallel

unittest-parallel is a third-party runner that discovers standard Python unittest tests and runs them across several worker processes, so a slow suite finishes in less wall-clock time…

Read More

Python Test Runners – pytest -n

pytest -n runs your test suite in parallel across several worker processes. The -n option is not part of pytest itself; it comes from the pytest-xdist plugin….

Read More

Python Test Runners – Pytest-asyncio

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…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x