【问题标题】:How to stop running other tests in a module if a specific test fails in pytest?如果 pytest 中的特定测试失败,如何停止在模块中运行其他测试?
【发布时间】:2021-04-05 11:40:54
【问题描述】:

我有一个带有 pytest 测试的模块。那里有很多测试,拳头检查是否有与目标的连接。如果此测试失败,则没有理由等待此特定模块中的所有其他测试超时。如果这一特定测试失败,我想停止模块中的所有测试。

我找到了pytest.exit(),但它太强大了,它终止了整个 pytest 运行。我还有其他模块要使用,所以我想在一个(当前)模块中快速跳过/失败所有其他测试。

有没有办法做到这一点?

【问题讨论】:

  • 您可以显式调用pytest.skip(),例如在本地自动使用装置中:@pytest.fixture(autouse=True, scope="function") def myfixture(): if not condition: pytest.skip("condition not fulfilled")

标签: python pytest


【解决方案1】:

你可以使用@pytest.mark.skipif注解而不是先运行另一个测试

def has_connection():
    return True


@pytest.mark.skipif(not has_connection(), reason='No connection')
def test_example(self):
    pass

如果所有测试都在类下,您可以将注释添加到类中,这将跳过所有测试

@pytest.mark.skipif(not has_connection(), reason='No connection')
class TestExample:

    def test_example1(self):
        pass

    def test_example2(self):
        pass

【讨论】:

  • 看起来几乎是对的,但@skipif 是在收集时执行的,我需要跳过测试时间。连接发生在服务器上,该服务器是通过 testinfra 的 host 固定装置提供的。 (很抱歉没有在原始问题中澄清这一点)。
  • @GeorgeShuklin 如果您不介意测试失败,您可以在相关测试的开头添加断言assert has_connection()
猜你喜欢
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
相关资源
最近更新 更多