[英]Can we call a pytest fixture conditionally?
My use case is to call fixture only if a certain condition is met.我的用例是仅在满足特定条件时才调用 fixture。 But since we need to call the pytest fixture as an argument to a test function it gets called every time I run the test.
但是由于我们需要调用 pytest 夹具作为测试 function 的参数,所以每次我运行测试时都会调用它。
I want to do something like this:我想做这样的事情:
@pytest.parameterize("a", [1, 2, 3])
def test_method(a):
if a == 2:
method_fixture
Yes, you can use indirect=True
for a parameter to have the parameter refer to a fixture.是的,您可以对参数使用
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
As asked in the edit, if your fixtures are dependent on each other, you'll probably need to use the pytest_generate_tests
hook instead.正如编辑中所问,如果您的固定装置相互依赖,您可能需要改用
pytest_generate_tests
挂钩。
Eg this will parametrize the test with values that aren't equal.例如,这将使用不相等的值对测试进行参数化。
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
The answer is accepted and helped for the OP however it is not "conditional fixture calling".答案被接受并为 OP 提供了帮助,但它不是“条件夹具调用”。 It is called always only it behaves differently based on some condition.
它总是被调用,只是它根据某些条件表现不同。
So I only want to clarify that real conditionally call (or dynamically run) a fixture is possible using the request
fixture.所以我只想澄清一下,使用
request
夹具可以真正有条件地调用(或动态运行)夹具。
@pytest.parameterize("a", [1, 2, 3])
def test_method(request, a):
if a == 2:
request.getfixturevalue('method_fixture')
See documentation here https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest.FixtureRequest.getfixturevalue请参阅此处的文档https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest.FixtureRequest.getfixturevalue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.