使用 Python unittest 缓存 setUp() 的结果 [英] Caching result of setUp() using Python unittest
问题描述
我目前有一个 unittest.TestCase 看起来像..
I currently have a unittest.TestCase that looks like..
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 个测试函数)
This works fine, but the Trailers()
call takes about 2 seconds to run.. Given that setUp()
is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions)
在测试之间缓存 self.all_trailers
变量的正确方法是什么?
What is the correct way of caching the self.all_trailers
variable between tests?
去掉setUp函数,然后做..
Removing the setUp function, and doing..
class test_appletrailer(unittest.TestCase):
all_trailers = Trailers(res = "720", verbose = True)
..有效,但随后它声称在 0.000 秒内进行了 3 次测试",这是不正确的.我能想到的唯一另一种方法是拥有一个 cache_trailers 全局变量(它工作正常,但相当可怕):
..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache_trailers global variable (which works correctly, but is rather horrible):
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
推荐答案
如何使用只初始化一次的类成员?
How about using a class member that only gets initialized once?
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
,将被初始化.
Lookups that refer to self.all_trailers
will go to the next step in the MRO -- self.__class__.all_trailers
, which will be initialized.
这篇关于使用 Python unittest 缓存 setUp() 的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!