2

I want to pass a pytest.fixture function to another fixture function's param argument. Something like this:

@pytest.fixture()
def foo():
    return "foo"

@pytest.fixture()
def boo(foo):
    return foo + "boo"

@pytest.fixture()
def bar(foo):
    return foo + "bar"

@pytest.fixture(params=[boo, bar], ids=["boo_fixture", "bar_fixture"])
def final_fixture(request):
    return request.param

def _test(final_fixture):
    assert final_fixture.startswith('foo')

The request.param in final_fixture returns the function object for that param, instead of the return value of the fixtures(boo and bar)

<function boo at 0x7f2bfceg41f0>
<function bar at 0x7f2bfceg41f1>

So, how can I make the final_fixture function return the actual return values for each fixture param?

zean_7
  • 336
  • 3
  • 12
  • 1
    What you are trying to do is not possible: See https://github.com/pytest-dev/pytest/issues/349 and https://stackoverflow.com/a/47035775/9978789 and https://docs.pytest.org/en/6.2.x/proposals/parametrize_with_fixtures.html – dosas May 04 '21 at 10:56
  • @PhilippSelenium I have found a solution for this below. Thanks for linking the pytest issue. There was a mention of a similar approach there as well. :) – zean_7 May 04 '21 at 12:16

1 Answers1

0

I found a solution that worked for me, thanks to this answer by Will.

It seems like you can just use request.getfixturevalue to get the return value of the fixture instead of the function object. Here is the working code for this:

@pytest.fixture()
def foo():
    return "foo"

@pytest.fixture()
def boo(foo):
    return foo + "boo"

@pytest.fixture()
def bar(foo):
    return foo + "bar"

@pytest.fixture(params=['boo', 'bar'], ids=["boo_fixture", "bar_fixture"])
def final_fixture(request):
    return request.getfixturevalue(request.param)

def _test(final_fixture):
    assert final_fixture.startswith('foo')

Here is the related doc: http://doc.pytest.org/en/latest/builtin.html#_pytest.fixtures.FixtureRequest.getfixturevalue

zean_7
  • 336
  • 3
  • 12
  • So we should probably close this question as duplicate – dosas May 04 '21 at 12:36
  • I am not sure if that's the right thing to do here. Atleast the question isn't duplicate, the other one talked about passing fixtures to `parametrize`, this is for passing fixtures to `fixture`. I agree that the answer could be very similar since its borrowed from there. Besides, it took me a lot of searches to find that question, since the keywords were not matching initially. :) – zean_7 May 05 '21 at 07:13