簡體   English   中英

pytest 如何制作對另一個夾具進行參數化的夾具

[英]pytest how to make a fixture that parametrizes another fixture

我有很多通過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

我不認為你可以按照你想要的方式做到這一點,但也許將夾具參數與普通 function 結合使用就足夠了,例如:

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

當然,這僅在您想對多個測試使用相同的參數時才有意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM