【问题标题】:What is the pytest equivalent for distinguishing test iterations using subtests使用子测试区分测试迭代的 pytest 等效项是什么
【发布时间】:2020-08-13 11:34:22
【问题描述】:

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", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

======================================================================
FAIL: test_even (__main__.NumbersTest) (i=5)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

如果不使用子测试,执行将在第一次失败后停止,并且错误将不太容易诊断,因为 i 的值不会显示。

当我使用 pytest 运行上述程序时,我看不到哪个测试失败了。 pytest不支持这个功能吗?

【问题讨论】:

    标签: python python-3.x pytest python-unittest


    【解决方案1】:

    你应该考虑参数化测试,而不是在测试用例中运行 for 循环。这是 pytest 为不同的输入值生成同一测试的多个实例的方式。

    pytest 文档有很多例子:

    https://docs.pytest.org/en/stable/parametrize.html

    【讨论】:

    • 你能举个例子吗
    • 你知道有没有办法循环文件吗?
    • 循环文件是什么意思?您是否在 python 文件中有一堆测试,并希望为一堆值执行所有测试,例如您拥有的范围示例?
    • 我只有一个要针对文件列表执行的测试。当我使用与问题中发布的相同示例时,为什么 pytest 无法返回失败的文件?
    • pytest 有一个名为 pytest_generate_tests 的钩子...您可以动态参数化任何测试。在您的情况下,您可以从您拥有它的目录中找到文件列表并将它们传递给测试..那应该解决.. pytest doc应该有相同的例子..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多