Pytest 在第一次失败后停止运行

史蒂夫

我正在使用 Pytest 在两个列表上运行测试

  import pytest
  def test_TestsRunAfterFailure():
     x = [1,2,3,4]
     test = [4, 5, 6]
     for t in test:
         assert (t in x)

我希望测试即使在第一次失败后也能测量每个变量,这样我就知道哪些变量失败了。生成的输出表明它在第一次失败后停止。

      E           assert 5 in [1, 2, 3, 4]

我在谷歌上搜索了这个问题,建议使用以下参数运行 pytest

     pytest --maxfail=3 

然而,结果表明它在第一个断言为假后停止。有没有更好的方法来做到这一点?

拉尔斯克

测试是一个函数,问题在于您编写的代码只有一个测试 ( test_TestsRunAfterFailure)。当代码遇到第一个失败的assert语句时,该测试失败了。

如果要运行多个测试,则需要:

  • 编写多个测试函数,或
  • 参数化测试

第二种解决方案可能是您想要的,可能如下所示:

import pytest

@pytest.mark.parametrize('value', [4, 5, 6])
def test_TestsRunAfterFailure(value):
   x = [1, 2, 3, 4]
   assert (value in x)

运行上面的代码将产生如下输出:

===================================== test session starts =====================================
platform linux -- Python 3.9.4, pytest-6.0.2, py-1.10.0, pluggy-0.13.1
rootdir: /home/lars/tmp/python
plugins: cov-2.11.1, flake8-1.0.7, asyncio-0.14.0, xonsh-0.9.26
collected 3 items

test_values.py .FF                                                                      [100%]

========================================== FAILURES ===========================================
________________________________ test_TestsRunAfterFailure[5] _________________________________

value = 5

    @pytest.mark.parametrize('value', [4, 5, 6])
    def test_TestsRunAfterFailure(value):
       x = [1, 2, 3, 4]
>      assert (value in x)
E      assert 5 in [1, 2, 3, 4]

test_values.py:6: AssertionError
________________________________ test_TestsRunAfterFailure[6] _________________________________

value = 6

    @pytest.mark.parametrize('value', [4, 5, 6])
    def test_TestsRunAfterFailure(value):
       x = [1, 2, 3, 4]
>      assert (value in x)
E      assert 6 in [1, 2, 3, 4]

test_values.py:6: AssertionError
=================================== short test summary info ===================================
FAILED test_values.py::test_TestsRunAfterFailure[5] - assert 5 in [1, 2, 3, 4]
FAILED test_values.py::test_TestsRunAfterFailure[6] - assert 6 in [1, 2, 3, 4]
================================= 2 failed, 1 passed in 0.15s =================================

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章