pytest how to make a fixture that parametrizes another fixture

Viewed 133

I have a lot of parametrized fixtures managed via pytest.

Sometimes, I want tests using the fixture not to have to worry about applying parameters.

Is it possible to make a fixture that parametrizes another fixture?

import pytest

class Foo:
    def __init__(self, a: int, b: int):
        pass

@pytest.fixture
def foo(a: int, b: int) -> Foo:
    return Foo(a, b)

@pytest.fixture
@pytest.mark.parametrize("a, b", [(2, 3)])  # How can I do this?
def fixture_parametrizing_another_fixture(foo: Foo) -> Foo:
    return foo

# I don't want to parametrize here, I want the fixture already set up
def test_with_second_fixture(fixture_parametrizing_another_fixture: Foo):
    pass
1 Answers

I don't think you can do this the way you want to, but maybe it would be sufficient to use fixture parameters in combination with a normal function, e.g.:

...
def foo(a: int, b: int) -> Foo:
    return Foo(a, b)

@pytest.fixture(params=[(3, 2)])
def parametrized_fixture1(request) -> Foo:
    yield foo(request.param[0], request.param[1])

@pytest.fixture(params=[(5, 6), (7, 8)])
def parametrized_fixture2(request) -> Foo:
    yield foo(request.param[0], request.param[1])

def test_with_second_fixture1(parametrized_fixture1: Foo):
    # one test with (3,2)
    pass

def test_with_second_fixture2(parametrized_fixture2: Foo):
    # two tests
    pass

Of course, this only makes sense if you want to use the same parameters for more than one test.

Related