【问题标题】:Skip testsuite if fixture fails in pytest如果夹具在 pytest 中失败,则跳过测试套件
【发布时间】:2019-12-18 16:44:39
【问题描述】:

我有一个测试套件,它是一个类,每个测试方法都是一个测试用例。我还为每种方法(测试用例)提供了一个固定装置,它可以做一些基本的事情。我有一个奇怪的要求,如果 testfixture 失败,我想跳过测试套件中的所有测试用例。

以下是我拥有的示例套件

class TestFeature:
    @pytest.fixture(scope="function", autouse=True)
    def _wrapper(self):
        print("Some precomditions")
        yield
        print("some post conditions")

    def test_first_testcase(self):
        print("First testcas")

    def test_second_testcase(self):
        print("second testcas")

    def test_third_testcase(self):
        print("Third testcas")

现在我想如果我的夹具失败,我想中止这个测试套件。假设我的第一个测试用例失败了。下一个测试用例的夹具失败。我想中止套件并且不想执行第三个测试用例。

如何在 pytest 中做到这一点

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    pytest allows you 使用 x 标志:

    pytest -x
    

    如果您想自定义退出前的失败次数,也可以使用maxfail 标志:

    --maxfail=NUMBER
    

    如果您需要从代码中退出测试套件,您可以使用exit 方法:

    import pytest
    
    pytest.exit()
    

    【讨论】:

    • 我认为这也会导致测试用例失败。我只想在夹具失败时中止
    • 您是否考虑过从灯具内致电pytest.exit
    • 有没有一种优雅的方式来做到这一点。 Pytest.exit 将突然退出。我想要类似的东西应该跳过并打印像我们使用 xfail 或跳过时跳过的测试用例这样的消息
    • pytest.skip(msg)
    猜你喜欢
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 2012-07-12
    • 2012-12-06
    • 1970-01-01
    相关资源
    最近更新 更多