How to configure event loop factories from the test item

pytest_asyncio_loop_factories is called with the current pytest item. Use that item to decide which named event loop factories are available for the test being collected.

For example, a hook can inspect the test’s fixtures and return a different factory mapping for tests that request a particular fixture. In conftest.py, check the current item’s fixture names and build the factory mapping for that item:

import asyncio

import pytest


class CustomEventLoop(asyncio.SelectorEventLoop):
    pass


@pytest.fixture
def requires_custom_loop():
    pass


def pytest_asyncio_loop_factories(config, item):
    if "requires_custom_loop" in item.fixturenames:
        return {"custom": CustomEventLoop}
    return {"default": asyncio.new_event_loop}

Then request the fixture from tests that should use the custom factory:

import pytest


@pytest.mark.asyncio
async def test_runs_with_default_factory_only():
    pass


@pytest.mark.asyncio
async def test_runs_with_custom_factory_only(requires_custom_loop):
    pass

In this example, test_runs_with_default_factory_only is parametrized only over default, while test_runs_with_custom_factory_only is parametrized only over custom.

The same pattern works with any information available from the current pytest item, such as fixture names, markers, node IDs, or file paths.

Because this is a standard pytest hook, its placement also matters. An implementation in a nested conftest.py applies to tests collected under that directory. Use this when a whole package or directory should share the same factory set.

For declaring factories without item-specific logic, see How to use custom event loop factories for tests.

For selecting a subset of available factories from a test, see How to run a test with specific event loop factories only.