unittest help

Scott David Daniels Scott.Daniels at Acm.Org
Thu Mar 24 08:54:35 EST 2005


Duncan Booth wrote:
> 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:

Given:
 >>  # file: myclass.py
 >>  import _extmod
 >>  class MyClass(object):
 >>      def __init__(self):
 >>          self.handle = _extmod.open()
 >>  ...

One other way to do your unit test stuff is:
     # file: test_myclass.py

     import sys, bogus_extmod     # First, get the fake hardware
     sys.modules['_extmod'] = bogus_extmod # then make that active

     import myclass, unittest  # and now do all you normally would do
     ...
     class SimplestTests(unittest.TestCase):
         ...

Note that the "module switch" must happen very early (probably at
the top of the main program).

--Scott David Daniels
Scott.Daniels at Acm.Org




More information about the Python-list mailing list