代码之家  ›  专栏  ›  技术社区  ›  jxramos

pytest是否有类似google test的非致命预期行为?

  •  2
  • jxramos  · 技术社区  · 6 年前

    我更熟悉google测试框架,了解他们支持的主要行为对 ASSERT_* VS EXPECT_* 它们是致命的和非致命的断言模式。

    documentation :

    断言成对出现,测试相同的东西,但是 对当前功能的不同影响。 断言_* 版本生成 当失败时发生致命错误,并中止当前函数。 期待_* 版本会生成非致命的失败,但不会中止 当前函数。通常首选expect,因为它们允许更多 在一次测试中要报告一次以上的失败。但是,您应该使用 断言如果在 问题失败了。

    问题 :pytest是否也有我可以启用的非致命断言风格或模式?

    允许所有测试最大限度地执行以获得最丰富的失败历史记录,而不是在第一次失败时中止,并可能隐藏必须通过运行测试应用程序的多个实例逐段发现的后续失败,这是很好的。

    2 回复  |  直到 6 年前
        1
  •  2
  •   wim    6 年前

    不,没有这样的功能 pytest . 最流行的方法是使用 assert 语句,如果表达式是错误的,则立即使测试失败。

    允许所有测试最大限度地执行以获得最丰富的失败历史记录,而不是在第一次失败时中止,并可能隐藏必须通过运行测试应用程序的多个实例逐段发现的后续失败,这是很好的。

    您可以很容易地重新创建expect东西,方法是在错误列表后面附加一个错误列表,然后在测试结束时断言该列表为空,但是在 脓包 为了这样一个特点。

        2
  •  3
  •   hoefling    6 年前

    我用 pytest-assume 对于非致命的断言。它做得很好。

    安装

    像往常一样,

    $ pip install pytest-assume
    

    使用示例

    import pytest
    
    
    def test_spam():
        pytest.assume(True)
        pytest.assume(False)
    
        a, b = True, False
        pytest.assume(a == b)
    
        pytest.assume(1 == 0)
        pytest.assume(1 < 0)
    
        pytest.assume('')
        pytest.assume([])
        pytest.assume({})
    

    如果你想写作 pytest.assume 有点太多了,只需将导入别名为:

    import pytest.assume as expect
    
    
    def test_spam():
        expect(True)
        ...
    

    运行上述测试得到:

    $ pytest -v
    ============================= test session starts ==============================
    platform linux -- Python 3.6.5, pytest-3.6.0, py-1.5.3, pluggy-0.6.0 -- /data/gentoo64-prefix/u0_a82/projects/stackoverflow/so-50630845
    cachedir: .pytest_cache
    rootdir: /data/gentoo64-prefix/u0_a82/projects/stackoverflow/so-50630845, inifile:
    plugins: assume-1.2
    collecting ... collected 1 item
    
    test_spam.py::test_spam FAILED                                            [100%]
    
    =================================== FAILURES ===================================
    __________________________________ test_spam ___________________________________
    test_spam.py:6: AssumptionFailure
            pytest.assume(False)
    
    
    test_spam.py:9: AssumptionFailure
            pytest.assume(a == b)
    
    
    test_spam.py:11: AssumptionFailure
            pytest.assume(1 == 0)
    
    
    test_spam.py:12: AssumptionFailure
            pytest.assume(1 < 0)
    
    
    test_spam.py:13: AssumptionFailure
            pytest.assume('')
    
    
    test_spam.py:14: AssumptionFailure
            pytest.assume([])
    
    
    test_spam.py:14: AssumptionFailure
            pytest.assume([])
    
    
    test_spam.py:15: AssumptionFailure
            pytest.assume({})
    
    ------------------------------------------------------------
    Failed Assumptions: 7
    =========================== 1 failed in 0.18 seconds ===========================