Over a million developers have joined DZone.

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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}