【问题标题】:How can I parametrize tests to run with different fixtures in pytest?如何参数化测试以在 pytest 中使用不同的夹具运行?
【发布时间】:2019-05-25 17:50:39
【问题描述】:

来自 pytest documentation:

@pytest.mark.parametrize 允许在测试函数或类中定义多组参数和夹具。

看起来这意味着pytest.mark.parametrize 可以将测试标记为使用多组夹具运行?我可以找到很多参数化参数的例子,但我不知道如何参数化不同的夹具集。

我认为this answer 很接近,但这实际上只是参数化参数,然后解析测试主体中的不同夹具。

是否可以使用不同的固定装置将测试标记为多次运行?


注意我正在尝试做这样的事情:

import pytest

# some data fixutres
@pytest.fixture()
def data1():
    """Create some data"""

@pytest.fixture()
def data2():
    """Create some different data"""

@pytest.fixture()
def data3():
    """Create yet different data"""


# The tests
@pytest.mark.parametrize('data', [data1, data2])
def test_foo(data):
    """Test something that makes sense with datasets 1 and 2"""

@pytest.mark.parametrize('data', [data2, data3])
def test_bar(data):
    """Test something that makes sense with datasets 2 and 3"""

【问题讨论】:

  • 你不能在parametrize 中传递固定装置,见issue #349。在变量中声明数据集并将它们用于参数化。

标签: python pytest


【解决方案1】:

您可以使用pytest-lazy-fixture 插件来做到这一点:

import pytest
from pytest_lazyfixture import lazy_fixture

@pytest.fixture()
def fixture1():
    return "data1"

@pytest.fixture()
def fixture2():
    return "data2"

@pytest.fixture()
def fixture3():
    return "data3"

@pytest.mark.parametrize("data", [lazy_fixture("fixture1"),
                                  lazy_fixture("fixture2")])
def test_foo(data):
    assert data in ("data1", "data2")

@pytest.mark.parametrize("data", [lazy_fixture("fixture2"),
                                  lazy_fixture("fixture3")])
def test_bar(data):
    assert data in ("data2", "data3")

请注意,有一个建议将类似的功能直接添加到 pytest:https://docs.pytest.org/en/latest/proposals/parametrize_with_fixtures.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多