[TIP] mocking out mixins and subclasses

Michael Foord fuzzyman at voidspace.org.uk
Mon Mar 5 12:55:01 PST 2007


Nate Lowrie wrote:
> On 3/5/07, Michael Foord <fuzzyman at voidspace.org.uk> wrote:
>> Nate Lowrie wrote:
>> > I have several mixin classes that are subclassed by other classes.  I
>> > am unit testing the mixin classes on there own. Some of the classes
>> > that subclass these mixins call the mixin functions in some of the
>> > methods.  I know that I can rebind the methods to mocked function
>> > after I instantiate an object but there are some calls to the mixin
>> > methods in the init section as well.  Ideally, I would like to mock
>> > the mixin before creating any objects.
>> >
>> > How are other people handling unit testing for mixins and objects
>> > using the mixin?  Is there an easy way to do this that I am
>> > overlooking?
>> >
>> Hmm... mocking out base classes before instantiation is something I
>> haven't had to do.
>>
>> As the code snippet below shows, you can do it by assigning to
>> '__bases__', to swap out the base class.
>>
>>  >>> class x(object):
>> ...  z = 3
>> ...
>>  >>> class y(object):
>> ...  z = 6
>> ...
>>  >>> class z(x):
>> ...  pass
>> ...
>>  >>> z.z
>> 3
>>  >>> z.__bases__
>> (<class '__main__.x'>,)
>>  >>> z.__bases__ = (y,)
>>  >>> z.z
>> 6
>>
Posted in true doctest style as well. ;-)


Fuzzyman





More information about the testing-in-python mailing list