Running the same test on two different fixtures

柔情痞子 提交于 2020-01-13 08:31:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!