pytest-asycnio file is marked to be run in an event loop with scope class, but is not part of any class

172 Views Asked by At

I'm trying to upgrade my the pytest-asyncio version from 0.21.0 to 0.23.2. I also tried to update to 0.22.0 without an issue.

When using pytest-asyncio==0.23.2 I get the following errors for all of my test cases.

ERROR tests/e2e/test_file.py - _pytest.config.exceptions.UsageError: test_file.py is marked to be run in an event loop with scope class, but is not part of any class.

I also attach my conftest.py

import os


def pytest_generate_tests(metafunc):
    idlist = []
    argvalues = []
    if hasattr(metafunc.cls, "parametrize_scenarios"):
        for scenario in metafunc.cls.parametrize_scenarios:
            idlist.append(scenario[0])
            items = scenario[1].items()
            argnames = [x[0] for x in items]
            argvalues.append([x[1] for x in items])
        metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")


def _get_static_folder():
    """Private method for retrieving the path of the static folder."""
    current_path = os.path.dirname(os.path.realpath(__file__))
    return os.path.join(current_path, "static")


# init os.environ['CONFIG_PATH']
os.environ["CONFIG_PATH"] = os.path.join(_get_static_folder(), "tests_config.yaml")


# LOAD FIXTURES

# LOAD MOCKS
from tests.utils.examples import *
...

And this is how I've constructed my test_file.py

import pytest
from fastapi.encoders import jsonable_encoder
from httpx import AsyncClient

from tests.utils.projects import PostProjectPayloadFactory
from tests.utils.users import CURRENT_USER


@pytest.fixture(scope="class")
def test_projects_state(request):
    """Simple fixture to store tests' state in a class."""

    class TestProjectTest(object):
        def __init__(self):
            self.project = None

    # make it available directly in the class
    request.cls.state = TestProjectTest()


@pytest.mark.usefixtures(
    "cli",
    "test_projects_state",
    "logged_user",
    "reset_examples",
)
@pytest.mark.random_order(disabled=True)
class TestExamples(object):

    async def test_1_post_project(
        self, some_code: some_type, cli: AsyncClient
    ):
        foo code

Any chance we know how this issue is coming up. Tried to check on the exception directly but no luck.

1

There are 1 best solutions below

1
Bart On

I dont think that the conftest.py and test_file.py that you shared provide enough information to give you to a solution -- it is not clear to me where the event_loop is used and which fixtures depend on it. Regardless, I think it is worthwhile to point out the following two points:

  1. pytest-asyncio==0.23 completely changes the way that the event_loop is scopes and how users can change that. The corresponding and significantly extended documentation provides some examples on how to use custom-scoped event loops in your tests.
  2. Although perfectly valid in semantic versioning (feature/ minor releases starting with v0.x can be breaking), v0.23 is unintentionally a breaking release. It seems that the author underestimated the impact of the changes with respect to custom scopes and particularly the interaction thereof with async fixtures. The author is actively involved in the discussions on how to follow-up. It might be wise to delay upgrading for a while and keep an eye on the ongoing discussions (#706, search 0.23).

Hope this is helps for now.