【问题标题】:How can I skip a test if another test fails with py.test?如果另一个测试因 py.test 失败,我该如何跳过测试?
【发布时间】:2012-05-05 17:57:27
【问题描述】:

假设我有这些测试功能:

def test_function_one():
    assert # etc...

def test_function_two():
    # should only run if test_function_one passes
    assert # etc.

如何确保 test_function_two 仅在 test_function_one 通过时运行(我希望它是可能的)?

编辑: 我需要这个,因为测试二使用的是测试一验证的属性。

【问题讨论】:

  • 你能解释一下你为什么需要这个吗?第一个测试是否设置了第二个使用的东西?这通常很糟糕。
  • 这通常是脆弱测试的标志,这种测试依赖于比它测试的单元更多的东西,你确定你需要这样做吗? (可能)重构测试和/或被测代码以避免这种依赖性会更好。
  • @tjd.rodgers 但是,如果输入不正确,第二次测试也会失败,这难道没有意义吗?为什么你不想运行它?
  • @loganfsmyth 我曾想过,但我不希望第二次测试无缘无故地失败并污染测试结果,而问题确实出现在第一次测试中。
  • 不要担心这个问题的回击。我认为这是一个值得提出的好问题,即使答案可能不是您最初的预期。没有什么不好的问题。

标签: python pytest


【解决方案1】:

我正在使用名为 pytest-dependency 的 pytest 插件。

除上述之外 - 如果您在测试类中使用测试 - 您必须将测试类名称添加到函数测试名称

例如:

import pytest


class TestFoo:

    @pytest.mark.dependency()
    def test_A(self):
        assert False

    @pytest.mark.dependency(depends=['TestFoo::test_A'])
    def test_B(self):
        assert True

因此,如果 test_A 失败 - test_B 将不会运行。如果 test_A 通过 - test_B 将运行。

【讨论】:

    【解决方案2】:

    您可以使用名为 pytest-dependency 的 pytest 插件。

    代码可能如下所示:

    import pytest
    
    @pytest.mark.dependency()   #First test have to have mark too
    def test_function_one():
        assert 0, "Deliberate fail"
    
    @pytest.mark.dependency(depends=["test_function_one"])
    def test_function_two():
        pass   #but will be skipped because first function failed
    

    【讨论】:

    • 这对我来说确实跳过了test_function_two,但它也会在test_function_one 通过时跳过
    • @Gulzar 我遇到了同样的问题,并意识到您还需要装饰所依赖的功能,即使它不依赖任何东西。在此示例中,请确保您在 test_function_one 上有 @pytest.mark.dependency()
    【解决方案3】:

    我认为你的解决方案是模拟 test1 设置的值。

    理想情况下,测试应该是独立的,因此请尝试模拟该值,以便您可以随时运行 test2,事实上,您还应该模拟(模拟)脏值,以便了解 test2 在收到意外数据时的行为。

    【讨论】:

    • 理论上你说的是真的。但根据我的经验,通过模拟第一个测试的结果,您最终会重新实现第一个函数/类的功能,而不是重用该代码。
    【解决方案4】:

    我想这就是你想要的:

    def test_function():
        assert # etc...
        assert # etc...
    

    这符合您的要求,即仅当第一个“测试”(断言)通过时才运行第二个“测试”(断言)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      相关资源
      最近更新 更多