问题描述
Distinguishing test iterations using subtests
class NumbersTest(unittest.TestCase):
def test_even(self):
"""
Test that numbers between 0 and 5 are all even.
"""
for i in range(0,6):
with self.subTest(i=i):
self.assertEqual(i % 2,0)
输出:
FAIL: test_even (__main__.NumbersTest) (i=1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "subtests.py",line 32,in test_even
self.assertEqual(i % 2,0)
AssertionError: 1 != 0
======================================================================
FAIL: test_even (__main__.NumbersTest) (i=3)
----------------------------------------------------------------------
Traceback (most recent call last):
File "subtests.py",0)
AssertionError: 1 != 0
======================================================================
FAIL: test_even (__main__.NumbersTest) (i=5)
----------------------------------------------------------------------
Traceback (most recent call last):
File "subtests.py",0)
AssertionError: 1 != 0
如果不使用子测试,则在第一次失败后将停止执行,并且由于不显示i的值,因此错误不易诊断。
当我使用pytest运行以上命令时,则看不到哪个测试失败。 pytest不支持此功能吗?
解决方法
U应该考虑对测试进行参数化,而不是在测试用例内部运行for循环。.pytest就是为不同的输入值生成同一测试的多个实例的方式。
pytest文档有很多示例: