【问题标题】:Using a fixture inside pytest.mark.parametrize在 pytest.mark.parametrize 中使用夹具
【发布时间】:2019-01-07 16:43:30
【问题描述】:

假设我有一个测试函数,它将参数化 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)

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

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

【问题讨论】:

  • 谢谢@wim - 如果我理解正确,这需要我修改运行测试的注释。有没有办法通过代码做到这一点?

标签: python python-2.7 testing pytest


【解决方案1】:

一种解决方案是创建record 作为夹具,而不是使用parametrize 并接受a_value 作为参数:

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

【讨论】:

  • 谢谢!但是,您如何对不同的records 进行参数化?我已经编辑了我的问题,使 record 参数有几个不同的值。
  • @A.Sarid 在您的示例中,记录只有两个字段。在实践中,记录真正有多少字段?
  • 变化,这就是使用参数化的全部原因,有些会有 2,有些会有更多的键值对。尽管在我的示例中,所有记录都将包含一个固定装置,例如 a_value
  • @A.Sarid 我从比我更了解 pytest 的人那里得到提示,建议 metafunc.parametrize:docs.pytest.org/en/latest/…
猜你喜欢
  • 2022-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-02
  • 2018-05-22
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多