循环测试函数时如何让Pytest识别迭代次数

2024-04-20 15:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用pytest做这个测试。你知道吗

我想多次执行相同的测试,同时更改种子输入。这将随机测试变量,我认为这是一个好主意。这样,如果测试失败,我可以使用相同的种子输入,在不同的环境中轻松地重新创建相同的测试,以查看失败的内容:

def test_foo():
    for i in range(0, 10):
        foo = random_foo('something', seed = i)

        assert subject_value(foo) == expected_value(foo)

但是,如果测试失败,Pytest不会告诉我发生AssertionError时的i值,这使得调试几乎不可能。有什么办法能成功做到这一点吗?或者这种糟糕的测试代码结构,在这种情况下,还有更好的方法吗?你知道吗


Tags: intest内容for环境foopytestvalue
1条回答
网友
1楼 · 发布于 2024-04-20 15:19:05

这个测试代码结构称为子测试。在您的例子中,循环的每个迭代都应该是一个新的子测试。你知道吗

你可能在找subtests plugin。你知道吗

import subtests

def test_foo():
    for i in range(10):
        with subtests.test(msg="seed", i=i):  # Add what you need to see here.
            foo = random_foo('something', seed=i)

            assert subject_value(foo) == expected_value(foo)

注意,标准库unittest.TestCasealready has支持使用with self.subTest()的子测试(从python3.4开始)。Pytest也可以运行这些标准测试用例。你知道吗


另外,如果您特别对随机测试输入感兴趣,您可能会对Hypothesis感兴趣。你知道吗

相关问题 更多 >