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")deffoobar():
return"blah", "whatever"deftest_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
defpytest_generate_tests(metafunc):
test_func = metafunc.function
if'use_multifixture'in [name for name, ob invars(test_func).items() ifisinstance(ob, MarkInfo)]:
result, func = test_func.use_multifixture.args
params_names = result.split(',')
params_values = list(func())
metafunc.parametrize(params_names, [params_values])
deffoobar():
return"blah", "whatever"@pytest.mark.use_multifixture("foo,bar", foobar)deftest_stuff(foo, bar):
assert foo == "blah"and bar == "whatever"deftest_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.fixturedeffoo():
return [object()]
# value derived from foo@pytest.fixturedefbar(foo):
return foo[0]
# totally independent fixture@pytest.fixturedefbaz():
returnobject()
deftest_fixtures(foo, bar, baz):
assert foo[0] is bar
assert foo[0] isnot 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.fixturedefshared():
return [object()]
@pytest.fixturedefderived_1(shared):
return shared[0]
@pytest.fixturedefderived_2(shared):
return shared[-1]
deftest_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"