首页 > 解决方案 > 使用带有来自标记的参数的 pytest 夹具

问题描述

我尝试在 pytest 中创建一个测试用例。我想使用参数化夹具从 @pytest.mark.parametrize 装饰器获取参数并创建更多类型的测试。我的代码现在看起来:

@pytest.mark.parametrize( 
    "a",
    ["1", "2"],
    ids=["a:1", "a:2"]
)
@pytest.mark.parametrize(  # type: ignore
    "fixture_a",
    [{"b": 1}],
    ids=["b:1"],
    indirect=["fixture_a"],
)
def test_postgres_basic(fixture_a, a):
    ...

我想要什么?

我想将参数发送afixture_a这样的装置request.param,而不是{"b": 1}{"b":1, a: "1"}and之类的东西{"b":1, a: "2"}。有可能以某种简单的方式吗?

谢谢

标签: python-3.xtestingpytestfixtures

解决方案


a另一种方法是在要传递给夹具的dict中手动定义值。

import pytest


@pytest.fixture
def fixture_a(request):
    print(f"{request.param=}")
    return request.param


@pytest.mark.parametrize( 
    "fixture_a, a",
    [
        ({"a": 1, "b": 1}, "1"),
        ({"a": 2, "b": 1}, "2"),
    ],
    ids=["a:1", "a:2"],
    indirect=["fixture_a"],
)
def test_postgres_basic(fixture_a, a):
    print(fixture_a, a)

输出

$ pytest -q -rP
..
[100%]
================================================================================================= PASSES ==================================================================================================
________________________________________________________________________________________ test_postgres_basic[a:1] _________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------------------------------
request.param={'a': 1, 'b': 1}
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
{'a': 1, 'b': 1} 1
________________________________________________________________________________________ test_postgres_basic[a:2] _________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout setup ------------------------------------------------------------------------------------------
request.param={'a': 2, 'b': 1}
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
{'a': 2, 'b': 1} 2
2 passed in 0.06s

推荐阅读