[英]How to dynamically select a pytest fixture?
import pytest
@pytest.fixture()
def fixture1(fixture_a):
print('In fixture 1')
<do>
step a
step b
<end>
return <some object1>
@pytest.fixture()
def fixture2(fixture_b):
print('In fixture 2')
<do>
step x
step y
<end>
return <some object2>
def decide():
a = 1
if a == 1:
return fixture1: Object1
else:
return fixture2: Object2
def test_me():
res = decide()
assert res == Object
I have two fixtures arg1 and arg2, now I want to return one of the fixture to the test but this has to be dynamic selection based on a condition.我有两个夹具 arg1 和 arg2,现在我想将其中一个夹具返回给测试,但这必须是基于条件的动态选择。 How to do this?这个怎么做?
UPDATE: The fixtures arg1 and arg2 have a chain of dependency and they are being used in different tests.更新:夹具 arg1 和 arg2 有一个依赖链,它们被用于不同的测试。
Also, decide function needs to be used in multiple tests.另外,决定 function 需要在多个测试中使用。
You can pass the arg1
and arg2
to test
and test the condition itself.您可以通过arg1
和arg2
来test
和测试条件本身。
def decide():
a = 1
if a == 1:
return 1
else:
return 2
def test_me(fixture1, fixture2):
arg = decide()
if arg == 1:
assert fixture1 == 1
else:
assert fixture2 == 2
I guess that can help - having fixture builder what runs functions(convert fixtures A,B to functions) in case of condition:我想这会有所帮助 - 让夹具构建器在以下情况下运行函数(将夹具 A、B 转换为函数):
def arg1():
print('In arg 1')
return 1
def arg2():
print('In arg 2')
return 2
@pytest.fixture
def env_builder():
if condition:
return arg1()
else
return arg2()
def test_smth(env_builder):
assert 2 == env_builder
your condition is up to you, os.getenv('environment'), or might positional cli argument while running tests您的情况取决于您,os.getenv('environment'),或者可能在运行测试时定位 cli 参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.