我的测试套件具有所有测试共享的夹具。
@pytest.fixture(scope="session")
def foo_fixture():
data = get_data()
if not data:
pytest.fail('ERROR: Could not get data', pytrace=False)
然后我有很多测试基本上可以归结为:
def test_foo(foo_fixture):
assert something, pytest.fail('ERROR: ...', pytrace=False)
def test_bar(foo_fixture):
assert something, pytest.fail('ERROR: ...', pytrace=False)
我看到的问题是,每当get_data()
不返回任何内容时,每次测试都会调用该固定装置。我为什么知道这个?因为输出是:
____________________________________________________________________ ERROR at setup of test_foo ____________________________________________________________________
ERROR: Could not get data
____________________________________________________________________ ERROR at setup of test_bar____________________________________________________________________
ERROR: Could not get data
如您所见,我将灯具设置为scope="session"
,因此它只能运行一次。我认为这里的问题是pytest.fail
。我猜它即将结束会话,所以这就是为什么总是调用固定装置的原因。
那么,我该如何以不同的方式编写代码,以使夹具仅被调用一次?当get_data()
实际返回内容时,由于测试持续时间,我可以注意到灯具仅运行一次。但是正如我说的,当没有数据时,它会为每个测试运行,而问题是get_data()
对不同的API发出了许多请求,因此我只想运行一次以缩短测试时间。