python - 使用 Python unittest 缓存 setUp() 的结果

标签 python unit-testing

我目前有一个 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 变量的正确方法是什么?

删除 setUp 函数,然后做..

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

..有效,但随后它声称“在 0.000 秒内进行了 3 次测试”,这是不正确的。我能想到的唯一其他方法是使用 cache_trailers 全局变量(它工作正常,但相当可怕):

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

最佳答案

使用只初始化一次的类成员怎么样?

class test_appletrailer(unittest.TestCase):

    all_trailers = None

    def setup(self):
        # Only initialize all_trailers once.
        if self.all_trailers is None:
            self.__class__.all_trailers = Trailers(res = "720", verbose = True)

引用 self.all_trailers 的查找将转到 MRO 中的下一步-- self.__class__.all_trailers,将被初始化。

关于python - 使用 Python unittest 缓存 setUp() 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/402483/

相关文章:

python - 扩展 pygame Sprite 类

python - 在 Django 项目上运行syncdb 不起作用 : Can't create/write to file

python - 如何移动一个矩形及其关联的绘图(Pygame)?

C# - 如何模拟 this.GetType().Assembly

c - 使用硬编码内存地址主机测试 C 程序

angularjs - 如何在 Jasmine 中模拟 response.headers ('location' )?

python - 如何提取元组列表的信息以及如何每行写入多个信息?

python - 手动安装pysam报错: "ImportError: No module named version"

java - 单元测试未初始化

c# - 单元测试 IServiceCollection 注册