我正在使用 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
但是结果表明它在第一个断言为假后停止。有没有更好的方法来做到这一点?
答案 0 :(得分:1)
测试是一个函数,问题在于您编写的代码只有一个测试 (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 =================================