简体   繁体   English

是否有可能在pytest终结器中引发未能(且不是错误)测试的异常?

[英]Is it possible to raise exception that fail (and not error) test in pytest finalizer?

Note : I'm using the version 2.7.3 of pytest with old-style for fixture. 注意:我使用的是pytest版本2.7.3和老式的夹具。 I have to use this version at the moment. 现在必须使用此版本。 I'm using python 2.7 on Linux. 我在Linux上使用python 2.7。

I currently working on tests with pytest that required a check at the end of each test. 我目前正在使用pytest进行测试,要求在每个测试结束时进行检查。 To proceed I have wrote a fixture with a finalizer which perform the check but when I raise an exception I have a strange result. 为了继续,我编写了一个带有终结器的夹具,该夹具执行检查,但是当我引发异常时,我得到一个奇怪的结果。

Here is the code (edited for SO, you can copy/paste to test): 这是代码(针对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

So the code currently works but the output looks weird and wrong : 因此,该代码当前有效,但是输出看起来很奇怪和错误:

# 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

The case where finaliser do nothing stay good. 终结器什么也不做的情况保持良好。

So if somebody have a idea how to fix it. 因此,如果有人对如何解决有想法。 May be I don't have the good approach but finalizer sounds like a good idea. 可能是我没有好的方法,但是终结器听起来像个好主意。

Thanks. 谢谢。

EDIT : I have the same comportment with the pytest_runtest_teardown hook. 编辑 :我有与pytest_runtest_teardown挂钩相同的pytest_runtest_teardown

So the solution was not so hard. 因此,解决方案并不是那么困难。

Pytest provide a lot of hooks and I have to use pytest_pyfunc_call which is run after test execution. Pytest提供了很多挂钩 ,我必须使用测试执行运行的pytest_pyfunc_call

Solution : 解决方案:

# 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

And the result : 结果:

test_foobar.py::test_ok FAILED
test_foobar.py::test_nok FAILED

Improve it : 改进它 :

By default, if test failed and check() failed only the AssertionError of check() is traced. 默认情况下,如果测试失败且check()失败,则仅跟踪check()AssertionError If I found a solution to ignore check() in case of test failure I'll update the answer. 如果找到在测试失败的情况下忽略check()的解决方案,则将更新答案。 If you have a solution, you are welcome ! 如果您有解决方案,欢迎您!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM