What I want to achieve is basically this but with a class scoped, parametrized fixture.
The problem is that if I import the methods (generate_fixture and inject_fixture
) from a helper file the inject fixture code seems to be getting called too late. Here is a complete, working code sample:
# all of the code in one file
import pytest
import pytest_check as check
def generate_fixture(params):
@pytest.fixture(scope='class', params=params)
def my_fixture(request, session):
request.cls.param = request.param
print(params)
return my_fixture
def inject_fixture(name, someparam):
globals()[name] = generate_fixture(someparam)
inject_fixture('myFixture', 'cheese')
@pytest.mark.usefixtures('myFixture')
class TestParkingInRadius:
def test_custom_fixture(self):
check.equal(True, self.param, 'Sandwhich')
If I move the generate and inject helpers into their own file (without changing them at all) I get a fixture not found error i.e. if the test file looks like this instead:
import pytest
import pytest_check as check
from .helpers import inject_fixture
inject_fixture('myFixture', 'cheese')
@pytest.mark.usefixtures('myFixture')
class TestParkingInRadius:
def test_custom_fixture(self):
check.equal(True, self.param, 'Sandwhich')
The I get an error at setup: E fixture 'myFixture' not found
followed by a list of available fixtures (which doesn't include the injected fixture).
Could someone help explain why this is happening? Having to define those functions in every single test file sort of defeats the whole point of doing this (keeping things DRY).