Qiangning Hong wrote: > As you see, it is an OO wrapper on _extmod, which is a pyrex extension > module. The question is: how to unittest this class? As the _extmod > is hardware-dependent, I want to use a mock class to replace it in unit > test. But how can I let myclass in unittest to import the mock class? > Like the following: > > class MyClassTest(unittest.TestCase): > def setUp(self): > import myclass > import mocklib > myclass.change_extmod(mocklib.MockExtMod()) > self.testobj = myclass.MyClass() # here MyClass.__init__ will > call the open > # method of MockExtMod class > instead of > # _extmod.open() > ... > > How to implement the change_extmod? (Or maybe my idea is totally > wrong?) >
One way is simply to do: def setUp(self): import myclass self.real_extmod = myclass._extmod myclass._extmod = mocklib.MockExtMod() self.testobj = myclass.MyClass() def tearDown(self): import myclass if hasattr(self, testobj): del self.testobj myclass._extmod = self.real_extmod This can be less intrusive than passing the mock object to a constructor, but it depends very much on the way the objects are used: changing global state for a unit test is a risky business, for example if an exception is thrown then tearDown would be called *before* your __del__ method is invoked. You can work round this by ensuring that the _extmod value is saved in your instance but that takes you pretty much back to André Malo's suggestion. BTW, accessing a global variable from a __del__ method is a bad idea generally: there is no guarantee that the global variable will still be set if __del__ is called during program exit. -- http://mail.python.org/mailman/listinfo/python-list