Py.test重复循环执行测试

3 投票
1 回答
3071 浏览
提问于 2025-04-17 16:47

我想把测试重复执行N次(就是那些收集到的相同测试)。

为什么要这样做呢?因为我想看看测试的速度是否会变慢,或者我可以先收集一个参数的“平均时间”,然后再换一个参数,再次获取“平均时间”。

我理解是要使用 def pytest_runtestloop() 这个钩子,但我在这方面遇到了一些问题。

这是我为这个钩子写的代码:

def pytest_runtestloop(session):
    repeat = int(session.config.option.repeat)
    assert isinstance(repeat, int), "Repeat must be an integer"
    for i in range(repeat): #@UnusedVariable                      
        session.config.pluginmanager.getplugin("main").pytest_runtestloop(session)

    return True

问题在于“设置”只在第一次运行时执行

举个例子:

class TestSomething(object):

    @classmethod
    @pytest.fixture(scope = "class", autouse = True)
    def setup(self):
        //setup function

    def test_something(self):
        //test function

在这里,setup 只会在第一次循环时被调用,而如果我把 session.config.option.repeat 设置为2,test_something 会被调用两次。

我哪里做错了?有没有更好的方法?

1 个回答

2

看起来pytest-2.3.4内部保存了一些状态,这导致测试用例中的准备工作(fixtures)没有再次运行。pytest_runtest_loop这个功能并不是专门为你的情况设计的。你可以提交一个“bug”问题,我们可以看看能否解决这个问题。(我快速查看了一下,但没有立刻找到问题所在,还需要进一步探索。)

撰写回答