如何动态选择pytest夹具


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

我有两个夹具arg1和arg2,现在我想将其中一个夹具返回测试,但这必须是基于条件的动态选择。如何做到这一点?

更新:设备arg1和arg2具有依赖链,它们正在不同的测试中使用。

此外,decision函数需要在多个测试中使用。

您可以将arg1arg2传递给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

我想这会有所帮助-让fixture生成器在条件为的情况下运行函数(将fixture 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

您的条件取决于您,os.getenv("environment"(,或者可能在运行测试时定位cli参数

最新更新