With pytest, I can define a fixture like so:
@pytest.fixture
def foo():
return "blah"
And use it in a test like so:
def test_blah(foo):
assert foo == "blah"
That's all very well. But what I want to do is define a single fixture function that "expands" to provide multiple arguments to a test function. Something like this:
@pytest.multifixture("foo,bar")
def foobar():
return "blah", "whatever"
def test_stuff(foo, bar):
assert foo == "blah" and bar == "whatever"
I want to define the two objects foo
and bar
together (not as separate fixtures) because they are related in some fashion. I may sometimes also want to define a fixture that depends on another fixture, but have the second fixture incorporate the result of the first and return it along with its own addition:
@pytest.fixture
def foo():
return "blah"
@pytest.multifixture("foo,bar")
def foobar():
f = foo()
return f, some_info_related_to(f)
This example may seem silly, but in some cases foo
is something like a Request object, and the bar
object needs to be linked to that same request object. (That is, I can't define foo
and bar
as independent fixtures because I need both to be derived from a single request.)
In essence, what I want to do is decouple the name of the fixture function from the name of the test-function argument, so that I can define a fixture which is "triggered" by a particular set of argument names in a test function signature, not just a single argument whose name is the same as that of the fixture function.
Of course, I can always just return a tuple as the result of the fixture and then unpack it myself inside the test function. But given that pytest provides various magical tricks for automatically matching names to arguments, it seems like it's not unthinkable that it could magically handle this as well. Is such a thing possible with pytest?
You can now do this using pytest-cases:
from pytest_cases import fixture
@fixture(unpack_into="foo,bar")
def foobar():
return "blah", "whatever"
def test_stuff(foo, bar):
assert foo == "blah" and bar == "whatever"
See the documentation for more details (I'm the author by the way)
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