Define A Pytest Fixture Providing Multiple Arguments To Test Function
Solution 1:
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)
Solution 2:
note: this solution not working if your fixture depends on another fixtures with parameters
Don't really know if there are any default solution in pytest package, but you can make a custom one:
import pytest
from _pytest.mark import MarkInfo
def pytest_generate_tests(metafunc):
test_func = metafunc.function
if 'use_multifixture' in [name for name, ob in vars(test_func).items() if isinstance(ob, MarkInfo)]:
result, func = test_func.use_multifixture.args
params_names = result.split(',')
params_values = list(func())
metafunc.parametrize(params_names, [params_values])
def foobar():
return "blah", "whatever"
@pytest.mark.use_multifixture("foo,bar", foobar)
def test_stuff(foo, bar):
assert foo == "blah" and bar == "whatever"
def test_stuff2():
assert 'blah' == "blah"
So we defined pytest_generate_tests metafunction. This function
- checks if multifixture mark is on the test
if the mark is on - it takes variables names "foo,bar" and fucntion foobar that will be executed on generation
@pytest.mark.multifixture("foo,bar", foobar)
Solution 3:
You can do this with two pytest fixtures, like so:
import pytest
@pytest.fixture
def foo():
return [object()]
# value derived from foo
@pytest.fixture
def bar(foo):
return foo[0]
# totally independent fixture
@pytest.fixture
def baz():
return object()
def test_fixtures(foo, bar, baz):
assert foo[0] is bar
assert foo[0] is not baz
# both assertions will pass
Here the foo and bar fixtures have a specific relation between their values (referencing the same object). This is the same result as you wanted from your multi fixture. (the baz fixture is included for comparison, and uses an unrelated instance of object().
If both values are derived from some shared context you can put the shared context in a fixture, and then derive the final results independently.
@pytest.fixture
def shared():
return [object()]
@pytest.fixture
def derived_1(shared):
return shared[0]
@pytest.fixture
def derived_2(shared):
return shared[-1]
def test_derived(derived_1, derived_2):
assert derived_1 is derived_2
Post a Comment for "Define A Pytest Fixture Providing Multiple Arguments To Test Function"