pytest如何通过中间夹具传递请求夹具

pytest how to pass request fixture through intermediary fixture

我有(在 pytest 中):

下面的代码示例将有助于解释:

import pytest

@pytest.fixture
def base(request) -> int:
    return request.param

@pytest.fixture
def intermediary(base: int) -> int:
    return base

# This does not work!  "In test_something: indirect fixture 'base' doesn't exist"
@pytest.mark.parametrize("intermediary", [1], indirect=["base"])
def test_something(intermediary: int) -> None:
    assert isinstance(intermediary, int)

我的问题:如何从仅使用 intermediary 夹具的测试中填充 base 夹具的 request


解决方法

在测试签名作品中包含基本装置:

@pytest.mark.parametrize("base", [1], indirect=True)
def test_something_workaround(base: int, intermediary: int) -> None:
    assert isinstance(intermediary, int)

然而,这对我来说是不可取的,因为测试实际上并没有使用 base,只有 intermediary.


版本

Python==3.8
pytest==6.2.2

你几乎可以这样做,但你必须使用“base”作为parametrize中的夹具名称:

@pytest.fixture
def base(request) -> int:
    return request.param


@pytest.fixture
def intermediary(base: int) -> int:
    return base + 1


@pytest.mark.parametrize("base", [1], indirect=True)
def test_something(intermediary: int) -> None:
    assert intermediary == 2

例如您参数化夹具 base,但使用派生夹具,然后从 base.

获得结果