Is it possible to parametrize a test with fixtures?
Asked Answered
B

1

2

I would like to pass @pytest.mark.parametrize not particular values but fixtures. Like so.

Given a conftest with:

@pytest.fixture
def name1():
    return 'foo'

@pytest.fixture
def name2():
    return 'bar'

within my test.py this works of course:

@pytest.mark.parametrize('name', ['foo', 'bar', 'baz'])
def test_name(name):
    print(name)

This does not:

 @pytest.mark.parametrize('name', [name1, name2])
 def test_name(name):
     print(name)

I am aware that in this trivial case I could just create one name fixture and parametrize the fixture instead, but there are cases were this is not deireable.

One way around this that I found is with pytest_factoryboy's LazyFixture. However, I often fail to access the lazyfixtures attributes within my test.

Breeching answered 9/11, 2015 at 14:27 Comment(2)
I don't really see the usecase in which parametrizing fixtures is not enough. However I was thinking about something like this: @pytest.mark.parametrize('name', [name1(), name2()]) def test_name(name): print(name). Of course this is not exactly what you want because in this case fixtures are used as it were standard functions, not fixtures.Barbiturism
There's a long standing feature request in the pytest tracker for this, but so far, nobody has worked on it.Jeunesse
E
4

I would insist in parametrizing the fixture

In your example this would amount to:

@pytest.fixture(params=['foo', 'bar'])
def name(request):
    return request.param

def test_name(name):
    print(name)

Another alternative:

@pytest.fixture(params=[1,2])
def name(name1, name2, request):
    if request.param == 1:
        return name1()
    elif request.param == 2:
        return name2()

def test_name(name):
    print(name)

Which approach works best for you will depend on the specifics of your tests and perhaps on what pre-existing fixtures you might be trying to leverage.

Equivalence answered 11/1, 2016 at 21:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.