Lets say I have two tests that basically do the same thing, however, I'd like to use a fixture for one of them.
I was thinking that this should work, but it doesn't
@fixture
bar_fixture():
do_something_but_Return_no_value()
@mark.parametrize(
"foo",
[
param(
True,
marks=[mark.test_1],
),
param(
False,
marks=[mark.test_2, mark.usefixtures("bar_fixture")],
),
],
)
def test_foo(foo):
func(foo)
Does anyone know how to do this? Of course, this can be done with two separate tests, but I was wondering if something like this could be done in order not to write basically the same code twice.
mark.usefixtures only seems to work on tests directly, not within other fixtures, which is I assume part of whats going on here.
For this case, you could fall back to request.getfixturevalue
Dynamically run a named fixture function. Declaring fixtures via function argument is recommended where possible. But if you can only decide whether to use another fixture at test setup time, you may use this function to retrieve it inside a fixture or test function body.
@pytest.fixture
def bar_fixture():
do_something_but_Return_no_value()
@pytest.mark.parametrize(
["foo", "fixtures"],
[
pytest.param(
True, [], marks=[pytest.mark.test_1],
),
pytest.param(
False, ["bar_fixture"], marks=[pytest.mark.test_2]
),
],
)
def test_foo(request, foo, fixtures):
for fixture in fixtures:
request.getfixturevalue(fixture)
func(foo)
This obviously isn't as elegant as other options, but its easy enough to follow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With