【发布时间】:2016-04-20 16:25:03
【问题描述】:
我正在寻找一种方法来运行我在 PyTest 中的单元测试中的所有断言,即使其中一些失败。我知道必须有一个简单的方法来做到这一点。我检查了 CLI 选项并浏览了该站点以查找类似的问题/答案,但没有看到任何内容。对不起,如果这已经回答了。
例如,考虑以下代码 sn-p,旁边有 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 遇到第一次失败后继续执行。
【问题讨论】:
-
另见this question
unittest,由一堆非常相似的问题链接到 -
@pytest.mark.parametrize是您正在寻找的。它需要 2 个参数,将提供数据的变量名称,以及您希望提供给测试的数据。因此,要实现您想要的,可以执行以下操作。 @pytest.mark.parametrize('parrot_num', (1, 2, 3, 4, 5)) def parrot(parrot_num): return parrot_num def test_parrot(): assert parrot(0) == 0 assert parrot(1) = = 1 断言鹦鹉(2) == 1 断言鹦鹉(2) == 2