[TIP] mock a base class and imported modules?

skip at pobox.com skip at pobox.com
Fri Mar 9 13:07:46 PST 2012


    skip> Is there some way to mock the base class before importing the
    skip> module containing my class?

I continued poking around after posting, and stumbled upon this thread from
last June:

  http://lists.idyll.org/pipermail/testing-in-python/2011-June/004151.html

so I know now that I have to twiddle the __bases__ tuple of MyClass.  Alas,
I can't seem to make that work:

    >>> MyClass.__bases__ = (mock.MagicMock(),)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: MyClass.__bases__ must be tuple of old- or new-style classes, not 'MagicMock'
    >>> MyClass.__bases__ = (mock.MagicMock,)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: __bases__ assignment: 'MagicMock' deallocator differs from 'gobject.GObject'

I thought maybe that second error was because object.GObject subclasses need
to be explicitly registered, but I get the same error whan I use a simple
dummy new style class:

    >>> class X(object):
    ...   pass
    ...
    >>> X.__bases__ = (mock.MagicMock,)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: __bases__ assignment: 'MagicMock' deallocator differs from 'object'

Couldn't make it work substituting a classic class either:

    >>> class B:
    ...   pass
    ...
    >>> class Y(B):
    ...   pass
    ...
    >>> Y.__bases__ = (mock.MagicMock,)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: __bases__ items must be classes
    >>> mock.MagicMock
    <class 'mock.MagicMock'>

I'm using Python 2.7.  I must be missing something basic here, but can't
figure out what...

S



More information about the testing-in-python mailing list