可以有条件地调用pytest fixture吗?



我的用例是仅在满足特定条件时调用fixture。但是,由于我们需要调用pytest fixture作为测试函数的参数,因此每次运行测试时都会调用它。

我想这样做:

@pytest.parameterize("a", [1, 2, 3])
def test_method(a):
if a == 2:
method_fixture

答案被接受并帮助OP,但它不是"条件fixture调用"。它被称为always,只是它根据某些条件表现不同。

所以我只想澄清,真正有条件地调用(或动态运行)一个夹具是可能使用request夹具。

@pytest.parameterize("a", [1, 2, 3])
def test_method(request, a):
if a == 2:
request.getfixturevalue('method_fixture')

查看这里的文档https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest.FixtureRequest.getfixturevalue

是的,您可以使用indirect=True作为参数,使该参数引用夹具。

import pytest

@pytest.fixture
def thing(request):
if request.param == 2:
return func()
return None

@pytest.mark.parametrize("thing", [1, 2, 3], indirect=True)
def test_indirect(thing):
pass  # thing will either be the retval of `func()` or NOne

带有独立的"固定结构">

如编辑中所问,如果您的fixture相互依赖,您可能需要使用pytest_generate_tests钩子代替。

。这将使用不相等的值来参数化测试。

import itertools

def pytest_generate_tests(metafunc):
if metafunc.function.__name__ == "test_combo":
a_values = [1, 2, 3, 4]
b_values = [2, 3, 4, 5]
all_combos = itertools.product(a_values, b_values)
combos = [
pair
for pair in all_combos
if pair[0] != pair[1]
]
metafunc.parametrize(["a", "b"], combos)

def test_combo(a, b):
assert a != b

最新更新