pytest 夹具传递值
pytest fixture passing values
我正在尝试将值传递给固定装置,因为我基本上对许多测试使用相同的代码,但只有一些值发生变化,据我所知,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
不是在夹具选项 a 或选项 b 之间进行选择,而是添加并且唯一改变的是值,我可以有一个夹具,我可以在其中设置我想要的值 运行 test_foo?
提前致谢。
您给出的示例非常简单,不需要固定装置。你只需要做:
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。
我正在尝试将值传递给固定装置,因为我基本上对许多测试使用相同的代码,但只有一些值发生变化,据我所知,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
不是在夹具选项 a 或选项 b 之间进行选择,而是添加并且唯一改变的是值,我可以有一个夹具,我可以在其中设置我想要的值 运行 test_foo?
提前致谢。
您给出的示例非常简单,不需要固定装置。你只需要做:
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。