python - 即使其中一些失败,如何运行所有 PyTest 断言?

标签 python pytest

我正在寻找一种方法来运行我在 PyTest 中的单元测试中的所有断言,即使其中一些断言失败了。我知道必须有一个简单的方法来做到这一点。我检查了 CLI 选项并浏览了该站点以查找类似的问题/答案,但没有看到任何内容。抱歉,如果这个问题已经得到回答。

例如,考虑以下代码片段,旁边有 PyTest 代码:

def parrot(i):
    return i

def test_parrot():
    assert parrot(0) == 0
    assert parrot(1) == 1
    assert parrot(2) == 1
    assert parrot(2) == 2

默认情况下,执行在第一次失败时停止:

$ python -m pytest fail_me.py 
=================== test session starts ===================
platform linux2 -- Python 2.7.10, pytest-2.9.1, py-1.4.31, pluggy-0.3.1
rootdir: /home/npsrt/Documents/repo/codewars, inifile: 
collected 1 items 

fail_me.py F

=================== FAILURES ===================
___________________ test_parrot ___________________

    def test_parrot():
        assert parrot(0) == 0
        assert parrot(1) == 1
>       assert parrot(2) == 1
E       assert 2 == 1
E        +  where 2 = parrot(2)

fail_me.py:7: AssertionError
=================== 1 failed in 0.05 seconds ===================

我想做的是让代码在 PyTest 遇到第一次失败后继续执行。

最佳答案

正如其他人已经提到的,您最好编写多个测试并且每个测试只有一个断言(这不是硬性限制,而是一个很好的指导方针)。

@pytest.mark.parametrize装饰器使这变得简单:

import pytest

def parrot(i):
    return i

@pytest.mark.parametrize('inp, expected', [(0, 0), (1, 1), (2, 1), (2, 2)])
def test_parrot(inp, expected):
    assert parrot(inp) == expected

使用 -v 运行时:

parrot.py::test_parrot[0-0] PASSED
parrot.py::test_parrot[1-1] PASSED
parrot.py::test_parrot[2-1] FAILED
parrot.py::test_parrot[2-2] PASSED

=================================== FAILURES ===================================
_______________________________ test_parrot[2-1] _______________________________

inp = 2, expected = 1

    @pytest.mark.parametrize('inp, expected', [(0, 0), (1, 1), (2, 1), (2, 2)])
    def test_parrot(inp, expected):
>       assert parrot(inp) == expected
E       assert 2 == 1
E        +  where 2 = parrot(2)

parrot.py:8: AssertionError
====================== 1 failed, 3 passed in 0.01 seconds ======================

关于python - 即使其中一些失败,如何运行所有 PyTest 断言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36749796/

相关文章:

python - 支持两个数据库后端并保持我的代码干燥的最pythonic方式/技巧是什么?

python - __init__.py 中的类实现

python - 如何为参数列表中的每个项目运行 pytest 测试

python - 模拟 SQLAlchemy 的默认属性

python - 将 2d numpy 数组转换为列表列表

python - 我可以让 IDLE shell 显示函数的描述吗?

python - 无法弄清楚 TypeError : __init__() takes exactly 3 arguments (2 given)

python-2.7 - py.test "--collectonly doesn' t尊重-k”问题没有解决?

python - 如何分离测试和 fixture

python - 如何使用 pytest 测试不同模块中的相同功能