[英]Failing a test after teardown_method has executed in pytest
我试图弄清楚如何编写一个 pytest 插件,该插件可用于在运行后使测试失败(对于任何想要更多上下文的人,这与astropy/pytest-openfiles#28 相关)。 让我们考虑以下简单的测试文件:
class TestClass:
def setup_method(self, method):
print("In setup_method")
def teardown_method(self, method):
print("In teardown_method")
def test_simple(self):
print("In test")
我现在可以定义一个conftest.py
文件,其中包含:
def pytest_runtest_teardown(item, nextitem):
print("In pytest_runtest_teardown")
在这个钩子中,我可以执行检查 - 例如在我感兴趣的情况下,我们正在检查未关闭的文件句柄。 然而,问题是这个钩子在setup_method
之后和测试本身( test_simple
)之后但在teardown_method
之前运行:
% pytest test.py -vs
...
collected 1 item
test.py::TestClass::test_simple In setup_method
In test
PASSEDIn pytest_runtest_teardown
In teardown_method
我考虑过使用:
def pytest_runtest_makereport(item, call):
if call.when != 'teardown':
return
print("In pytest_runtest_makereport")
这确实在teardown_method
之后被执行,但在那时如果我引发异常 pytest 将输出一个INTERNALERROR
并且仍然会认为测试成功。
在调用teardown_method
后,有没有办法使测试失败/出错?
test_simple
结束后 Pytest 认为它完成了,从现在开始的所有内容都将超出测试范围。 您可以将@pytest.fixture
注释添加到函数中,这将为您提供pytest
设置和拆卸功能。 测试本身将被视为通过,但不是所有套件。 TestClass
将被标记为失败,并引发来自teardown_method
的异常
class TestClass:
@pytest.fixture
def run_for_test(self):
self.setup_method()
yield
self.teardown_method()
def setup_method(self, method):
print("In setup_method")
def teardown_method(self, method):
print("In teardown_method")
# just for the example
if not method:
raise AssertionError
def test_simple(self):
print("In test")
输出
In setup_method
.In test
In teardown_method
> raise AssertionError
E AssertionError
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.