使用Python unittes缓存setUp()的结果

2024-04-20 00:57:21 发布

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

我现在有一个unittest.TestCase看起来像。。

class test_appletrailer(unittest.TestCase):
    def setup(self):
        self.all_trailers = Trailers(res = "720", verbose = True)

    def test_has_trailers(self):
        self.failUnless(len(self.all_trailers) > 1)

    # ..more tests..

这很好,但是Trailers()调用需要大约2秒才能运行。。假设在运行每个测试之前调用了setUp(),那么测试现在运行大约需要10秒(只有3个测试函数)

在测试之间缓存self.all_trailers变量的正确方法是什么?

删除安装功能,并执行。。

class test_appletrailer(unittest.TestCase):
    all_trailers = Trailers(res = "720", verbose = True)

…可以,但是它声称“在0.000秒内运行了3个测试”,这是不正确的。。我唯一能想到的另一种方法是使用一个cache_trailes全局变量(它工作正常,但相当糟糕):

cache_trailers = None
class test_appletrailer(unittest.TestCase):
    def setUp(self):
        global cache_trailers
        if cache_trailers is None:
            cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True)
        else:
            self.all_trailers = cache_trailers

Tags: testselftruecacheverbosedefsetupres