使用带有来自标记的参数的pytest夹具

Using pytest fixture with parameter from mark

我尝试在 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):
    ...

我想要什么?

我想将参数 a 发送到 fixture_a,这样夹具 request.param 就不会是 {"b": 1},而是像 {"b":1, a: "1"}{"b":1, a: "2"}.是否可以通过一些简单的方式实现?

谢谢

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

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