DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Python Method For Dynamically Creating Zope Interface Mock Classes

  • submit to reddit
        Given a Zope interface IFoo, the method below creates a Mock (<a href=""></a>) subclass IFooMock that properly implements IFoo.

See <a href=""></a> 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