问题
I have a test which currently runs with a single fixture like this:
@pytest.fixture()
def foo():
return 'foo'
def test_something(foo):
# assert something about foo
Now I am creating a slightly different fixture, say
@pytest.fixture
def bar():
return 'bar'
I need to repeat the exact same test against this second fixture. How can I do that without just copy/pasting the test and changing the parameter name?
回答1:
Beside the test generation, you can do it the "fixture-way" for any number of sub-fixtures applied dynamically. For this, define the actual fixture to be used as a parameter:
@pytest.fixture
def arg(request):
return request.getfuncargvalue(request.param)
The define a test with am indirect parametrization (the param name arg
and the fixture name arg
must match):
@pytest.mark.parametrize('arg', ['foo', 'bar'], indirect=True)
def test_me(arg):
print(arg)
Lets also define those fixtures we refer to:
@pytest.fixture
def foo():
return 'foo'
@pytest.fixture
def bar():
return 'bar'
Observe how nicely parametrized and identified these tests are:
$ pytest test_me.py -s -v -ra
collected 2 items
test_me.py::test_me[foo] foo
PASSED
test_me.py::test_me[bar] bar
PASSED
来源:https://stackoverflow.com/questions/46223358/running-the-same-test-on-two-different-fixtures