{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner

Python Method For Dynamically Creating Zope Interface Mock Classes

Given a Zope interface IFoo, the method below creates a Mock (http://www.voidspace.org.uk/python/mock) subclass IFooMock that properly implements IFoo.

See http://programmaticallyspeaking.com/?p=30 for more info.

from mock import Mock
from zope.interface import classImplements
import types

def create_interface_mock(interface_class):
    """Dynamically create a Mock sub class that implements the given Zope interface class."""

    # the init method, automatically specifying the interface methods
    def init(self, *args, **kwargs):
        Mock.__init__(self, spec=interface_class.names(),
                      *args, **kwargs)

    # we derive the sub class name from the interface name
    name = interface_class.__name__ + "Mock"

    # create the class object and provide the init method
    klass = types.TypeType(name, (Mock, ), {"__init__": init})

    # the new class should implement the interface
    classImplements(klass, interface_class)

    # make the class available to unit tests
    globals()[name] = klass
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks