簡體   English   中英

是否有可能在pytest終結器中引發未能(且不是錯誤)測試的異常?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM