pytest中测试之间的间隔时间

4

在pytest中是否有常见的添加测试间隔的做法?目前集成测试失败,但如果单独运行测试则正常工作。

3个回答

16
你可以在pytest中使用autouse fixtures自动在测试用例之间进行休眠:
@pytest.fixture(autouse=True)
def slow_down_tests():
    yield
    time.sleep(1)

这个夹具将自动用于所有的测试用例并将执行权交给一个测试用例,以便它可以正常运行,但当测试结束时,执行权会回到这个夹具,然后睡眠将被执行。


3
如果您想对模块中的每个函数进行拆解:
import time
def teardown_function(function):   # the function parameter is optional
    time.sleep(3)

如果您想要在一个类中 为每个方法进行拆解,您有两个选项。
  1. 在这种情况下,您无法访问被调用的方法:
class TestClass:
    def teardown(self):
        time.sleep(1)
  1. 如果您需要访问它:
class TestClass:
    def teardown_method(self, method):
        print(method)
        time.sleep(1)

如果您想要一个拆解(teardown)函数,它将在类执行后被调用:
@classmethod
def teardown_class(cls):
    print(cls)
    time.sleep(2)

所有这些方法在设置方面的工作方式都相同。您可以查看文档。对于更复杂的实现,请使用固定装置

0

你可以在每个测试的拆卸方法中插入time.sleep(1),即:

class TestClass:
    def setup(self):
        pass

    def teardown(self):
        time.sleep(1) # sleep for 1 second

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接