Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running the same test on two different fixtures

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?

like image 858
Code-Apprentice Avatar asked Sep 14 '17 15:09

Code-Apprentice


1 Answers

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
like image 162
Sergey Vasilyev Avatar answered Sep 23 '22 15:09

Sergey Vasilyev