[英]Is it possible to raise exception that fail (and not error) test in pytest finalizer?
注意:我使用的是pytest版本2.7.3和老式的夹具。 我现在必须使用此版本。 我在Linux上使用python 2.7。
我目前正在使用pytest进行测试,要求在每个测试结束时进行检查。 为了继续,我编写了一个带有终结器的夹具,该夹具执行检查,但是当我引发异常时,我得到一个奇怪的结果。
这是代码(针对SO进行了编辑,您可以复制/粘贴以进行测试):
# copy/past to foobar.py and run `python -m pytest -v foobar.py`
import pytest
def check():
assert 0
@pytest.fixture(autouse=True, scope='function')
def fixture_foobar(request):
def tear_down():
check()
request.addfinalizer(tear_down)
def test_ok():
assert 1
def test_nok():
assert 0
因此,该代码当前有效,但是输出看起来很奇怪和错误:
# test pass and finalizer raise exception
# expected result : foobar.py::test_ok FAILED
foobar.py::test_ok PASSED
foobar.py::test_ok ERROR
# test fail and finalizer raise exception
# expected result : foobar.py::test_nok FAILED
foobar.py::test_nok FAILED
foobar.py::test_nok ERROR
终结器什么也不做的情况保持良好。
因此,如果有人对如何解决有想法。 可能是我没有好的方法,但是终结器听起来像个好主意。
谢谢。
编辑 :我有与pytest_runtest_teardown
挂钩相同的pytest_runtest_teardown
。
因此,解决方案并不是那么困难。
Pytest提供了很多挂钩 ,我必须使用在测试执行后运行的pytest_pyfunc_call
。
解决方案:
# conftest.py
def check():
assert 0
def pytest_pyfunc_call(pyfuncitem):
check()
# test_foobar.py
def test_ok():
assert 1
def test_nok():
assert 0
结果:
test_foobar.py::test_ok FAILED
test_foobar.py::test_nok FAILED
改进它 :
默认情况下,如果测试失败且check()
失败,则仅跟踪check()
的AssertionError
。 如果找到在测试失败的情况下忽略check()
的解决方案,则将更新答案。 如果您有解决方案,欢迎您!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.