我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用zope.interface.Interface()。
def registerAdapter(adapterFactory, origInterface, *interfaceClasses): """Register an adapter class. An adapter class is expected to implement the given interface, by adapting instances implementing 'origInterface'. An adapter class's __init__ method should accept one parameter, an instance implementing 'origInterface'. """ self = globalRegistry assert interfaceClasses, "You need to pass an Interface" global ALLOW_DUPLICATES # deal with class->interface adapters: if not isinstance(origInterface, interface.InterfaceClass): origInterface = declarations.implementedBy(origInterface) for interfaceClass in interfaceClasses: factory = _registered(self, origInterface, interfaceClass) if factory is not None and not ALLOW_DUPLICATES: raise ValueError("an adapter (%s) was already registered." % (factory, )) for interfaceClass in interfaceClasses: self.register([origInterface], interfaceClass, '', adapterFactory)
def test_classProvides_before_implements(): """Special descriptor for class __provides__ The descriptor caches the implementedBy info, so that we can get declarations for objects without instance-specific interfaces a bit quicker. For example:: >>> from zope.interface import Interface >>> class IFooFactory(Interface): ... pass >>> class IFoo(Interface): ... pass >>> class C(object): ... classProvides(IFooFactory) ... implements(IFoo) >>> [i.getName() for i in C.__provides__] ['IFooFactory'] >>> [i.getName() for i in C().__provides__] ['IFoo'] """
def testExtraArgs(self): class I(Interface): def f(a): pass class C(object): def f(self, a, b): pass implements(I) self.assertRaises(BrokenMethodImplementation, verifyClass, I, C) C.f=lambda self, a: None verifyClass(I, C) C.f=lambda self, a, b=None: None verifyClass(I, C)
def load_contenttype(_context, contenttype): conf = contenttype['config'] klass = contenttype['klass'] if 'schema' in conf: classImplements(klass, conf['schema']) from plone.server.content import ResourceFactory factory = ResourceFactory( klass, title='', description='', portal_type=conf['portal_type'], schema=resolve_or_get(conf.get('schema', Interface)), behaviors=[resolve_or_get(b) for b in conf.get('behaviors', []) or ()], add_permission=conf.get('add_permission') or DEFAULT_ADD_PERMISSION, allowed_types=conf.get('allowed_types', None) ) zcml.utility( _context, provides=IResourceFactory, component=factory, name=conf['portal_type'], )
def test_called_from_function(self): import warnings from guillotina.component._declaration import adapts from zope.interface import Interface class IFoo(Interface): pass globs = {'adapts': adapts, 'IFoo': IFoo} locs = {} CODE = "\n".join([ 'def foo():', ' adapts(IFoo)' ]) if self._run_generated_code(CODE, globs, locs, False): foo = locs['foo'] with warnings.catch_warnings(record=True) as log: warnings.resetwarnings() self.assertRaises(TypeError, foo) self.assertEqual(len(log), 0) # no longer warn
def test_get_interfaces_explicit(self): from zope.interface import Interface from zope.interface import implementer class IFoo(Interface): pass class IBar(Interface): pass class IBaz(Interface): pass @implementer(IBaz) def _callable(): pass factory = self._makeOne(_callable, interfaces=(IFoo, IBar)) spec = factory.get_interfaces() self.assertEqual(spec.__name__, '_callable') self.assertEqual(list(spec), [IFoo, IBar])
def test_anonymous_no_provides_no_adapts(self): from zope.interface import Interface from zope.interface import implementer from guillotina.component.globalregistry import get_global_components from guillotina.component._declaration import adapter class IFoo(Interface): pass class IBar(Interface): pass @implementer(IFoo) class Foo(object): pass @adapter(IFoo) @implementer(IBar) class Bar(object): def __init__(self, context): self.context = context self._callFUT(Bar) gsm = get_global_components() foo = Foo() adapted = gsm.getAdapter(foo, IBar) self.assertTrue(isinstance(adapted, Bar)) self.assertTrue(adapted.context is foo)
def test_named_w_provides_w_adapts(self): from zope.interface import Interface from zope.interface import implementer from guillotina.component.globalregistry import get_global_components class IFoo(Interface): pass class IBar(Interface): pass @implementer(IFoo) class Foo(object): pass class Bar(object): def __init__(self, context): self.context = context self._callFUT(Bar, (IFoo,), IBar, 'test') gsm = get_global_components() foo = Foo() adapted = gsm.getAdapter(foo, IBar, name='test') self.assertTrue(isinstance(adapted, Bar)) self.assertTrue(adapted.context is foo)
def test_w_provides_w_adapts(self): from zope.interface import Interface from zope.interface import implementer from guillotina.component.globalregistry import get_global_components class IFoo(Interface): pass class IBar(Interface): pass @implementer(IFoo) class Foo(object): pass class Bar(object): def __init__(self, context): self.context = context self._callFUT(Bar, (IFoo,), IBar) gsm = get_global_components() foo = Foo() adapted = gsm.subscribers((foo,), IBar) self.assertEqual(len(adapted), 1) self.assertTrue(isinstance(adapted[0], Bar)) self.assertTrue(adapted[0].context is foo)
def test_no_adapts(self): from zope.interface import Interface from zope.interface import implementer from zope.interface import providedBy from guillotina.component.globalregistry import get_global_components from guillotina.component._declaration import adapter class IFoo(Interface): pass @implementer(IFoo) class Foo(object): pass @adapter(IFoo) def _handler(context): assert 0, "DON'T GO HERE" self._callFUT(_handler) gsm = get_global_components() regs = list(gsm.registeredHandlers()) self.assertEqual(len(regs), 1) hr = regs[0] self.assertEqual(list(hr.required), list(providedBy(Foo()))) self.assertEqual(hr.name, '') self.assertTrue(hr.factory is _handler)
def test_anonymous_hit(self): from zope.interface import Interface from zope.interface import implementer from guillotina.component import get_global_components class IFoo(Interface): pass class IBar(Interface): pass @implementer(IBar) class Bar(object): pass @implementer(IFoo) class Baz(object): def __init__(self, context): self.context = context get_global_components().registerAdapter(Baz, (IBar,), IFoo, '') bar = Bar() adapted = self._callFUT(bar, IFoo, '') self.assertTrue(adapted.__class__ is Baz) self.assertTrue(adapted.context is bar)
def test_named_hit(self): from zope.interface import Interface from zope.interface import implementer from guillotina.component import get_global_components class IFoo(Interface): pass class IBar(Interface): pass @implementer(IBar) class Bar(object): pass @implementer(IFoo) class Baz(object): def __init__(self, context): self.context = context get_global_components().registerAdapter(Baz, (IBar,), IFoo, 'named') bar = Bar() adapted = self._callFUT(bar, IFoo, 'named') self.assertTrue(adapted.__class__ is Baz) self.assertTrue(adapted.context is bar)
def test_anonymous_hit_registered_for_None(self): from zope.interface import Interface from zope.interface import implementer from guillotina.component import get_global_components class IFoo(Interface): pass class IBar(Interface): pass class IBaz(Interface): pass @implementer(IBar) class Bar(object): pass @implementer(IFoo) class FooAdapter(object): def __init__(self, first, second): self.first, self.second = first, second get_global_components().registerAdapter( FooAdapter, (IBar, None), IFoo, '') bar = Bar() baz = object() adapted = self._callFUT((bar, baz), IFoo, '') self.assertTrue(adapted.__class__ is FooAdapter) self.assertTrue(adapted.first is bar) self.assertTrue(adapted.second is baz)
def test_wo_sitemanager(self): from zope.interface import Interface from zope.interface import implementer from guillotina.component.interfaces import ComponentLookupError class IFoo(Interface): pass class IBar(Interface): pass class IBaz(Interface): pass @implementer(IBar) class Bar(object): pass @implementer(IBaz) class Baz(object): pass class Context(object): def __conform__(self, iface): raise ComponentLookupError bar = Bar() baz = Baz() adapted = self._callFUT((bar, baz), IFoo, '', context=Context()) self.assertTrue(adapted is None)
def test_hit(self): from zope.interface import Interface from guillotina.component import get_global_components class IFoo(Interface): pass class BarAdapter(object): def __init__(self, context): self.context = context class BazAdapter(object): def __init__(self, context): self.context = context gsm = get_global_components() gsm.registerAdapter(BarAdapter, (None,), IFoo) gsm.registerAdapter(BazAdapter, (None,), IFoo, name='bar') tuples = list(self._callFUT((object(),), IFoo)) self.assertEqual(len(tuples), 2) names = [(x, y.__class__.__name__) for x, y in tuples] self.assertTrue(('', 'BarAdapter') in names) self.assertTrue(('bar', 'BazAdapter') in names)
def test_wo_sitemanager(self): from zope.interface import Interface from zope.interface import implementer from guillotina.component.interfaces import ComponentLookupError class IFoo(Interface): pass class IBar(Interface): pass class IBaz(Interface): pass @implementer(IBar) class Bar(object): pass @implementer(IBaz) class Baz(object): pass class Context(object): def __conform__(self, iface): raise ComponentLookupError bar = Bar() baz = Baz() adapted = self._callFUT((bar, baz), IFoo, context=Context()) self.assertEqual(adapted, [])
def test_hit(self): from zope.interface import Interface from guillotina.component import get_global_components class IFoo(Interface): pass class BarAdapter(object): def __init__(self, context): self.context = context class BazAdapter(object): def __init__(self, context): self.context = context gsm = get_global_components() gsm.registerSubscriptionAdapter(BarAdapter, (None,), IFoo) gsm.registerSubscriptionAdapter(BazAdapter, (None,), IFoo) subscribers = self._callFUT((object(),), IFoo) self.assertEqual(len(subscribers), 2) names = [(x.__class__.__name__) for x in subscribers] self.assertTrue('BarAdapter' in names) self.assertTrue('BazAdapter' in names)
def test_hit(self): from guillotina.component import get_global_components from zope.interface import Interface from zope.interface import implementer class IFoo(Interface): pass @implementer(IFoo) class Foo(object): pass _called = [] def _bar(context): _called.append('_bar') def _baz(context): _called.append('_baz') gsm = get_global_components() gsm.registerHandler(_bar, (IFoo,)) gsm.registerHandler(_baz, (IFoo,)) self._callFUT(Foo()) self.assertEqual(len(_called), 2, _called) self.assertTrue('_bar' in _called) self.assertTrue('_baz' in _called)
def test_w_conforming_context(self): from zope.interface import Interface from guillotina.component import get_global_components from guillotina.component.tests.examples import ConformsToIComponentLookup class SM(object): def __init__(self, obj): self._obj = obj def queryUtility(self, interface, name, default): return self._obj class IFoo(Interface): pass obj1 = object() obj2 = object() sm = SM(obj2) context = ConformsToIComponentLookup(sm) get_global_components().registerUtility(obj1, IFoo) self.assertTrue(self._callFUT(IFoo, context=context) is obj2)
def test_hit(self): from zope.interface import Interface from guillotina.component import get_global_components class IFoo(Interface): pass class IBar(IFoo): pass obj = object() obj1 = object() obj2 = object() get_global_components().registerUtility(obj, IFoo) get_global_components().registerUtility(obj1, IFoo, name='bar') get_global_components().registerUtility(obj2, IBar) uts = list(self._callFUT(IFoo)) self.assertEqual(len(uts), 3) self.assertTrue(obj in uts) self.assertTrue(obj1 in uts) self.assertTrue(obj2 in uts)
def test_w_factory_returning_spec(self): from zope.interface import Interface from zope.interface import implementer from zope.interface import providedBy from guillotina.component.interfaces import IFactory class IFoo(Interface): pass class IBar(Interface): pass @implementer(IFoo, IBar) class _Factory(object): def get_interfaces(self): return providedBy(self) _factory = _Factory() class Context(object): def __conform__(self, iface): return self def getUtilitiesFor(self, iface): if iface is IFactory: return [('test', _factory)] self.assertEqual(list(self._callFUT(IFoo, context=Context())), [('test', _factory)]) self.assertEqual(list(self._callFUT(IBar, context=Context())), [('test', _factory)])
def test_w_factory_returning_list_of_interfaces(self): from zope.interface import Interface from guillotina.component.interfaces import IFactory class IFoo(Interface): pass class IBar(Interface): pass class _Factory(object): def get_interfaces(self): return [IFoo, IBar] _factory = _Factory() class Context(object): def __conform__(self, iface): return self def getUtilitiesFor(self, iface): if iface is IFactory: return [('test', _factory)] self.assertEqual(list(self._callFUT(IFoo, context=Context())), [('test', _factory)]) self.assertEqual(list(self._callFUT(IBar, context=Context())), [('test', _factory)])
def _makeMyUtility(name, sm): global IMyUtility from zope.interface import Interface from zope.interface import implementer from guillotina.component.tests.examples import ConformsToIComponentLookup if IMyUtility is None: class IMyUtility(Interface): pass @implementer(IMyUtility) class MyUtility(ConformsToIComponentLookup): def __init__(self, id, sm): self.id = id self.sitemanager = sm return MyUtility(name, sm)
def query_multi_adapter(objects, interface=Interface, name=_BLANK, default=None, context=None, args=[], kwargs={}): try: registry = get_component_registry(context) except ComponentLookupError: # Oh blast, no site manager. This should *never* happen! return default factory = registry.adapters.lookup(map(providedBy, objects), interface, name) if factory is None: return default result = factory(*objects, *args, **kwargs) if result is None: return default return result
def get_multi_adapter(objects, interface=Interface, name='', context=None): """Look for a multi-adapter to an interface for an objects Returns a multi-adapter that can adapt objects to interface. If a matching adapter cannot be found, raises ComponentLookupError. If context is None, an application-defined policy is used to choose an appropriate service manager from which to get an 'Adapters' service. If 'context' is not None, context is adapted to IServiceService, and this adapter's 'Adapters' service is used. The name consisting of an empty string is reserved for unnamed adapters. The unnamed adapter methods will often call the named adapter methods with an empty string for a name. """
def test_multiple_factory_multiple_for_(self): from zope.interface import Interface from guillotina.configure.component import ComponentConfigurationError class IFoo(Interface): pass class IBar(Interface): pass class Foo(object): pass class Bar(object): pass _cfg_ctx = _makeConfigContext() self.assertRaises(ComponentConfigurationError, self._callFUT, _cfg_ctx, [Foo, Bar], [Interface, IBar], IFoo)
def test_no_name(self): from zope.interface import Interface class IFoo(Interface): pass class IBar(Interface): pass from guillotina.component import adapter from zope.interface import implementer, named @adapter(IFoo) @implementer(IBar) @named('bar') class _Factory(object): def __init__(self, context): self.context = context _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, [_Factory]) # Register the adapter action = _cfg_ctx._actions[0][1] self.assertEqual(action['args'][4], 'bar')
def test_no_factory_w_handler_no_provides(self): from zope.interface import Interface from guillotina.component.interface import provide_interface from guillotina.configure.component import handler def _handler(*args): pass _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, (Interface,), handler=_handler) self.assertEqual(len(_cfg_ctx._actions), 2) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the adapter action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'][0], 'registerHandler') self.assertEqual(action['args'][1], _handler) self.assertEqual(action['args'][2], (Interface,)) self.assertEqual(action['args'][3], '') # Register the required interface(s) self.assertEqual(_cfg_ctx._actions[1][0], ()) action = _cfg_ctx._actions[1][1] self.assertEqual(action['callable'], provide_interface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', Interface))
def test_w_component_wo_provides_wo_name(self): from zope.interface import Interface, implementer, named class IFoo(Interface): pass @implementer(IFoo) @named('foo') class Foo(object): pass foo = Foo() _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, component=foo) action = _cfg_ctx._actions[0][1] self.assertEqual(action['args'][1], foo) self.assertEqual(action['args'][2], IFoo) self.assertEqual(action['args'][3], 'foo')
def test_w_name_w_type(self): from zope.interface import Interface from guillotina.component.interface import provide_interface class IFoo(Interface): pass class IBar(Interface): pass _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, IFoo, name='foo', type=IBar) self.assertEqual(len(_cfg_ctx._actions), 1) self.assertEqual(_cfg_ctx._actions[0][0], ()) action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], provide_interface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('foo', IFoo, IBar))
def load_contenttype(_context, contenttype): conf = contenttype['config'] klass = contenttype['klass'] if 'schema' in conf: classImplements(klass, conf['schema']) from guillotina.content import ResourceFactory factory = ResourceFactory( klass, title='', description='', type_name=conf['type_name'], schema=resolve_dotted_name(conf.get('schema', Interface)), behaviors=[resolve_dotted_name(b) for b in conf.get('behaviors', []) or ()], add_permission=conf.get('add_permission') or DEFAULT_ADD_PERMISSION, allowed_types=conf.get('allowed_types', None) ) component.utility( _context, provides=IResourceFactory, component=factory, name=conf['type_name'], )
def test_set_w_writer(self): from zope.interface import Interface class IFoo(Interface): getter = self._makeOne() getter = IFoo['getter'] _called_with = [] class Writer(object): pass writer = Writer() writer.__name__ = 'setMe' getter.writer = writer class Foo(object): def setMe(self, value): _called_with.append(value) getter.set(Foo(), '456') self.assertEqual(_called_with, ['456'])
def test_w_only_read_accessor(self): from zope.interface import Interface from guillotina.schema import Text field = Text(title='Hmm', readonly=True) class IFoo(Interface): getter, = self._callFUT(field) getter = IFoo['getter'] self.assertEqual(getter.__name__, 'getter') self.assertEqual(getter.__doc__, 'get Hmm') self.assertEqual(getter.getSignatureString(), '()') info = getter.getSignatureInfo() self.assertEqual(info['positional'], ()) self.assertEqual(info['required'], ()) self.assertEqual(info['optional'], ()) self.assertEqual(info['varargs'], None) self.assertEqual(info['kwargs'], None)
def test_ctor_additional_interfaces(self): from zope.interface import Interface from guillotina.schema.vocabulary import SimpleTerm class IStupid(Interface): pass VALUES = [1, 4, 2, 9] vocabulary = self._makeOne([SimpleTerm(x) for x in VALUES], IStupid) self.assertTrue(IStupid.providedBy(vocabulary)) self.assertEqual(len(vocabulary), len(VALUES)) for value, term in zip(VALUES, vocabulary): self.assertEqual(term.value, value) for value in VALUES: self.assertTrue(value in vocabulary) self.assertFalse('ABC' in vocabulary) for term in vocabulary: self.assertTrue(vocabulary.getTerm(term.value) is term) self.assertTrue(vocabulary.getTermByToken(term.token) is term)
def test_fromItems(self): from zope.interface import Interface from guillotina.schema.interfaces import ITokenizedTerm class IStupid(Interface): pass ITEMS = [('one', 1), ('two', 2), ('three', 3), ('fore!', 4)] vocabulary = self._getTargetClass().fromItems(ITEMS) self.assertEqual(len(vocabulary), len(ITEMS)) for item, term in zip(ITEMS, vocabulary): self.assertTrue(ITokenizedTerm.providedBy(term)) self.assertEqual(term.token, item[0]) self.assertEqual(term.value, item[1]) for item in ITEMS: self.assertTrue(item[1] in vocabulary)
def _makeSchema(): from zope.interface import Interface from guillotina.schema import Bytes class ISchemaTest(Interface): title = Bytes( title="Title", description="Title", default=b"", required=True) description = Bytes( title="Description", description="Description", default=b"", required=True) spam = Bytes( title="Spam", description="Spam", default=b"", required=True) return ISchemaTest
def build_firewall_activation_commands(self): """ When services VLANs are defined, the firewalls will need to have the services VLANs added to them. """ ns = {} section = Template("""<appendix><title>Firewall Activation Commands</title> $sections </appendix> """) ns['sections'] = '' subinterface_section = Template("""<section> <title>Configure Firewall Sub-Interface</title> $subinterface_commands </section> """) ns['subinterface_commands'] = "<screen>%s</screen>" % '\n'.join( self.build_firewall_subinterface_commands() ) ns['sections'] += subinterface_section.safe_substitute(ns) return section.safe_substitute(ns)
def test_asStructuredText_empty_with_multiline_docstring(self): from zope.interface import Interface EXPECTED = '\n'.join([ "IEmpty", "", " This is an empty interface.", " ", (" It can be used to annotate any class or object, " "because it promises"), " nothing.", "", " Attributes:", "", " Methods:", "", "" ]) class IEmpty(Interface): """ This is an empty interface. It can be used to annotate any class or object, because it promises nothing. """ self.assertEqual(self._callFUT(IEmpty), EXPECTED)
def test_asStructuredText_with_attribute_no_docstring(self): from zope.interface import Attribute from zope.interface import Interface EXPECTED = '\n\n'.join([ "IHasAttribute", " This interface has an attribute.", " Attributes:", " an_attribute -- no documentation", " Methods:", "" ]) class IHasAttribute(Interface): """ This interface has an attribute. """ an_attribute = Attribute('an_attribute') self.assertEqual(self._callFUT(IHasAttribute), EXPECTED)
def test_asStructuredText_with_method_no_args_no_docstring(self): from zope.interface import Interface EXPECTED = '\n\n'.join([ "IHasMethod", " This interface has a method.", " Attributes:", " Methods:", " aMethod() -- no documentation", "" ]) class IHasMethod(Interface): """ This interface has a method. """ def aMethod(): pass self.assertEqual(self._callFUT(IHasMethod), EXPECTED)
def test_asStructuredText_with_method_positional_args_no_docstring(self): from zope.interface import Interface EXPECTED = '\n\n'.join([ "IHasMethod", " This interface has a method.", " Attributes:", " Methods:", " aMethod(first, second) -- no documentation", "" ]) class IHasMethod(Interface): """ This interface has a method. """ def aMethod(first, second): pass self.assertEqual(self._callFUT(IHasMethod), EXPECTED)
def test_asStructuredText_with_method_starargs_no_docstring(self): from zope.interface import Interface EXPECTED = '\n\n'.join([ "IHasMethod", " This interface has a method.", " Attributes:", " Methods:", " aMethod(first, second, *rest) -- no documentation", "" ]) class IHasMethod(Interface): """ This interface has a method. """ def aMethod(first, second, *rest): pass self.assertEqual(self._callFUT(IHasMethod), EXPECTED)
def test_asStructuredText_with_method_kwargs_no_docstring(self): from zope.interface import Interface EXPECTED = '\n\n'.join([ "IHasMethod", " This interface has a method.", " Attributes:", " Methods:", " aMethod(first, second, **kw) -- no documentation", "" ]) class IHasMethod(Interface): """ This interface has a method. """ def aMethod(first, second, **kw): pass self.assertEqual(self._callFUT(IHasMethod), EXPECTED)
def test_asStructuredText_with_method_with_docstring(self): from zope.interface import Interface EXPECTED = '\n\n'.join([ "IHasMethod", " This interface has a method.", " Attributes:", " Methods:", " aMethod() -- This method is documented.", "" ]) class IHasMethod(Interface): """ This interface has a method. """ def aMethod(): """This method is documented. """ self.assertEqual(self._callFUT(IHasMethod), EXPECTED)
def _registerAdapterForClassOrInterface(self, original): adapter = lambda o: None class TheInterface(Interface): pass components.registerAdapter(adapter, original, TheInterface) self.assertIdentical( components.getAdapterFactory(original, TheInterface, None), adapter)