2016-12-16 63 views
0

我有一个遵循Singleton模式的类,如下所示。在一个Python模块automaton.py我:在Python中创建可测试单例的最佳方法

class Automaton(object): 
    def launch_probe(self): 
     if hasattr(self, 'launched') and self.launched: 
      return 
     print "Launched!" 
     self.launched = True 

automaton = Automaton() 

我从各种其他模块的调用对象的方法,从内。无处将我实例化类,我希望是经常调用方法或访问属性,因此是很好的保持它简单的像这种访问:

from automaton import automaton 

automaton.launch_probe() 
print 'Status:' 
print automaton.launched 

不过,现在我工作的更好的测试验证码,并会喜欢在setUp()中的单元测试之间重置单例。

import automaton 

def setUp(): 
    automaton.automaton = automaton.Automaton() 

但是,由于其他加载的模块对原始单例的引用没有完成,因此无法完成工作。我可以切换到一个模式,我用Automaton.get_instance()获取单例,或者只是导入模块并引用该模块中的变量,但是我发现这使得主生产代码更加冗长和难以遵循。我考虑过试图使automaton变量成为描述符,因此它具有智能性,但发现描述符只能在类中使用。我正在考虑的最后一种方法是试图通过清除它的字典并将其称为__init__方法来重新初始化现有的Automaton实例。对于这样的东西,推荐的方法是什么?

+0

有许多可能的解决方案,也许不仅是一个推荐的方法(恕我直言)。我会添加一个'private'_reset()方法,确保干净的启动(无论何时需要,特别是在测试中)。但是,你真的需要一堂课吗?你的singleton可能只是自动机模块本身(因为它是一个对象)并定义了函数... –

+0

使用类的好处是所有的状态都被隐藏在它的实例的'__dict__'中,所以它更容易重置用于测试,而不是全局模块空间,其中包含其他字段,如'__name__'以及需要保留的函数或其他代码。 – penguin359

回答

0

之一许多可用的选项将提供一个方法来重置单身的状态为零(初始状态),例如:

class Automaton(object): 

    def __init__(self): 
     self.reset() 

    def reset(self): 
     self.launched = False 

    def launch_probe(self): 
     if hasattr(self, 'launched') and self.launched: 
      return 
     print("Launched!") 
     self.launched = True 

automaton = Automaton() 

if __name__ == "__main__": 
    import unittest 

    class Test(unittest.TestCase): 

     def setUp(self): 
      automaton.reset() 

     def test1(self): 
      automaton.launch_probe() 
      self.assertEqual(automaton.launched, True) 

     def test2(self): 
      self.assertEqual(automaton.launched, False) 

    unittest.main() 
相关问题