首页 > 解决方案 > pytest如何制作一个参数化另一个夹具的夹具

问题描述

我有很多通过pytest.

有时,我希望使用夹具进行测试而不必担心应用参数。

是否可以制作一个参数化另一个夹具的夹具?

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

标签: pythonpytestfixtures

解决方案


我不认为你可以按照你想要的方式做到这一点,但也许将夹具参数与普通函数结合使用就足够了,例如:

...
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

当然,这仅在您想对多个测试使用相同的参数时才有意义。


推荐阅读