[TIP] mock a base class and imported modules?

skip at pobox.com skip at pobox.com
Fri Mar 9 11:44:57 PST 2012


I have a class to test which subclasses gobject.GObject:

    http://www.pygtk.org/docs/pygobject/class-gobject.html

I don't really need much of the base class for my testing except the ability
to emit signals.  Is there some way to mock the base class before importing
the module containing my class?  Skeletal example:

    import gobject
    import another_module

    class MyClass(gobject.GObject):
        def __init__(self, ...)
            gobject.GObject.__init__(self)
            ...

        def some_method(self, ...);
            x = another_module.SomeClass()
            ...

        def another_method(self, ...):
            ...
            self.emit("mysignal", ...)

The emit method comes from the base class.

Reading the documentation for the patch decorator it's not clear to me that
mock will get a shot at replacing the gobject.GObject reference before
MyClass is defined.  I assume (without empirical proof at this point) that I
will be able to use patch to stub out another_module.SomeClass though, since
it isn't used until I have a MyClass instance.

Any suggestions appreciated.  (Mock usage is still very new to me.  You will
probably have to use very small words and speak slowly.)

Thx,

-- 
Skip Montanaro - skip at pobox.com - http://www.smontanaro.net/



More information about the testing-in-python mailing list