Is it possible to parameterize a fixture, which is used as a parameter in another fixture? I want to define a parent fixture, and have several variant fixtures which inherit from this parent fixture.
@pytest.fixture
def fixtureA(request):
value = '1'
if hasattr(request, 'param'):
data = request.param
if data.get('id'):
value = data.get('id')
return value
@pytest.fixture
@pytest.mark.parametrize("fixtureA", [{'id': '2'}], indirect=True)
def fixtureB(fixture_A):
return fixtureA
def test_case(fixtureB):
value = fixtureB
assert value == '2'
From the example, fixtureB inherits fixtureA, and I want to be able to return the value of '2' while calling fixtureB in the testcase. When running the testcase, it is still returning the default value of '1'
Is it possible to parameterize a fixture, which is used as a parameter in another fixture? I want to define a parent fixture, and have several variant fixtures which inherit from this parent fixture.
@pytest.fixture
def fixtureA(request):
value = '1'
if hasattr(request, 'param'):
data = request.param
if data.get('id'):
value = data.get('id')
return value
@pytest.fixture
@pytest.mark.parametrize("fixtureA", [{'id': '2'}], indirect=True)
def fixtureB(fixture_A):
return fixtureA
def test_case(fixtureB):
value = fixtureB
assert value == '2'
From the example, fixtureB inherits fixtureA, and I want to be able to return the value of '2' while calling fixtureB in the testcase. When running the testcase, it is still returning the default value of '1'
Share Improve this question asked Nov 20, 2024 at 4:31 GeeGee 112 bronze badges1 Answer
Reset to default 0According to the pytest
documentation about parametrization (1, 2, and 3), @pytest.mark.parametrize
can only be used on test functions (or classes). Not on fixtures.
When you run your example, parametrization of fixtureB
is ignored, and fixtureA
is called without param
(a simple pytest.set_trace()
inside fixtureA
can show you that).
You can set parameters on fixtures, but with the following syntax :
@pytest.fixture(params=["1", "2"])
def myfixture(request):
return request.param
But that, of course, does not allow you to perform indirect parametrization.
You could move your parametrize
to the test function, and call fixtureA
in your test even if you don’t use its value directly.
import pytest
@pytest.fixture
def fixtureA(request):
value = "1"
if hasattr(request, "param"):
data = request.param
if data.get("id"):
value = data.get("id")
return value
@pytest.fixture
def fixtureB(fixtureA):
return fixtureA
@pytest.mark.parametrize("fixtureA", [{"id": "2"}], indirect=True)
def test_case(fixtureB, fixtureA):
value = fixtureB
assert value == "2"
That way, fixtureA
has a param
and is returning the correct value, even when called from fixtureB
(because a fixture can only have a single result for the whole test scope).