pytest raing 错误 - 夹具"teardown"直接调用



我正在维护一些用pytest编写的测试套件。在pytest升级到7.x版本后,我得到了这样的错误:

夹具"拆卸";直接调用。固定装置不意味着直接调用,而是在测试功能请求它们作为参数时自动创建。看见https://docs.pytest.org/en/stable/explanation/fixtures.html有关固定装置的详细信息,以及
https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures直接介绍如何更新代码。

这条消息很清楚,我完全知道这一变化。我仍然不知道pytest为什么在下面的场景中提出它:

import pytest
class TestDemo():
@pytest.fixture(scope="class")
def teardown(self, request):
def teardown():
pass
request.addfinalizer(teardown)
def test_demo(self, teardown):
return True

你有什么建议吗;直接呼叫";发生了什么?

teardown()实际上是一个单元测试风格的方法。它在test完成后自动调用,但作为测试用例的一部分,而不是作为正常pytest拆卸的一部分。因此pytest将其视为直接调用的fixture

来自单元测试。测试用例支持(页面底部的注释部分(

unittest.TestCase方法不能直接接收fixture可能会影响运行通用单元测试。TestCase测试套件。

由于两个框架之间的架构差异,设置和基于单元测试的测试的拆卸是在调用阶段执行的而不是在pytest的标准设置和拆卸阶段。在某些情况下,尤其是当对错误进行推理时。例如,如果一个基于单元测试的套件在安装过程中显示错误,pytest在其设置阶段,并将在调用期间引发错误。

我建议您使用pytest格式来设置和拆除

# with request.addfinalizer
@pytest.fixture(scope='class', autouse=True)
def setup_and_teardown(self, request):
def teardown():
print('teardown')
request.addfinalizer(teardown)
print('setup')
yield
# without request.addfinalizer
@pytest.fixture(scope='class', autouse=True)
def setup_and_teardown(self):
print('setup')
yield
print('teardown')
def test_demo(self):
print('test')

输出

setup
PASSED                             [100%]test
teardown

最新更新