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
Python Method For Dynamically Creating Zope Interface Mock Classes
Given a Zope interface IFoo, the method below creates a Mock (<a href="http://www.voidspace.org.uk/python/mock">http://www.voidspace.org.uk/python/mock</a>) subclass IFooMock that properly implements IFoo.
See <a href="http://programmaticallyspeaking.com/?p=30">http://programmaticallyspeaking.com/?p=30</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





