ScopeMismatch when i try to make setup_teardown pytest function
My goal is to create a fixture that will run once at the beginning of the class function test and initialize the attributes I need in self. To do this, I created a fixture with the scope of the class and applied it directly to the class. To solve the compatibility problem of pytest with asynchronous code, pytest-asyncio was used.
My minimally reproducible example:
import pytest
@pytest.fixture(scope="class")
async def setup_teardown(request):
request.cls.test_number = '123'
yield
# ...
@pytest.mark.asyncio
@pytest.mark.usefixtures("setup_teardown")
class Test_BaseFunctional():
async def test_my_number(self):
assert self.test_number == '123'
But i'm receiving:
ScopeMismatch: You tried to access the function scoped fixture event_loop with a class scoped request object, involved factories:
tests/issue.py:4: def setup_teardown(request)
I tried many ways, from time to time I got a large-scale non-working code, and in the end I returned to this minimal example.
Pytest-asyncio internally uses a pytest fixture to control the lifetime of the asyncio event loop. It is implicitly requested by each async def fixture and test function. This fixture is called event_loop as seen in your error message. By default, the fixture has function scope, in order to isolate tests from each other.
It is possible to widen the scope by overriding the fixture (see the docs). In your example, the event_loop fixture scope needs to be class or wider, because it is implicitly requested by setup_teardown, which is a class-scoped fixture.
Adding an import asyncio and the following fixture redefinition to your code fixes the example:
@pytest.fixture(scope="class")
def event_loop():
policy = asyncio.get_event_loop_policy()
loop = policy.new_event_loop()
yield loop
loop.close()
If you still encounter problems, just reopen the issue.