首页 > 解决方案 > 在 pytest.mark.parametrize 中使用夹具

问题描述

假设我有一个测试函数,它将参数化record作为 dict,其中一个值是已经定义的夹具。

例如,我们有一个夹具:

@pytest.fixture
def a_value():
    return "some_value"

和测试功能:

@pytest.mark.parametrize("record", [{"a": a_value, "other": "other_value"},
                                    {"a": a_value, "another": "another_value"}])
def test_record(record):
    do_something(record)

现在,我知道这可以通过将夹具传递给测试函数并相应地更新记录来解决,例如:

@pytest.mark.parametrize("record", [{"other": "other_value"},
                                    {"another": "another_value"}])
def test_record(a_value, record):
    record["a"] = a_value
    do_something(record)

但是我想知道是否有一种方法可以在没有这种“解决方法”的情况下做到这一点,当我有许多已经定义的固定装置并且我只想在传递给函数的每个参数化记录中使用它们时。

我已经检查过这个问题,尽管它似乎并不完全适合我的情况。从那里的答案中找不到正确的用法。

标签: pythonpython-2.7testingpytest

解决方案


一种解决方案是创建record为固定装置,而不是使用parametrize和接受a_value作为参数:

@pytest.fixture
def record(a_value):
    return {
        'a': a_value,
        'other': 'other_value',
    }

推荐阅读