pytest fixture传递值

时间:2018-06-08 01:17:37

标签: python pytest

我试图将值传递给灯具,因为我基本上为许多测试都有相同的代码,但只有一些值发生变化,因为我理解pytest灯具不接受但不确定如何解决这个问题,例如我有这个:

import pytest


@pytest.fixture
def option_a():
    a = 1
    b = 2
    return print(a + b)


@pytest.fixture
def option_b():
    a = 5
    b = 3
    return print(a + b)


def test_foo(option_b):
    pass

而不是在fixture选项a或选项b之间进行选择,两者都进行添加,唯一改变的是值,我可以使用一个夹具来设置我想在test_foo上运行哪些值吗?

提前感谢。

1 个答案:

答案 0 :(得分:1)

您提供的示例非常简单,您不需要灯具。你只是这样做:

import pytest

@pytest.mark.parametrize("a,b,expected", [
    (1,2,3),
    (5,3,8),
])
def test_foo(a, b, expected):
    assert a + b == expected

有关详细信息,请参阅https://docs.pytest.org/en/3.6.1/parametrize.html

但是,我要假设,你只是将它简化为制作MCVE的一部分。在这种情况下,您将执行以下操作:

@pytest.fixture(params=[(1 , 2, "three"), (5,3,"eight")])
def option_a_and_b(request):
    a, b, word = request.param
    return a + b, word

def test_foo(option_a_and_b):
    total, word = option_a_and_b
    if total == 3:
        assert word == "three"
    elif total == 8:
        assert word == "eight"
    else:
        assert False

def test_bar(option_a_and_b):
    pass

如果您运行此代码,您将注意到4个传递测试,因为每个param都会运行获得该工具的每个测试。

有关详细信息,请参阅https://docs.pytest.org/en/3.6.1/fixture.html#fixture-parametrize

相关问题