unittest help

Qiangning Hong hongqn at gmail.com
Thu Mar 24 11:45:43 CET 2005


I want to apply TDD (test driven development) on my project.  I am
working on a class like this (in plan):

# file: myclass.py
import _extmod

class MyClass(object):
    def __init__(self):
        self.handle = _extmod.open()

    def __del__(self):
        _extmod.close(self.handle)

    def some_stuff(self):
        _extmod.foobar(self.handle)

    ...

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?)




More information about the Python-list mailing list