簡體   English   中英

在pytest中執行teardown_method后測試失敗

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

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