PK±†h4~ø7óÌÌzope/__init__.py# namespace package boilerplate try: __import__('pkg_resources').declare_namespace(__name__) except ImportError, e: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) PK¶“„4¶!èg‰‰zope/__init__.pyc;ò ^RDc@sOyedƒieƒWn1ej o%ZdklZeeeƒZnXdS(s pkg_resources(s extend_pathN(s __import__sdeclare_namespaces__name__s ImportErrorsespkgutils extend_paths__path__(ses extend_paths__path__((s+build/bdist.linux-i686/egg/zope/__init__.pys?s PKPs„4h0½@"zope/component/contextdependent.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """A simple mix-in class that implements IContextDependent. $Id: contextdependent.py 25177 2004-06-02 13:17:31Z jim $ """ from zope.component.interfaces import IContextDependent from zope.interface import implements class ContextDependent(object): """standard boilerplate for context dependent objects""" implements(IContextDependent) def __init__(self, context): self.context = context PKPs„4ÔÌæ–G–Gzope/component/presentation.py############################################################################## # # Copyright (c) 2003 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Global Presentation Service This module contains an adapter-registry-based global presentation service. Additionally it contains all registration classes that can occur: - SkinRegistration - LayerRegistration - DefaultSkinRegistration - PresentationRegistration $Id: presentation.py 27309 2004-08-27 21:01:06Z jim $ """ from types import ClassType from zope.component.interfaces import IPresentationService, IRegistry from zope.component.service import GlobalService from zope.component.servicenames import Presentation from zope.interface import providedBy from zope.interface.interfaces import IInterface import zope.interface import zope.interface.adapter class IGlobalPresentationService(zope.interface.Interface): """Provide ability to update the global presentation service """ def defineSkin(name, layers): """Define a skin A skin is defined for a request type. It consists of a sequence of layer names. Layers must be defined before they are used in a skin definition. Note that there is one predefined layer, "default". """ def setDefaultSkin(name): """Set the default skin for a request type If not set, it defaults to the "default" skin. """ def defineLayer(name): """Define a layer """ def provideAdapter(request_type, factory, name='', contexts=(), providing=zope.interface.Interface, layer='default'): """Provide a presentation adapter """ class IDefaultViewName(zope.interface.Interface): """A string that contains the default view name A default view name is used to select a view when a user hasn't specified one. """ class GlobalPresentationService(GlobalService): r"""Global presentation service The global presentation service provides management of views, and resources arranged in skins, where skins are ordered collections of layers. Views are modeled as adapters of objects and requests. Resources are just request adapters. The adapters are arranged in layers. Let's look at some examples. First, we'll create a service: >>> s = GlobalPresentationService() And define a custom layer and skin: >>> s.defineLayer('custom') >>> s.defineSkin('custom', ['custom', 'default']) We'll define a request type and a fake request: >>> class IRequest(zope.interface.Interface): ... "Demonstration request type" >>> class Request(object): ... zope.interface.implements(IRequest) ... def getPresentationSkin(self): ... return getattr(self, 'skin', None) >>> request = Request() With this in place, we can start registering resources. A resource is just a request adapter. >>> class MyResource(object): ... def __init__(self, request): ... self.request = request To register a resource, we register it as an adapter. Most resources are going to interface with a user, and, so, don't really provide a programatic interface. For this reason, we register them to provide the empty interface, Interface, which is the default provided interface: >>> s.provideAdapter(IRequest, MyResource, name='foo', layer='custom') Now we can try to look this up: >>> s.queryResource('foo', request) But we won't get anything, because our request doesn't specify a skin and, the default skin gets used. Our resource was registered in the custom layer, which isn't used by the default skin. If we set out request skin to 'custom': >>> request.skin = 'custom' Then the lookup will suceed: >>> r = s.queryResource('foo', request) >>> r.__class__.__name__ 'MyResource' >>> r.request is request True Views are registered as "multi" adapters. Multi-adapters adapt multiple objects simultaneously. >>> class IContact(zope.interface.Interface): ... "Demonstration content type" >>> class MyView(object): ... def __init__(self, context, request): ... self.context, self.request = context, request >>> s.provideAdapter(IRequest, MyView, contexts=[IContact], ... name='foo', layer='custom') When defining views, we provide one or more (typically 1) context interfaces, corresponding to the contexts of the view. >>> class Contact(object): ... zope.interface.implements(IContact) >>> c = Contact() We look up views with queryView: >>> v = s.queryView(c, 'foo', request) >>> v.__class__.__name__ 'MyView' >>> v.request is request True >>> v.context is c True Most views and resources are unnamed and provide no interface. We can also have views that provide interfaces. For example, we might need a view to help out with finding objects: >>> class ITraverse(zope.interface.Interface): ... "Sample traversal interface (imagine interesting methods :)" >>> class Traverser(object): ... zope.interface.implements(ITraverse) ... def __init__(self, context, request): ... self.context, self.request = context, request which we register using the provided interface, rather than a name. >>> s.provideAdapter(IRequest, Traverser, contexts=[IContact], ... providing=ITraverse, layer='custom') (We could use a name too, if we wanted to.) Then we look up the view using the interface: >>> v = s.queryView(c, '', request, providing=ITraverse) >>> v.__class__.__name__ 'Traverser' >>> v.request is request True >>> v.context is c True """ zope.interface.implements(IPresentationService, IGlobalPresentationService, IRegistry, ) def __init__(self): self._layers = {'default': GlobalLayer(self, 'default')} self._skins = {'default': [self._layers['default']]} self.skins = {'default': ('default', )} self.defaultSkin = 'default' self._registrations = {} def registrations(self): return self._registrations.itervalues() def defineSkin(self, name, layers, info=''): """Define a skin A skin is defined for a request type. It consists of a sequence of layer names. Layers must be defined before they are used in a skin definition. Note that there is one predefined layer, "default". >>> s = GlobalPresentationService() >>> s.defineSkin('default', ['default']) Traceback (most recent call last): ... ValueError: ("Can\'t redefine skin", 'default') The layers used in a skin definition must be defined before they are used: >>> s.defineSkin('custom', ['custom', 'default']) Traceback (most recent call last): ... ValueError: ('Undefined layers', ['custom']) >>> s.defineLayer('custom') >>> s.defineSkin('custom', ['custom', 'default'], 'custom doc') >>> skins = s.skins.items() >>> skins.sort() >>> skins [('custom', ('custom', 'default')), ('default', ('default',))] A skin registration is also recorded for each registered skin. >>> registrations = map(str, s.registrations()) >>> registrations.sort() >>> for r in registrations: ... print r zope.component.presentation.LayerRegistration('custom', '') zope.component.presentation.SkinRegistration('custom', """ \ """['custom', 'default'], 'custom doc') """ if name in self._skins: raise ValueError("Can't redefine skin", name) bad = [layer for layer in layers if layer not in self._layers] if bad: raise ValueError, ("Undefined layers", bad) self._skins[name] = [self._layers[layer] for layer in layers] self.skins[name] = tuple(layers) self._registrations[('skin', name) ] = SkinRegistration(name, layers, info) def querySkin(self, name): return self.skins.get(name) def queryLayer(self, name): return self._layers.get(name) def setDefaultSkin(self, name, info=''): """Set the default skin for a request type If not set, it defaults to the "default" skin. >>> s = GlobalPresentationService() >>> s.defaultSkin 'default' >>> s.setDefaultSkin('custom') Traceback (most recent call last): ... ValueError: ('Undefined skin', 'custom') >>> s.defineLayer('custom') >>> s.defineSkin('custom', ['custom', 'default']) >>> s.setDefaultSkin('custom', 'yawn') >>> s.defaultSkin 'custom' A default skin registration is also recorded for each registered default skin. >>> registrations = map(str, s.registrations()) >>> registrations.sort() >>> for r in registrations: ... print r zope.component.presentation.DefaultSkinRegistration('custom', 'yawn') zope.component.presentation.LayerRegistration('custom', '') zope.component.presentation.SkinRegistration('custom', """ \ """['custom', 'default'], '') """ # Make sure we are refering to a defined skin if name not in self._skins: raise ValueError, ("Undefined skin", name) self.defaultSkin = name self._registrations['defaultSkin' ] = DefaultSkinRegistration(name, info) def defineLayer(self, name, info=''): """Define a layer >>> s = GlobalPresentationService() >>> s.defineLayer('custom', 'blah') You can't define a layer that's already defined: >>> s.defineLayer('custom') Traceback (most recent call last): ... ValueError: ("Can\'t redefine layer", 'custom') A layer registration is also recorded for each registered layer. >>> list(s.registrations()) [zope.component.presentation.LayerRegistration('custom', 'blah')] """ if name in self._layers: raise ValueError("Can\'t redefine layer", name) self._layers[name] = GlobalLayer(self, name) self._registrations[('layer', name)] = LayerRegistration(name, info) def provideAdapter(self, request_type, factory, name=u'', contexts=(), providing=zope.interface.Interface, layer='default', info=''): """Provide a presentation adapter This is a fairly low-level interface that supports both resources and views. """ ifaces = [] for context in contexts: if not IInterface.providedBy(context) and context is not None: if not isinstance(context, (type, ClassType)): raise TypeError(context, IInterface) context = zope.interface.implementedBy(context) ifaces.append(context) ifaces.append(request_type) ifaces = tuple(ifaces) reg = self._layers[layer] reg.register(ifaces, providing, name, factory) self._registrations[ (layer, ifaces, providing, name) ] = PresentationRegistration(layer, ifaces, providing, name, factory, info) def queryResource(self, name, request, default=None, providing=zope.interface.Interface): """Look up a named resource for a given request The request must implement IPresentationRequest. The default will be returned if the component can't be found. """ skin = request.getPresentationSkin() or self.defaultSkin for layer in self._skins[skin]: r = layer.queryAdapter(request, providing, name) if r is not None: return r return default def queryView(self, object, name, request, providing=zope.interface.Interface, default=None): """Look for a named view for a given object and request The request must implement IPresentationRequest. The default will be returned if the component can't be found. """ skin = request.getPresentationSkin() or self.defaultSkin objects = object, request for layer in self._skins.get(skin, ()): r = layer.queryMultiAdapter(objects, providing, name) if r is not None: return r return default def queryMultiView(self, objects, request, providing=zope.interface.Interface, name='', default=None): """Adapt the given objects and request The first argument is a sequence of objects to be adapted with the request. """ skin = request.getPresentationSkin() or self.defaultSkin objects = objects + (request, ) for layer in self._skins[skin]: r = layer.queryMultiAdapter(objects, providing, name) if r is not None: return r return default ############################################################ # # The following methods are provided for convenience and for # backward compatability with old code: def provideView(self, for_, name, type, maker, layer='default', providing=zope.interface.Interface): # Helper function for simple view defs return self.provideAdapter(type, maker, name, contexts=[for_], layer=layer, providing=providing) def setDefaultViewName(self, for_, request_type, name, layer="default"): """Default view names A default view name is a name that an application should use if a user hasn't selected one. This should not be confused with unnamed views. The presentation service can store this by storing the name as an "adapter". """ return self.provideAdapter(request_type, name, providing=IDefaultViewName, contexts=[for_], layer=layer) def queryDefaultViewName(self, object, request, default=None): skin = request.getPresentationSkin() or 'default' objects = object, request for layer in self._skins[skin]: r = layer.lookup(map(providedBy, objects), IDefaultViewName) if r is not None: return r return default def provideResource(self, name, request_type, factory, layer='default', providing=zope.interface.Interface): # Helper function for simple view defs return self.provideAdapter(request_type, factory, name, layer=layer, providing=providing) def GL(presentation_service, layer_name): return presentation_service.queryLayer(layer_name) class GlobalLayer(zope.interface.adapter.AdapterRegistry): def __init__(self, parent, name): super(GlobalLayer, self).__init__() self.__parent__ = parent self.__name__ = name def __reduce__(self): return GL, (self.__parent__, self.__name__) class SkinRegistration(object): """Registration for a global skin.""" def __init__(self, skin, layers, info): self.skin, self.layers, self.doc = skin, layers, info def __repr__(self): """Representation of the object in a doctest-friendly format.""" return '%s.%s(%r, %r, %r)' % ( self.__class__.__module__, self.__class__.__name__, self.skin, self.layers, self.doc) class LayerRegistration(object): """Registration for a global layer.""" def __init__(self, layer, info): self.layer, self.doc = layer, info def __repr__(self): """Representation of the object in a doctest-friendly format.""" return '%s.%s(%r, %r)' % ( self.__class__.__module__, self.__class__.__name__, self.layer, self.doc) class DefaultSkinRegistration(object): """Registration for the global default skin.""" def __init__(self, skin, info): self.skin, self.doc = skin, info def __repr__(self): """Representation of the object in a doctest-friendly format.""" return '%s.%s(%r, %r)' % ( self.__class__.__module__, self.__class__.__name__, self.skin, self.doc) class PresentationRegistration(object): """Registration for a single presentation component.""" def __init__(self, layer, required, provided, name, factory, info): (self.layer, self.required, self.provided, self.name, self.factory, self.doc ) = layer, required, provided, name, factory, info def __repr__(self): """Representation of the object in a doctest-friendly format.""" return '%s.%s(%s, %r, %r, %r, %r, %r)' % ( self.__class__.__module__, self.__class__.__name__, self.layer, tuple([getattr(s, '__name__', None) for s in self.required]), self.provided.__name__, self.name, getattr(self.factory, '__name__', self.factory), self.doc) PKPs„4ÉÁð1Î%Î%zope/component/__init__.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Zope 3 Component Architecture $Id: __init__.py 27075 2004-08-12 19:16:05Z srichter $ """ import sys import warnings from zope.interface import moduleProvides, Interface from zope.interface.interfaces import IInterface from zope.component.interfaces import IComponentArchitecture, IFactory from zope.component.interfaces import IServiceService from zope.component.exceptions import ComponentLookupError from zope.component.service import serviceManager from zope.component.servicenames import Adapters, Presentation, Utilities # Try to be hookable. Do so in a try/except to avoid a hard dependency. try: from zope.hookable import hookable except ImportError: def hookable(ob): return ob moduleProvides(IComponentArchitecture) __all__ = tuple(IComponentArchitecture) def warningLevel(): """Returns the number of the first stack frame outside of zope.component""" try: level = 2 while sys._getframe(level).f_globals['__name__'] == 'zope.component': level += 1 return level except ValueError: return 2 def getGlobalServices(): return serviceManager def getGlobalService(name): return serviceManager.getService(name) def getServices(context=None): if context is None: return serviceManager else: # Use the global service manager to adapt context to IServiceService # to avoid the recursion implied by using a local getAdapter call. try: return IServiceService(context) except TypeError, error: raise ComponentLookupError(*error.args) getServices = hookable(getServices) def getService(name, context=None): return getServices(context).getService(name) def getServiceDefinitions(context=None): return getServices(context).getServiceDefinitions() # Utility service def getUtility(interface, name='', context=None): return getService(Utilities, context=context).getUtility(interface, name) def queryUtility(interface, name='', default=None, context=None): return getService(Utilities, context).queryUtility( interface, name, default) def getUtilitiesFor(interface, context=None): if not IInterface.providedBy(interface): raise TypeError("getUtilitiesFor got nonsense arguments." " Check that you are updated with the" " component API change.") return getService(Utilities, context).getUtilitiesFor(interface) def getAllUtilitiesRegisteredFor(interface, context=None): return getService(Utilities, context ).getAllUtilitiesRegisteredFor(interface) # Adapter service def getAdapterInContext(object, interface, context): adapter = queryAdapterInContext(object, interface, context) if adapter is None: raise ComponentLookupError(object, interface) return adapter def queryAdapterInContext(object, interface, context, default=None): conform = getattr(object, '__conform__', None) if conform is not None: try: adapter = conform(interface) except TypeError: # We got a TypeError. It might be an error raised by # the __conform__ implementation, or *we* may have # made the TypeError by calling an unbound method # (object is a class). In the later case, we behave # as though there is no __conform__ method. We can # detect this case by checking whether there is more # than one traceback object in the traceback chain: if sys.exc_info()[2].tb_next is not None: # There is more than one entry in the chain, so # reraise the error: raise # This clever trick is from Phillip Eby else: if adapter is not None: return adapter if interface.providedBy(object): return object adapters = getService(Adapters, context) return adapters.queryAdapter(object, interface, '', default) def getAdapter(object, interface, name, context=None): adapter = queryAdapter(object, interface, name, None, context) if adapter is None: raise ComponentLookupError(object, interface) return adapter def adapter_hook(interface, object, name='', default=None): try: adapters = getService(Adapters) except ComponentLookupError: # Oh blast, no adapter service. We're probably just running # from a test return None return adapters.queryAdapter(object, interface, name, default) adapter_hook = hookable(adapter_hook) import zope.interface.interface zope.interface.interface.adapter_hooks.append(adapter_hook) def queryAdapter(object, interface, name, default=None, context=None): if context is None: return adapter_hook(interface, object, name, default) adapters = getService(Adapters, context) return adapters.queryAdapter(object, interface, name, default) def getMultiAdapter(objects, interface, name=u'', context=None): adapter = queryMultiAdapter(objects, interface, name, context=context) if adapter is None: raise ComponentLookupError(objects, interface) return adapter def queryMultiAdapter(objects, interface, name=u'', default=None, context=None): try: adapters = getService(Adapters, context) except ComponentLookupError: # Oh blast, no adapter service. We're probably just running from a test return default return adapters.queryMultiAdapter(objects, interface, name, default) def subscribers(objects, interface, context=None): try: adapters = getService(Adapters, context=context) except ComponentLookupError: # Oh blast, no adapter service. We're probably just running from a test return [] return adapters.subscribers(objects, interface) # Factories def createObject(context, name, *args, **kwargs): return getUtility(IFactory, name, context)(*args, **kwargs) def getFactoryInterfaces(name, context=None): return getUtility(IFactory, name, context).getInterfaces() def getFactoriesFor(interface, context=None): utils = getService(Utilities, context) for (name, factory) in utils.getUtilitiesFor(IFactory): interfaces = factory.getInterfaces() try: if interfaces.isOrExtends(interface): yield name, factory except AttributeError: for iface in interfaces: if iface.isOrExtends(interface): yield name, factory break # Presentation service def getView(object, name, request, providing=Interface, context=None): view = queryView(object, name, request, context=context, providing=providing) if view is not None: return view raise ComponentLookupError("Couldn't find view", name, object, context, request) def queryView(object, name, request, default=None, providing=Interface, context=None): s = getService(Presentation, context=context) return s.queryView(object, name, request, default=default, providing=providing) queryView = hookable(queryView) def getMultiView(objects, request, providing=Interface, name='', context=None): view = queryMultiView(objects, request, providing, name, context=context) if view is not None: return view raise ComponentLookupError("Couldn't find view", name, object, context, request) def queryMultiView(objects, request, providing=Interface, name='', default=None, context=None): s = getService(Presentation, context) return s.queryMultiView(objects, request, providing, name, default) def getViewProviding(object, providing, request, context=None): return getView(object, '', request, providing, context) def queryViewProviding(object, providing, request, default=None, context=None): return queryView(object, '', request, default, providing, context) def getDefaultViewName(object, request, context=None): view = queryDefaultViewName(object, request, context=context) if view is not None: return view raise ComponentLookupError("Couldn't find default view name", context, request) def queryDefaultViewName(object, request, default=None, context=None): s = getService(Presentation, context) return s.queryDefaultViewName(object, request, default) def getResource(name, request, providing=Interface, context=None): view = queryResource(name, request, providing=providing, context=context) if view is not None: return view raise ComponentLookupError("Couldn't find resource", name, request) def queryResource(name, request, default=None, providing=Interface, context=None): s = getService(Presentation, context) return s.queryResource(name, request, default=default, providing=providing) PKPs„4Ò××>&&zope/component/adapter.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Global Adapter Service $Id: adapter.py 26080 2004-07-02 22:25:52Z jim $ """ from zope.component.exceptions import ComponentLookupError from zope.component.interfaces import IAdapterService, IRegistry from zope.component.service import GlobalService from zope.interface.adapter import AdapterRegistry from zope.interface import implements, providedBy, Interface import sys import warnings class IGlobalAdapterService(IAdapterService, IRegistry): def register(required, provided, name, factory, info=''): """Register an adapter factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the adapter - `info`: Provide some info about this particular adapter. """ def subscribe(required, provided, factory, info=''): """Register a subscriber factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the subscriber - `info`: Provide some info about this particular adapter. """ class AdapterService(AdapterRegistry): """Base implementation of an adapter service, implementing only the 'IAdapterService' interface. No write-methods were implemented. """ implements(IAdapterService) class GlobalAdapterService(AdapterService, GlobalService): """Global Adapter Service implementation.""" implements(IGlobalAdapterService) def __init__(self): AdapterRegistry.__init__(self) self._registrations = {} def register(self, required, provided, name, factory, info=''): """Register an adapter >>> registry = GlobalAdapterService() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.register((R1, ), P2, 'bob', 'c1', 'd1') >>> registry.register((R1, ), P2, '', 'c2', 'd2') >>> registry.lookup((R2, ), P1, '') 'c2' >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration AdapterRegistration(('R1',), 'P2', '', 'c2', 'd2') AdapterRegistration(('R1',), 'P2', 'bob', 'c1', 'd1') """ required = tuple(required) self._registrations[(required, provided, name)] = AdapterRegistration( required, provided, name, factory, info) AdapterService.register(self, required, provided, name, factory) def subscribe(self, required, provided, factory, info=''): """Register an subscriptions adapter >>> registry = GlobalAdapterService() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.subscribe((R1, ), P2, 'c1', 'd1') >>> registry.subscribe((R1, ), P2, 'c2', 'd2') >>> subscriptions = map(str, registry.subscriptions((R2, ), P1)) >>> subscriptions.sort() >>> subscriptions ['c1', 'c2'] >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration SubscriptionRegistration(('R1',), 'P2', 'c1', 'd1') SubscriptionRegistration(('R1',), 'P2', 'c2', 'd2') """ required = tuple(required) registration = SubscriptionRegistration( required, provided, factory, info) self._registrations[(required, provided)] = ( self._registrations.get((required, provided), ()) + (registration, ) ) AdapterService.subscribe(self, required, provided, factory) def registrations(self): for registration in self._registrations.itervalues(): if isinstance(registration, tuple): for r in registration: yield r else: yield registration class AdapterRegistration(object): """Registration for a simple adapter.""" def __init__(self, required, provided, name, value, doc=''): (self.required, self.provided, self.name, self.value, self.doc ) = required, provided, name, value, doc def __repr__(self): return '%s(%r, %r, %r, %r, %r)' % ( self.__class__.__name__, tuple([getattr(r, '__name__', None) for r in self.required]), self.provided.__name__, self.name, self.value, self.doc, ) class SubscriptionRegistration(object): """Registration for a subscription adapter.""" def __init__(self, required, provided, value, doc): (self.required, self.provided, self.value, self.doc ) = required, provided, value, doc def __repr__(self): return '%s(%r, %r, %r, %r)' % ( self.__class__.__name__, tuple([getattr(r, '__name__', None) for r in self.required]), self.provided.__name__, self.value, self.doc, ) PKPs„4À ±>>zope/component/service.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Service Manager implementation $Id: service.py 27082 2004-08-12 20:03:58Z srichter $ """ from zope.exceptions import DuplicationError from zope.component.interfaces import IServiceService from zope.component.exceptions import ComponentLookupError from zope.interface import implements class IGlobalServiceManager(IServiceService): def defineService(name, interface): """Define a new service of the given name implementing the given interface. If the name already exists, raises DuplicationError""" def provideService(name, component): """Register a service component. Provide a service component to do the work of the named service. If a service component has already been assigned to this name, raise DuplicationError; if the name has not been defined, raises UndefinedService; if the component does not implement the registered interface for the service name, raises InvalidService. """ class UndefinedService(Exception): """An attempt to register a service that has not been defined """ class InvalidService(Exception): """An attempt to register a service that doesn't implement the required interface """ class GlobalServiceManager(object): """service manager""" implements(IGlobalServiceManager) def __init__(self, name=None, module=None): self._clear() self.__name__ = name self.__module__ = module def _clear(self): self.__defs = {'Services': IServiceService} self.__services = {'Services': self} def __reduce__(self): # Global service managers are pickled as global objects return self.__name__ def defineService(self, name, interface): """see IGlobalServiceManager interface""" if name in self.__defs: raise DuplicationError(name) self.__defs[name] = interface def getServiceDefinitions(self): """see IServiceService Interface""" return self.__defs.items() def provideService(self, name, component, force=False): """see IGlobalServiceManager interface, above The force keyword allows one to replace an existing service. This is mostly useful in testing scenarios. """ if not force and name in self.__services: raise DuplicationError(name) if name not in self.__defs: raise UndefinedService(name) if not self.__defs[name].providedBy(component): raise InvalidService(name, component, self.__defs[name]) if isinstance(component, GlobalService): component.__parent__ = self component.__name__ = name self.__services[name] = component def getService(self, name): """see IServiceService interface""" service = self.__services.get(name) if service is None: raise ComponentLookupError(name) return service def GS(service_manager, service_name): return service_manager.getService(service_name) class GlobalService(object): def __reduce__(self): return GS, (self.__parent__, self.__name__) # the global service manager instance serviceManager = GlobalServiceManager('serviceManager', __name__) defineService = serviceManager.defineService # Register our cleanup with Testing.CleanUp to make writing unit tests # simpler. from zope.testing.cleanup import addCleanUp addCleanUp(serviceManager._clear) del addCleanUp PKPs„4Âô¦ennzope/component/exceptions.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Exceptions used by the Component Architecture $Id: exceptions.py 25177 2004-06-02 13:17:31Z jim $ """ from zope.exceptions import NotFoundError __all__ = ["ComponentLookupError", "Invalid", "Misused"] class ComponentLookupError(NotFoundError): """A component could not be found.""" class Invalid(Exception): """A component doesn't satisfy a promise.""" class Misused(Exception): """A component is being used (registered) for the wrong interface.""" PKPs„4Ž$R¶ØMØMzope/component/interfaces.py############################################################################ # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################ """Component and Component Architecture Interfaces $Id: interfaces.py 27076 2004-08-12 19:18:08Z srichter $ """ from zope.interface import Interface, Attribute from zope.component.exceptions import * class IComponentArchitecture(Interface): """The Component Architecture is defined by six key services, all of which are managed by service managers. """ # basic service manager tools def getGlobalServices(): """Get the global service manager.""" def getGlobalService(name): """Get a global service.""" def getServices(context=None): """Get the service manager If context is None, an application-defined policy is used to choose an appropriate service manager. If 'context' is not None, context is adapted to IServiceService, and this adapter is returned. """ def getService(name, context=None): """Get a named service. Returns the service defined by 'name' from the service manager. If context is None, an application-defined policy is used to choose an appropriate service manager. If 'context' is not None, context is adapted to IServiceService, and this adapter is returned. """ def getServiceDefinitions(context=None): """Get service definitions Returns a dictionary of the service definitions from the service manager in the format {nameString: serviceInterface}. The default behavior of placeful service managers is to include service definitions above them, but this can be overridden. If context is None, an application-defined policy is used to choose an appropriate service manager. If 'context' is not None, context is adapted to IServiceService, and this adapter is returned. """ # Utility service def getUtility(interface, name='', context=None): """Get the utility that provides interface Returns the nearest utility to the context that implements the specified interface. If one is not found, raises ComponentLookupError. """ def queryUtility(interface, name='', default=None, context=None): """Look for the utility that provides interface Returns the nearest utility to the context that implements the specified interface. If one is not found, returns default. """ def getUtilitiesFor(interface, context=None): """Return the utilities that provide an interface An iterable of utility name-value pairs is returned. """ def getAllUtilitiesRegisteredFor(interface, context=None): """Return all registered utilities for an interface This includes overwridden utilities. An iterable of utility instances is returned. No names are returned. """ # Adapter service def getAdapter(object, interface, name, context=''): """Get a named adapter to an interface for an object Returns an adapter that can adapt object 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. """ def getAdapterInContext(object, interface, context): """Get a special adapter to an interface for an object NOTE: This method should only be used if a custom context needs to be provided to provide custom component lookup. Otherwise, call the interface, as in:: interface(object) Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, raises ComponentLookupError. Context is adapted to IServiceService, and this adapter's 'Adapters' service is used. If the object has a __conform__ method, this method will be called with the requested interface. If the method returns a non-None value, that value will be returned. Otherwise, if the object already implements the interface, the object will be returned. """ def getMultiAdapter(objects, 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 queryAdapter(object, interface, name, default=None, context=None): """Look for a named adapter to an interface for an object Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, returns the default. 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. """ def queryAdapterInContext(object, interface, context, default=None): """Look for a special adapter to an interface for an object NOTE: This method should only be used if a custom context needs to be provided to provide custom component lookup. Otherwise, call the interface, as in:: interface(object, default) Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, returns the default. Context is adapted to IServiceService, and this adapter's 'Adapters' service is used. If the object has a __conform__ method, this method will be called with the requested interface. If the method returns a non-None value, that value will be returned. Otherwise, if the object already implements the interface, the object will be returned. """ def queryMultiAdapter(objects, interface, name='', default=None, context=None): """Look for a multi-adapter to an interface for objects Returns a multi-adapter that can adapt objects to interface. If a matching adapter cannot be found, returns the default. 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 subscribers(required, provided, context=None): """Get subscribers Subscribers are returned that provide the provided interface and that depend on and are computed from the sequence of required objects. 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. """ # Factory service # TODO: Hard to make context a keyword, leaving as it is. Maybe we should # at least move it to the second position. def createObject(context, name, *args, **kwargs): """Create an object using a factory Finds the factory of the given name that is nearest to the context, and passes the other given arguments to the factory to create a new instance. Returns a reference to the new object. If a matching factory cannot be found raises ComponentLookupError """ def getFactoryInterfaces(name, context=None): """Get interfaces implemented by a factory Finds the factory of the given name that is nearest to the context, and returns the interface or interface tuple that object instances created by the named factory will implement. """ def getFactoriesFor(interface, context=None): """Return a tuple (name, factory) of registered factories that create objects which implement the given interface. """ # Presentation service def getView(object, name, request, providing=Interface, context=None): """Get a named view for a given object. The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, raises ComponentLookupError. """ def queryView(object, name, request, default=None, providing=Interface, context=None): """Look for a named view for a given object. The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, returns default. If context is not specified, attempts to use object to specify a context. """ def getMultiView(objects, request, providing=Interface, name='', context=None): """Look for a multi-view for given objects The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, raises ComponentLookupError. If context is not specified, attempts to use the first object to specify a context. """ def queryMultiView(objects, request, providing=Interface, name='', default=None, context=None): """Look for a multi-view for given objects The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, returns default. If context is not specified, attempts to use the first object to specify a context. """ def getViewProviding(object, providing, request, context=None): """Look for a view based on the interface it provides. A call to this method is equivalent to: getView(object, '', request, context, providing) """ def queryViewProviding(object, providing, request, default=None, context=None): """Look for a view that provides the specified interface. A call to this method is equivalent to: queryView(object, '', request, default, context, providing) """ def getDefaultViewName(object, request, context=None): """Get the name of the default view for the object and request. The request must implement IPresentationRequest, and provides the desired view type. The nearest one to the object is found. If a matching default view name cannot be found, raises NotFoundError. If context is not specified, attempts to use object to specify a context. """ def queryDefaultViewName(object, request, default=None, context=None): """Look for the name of the default view for the object and request. The request must implement IPresentationRequest, and provides the desired view type. The nearest one to the object is found. If a matching default view name cannot be found, returns the default. If context is not specified, attempts to use object to specify a context. """ def getResource(name, request, providing=Interface, context=None): """Get a named resource for a given request The request must implement IPresentationRequest. The context provides a place to look for placeful resources. A ComponentLookupError will be raised if the component can't be found. """ def queryResource(name, request, default=None, providing=Interface, context=None): """Get a named resource for a given request The request must implement IPresentationRequest. The context provides a place to look for placeful resources. If the component can't be found, the default is returned. """ class IRegistry(Interface): """Object that supports component registry """ def registrations(): """Return an iterable of component registrations """ class IServiceService(Interface): """A service to manage Services.""" def getServiceDefinitions(): """Retrieve all Service Definitions Should return a list of tuples (name, interface) """ def getInterfaceFor(name): """Retrieve the service interface for the given name """ def getService(name): """Retrieve a service implementation Raises ComponentLookupError if the service can't be found. """ class IFactory(Interface): """A factory is responsible for creating other components.""" title = Attribute("The factory title.") description = Attribute("A brief description of the factory.") def __call__(*args, **kw): """Return an instance of the objects we're a factory for.""" def getInterfaces(): """Get the interfaces implemented by the factory Return the interface(s), as an instance of Implements, that objects created by this factory will implement. If the callable's Implements instance cannot be created, an empty Implements instance is returned. """ class IUtilityService(Interface): """A service to manage Utilities.""" def getUtility(interface, name=''): """Look up a utility that provides an interface. If one is not found, raises ComponentLookupError. """ def queryUtility(interface, name='', default=None): """Look up a utility that provides an interface. If one is not found, returns default. """ def getUtilitiesFor(interface): """Look up the registered utilities that provide an interface. Returns an iterable of name-utility pairs. """ def getAllUtilitiesRegisteredFor(interface): """Return all registered utilities for an interface This includes overwridden utilities. An iterable of utility instances is returned. No names are returned. """ class IContextDependent(Interface): """Components implementing this interface must have a context component. Usually the context must be one of the arguments of the constructor. Adapters and views are a primary example of context-dependent components. """ context = Attribute( """The context of the object This is the object being adapted, viewed, extended, etc. """) class IAdapterService(Interface): """A service to manage Adapters.""" def queryAdapter(object, interface, name, default=None): """Look for a named adapter to an interface for an object If a matching adapter cannot be found, returns the default. 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 queryMultiAdapter(objects, interface, name, default=None): """Look for a multi-adapter to an interface for an object If a matching adapter cannot be found, returns the default. 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 subscribers(required, provided): """Get subscribers Subscribers are returned that provide the provided interface and that depend on and are comuted from the sequence of required objects. """ class IPresentation(Interface): """Presentation components provide interfaces to external actors The are created for requests, which encapsulate external actors, connections, etc. """ request = Attribute( """The request The request is a surrogate for the user. It also provides the presentation type and skin. It is of type IPresentationRequest. """) class IPresentationRequest(Interface): """An IPresentationRequest provides methods for getting view meta data.""" def getPresentationSkin(): """Get the skin to be used for a request. The skin is a string as would be passed to IViewService.getView. """ class IResource(IPresentation): """Resources provide data to be used for presentation.""" class IResourceFactory(Interface): """A factory to create factories using the request.""" def __call__(request): """Create a resource for a request The request must be an IPresentationRequest. """ class IView(IPresentation, IContextDependent): """Views provide a connection between an external actor and an object""" class IViewFactory(Interface): """Objects for creating views""" def __call__(context, request): """Create an view (IView) object The context aregument is the object displayed by the view. The request argument is an object, such as a web request, that "stands in" for the user. """ class IPresentationService(Interface): """A service to manage Presentation components.""" def queryResource(name, request, default=None, providing=Interface): """Look up a named resource for a given request The request must implement IPresentationRequest. The default will be returned if the component can't be found. """ def queryView(object, name, request, default=None, providing=Interface): """Look for a named view for a given object and request The request must implement IPresentationRequest. The default will be returned if the component can't be found. """ def queryMultiView(objects, request, providing=Interface, name='', default=None): """Adapt the given objects and request The first argument is a tuple of objects to be adapted with the request. """ PKPs„4}%Æèƒ ƒ zope/component/utility.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """utility service $Id: utility.py 25389 2004-06-12 13:19:36Z alga $ """ from zope.component.exceptions import Invalid, ComponentLookupError from zope.component.interfaces import IUtilityService, IRegistry from zope.component.service import GlobalService from zope.interface.adapter import AdapterRegistry import zope.interface class IGlobalUtilityService(IUtilityService, IRegistry): def provideUtility(providedInterface, component, name=''): """Provide a utility A utility is a component that provides an interface. """ class UtilityService(AdapterRegistry): """Provide IUtilityService Mixin that superimposes utility management on adapter registery implementation """ def getUtility(self, interface, name=''): """See IUtilityService interface""" c = self.queryUtility(interface, name) if c is not None: return c raise ComponentLookupError(interface, name) def queryUtility(self, interface, name='', default=None): """See IUtilityService interface""" byname = self._null.get(interface) if byname: return byname.get(name, default) else: return default def getUtilitiesFor(self, interface): byname = self._null.get(interface) if byname: for item in byname.iteritems(): yield item def getAllUtilitiesRegisteredFor(self, interface): return iter(self._null.get(('s', interface)) or ()) class GlobalUtilityService(UtilityService, GlobalService): zope.interface.implementsOnly(IGlobalUtilityService) def __init__(self): UtilityService.__init__(self) self._registrations = {} def provideUtility(self, providedInterface, component, name='', info=''): if not providedInterface.providedBy(component): raise Invalid("The registered component doesn't implement " "the promised interface.") self.register((), providedInterface, name, component) # Also subscribe to support getAllUtilitiesRegisteredFor: self.subscribe((), providedInterface, component) self._registrations[(providedInterface, name)] = UtilityRegistration( providedInterface, name, component, info) def registrations(self): return self._registrations.itervalues() class UtilityRegistration(object): def __init__(self, provided, name, component, doc): (self.provided, self.name, self.component, self.doc ) = provided, name, component, doc def __repr__(self): return '%s(%r, %r, %r, %r)' % ( self.__class__.__name__, self.provided.__name__, self.name, getattr(self.component, '__name__', self.component), self.doc, ) PKPs„4f<:OOzope/component/servicenames.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Default service names for CA core services $Id: servicenames.py 25177 2004-06-02 13:17:31Z jim $ """ Adapters = 'Adapters' Utilities = 'Utilities' Presentation = 'Presentation' Services = 'Services' PKPs„4³Ù¶¿22zope/component/factory.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Factory object $Id: factory.py 27052 2004-08-12 15:45:44Z srichter $ """ from zope.interface import implements, implementedBy from zope.interface.declarations import Implements from zope.component.interfaces import IFactory class Factory(object): """Generic factory implementation. The purpose of this implementation is to provide a quick way of creating factories for classes, functions and other objects. """ implements(IFactory) def __init__(self, callable, title='', description='', interfaces=None): self._callable = callable self.title = title self.description = description self._interfaces = interfaces def __call__(self, *args, **kw): return self._callable(*args, **kw) def getInterfaces(self): if self._interfaces is not None: spec = Implements(*self._interfaces) spec.__name__ = getattr(self._callable, '__name__', '[callable]') return spec try: return implementedBy(self._callable) except TypeError: spec = Implements() spec.__name__ = getattr(self._callable, '__name__', '[callable]') return spec PKPs„4¶‡¼Å,,zope/component/DEPENDENCIES.cfgzope.exceptions zope.interface zope.testing PK]^„4«û<³MMzope/component/testing.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Placeless Test Setup $Id: testing.py 29152 2005-02-16 01:04:30Z jim $ """ from zope.testing import cleanup # A mix-in class inheriting from CleanUp that also connects the CA services class PlacelessSetup(cleanup.CleanUp): def setUp(self): super(PlacelessSetup, self).setUp() def tearDown(self): super(PlacelessSetup, self).tearDown() def setUp(test=None): cleanup.setUp() def tearDown(test=None): cleanup.tearDown() PK]^„4a˜*ùLùLzope/component/tests.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Component Architecture Tests $Id: test_api.py 28632 2004-12-16 17:42:59Z srichter $ """ import unittest from zope.interface import Interface, implements from zope.interface.verify import verifyObject from zope.testing import doctest import zope.component from zope.component.interfaces import ComponentLookupError from zope.component.interfaces import IComponentArchitecture from zope.component.interfaces import ISiteManager from zope.component.testing import setUp, tearDown class I1(Interface): pass class I2(Interface): pass class I3(Interface): pass class Ob(object): implements(I1) def __repr__(self): return '' ob = Ob() class Ob2(object): implements(I2) def __repr__(self): return '' class Comp(object): implements(I2) def __init__(self, context): self.context = context comp = Comp(1) class Comp2(object): implements(I3) def __init__(self, context): self.context = context class ConformsToISiteManager(object): """This object allows the sitemanager to conform/adapt to `ISiteManager` and thus to itself.""" def __init__(self, sitemanager): self.sitemanager = sitemanager def __conform__(self, interface): """This method is specified by the adapter PEP to do the adaptation.""" if interface is ISiteManager: return self.sitemanager def testInterfaces(): """Ensure that the component architecture API is provided by `zope.component`. >>> import zope.component >>> verifyObject(IComponentArchitecture, zope.component) True """ def test_getGlobalSiteManager(): """One of the most important functions is to get the global site manager. >>> from zope.component.site import IGlobalSiteManager, globalSiteManager Get the global site manager via the CA API function: >>> gsm = zope.component.getGlobalSiteManager() Make sure that the global site manager implements the correct interface and is the global site manager instance we expect to get. >>> IGlobalSiteManager.providedBy(gsm) True >>> globalSiteManager is gsm True Finally, ensure that we always get the same global site manager, otherwise our component registry will always be reset. >>> zope.component.getGlobalSiteManager() is gsm True """ def test_getSiteManager(): """Make sure that `getSiteManager()` always returns the correct site manager instance. We don't know anything about the default service manager, except that it is an `ISiteManager`. >>> ISiteManager.providedBy(zope.component.getSiteManager()) True Calling `getSiteManager()` with no args is equivalent to calling it with a context of `None`. >>> zope.component.getSiteManager() is zope.component.getSiteManager(None) True If the context passed to `getSiteManager()` is not `None`, it is adapted to `ISiteManager` and this adapter returned. So, we create a context that can be adapted to `ISiteManager` using the `__conform__` API. Let's create the simplest stub-implementation of a site manager possible: >>> sitemanager = object() Now create a context that knows how to adapt to our newly created site manager. >>> context = ConformsToISiteManager(sitemanager) Now make sure that the `getSiteManager()` API call returns the correct site manager. >>> zope.component.getSiteManager(context) is sitemanager True Using a context that is not adaptable to `ISiteManager` should fail. >>> zope.component.getSiteManager(ob) #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: ('Could not adapt', , ) """ def testAdapterInContext(self): """The `getAdapterInContext()` and `queryAdapterInContext()` API functions do not only use the site manager to look up the adapter, but first tries to use the `__conform__()` method of the object to find an adapter as specified by PEP 246. Let's start by creating a component that support's the PEP 246's `__conform__()` method: >>> class Component(object): ... implements(I1) ... def __conform__(self, iface, default=None): ... if iface == I2: ... return 42 ... def __repr__(self): ... return '''''' >>> ob = Component() We also gave the component a custom representation, so it will be easier to use in these tests. We now have to create a site manager (other than the default global one) with which we can register adapters for `I1`. >>> from zope.component.site import GlobalSiteManager >>> sitemanager = GlobalSiteManager() Now we create a new `context` that knows how to get to our custom site manager. >>> context = ConformsToISiteManager(sitemanager) We now register an adapter from `I1` to `I3`: >>> sitemanager.provideAdapter((I1,), I3, '', lambda x: 43) If an object implements the interface you want to adapt to, `getAdapterInContext()` should simply return the object. >>> zope.component.getAdapterInContext(ob, I1, context) >>> zope.component.queryAdapterInContext(ob, I1, context) If an object conforms to the interface you want to adapt to, `getAdapterInContext()` should simply return the conformed object. >>> zope.component.getAdapterInContext(ob, I2, context) 42 >>> zope.component.queryAdapterInContext(ob, I2, context) 42 If an adapter isn't registered for the given object and interface, and you provide no default, raise ComponentLookupError... >>> class I4(Interface): ... pass >>> zope.component.getAdapterInContext(ob, I4, context) \\ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, ) ...otherwise, you get the default: >>> zope.component.queryAdapterInContext(ob, I4, context, 44) 44 If you ask for an adapter for which something's registered you get the registered adapter >>> zope.component.getAdapterInContext(ob, I3, context) 43 >>> zope.component.queryAdapterInContext(ob, I3, context) 43 """ def testAdapter(): """The `getAdapter()` and `queryAdapter()` API functions are similar to `{get|query}AdapterInContext()` functions, except that they do not care about the `__conform__()` but also handle named adapters. (Actually, the name is a required argument.) If an adapter isn't registered for the given object and interface, and you provide no default, raise `ComponentLookupError`... >>> zope.component.getAdapter(ob, I2, '') #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, , '') ...otherwise, you get the default >>> zope.component.queryAdapter(ob, I2, '', '') '' Now get the global site manager and register an adapter from `I1` to `I2` without a name: >>> zope.component.getGlobalSiteManager().provideAdapter( ... (I1,), I2, '', Comp) You should get a sensible error message if you forget that the 'requires' argument is supposed to be a sequence >>> zope.component.getGlobalSiteManager().provideAdapter( ... I1, I2, '', Comp) Traceback (most recent call last): ... TypeError: the required argument should be a list of interfaces, not a single interface You can now simply access the adapter using the `getAdapter()` API function: >>> adapter = zope.component.getAdapter(ob, I2, '') >>> adapter.__class__ is Comp True >>> adapter.context is ob True """ def testInterfaceCall(): """Here we test the `adapter_hook()` function that we registered with the `zope.interface` adapter hook registry, so that we can call interfaces to do adaptation. First, we need to register an adapter: >>> zope.component.getGlobalSiteManager().provideAdapter( ... [I1], I2, '', Comp) Then we try to adapt `ob` to provide an `I2` interface by calling the `I2` interface with the obejct as first argument: >>> adapter = I2(ob) >>> adapter.__class__ is Comp True >>> adapter.context is ob True If no adapter is found, a `TypeError is raised... >>> I1(Ob2()) #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: ('Could not adapt', , ) ...unless we specify an alternative adapter: >>> marker = object() >>> I2(object(), marker) is marker True """ def testNamedAdapter(): """Make sure that adapters with names are correctly selected from the registry. First we register some named adapter: >>> zope.component.getGlobalSiteManager().provideAdapter( ... [I1], I2, 'foo', lambda x: 0) If an adapter isn't registered for the given object and interface, and you provide no default, raise `ComponentLookupError`... >>> zope.component.getAdapter(ob, I2, 'bar') \\ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, , 'bar') ...otherwise, you get the default >>> zope.component.queryAdapter(ob, I2, 'bar', '') '' But now we register an adapter for the object having the correct name >>> zope.component.getGlobalSiteManager().provideAdapter( ... [I1], I2, 'bar', Comp) so that the lookup succeeds: >>> adapter = zope.component.getAdapter(ob, I2, 'bar') >>> adapter.__class__ is Comp True >>> adapter.context is ob True """ def testMultiAdapter(): """Adapting a combination of 2 objects to an interface Multi-adapters adapt one or more objects to another interface. To make this demonstration non-trivial, we need to create a second object to be adapted: >>> ob2 = Ob2() Like for regular adapters, if an adapter isn't registered for the given objects and interface, and you provide no default, raise `ComponentLookupError`... >>> zope.component.getMultiAdapter((ob, ob2), I3) \\ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: ((, ), , u'') ...otherwise, you get the default >>> zope.component.queryMultiAdapter((ob, ob2), I3, default='') '' Note that the name is not a required attribute here. To test multi-adapters, we also have to create an adapter class that handles to context objects: >>> class DoubleAdapter(object): ... implements(I3) ... def __init__(self, first, second): ... self.first = first ... self.second = second Now we can register the multi-adapter using >>> zope.component.getGlobalSiteManager().provideAdapter( ... (I1, I2), I3, '', DoubleAdapter) Notice how the required interfaces are simply provided by a tuple. Now we can get the adapter: >>> adapter = zope.component.getMultiAdapter((ob, ob2), I3) >>> adapter.__class__ is DoubleAdapter True >>> adapter.first is ob True >>> adapter.second is ob2 True """ def testAdapterForInterfaceNone(): """Providing an adapter for None says that your adapter can adapt anything to `I2`. >>> zope.component.getGlobalSiteManager().provideAdapter( ... (None,), I2, '', Comp) >>> adapter = I2(ob) >>> adapter.__class__ is Comp True >>> adapter.context is ob True It can really adapt any arbitrary object: >>> something = object() >>> adapter = I2(something) >>> adapter.__class__ is Comp True >>> adapter.context is something True """ def testGetAdapters(): """It is sometimes desireable to get a list of all adapters that are registered for a particular output interface, given a set of objects. Let's register some adapters first: >>> zope.component.getGlobalSiteManager().provideAdapter( ... [I1], I2, '', Comp) >>> zope.component.getGlobalSiteManager().provideAdapter( ... [None], I2, 'foo', Comp) Now we get all the adapters that are registered for `ob` that provide `I2`: >>> adapters = zope.component.getAdapters((ob,), I2) >>> adapters.sort() >>> [(name, adapter.__class__.__name__) for name, adapter in adapters] [(u'', 'Comp'), (u'foo', 'Comp')] Note that the output doesn't include None values. If an adapter factory returns None, it is as if it wasn't present. >>> zope.component.getGlobalSiteManager().provideAdapter( ... [I1], I2, 'nah', lambda context: None) >>> adapters = zope.component.getAdapters((ob,), I2) >>> adapters.sort() >>> [(name, adapter.__class__.__name__) for name, adapter in adapters] [(u'', 'Comp'), (u'foo', 'Comp')] """ def testUtility(): """Utilities are components that simply provide an interface. They are instantiated at the time or before they are registered. Here we test the simple query interface. Before we register any utility, there is no utility available, of course. The pure instatiation of an object does not make it a utility. If you do not specify a default, you get a `ComponentLookupError`... >>> zope.component.getUtility(I1) #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: \ (, '') ...otherwise, you get the default >>> zope.component.queryUtility(I1, default='') '' >>> zope.component.queryUtility(I2, default='') '' Now we declare `ob` to be the utility providing `I1` >>> zope.component.getGlobalSiteManager().provideUtility(I1, ob) so that the component is now available: >>> zope.component.getUtility(I1) is ob True """ def testNamedUtility(): """Like adapters, utilities can be named. Just because you register an utility having no name >>> zope.component.getGlobalSiteManager().provideUtility(I1, ob) does not mean that they are available when you specify a name: >>> zope.component.getUtility(I1, name='foo') \\ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, 'foo') ...otherwise, you get the default >>> zope.component.queryUtility(I1, name='foo', default='') '' Registering the utility under the correct name >>> zope.component.getGlobalSiteManager().provideUtility( ... I1, ob, name='foo') really helps: >>> zope.component.getUtility(I1, 'foo') is ob True """ def test_getAllUtilitiesRegisteredFor(): """Again, like for adapters, it is often useful to get a list of all utilities that have been registered for a particular interface. Utilities providing a derived interface are also listed. Thus, let's create a derivative interface of `I1`: >>> class I11(I1): ... pass >>> class Ob11(Ob): ... implements(I11) >>> ob11 = Ob11() >>> ob_bob = Ob() Now we register the new utilities: >>> gsm = zope.component.getGlobalSiteManager() >>> gsm.provideUtility(I1, ob) >>> gsm.provideUtility(I11, ob11) >>> gsm.provideUtility(I1, ob_bob, name='bob') >>> gsm.provideUtility(I2, Comp(2)) We can now get all the utilities that provide interface `I1`: >>> uts = list(zope.component.getAllUtilitiesRegisteredFor(I1)) >>> uts = [util.__class__.__name__ for util in uts] >>> uts.sort() >>> uts ['Ob', 'Ob', 'Ob11'] Note that `getAllUtilitiesRegisteredFor()` does not return the names of the utilities. """ def testNotBrokenWhenNoSiteManager(): """Make sure that the adapter lookup is not broken, when no site manager is available. Both of those things emit `DeprecationWarnings`. >>> I2(ob) #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: ('Could not adapt', , ) >>> I2(ob, 42) 42 """ def testNo__component_adapts__leakage(): """ We want to make sure that an `adapts()` call in a class definition doesn't affect instances. >>> import zope.component >>> class C: ... zope.component.adapts() >>> C.__component_adapts__ () >>> C().__component_adapts__ Traceback (most recent call last): ... AttributeError: __component_adapts__ """ def test_ability_to_pickle_globalsitemanager(): """ We need to make sure that it is possible to pickle the global site manager and its two global adapter registries. >>> from zope.component import site >>> import cPickle >>> pickle = cPickle.dumps(site.globalSiteManager) >>> sm = cPickle.loads(pickle) >>> sm is site.globalSiteManager True Now let's ensure that the registries themselves can be pickled as well: >>> pickle = cPickle.dumps(site.globalSiteManager.adapters) >>> adapters = cPickle.loads(pickle) >>> adapters is site.globalSiteManager.adapters True """ def test_suite(): return unittest.TestSuite(( doctest.DocTestSuite(setUp=setUp, tearDown=tearDown), doctest.DocTestSuite('zope.component.site'), doctest.DocFileSuite('README.txt', setUp=setUp, tearDown=tearDown), doctest.DocFileSuite('socketexample.txt', setUp=setUp, tearDown=tearDown), doctest.DocFileSuite('factory.txt', setUp=setUp, tearDown=tearDown), )) if __name__ == "__main__": unittest.main(defaultTest='test_suite') # BBB: Import some backward-compatibility; 12/10/2004 from zope.component.bbb.tests import placelesssetup PK]^„4È’Òóú.ú.zope/component/site.py############################################################################## # # Copyright (c) 2004 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Global Site Manager $Id$ """ __docformat__ = "reStructuredText" import types from zope.interface import implements, providedBy, implementedBy, declarations from zope.interface.adapter import AdapterRegistry from zope.interface.interfaces import IInterface from zope.component.interfaces import ISiteManager, IRegistry from zope.component.interfaces import ComponentLookupError, Invalid class IGlobalSiteManager(ISiteManager, IRegistry): def provideAdapter(required, provided, name, factory, info=''): """Register an adapter factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the adapter - `info`: Provide some info about this particular adapter. """ def subscribe(required, provided, factory, info=''): """Register a subscriber factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the subscriber - `info`: Provide some info about this particular adapter. """ def provideUtility(providedInterface, component, name='', info='', strict=True): """Register a utility If strict is true, then the specified component *must* implement the `providedInterface`. Turning strict off is particularly useful for tests. """ class SiteManager(object): """Site Manager implementation""" def queryAdapter(self, object, interface, name, default=None): """See ISiteManager interface""" return self.adapters.queryAdapter(object, interface, name, default) def queryMultiAdapter(self, objects, interface, name='', default=None): """See ISiteManager interface""" return self.adapters.queryMultiAdapter(objects, interface, name, default) def getAdapters(self, objects, provided): """See ISiteManager interface""" result = [] for name, factory in self.adapters.lookupAll(map(providedBy, objects), provided): adapter = factory(*objects) if adapter is not None: result.append((name, adapter)) return result def subscribers(self, required, provided): """See ISiteManager interface""" return self.adapters.subscribers(required, provided) def queryUtility(self, interface, name='', default=None): """See ISiteManager interface""" byname = self.utilities._null.get(interface) if byname: return byname.get(name, default) else: return default def getUtilitiesFor(self, interface): byname = self.utilities._null.get(interface) if byname: for item in byname.iteritems(): yield item def getAllUtilitiesRegisteredFor(self, interface): return iter(self.utilities._null.get(('s', interface)) or ()) class GlobalSiteManager(SiteManager): """Global Site Manager implementation.""" implements(IGlobalSiteManager) def __init__(self, name=None): self.__name__ = name self._registrations = {} self.adapters = GlobalAdapterRegistry(self, 'adapters') self.utilities = GlobalAdapterRegistry(self, 'utilities') def provideAdapter(self, required, provided, name, factory, info=''): """Register an adapter >>> from zope.interface import Interface >>> registry = GlobalSiteManager() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.provideAdapter((R1, ), P2, 'bob', 'c1', 'd1') >>> registry.provideAdapter((R1, ), P2, '', 'c2', 'd2') >>> registry.adapters.lookup((R2, ), P1, '') 'c2' >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration AdapterRegistration(('R1',), 'P2', '', 'c2', 'd2') AdapterRegistration(('R1',), 'P2', 'bob', 'c1', 'd1') Let's make sure that we can also register regular classes for adaptation. >>> class O1(object): ... pass >>> class O2(object): ... pass >>> class O3(object): ... def __init__(self, obj1, obj2=None): ... pass >>> registry.provideAdapter((O1, ), R1, '', O3) >>> registry.queryAdapter(O1(), R1, '').__class__ >>> registry.provideAdapter((O1, O2), R1, '', O3) >>> registry.queryMultiAdapter((O1(), O2()), R1, '').__class__ """ if IInterface.providedBy(required): raise TypeError('the required argument should be a list of' ' interfaces, not a single interface') ifaces = [] for iface in required: if not IInterface.providedBy(iface) and iface is not None: if not isinstance(iface, (type, types.ClassType)): raise TypeError(iface, IInterface) iface = implementedBy(iface) ifaces.append(iface) required = tuple(ifaces) self._registrations[(required, provided, name)] = AdapterRegistration( required, provided, name, factory, info) self.adapters.register(required, provided, name, factory) def subscribe(self, required, provided, factory, info=''): """Register an subscriptions adapter >>> from zope.interface import Interface >>> registry = GlobalSiteManager() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.subscribe((R1, ), P2, 'c1', 'd1') >>> registry.subscribe((R1, ), P2, 'c2', 'd2') >>> subscriptions = map(str, ... registry.adapters.subscriptions((R2, ), P1)) >>> subscriptions.sort() >>> subscriptions ['c1', 'c2'] >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration SubscriptionRegistration(('R1',), 'P2', 'c1', 'd1') SubscriptionRegistration(('R1',), 'P2', 'c2', 'd2') """ ifaces = [] for iface in required: if not IInterface.providedBy(iface) and \ not isinstance(iface, declarations.Implements) and \ iface is not None: if not isinstance(iface, (type, types.ClassType)): raise TypeError(iface, IInterface) iface = implementedBy(iface) ifaces.append(iface) required = tuple(ifaces) registration = SubscriptionRegistration( required, provided, factory, info) self._registrations[(required, provided)] = ( self._registrations.get((required, provided), ()) + (registration, ) ) self.adapters.subscribe(required, provided, factory) def provideUtility(self, providedInterface, component, name='', info='', strict=True): if strict and not providedInterface.providedBy(component): raise Invalid("The registered component doesn't provide " "the promised interface.") self.utilities.register((), providedInterface, name, component) # Also subscribe to support getAllUtilitiesRegisteredFor: self.utilities.subscribe((), providedInterface, component) self._registrations[(providedInterface, name)] = UtilityRegistration( providedInterface, name, component, info) def registrations(self): for registration in self._registrations.itervalues(): if isinstance(registration, tuple): for r in registration: yield r else: yield registration def __reduce__(self): # Global site managers are pickled as global objects return self.__name__ def GAR(siteManager, registryName): return getattr(siteManager, registryName) class GlobalAdapterRegistry(AdapterRegistry): """A global adapter registry This adapter registry's main purpose is to be picklable in combination with a site manager. """ def __init__(self, parent=None, name=None): self.__parent__ = parent self.__name__ = name super(GlobalAdapterRegistry, self).__init__() def __reduce__(self): return GAR, (self.__parent__, self.__name__) # Global Site Manager Instance globalSiteManager = GlobalSiteManager('globalSiteManager') # Register our cleanup with zope.testing.cleanup to make writing unit tests # simpler. from zope.testing.cleanup import addCleanUp addCleanUp(lambda : globalSiteManager.__init__(globalSiteManager.__name__)) del addCleanUp class AdapterRegistration(object): """Registration for a simple adapter.""" def __init__(self, required, provided, name, value, doc=''): (self.required, self.provided, self.name, self.value, self.doc ) = required, provided, name, value, doc def __repr__(self): return '%s(%r, %r, %r, %r, %r)' % ( self.__class__.__name__, tuple([getattr(r, '__name__', None) for r in self.required]), getattr(self.provided, '__name__', None), self.name, self.value, self.doc, ) def __cmp__(self, other): return cmp(self.__repr__(), other.__repr__()) class SubscriptionRegistration(object): """Registration for a subscription adapter.""" def __init__(self, required, provided, value, doc): (self.required, self.provided, self.value, self.doc ) = required, provided, value, doc def __repr__(self): return '%s(%r, %r, %r, %r)' % ( self.__class__.__name__, tuple([getattr(r, '__name__', None) for r in self.required]), getattr(self.provided, '__name__', None), self.value, self.doc, ) def __cmp__(self, other): return cmp(self.__repr__(), other.__repr__()) class UtilityRegistration(object): def __init__(self, provided, name, component, doc): (self.provided, self.name, self.component, self.doc ) = provided, name, component, doc def __repr__(self): return '%s(%r, %r, %r, %r)' % ( self.__class__.__name__, getattr(self.provided, '__name__', None), self.name, getattr(self.component, '__name__', self.component), self.doc, ) def __cmp__(self, other): return cmp(self.__repr__(), other.__repr__()) PK]^„4×G1G1zope/component/README.txtZope Component Architecture =========================== This package, together with `zope.interface`, provides facilities for defining, registering and looking up components. There are two basic kinds of components: adapters and utilities. Utilities --------- Utilities are just components that provide an interface and that are looked up by an interface and a name. Let's look at a trivial utility definition: >>> from zope import interface >>> class IGreeter(interface.Interface): ... def greet(): ... "say hello" >>> class Greeter: ... interface.implements(IGreeter) ... ... def __init__(self, other="world"): ... self.other = other ... ... def greet(self): ... print "Hello", self.other We can register an instance this class using `provideUtility` [1]_: >>> from zope import component >>> greet = Greeter('bob') >>> component.provideUtility(greet, IGreeter, 'robert') In this example we registered the utility as providing the `IGreeter` interface with a name of 'bob'. We can look the interface up with either `queryUtility` or `getUtility`: >>> component.queryUtility(IGreeter, 'robert').greet() Hello bob >>> component.getUtility(IGreeter, 'robert').greet() Hello bob `queryUtility` and `getUtility` differ in how failed lookups are handled: >>> component.queryUtility(IGreeter, 'ted') >>> component.queryUtility(IGreeter, 'ted', 42) 42 >>> component.getUtility(IGreeter, 'ted') ... # doctest: +ELLIPSIS Traceback (most recent call last): ... ComponentLookupError: (, 'ted') If a component provides only one interface, as in the example above, then we can omit the provided interface from the call to `provideUtility`: >>> ted = Greeter('ted') >>> component.provideUtility(ted, name='ted') >>> component.queryUtility(IGreeter, 'ted').greet() Hello ted The name defaults to an empty string: >>> world = Greeter() >>> component.provideUtility(world) >>> component.queryUtility(IGreeter).greet() Hello world Adapters -------- Adapters are components that are computed from other components to adapt them to some interface. Because they are computed from other objects, they are provided as factories, usually classes. Here, we'll create a greeter for persons, so we can provide personalized greetings for different people: >>> class IPerson(interface.Interface): ... name = interface.Attribute("Name") >>> class PersonGreeter: ... ... component.adapts(IPerson) ... interface.implements(IGreeter) ... ... def __init__(self, person): ... self.person = person ... ... def greet(self): ... print "Hello", self.person.name The class defines a constructor that takes an argument for every object adapted. We used `component.adapts` to declare what we adapt. We can find out if an object declares that it adapts anything using adaptedBy: >>> list(component.adaptedBy(PersonGreeter)) == [IPerson] True If an object makes no declaration, then None is returned: >>> component.adaptedBy(Greeter()) is None True If we declare the interfaces adapted and if we provide only one interface, as in the example above, then we can provide the adapter very simply [1]_: >>> component.provideAdapter(PersonGreeter) For adapters that adapt a single interface to a single interface without a name, we can get the adapter by simply calling the interface: >>> class Person: ... interface.implements(IPerson) ... ... def __init__(self, name): ... self.name = name >>> IGreeter(Person("Sally")).greet() Hello Sally We can also provide arguments to be very specific about what how to register the adapter. >>> class BobPersonGreeter(PersonGreeter): ... name = 'Bob' ... def greet(self): ... print "Hello", self.person.name, "my name is", self.name >>> component.provideAdapter( ... BobPersonGreeter, [IPerson], IGreeter, 'bob') The arguments can also be provided as keyword arguments: >>> class TedPersonGreeter(BobPersonGreeter): ... name = "Ted" >>> component.provideAdapter( ... factory=TedPersonGreeter, adapts=[IPerson], ... provides=IGreeter, name='ted') For named adapters, use `queryAdapter`, or `getAdapter`: >>> component.queryAdapter(Person("Sally"), IGreeter, 'bob').greet() Hello Sally my name is Bob >>> component.getAdapter(Person("Sally"), IGreeter, 'ted').greet() Hello Sally my name is Ted If an adapter can't be found, `queryAdapter` returns a default value and `getAdapter` raises an error: >>> component.queryAdapter(Person("Sally"), IGreeter, 'frank') >>> component.queryAdapter(Person("Sally"), IGreeter, 'frank', 42) 42 >>> component.getAdapter(Person("Sally"), IGreeter, 'frank') ... # doctest: +ELLIPSIS Traceback (most recent call last): ... ComponentLookupError: (...Person...>, <...IGreeter>, 'frank') Adapters can adapt multiple objects: >>> class TwoPersonGreeter: ... ... component.adapts(IPerson, IPerson) ... interface.implements(IGreeter) ... ... def __init__(self, person, greeter): ... self.person = person ... self.greeter = greeter ... ... def greet(self): ... print "Hello", self.person.name ... print "my name is", self.greeter.name >>> component.provideAdapter(TwoPersonGreeter) To look up a multi-adapter, use either `queryMultiAdapter` or `getMultiAdapter`: >>> component.queryMultiAdapter((Person("Sally"), Person("Bob")), ... IGreeter).greet() Hello Sally my name is Bob Adapters need not be classes. Any callable will do. We use the adapter decorator (in the Python 2.4 decorator sense) to declare that a callable object adapts some interfaces (or classes): >>> class IJob(interface.Interface): ... "A job" >>> class Job: ... interface.implements(IJob) >>> def personJob(person): ... return getattr(person, 'job', None) >>> personJob = interface.implementer(IJob)(personJob) >>> personJob = component.adapter(IPerson)(personJob) In Python 2.4, the example can be written: >>> @interface.implementer(IJob) ... @component.adapter(IPerson) ... def personJob(person): ... return getattr(person, 'job', None) which looks a bit nicer. In this example, the personJob function simply returns the person's `job` attribute if present, or None if it's not present. An adapter factory can return None to indicate that adaptation wasn't possible. Let's register this adapter and try it out: >>> component.provideAdapter(personJob) >>> sally = Person("Sally") >>> IJob(sally) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: ('Could not adapt', ... The adaptation failed because sally didn't have a job. Let's give her one: >>> job = Job() >>> sally.job = job >>> IJob(sally) is job True Subscription Adapters ********************* Unlike regular adapters, subscription adapters are used when we want all of the adapters that adapt an object to a particular adapter. Consider a validation problem. We have objects and we want to assess whether they meet some sort of standards. We define a validation interface: >>> class IValidate(interface.Interface): ... def validate(ob): ... """Determine whether the object is valid ... ... Return a string describing a validation problem. ... An empty string is returned to indicate that the ... object is valid. ... """ Perhaps we have documents: >>> class IDocument(interface.Interface): ... summary = interface.Attribute("Document summary") ... body = interface.Attribute("Document text") >>> class Document: ... interface.implements(IDocument) ... def __init__(self, summary, body): ... self.summary, self.body = summary, body Now, we may want to specify various validation rules for documents. For example, we might require that the summary be a single line: >>> class SingleLineSummary: ... component.adapts(IDocument) ... interface.implements(IValidate) ... ... def __init__(self, doc): ... self.doc = doc ... ... def validate(self): ... if '\n' in self.doc.summary: ... return 'Summary should only have one line' ... else: ... return '' Or we might require the body to be at least 1000 characters in length: >>> class AdequateLength: ... component.adapts(IDocument) ... interface.implements(IValidate) ... ... def __init__(self, doc): ... self.doc = doc ... ... def validate(self): ... if len(self.doc.body) < 1000: ... return 'too short' ... else: ... return '' We can register these as subscription adapters [1]_: >>> component.provideSubscriptionAdapter(SingleLineSummary) >>> component.provideSubscriptionAdapter(AdequateLength) We can then use the subscribers to validate objects: >>> doc = Document("A\nDocument", "blah") >>> [adapter.validate() ... for adapter in component.subscribers([doc], IValidate) ... if adapter.validate()] ['Summary should only have one line', 'too short'] >>> doc = Document("A\nDocument", "blah" * 1000) >>> [adapter.validate() ... for adapter in component.subscribers([doc], IValidate) ... if adapter.validate()] ['Summary should only have one line'] >>> doc = Document("A Document", "blah") >>> [adapter.validate() ... for adapter in component.subscribers([doc], IValidate) ... if adapter.validate()] ['too short'] Handlers ******** Handlers are subscription adapter factories that don't produce anything. They do all of their work when called. Handlers are typically used to handle events. Event subscribers are different from other subscription adapters in that the caller of event subscribers doesn't expect to interact with them in any direct way. For example, an event publisher doesn't expect to get any return value. Because subscribers don't need to provide an API to their callers, it is more natural to define them with functions, rather than classes. For example, in a document-management system, we might want to record creation times for documents: >>> import datetime >>> def documentCreated(event): ... event.doc.created = datetime.datetime.utcnow() In this example, we have a function that takes an event and performs some processing. It doesn't actually return anything. This is a special case of a subscription adapter that adapts an event to nothing. All of the work is done when the adapter "factory" is called. We call subscribers that don't actually create anything "handlers". There are special APIs for registering and calling them. To register the subscriber above, we define a document-created event: >>> class IDocumentCreated(interface.Interface): ... doc = interface.Attribute("The document that was created") >>> class DocumentCreated: ... interface.implements(IDocumentCreated) ... ... def __init__(self, doc): ... self.doc = doc We'll also change our handler definition to: >>> def documentCreated(event): ... event.doc.created = datetime.datetime.utcnow() >>> documentCreated = component.adapter(IDocumentCreated)(documentCreated) Note that in Python 2.4, this can be written: >>> @component.adapter(IDocumentCreated) ... def documentCreated(event): ... event.doc.created = datetime.datetime.utcnow() This marks the handler as an adapter of `IDocumentCreated` events. Now we'll register the handler [1]_: >>> component.provideHandler(documentCreated) Now, if we can create an event and use the `handle` function to call handlers registered for the event: >>> component.handle(DocumentCreated(doc)) >>> doc.created.__class__.__name__ 'datetime' .. [1] CAUTION: This API should only be used from test or application-setup code. This API shouldn't be used by regular library modules, as component registration is a configuration activity. PK]^„4¯V>Óc c zope/component/factory.txt========= Factories ========= The Factory Class ----------------- >>> from zope.interface import Interface >>> class IFunction(Interface): ... pass >>> class IKlass(Interface): ... pass >>> from zope.interface import implements >>> class Klass(object): ... implements(IKlass) ... ... def __init__(self, *args, **kw): ... self.args = args ... self.kw = kw >>> from zope.component.factory import Factory >>> factory = Factory(Klass, 'Klass', 'Klassier') >>> factory2 = Factory(lambda x: x, 'Func', 'Function') >>> factory3 = Factory(lambda x: x, 'Func', 'Function', (IFunction,)) Calling a Factory +++++++++++++++++ Here we test whether the factory correctly creates the objects and including the correct handling of constructor elements. First we create a factory that creates instanace of the `Klass` class: >>> factory = Factory(Klass, 'Klass', 'Klassier') Now we use the factory to create the instance >>> kl = factory(1, 2, foo=3, bar=4) and make sure that the correct class was used to create the object: >>> kl.__class__ Since we passed in a couple positional and keyword arguments >>> kl.args (1, 2) >>> kl.kw {'foo': 3, 'bar': 4} >>> factory2(3) 3 >>> factory3(3) 3 Title and Description +++++++++++++++++++++ >>> factory.title 'Klass' >>> factory.description 'Klassier' >>> factory2.title 'Func' >>> factory2.description 'Function' >>> factory3.title 'Func' >>> factory3.description 'Function' Provided Interfaces +++++++++++++++++++ >>> implemented = factory.getInterfaces() >>> implemented.isOrExtends(IKlass) True >>> list(implemented) [] >>> implemented2 = factory2.getInterfaces() >>> list(implemented2) [] >>> implemented3 = factory3.getInterfaces() >>> list(implemented3) [] The Componant Architecture Factory API -------------------------------------- >>> import zope.component >>> factory = Factory(Klass, 'Klass', 'Klassier') >>> gsm = zope.component.getGlobalSiteManager() >>> from zope.component.interfaces import IFactory >>> gsm.provideUtility(IFactory, factory, 'klass') Creating an Object ++++++++++++++++++ >>> kl = zope.component.createObject('klass', 1, 2, foo=3, bar=4) >>> isinstance(kl, Klass) True >>> kl.args (1, 2) >>> kl.kw {'foo': 3, 'bar': 4} Accessing Provided Interfaces +++++++++++++++++++++++++++++ >>> implemented = zope.component.getFactoryInterfaces('klass') >>> implemented.isOrExtends(IKlass) True >>> [iface for iface in implemented] [] List of All Factories +++++++++++++++++++++ >>> [(name, fac.__class__) for name, fac in ... zope.component.getFactoriesFor(IKlass)] [(u'klass', )] PK]^„4§ÙÝ8ÂPÂP zope/component/socketexample.txt================================================== The Zope 3 Component Architecture (Socket Example) ================================================== The component architecture provides an application framework that provides its functionality through loosly-connected components. A *component* can be any Python object and has a particular purpose associated with it. Thus, in a component-based applications you have many small component in contrast to classical object-oriented development, where yoiu have a few big objects. Components communicate via specific APIs, which are formally defined by interfaces, which are provided by the `zope.interface` package. *Interfaces* describe the methods and properties that a component is expected to provide. They are also used as a primary mean to provide developer-level documentation for the components. For more details about interfaces see `zope/interface/README.txt`. The two main types of components are *adapters* and *utilities*. They will be discussed in detail later in this document. Both component types are managed by the *site manager*, with which you can register and access these components. However, most of the site manager's functionality is hidden behind the component architecture's public API, which is documented in `IComponentArchitecture`. Adapters -------- Adapters are a well-established pattern. An *adapter* uses an object providing one interface to produce an object that provides another interface. Here an example: Imagine that you purchased an electric shaver in the US, and thus you require the US socket type. You are now traveling in Germany, where another socket style is used. You will need a device, an adapter, that converts from the German to the US socket style. The functionality of adapters is actually natively provided by the `zope.interface` package and is thus well documented there. The `human.txt` file provides a gentle introduction to adapters, whereby `adapter.txt` is aimed at providing a comprehensive insight into adapters, but is too abstract for many as an inital read. Thus, we will only explain adapters in the context of the component architecture's API. So let's say that we have a German socket >>> from zope.interface import Interface, implements >>> class IGermanSocket(Interface): ... pass >>> class Socket(object): ... def __repr__(self): ... return '' %self.__class__.__name__ >>> class GermanSocket(Socket): ... """German wall socket.""" ... implements(IGermanSocket) and we want to convert it to an US socket >>> class IUSSocket(Interface): ... pass so that our shaver can be used in Germany. So we go to a German electronics store to look for an adapter that we can plug in the wall: >>> class GermanToUSSocketAdapter(Socket): ... implements(IUSSocket) ... __used_by__ = IGermanSocket ... ... def __init__(self, socket): ... self.context = socket Note that I could have called the passed in socket any way I like, but `context` is the standard name accepted. Single Adapters +++++++++++++++ Before we can use the adapter, we have to buy it and make it part of our inventory. In the component architecture we do this by registering the adapter with the framework, more specifically with the global site manager: >>> import zope.component >>> gsm = zope.component.getGlobalSiteManager() >>> gsm.provideAdapter((IGermanSocket,), IUSSocket, '', ... GermanToUSSocketAdapter) `zope.component` is the component architecture API that is being presented by this file. You registered an adapter from `IGermanSocket` to `IUSSocket` having no name (thus the empty string). Anyways, you finally get back to your hotel room and shave, since you have not been able to shave in the plane. In the bathroom you discover a socket: >>> bathroomDE = GermanSocket() >>> IGermanSocket.providedBy(bathroomDE) True You now insert the adapter in the German socket >>> bathroomUS = zope.component.getAdapter(bathroomDE, IUSSocket, '') so that the socket now provides the US version: >>> IUSSocket.providedBy(bathroomUS) True Now you can insert your shaver and get on with your day. After a week you travel for a couple of days to the Prague and you notice that the Czech have yet another socket type: >>> class ICzechSocket(Interface): ... pass >>> class CzechSocket(Socket): ... implements(ICzechSocket) >>> czech = CzechSocket() You try to find an adapter for your shaver in your bag, but you fail, since you do not have one: >>> zope.component.getAdapter(czech, IUSSocket, '') \ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, , '') or the more graceful way: >>> marker = object() >>> socket = zope.component.queryAdapter(czech, IUSSocket, '', marker) >>> socket is marker True In the component architecture API any `get*` method will fail with a specific exception, if a query failed, whereby methods starting with `query*` will always return a `default` value after a failure. Named Adapters ++++++++++++++ You are finally back in Germany. You also brought your DVD player and a couple DVDs with you, which you would like to watch. Your shaver was able to convert automatically from 110 volts to 240 volts, but your DVD player cannot. So you have to buy another adapter that also handles converting the voltage and the frequency of the AC current: >>> class GermanToUSSocketAdapterAndTransformer(object): ... implements(IUSSocket) ... __used_by__ = IGermanSocket ... ... def __init__(self, socket): ... self.context = socket Now, we need a way to keep the two adapters apart. Thus we register them with a name: >>> gsm.provideAdapter((IGermanSocket,), IUSSocket, 'shaver', ... GermanToUSSocketAdapter) >>> gsm.provideAdapter((IGermanSocket,), IUSSocket, 'dvd', ... GermanToUSSocketAdapterAndTransformer) Now we simply look up the adapters using their labels (called *name*): >>> socket = zope.component.getAdapter(bathroomDE, IUSSocket, 'shaver') >>> socket.__class__ is GermanToUSSocketAdapter True >>> socket = zope.component.getAdapter(bathroomDE, IUSSocket, 'dvd') >>> socket.__class__ is GermanToUSSocketAdapterAndTransformer True Clearly, we do not have an adapter for the MP3 player >>> zope.component.getAdapter(bathroomDE, IUSSocket, 'mp3') \ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, , 'mp3') but you could use the 'dvd' adapter in this case of course. ;) Sometimes you want to know all adapters that are available. Let's say you want to know about all the adapters that convert a German to a US socket type: >>> sockets = zope.component.getAdapters((bathroomDE,), IUSSocket) >>> len(sockets) 3 >>> names = [name for name, socket in sockets] >>> names.sort() >>> names [u'', u'dvd', u'shaver'] `zope.component.getAdapters()` returns a list of tuples. The first entry of the tuple is the name of the adapter and the second is the adapter itself. Multi-Adapters ++++++++++++++ After watching all the DVDs you brought at least twice, you get tired of them and you want to listen to some music using your MP3 player. But darn, the MP3 player plug has a ground pin and all the adapters you have do not support that: >>> class IUSGroundedSocket(IUSSocket): ... pass So you go out another time to buy an adapter. This time, however, you do not buy yet another adapter, but a piece that provides the grounding plug: >>> class IGrounder(Interface): ... pass >>> class Grounder(object): ... implements(IGrounder) ... def __repr__(self): ... return '' Then together they will provided a grounded us socket: >>> class GroundedGermanToUSSocketAdapter(object): ... implements(IUSGroundedSocket) ... __used_for__ = (IGermanSocket, IGrounder) ... def __init__(self, socket, grounder): ... self.socket, self.grounder = socket, grounder You now register the combination, so that you know you can create a `IUSGroundedSocket`: >>> gsm.provideAdapter((IGermanSocket, IGrounder), IUSGroundedSocket, 'mp3', ... GroundedGermanToUSSocketAdapter) Given the grounder >>> grounder = Grounder() and a German socket >>> livingroom = GermanSocket() we can now get a gounded US socket: >>> socket = zope.component.getMultiAdapter((livingroom, grounder), ... IUSGroundedSocket, 'mp3') >>> socket.__class__ is GroundedGermanToUSSocketAdapter True >>> socket.socket is livingroom True >>> socket.grounder is grounder True Of course, you do not have a 'dvd' grounded US socket available: >>> zope.component.getMultiAdapter((livingroom, grounder), ... IUSGroundedSocket, 'dvd') \ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: ((, ), , 'dvd') >>> socket = zope.component.queryMultiAdapter( ... (livingroom, grounder), IUSGroundedSocket, 'dvd', marker) >>> socket is marker True Again, you might want to read `adapter.txt` in `zope.interface` for a more comprehensive coverage of multi-adapters. Subscribers ----------- While subscribers are directly supported by the adapter registry and are adapters for all theoretical purposes, practically it might be better to think of them as separate components. Subscribers are particularly useful for events. Let's say one of our adapters overheated and caused a small fire: >>> class IFire(Interface): ... pass >>> class Fire(object): ... implements(IFire) >>> fire = Fire() We want to use all available objects to put out the fire: >>> class IFireExtinguisher(Interface): ... def extinguish(): ... pass >>> class FireExtinguisher(object): ... def __init__(self, fire): ... pass ... def extinguish(self): ... "Place extinguish code here." ... print 'Used ' + self.__class__.__name__ + '.' Here some specific methods to put out the fire: >>> class PowderExtinguisher(FireExtinguisher): ... pass >>> gsm.subscribe((IFire,), IFireExtinguisher, PowderExtinguisher) >>> class Blanket(FireExtinguisher): ... pass >>> gsm.subscribe((IFire,), IFireExtinguisher, Blanket) >>> class SprinklerSystem(FireExtinguisher): ... pass >>> gsm.subscribe((IFire,), IFireExtinguisher, SprinklerSystem) Now let use all these things to put out the fire: >>> extinguishers = zope.component.subscribers((fire,), IFireExtinguisher) >>> extinguishers.sort() >>> for extinguisher in extinguishers: ... extinguisher.extinguish() Used Blanket. Used PowderExtinguisher. Used SprinklerSystem. If no subscribers are found for a particular object, then an empty list is returned: >>> zope.component.subscribers((object(),), IFireExtinguisher) [] Utilities --------- Utilities are the second type of component, the component architecture implements. *Utilities* are simply components that provide an interface. When you register an utility, you always register an instance (in cotrast to a factory for adapters) since the initialization and setup process of a utility might be complex and is not well defined. In some ways a utility is much more fundamental than an adapter, because an adapter cannot be used without another component, but a utility is always self-contained. I like to think of utilities as the foundation of your application and adapters as components extending beyond this foundation. Back to our story... After your vacation is over you fly back home to Tampa, Florida. But it is August now, the middle of the Hurrican season. And, believe it or not, you are worried that you will not be able to shave when the power goes out for several days. (You just hate wet shavers.) So you decide to go to your favorite hardware store and by a Diesel-powered electric generator. The generator provides of course a US-style socket: >>> class Generator(object): ... implements(IUSSocket) ... def __repr__(self): ... return '' >>> generator = Generator() Like for adapters, we now have to add the newly-acquired generator to our inventory by registering it as a utility: >>> gsm.provideUtility(IUSSocket, generator) We can now get the utility using >>> utility = zope.component.getUtility(IUSSocket) >>> utility is generator True As you can see, it is very simple to register and retrieve utilities. If a utility does not exsist for a particular interface, such as the German socket, then the lookup fails >>> zope.component.getUtility(IGermanSocket) Traceback (most recent call last): ... ComponentLookupError: (, '') or more gracefully when specifying a default value: >>> default = object() >>> utility = zope.component.queryUtility(IGermanSocket, default=default) >>> utility is default True Note: The only difference between `getUtility()` and `queryUtility()` is the fact that you can specify a default value for the latter function, so that it will never cause a `ComponentLookupError`. Named Utilities +++++++++++++++ It is often desirable to have several utilities providing the same interface per site. This way you can implement any sort of registry using utilities. For this reason, utilities -- like adapters -- can be named. In the context of our story, we might want to do the following: You really do not trust gas stations either. What if the roads are blocked after a hurricane and the gas stations run out of oil. So you look for another renewable power source. Then you think about solar panels! After a storm there is usually very nice weather, so why not? Via the Web you order a set of 110V/120W solar panels that provide a regular US-style socket as output: >>> class SolarPanel(object): ... implements(IUSSocket) ... def __repr__(self): ... return '' >>> panel = SolarPanel() Once it arrives, we add it to our inventory: >>> gsm.provideUtility(IUSSocket, panel, 'Solar Panel') You can now access the solar panel using >>> utility = zope.component.getUtility(IUSSocket, 'Solar Panel') >>> utility is panel True Of course, if a utility is not available, then the lookup will simply fail >>> zope.component.getUtility(IUSSocket, 'Wind Mill') Traceback (most recent call last): ... ComponentLookupError: (, 'Wind Mill') or more gracefully when specifying a default value: >>> default = object() >>> utility = zope.component.queryUtility(IUSSocket, 'Wind Mill', ... default=default) >>> utility is default True Now you want to look at all the utilities you have for a particular kind. The following API function will return a list of name/utility pairs: >>> utils = list(zope.component.getUtilitiesFor(IUSSocket)) >>> utils.sort() >>> utils #doctest: +NORMALIZE_WHITESPACE [(u'', ), (u'Solar Panel', )] Another method of looking up all utilities is by using `getAllUtilitiesRegisteredFor(iface)`. This function will return an iteratable of utilities (without names); however, it will also return overridden utilities. If you are not using multiple site managers, you will not actually need this method. >>> utils = list(zope.component.getAllUtilitiesRegisteredFor(IUSSocket)) >>> utils.sort() >>> utils [, ] Factories +++++++++ A *factory* is a special kind of utility that exists to create other components. A factory is always identified by a name. It also provides a title and description and is able to tell the developer what interfaces the created object will provide. The advantage of using a factory to create an object instead of directly isntantiating a class or executing any other callable is that we can refer to the factory by name. As long as the name stays fixed, the implementation of the callable can be renamed or moved without a breakage in code. Let's say that our solar panel comes in parts and they have to be assembled. This assembly would be done by a factory, so let's create one for the solar panel. To do this, we can use a standard implementation of the `IFactory` interface: >>> from zope.component.factory import Factory >>> factory = Factory(SolarPanel, ... 'Solar Panel', ... 'This factory creates a solar panel.') Optionally, I could have also specifed the interfaces that the created object will provide, but the factory class is smart enough to determine the implemented interface from the class. We now register the factory: >>> from zope.component.interfaces import IFactory >>> gsm.provideUtility(IFactory, factory, 'SolarPanel') We can now get a list of interfaces the produced object will provide: >>> ifaces = zope.component.getFactoryInterfaces('SolarPanel') >>> IUSSocket in ifaces True By the way, this is equivalent to >>> ifaces2 = factory.getInterfaces() >>> ifaces is ifaces2 True Of course you can also just create an object: >>> panel = zope.component.createObject('SolarPanel') >>> panel.__class__ is SolarPanel True Note: Ignore the first argument (`None`) for now; it is the context of the utility lookup, which is usually an optional argument, but cannot be in this case, since all other arguments beside the `name` are passed in as arguments to the specified callable. Once you register several factories >>> gsm.provideUtility(IFactory, Factory(Generator), 'Generator') you can also determine, which available factories will create objects providing a certian interface: >>> factories = zope.component.getFactoriesFor(IUSSocket) >>> factories = [(name, factory.__class__) for name, factory in factories] >>> factories.sort() >>> factories #doctest: +NORMALIZE_WHITESPACE [(u'Generator', ), (u'SolarPanel', )] Site Managers ------------- Why do we need site managers? Why is the component architecture API not sufficient? Some applications, including Zope 3, have a concept of locations. It is often desireable to have different configurations for these location; this can be done by overwriting existing or adding new component registrations. Site managers in locations below the root location, should be able to delegate requests to their parent locations. The root site manager is commonly known as *global site manager*, since it is always available. You can always get the global site manager using the API: >>> gsm = zope.component.getGlobalSiteManager() >>> from zope.component.site import globalSiteManager >>> gsm is globalSiteManager True >>> from zope.component.interfaces import ISiteManager >>> ISiteManager.providedBy(gsm) True >>> from zope.component.site import IGlobalSiteManager >>> IGlobalSiteManager.providedBy(gsm) True You can also lookup at site manager in a given context. The only requirement is that the context can be adapted to a site manager. So let's create a special site manager: >>> from zope.component.site import SiteManager >>> sm = SiteManager() Now we create a context that adapts to the site manager via the `__conform__` method as specied in PEP 246. >>> class Context(object): ... def __init__(self, sm): ... self.sm = sm ... def __conform__(self, interface): ... if interface.isOrExtends(ISiteManager): ... return self.sm We now instantiate the `Context` with our special site manager: >>> context = Context(sm) >>> context.sm is sm True We can now ask for the site manager of this context: >>> lsm = zope.component.getSiteManager(context) >>> lsm is sm True The site manager instance `lsm` is formally known as a *local site manager* of `context`. PK¶“„4Iy!KK#zope/component/contextdependent.pyc;ò Xº2Dc@s:dZdklZdklZdefd„ƒYZdS(suA simple mix-in class that implements IContextDependent. $Id: contextdependent.py 25177 2004-06-02 13:17:31Z jim $ (sIContextDependent(s implementssContextDependentcBs!tZdZeeƒd„ZRS(s2standard boilerplate for context dependent objectscCs ||_dS(N(scontextsself(sselfscontext((s=build/bdist.linux-i686/egg/zope/component/contextdependent.pys__init__s(s__name__s __module__s__doc__s implementssIContextDependents__init__(((s=build/bdist.linux-i686/egg/zope/component/contextdependent.pysContextDependents  N(s__doc__szope.component.interfacessIContextDependentszope.interfaces implementssobjectsContextDependent(s implementssIContextDependentsContextDependent((s=build/bdist.linux-i686/egg/zope/component/contextdependent.pys?s  PK¶“„4ïu‚Q__zope/component/presentation.pyc;ò Xº2Dc@s>dZdklZdklZlZdklZdkl Z dk l Z dk l Z dk ZdkZdeiifd „ƒYZd eiifd „ƒYZd efd „ƒYZd„Zdeiiifd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdS(sJGlobal Presentation Service This module contains an adapter-registry-based global presentation service. Additionally it contains all registration classes that can occur: - SkinRegistration - LayerRegistration - DefaultSkinRegistration - PresentationRegistration $Id: presentation.py 27309 2004-08-27 21:01:06Z jim $ (s ClassType(sIPresentationServices IRegistry(s GlobalService(s Presentation(s providedBy(s IInterfaceNsIGlobalPresentationServicecBsDtZdZd„Zd„Zd„Zdfeiidd„Z RS(s>Provide ability to update the global presentation service cCsdS(sDefine a skin A skin is defined for a request type. It consists of a sequence of layer names. Layers must be defined before they are used in a skin definition. Note that there is one predefined layer, "default". N((snameslayers((s9build/bdist.linux-i686/egg/zope/component/presentation.pys defineSkin*scCsdS(shSet the default skin for a request type If not set, it defaults to the "default" skin. N((sname((s9build/bdist.linux-i686/egg/zope/component/presentation.pyssetDefaultSkin4scCsdS(sDefine a layer N((sname((s9build/bdist.linux-i686/egg/zope/component/presentation.pys defineLayer:sssdefaultcCsdS(s'Provide a presentation adapter N((s request_typesfactorysnamescontextss providingslayer((s9build/bdist.linux-i686/egg/zope/component/presentation.pysprovideAdapter>s( s__name__s __module__s__doc__s defineSkinssetDefaultSkins defineLayerszopes interfaces InterfacesprovideAdapter(((s9build/bdist.linux-i686/egg/zope/component/presentation.pysIGlobalPresentationService&s   sIDefaultViewNamecBstZdZRS(s‰A string that contains the default view name A default view name is used to select a view when a user hasn't specified one. (s__name__s __module__s__doc__(((s9build/bdist.linux-i686/egg/zope/component/presentation.pysIDefaultViewNameCs sGlobalPresentationServicecBstZdZeiieeeƒd„Z d„Z dd„Z d„Z d„Z dd„Zdd„Zd feiid dd „Zeeiid „Zeiied „Zeiided„Zd eiid„Zd d„Zed„Zd eiid„ZRS(sHGlobal presentation service The global presentation service provides management of views, and resources arranged in skins, where skins are ordered collections of layers. Views are modeled as adapters of objects and requests. Resources are just request adapters. The adapters are arranged in layers. Let's look at some examples. First, we'll create a service: >>> s = GlobalPresentationService() And define a custom layer and skin: >>> s.defineLayer('custom') >>> s.defineSkin('custom', ['custom', 'default']) We'll define a request type and a fake request: >>> class IRequest(zope.interface.Interface): ... "Demonstration request type" >>> class Request(object): ... zope.interface.implements(IRequest) ... def getPresentationSkin(self): ... return getattr(self, 'skin', None) >>> request = Request() With this in place, we can start registering resources. A resource is just a request adapter. >>> class MyResource(object): ... def __init__(self, request): ... self.request = request To register a resource, we register it as an adapter. Most resources are going to interface with a user, and, so, don't really provide a programatic interface. For this reason, we register them to provide the empty interface, Interface, which is the default provided interface: >>> s.provideAdapter(IRequest, MyResource, name='foo', layer='custom') Now we can try to look this up: >>> s.queryResource('foo', request) But we won't get anything, because our request doesn't specify a skin and, the default skin gets used. Our resource was registered in the custom layer, which isn't used by the default skin. If we set out request skin to 'custom': >>> request.skin = 'custom' Then the lookup will suceed: >>> r = s.queryResource('foo', request) >>> r.__class__.__name__ 'MyResource' >>> r.request is request True Views are registered as "multi" adapters. Multi-adapters adapt multiple objects simultaneously. >>> class IContact(zope.interface.Interface): ... "Demonstration content type" >>> class MyView(object): ... def __init__(self, context, request): ... self.context, self.request = context, request >>> s.provideAdapter(IRequest, MyView, contexts=[IContact], ... name='foo', layer='custom') When defining views, we provide one or more (typically 1) context interfaces, corresponding to the contexts of the view. >>> class Contact(object): ... zope.interface.implements(IContact) >>> c = Contact() We look up views with queryView: >>> v = s.queryView(c, 'foo', request) >>> v.__class__.__name__ 'MyView' >>> v.request is request True >>> v.context is c True Most views and resources are unnamed and provide no interface. We can also have views that provide interfaces. For example, we might need a view to help out with finding objects: >>> class ITraverse(zope.interface.Interface): ... "Sample traversal interface (imagine interesting methods :)" >>> class Traverser(object): ... zope.interface.implements(ITraverse) ... def __init__(self, context, request): ... self.context, self.request = context, request which we register using the provided interface, rather than a name. >>> s.provideAdapter(IRequest, Traverser, contexts=[IContact], ... providing=ITraverse, layer='custom') (We could use a name too, if we wanted to.) Then we look up the view using the interface: >>> v = s.queryView(c, '', request, providing=ITraverse) >>> v.__class__.__name__ 'Traverser' >>> v.request is request True >>> v.context is c True cCsbhdt|dƒ<|_hd|idg<|_hddf<|_d|_h|_dS(Nsdefault(s GlobalLayersselfs_layerss_skinssskinss defaultSkins_registrations(sself((s9build/bdist.linux-i686/egg/zope/component/presentation.pys__init__Ðs  cCs|iiƒSdS(N(sselfs_registrationss itervalues(sself((s9build/bdist.linux-i686/egg/zope/component/presentation.pys registrations×sscCsã||ijotd|ƒ‚ngi}|D]$}||ijo||ƒq1q1~}|otd|f‚ngi}|D]}||i|ƒq†~|i|>> s = GlobalPresentationService() >>> s.defineSkin('default', ['default']) Traceback (most recent call last): ... ValueError: ("Can't redefine skin", 'default') The layers used in a skin definition must be defined before they are used: >>> s.defineSkin('custom', ['custom', 'default']) Traceback (most recent call last): ... ValueError: ('Undefined layers', ['custom']) >>> s.defineLayer('custom') >>> s.defineSkin('custom', ['custom', 'default'], 'custom doc') >>> skins = s.skins.items() >>> skins.sort() >>> skins [('custom', ('custom', 'default')), ('default', ('default',))] A skin registration is also recorded for each registered skin. >>> registrations = map(str, s.registrations()) >>> registrations.sort() >>> for r in registrations: ... print r zope.component.presentation.LayerRegistration('custom', '') zope.component.presentation.SkinRegistration('custom', ['custom', 'default'], 'custom doc') sCan't redefine skinsUndefined layerssskinN(snamesselfs_skinss ValueErrorsappends_[1]slayersslayers_layerssbadstuplesskinssSkinRegistrationsinfos_registrations(sselfsnameslayerssinfoslayers_[1]sbad((s9build/bdist.linux-i686/egg/zope/component/presentation.pys defineSkinÚs(;5cCs|ii|ƒSdS(N(sselfsskinssgetsname(sselfsname((s9build/bdist.linux-i686/egg/zope/component/presentation.pys querySkinscCs|ii|ƒSdS(N(sselfs_layerssgetsname(sselfsname((s9build/bdist.linux-i686/egg/zope/component/presentation.pys queryLayerscCsF||ijotd|f‚n||_t||ƒ|id>> s = GlobalPresentationService() >>> s.defaultSkin 'default' >>> s.setDefaultSkin('custom') Traceback (most recent call last): ... ValueError: ('Undefined skin', 'custom') >>> s.defineLayer('custom') >>> s.defineSkin('custom', ['custom', 'default']) >>> s.setDefaultSkin('custom', 'yawn') >>> s.defaultSkin 'custom' A default skin registration is also recorded for each registered default skin. >>> registrations = map(str, s.registrations()) >>> registrations.sort() >>> for r in registrations: ... print r zope.component.presentation.DefaultSkinRegistration('custom', 'yawn') zope.component.presentation.LayerRegistration('custom', '') zope.component.presentation.SkinRegistration('custom', ['custom', 'default'], '') sUndefined skins defaultSkinN(snamesselfs_skinss ValueErrors defaultSkinsDefaultSkinRegistrationsinfos_registrations(sselfsnamesinfo((s9build/bdist.linux-i686/egg/zope/component/presentation.pyssetDefaultSkins  cCsY||ijotd|ƒ‚nt||ƒ|i|>> s = GlobalPresentationService() >>> s.defineLayer('custom', 'blah') You can't define a layer that's already defined: >>> s.defineLayer('custom') Traceback (most recent call last): ... ValueError: ("Can't redefine layer", 'custom') A layer registration is also recorded for each registered layer. >>> list(s.registrations()) [zope.component.presentation.LayerRegistration('custom', 'blah')] sCan't redefine layerslayerN(snamesselfs_layerss ValueErrors GlobalLayersLayerRegistrationsinfos_registrations(sselfsnamesinfo((s9build/bdist.linux-i686/egg/zope/component/presentation.pys defineLayerAs usdefaultc Csðg}xy|D]q} ti| ƒ o | tj o@t| ttfƒ ot | tƒ‚nt i i | ƒ} n|i | ƒq W|i |ƒt|ƒ}|i|} | i||||ƒt||||||ƒ|i||||fs__doc__ssysswarningsszope.interfacesmoduleProvidess Interfaceszope.interface.interfacess IInterfaceszope.component.interfacessIComponentArchitecturesIFactorysIServiceServiceszope.component.exceptionssComponentLookupErrorszope.component.servicesserviceManagerszope.component.servicenamessAdapterss Presentations Utilitiess zope.hookableshookables ImportErrorstuples__all__s warningLevelsgetGlobalServicessgetGlobalServicesNones getServicess getServicesgetServiceDefinitionss getUtilitys queryUtilitysgetUtilitiesForsgetAllUtilitiesRegisteredForsgetAdapterInContextsqueryAdapterInContexts getAdapters adapter_hookszope.interface.interfaceszopes interfaces adapter_hookssappends queryAdaptersgetMultiAdaptersqueryMultiAdapters subscriberss createObjectsgetFactoryInterfacessgetFactoriesForsgetViews queryViews getMultiViewsqueryMultiViewsgetViewProvidingsqueryViewProvidingsgetDefaultViewNamesqueryDefaultViewNames getResources queryResource(/sgetViews getMultiViewsgetServiceDefinitionss queryResourcesqueryViewProvidingsComponentLookupErrorsgetAdapterInContexts getUtilitysIServiceServices Presentations getResourceshookables__all__sgetMultiAdaptersgetAllUtilitiesRegisteredFors Utilitiess queryAdapters InterfacesqueryMultiViewsIFactorys queryUtilitysqueryDefaultViewNamesgetViewProvidingsgetGlobalServicess queryViewswarningssmoduleProvidessqueryMultiAdaptersqueryAdapterInContexts getServicessysszopesgetUtilitiesFors subscriberssserviceManagers adapter_hooks getAdaptersAdapterssgetFactoriesForsgetFactoryInterfacess createObjectsgetGlobalServices IInterfacesIComponentArchitectures getServicess warningLevelsgetDefaultViewName((s5build/bdist.linux-i686/egg/zope/component/__init__.pys?sf                           PK¶“„4>MÈY"Y"zope/component/adapter.pyc;ò Xº2Dc@sãdZdklZdklZlZdklZdkl Z dk l Z l Z l Z dkZdkZdeefd„ƒYZd e fd „ƒYZd eefd „ƒYZd efd„ƒYZdefd„ƒYZdS(sIGlobal Adapter Service $Id: adapter.py 26080 2004-07-02 22:25:52Z jim $ (sComponentLookupError(sIAdapterServices IRegistry(s GlobalService(sAdapterRegistry(s implementss providedBys InterfaceNsIGlobalAdapterServicecBs tZdd„Zdd„ZRS(NscCsdS(s~Register an adapter factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the adapter - `info`: Provide some info about this particular adapter. N((srequiredsprovidedsnamesfactorysinfo((s4build/bdist.linux-i686/egg/zope/component/adapter.pysregisters cCsdS(sƒRegister a subscriber factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the subscriber - `info`: Provide some info about this particular adapter. N((srequiredsprovidedsfactorysinfo((s4build/bdist.linux-i686/egg/zope/component/adapter.pys subscribe(s (s__name__s __module__sregisters subscribe(((s4build/bdist.linux-i686/egg/zope/component/adapter.pysIGlobalAdapterServices sAdapterServicecBstZdZeeƒRS(sŽBase implementation of an adapter service, implementing only the 'IAdapterService' interface. No write-methods were implemented. (s__name__s __module__s__doc__s implementssIAdapterService(((s4build/bdist.linux-i686/egg/zope/component/adapter.pysAdapterService4s sGlobalAdapterServicecBsBtZdZeeƒd„Zdd„Zdd„Zd„ZRS(s&Global Adapter Service implementation.cCsti|ƒh|_dS(N(sAdapterRegistrys__init__sselfs_registrations(sself((s4build/bdist.linux-i686/egg/zope/component/adapter.pys__init__Bs scCsQt|ƒ}t|||||ƒ|i|||f>> registry = GlobalAdapterService() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.register((R1, ), P2, 'bob', 'c1', 'd1') >>> registry.register((R1, ), P2, '', 'c2', 'd2') >>> registry.lookup((R2, ), P1, '') 'c2' >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration AdapterRegistration(('R1',), 'P2', '', 'c2', 'd2') AdapterRegistration(('R1',), 'P2', 'bob', 'c1', 'd1') N( stuplesrequiredsAdapterRegistrationsprovidedsnamesfactorysinfosselfs_registrationssAdapterServicesregister(sselfsrequiredsprovidedsnamesfactorysinfo((s4build/bdist.linux-i686/egg/zope/component/adapter.pysregisterFs (cCsjt|ƒ}t||||ƒ}|ii ||ffƒ|f|i||f>> registry = GlobalAdapterService() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.subscribe((R1, ), P2, 'c1', 'd1') >>> registry.subscribe((R1, ), P2, 'c2', 'd2') >>> subscriptions = map(str, registry.subscriptions((R2, ), P1)) >>> subscriptions.sort() >>> subscriptions ['c1', 'c2'] >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration SubscriptionRegistration(('R1',), 'P2', 'c1', 'd1') SubscriptionRegistration(('R1',), 'P2', 'c2', 'd2') N( stuplesrequiredsSubscriptionRegistrationsprovidedsfactorysinfos registrationsselfs_registrationssgetsAdapterServices subscribe(sselfsrequiredsprovidedsfactorysinfos registration((s4build/bdist.linux-i686/egg/zope/component/adapter.pys subscribefs  /ccsKxD|iiƒD]3}t|tƒox|D] }|Vq-Wq|VqWdS(N(sselfs_registrationss itervaluess registrations isinstancestuplesr(sselfsrs registration((s4build/bdist.linux-i686/egg/zope/component/adapter.pys registrationss ( s__name__s __module__s__doc__s implementssIGlobalAdapterServices__init__sregisters subscribes registrations(((s4build/bdist.linux-i686/egg/zope/component/adapter.pysGlobalAdapterService=s    )sAdapterRegistrationcBs#tZdZdd„Zd„ZRS(s"Registration for a simple adapter.scCs7|||||f\|_|_|_|_|_dS(N(srequiredsprovidedsnamesvaluesdocsself(sselfsrequiredsprovidedsnamesvaluesdoc((s4build/bdist.linux-i686/egg/zope/component/adapter.pys__init__›sc Csid|iitgi}|iD]}|t|dt ƒƒq ~ƒ|i i|i |i |i fSdS(Ns%s(%r, %r, %r, %r, %r)s__name__(sselfs __class__s__name__stuplesappends_[1]srequiredsrsgetattrsNonesprovidedsnamesvaluesdoc(sselfs_[1]sr((s4build/bdist.linux-i686/egg/zope/component/adapter.pys__repr__Ÿs(s__name__s __module__s__doc__s__init__s__repr__(((s4build/bdist.linux-i686/egg/zope/component/adapter.pysAdapterRegistration˜s  sSubscriptionRegistrationcBs tZdZd„Zd„ZRS(s(Registration for a subscription adapter.cCs.||||f\|_|_|_|_dS(N(srequiredsprovidedsvaluesdocsself(sselfsrequiredsprovidedsvaluesdoc((s4build/bdist.linux-i686/egg/zope/component/adapter.pys__init__«sc Cscd|iitgi}|iD]}|t|dt ƒƒq ~ƒ|i i|i |i fSdS(Ns%s(%r, %r, %r, %r)s__name__( sselfs __class__s__name__stuplesappends_[1]srequiredsrsgetattrsNonesprovidedsvaluesdoc(sselfs_[1]sr((s4build/bdist.linux-i686/egg/zope/component/adapter.pys__repr__¯s(s__name__s __module__s__doc__s__init__s__repr__(((s4build/bdist.linux-i686/egg/zope/component/adapter.pysSubscriptionRegistration¨s  (s__doc__szope.component.exceptionssComponentLookupErrorszope.component.interfacessIAdapterServices IRegistryszope.component.services GlobalServiceszope.interface.adaptersAdapterRegistryszope.interfaces implementss providedBys InterfacessysswarningssIGlobalAdapterServicesAdapterServicesGlobalAdapterServicesobjectsAdapterRegistrationsSubscriptionRegistration(s implementssAdapterServices GlobalServicesAdapterRegistrationswarningssSubscriptionRegistrationsComponentLookupErrorsIAdapterServices IRegistryssyss InterfacesGlobalAdapterServices providedBysIGlobalAdapterServicesAdapterRegistry((s4build/bdist.linux-i686/egg/zope/component/adapter.pys?s      [PK¶“„4aEÇkzope/component/service.pyc;ò Xº2Dc@sêdZdklZdklZdklZdklZdefd„ƒYZ de fd„ƒYZ d e fd „ƒYZ d e fd „ƒYZd „Zde fd„ƒYZedeƒZeiZdklZeeiƒ[dS(sVService Manager implementation $Id: service.py 27082 2004-08-12 20:03:58Z srichter $ (sDuplicationError(sIServiceService(sComponentLookupError(s implementssIGlobalServiceManagercBstZd„Zd„ZRS(NcCsdS(sDefine a new service of the given name implementing the given interface. If the name already exists, raises DuplicationErrorN((snames interface((s4build/bdist.linux-i686/egg/zope/component/service.pys defineServicescCsdS(s–Register a service component. Provide a service component to do the work of the named service. If a service component has already been assigned to this name, raise DuplicationError; if the name has not been defined, raises UndefinedService; if the component does not implement the registered interface for the service name, raises InvalidService. N((snames component((s4build/bdist.linux-i686/egg/zope/component/service.pysprovideService s (s__name__s __module__s defineServicesprovideService(((s4build/bdist.linux-i686/egg/zope/component/service.pysIGlobalServiceManagers sUndefinedServicecBstZdZRS(s?An attempt to register a service that has not been defined (s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/component/service.pysUndefinedService,s sInvalidServicecBstZdZRS(sZAn attempt to register a service that doesn't implement the required interface (s__name__s __module__s__doc__(((s4build/bdist.linux-i686/egg/zope/component/service.pysInvalidService0s sGlobalServiceManagercBs`tZdZeeƒeed„Zd„Zd„Zd„Z d„Z e d„Z d„Z RS(sservice managercCs |iƒ||_||_dS(N(sselfs_clearsnames__name__smodules __module__(sselfsnamesmodule((s4build/bdist.linux-i686/egg/zope/component/service.pys__init__:s  cCs(hdt<|_hd|<|_dS(NsServices(sIServiceServicesselfs_GlobalServiceManager__defss_GlobalServiceManager__services(sself((s4build/bdist.linux-i686/egg/zope/component/service.pys_clear?scCs |iSdS(N(sselfs__name__(sself((s4build/bdist.linux-i686/egg/zope/component/service.pys __reduce__CscCs1||ijot|ƒ‚n||i|tZdZeed„Zeed„Zeded„ZRS(s,A service to manage Presentation components.cCsdS(s¶Look up a named resource for a given request The request must implement IPresentationRequest. The default will be returned if the component can't be found. N((snamesrequestsdefaults providing((s7build/bdist.linux-i686/egg/zope/component/interfaces.pys queryResource+scCsdS(s¾Look for a named view for a given object and request The request must implement IPresentationRequest. The default will be returned if the component can't be found. N((sobjectsnamesrequestsdefaults providing((s7build/bdist.linux-i686/egg/zope/component/interfaces.pys queryView3sscCsdS(s†Adapt the given objects and request The first argument is a tuple of objects to be adapted with the request. N((sobjectssrequests providingsnamesdefault((s7build/bdist.linux-i686/egg/zope/component/interfaces.pysqueryMultiView;s(s__name__s __module__s__doc__sNones Interfaces queryResources queryViewsqueryMultiView(((s7build/bdist.linux-i686/egg/zope/component/interfaces.pysIPresentationService(s N(s__doc__szope.interfaces Interfaces Attributeszope.component.exceptionssIComponentArchitectures IRegistrysIServiceServicesIFactorysIUtilityServicesIContextDependentsIAdapterServices IPresentationsIPresentationRequests IResourcesIResourceFactorysIViews IViewFactorysIPresentationService(s IPresentationsIResourceFactorysIPresentationRequests AttributesIContextDependentsIAdapterServices IRegistrysIUtilityServicesIServiceServicesIFactorys IViewFactorys Interfaces IResourcesIViewsIPresentationServicesIComponentArchitecture((s7build/bdist.linux-i686/egg/zope/component/interfaces.pys?s"ÿ\     PK¶“„4b‚´€òòzope/component/utility.pyc;ò Xº2Dc@s±dZdklZlZdklZlZdklZdk l Z dk Z deefd„ƒYZ de fd „ƒYZd eefd „ƒYZd efd „ƒYZdS(sCutility service $Id: utility.py 25389 2004-06-12 13:19:36Z alga $ (sInvalidsComponentLookupError(sIUtilityServices IRegistry(s GlobalService(sAdapterRegistryNsIGlobalUtilityServicecBstZdd„ZRS(NscCsdS(sXProvide a utility A utility is a component that provides an interface. N((sprovidedInterfaces componentsname((s4build/bdist.linux-i686/egg/zope/component/utility.pysprovideUtilitys(s__name__s __module__sprovideUtility(((s4build/bdist.linux-i686/egg/zope/component/utility.pysIGlobalUtilityServicessUtilityServicecBs;tZdZdd„Zded„Zd„Zd„ZRS(stProvide IUtilityService Mixin that superimposes utility management on adapter registery implementation scCs:|i||ƒ}|tj o|Snt||ƒ‚dS(sSee IUtilityService interfaceN(sselfs queryUtilitys interfacesnamescsNonesComponentLookupError(sselfs interfacesnamesc((s4build/bdist.linux-i686/egg/zope/component/utility.pys getUtility's  cCs5|ii|ƒ}|o|i||ƒSn|SdS(sSee IUtilityService interfaceN(sselfs_nullsgets interfacesbynamesnamesdefault(sselfs interfacesnamesdefaultsbyname((s4build/bdist.linux-i686/egg/zope/component/utility.pys queryUtility.s ccs<|ii|ƒ}|ox|iƒD] }|Vq&WndS(N(sselfs_nullsgets interfacesbynames iteritemssitem(sselfs interfacesitemsbyname((s4build/bdist.linux-i686/egg/zope/component/utility.pysgetUtilitiesFor7s  cCs't|iid|fƒpfƒSdS(Nss(sitersselfs_nullsgets interface(sselfs interface((s4build/bdist.linux-i686/egg/zope/component/utility.pysgetAllUtilitiesRegisteredFor=s(s__name__s __module__s__doc__s getUtilitysNones queryUtilitysgetUtilitiesForsgetAllUtilitiesRegisteredFor(((s4build/bdist.linux-i686/egg/zope/component/utility.pysUtilityService s   sGlobalUtilityServicecBs9tZeiieƒd„Zddd„Zd„ZRS(NcCsti|ƒh|_dS(N(sUtilityServices__init__sselfs_registrations(sself((s4build/bdist.linux-i686/egg/zope/component/utility.pys__init__Ds scCsp|i|ƒ otdƒ‚n|if|||ƒ|if||ƒt||||ƒ|i ||f> aazope/component/tests.pyc;ò ã•2Dc@sdZdkZdklZlZdklZdklZdk Z dk l Z dk l Z dk lZdklZlZd efd „ƒYZd efd „ƒYZd efd„ƒYZdefd„ƒYZeƒZdefd„ƒYZdefd„ƒYZedƒZdefd„ƒYZdefd„ƒYZd„Zd„Zd„Zd„Z d„Z!d„Z"d „Z#d!„Z$d"„Z%d#„Z&d$„Z'd%„Z(d&„Z)d'„Z*d(„Z+d)„Z,d*„Z-e.d+joei/d,d-ƒnd.k0l1Z1dS(/sUComponent Architecture Tests $Id: test_api.py 28632 2004-12-16 17:42:59Z srichter $ N(s Interfaces implements(s verifyObject(sdoctest(sComponentLookupError(sIComponentArchitecture(s ISiteManager(ssetUpstearDownsI1cBstZRS(N(s__name__s __module__(((s2build/bdist.linux-i686/egg/zope/component/tests.pysI1ssI2cBstZRS(N(s__name__s __module__(((s2build/bdist.linux-i686/egg/zope/component/tests.pysI2 ssI3cBstZRS(N(s__name__s __module__(((s2build/bdist.linux-i686/egg/zope/component/tests.pysI3"ssObcBstZeeƒd„ZRS(NcCsdSdS(Ns ((sself((s2build/bdist.linux-i686/egg/zope/component/tests.pys__repr__'s(s__name__s __module__s implementssI1s__repr__(((s2build/bdist.linux-i686/egg/zope/component/tests.pysOb%s sOb2cBstZeeƒd„ZRS(NcCsdSdS(Ns((sself((s2build/bdist.linux-i686/egg/zope/component/tests.pys__repr__/s(s__name__s __module__s implementssI2s__repr__(((s2build/bdist.linux-i686/egg/zope/component/tests.pysOb2-s sCompcBstZeeƒd„ZRS(NcCs ||_dS(N(scontextsself(sselfscontext((s2build/bdist.linux-i686/egg/zope/component/tests.pys__init__4s(s__name__s __module__s implementssI2s__init__(((s2build/bdist.linux-i686/egg/zope/component/tests.pysComp2s isComp2cBstZeeƒd„ZRS(NcCs ||_dS(N(scontextsself(sselfscontext((s2build/bdist.linux-i686/egg/zope/component/tests.pys__init__;s(s__name__s __module__s implementssI3s__init__(((s2build/bdist.linux-i686/egg/zope/component/tests.pysComp29s sConformsToISiteManagercBs tZdZd„Zd„ZRS(s]This object allows the sitemanager to conform/adapt to `ISiteManager` and thus to itself.cCs ||_dS(N(s sitemanagersself(sselfs sitemanager((s2build/bdist.linux-i686/egg/zope/component/tests.pys__init__CscCs|tjo |iSndS(sAThis method is specified by the adapter PEP to do the adaptation.N(s interfaces ISiteManagersselfs sitemanager(sselfs interface((s2build/bdist.linux-i686/egg/zope/component/tests.pys __conform__Fs (s__name__s __module__s__doc__s__init__s __conform__(((s2build/bdist.linux-i686/egg/zope/component/tests.pysConformsToISiteManager?s  cCsdS(s¹Ensure that the component architecture API is provided by `zope.component`. >>> import zope.component >>> verifyObject(IComponentArchitecture, zope.component) True N((((s2build/bdist.linux-i686/egg/zope/component/tests.pystestInterfacesLscCsdS(sÃOne of the most important functions is to get the global site manager. >>> from zope.component.site import IGlobalSiteManager, globalSiteManager Get the global site manager via the CA API function: >>> gsm = zope.component.getGlobalSiteManager() Make sure that the global site manager implements the correct interface and is the global site manager instance we expect to get. >>> IGlobalSiteManager.providedBy(gsm) True >>> globalSiteManager is gsm True Finally, ensure that we always get the same global site manager, otherwise our component registry will always be reset. >>> zope.component.getGlobalSiteManager() is gsm True N((((s2build/bdist.linux-i686/egg/zope/component/tests.pystest_getGlobalSiteManagerUscCsdS(s«Make sure that `getSiteManager()` always returns the correct site manager instance. We don't know anything about the default service manager, except that it is an `ISiteManager`. >>> ISiteManager.providedBy(zope.component.getSiteManager()) True Calling `getSiteManager()` with no args is equivalent to calling it with a context of `None`. >>> zope.component.getSiteManager() is zope.component.getSiteManager(None) True If the context passed to `getSiteManager()` is not `None`, it is adapted to `ISiteManager` and this adapter returned. So, we create a context that can be adapted to `ISiteManager` using the `__conform__` API. Let's create the simplest stub-implementation of a site manager possible: >>> sitemanager = object() Now create a context that knows how to adapt to our newly created site manager. >>> context = ConformsToISiteManager(sitemanager) Now make sure that the `getSiteManager()` API call returns the correct site manager. >>> zope.component.getSiteManager(context) is sitemanager True Using a context that is not adaptable to `ISiteManager` should fail. >>> zope.component.getSiteManager(ob) #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: ('Could not adapt', , ) N((((s2build/bdist.linux-i686/egg/zope/component/tests.pystest_getSiteManagerms*cCsdS(s” The `getAdapterInContext()` and `queryAdapterInContext()` API functions do not only use the site manager to look up the adapter, but first tries to use the `__conform__()` method of the object to find an adapter as specified by PEP 246. Let's start by creating a component that support's the PEP 246's `__conform__()` method: >>> class Component(object): ... implements(I1) ... def __conform__(self, iface, default=None): ... if iface == I2: ... return 42 ... def __repr__(self): ... return '''''' >>> ob = Component() We also gave the component a custom representation, so it will be easier to use in these tests. We now have to create a site manager (other than the default global one) with which we can register adapters for `I1`. >>> from zope.component.site import GlobalSiteManager >>> sitemanager = GlobalSiteManager() Now we create a new `context` that knows how to get to our custom site manager. >>> context = ConformsToISiteManager(sitemanager) We now register an adapter from `I1` to `I3`: >>> sitemanager.provideAdapter((I1,), I3, '', lambda x: 43) If an object implements the interface you want to adapt to, `getAdapterInContext()` should simply return the object. >>> zope.component.getAdapterInContext(ob, I1, context) >>> zope.component.queryAdapterInContext(ob, I1, context) If an object conforms to the interface you want to adapt to, `getAdapterInContext()` should simply return the conformed object. >>> zope.component.getAdapterInContext(ob, I2, context) 42 >>> zope.component.queryAdapterInContext(ob, I2, context) 42 If an adapter isn't registered for the given object and interface, and you provide no default, raise ComponentLookupError... >>> class I4(Interface): ... pass >>> zope.component.getAdapterInContext(ob, I4, context) \ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, ) ...otherwise, you get the default: >>> zope.component.queryAdapterInContext(ob, I4, context, 44) 44 If you ask for an adapter for which something's registered you get the registered adapter >>> zope.component.getAdapterInContext(ob, I3, context) 43 >>> zope.component.queryAdapterInContext(ob, I3, context) 43 N((sself((s2build/bdist.linux-i686/egg/zope/component/tests.pystestAdapterInContext™sNcCsdS(s<The `getAdapter()` and `queryAdapter()` API functions are similar to `{get|query}AdapterInContext()` functions, except that they do not care about the `__conform__()` but also handle named adapters. (Actually, the name is a required argument.) If an adapter isn't registered for the given object and interface, and you provide no default, raise `ComponentLookupError`... >>> zope.component.getAdapter(ob, I2, '') #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, , '') ...otherwise, you get the default >>> zope.component.queryAdapter(ob, I2, '', '') '' Now get the global site manager and register an adapter from `I1` to `I2` without a name: >>> zope.component.getGlobalSiteManager().provideAdapter( ... (I1,), I2, '', Comp) You should get a sensible error message if you forget that the 'requires' argument is supposed to be a sequence >>> zope.component.getGlobalSiteManager().provideAdapter( ... I1, I2, '', Comp) Traceback (most recent call last): ... TypeError: the required argument should be a list of interfaces, not a single interface You can now simply access the adapter using the `getAdapter()` API function: >>> adapter = zope.component.getAdapter(ob, I2, '') >>> adapter.__class__ is Comp True >>> adapter.context is ob True N((((s2build/bdist.linux-i686/egg/zope/component/tests.pys testAdapterés,cCsdS(sÅHere we test the `adapter_hook()` function that we registered with the `zope.interface` adapter hook registry, so that we can call interfaces to do adaptation. First, we need to register an adapter: >>> zope.component.getGlobalSiteManager().provideAdapter( ... [I1], I2, '', Comp) Then we try to adapt `ob` to provide an `I2` interface by calling the `I2` interface with the obejct as first argument: >>> adapter = I2(ob) >>> adapter.__class__ is Comp True >>> adapter.context is ob True If no adapter is found, a `TypeError is raised... >>> I1(Ob2()) #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: ('Could not adapt', , ) ...unless we specify an alternative adapter: >>> marker = object() >>> I2(object(), marker) is marker True N((((s2build/bdist.linux-i686/egg/zope/component/tests.pystestInterfaceCalls cCsdS(sRMake sure that adapters with names are correctly selected from the registry. First we register some named adapter: >>> zope.component.getGlobalSiteManager().provideAdapter( ... [I1], I2, 'foo', lambda x: 0) If an adapter isn't registered for the given object and interface, and you provide no default, raise `ComponentLookupError`... >>> zope.component.getAdapter(ob, I2, 'bar') \ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, , 'bar') ...otherwise, you get the default >>> zope.component.queryAdapter(ob, I2, 'bar', '') '' But now we register an adapter for the object having the correct name >>> zope.component.getGlobalSiteManager().provideAdapter( ... [I1], I2, 'bar', Comp) so that the lookup succeeds: >>> adapter = zope.component.getAdapter(ob, I2, 'bar') >>> adapter.__class__ is Comp True >>> adapter.context is ob True N((((s2build/bdist.linux-i686/egg/zope/component/tests.pystestNamedAdapter9s$cCsdS(s|Adapting a combination of 2 objects to an interface Multi-adapters adapt one or more objects to another interface. To make this demonstration non-trivial, we need to create a second object to be adapted: >>> ob2 = Ob2() Like for regular adapters, if an adapter isn't registered for the given objects and interface, and you provide no default, raise `ComponentLookupError`... >>> zope.component.getMultiAdapter((ob, ob2), I3) \ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: ((, ), , u'') ...otherwise, you get the default >>> zope.component.queryMultiAdapter((ob, ob2), I3, default='') '' Note that the name is not a required attribute here. To test multi-adapters, we also have to create an adapter class that handles to context objects: >>> class DoubleAdapter(object): ... implements(I3) ... def __init__(self, first, second): ... self.first = first ... self.second = second Now we can register the multi-adapter using >>> zope.component.getGlobalSiteManager().provideAdapter( ... (I1, I2), I3, '', DoubleAdapter) Notice how the required interfaces are simply provided by a tuple. Now we can get the adapter: >>> adapter = zope.component.getMultiAdapter((ob, ob2), I3) >>> adapter.__class__ is DoubleAdapter True >>> adapter.first is ob True >>> adapter.second is ob2 True N((((s2build/bdist.linux-i686/egg/zope/component/tests.pystestMultiAdapter_s5cCsdS(sProviding an adapter for None says that your adapter can adapt anything to `I2`. >>> zope.component.getGlobalSiteManager().provideAdapter( ... (None,), I2, '', Comp) >>> adapter = I2(ob) >>> adapter.__class__ is Comp True >>> adapter.context is ob True It can really adapt any arbitrary object: >>> something = object() >>> adapter = I2(something) >>> adapter.__class__ is Comp True >>> adapter.context is something True N((((s2build/bdist.linux-i686/egg/zope/component/tests.pystestAdapterForInterfaceNone–scCsdS(sfIt is sometimes desireable to get a list of all adapters that are registered for a particular output interface, given a set of objects. Let's register some adapters first: >>> zope.component.getGlobalSiteManager().provideAdapter( ... [I1], I2, '', Comp) >>> zope.component.getGlobalSiteManager().provideAdapter( ... [None], I2, 'foo', Comp) Now we get all the adapters that are registered for `ob` that provide `I2`: >>> adapters = zope.component.getAdapters((ob,), I2) >>> adapters.sort() >>> [(name, adapter.__class__.__name__) for name, adapter in adapters] [(u'', 'Comp'), (u'foo', 'Comp')] Note that the output doesn't include None values. If an adapter factory returns None, it is as if it wasn't present. >>> zope.component.getGlobalSiteManager().provideAdapter( ... [I1], I2, 'nah', lambda context: None) >>> adapters = zope.component.getAdapters((ob,), I2) >>> adapters.sort() >>> [(name, adapter.__class__.__name__) for name, adapter in adapters] [(u'', 'Comp'), (u'foo', 'Comp')] N((((s2build/bdist.linux-i686/egg/zope/component/tests.pystestGetAdapters­scCsdS(s Utilities are components that simply provide an interface. They are instantiated at the time or before they are registered. Here we test the simple query interface. Before we register any utility, there is no utility available, of course. The pure instatiation of an object does not make it a utility. If you do not specify a default, you get a `ComponentLookupError`... >>> zope.component.getUtility(I1) #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, '') ...otherwise, you get the default >>> zope.component.queryUtility(I1, default='') '' >>> zope.component.queryUtility(I2, default='') '' Now we declare `ob` to be the utility providing `I1` >>> zope.component.getGlobalSiteManager().provideUtility(I1, ob) so that the component is now available: >>> zope.component.getUtility(I1) is ob True N((((s2build/bdist.linux-i686/egg/zope/component/tests.pys testUtilityÍscCsdS(sILike adapters, utilities can be named. Just because you register an utility having no name >>> zope.component.getGlobalSiteManager().provideUtility(I1, ob) does not mean that they are available when you specify a name: >>> zope.component.getUtility(I1, name='foo') \ ... #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (, 'foo') ...otherwise, you get the default >>> zope.component.queryUtility(I1, name='foo', default='') '' Registering the utility under the correct name >>> zope.component.getGlobalSiteManager().provideUtility( ... I1, ob, name='foo') really helps: >>> zope.component.getUtility(I1, 'foo') is ob True N((((s2build/bdist.linux-i686/egg/zope/component/tests.pystestNamedUtilityíscCsdS(sAgain, like for adapters, it is often useful to get a list of all utilities that have been registered for a particular interface. Utilities providing a derived interface are also listed. Thus, let's create a derivative interface of `I1`: >>> class I11(I1): ... pass >>> class Ob11(Ob): ... implements(I11) >>> ob11 = Ob11() >>> ob_bob = Ob() Now we register the new utilities: >>> gsm = zope.component.getGlobalSiteManager() >>> gsm.provideUtility(I1, ob) >>> gsm.provideUtility(I11, ob11) >>> gsm.provideUtility(I1, ob_bob, name='bob') >>> gsm.provideUtility(I2, Comp(2)) We can now get all the utilities that provide interface `I1`: >>> uts = list(zope.component.getAllUtilitiesRegisteredFor(I1)) >>> uts = [util.__class__.__name__ for util in uts] >>> uts.sort() >>> uts ['Ob', 'Ob', 'Ob11'] Note that `getAllUtilitiesRegisteredFor()` does not return the names of the utilities. N((((s2build/bdist.linux-i686/egg/zope/component/tests.pys!test_getAllUtilitiesRegisteredFors"cCsdS(s™Make sure that the adapter lookup is not broken, when no site manager is available. Both of those things emit `DeprecationWarnings`. >>> I2(ob) #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: ('Could not adapt', , ) >>> I2(ob, 42) 42 N((((s2build/bdist.linux-i686/egg/zope/component/tests.pystestNotBrokenWhenNoSiteManager2scCsdS(sp We want to make sure that an `adapts()` call in a class definition doesn't affect instances. >>> import zope.component >>> class C: ... zope.component.adapts() >>> C.__component_adapts__ () >>> C().__component_adapts__ Traceback (most recent call last): ... AttributeError: __component_adapts__ N((((s2build/bdist.linux-i686/egg/zope/component/tests.pys!testNo__component_adapts__leakageEscCsdS(sO We need to make sure that it is possible to pickle the global site manager and its two global adapter registries. >>> from zope.component import site >>> import cPickle >>> pickle = cPickle.dumps(site.globalSiteManager) >>> sm = cPickle.loads(pickle) >>> sm is site.globalSiteManager True Now let's ensure that the registries themselves can be pickled as well: >>> pickle = cPickle.dumps(site.globalSiteManager.adapters) >>> adapters = cPickle.loads(pickle) >>> adapters is site.globalSiteManager.adapters True N((((s2build/bdist.linux-i686/egg/zope/component/tests.pys(test_ability_to_pickle_globalsitemanagerVsc CsztitidtdtƒtidƒtiddtdtƒtiddtdtƒtiddtdtƒfƒSdS(NssetUpstearDownszope.component.sites README.txtssocketexample.txts factory.txt(sunittests TestSuitesdoctests DocTestSuitessetUpstearDowns DocFileSuite(((s2build/bdist.linux-i686/egg/zope/component/tests.pys test_suitejs0s__main__s defaultTests test_suite(splacelesssetup(2s__doc__sunittestszope.interfaces Interfaces implementsszope.interface.verifys verifyObjects zope.testingsdoctestszope.componentszopeszope.component.interfacessComponentLookupErrorsIComponentArchitectures ISiteManagerszope.component.testingssetUpstearDownsI1sI2sI3sobjectsObsobsOb2sCompscompsComp2sConformsToISiteManagerstestInterfacesstest_getGlobalSiteManagerstest_getSiteManagerstestAdapterInContexts testAdapterstestInterfaceCallstestNamedAdapterstestMultiAdapterstestAdapterForInterfaceNonestestGetAdapterss testUtilitystestNamedUtilitys!test_getAllUtilitiesRegisteredForstestNotBrokenWhenNoSiteManagers!testNo__component_adapts__leakages(test_ability_to_pickle_globalsitemanagers test_suites__name__smainszope.component.bbb.testssplacelesssetup('stearDownsunittestsComponentLookupErrors testAdapters!testNo__component_adapts__leakagesOb2stest_getGlobalSiteManagers testUtilitysI1sCompsI3sI2stestAdapterInContextsConformsToISiteManagerstestAdapterForInterfaceNonescompszopestestInterfacessIComponentArchitecturestestMultiAdapterstestNamedAdapters ISiteManagerssetUpsObsplacelesssetups InterfacestestGetAdaptersstest_getSiteManagers implementss!test_getAllUtilitiesRegisteredForstestNamedUtilitys verifyObjectstestInterfaceCallsobsComp2s(test_ability_to_pickle_globalsitemanagers test_suitesdocteststestNotBrokenWhenNoSiteManager((s2build/bdist.linux-i686/egg/zope/component/tests.pys?sN           , P . " & 7  ! $    PK¶“„4©ê_d´D´Dzope/component/site.pyc;ò ã•2Dc@sGdZdZdkZdklZlZlZlZdkl Z dk l Z dk l Z lZdk lZlZde efd „ƒYZd efd „ƒYZd efd „ƒYZd„Zde fd„ƒYZedƒZdklZed„ƒ[defd„ƒYZdefd„ƒYZdefd„ƒYZdS(sGlobal Site Manager $Id$ sreStructuredTextN(s implementss providedBys implementedBys declarations(sAdapterRegistry(s IInterface(s ISiteManagers IRegistry(sComponentLookupErrorsInvalidsIGlobalSiteManagercBs2tZdd„Zdd„Zdded„ZRS(NscCsdS(s}Register an adapter factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the adapter - `info`: Provide some info about this particular adapter. N((srequiredsprovidedsnamesfactorysinfo((s1build/bdist.linux-i686/egg/zope/component/site.pysprovideAdapters cCsdS(s‚Register a subscriber factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the subscriber - `info`: Provide some info about this particular adapter. N((srequiredsprovidedsfactorysinfo((s1build/bdist.linux-i686/egg/zope/component/site.pys subscribe+s cCsdS(sÃRegister a utility If strict is true, then the specified component *must* implement the `providedInterface`. Turning strict off is particularly useful for tests. N((sprovidedInterfaces componentsnamesinfosstrict((s1build/bdist.linux-i686/egg/zope/component/site.pysprovideUtility7s(s__name__s __module__sprovideAdapters subscribesTruesprovideUtility(((s1build/bdist.linux-i686/egg/zope/component/site.pysIGlobalSiteManagers s SiteManagercBs\tZdZed„Zded„Zd„Zd„Zded„Zd„Z d„Z RS( sSite Manager implementationcCs|ii||||ƒSdS(sSee ISiteManager interfaceN(sselfsadapterss queryAdaptersobjects interfacesnamesdefault(sselfsobjects interfacesnamesdefault((s1build/bdist.linux-i686/egg/zope/component/site.pys queryAdapterDsscCs|ii||||ƒSdS(sSee ISiteManager interfaceN(sselfsadapterssqueryMultiAdaptersobjectss interfacesnamesdefault(sselfsobjectss interfacesnamesdefault((s1build/bdist.linux-i686/egg/zope/component/site.pysqueryMultiAdapterHscCsmg}x\|iitt|ƒ|ƒD]<\}}||Œ}|t j o|i ||fƒq%q%W|SdS(sSee ISiteManager interfaceN( sresultsselfsadapterss lookupAllsmaps providedBysobjectssprovidedsnamesfactorysadaptersNonesappend(sselfsobjectssprovidedsnamesfactorysresultsadapter((s1build/bdist.linux-i686/egg/zope/component/site.pys getAdaptersMs   cCs|ii||ƒSdS(sSee ISiteManager interfaceN(sselfsadapterss subscriberssrequiredsprovided(sselfsrequiredsprovided((s1build/bdist.linux-i686/egg/zope/component/site.pys subscribersWscCs8|iii|ƒ}|o|i||ƒSn|SdS(sSee ISiteManager interfaceN(sselfs utilitiess_nullsgets interfacesbynamesnamesdefault(sselfs interfacesnamesdefaultsbyname((s1build/bdist.linux-i686/egg/zope/component/site.pys queryUtility[s ccs?|iii|ƒ}|ox|iƒD] }|Vq)WndS(N(sselfs utilitiess_nullsgets interfacesbynames iteritemssitem(sselfs interfacesitemsbyname((s1build/bdist.linux-i686/egg/zope/component/site.pysgetUtilitiesFords  cCs*t|iiid|fƒpfƒSdS(Nss(sitersselfs utilitiess_nullsgets interface(sselfs interface((s1build/bdist.linux-i686/egg/zope/component/site.pysgetAllUtilitiesRegisteredForjs( s__name__s __module__s__doc__sNones queryAdaptersqueryMultiAdapters getAdapterss subscriberss queryUtilitysgetUtilitiesForsgetAllUtilitiesRegisteredFor(((s1build/bdist.linux-i686/egg/zope/component/site.pys SiteManagerAs    sGlobalSiteManagercBs`tZdZeeƒed„Zdd„Zdd„Zdde d„Z d„Z d„Z RS(s#Global Site Manager implementation.cCs:||_h|_t|dƒ|_t|dƒ|_dS(Nsadapterss utilities(snamesselfs__name__s_registrationssGlobalAdapterRegistrysadapterss utilities(sselfsname((s1build/bdist.linux-i686/egg/zope/component/site.pys__init__ss  scCsðti|ƒotdƒ‚ng}xv|D]n}ti|ƒ o |tj o=t|tt i fƒ ot|tƒ‚nt |ƒ}n|i |ƒq-Wt |ƒ}t|||||ƒ|i|||f<|ii||||ƒdS(s­Register an adapter >>> from zope.interface import Interface >>> registry = GlobalSiteManager() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.provideAdapter((R1, ), P2, 'bob', 'c1', 'd1') >>> registry.provideAdapter((R1, ), P2, '', 'c2', 'd2') >>> registry.adapters.lookup((R2, ), P1, '') 'c2' >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration AdapterRegistration(('R1',), 'P2', '', 'c2', 'd2') AdapterRegistration(('R1',), 'P2', 'bob', 'c1', 'd1') Let's make sure that we can also register regular classes for adaptation. >>> class O1(object): ... pass >>> class O2(object): ... pass >>> class O3(object): ... def __init__(self, obj1, obj2=None): ... pass >>> registry.provideAdapter((O1, ), R1, '', O3) >>> registry.queryAdapter(O1(), R1, '').__class__ >>> registry.provideAdapter((O1, O2), R1, '', O3) >>> registry.queryMultiAdapter((O1(), O2()), R1, '').__class__ sLthe required argument should be a list of interfaces, not a single interfaceN(s IInterfaces providedBysrequireds TypeErrorsifacessifacesNones isinstancestypestypess ClassTypes implementedBysappendstuplesAdapterRegistrationsprovidedsnamesfactorysinfosselfs_registrationssadapterssregister(sselfsrequiredsprovidedsnamesfactorysinfosifacessiface((s1build/bdist.linux-i686/egg/zope/component/site.pysprovideAdapterzs, (cCsýg}xŠ|D]‚}ti|ƒ ot|tiƒ o |tj o=t|t t i fƒ ot |tƒ‚nt |ƒ}n|i|ƒq Wt|ƒ}t||||ƒ}|ii||ffƒ|f|i||f<|ii|||ƒdS(s­Register an subscriptions adapter >>> from zope.interface import Interface >>> registry = GlobalSiteManager() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.subscribe((R1, ), P2, 'c1', 'd1') >>> registry.subscribe((R1, ), P2, 'c2', 'd2') >>> subscriptions = map(str, ... registry.adapters.subscriptions((R2, ), P1)) >>> subscriptions.sort() >>> subscriptions ['c1', 'c2'] >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration SubscriptionRegistration(('R1',), 'P2', 'c1', 'd1') SubscriptionRegistration(('R1',), 'P2', 'c2', 'd2') N(sifacessrequiredsifaces IInterfaces providedBys isinstances declarationss ImplementssNonestypestypess ClassTypes TypeErrors implementedBysappendstuplesSubscriptionRegistrationsprovidedsfactorysinfos registrationsselfs_registrationssgetsadapterss subscribe(sselfsrequiredsprovidedsfactorysinfosifacesifacess registration((s1build/bdist.linux-i686/egg/zope/component/site.pys subscribe¹s2 /cCs}|o|i|ƒ otdƒ‚n|iif|||ƒ|ii f||ƒt ||||ƒ|i ||f!ssAdapterRegistrationcBs,tZdZdd„Zd„Zd„ZRS(s"Registration for a simple adapter.scCs7|||||f\|_|_|_|_|_dS(N(srequiredsprovidedsnamesvaluesdocsself(sselfsrequiredsprovidedsnamesvaluesdoc((s1build/bdist.linux-i686/egg/zope/component/site.pys__init__)sc Csrd|iitgi}|iD]}|t|dt ƒƒq ~ƒt|i dt ƒ|i |i |i fSdS(Ns%s(%r, %r, %r, %r, %r)s__name__(sselfs __class__s__name__stuplesappends_[1]srequiredsrsgetattrsNonesprovidedsnamesvaluesdoc(sselfs_[1]sr((s1build/bdist.linux-i686/egg/zope/component/site.pys__repr__-scCst|iƒ|iƒƒSdS(N(scmpsselfs__repr__sother(sselfsother((s1build/bdist.linux-i686/egg/zope/component/site.pys__cmp__5s(s__name__s __module__s__doc__s__init__s__repr__s__cmp__(((s1build/bdist.linux-i686/egg/zope/component/site.pysAdapterRegistration&s   sSubscriptionRegistrationcBs)tZdZd„Zd„Zd„ZRS(s(Registration for a subscription adapter.cCs.||||f\|_|_|_|_dS(N(srequiredsprovidedsvaluesdocsself(sselfsrequiredsprovidedsvaluesdoc((s1build/bdist.linux-i686/egg/zope/component/site.pys__init__<sc Csld|iitgi}|iD]}|t|dt ƒƒq ~ƒt|i dt ƒ|i |i fSdS(Ns%s(%r, %r, %r, %r)s__name__( sselfs __class__s__name__stuplesappends_[1]srequiredsrsgetattrsNonesprovidedsvaluesdoc(sselfs_[1]sr((s1build/bdist.linux-i686/egg/zope/component/site.pys__repr__@scCst|iƒ|iƒƒSdS(N(scmpsselfs__repr__sother(sselfsother((s1build/bdist.linux-i686/egg/zope/component/site.pys__cmp__Gs(s__name__s __module__s__doc__s__init__s__repr__s__cmp__(((s1build/bdist.linux-i686/egg/zope/component/site.pysSubscriptionRegistration9s   sUtilityRegistrationcBs#tZd„Zd„Zd„ZRS(NcCs.||||f\|_|_|_|_dS(N(sprovidedsnames componentsdocsself(sselfsprovidedsnames componentsdoc((s1build/bdist.linux-i686/egg/zope/component/site.pys__init__MscCsHd|iit|idtƒ|it|id|iƒ|ifSdS(Ns%s(%r, %r, %r, %r)s__name__( sselfs __class__s__name__sgetattrsprovidedsNonesnames componentsdoc(sself((s1build/bdist.linux-i686/egg/zope/component/site.pys__repr__QscCst|iƒ|iƒƒSdS(N(scmpsselfs__repr__sother(sselfsother((s1build/bdist.linux-i686/egg/zope/component/site.pys__cmp__Xs(s__name__s __module__s__init__s__repr__s__cmp__(((s1build/bdist.linux-i686/egg/zope/component/site.pysUtilityRegistrationKs  (s__doc__s __docformat__stypesszope.interfaces implementss providedBys implementedBys declarationsszope.interface.adaptersAdapterRegistryszope.interface.interfacess IInterfaceszope.component.interfacess ISiteManagers IRegistrysComponentLookupErrorsInvalidsIGlobalSiteManagersobjects SiteManagersGlobalSiteManagersGARsGlobalAdapterRegistrysglobalSiteManagerszope.testing.cleanups addCleanUpsAdapterRegistrationsSubscriptionRegistrationsUtilityRegistration(sglobalSiteManagersAdapterRegistrationsGlobalAdapterRegistrysComponentLookupErrorsSubscriptionRegistrations IRegistrys __docformat__sAdapterRegistrysUtilityRegistrations implementedBysGARsGlobalSiteManagers ISiteManagers addCleanUpsInvalids providedBysIGlobalSiteManagerstypess implementss SiteManagers declarationss IInterface((s1build/bdist.linux-i686/egg/zope/component/site.pys?s&   $-›    PK]^„4ŒØŠÚ$$&zope/component/bbb/contextdependent.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """A simple mix-in class that implements IContextDependent. $Id: contextdependent.py 29143 2005-02-14 22:43:16Z srichter $ """ from zope.component.interfaces import IContextDependent from zope.interface import implements class ContextDependent(object): """standard boilerplate for context dependent objects""" implements(IContextDependent) def __init__(self, context): self.context = context PK]^„4¥—­ê$$zope/component/bbb/__init__.py############################################################################## # # Copyright (c) 2004 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Component Architecture API Backward-Compatibility $Id: __init__.py 38606 2005-09-24 22:35:29Z faassen $ """ __docformat__ = "reStructuredText" __warn__ = True import sys import warnings from zope.interface import Interface, providedBy from zope.component.bbb.interfaces import IServiceService, IDefaultViewName from zope.component.bbb.service import GlobalServiceManager # Try to be hookable. Do so in a try/except to avoid a hard dependency. try: from zope.hookable import hookable except ImportError: def hookable(ob): return ob def warningLevel(): """Returns the number of the first stack frame outside of zope.component""" try: level = 2 while sys._getframe(level).f_globals['__name__']=='zope.component.bbb': level += 1 return level except ValueError: return 2 def getGlobalServices(): if __warn__: warnings.warn( "The concept of services has been deprecated. You probably want to " "use `getGlobalSiteManager()`.", DeprecationWarning, warningLevel()) from zope.component import getGlobalSiteManager return GlobalServiceManager('servicemanager', 'zope.component.service', getGlobalSiteManager()) def getGlobalService(name): if __warn__: warnings.warn( "The concept of services has been deprecated. You probably want to " "use `getGlobalSiteManager()` or `getUtility()`.", DeprecationWarning, warningLevel()) return getGlobalServices().getService(name) def getServices(context=None): if __warn__: warnings.warn( "The concept of services has been deprecated. You probably want to " "use `getGlobalSiteManager()` or `getUtility()`.", DeprecationWarning, warningLevel()) if context is None: return getGlobalServices() else: # Use the global service manager to adapt context to IServiceService # to avoid the recursion implied by using a local getAdapter call. try: return IServiceService(context) except TypeError, error: from zope.component.bbb.exceptions import ComponentLookupError raise ComponentLookupError(*error.args) getServices = hookable(getServices) def getService(name, context=None): if __warn__: warnings.warn( "The concept of services has been deprecated. You probably want to " "use `getGlobalSiteManager()` or `getUtility()`.", DeprecationWarning, warningLevel()) return getServices(context).getService(name) def getServiceDefinitions(context=None): if __warn__: warnings.warn( "The concept of services has been deprecated.", DeprecationWarning, warningLevel()) return getServices(context).getServiceDefinitions() # Presentation API def getView(object, name, request, providing=Interface, context=None): if __warn__: warnings.warn( "The concrete concept of a view has been deprecated. You want to " "use `getMultiAdapter((object, request), providing, name, " "context)`.", DeprecationWarning, warningLevel()) view = queryView(object, name, request, context=context, providing=providing) if view is not None: return view from zope.component.bbb.exceptions import ComponentLookupError raise ComponentLookupError("Couldn't find view", name, object, context, request, providing) def queryView(object, name, request, default=None, providing=Interface, context=None): if __warn__: warnings.warn( "The concrete concept of a view has been deprecated. You want to " "use `queryMultiAdapter((object, request), providing, name, " "default, context)`.", DeprecationWarning, warningLevel()) from zope.component import queryMultiAdapter return queryMultiAdapter((object, request), providing, name, default, context) queryView = hookable(queryView) def getMultiView(objects, request, providing=Interface, name='', context=None): if __warn__: warnings.warn( "The concrete concept of a view has been deprecated. You want to " "use `getMultiAdapter(objects+(request,), providing, name, " "context)`.", DeprecationWarning, warningLevel()) view = queryMultiView(objects, request, providing, name, context=context) if view is not None: return view from zope.component.bbb.exceptions import ComponentLookupError raise ComponentLookupError("Couldn't find view", name, objects, context, request) def queryMultiView(objects, request, providing=Interface, name='', default=None, context=None): if __warn__: warnings.warn( "The concrete concept of a view has been deprecated. You want to " "use `getMultiAdapter(objects+(request,), providing, name, " "default, context)`.", DeprecationWarning, warningLevel()) from zope.component import queryMultiAdapter return queryMultiAdapter(objects+(request,), providing, name, default, context) def getViewProviding(object, providing, request, context=None): if __warn__: warnings.warn( "The concrete concept of a view has been deprecated. You want to " "use `getMultiAdapter((object, request), providing, name, " "context)`.", DeprecationWarning, warningLevel()) return getView(object, '', request, providing, context) def queryViewProviding(object, providing, request, default=None, context=None): if __warn__: warnings.warn( "The concrete concept of a view has been deprecated. You want to " "use `queryMultiAdapter((object, request), providing, name, " "default, context)`.", DeprecationWarning, warningLevel()) return queryView(object, '', request, default, providing, context) def getDefaultViewName(object, request, context=None): if __warn__: warnings.warn( "The concrete concept of a view has been deprecated. You want to " "use `zapi.getDefaultViewName()` instead.", DeprecationWarning, warningLevel()) view = queryDefaultViewName(object, request, context=context) if view is not None: return view from zope.component.bbb.exceptions import ComponentLookupError raise ComponentLookupError("Couldn't find default view name", context, request) def queryDefaultViewName(object, request, default=None, context=None): if __warn__: warnings.warn( "The concrete concept of a view has been deprecated. You want to " "use `zapi.queryDefaultViewName()` instead.", DeprecationWarning, warningLevel()) from zope.component.bbb.exceptions import ComponentLookupError from zope.component import getSiteManager try: adapters = getSiteManager(context) except ComponentLookupError: # Oh blast, no adapter service. We're probably just running from a test return default name = adapters.adapters.lookup(map(providedBy, (object, request)), IDefaultViewName) if name is not None: return name return default def getResource(name, request, providing=Interface, context=None): if __warn__: warnings.warn( "The concrete concept of a resource has been deprecated. You want " "to use `getAdapter(request, providing, name, context)`", DeprecationWarning, warningLevel()) view = queryResource(name, request, providing=providing, context=context) if view is not None: return view from zope.component.bbb.exceptions import ComponentLookupError raise ComponentLookupError("Couldn't find resource", name, request) def queryResource(name, request, default=None, providing=Interface, context=None): if __warn__: warnings.warn( "The concrete concept of a resource has been deprecated. You want " "to use `queryAdapter(request, providing, name, default, context)`", DeprecationWarning, warningLevel()) from zope.component import queryAdapter return queryAdapter(request, providing, name, default, context) PK]^„4 O¯¬¬zope/component/bbb/adapter.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Global Adapter Service $Id: adapter.py 39752 2005-10-30 20:16:09Z srichter $ """ __docformat__ = "reStructuredText" import sys import warnings from types import ClassType from zope.component.exceptions import ComponentLookupError from zope.component.interfaces import IAdapterService, IRegistry from zope.component.bbb.service import GlobalService from zope.component.site import AdapterRegistration, SubscriptionRegistration from zope.interface import implements, providedBy, Interface, implementedBy from zope.interface.interfaces import IInterface class IGlobalAdapterService(IAdapterService, IRegistry): def register(required, provided, name, factory, info=''): """Register an adapter factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the adapter - `info`: Provide some info about this particular adapter. """ def subscribe(required, provided, factory, info=''): """Register a subscriber factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the subscriber - `info`: Provide some info about this particular adapter. """ class AdapterService(object): """Base implementation of an adapter service, implementing only the `IAdapterService` interface. No write-methods were implemented. """ implements(IAdapterService) def __init__(self, sitemanager=None): if sitemanager is None: from zope.component.site import GlobalSiteManager sitemanager = GlobalSiteManager() self.sm = sitemanager def __getattr__(self, name): attr = getattr(self.sm.adapters, name) if attr is not None: return attr raise AttributeError(name) class GlobalAdapterService(AdapterService, GlobalService): """Global Adapter Service implementation.""" implements(IGlobalAdapterService) def __init__(self, sitemanager=None): super(GlobalAdapterService, self).__init__(sitemanager) def register(self, required, provided, name, factory, info=''): """Register an adapter >>> registry = GlobalAdapterService() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.register((R1, ), P2, 'bob', 'c1', 'd1') >>> registry.register((R1, ), P2, '', 'c2', 'd2') >>> registry.lookup((R2, ), P1, '') 'c2' >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration AdapterRegistration(('R1',), 'P2', '', 'c2', 'd2') AdapterRegistration(('R1',), 'P2', 'bob', 'c1', 'd1') Let's make sure that we can also register regular classes for adaptation. >>> class O1(object): ... pass >>> class O2(object): ... pass >>> class O3(object): ... def __init__(self, obj1, obj2=None): ... pass >>> registry.register((O1, ), R1, '', O3) >>> registry.queryAdapter(O1(), R1, '').__class__ >>> registry.register((O1, O2), R1, '', O3) >>> registry.queryMultiAdapter((O1(), O2()), R1, '').__class__ """ self.sm.provideAdapter(required, provided, name, factory, info) def subscribe(self, required, provided, factory, info=''): """Register an subscriptions adapter >>> registry = GlobalAdapterService() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.subscribe((R1, ), P2, 'c1', 'd1') >>> registry.subscribe((R1, ), P2, 'c2', 'd2') >>> subscriptions = map(str, registry.subscriptions((R2, ), P1)) >>> subscriptions.sort() >>> subscriptions ['c1', 'c2'] >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration SubscriptionRegistration(('R1',), 'P2', 'c1', 'd1') SubscriptionRegistration(('R1',), 'P2', 'c2', 'd2') """ self.sm.subscribe(required, provided, factory, info) def registrations(self): for registration in self.sm.registrations(): if isinstance(registration, (AdapterRegistration, SubscriptionRegistration)): yield registration PK]^„4;Œ(zzzope/component/bbb/service.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Service Manager implementation $Id: service.py 29143 2005-02-14 22:43:16Z srichter $ """ __warn__ = True import warnings from zope.exceptions import DuplicationError from zope.component.bbb.interfaces import IServiceService from zope.interface import implements, Interface, directlyProvides class IGlobalServiceManager(IServiceService): def defineService(name, interface): """Define a new service of the given name implementing the given interface. If the name already exists, raises DuplicationError""" def provideService(name, component): """Register a service component. Provide a service component to do the work of the named service. If a service component has already been assigned to this name, raise DuplicationError; if the name has not been defined, raises UndefinedService; if the component does not implement the registered interface for the service name, raises InvalidService. """ class IService(Interface): """Marker interface that is used as utility interface to simulate services.""" class IServiceDefinition(Interface): """Marker interface that is used as utility interface to store service defintions (name, interface).""" class UndefinedService(Exception): """An attempt to register a service that has not been defined """ class InvalidService(Exception): """An attempt to register a service that doesn't implement the required interface """ class GlobalServiceManager(object): """service manager""" implements(IGlobalServiceManager) def __init__(self, name=None, module=None, sitemanager=None): if __warn__: warnings.warn( "The concept of services has been deprecated. You now have " "only adapters and utilities, which are managed by the site " "manager, which is probably the object you want.", DeprecationWarning, 2) if sitemanager is None: from zope.component.site import GlobalSiteManager sitemanager = GlobalSiteManager() self.sm = sitemanager self.__name__ = name self.__module__ = module def _clear(self): pass def __reduce__(self): # Global service managers are pickled as global objects return self.__name__ def defineService(self, name, interface): """see IGlobalServiceManager interface""" utils = self.sm.getAllUtilitiesRegisteredFor(IServiceDefinition) names = [n for n, iface in utils] if name in names: raise DuplicationError(name) self.sm.provideUtility(IServiceDefinition, (name, interface), name=name, strict=False) def getServiceDefinitions(self): """see IServiceService Interface""" defs = list(self.sm.getAllUtilitiesRegisteredFor(IServiceDefinition)) return defs + [('Services', IServiceService)] def provideService(self, name, component, force=False): """see IGlobalServiceManager interface, above The force keyword allows one to replace an existing service. This is mostly useful in testing scenarios. """ if not force and self.sm.queryUtility(IService, name) is not None: raise DuplicationError(name) utils = self.sm.getAllUtilitiesRegisteredFor(IServiceDefinition) if name not in [name for name, iface in utils]: raise UndefinedService(name) if not dict(self.getServiceDefinitions())[name].providedBy(component): raise InvalidService(name, component, dict(self.getServiceDefinitions())[name]) if isinstance(component, GlobalService): component.__parent__ = self component.__name__ = name # Ignore the base services, since their functionality is provided by # the SM. if name in ('Adapters', 'Utilities', 'Services'): return directlyProvides(component, IService) self.sm.provideUtility(IService, component, name) def getService(self, name): """see IServiceService interface""" if name == 'Services': return self if name == 'Adapters': from zope.component.bbb.adapter import GlobalAdapterService return GlobalAdapterService(self.sm) if name == 'Utilities': from zope.component.bbb.utility import GlobalUtilityService return GlobalUtilityService(self.sm) service = self.sm.queryUtility(IService, name) if service is None: from zope.component.bbb.exceptions import ComponentLookupError raise ComponentLookupError(name) return service def GS(service_manager, service_name): return service_manager.getService(service_name) class GlobalService(object): def __reduce__(self): return GS, (self.__parent__, self.__name__) def __getSM(sitemanager=None): return GlobalServiceManager('serviceManager', __name__, sitemanager) def defineService(name, interface, sitemanager=None): if sitemanager is None: from zope.component.site import globalSiteManager sitemanager = globalSiteManager __getSM(sitemanager).defineService(name, interface) PK]^„4¶äµµ zope/component/bbb/exceptions.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Exceptions used by the Component Architecture $Id: exceptions.py 29143 2005-02-14 22:43:16Z srichter $ """ from zope.component.interfaces import ComponentLookupError from zope.component.interfaces import Invalid, Misused __all__ = ["ComponentLookupError", "Invalid", "Misused"] PK]^„4ã( , , zope/component/bbb/interfaces.py############################################################################## # # Copyright (c) 2004 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Component Architecture Interfaces kept for Backward-Compatibility. $Id: interfaces.py 38606 2005-09-24 22:35:29Z faassen $ """ __docformat__ = "reStructuredText" from zope.interface import Interface, Attribute class IBBBComponentArchitecture(Interface): """The Component Architecture is defined by six key services, all of which are managed by service managers. """ # basic service manager tools def getGlobalServices(): """Get the global service manager.""" def getGlobalService(name): """Get a global service.""" def getServices(context=None): """Get the service manager If context is None, an application-defined policy is used to choose an appropriate service manager. If 'context' is not None, context is adapted to IServiceService, and this adapter is returned. """ def getService(name, context=None): """Get a named service. Returns the service defined by 'name' from the service manager. If context is None, an application-defined policy is used to choose an appropriate service manager. If 'context' is not None, context is adapted to IServiceService, and this adapter is returned. """ def getServiceDefinitions(context=None): """Get service definitions Returns a dictionary of the service definitions from the service manager in the format {nameString: serviceInterface}. The default behavior of placeful service managers is to include service definitions above them, but this can be overridden. If context is None, an application-defined policy is used to choose an appropriate service manager. If 'context' is not None, context is adapted to IServiceService, and this adapter is returned. """ # Presentation service def getView(object, name, request, providing=Interface, context=None): """Get a named view for a given object. The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, raises ComponentLookupError. """ def queryView(object, name, request, default=None, providing=Interface, context=None): """Look for a named view for a given object. The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, returns default. If context is not specified, attempts to use object to specify a context. """ def getMultiView(objects, request, providing=Interface, name='', context=None): """Look for a multi-view for given objects The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, raises ComponentLookupError. If context is not specified, attempts to use the first object to specify a context. """ def queryMultiView(objects, request, providing=Interface, name='', default=None, context=None): """Look for a multi-view for given objects The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, returns default. If context is not specified, attempts to use the first object to specify a context. """ def getViewProviding(object, providing, request, context=None): """Look for a view based on the interface it provides. A call to this method is equivalent to: getView(object, '', request, context, providing) """ def queryViewProviding(object, providing, request, default=None, context=None): """Look for a view that provides the specified interface. A call to this method is equivalent to: queryView(object, '', request, default, context, providing) """ def getDefaultViewName(object, request, context=None): """Get the name of the default view for the object and request. The request must implement IPresentationRequest, and provides the desired view type. The nearest one to the object is found. If a matching default view name cannot be found, raises ComponentLookupError. If context is not specified, attempts to use object to specify a context. """ def queryDefaultViewName(object, request, default=None, context=None): """Look for the name of the default view for the object and request. The request must implement IPresentationRequest, and provides the desired view type. The nearest one to the object is found. If a matching default view name cannot be found, returns the default. If context is not specified, attempts to use object to specify a context. """ def getResource(name, request, providing=Interface, context=None): """Get a named resource for a given request The request must implement IPresentationRequest. The context provides a place to look for placeful resources. A ComponentLookupError will be raised if the component can't be found. """ def queryResource(name, request, default=None, providing=Interface, context=None): """Get a named resource for a given request The request must implement IPresentationRequest. The context provides a place to look for placeful resources. If the component can't be found, the default is returned. """ class IServiceService(Interface): """A service to manage Services.""" def getServiceDefinitions(): """Retrieve all Service Definitions Should return a list of tuples (name, interface) """ def getInterfaceFor(name): """Retrieve the service interface for the given name """ def getService(name): """Retrieve a service implementation Raises ComponentLookupError if the service can't be found. """ class IUtilityService(Interface): """A service to manage Utilities.""" def getUtility(interface, name=''): """Look up a utility that provides an interface. If one is not found, raises ComponentLookupError. """ def queryUtility(interface, name='', default=None): """Look up a utility that provides an interface. If one is not found, returns default. """ def getUtilitiesFor(interface): """Look up the registered utilities that provide an interface. Returns an iterable of name-utility pairs. """ def getAllUtilitiesRegisteredFor(interface): """Return all registered utilities for an interface This includes overwridden utilities. An iterable of utility instances is returned. No names are returned. """ class IAdapterService(Interface): """A service to manage Adapters.""" def queryAdapter(object, interface, name, default=None): """Look for a named adapter to an interface for an object If a matching adapter cannot be found, returns the default. 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 queryMultiAdapter(objects, interface, name, default=None): """Look for a multi-adapter to an interface for an object If a matching adapter cannot be found, returns the default. 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 subscribers(required, provided): """Get subscribers Subscribers are returned that provide the provided interface and that depend on and are comuted from the sequence of required objects. """ class IContextDependent(Interface): """Components implementing this interface must have a context component. Usually the context must be one of the arguments of the constructor. Adapters and views are a primary example of context-dependent components. """ context = Attribute( """The context of the object This is the object being adapted, viewed, extended, etc. """) class IPresentation(Interface): """Presentation components provide interfaces to external actors The are created for requests, which encapsulate external actors, connections, etc. """ request = Attribute( """The request The request is a surrogate for the user. It also provides the presentation type and skin. It is of type IPresentationRequest. """) class IPresentationRequest(Interface): """An IPresentationRequest provides methods for getting view meta data.""" class IResource(IPresentation): """Resources provide data to be used for presentation.""" class IResourceFactory(Interface): """A factory to create factories using the request.""" def __call__(request): """Create a resource for a request The request must be an IPresentationRequest. """ class IView(IPresentation, IContextDependent): """Views provide a connection between an external actor and an object""" class IViewFactory(Interface): """Objects for creating views""" def __call__(context, request): """Create an view (IView) object The context aregument is the object displayed by the view. The request argument is an object, such as a web request, that "stands in" for the user. """ # When this code is removed, this needs to be undeprecated and moved # towards a private interface somewhere in zope.app.publisher. In # effect the Zope 3 core is still using IDefaultViewName at present, # even though it's in bbb. class IDefaultViewName(Interface): """A string that contains the default view name A default view name is used to select a view when a user hasn't specified one. """ PK]^„4bÏPÜË Ë zope/component/bbb/utility.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """utility service $Id: utility.py 38178 2005-08-30 21:50:19Z mj $ """ from zope.component.exceptions import Invalid, ComponentLookupError from zope.component.interfaces import IUtilityService, IRegistry from zope.component.service import GlobalService, IService, IServiceDefinition from zope.component.site import UtilityRegistration import zope.interface class IGlobalUtilityService(IUtilityService, IRegistry): def provideUtility(providedInterface, component, name='', info=''): """Provide a utility A utility is a component that provides an interface. """ class UtilityService(object): """Provide IUtilityService Mixin that superimposes utility management on adapter registery implementation """ def __init__(self, sitemanager=None): self.__parent__ = None if sitemanager is None: from zope.component.site import GlobalSiteManager sitemanager = GlobalSiteManager() self.sm = sitemanager def __getattr__(self, name): attr = getattr(self.sm, name) if attr is not None: return attr attr = getattr(self.sm.utilities, name) if attr is not None: return attr raise AttributeError(name) class GlobalUtilityService(UtilityService, GlobalService): zope.interface.implementsOnly(IGlobalUtilityService) def __init__(self, sitemanager=None): super(GlobalUtilityService, self).__init__(sitemanager) def provideUtility(self, providedInterface, component, name='', info=''): self.sm.provideUtility(providedInterface, component, name, info) def registrations(self): for reg in self.sm.registrations(): if isinstance(reg, UtilityRegistration): if not reg.provided in (IService, IServiceDefinition): yield reg PK]^„4ì“ÿ55"zope/component/bbb/servicenames.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Default service names for CA core services $Id: servicenames.py 29143 2005-02-14 22:43:16Z srichter $ """ Adapters = 'Adapters' Utilities = 'Utilities' Services = 'Services' PK¶“„4 ¢Åx\\'zope/component/bbb/contextdependent.pyc;ò â•2Dc@s:dZdklZdklZdefd„ƒYZdS(szA simple mix-in class that implements IContextDependent. $Id: contextdependent.py 29143 2005-02-14 22:43:16Z srichter $ (sIContextDependent(s implementssContextDependentcBs!tZdZeeƒd„ZRS(s2standard boilerplate for context dependent objectscCs ||_dS(N(scontextsself(sselfscontext((sAbuild/bdist.linux-i686/egg/zope/component/bbb/contextdependent.pys__init__s(s__name__s __module__s__doc__s implementssIContextDependents__init__(((sAbuild/bdist.linux-i686/egg/zope/component/bbb/contextdependent.pysContextDependents  N(s__doc__szope.component.interfacessIContextDependentszope.interfaces implementssobjectsContextDependent(s implementssIContextDependentsContextDependent((sAbuild/bdist.linux-i686/egg/zope/component/bbb/contextdependent.pys?s  PK¶“„4¾y¾T¾/¾/zope/component/bbb/__init__.pyc;ò â•2Dc@sdZdZeZdkZdkZdklZlZdk l Z l Z dk l Z ydklZWnej od„ZnXd„Zd „Zd „Zed „ZeeƒZed „Zed „Zeed„Zeeed„ZeeƒZeded„Zedeed„Zed„Zeed„Zed„Zeed„Zeed„Z eeed„Z!dS(siComponent Architecture API Backward-Compatibility $Id: __init__.py 38606 2005-09-24 22:35:29Z faassen $ sreStructuredTextN(s Interfaces providedBy(sIServiceServicesIDefaultViewName(sGlobalServiceManager(shookablecCs|SdS(N(sob(sob((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pyshookable!scCs[y=d}x,ti|ƒiddjo|d7}q W|SWntj o dSnXdS(sEReturns the number of the first stack frame outside of zope.componentis__name__szope.component.bbbiN(slevelssyss _getframes f_globalss ValueError(slevel((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pys warningLevel$scCsEtotidttƒƒndkl}tdd|ƒƒSdS(Ns_The concept of services has been deprecated. You probably want to use `getGlobalSiteManager()`.(sgetGlobalSiteManagersservicemanagerszope.component.service(s__warn__swarningsswarnsDeprecationWarnings warningLevelszope.componentsgetGlobalSiteManagersGlobalServiceManager(sgetGlobalSiteManager((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pysgetGlobalServices/s    cCs5totidttƒƒntƒi|ƒSdS(NsqThe concept of services has been deprecated. You probably want to use `getGlobalSiteManager()` or `getUtility()`.(s__warn__swarningsswarnsDeprecationWarnings warningLevelsgetGlobalServicess getServicesname(sname((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pysgetGlobalService9s cCstotidttƒƒn|tjo tƒSnCyt|ƒSWn1t j o%}dk l }||i Œ‚nXdS(NsqThe concept of services has been deprecated. You probably want to use `getGlobalSiteManager()` or `getUtility()`.(sComponentLookupError(s__warn__swarningsswarnsDeprecationWarnings warningLevelscontextsNonesgetGlobalServicessIServiceServices TypeErrorserrorszope.component.bbb.exceptionssComponentLookupErrorsargs(scontextsComponentLookupErrorserror((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pys getServicesAs    cCs8totidttƒƒnt|ƒi|ƒSdS(NsqThe concept of services has been deprecated. You probably want to use `getGlobalSiteManager()` or `getUtility()`.( s__warn__swarningsswarnsDeprecationWarnings warningLevels getServicesscontexts getServicesname(snamescontext((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pys getServiceTs cCs5totidttƒƒnt|ƒiƒSdS(Ns,The concept of services has been deprecated.(s__warn__swarningsswarnsDeprecationWarnings warningLevels getServicesscontextsgetServiceDefinitions(scontext((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pysgetServiceDefinitions\s cCs€totidttƒƒnt|||d|d|ƒ}|t j o|Sndk l}|d|||||ƒ‚dS(NsƒThe concrete concept of a view has been deprecated. You want to use `getMultiAdapter((object, request), providing, name, context)`.scontexts providing(sComponentLookupErrorsCouldn't find view(s__warn__swarningsswarnsDeprecationWarnings warningLevels queryViewsobjectsnamesrequestscontexts providingsviewsNoneszope.component.bbb.exceptionssComponentLookupError(sobjectsnamesrequests providingscontextsComponentLookupErrorsview((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pysgetViewes    cCsNtotidttƒƒndkl}|||f||||ƒSdS(NsŽThe concrete concept of a view has been deprecated. You want to use `queryMultiAdapter((object, request), providing, name, default, context)`.(squeryMultiAdapter( s__warn__swarningsswarnsDeprecationWarnings warningLevelszope.componentsqueryMultiAdaptersobjectsrequests providingsnamesdefaultscontext(sobjectsnamesrequestsdefaults providingscontextsqueryMultiAdapter((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pys queryViewus   scCsztotidttƒƒnt||||d|ƒ}|t j o|Sndk l}|d||||ƒ‚dS(Ns„The concrete concept of a view has been deprecated. You want to use `getMultiAdapter(objects+(request,), providing, name, context)`.scontext(sComponentLookupErrorsCouldn't find view(s__warn__swarningsswarnsDeprecationWarnings warningLevelsqueryMultiViewsobjectssrequests providingsnamescontextsviewsNoneszope.component.bbb.exceptionssComponentLookupError(sobjectssrequests providingsnamescontextsComponentLookupErrorsview((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pys getMultiViewƒs   cCsOtotidttƒƒndkl}|||f||||ƒSdS(NsThe concrete concept of a view has been deprecated. You want to use `getMultiAdapter(objects+(request,), providing, name, default, context)`.(squeryMultiAdapter( s__warn__swarningsswarnsDeprecationWarnings warningLevelszope.componentsqueryMultiAdaptersobjectssrequests providingsnamesdefaultscontext(sobjectssrequests providingsnamesdefaultscontextsqueryMultiAdapter((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pysqueryMultiView’s   cCs;totidttƒƒnt|d|||ƒSdS(NsƒThe concrete concept of a view has been deprecated. You want to use `getMultiAdapter((object, request), providing, name, context)`.s( s__warn__swarningsswarnsDeprecationWarnings warningLevelsgetViewsobjectsrequests providingscontext(sobjects providingsrequestscontext((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pysgetViewProvidingžs cCs>totidttƒƒnt|d||||ƒSdS(NsŽThe concrete concept of a view has been deprecated. You want to use `queryMultiAdapter((object, request), providing, name, default, context)`.s( s__warn__swarningsswarnsDeprecationWarnings warningLevels queryViewsobjectsrequestsdefaults providingscontext(sobjects providingsrequestsdefaultscontext((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pysqueryViewProviding§s cCsntotidttƒƒnt||d|ƒ}|t j o|Sndk l }|d||ƒ‚dS(NshThe concrete concept of a view has been deprecated. You want to use `zapi.getDefaultViewName()` instead.scontext(sComponentLookupErrorsCouldn't find default view name( s__warn__swarningsswarnsDeprecationWarnings warningLevelsqueryDefaultViewNamesobjectsrequestscontextsviewsNoneszope.component.bbb.exceptionssComponentLookupError(sobjectsrequestscontextsComponentLookupErrorsview((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pysgetDefaultViewName±s   cCs¦totidttƒƒndkl}dkl}y||ƒ}Wn|j o |SnX|i i t t||fƒtƒ}|tj o|Sn|SdS(NsjThe concrete concept of a view has been deprecated. You want to use `zapi.queryDefaultViewName()` instead.(sComponentLookupError(sgetSiteManager(s__warn__swarningsswarnsDeprecationWarnings warningLevelszope.component.bbb.exceptionssComponentLookupErrorszope.componentsgetSiteManagerscontextsadapterssdefaultslookupsmaps providedBysobjectsrequestsIDefaultViewNamesnamesNone(sobjectsrequestsdefaultscontextsComponentLookupErrorsnamesadapterssgetSiteManager((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pysqueryDefaultViewName¿s      cCsttotidttƒƒnt||d|d|ƒ}|t j o|Sndk l }|d||ƒ‚dS(NswThe concrete concept of a resource has been deprecated. You want to use `getAdapter(request, providing, name, context)`s providingscontext(sComponentLookupErrorsCouldn't find resource(s__warn__swarningsswarnsDeprecationWarnings warningLevels queryResourcesnamesrequests providingscontextsviewsNoneszope.component.bbb.exceptionssComponentLookupError(snamesrequests providingscontextsComponentLookupErrorsview((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pys getResourceÓs   cCsHtotidttƒƒndkl}||||||ƒSdS(Ns‚The concrete concept of a resource has been deprecated. You want to use `queryAdapter(request, providing, name, default, context)`(s queryAdapter( s__warn__swarningsswarnsDeprecationWarnings warningLevelszope.components queryAdaptersrequests providingsnamesdefaultscontext(snamesrequestsdefaults providingscontexts queryAdapter((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pys queryResourceàs   ("s__doc__s __docformat__sTrues__warn__ssysswarningsszope.interfaces Interfaces providedByszope.component.bbb.interfacessIServiceServicesIDefaultViewNameszope.component.bbb.servicesGlobalServiceManagers zope.hookableshookables ImportErrors warningLevelsgetGlobalServicessgetGlobalServicesNones getServicess getServicesgetServiceDefinitionssgetViews queryViews getMultiViewsqueryMultiViewsgetViewProvidingsqueryViewProvidingsgetDefaultViewNamesqueryDefaultViewNames getResources queryResource(sgetViews getMultiViewsgetServiceDefinitionss queryResourcesqueryViewProvidingsgetViewProvidings __docformat__sIServiceServices__warn__shookables InterfacesqueryMultiViewsgetDefaultViewNamesqueryDefaultViewNamesIDefaultViewNames getResourcesgetGlobalServicess queryViewswarningssGlobalServiceManagerssyss providedBys getServicesgetGlobalServices getServicess warningLevel((s9build/bdist.linux-i686/egg/zope/component/bbb/__init__.pys?s:            PK¶“„4ìâ)K““zope/component/bbb/adapter.pyc;ò â•2Dc@sãdZdZdkZdkZdklZdklZdkl Z l Z dk l Z dk lZlZdklZlZlZlZd klZd e e fd „ƒYZd efd „ƒYZdee fd„ƒYZdS(sNGlobal Adapter Service $Id: adapter.py 39752 2005-10-30 20:16:09Z srichter $ sreStructuredTextN(s ClassType(sComponentLookupError(sIAdapterServices IRegistry(s GlobalService(sAdapterRegistrationsSubscriptionRegistration(s implementss providedBys Interfaces implementedBy(s IInterfacesIGlobalAdapterServicecBs tZdd„Zdd„ZRS(NscCsdS(s}Register an adapter factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the adapter - `info`: Provide some info about this particular adapter. N((srequiredsprovidedsnamesfactorysinfo((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pysregister!s cCsdS(s‚Register a subscriber factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the subscriber - `info`: Provide some info about this particular adapter. N((srequiredsprovidedsfactorysinfo((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pys subscribe-s (s__name__s __module__sregisters subscribe(((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pysIGlobalAdapterServices sAdapterServicecBs-tZdZeeƒed„Zd„ZRS(sŽBase implementation of an adapter service, implementing only the `IAdapterService` interface. No write-methods were implemented. cCs4|tjodkl}|ƒ}n||_dS(N(sGlobalSiteManager(s sitemanagersNoneszope.component.sitesGlobalSiteManagersselfssm(sselfs sitemanagersGlobalSiteManager((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pys__init__Bs   cCs:t|ii|ƒ}|tj o|Snt|ƒ‚dS(N(sgetattrsselfssmsadapterssnamesattrsNonesAttributeError(sselfsnamesattr((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pys __getattr__Hs (s__name__s __module__s__doc__s implementssIAdapterServicesNones__init__s __getattr__(((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pysAdapterService9s   sGlobalAdapterServicecBsEtZdZeeƒed„Zdd„Zdd„Zd„Z RS(s&Global Adapter Service implementation.cCstt|ƒi|ƒdS(N(ssupersGlobalAdapterServicesselfs__init__s sitemanager(sselfs sitemanager((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pys__init__TsscCs |ii|||||ƒdS(slRegister an adapter >>> registry = GlobalAdapterService() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.register((R1, ), P2, 'bob', 'c1', 'd1') >>> registry.register((R1, ), P2, '', 'c2', 'd2') >>> registry.lookup((R2, ), P1, '') 'c2' >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration AdapterRegistration(('R1',), 'P2', '', 'c2', 'd2') AdapterRegistration(('R1',), 'P2', 'bob', 'c1', 'd1') Let's make sure that we can also register regular classes for adaptation. >>> class O1(object): ... pass >>> class O2(object): ... pass >>> class O3(object): ... def __init__(self, obj1, obj2=None): ... pass >>> registry.register((O1, ), R1, '', O3) >>> registry.queryAdapter(O1(), R1, '').__class__ >>> registry.register((O1, O2), R1, '', O3) >>> registry.queryMultiAdapter((O1(), O2()), R1, '').__class__ N(sselfssmsprovideAdaptersrequiredsprovidedsnamesfactorysinfo(sselfsrequiredsprovidedsnamesfactorysinfo((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pysregisterWs+cCs|ii||||ƒdS(sWRegister an subscriptions adapter >>> registry = GlobalAdapterService() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.subscribe((R1, ), P2, 'c1', 'd1') >>> registry.subscribe((R1, ), P2, 'c2', 'd2') >>> subscriptions = map(str, registry.subscriptions((R2, ), P1)) >>> subscriptions.sort() >>> subscriptions ['c1', 'c2'] >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration SubscriptionRegistration(('R1',), 'P2', 'c1', 'd1') SubscriptionRegistration(('R1',), 'P2', 'c2', 'd2') N(sselfssms subscribesrequiredsprovidedsfactorysinfo(sselfsrequiredsprovidedsfactorysinfo((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pys subscribe…sccs<x5|iiƒD]$}t|ttfƒo|VqqWdS(N(sselfssms registrationss registrations isinstancesAdapterRegistrationsSubscriptionRegistration(sselfs registration((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pys registrations£s ( s__name__s __module__s__doc__s implementssIGlobalAdapterServicesNones__init__sregisters subscribes registrations(((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pysGlobalAdapterServiceOs    . (s__doc__s __docformat__ssysswarningsstypess ClassTypeszope.component.exceptionssComponentLookupErrorszope.component.interfacessIAdapterServices IRegistryszope.component.bbb.services GlobalServiceszope.component.sitesAdapterRegistrationsSubscriptionRegistrationszope.interfaces implementss providedBys Interfaces implementedByszope.interface.interfacess IInterfacesIGlobalAdapterServicesobjectsAdapterServicesGlobalAdapterService(s implementssAdapterServicesSubscriptionRegistrations GlobalServicesAdapterRegistrationsGlobalAdapterServiceswarningss ClassTypesComponentLookupErrorsIAdapterServices IRegistrys __docformat__ssyss Interfaces implementedBys IInterfaces providedBysIGlobalAdapterService((s8build/bdist.linux-i686/egg/zope/component/bbb/adapter.pys?s      PK¶“„4°ƒiªu%u%zope/component/bbb/service.pyc;ò â•2Dc@sdZeZdkZdklZdklZdkl Z l Z l Z defd„ƒYZ de fd„ƒYZ d e fd „ƒYZd efd „ƒYZd efd„ƒYZdefd„ƒYZd„Zdefd„ƒYZed„Zed„ZdS(sVService Manager implementation $Id: service.py 29143 2005-02-14 22:43:16Z srichter $ N(sDuplicationError(sIServiceService(s implementss InterfacesdirectlyProvidessIGlobalServiceManagercBstZd„Zd„ZRS(NcCsdS(sDefine a new service of the given name implementing the given interface. If the name already exists, raises DuplicationErrorN((snames interface((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys defineServicescCsdS(s–Register a service component. Provide a service component to do the work of the named service. If a service component has already been assigned to this name, raise DuplicationError; if the name has not been defined, raises UndefinedService; if the component does not implement the registered interface for the service name, raises InvalidService. N((snames component((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pysprovideService!s (s__name__s __module__s defineServicesprovideService(((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pysIGlobalServiceManagers sIServicecBstZdZRS(sOMarker interface that is used as utility interface to simulate services.(s__name__s __module__s__doc__(((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pysIService-s sIServiceDefinitioncBstZdZRS(seMarker interface that is used as utility interface to store service defintions (name, interface).(s__name__s __module__s__doc__(((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pysIServiceDefinition1s sUndefinedServicecBstZdZRS(s?An attempt to register a service that has not been defined (s__name__s __module__s__doc__(((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pysUndefinedService5s sInvalidServicecBstZdZRS(sZAn attempt to register a service that doesn't implement the required interface (s__name__s __module__s__doc__(((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pysInvalidService9s sGlobalServiceManagercBsctZdZeeƒeeed„Zd„Zd„Zd„Z d„Z e d„Z d„Z RS(sservice managercCsdtotidtdƒn|tjodkl}|ƒ}n||_ ||_ ||_ dS(Ns¤The concept of services has been deprecated. You now have only adapters and utilities, which are managed by the site manager, which is probably the object you want.i(sGlobalSiteManager(s__warn__swarningsswarnsDeprecationWarnings sitemanagersNoneszope.component.sitesGlobalSiteManagersselfssmsnames__name__smodules __module__(sselfsnamesmodules sitemanagersGlobalSiteManager((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys__init__Cs      cCsdS(N((sself((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys_clearQscCs |iSdS(N(sselfs__name__(sself((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys __reduce__TscCs…|iitƒ}gi}|D]\}}||ƒq ~}||jot |ƒ‚n|ii t||fd|dtƒdS(s#see IGlobalServiceManager interfacesnamesstrictN(sselfssmsgetAllUtilitiesRegisteredForsIServiceDefinitionsutilssappends_[1]snsifacesnamessnamesDuplicationErrorsprovideUtilitys interfacesFalse(sselfsnames interfacesifaces_[1]snamessnsutils((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys defineServiceXs- cCs-t|iitƒƒ}|dtfgSdS(ssee IServiceService InterfacesServicesN(slistsselfssmsgetAllUtilitiesRegisteredForsIServiceDefinitionsdefssIServiceService(sselfsdefs((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pysgetServiceDefinitionscscCs<| o|iit|ƒtj ot|ƒ‚n|iit ƒ}|gi }|D]\}}||ƒqW~jot|ƒ‚nt|iƒƒ|i|ƒ o&t||t|iƒƒ|ƒ‚nt|tƒo||_||_n|dddfjodSnt|tƒ|iit||ƒdS(s®see IGlobalServiceManager interface, above The force keyword allows one to replace an existing service. This is mostly useful in testing scenarios. sAdapterss UtilitiessServicesN(sforcesselfssms queryUtilitysIServicesnamesNonesDuplicationErrorsgetAllUtilitiesRegisteredForsIServiceDefinitionsutilssappends_[1]sifacesUndefinedServicesdictsgetServiceDefinitionss providedBys componentsInvalidServices isinstances GlobalServices __parent__s__name__sdirectlyProvidessprovideUtility(sselfsnames componentsforcesifaces_[1]sutils((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pysprovideServicehs $4!    cCs²|djo|Sn|djodkl}||iƒSn|djodkl}||iƒSn|iit|ƒ}|t jodk l }||ƒ‚n|SdS(ssee IServiceService interfacesServicessAdapters(sGlobalAdapterServices Utilities(sGlobalUtilityService(sComponentLookupErrorN( snamesselfszope.component.bbb.adaptersGlobalAdapterServicessmszope.component.bbb.utilitysGlobalUtilityServices queryUtilitysIServicesservicesNoneszope.component.bbb.exceptionssComponentLookupError(sselfsnamesservicesGlobalUtilityServicesComponentLookupErrorsGlobalAdapterService((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys getService†s       (s__name__s __module__s__doc__s implementssIGlobalServiceManagersNones__init__s_clears __reduce__s defineServicesgetServiceDefinitionssFalsesprovideServices getService(((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pysGlobalServiceManager>s      cCs|i|ƒSdS(N(sservice_managers getServices service_name(sservice_managers service_name((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pysGS›ss GlobalServicecBstZd„ZRS(NcCst|i|iffSdS(N(sGSsselfs __parent__s__name__(sself((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys __reduce__ s(s__name__s __module__s __reduce__(((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys GlobalServicežscCstdt|ƒSdS(NsserviceManager(sGlobalServiceManagers__name__s sitemanager(s sitemanager((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys__getSM¤scCs>|tjodkl}|}nt|ƒi||ƒdS(N(sglobalSiteManager(s sitemanagersNoneszope.component.sitesglobalSiteManagers__getSMs defineServicesnames interface(snames interfaces sitemanagersglobalSiteManager((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys defineService§s   (s__doc__sTrues__warn__swarningsszope.exceptionssDuplicationErrorszope.component.bbb.interfacessIServiceServiceszope.interfaces implementss InterfacesdirectlyProvidessIGlobalServiceManagersIServicesIServiceDefinitions ExceptionsUndefinedServicesInvalidServicesobjectsGlobalServiceManagersGSs GlobalServicesNones__getSMs defineService(s implementssIServicesIGlobalServiceManagersInvalidServiceswarningss__warn__sdirectlyProvidessIServiceDefinitions InterfacesDuplicationErrors GlobalServices__getSMsIServiceServicesGSsGlobalServiceManagersUndefinedServices defineService((s8build/bdist.linux-i686/egg/zope/component/bbb/service.pys?s   ]  PK¶“„4'ñW3CC!zope/component/bbb/exceptions.pyc;ò â•2Dc@s9dZdklZdklZlZdddgZdS(shExceptions used by the Component Architecture $Id: exceptions.py 29143 2005-02-14 22:43:16Z srichter $ (sComponentLookupError(sInvalidsMisusedsComponentLookupErrorsInvalidsMisusedN(s__doc__szope.component.interfacessComponentLookupErrorsInvalidsMisuseds__all__(sMisusedsComponentLookupErrors__all__sInvalid((s;build/bdist.linux-i686/egg/zope/component/bbb/exceptions.pys?s PK¶“„4sY^­C­C!zope/component/bbb/interfaces.pyc;ò â•2Dc@s.dZdZdklZlZdefd„ƒYZdefd„ƒYZdefd„ƒYZd efd „ƒYZd efd „ƒYZ d efd„ƒYZ defd„ƒYZ de fd„ƒYZ defd„ƒYZ de e fd„ƒYZdefd„ƒYZdefd„ƒYZdS(s|Component Architecture Interfaces kept for Backward-Compatibility. $Id: interfaces.py 38606 2005-09-24 22:35:29Z faassen $ sreStructuredText(s Interfaces AttributesIBBBComponentArchitecturecBsãtZdZd„Zd„Zed„Zed„Zed„Ze ed„Z ee ed„Z e ded „Z e deed „Z ed „Zeed „Zed „Zeed„Ze ed„Zee ed„ZRS(sqThe Component Architecture is defined by six key services, all of which are managed by service managers. cCsdS(sGet the global service manager.N((((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysgetGlobalServicesscCsdS(sGet a global service.N((sname((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysgetGlobalService!scCsdS(sGet the service manager If context is None, an application-defined policy is used to choose an appropriate service manager. If 'context' is not None, context is adapted to IServiceService, and this adapter is returned. N((scontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys getServices$scCsdS(sKGet a named service. Returns the service defined by 'name' from the service manager. If context is None, an application-defined policy is used to choose an appropriate service manager. If 'context' is not None, context is adapted to IServiceService, and this adapter is returned. N((snamescontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys getService.s cCsdS(sGet service definitions Returns a dictionary of the service definitions from the service manager in the format {nameString: serviceInterface}. The default behavior of placeful service managers is to include service definitions above them, but this can be overridden. If context is None, an application-defined policy is used to choose an appropriate service manager. If 'context' is not None, context is adapted to IServiceService, and this adapter is returned. N((scontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysgetServiceDefinitions:scCsdS(sGet a named view for a given object. The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, raises ComponentLookupError. N((sobjectsnamesrequests providingscontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysgetViewLscCsdS(skLook for a named view for a given object. The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, returns default. If context is not specified, attempts to use object to specify a context. N((sobjectsnamesrequestsdefaults providingscontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys queryViewUs scCsdS(sLook for a multi-view for given objects The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, raises ComponentLookupError. If context is not specified, attempts to use the first object to specify a context. N((sobjectssrequests providingsnamescontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys getMultiViewbs cCsdS(ssLook for a multi-view for given objects The request must implement IPresentationRequest: it provides the view type and the skin name. The nearest one to the object is found. If a matching view cannot be found, returns default. If context is not specified, attempts to use the first object to specify a context. N((sobjectssrequests providingsnamesdefaultscontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysqueryMultiViewos cCsdS(s«Look for a view based on the interface it provides. A call to this method is equivalent to: getView(object, '', request, context, providing) N((sobjects providingsrequestscontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysgetViewProviding|scCsdS(s¹Look for a view that provides the specified interface. A call to this method is equivalent to: queryView(object, '', request, default, context, providing) N((sobjects providingsrequestsdefaultscontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysqueryViewProviding„scCsdS(sGet the name of the default view for the object and request. The request must implement IPresentationRequest, and provides the desired view type. The nearest one to the object is found. If a matching default view name cannot be found, raises ComponentLookupError. If context is not specified, attempts to use object to specify a context. N((sobjectsrequestscontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysgetDefaultViewNames cCsdS(s‹Look for the name of the default view for the object and request. The request must implement IPresentationRequest, and provides the desired view type. The nearest one to the object is found. If a matching default view name cannot be found, returns the default. If context is not specified, attempts to use object to specify a context. N((sobjectsrequestsdefaultscontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysqueryDefaultViewName™s cCsdS(s Get a named resource for a given request The request must implement IPresentationRequest. The context provides a place to look for placeful resources. A ComponentLookupError will be raised if the component can't be found. N((snamesrequests providingscontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys getResource¥s cCsdS(sôGet a named resource for a given request The request must implement IPresentationRequest. The context provides a place to look for placeful resources. If the component can't be found, the default is returned. N((snamesrequestsdefaults providingscontext((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys queryResource°s (s__name__s __module__s__doc__sgetGlobalServicessgetGlobalServicesNones getServicess getServicesgetServiceDefinitionss InterfacesgetViews queryViews getMultiViewsqueryMultiViewsgetViewProvidingsqueryViewProvidingsgetDefaultViewNamesqueryDefaultViewNames getResources queryResource(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysIBBBComponentArchitectures           sIServiceServicecBs)tZdZd„Zd„Zd„ZRS(sA service to manage Services.cCsdS(scRetrieve all Service Definitions Should return a list of tuples (name, interface) N((((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysgetServiceDefinitions¿scCsdS(s:Retrieve the service interface for the given name N((sname((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysgetInterfaceForÅscCsdS(snRetrieve a service implementation Raises ComponentLookupError if the service can't be found. N((sname((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys getServiceÉs(s__name__s __module__s__doc__sgetServiceDefinitionssgetInterfaceFors getService(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysIServiceService¼s   sIUtilityServicecBs;tZdZdd„Zded„Zd„Zd„ZRS(sA service to manage Utilities.scCsdS(sqLook up a utility that provides an interface. If one is not found, raises ComponentLookupError. N((s interfacesname((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys getUtilityÓscCsdS(seLook up a utility that provides an interface. If one is not found, returns default. N((s interfacesnamesdefault((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys queryUtilityÙscCsdS(sxLook up the registered utilities that provide an interface. Returns an iterable of name-utility pairs. N((s interface((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysgetUtilitiesForßscCsdS(s¾Return all registered utilities for an interface This includes overwridden utilities. An iterable of utility instances is returned. No names are returned. N((s interface((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysgetAllUtilitiesRegisteredForås(s__name__s __module__s__doc__s getUtilitysNones queryUtilitysgetUtilitiesForsgetAllUtilitiesRegisteredFor(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysIUtilityServiceÐs   sIAdapterServicecBs/tZdZed„Zed„Zd„ZRS(sA service to manage Adapters.cCsdS(sMLook for a named adapter to an interface for an object If a matching adapter cannot be found, returns the default. 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. N((sobjects interfacesnamesdefault((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys queryAdapterñscCsdS(sMLook for a multi-adapter to an interface for an object If a matching adapter cannot be found, returns the default. 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. N((sobjectss interfacesnamesdefault((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysqueryMultiAdapterûscCsdS(s¸Get subscribers Subscribers are returned that provide the provided interface and that depend on and are comuted from the sequence of required objects. N((srequiredsprovided((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys subscriberss(s__name__s __module__s__doc__sNones queryAdaptersqueryMultiAdapters subscribers(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysIAdapterServiceîs  sIContextDependentcBstZdZedƒZRS(sæComponents implementing this interface must have a context component. Usually the context must be one of the arguments of the constructor. Adapters and views are a primary example of context-dependent components. sdThe context of the object This is the object being adapted, viewed, extended, etc. (s__name__s __module__s__doc__s Attributescontext(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysIContextDependents s IPresentationcBstZdZedƒZRS(sžPresentation components provide interfaces to external actors The are created for requests, which encapsulate external actors, connections, etc. s«The request The request is a surrogate for the user. It also provides the presentation type and skin. It is of type IPresentationRequest. (s__name__s __module__s__doc__s Attributesrequest(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys IPresentations sIPresentationRequestcBstZdZRS(sDAn IPresentationRequest provides methods for getting view meta data.(s__name__s __module__s__doc__(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysIPresentationRequest-s s IResourcecBstZdZRS(s3Resources provide data to be used for presentation.(s__name__s __module__s__doc__(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys IResource1s sIResourceFactorycBstZdZd„ZRS(s0A factory to create factories using the request.cCsdS(s^Create a resource for a request The request must be an IPresentationRequest. N((srequest((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys__call__8s(s__name__s __module__s__doc__s__call__(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysIResourceFactory5s sIViewcBstZdZRS(sBViews provide a connection between an external actor and an object(s__name__s __module__s__doc__(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysIView?s s IViewFactorycBstZdZd„ZRS(sObjects for creating viewscCsdS(sÓCreate an view (IView) object The context aregument is the object displayed by the view. The request argument is an object, such as a web request, that "stands in" for the user. N((scontextsrequest((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys__call__Fs(s__name__s __module__s__doc__s__call__(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys IViewFactoryCs sIDefaultViewNamecBstZdZRS(s‰A string that contains the default view name A default view name is used to select a view when a user hasn't specified one. (s__name__s __module__s__doc__(((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pysIDefaultViewNameRs N(s__doc__s __docformat__szope.interfaces Interfaces AttributesIBBBComponentArchitecturesIServiceServicesIUtilityServicesIAdapterServicesIContextDependents IPresentationsIPresentationRequests IResourcesIResourceFactorysIViews IViewFactorysIDefaultViewName(sIDefaultViewNames IPresentationsIResourceFactorysIPresentationRequests AttributesIBBBComponentArchitecturesIAdapterServices __docformat__sIUtilityServicesIServiceServices IViewFactorys Interfaces IResourcesIContextDependentsIView((s;build/bdist.linux-i686/egg/zope/component/bbb/interfaces.pys?s¥  PK¶“„4<6RñTTzope/component/bbb/utility.pyc;ò â•2Dc@s§dZdklZlZdklZlZdklZl Z l Z dk l Z dk Zdeefd„ƒYZdefd „ƒYZd eefd „ƒYZdS( sAutility service $Id: utility.py 38178 2005-08-30 21:50:19Z mj $ (sInvalidsComponentLookupError(sIUtilityServices IRegistry(s GlobalServicesIServicesIServiceDefinition(sUtilityRegistrationNsIGlobalUtilityServicecBstZddd„ZRS(NscCsdS(sXProvide a utility A utility is a component that provides an interface. N((sprovidedInterfaces componentsnamesinfo((s8build/bdist.linux-i686/egg/zope/component/bbb/utility.pysprovideUtilitys(s__name__s __module__sprovideUtility(((s8build/bdist.linux-i686/egg/zope/component/bbb/utility.pysIGlobalUtilityServicessUtilityServicecBs#tZdZed„Zd„ZRS(stProvide IUtilityService Mixin that superimposes utility management on adapter registery implementation cCs=t|_|tjodkl}|ƒ}n||_dS(N(sGlobalSiteManager(sNonesselfs __parent__s sitemanagerszope.component.sitesGlobalSiteManagerssm(sselfs sitemanagersGlobalSiteManager((s8build/bdist.linux-i686/egg/zope/component/bbb/utility.pys__init__'s     cCsat|i|ƒ}|tj o|Snt|ii|ƒ}|tj o|Snt|ƒ‚dS(N(sgetattrsselfssmsnamesattrsNones utilitiessAttributeError(sselfsnamesattr((s8build/bdist.linux-i686/egg/zope/component/bbb/utility.pys __getattr__.s  (s__name__s __module__s__doc__sNones__init__s __getattr__(((s8build/bdist.linux-i686/egg/zope/component/bbb/utility.pysUtilityService s  sGlobalUtilityServicecBs<tZeiieƒed„Zddd„Zd„Z RS(NcCstt|ƒi|ƒdS(N(ssupersGlobalUtilityServicesselfs__init__s sitemanager(sselfs sitemanager((s8build/bdist.linux-i686/egg/zope/component/bbb/utility.pys__init__>sscCs|ii||||ƒdS(N(sselfssmsprovideUtilitysprovidedInterfaces componentsnamesinfo(sselfsprovidedInterfaces componentsnamesinfo((s8build/bdist.linux-i686/egg/zope/component/bbb/utility.pysprovideUtilityAsccsQxJ|iiƒD]9}t|tƒo#|ittfj o|VqIqqWdS(N( sselfssms registrationssregs isinstancesUtilityRegistrationsprovidedsIServicesIServiceDefinition(sselfsreg((s8build/bdist.linux-i686/egg/zope/component/bbb/utility.pys registrationsDs ( s__name__s __module__szopes interfacesimplementsOnlysIGlobalUtilityServicesNones__init__sprovideUtilitys registrations(((s8build/bdist.linux-i686/egg/zope/component/bbb/utility.pysGlobalUtilityService:s (s__doc__szope.component.exceptionssInvalidsComponentLookupErrorszope.component.interfacessIUtilityServices IRegistryszope.component.services GlobalServicesIServicesIServiceDefinitionszope.component.sitesUtilityRegistrationszope.interfaceszopesIGlobalUtilityServicesobjectsUtilityServicesGlobalUtilityService( sUtilityRegistrationsIServices GlobalServicesGlobalUtilityServicesComponentLookupErrorsIGlobalUtilityServices IRegistrysInvalidsIUtilityServicesUtilityServiceszopesIServiceDefinition((s8build/bdist.linux-i686/egg/zope/component/bbb/utility.pys?s  PK¶“„4ƒ>ç­››#zope/component/bbb/servicenames.pyc;ò â•2Dc@sdZdZdZdZdS(sgDefault service names for CA core services $Id: servicenames.py 29143 2005-02-14 22:43:16Z srichter $ sAdapterss UtilitiessServicesN(s__doc__sAdapterss UtilitiessServices(sServicessAdapterss Utilities((s=build/bdist.linux-i686/egg/zope/component/bbb/servicenames.pys?sPK]^„47íË®……(zope/component/bbb/tests/test_adapter.py############################################################################## # # Copyright (c) 2003 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Global Adapter Service Tests $Id: test_adapter.py 29143 2005-02-14 22:43:16Z srichter $ """ import unittest from doctest import DocTestSuite from zope.component.adapter import GlobalAdapterService class GlobalAdapterServiceTests(unittest.TestCase): # This test does not work with the backward-compatibility code. # Global adapter services are not pickled anyways. def BBB_test_pickling(self): from zope.component.bbb.tests.test_service import testServiceManager from zope.component.interfaces import IAdapterService testServiceManager.defineService('Adapters', IAdapterService) adapters = GlobalAdapterService() testServiceManager.provideService('Adapters', adapters) import pickle as = pickle.loads(pickle.dumps(adapters)) self.assert_(as.sm is adapters.sm) testServiceManager._clear() def test_suite(): suite = unittest.makeSuite(GlobalAdapterServiceTests) suite.addTest(DocTestSuite('zope.component.adapter')) return suite PK]^„4ýKxòPP#zope/component/bbb/tests/request.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Request for tests $Id: request.py 30931 2005-06-27 15:48:32Z benji_york $ """ import warnings import zope.interface from zope.component import bbb if bbb.tests.__warn__: warnings.warn( "`zope.component.tests.request` is deprecated, since the component " "architecture does not support presentation components anymore.", DeprecationWarning, 2) class Request(object): def __init__(self, type, skin=None): zope.interface.directlyProvides(self, type) # BBB goes away in 3.3 if skin is not None: import warnings warnings.warn( "The skin argument is deprecated for " "zope.component.tests.request.Request and will go away in " "Zope 3.3. Use zope.publisher.browser.TestRequest if " "you need to test skins.", DeprecationWarning) zope.interface.directlyProvides(self, skin) self._skin = skin PK]^„4 àóN£U£U$zope/component/bbb/tests/test_api.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """API tests $Id: test_api.py 38178 2005-08-30 21:50:19Z mj $ """ import unittest from zope import component from zope.component import servicenames from zope.component import getAdapter, queryAdapter, getAdapters from zope.component import getAdapterInContext, queryAdapterInContext from zope.component import getService from zope.component import getUtility, queryUtility from zope.component import getDefaultViewName from zope.component import queryMultiAdapter from zope.component.exceptions import ComponentLookupError from zope.component.servicenames import Adapters from zope.component.tests.placelesssetup import PlacelessSetup from zope.component.tests.request import Request from zope.component.interfaces import IComponentArchitecture, IServiceService from zope.component.interfaces import IDefaultViewName from zope.interface import Interface, implements from zope.interface.verify import verifyObject class I1(Interface): pass class I2(Interface): pass class I3(Interface): pass class Comp(object): implements(I2) def __init__(self, context, request=None): self.context = context class Comp2(object): implements(I3) def __init__(self, context, request=None): self.context = context comp = Comp(1) class Ob(object): implements(I1) def __conform__(self, i): if i is IServiceService: from zope.component.bbb import getServices return getServices() from zope.component.interfaces import ISiteManager from zope.component import getSiteManager if i is ISiteManager: return getSiteManager() ob = Ob() class Conforming(Ob): def __conform__(self, i): if i is I3: return Comp(self) else: return Ob.__conform__(self, i) class StubServiceService(object): implements(IServiceService) # This is a lie. def __init__(self): self.services = {} from zope.component.site import GlobalSiteManager self.sm = GlobalSiteManager() def setService(self, name, service): self.services[name] = service def getService(self, name): try: return self.services[name] except KeyError: raise ComponentLookupError(name) class ConformsToIServiceService(object): def __init__(self, serviceservice): self.serviceservice = serviceservice def __conform__(self, interface): if interface is IServiceService: return self.serviceservice from zope.component.interfaces import ISiteManager if interface is ISiteManager: return self.serviceservice.sm class Test(PlacelessSetup, unittest.TestCase): def setUp(self): from zope.component import bbb bbb.__warn__ = False bbb.service.__warn__ = False super(Test, self).setUp() def cleanUp(self): super(Test, self).cleanUp() from zope.component import bbb bbb.__warn__ = True bbb.service.__warn__ = True def testInterfaces(self): import zope.component self.failUnless(verifyObject(IComponentArchitecture, zope.component)) def test_getGlobalServices(self): from zope.component import getGlobalServices from zope.component.service import IGlobalServiceManager gsm = getGlobalServices() self.assert_(IGlobalServiceManager.providedBy(gsm)) self.assert_(getGlobalServices().sm is gsm.sm) def test_getServices(self): from zope.component import getServices # We don't know anything about the default service manager, except # that it is an IServiceService. self.assert_(IServiceService.providedBy(getServices())) # Calling getServices with no args is equivalent to calling it # with a context of None. self.assert_(getServices().sm is getServices(None).sm) # If the context passed to getServices is not None, it is # adapted to IServiceService and this adapter returned. # So, we create a context that can be adapted to IServiceService # using the __conform__ API. servicemanager = StubServiceService() context = ConformsToIServiceService(servicemanager) self.assert_(getServices(context) is servicemanager) # Using a context that is not adaptable to IServiceService should # fail. self.assertRaises(ComponentLookupError, getServices, object()) def test_getService(self): from zope.component import getService, getServices # Getting the adapter service with no context given is the same # as getting the adapter service from the no-context service manager. self.assert_(getService(Adapters).sm is getServices().getService(Adapters).sm) # And, a context of 'None' is the same as not providing a context. self.assert_(getService(Adapters, None).sm is getService(Adapters).sm) # If the context is adaptable to IServiceService then we use that # adapter. servicemanager = StubServiceService() adapterservice = object() servicemanager.setService(Adapters, adapterservice) context = ConformsToIServiceService(servicemanager) self.assert_(getService(Adapters, context) is adapterservice) # Using a context that is not adaptable to IServiceService should # fail. self.assertRaises(ComponentLookupError, getService, Adapters, object()) def testAdapterInContext(self): class I1(Interface): pass class I2(Interface): pass class C(object): implements(I1) def __conform__(self, iface, default=None): if iface == I2: return 42 ob = C() servicemanager = StubServiceService() context = ConformsToIServiceService(servicemanager) class I3(Interface): pass servicemanager.sm.provideAdapter((I1,), I3, '', lambda x: 43) # If an object implements the interface you want to adapt to, # getAdapterInContext should simply return the object. self.assertEquals(getAdapterInContext(ob, I1, context), ob) self.assertEquals(queryAdapterInContext(ob, I1, context), ob) # If an object conforms to the interface you want to adapt to, # getAdapterInContext should simply return the conformed object. self.assertEquals(getAdapterInContext(ob, I2, context), 42) self.assertEquals(queryAdapterInContext(ob, I2, context), 42) class I4(Interface): pass # If an adapter isn't registered for the given object and interface, # and you provide no default, raise ComponentLookupError... self.assertRaises(ComponentLookupError, getAdapterInContext, ob, I4, context) # ...otherwise, you get the default self.assertEquals(queryAdapterInContext(ob, I4, context, 44), 44) # If you ask for an adapter for which something's registered # you get the registered adapter self.assertEquals(getAdapterInContext(ob, I3, context), 43) self.assertEquals(queryAdapterInContext(ob, I3, context), 43) def testAdapter(self): # If an adapter isn't registered for the given object and interface, # and you provide no default, raise ComponentLookupError... self.assertRaises(ComponentLookupError, getAdapter, ob, I2, '') # ...otherwise, you get the default self.assertEquals(queryAdapter(ob, I2, '', Test), Test) getService(Adapters).register([I1], I2, '', Comp) c = getAdapter(ob, I2, '') self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) def testInterfaceCall(self): getService(Adapters).register([I1], I2, '', Comp) c = I2(ob) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) def testNamedAdapter(self): self.testAdapter() # If an adapter isn't registered for the given object and interface, # and you provide no default, raise ComponentLookupError... self.assertRaises(ComponentLookupError, getAdapter, ob, I2, 'test') # ...otherwise, you get the default self.assertEquals(queryAdapter(ob, I2, 'test', Test), Test) class Comp2(Comp): pass getService(Adapters).register([I1], I2, 'test', Comp2) c = getAdapter(ob, I2, 'test') self.assertEquals(c.__class__, Comp2) self.assertEquals(c.context, ob) def testQueryMultiAdapter(self): # Adapting a combination of 2 objects to an interface class DoubleAdapter(object): implements(I3) def __init__(self, first, second): self.first = first self.second = second class Ob2(object): implements(I2) ob2 = Ob2() context = None getService(Adapters, context).register([I1, I2], I3, '', DoubleAdapter) c = queryMultiAdapter((ob, ob2), I3, context=context) self.assertEquals(c.__class__, DoubleAdapter) self.assertEquals(c.first, ob) self.assertEquals(c.second, ob2) def testAdapterForInterfaceNone(self): # providing an adapter for None says that your adapter can # adapt anything to I2. getService(Adapters).register([None], I2, '', Comp) c = I2(ob) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) def testgetAdapters(self): getService(Adapters).register([I1], I2, '', Comp) getService(Adapters).register([None], I2, 'foo', Comp) c = getAdapters((ob,), I2) c.sort() self.assertEquals([(name, adapter.__class__, adapter.context) for name, adapter in c], [('', Comp, ob), ('foo', Comp, ob)]) def testUtility(self): self.assertRaises(ComponentLookupError, getUtility, I1, context=ob) self.assertRaises(ComponentLookupError, getUtility, I2, context=ob) self.assertEquals(queryUtility(I2, default=Test, context=ob), Test) getService('Utilities').provideUtility(I2, comp) self.assertEquals(id(getUtility(I2, context=ob)), id(comp)) def testNamedUtility(self): from zope.component import getUtility, queryUtility from zope.component import getService from zope.component.exceptions import ComponentLookupError self.testUtility() self.assertRaises(ComponentLookupError, getUtility, I1, 'test', context=ob) self.assertRaises(ComponentLookupError, getUtility, I2, 'test', context=ob) self.assertEquals(queryUtility(I2, 'test', Test, context=ob), Test) getService('Utilities').provideUtility(I2, comp, 'test') self.assertEquals(id(getUtility(I2, 'test', ob)), id(comp)) def test_getAllUtilitiesRegisteredFor(self): class I21(I2): pass class Comp21(Comp): implements(I21) compbob = Comp('bob') comp21 = Comp21('21') comp21bob = Comp21('21bob') getService('Utilities').provideUtility(I2, comp) getService('Utilities').provideUtility(I21, comp21) getService('Utilities').provideUtility(I2, compbob, 'bob') getService('Utilities').provideUtility(I21, comp21bob, 'bob') comps = [comp, compbob, comp21, comp21bob] comps.sort() uts = list(component.getUtilitiesFor(I2)) uts.sort() self.assertEqual(uts, [('', comp), ('bob', compbob)]) uts = list(component.getAllUtilitiesRegisteredFor(I2)) uts.sort() self.assertEqual(uts, comps) def testView(self): from zope.component import getView, queryView, getService from zope.component.exceptions import ComponentLookupError self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I1)) self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I2)) self.assertEquals(queryView(ob, 'foo', Request(I2), Test), Test) getService(Adapters).register([I1, I2], Interface, 'foo', Comp) c = getView(ob, 'foo', Request(I2)) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) self.assertRaises(ComponentLookupError, getView, ob, 'foo2', Request(I1)) self.assertRaises(ComponentLookupError, getView, ob, 'foo2', Request(I2)) self.assertEquals(queryView(ob, 'foo2', Request(I2), Test), Test) self.assertEquals(queryView(ob, 'foo2', Request(I1), None), None) def testView_w_provided(self): from zope.component import getView, queryView, getService from zope.component.exceptions import ComponentLookupError self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I1), providing=I3) self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I2), providing=I3) self.assertEquals( queryView(ob, 'foo', Request(I2), Test, providing=I3), Test) getService(Adapters).register([I1, I2], Interface, 'foo', Comp) self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I1), providing=I3) self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I2), providing=I3) self.assertEquals( queryView(ob, 'foo', Request(I2), Test, providing=I3), Test) getService(Adapters).register([I1, I2], I3, 'foo', Comp) c = getView(ob, 'foo', Request(I2), providing=I3) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) def testMultiView(self): from zope.component import queryMultiView, getService from zope.component.exceptions import ComponentLookupError class Ob2(object): implements(I2) ob2 = Ob2() class IRequest(Interface): pass request = Request(IRequest) class MV(object): implements(I3) def __init__(self, context, other, request): self.context, self.other, self.request = context, other, request self.assertEquals( queryMultiView((ob, ob2), request, I3, 'foo', 42), 42) getService(Adapters).register((I1, I2, IRequest), I3, 'foo', MV) view = queryMultiView((ob, ob2), request, I3, 'foo') self.assertEquals(view.__class__, MV) self.assertEquals(view.context, ob) self.assertEquals(view.other, ob2) self.assertEquals(view.request, request) def test_viewProvidingFunctions(self): # Confirm that a call to getViewProving/queryViewProviding simply # passes its arguments through to getView/queryView - here we hack # getView and queryView to inspect the args passed through. import zope.component # hack zope.component.getView def getView(object, name, request, context, providing): self.args = [object, name, request, context, providing] savedGetView = zope.component.getView zope.component.bbb.getView = getView # confirm pass through of args to getView by way of getViewProviding zope.component.getViewProviding( object='object', providing='providing', request='request', context='context') self.assertEquals(self.args, ['object', '', 'request', 'providing', 'context']) # hack zope.component.queryView def queryView(object, name, request, default, providing, context): self.args = [object, name, request, default, providing, context] savedQueryView = zope.component.queryView zope.component.bbb.queryView = queryView # confirm pass through of args to queryView by way of queryViewProviding zope.component.queryViewProviding( object='object', providing='providing', request='request', default='default', context='context') self.assertEquals(self.args, ['object', '', 'request', 'default', 'providing', 'context']) # restore zope.component zope.component.bbb.getView = savedGetView zope.component.bbb.queryView = savedQueryView def testResource(self): from zope.component import getResource, queryResource, getService from zope.component.exceptions import ComponentLookupError r1 = Request(I1) r2 = Request(I2) self.assertRaises(ComponentLookupError, getResource, 'foo', r1) self.assertRaises(ComponentLookupError, getResource, 'foo', r2) self.assertEquals(queryResource('foo', r2, Test), Test) getService(Adapters).register((I2,), Interface, 'foo', Comp) c = getResource('foo', r2) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, r2) self.assertRaises(ComponentLookupError, getResource, 'foo2', r1, ob) self.assertRaises(ComponentLookupError, getResource, 'foo2', r2) self.assertEquals(queryResource('foo2', r2, Test, ob), Test) self.assertEquals(queryResource('foo2', r1, None), None) def testResource_w_provided(self): from zope.component import getResource, queryResource, getService from zope.component.exceptions import ComponentLookupError r1 = Request(I1) r2 = Request(I2) self.assertRaises(ComponentLookupError, getResource, 'foo', r1, providing=I3) self.assertRaises(ComponentLookupError, getResource, 'foo', r2, providing=I3) self.assertEquals(queryResource('foo', r2, Test, providing=I3), Test) getService(Adapters).register((I2,), Interface, 'foo', Comp) self.assertRaises(ComponentLookupError, getResource, 'foo', r1, providing=I3) self.assertRaises(ComponentLookupError, getResource, 'foo', r2, providing=I3) self.assertEquals(queryResource('foo', r2, Test, providing=I3), Test) getService(Adapters).register((I2,), I3, 'foo', Comp) c = getResource('foo', r2, providing=I3) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, r2) def testViewWithContextArgument(self): # Basically the same as testView, but exercising the context # argument. As this only tests global views, the context # argument is pretty much a no-operation. from zope.component import getView, queryView, getService from zope.component.exceptions import ComponentLookupError self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I1), context=ob) self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I2), context=ob) self.assertEquals(queryView(ob, 'foo', Request(I2), Test, context=ob), Test) getService(Adapters, ob).register((I1, I2), Interface, 'foo', Comp) c = getView(ob, 'foo', Request(I2), context=ob) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) self.assertRaises(ComponentLookupError, getView, ob, 'foo2', Request(I1), context=ob) self.assertRaises(ComponentLookupError, getView, ob, 'foo2', Request(I2), context=ob) self.assertEquals(queryView(ob, 'foo2', Request(I2), Test, context=ob), Test) self.assertEquals(queryView(ob, 'foo2', Request(I1), None, context=ob), None) def testDefaultViewName(self): from zope.component import getService getService(Adapters).register((I1, I2), IDefaultViewName, '', 'sample_name') self.assertRaises(ComponentLookupError, getDefaultViewName, ob, Request(I1)) self.assertEquals(getDefaultViewName(ob, Request(I2)), 'sample_name') self.assertRaises(ComponentLookupError, getDefaultViewName, ob, Request(I1)) class TestNoSetup(unittest.TestCase): def testNotBrokenWhenNoService(self): # Both of those things emit DeprecationWarnings. self.assertRaises(TypeError, I2, ob) self.assertEquals(I2(ob, 42), 42) pass def test_suite(): return unittest.TestSuite(( unittest.makeSuite(Test), unittest.makeSuite(TestNoSetup), )) if __name__ == "__main__": unittest.TextTestRunner().run(test_suite()) PK]^„4¤Mh]--$zope/component/bbb/tests/__init__.py# Make directory a package. __warn__ = True PK]^„4~ŠB§ââ*zope/component/bbb/tests/placelesssetup.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Placeless Test Setup $Id: placelesssetup.py 29143 2005-02-14 22:43:16Z srichter $ """ import warnings from zope.component.testing import * from zope.component import bbb if bbb.tests.__warn__: warnings.warn( "`zope.component.tests.placelesssetup` is superceded by " "`zope.component.testing`.", DeprecationWarning, 2) PK]^„4r „€€(zope/component/bbb/tests/test_service.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Test ServiceService component $Id: test_service.py 29930 2005-04-09 17:40:14Z srichter $ """ import unittest import pickle from zope.interface import Interface, implements from zope.exceptions import DuplicationError from zope.testing.cleanup import CleanUp from zope.component import getServiceDefinitions, getService, getGlobalServices from zope.component.service import UndefinedService, InvalidService from zope.component.service import GlobalServiceManager, GlobalService from zope.component.exceptions import ComponentLookupError from zope.component.interfaces import IServiceService class IOne(Interface): pass class ITwo(Interface): pass class ServiceOne(GlobalService): implements(IOne) class ServiceTwo(GlobalService): implements(ITwo) class Test(CleanUp, unittest.TestCase): def setUp(self): super(Test, self).setUp() from zope.component import bbb bbb.__warn__ = False bbb.service.__warn__ = False def tearDown(self): super(Test, self).cleanUp() # Make sure that the testServiceManager is clean global testServiceManager testServiceManager.sm.__init__(testServiceManager.sm.__name__) from zope.component import bbb bbb.__warn__ = True bbb.service.__warn__ = True def testNormal(self): ss = getGlobalServices() ss.defineService('one', IOne) c = ServiceOne() ss.provideService('one', c) self.assertEqual(id(getService('one',)), id(c)) def testFailedLookup(self): self.assertRaises(ComponentLookupError, getService, 'two') def testDup(self): getGlobalServices().defineService('one', IOne) self.assertRaises(DuplicationError, getGlobalServices().defineService, 'one', ITwo) c = ServiceOne() getGlobalServices().provideService('one', c) c2 = ServiceOne() self.assertRaises(DuplicationError, getGlobalServices().provideService, 'one', c2) self.assertEqual(id(getService('one')), id(c)) def testUndefined(self): c = ServiceOne() self.assertRaises(UndefinedService, getGlobalServices().provideService, 'one', c) def testInvalid(self): getGlobalServices().defineService('one', IOne) getGlobalServices().defineService('two', ITwo) c = ServiceOne() self.assertRaises(InvalidService, getGlobalServices().provideService, 'two', c) def testGetService(self): # Testing looking up a service from a service manager container that # doesn't have a service manager. getGlobalServices().defineService('one', IOne) c = ServiceOne() getGlobalServices().provideService('one', c) self.assertEqual(id(getService('one')), id(c)) def testGetServiceDefinitions(self): # test that the service definitions are the ones we added sm = getGlobalServices() sm.defineService('one', IOne) c = ServiceOne() sm.provideService('one', c) sm.defineService('two', ITwo) d = ServiceTwo() sm.provideService('two', d) defs = getServiceDefinitions() defs.sort() self.assertEqual(defs, [('Services', IServiceService), ('one', IOne), ('two', ITwo)]) def testPickling(self): self.assertEqual(testServiceManager.__reduce__(), 'testServiceManager') sm = pickle.loads(pickle.dumps(testServiceManager)) self.assert_(sm is testServiceManager) s2 = ServiceTwo() sm.defineService('2', ITwo) sm.provideService('2', s2) self.assert_(s2.__parent__ is sm) self.assertEqual(s2.__name__, '2') s = pickle.loads(pickle.dumps(s2)) self.assert_(s is s2) testServiceManager._clear() from zope.component import bbb bbb.service.__warn__ = False testServiceManager = GlobalServiceManager('testServiceManager', __name__) bbb.service.__warn__ = True def test_suite(): return unittest.TestSuite(( unittest.makeSuite(Test), )) if __name__ == '__main__': unittest.main(defaultTest='test_suite') PK]^„4 YZ¢¢&zope/component/bbb/tests/components.py############################################################################## # # Copyright (c) 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Components for testing $Id: components.py 29143 2005-02-14 22:43:16Z srichter $ """ import warnings from zope.interface import Interface, Attribute, implements from zope.component import bbb if bbb.tests.__warn__: warnings.warn( "`zope.component.tests.components` has been deprecated, since the " " contained helper objects were very simple and did not add much " "value.", DeprecationWarning, 2) class RecordingAdapter(object): def __init__(self): self.record = [] def __call__(self, context): # Note that this sets the context rather than appending to the record # so as not to assume things about adapters being cached, if this # happens in the future. self.context = context return self def check(self, *args): record = self.record if len(args) != len(record): raise AssertionError('wrong number of entries in record', args, record) for arg, entry in zip(args, record): if arg != entry: raise AssertionError('record entry does not match', args, record) class IApp(Interface): a = Attribute('test attribute') def f(): "test func" class IContent(Interface): pass class Content(object): implements(IContent) class Comp(object): __used_for__ = IContent implements(IApp) def __init__(self, *args): # Ignore arguments passed to constructor pass a = 1 def f(): pass comp = Comp() PK]^„4yáò(ßß/zope/component/bbb/tests/test_utilityservice.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Utility service tests $Id: test_utilityservice.py 29143 2005-02-14 22:43:16Z srichter $ """ from unittest import TestCase, main, makeSuite from zope.component import \ getUtility, getUtilitiesFor, getService, queryUtility, \ getServices, getUtilitiesFor, getGlobalServices from zope.component.exceptions import ComponentLookupError from zope.component.servicenames import Utilities from zope.interface import Interface, implements from zope.testing.cleanup import CleanUp # Base class w registry cleanup class IDummyUtility(Interface): pass class IDummerUtility(IDummyUtility): pass class DummyUtility(object): __name__ = 'DummyUtility' implements(IDummyUtility) class DummyUtility2(object): implements(IDummyUtility) __name__ = 'DummyUtility2' def __len__(self): return 0 class DummerUtility(object): __name__ = 'DummerUtility' implements(IDummerUtility) dummyUtility = DummyUtility() dummerUtility = DummerUtility() dummyUtility2 = DummyUtility2() class Test(TestCase, CleanUp): def setUp(self): from zope.component import bbb bbb.__warn__ = False bbb.service.__warn__ = False CleanUp.setUp(self) sm = getGlobalServices() defineService = sm.defineService provideService = sm.provideService from zope.component.interfaces import IUtilityService defineService('Utilities',IUtilityService) from zope.component.utility import GlobalUtilityService provideService('Utilities', GlobalUtilityService()) def cleanUp(self): super(Test, self).cleanUp() from zope.component import bbb bbb.__warn__ = True bbb.service.__warn__ = True def testGetUtility(self): us = getService(Utilities) self.assertRaises( ComponentLookupError, getUtility, IDummyUtility) us.provideUtility(IDummyUtility, dummyUtility) self.assertEqual(getUtility(IDummyUtility), dummyUtility) def testQueryUtility(self): us = getService(Utilities) self.assertEqual(queryUtility(IDummyUtility), None) self.assertEqual(queryUtility(IDummyUtility, default=self), self) us.provideUtility(IDummyUtility, dummyUtility) self.assertEqual(queryUtility(IDummyUtility), dummyUtility) def testgetUtilitiesFor(self): us = getService(Utilities) us.provideUtility(IDummyUtility, dummyUtility) self.assertEqual(list(getUtilitiesFor(IDummyUtility)), [('',dummyUtility)]) self.assertEqual(list(us.getUtilitiesFor(IDummyUtility)), [('',dummyUtility)]) def testregistrations(self): us = getService(Utilities) us.provideUtility(IDummyUtility, dummyUtility) self.assertEqual( map(str, us.registrations()), ["UtilityRegistration('IDummyUtility', '', 'DummyUtility', '')"]) def testOverrides(self): us = getService(Utilities) # fail if nothing registered: self.assertRaises( ComponentLookupError, getUtility, IDummyUtility) # set and retiev dummy us.provideUtility(IDummyUtility, dummyUtility) self.assertEqual(getUtility(IDummyUtility), dummyUtility) # dummer overrides us.provideUtility(IDummerUtility, dummerUtility) self.assertEqual(getUtility(IDummerUtility), dummerUtility) # But not if we ask for dummy self.assertEqual(getUtility(IDummyUtility), dummyUtility) # same for named: self.assertRaises( ComponentLookupError, getUtility, IDummyUtility, 'bob') us.provideUtility(IDummyUtility, dummyUtility, 'bob') self.assertEqual(getUtility(IDummyUtility), dummyUtility, 'bob') us.provideUtility(IDummerUtility, dummerUtility, 'bob') self.assertEqual(getUtility(IDummerUtility), dummerUtility, 'bob') self.assertEqual(getUtility(IDummyUtility), dummyUtility, 'bob') # getUtilitiesFor doesn the right thing: uts = list(us.getUtilitiesFor(IDummyUtility)) uts.sort() self.assertEqual(uts, [('', dummyUtility), ('bob', dummyUtility)]) uts = list(us.getUtilitiesFor(IDummerUtility)) uts.sort() self.assertEqual(uts, [('', dummerUtility), ('bob', dummerUtility)]) return us def test_getAllUtilitiesRegisteredFor(self): us = self.testOverrides() # getAllUtilitiesRegisteredFor includes overridden uts = list(us.getAllUtilitiesRegisteredFor(IDummerUtility)) self.assertEqual(uts, [dummerUtility, dummerUtility]) uts = list(us.getAllUtilitiesRegisteredFor(IDummyUtility)) uts.remove(dummyUtility) uts.remove(dummyUtility) uts.remove(dummerUtility) uts.remove(dummerUtility) self.assertEqual(uts, []) def test_getAllUtilitiesRegisteredFor_empty(self): us = getService(Utilities) class IFoo(Interface): pass self.assertEqual(list(us.getAllUtilitiesRegisteredFor(IFoo)), []) def test_suite(): return makeSuite(Test) if __name__=='__main__': main(defaultTest='test_suite') PK¶“„4‰(oB)zope/component/bbb/tests/test_adapter.pyc;ò â•2Dc@sOdZdkZdklZdklZdeifd„ƒYZd„ZdS(sYGlobal Adapter Service Tests $Id: test_adapter.py 29143 2005-02-14 22:43:16Z srichter $ N(s DocTestSuite(sGlobalAdapterServicesGlobalAdapterServiceTestscBstZd„ZRS(NcCs‹dkl}dkl}|id|ƒtƒ}|id|ƒdk}|i |i |ƒƒ}|i |i|ijƒ|iƒdS(N(stestServiceManager(sIAdapterServicesAdapters(s%zope.component.bbb.tests.test_servicestestServiceManagerszope.component.interfacessIAdapterServices defineServicesGlobalAdapterServicesadapterssprovideServicespicklesloadssdumpssassselfsassert_ssms_clear(sselfstestServiceManagerspicklesIAdapterServicesassadapters((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_adapter.pysBBB_test_picklings    (s__name__s __module__sBBB_test_pickling(((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_adapter.pysGlobalAdapterServiceTestsscCs*titƒ}|itdƒƒ|SdS(Nszope.component.adapter(sunittests makeSuitesGlobalAdapterServiceTestsssuitesaddTests DocTestSuite(ssuite((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_adapter.pys test_suite(s( s__doc__sunittestsdoctests DocTestSuiteszope.component.adaptersGlobalAdapterServicesTestCasesGlobalAdapterServiceTestss test_suite(sunittestsGlobalAdapterServices test_suites DocTestSuitesGlobalAdapterServiceTests((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_adapter.pys?s    PK¶“„4}uD›ÖÖ$zope/component/bbb/tests/request.pyc;ò â•2Dc@scdZdkZdkZdklZeiioeide dƒnde fd„ƒYZ dS(sKRequest for tests $Id: request.py 30931 2005-06-27 15:48:32Z benji_york $ N(sbbbs€`zope.component.tests.request` is deprecated, since the component architecture does not support presentation components anymore.isRequestcBstZed„ZRS(NcCs]tii||ƒ|tj o0dk}|idt ƒtii||ƒn||_ dS(Ns¨The skin argument is deprecated for zope.component.tests.request.Request and will go away in Zope 3.3. Use zope.publisher.browser.TestRequest if you need to test skins.( szopes interfacesdirectlyProvidessselfstypesskinsNoneswarningsswarnsDeprecationWarnings_skin(sselfstypesskinswarnings((s>build/bdist.linux-i686/egg/zope/component/bbb/tests/request.pys__init__s   (s__name__s __module__sNones__init__(((s>build/bdist.linux-i686/egg/zope/component/bbb/tests/request.pysRequests( s__doc__swarningsszope.interfaceszopeszope.componentsbbbstestss__warn__swarnsDeprecationWarningsobjectsRequest(swarningssRequestsbbbszope((s>build/bdist.linux-i686/egg/zope/component/bbb/tests/request.pys?s     PK¶“„4¬y‰)w)w%zope/component/bbb/tests/test_api.pyc;ò â•2Dc@sGdZdkZdklZdklZdklZlZlZdkl Z l Z dkl Z dkl Z l Z dklZd klZd klZd klZd klZd klZdklZlZdklZdklZlZdkl Z defd„ƒYZ!defd„ƒYZ"defd„ƒYZ#de$fd„ƒYZ%de$fd„ƒYZ&e%dƒZ'de$fd„ƒYZ(e(ƒZ)de(fd „ƒYZ*d!e$fd"„ƒYZ+d#e$fd$„ƒYZ,d%eei-fd&„ƒYZ.d'ei-fd(„ƒYZ/d)„Z0e1d*joei2ƒi3e0ƒƒndS(+s<API tests $Id: test_api.py 38178 2005-08-30 21:50:19Z mj $ N(s component(s servicenames(s getAdapters queryAdapters getAdapters(sgetAdapterInContextsqueryAdapterInContext(s getService(s getUtilitys queryUtility(sgetDefaultViewName(squeryMultiAdapter(sComponentLookupError(sAdapters(sPlacelessSetup(sRequest(sIComponentArchitecturesIServiceService(sIDefaultViewName(s Interfaces implements(s verifyObjectsI1cBstZRS(N(s__name__s __module__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysI1&ssI2cBstZRS(N(s__name__s __module__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysI2(ssI3cBstZRS(N(s__name__s __module__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysI3*ssCompcBstZeeƒed„ZRS(NcCs ||_dS(N(scontextsself(sselfscontextsrequest((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys__init__/s(s__name__s __module__s implementssI2sNones__init__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysComp-s sComp2cBstZeeƒed„ZRS(NcCs ||_dS(N(scontextsself(sselfscontextsrequest((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys__init__3s(s__name__s __module__s implementssI3sNones__init__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysComp21s isObcBstZeeƒd„ZRS(NcCs[|tjodkl}|ƒSndkl}dkl}||jo |ƒSndS(N(s getServices(s ISiteManager(sgetSiteManager(sisIServiceServiceszope.component.bbbs getServicesszope.component.interfacess ISiteManagerszope.componentsgetSiteManager(sselfsis ISiteManagersgetSiteManagers getServices((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys __conform__9s      (s__name__s __module__s implementssI1s __conform__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysOb7s s ConformingcBstZd„ZRS(NcCs/|tjot|ƒSnti||ƒSdS(N(sisI3sCompsselfsObs __conform__(sselfsi((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys __conform__Fs (s__name__s __module__s __conform__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys ConformingEssStubServiceServicecBs-tZeeƒd„Zd„Zd„ZRS(NcCs&h|_dkl}|ƒ|_dS(N(sGlobalSiteManager(sselfsservicesszope.component.sitesGlobalSiteManagerssm(sselfsGlobalSiteManager((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys__init__Os  cCs||i|Åsi*sI4cBstZRS(N(s__name__s __module__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysI4Ñsi,i+(s InterfacesI1sI2sobjectsCsobsStubServiceServicesservicemanagersConformsToIServiceServicescontextsI3ssmsprovideAdaptersselfs assertEqualssgetAdapterInContextsqueryAdapterInContextsI4s assertRaisessComponentLookupError( sselfsCsI1sI2sobsI4sservicemanagerscontextsI3((sI1sI2s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestAdapterInContext´s$    cCs“|ittttdƒ|itttdtƒtƒt t ƒi t gtdt ƒtttdƒ}|i|it ƒ|i|itƒdS(Ns(sselfs assertRaisessComponentLookupErrors getAdaptersobsI2s assertEqualss queryAdaptersTests getServicesAdapterssregistersI1sCompscs __class__scontext(sselfsc((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys testAdapteràs cCsUttƒitgtdtƒttƒ}|i |i tƒ|i |i tƒdS(Ns( s getServicesAdapterssregistersI1sI2sCompsobscsselfs assertEqualss __class__scontext(sselfsc((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestInterfaceCallís cCs³|iƒ|ittttdƒ|itttdt ƒt ƒdt fd„ƒY}t t ƒitgtd|ƒtttdƒ}|i|i|ƒ|i|itƒdS(NstestsComp2cBstZRS(N(s__name__s __module__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysComp2ýs(sselfs testAdapters assertRaisessComponentLookupErrors getAdaptersobsI2s assertEqualss queryAdaptersTestsCompsComp2s getServicesAdapterssregistersI1scs __class__scontext(sselfscsComp2((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestNamedAdapterós cCs¸dtfd„ƒY}dtfd„ƒY}|ƒ}t}tt|ƒit t gt d|ƒt t |ft d|ƒ}|i|i|ƒ|i|it ƒ|i|i|ƒdS(Ns DoubleAdaptercBstZeeƒd„ZRS(NcCs||_||_dS(N(sfirstsselfssecond(sselfsfirstssecond((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys__init__s (s__name__s __module__s implementssI3s__init__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys DoubleAdapters sOb2cBstZeeƒRS(N(s__name__s __module__s implementssI2(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysOb2 ssscontext(sobjects DoubleAdaptersOb2sob2sNonescontexts getServicesAdapterssregistersI1sI2sI3squeryMultiAdaptersobscsselfs assertEqualss __class__sfirstssecond(sselfsOb2scscontexts DoubleAdaptersob2((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestQueryMultiAdapters %cCsUttƒitgtdtƒttƒ}|i |i tƒ|i |i tƒdS(Ns( s getServicesAdapterssregistersNonesI2sCompsobscsselfs assertEqualss __class__scontext(sselfsc((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestAdapterForInterfaceNones cCs¼ttƒitgtdtƒttƒitgtdtƒttftƒ}|i ƒ|i gi }|D]%\}}|||i|ifƒqn~dttfdttfgƒdS(Nssfoo(s getServicesAdapterssregistersI1sI2sCompsNones getAdapterssobscssortsselfs assertEqualssappends_[1]snamesadapters __class__scontext(sselfsnamescs_[1]sadapter((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestgetAdapterss  ?cCs–|itttdtƒ|itttdtƒ|ittdt dtƒt ƒt dƒi tt ƒ|it ttdtƒƒt t ƒƒdS(Nscontextsdefaults Utilities(sselfs assertRaisessComponentLookupErrors getUtilitysI1sobsI2s assertEqualss queryUtilitysTests getServicesprovideUtilityscompsid(sself((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys testUtility's "cCsÖdkl}l}dkl}dkl}|iƒ|i||t ddt ƒ|i||t ddt ƒ|i |t dt dt ƒt ƒ|dƒit tdƒ|i t|t dt ƒƒttƒƒdS(N(s getUtilitys queryUtility(s getService(sComponentLookupErrorstestscontexts Utilities(szope.components getUtilitys queryUtilitys getServiceszope.component.exceptionssComponentLookupErrorsselfs testUtilitys assertRaisessI1sobsI2s assertEqualssTestsprovideUtilityscompsid(sselfs queryUtilitysComponentLookupErrors getUtilitys getService((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestNamedUtility/s     csAdtfd„ƒY‰dtf‡d†ƒY}tdƒ}|dƒ}|dƒ}tdƒitt ƒtdƒiˆ|ƒtdƒit|dƒtdƒiˆ|dƒt |||g}|i ƒt t itƒƒ}|i ƒ|i|d t fd|fgƒt t itƒƒ}|i ƒ|i||ƒdS( NsI21cBstZRS(N(s__name__s __module__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysI21AssComp21cstZeˆƒRS(N(s__name__s __module__s implementssI21((sI21(s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysComp21Cssbobs21s21bobs Utilitiess(sI2sI21sCompsComp21scompbobscomp21s comp21bobs getServicesprovideUtilityscompscompsssortslists componentsgetUtilitiesForsutssselfs assertEqualsgetAllUtilitiesRegisteredFor(sselfscompbobscompssComp21sI21s comp21bobscomp21suts((sI21s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys!test_getAllUtilitiesRegisteredFor@s"     " cCsudkl}l}l}dkl}|i||tdt t ƒƒ|i||tdt t ƒƒ|i |tdt t ƒt ƒt ƒ|tƒit t gtdtƒ|tdt t ƒƒ}|i |itƒ|i |itƒ|i||tdt t ƒƒ|i||tdt t ƒƒ|i |tdt t ƒt ƒt ƒ|i |tdt t ƒtƒtƒdS(N(sgetViews queryViews getService(sComponentLookupErrorsfoosfoo2(szope.componentsgetViews queryViews getServiceszope.component.exceptionssComponentLookupErrorsselfs assertRaisessobsRequestsI1sI2s assertEqualssTestsAdapterssregisters InterfacesCompscs __class__scontextsNone(sselfsgetViewscs queryViewsComponentLookupErrors getService((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestViewZs"   %"  %cCsœdkl}l}l}dkl}|i||tdt t ƒdt ƒ|i||tdt t ƒdt ƒ|i |tdt t ƒtdt ƒtƒ|tƒit t gtdtƒ|i||tdt t ƒdt ƒ|i||tdt t ƒdt ƒ|i |tdt t ƒtdt ƒtƒ|tƒit t gt dtƒ|tdt t ƒdt ƒ}|i |itƒ|i |itƒdS(N(sgetViews queryViews getService(sComponentLookupErrorsfoos providing(szope.componentsgetViews queryViews getServiceszope.component.exceptionssComponentLookupErrorsselfs assertRaisessobsRequestsI1sI3sI2s assertEqualssTestsAdapterssregisters InterfacesCompscs __class__scontext(sselfsgetViewscs queryViewsComponentLookupErrors getService((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestView_w_providedqs&   $"  $"c Cs/dkl}l}dkl}dtfd„ƒY}|ƒ}dtfd„ƒY}t |ƒ}dtfd„ƒY}|i|t|f|td d ƒd ƒ|tƒitt|ftd |ƒ|t|f|td ƒ} |i| i|ƒ|i| itƒ|i| i|ƒ|i| i |ƒdS( N(squeryMultiViews getService(sComponentLookupErrorsOb2cBstZeeƒRS(N(s__name__s __module__s implementssI2(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysOb2‘ssIRequestcBstZRS(N(s__name__s __module__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysIRequest–ssMVcBstZeeƒd„ZRS(NcCs%|||f\|_|_|_dS(N(scontextsothersrequestsself(sselfscontextsothersrequest((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys__init__s(s__name__s __module__s implementssI3s__init__(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysMV›s sfooi*(szope.componentsqueryMultiViews getServiceszope.component.exceptionssComponentLookupErrorsobjectsOb2sob2s InterfacesIRequestsRequestsrequestsMVsselfs assertEqualssobsI3sAdapterssregistersI1sI2sviews __class__scontextsother( sselfsMVsob2sComponentLookupErrorsrequests getServicesIRequestsqueryMultiViewsOb2sview((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys testMultiViews   (%c sdk}‡d†}|ii}||ii_|iiddddddddƒˆiˆi dddddgƒ‡d†}|ii }||ii_ |ii ddddddddddƒˆiˆi ddddddgƒ||ii_||ii_ dS( Ncs|||||gˆ_dS(N(sobjectsnamesrequestscontexts providingsselfsargs(sobjectsnamesrequestscontexts providing(sself(s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysgetView²ssobjects providingsrequestscontextscs||||||gˆ_dS(N(sobjectsnamesrequestsdefaults providingscontextsselfsargs(sobjectsnamesrequestsdefaults providingscontext(sself(s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys queryView¿ssdefault( szope.componentszopesgetViews components savedGetViewsbbbsgetViewProvidingsselfs assertEqualssargss queryViewssavedQueryViewsqueryViewProviding(sselfsgetViewssavedQueryViews savedGetViews queryViewszope((sselfs?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystest_viewProvidingFunctions«s"        cCsHdkl}l}l}dkl}ttƒ}tt ƒ}|i ||d|ƒ|i ||d|ƒ|i |d|tƒtƒ|tƒit ftdtƒ|d|ƒ}|i |itƒ|i |i|ƒ|i ||d|tƒ|i ||d|ƒ|i |d|ttƒtƒ|i |d|tƒtƒdS(N(s getResources queryResources getService(sComponentLookupErrorsfoosfoo2(szope.components getResources queryResources getServiceszope.component.exceptionssComponentLookupErrorsRequestsI1sr1sI2sr2sselfs assertRaisess assertEqualssTestsAdapterssregisters InterfacesCompscs __class__scontextsobsNone(sselfscs getResourcesr1sr2sComponentLookupErrors getServices queryResource((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys testResourceÏs   cCsodkl}l}l}dkl}ttƒ}tt ƒ}|i ||d|dt ƒ|i ||d|dt ƒ|i|d|tdt ƒtƒ|tƒit ftdtƒ|i ||d|dt ƒ|i ||d|dt ƒ|i|d|tdt ƒtƒ|tƒit ft dtƒ|d|dt ƒ}|i|itƒ|i|i|ƒdS(N(s getResources queryResources getService(sComponentLookupErrorsfoos providing(szope.components getResources queryResources getServiceszope.component.exceptionssComponentLookupErrorsRequestsI1sr1sI2sr2sselfs assertRaisessI3s assertEqualssTestsAdapterssregisters InterfacesCompscs __class__scontext(sselfscs getResourcesr1sr2sComponentLookupErrors getServices queryResource((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestResource_w_providedås*       cCs¨dkl}l}l}dkl}|i||tdt t ƒdtƒ|i||tdt t ƒdtƒ|i |tdt t ƒt dtƒt ƒ|ttƒit t ftdtƒ|tdt t ƒdtƒ}|i |itƒ|i |itƒ|i||tdt t ƒdtƒ|i||tdt t ƒdtƒ|i |tdt t ƒt dtƒt ƒ|i |tdt t ƒtdtƒtƒdS(N(sgetViews queryViews getService(sComponentLookupErrorsfooscontextsfoo2(szope.componentsgetViews queryViews getServiceszope.component.exceptionssComponentLookupErrorsselfs assertRaisessobsRequestsI1sI2s assertEqualssTestsAdapterssregisters InterfacesCompscs __class__scontextsNone(sselfsgetViewscs queryViewsComponentLookupErrors getService((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestViewWithContextArguments,   $%    cCsŠdkl}|tƒittftddƒ|it t t t tƒƒ|i t t t tƒƒdƒ|it t t t tƒƒdS(N(s getServicess sample_name(szope.components getServicesAdapterssregistersI1sI2sIDefaultViewNamesselfs assertRaisessComponentLookupErrorsgetDefaultViewNamesobsRequests assertEquals(sselfs getService((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestDefaultViewName"s    (s__name__s __module__ssetUpscleanUpstestInterfacesstest_getGlobalServicesstest_getServicesstest_getServicestestAdapterInContexts testAdapterstestInterfaceCallstestNamedAdapterstestQueryMultiAdapterstestAdapterForInterfaceNonestestgetAdapterss testUtilitystestNamedUtilitys!test_getAllUtilitiesRegisteredForstestViewstestView_w_provideds testMultiViewstest_viewProvidingFunctionss testResourcestestResource_w_providedstestViewWithContextArgumentstestDefaultViewName(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pysTestjs0       ,          $   s TestNoSetupcBstZd„ZRS(NcCs0|itttƒ|ittdƒdƒdS(Ni*(sselfs assertRaisess TypeErrorsI2sobs assertEquals(sself((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pystestNotBrokenWhenNoService2s(s__name__s __module__stestNotBrokenWhenNoService(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys TestNoSetup0scCs)tititƒtitƒfƒSdS(N(sunittests TestSuites makeSuitesTests TestNoSetup(((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys test_suite8ss__main__(4s__doc__sunittestszopes componentszope.components servicenamess getAdapters queryAdapters getAdapterssgetAdapterInContextsqueryAdapterInContexts getServices getUtilitys queryUtilitysgetDefaultViewNamesqueryMultiAdapterszope.component.exceptionssComponentLookupErrorszope.component.servicenamessAdapterss#zope.component.tests.placelesssetupsPlacelessSetupszope.component.tests.requestsRequestszope.component.interfacessIComponentArchitecturesIServiceServicesIDefaultViewNameszope.interfaces Interfaces implementsszope.interface.verifys verifyObjectsI1sI2sI3sobjectsCompsComp2scompsObsobs ConformingsStubServiceServicesConformsToIServiceServicesTestCasesTests TestNoSetups test_suites__name__sTextTestRunnersrun(%sunittestsComponentLookupErrorsIDefaultViewNames getUtilitys ConformingsTestsIServiceServicesqueryMultiAdapters getAdaptersI1sCompsI3sI2s queryAdapters servicenamess InterfacesRequestsgetDefaultViewNames queryUtilitysgetAdapterInContextsStubServiceServices components getAdapterssqueryAdapterInContextsObsPlacelessSetups getServicesAdapterss implementss TestNoSetups verifyObjectsobsComp2s test_suitesConformsToIServiceServicesIComponentArchitecturescomp((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/test_api.pys?sD               ÿÇ  PK¶“„4ÅaÓ)¸¸%zope/component/bbb/tests/__init__.pyc;ò â•2Dc@s eZdS(N(sTrues__warn__(s__warn__((s?build/bdist.linux-i686/egg/zope/component/bbb/tests/__init__.pys?sPK¶“„4µQ¾·MM+zope/component/bbb/tests/placelesssetup.pyc;ò â•2Dc@sKdZdkZdkTdklZeiioeidedƒndS(sSPlaceless Test Setup $Id: placelesssetup.py 29143 2005-02-14 22:43:16Z srichter $ N(s*(sbbbsP`zope.component.tests.placelesssetup` is superceded by `zope.component.testing`.i( s__doc__swarningsszope.component.testingszope.componentsbbbstestss__warn__swarnsDeprecationWarning(sbbbswarnings((sEbuild/bdist.linux-i686/egg/zope/component/bbb/tests/placelesssetup.pys?s     PK¶“„4t ð‹ïï)zope/component/bbb/tests/test_service.pyc;ò â•2Dc@stdZdkZdkZdklZlZdklZdkl Z dk l Z l Z l Z dklZlZdklZlZdklZd klZd efd „ƒYZd efd „ƒYZdefd„ƒYZdefd„ƒYZde eifd„ƒYZdk lZeei_ ede!ƒa"e#ei_ d„Z$e!djoei%ddƒndS(sZTest ServiceService component $Id: test_service.py 29930 2005-04-09 17:40:14Z srichter $ N(s Interfaces implements(sDuplicationError(sCleanUp(sgetServiceDefinitionss getServicesgetGlobalServices(sUndefinedServicesInvalidService(sGlobalServiceManagers GlobalService(sComponentLookupError(sIServiceServicesIOnecBstZRS(N(s__name__s __module__(((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pysIOne ssITwocBstZRS(N(s__name__s __module__(((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pysITwo#ss ServiceOnecBstZeeƒRS(N(s__name__s __module__s implementssIOne(((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pys ServiceOne&ss ServiceTwocBstZeeƒRS(N(s__name__s __module__s implementssITwo(((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pys ServiceTwo)ssTestcBsbtZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d „Z d „Z RS( NcCs9tt|ƒiƒdkl}t|_t|i_dS(N(sbbb( ssupersTestsselfssetUpszope.componentsbbbsFalses__warn__sservice(sselfsbbb((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pyssetUp.s  cCsOtt|ƒiƒtiitiiƒdkl }t |_ t |i _ dS(N(sbbb( ssupersTestsselfscleanUpstestServiceManagerssms__init__s__name__szope.componentsbbbsTrues__warn__sservice(sselfsbbb((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pystearDown4s   cCsXtƒ}|idtƒtƒ}|id|ƒ|it t dƒƒt |ƒƒdS(Nsone( sgetGlobalServicesssss defineServicesIOnes ServiceOnescsprovideServicesselfs assertEqualsids getService(sselfscsss((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pys testNormal=s   cCs|ittdƒdS(Nstwo(sselfs assertRaisessComponentLookupErrors getService(sself((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pystestFailedLookupDscCs–tƒidtƒ|ittƒidtƒtƒ}tƒi d|ƒtƒ}|ittƒi d|ƒ|i t t dƒƒt |ƒƒdS(Nsone(sgetGlobalServicess defineServicesIOnesselfs assertRaisessDuplicationErrorsITwos ServiceOnescsprovideServicesc2s assertEqualsids getService(sselfscsc2((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pystestDupGs        cCs)tƒ}|ittƒid|ƒdS(Nsone(s ServiceOnescsselfs assertRaisessUndefinedServicesgetGlobalServicessprovideService(sselfsc((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pys testUndefinedXs   cCsOtƒidtƒtƒidtƒtƒ}|ittƒi d|ƒdS(Nsonestwo( sgetGlobalServicess defineServicesIOnesITwos ServiceOnescsselfs assertRaisessInvalidServicesprovideService(sselfsc((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pys testInvalid^s    cCsUtƒidtƒtƒ}tƒid|ƒ|itt dƒƒt|ƒƒdS(Nsone( sgetGlobalServicess defineServicesIOnes ServiceOnescsprovideServicesselfs assertEqualsids getService(sselfsc((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pystestGetServicefs cCstƒ}|idtƒtƒ}|id|ƒ|idtƒtƒ}|id|ƒt ƒ}|i ƒ|i|dtfdtfdtfgƒdS(NsonestwosServices(sgetGlobalServicesssms defineServicesIOnes ServiceOnescsprovideServicesITwos ServiceTwosdsgetServiceDefinitionssdefsssortsselfs assertEqualsIServiceService(sselfsdefsscssmsd((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pystestGetServiceDefinitionsns      cCsÌ|itiƒdƒtititƒƒ}|i|tjƒt ƒ}|i dt ƒ|i d|ƒ|i|i|jƒ|i|idƒtiti|ƒƒ}|i||jƒtiƒdS(NstestServiceManagers2(sselfs assertEqualstestServiceManagers __reduce__spicklesloadssdumpsssmsassert_s ServiceTwoss2s defineServicesITwosprovideServices __parent__s__name__sss_clear(sselfss2ssssm((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pys testPickling}s ( s__name__s __module__ssetUpstearDowns testNormalstestFailedLookupstestDups testUndefineds testInvalidstestGetServicestestGetServiceDefinitionss testPickling(((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pysTest,s        (sbbbstestServiceManagercCstititƒfƒSdS(N(sunittests TestSuites makeSuitesTest(((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pys test_suite“ss__main__s defaultTests test_suite(&s__doc__sunittestspickleszope.interfaces Interfaces implementsszope.exceptionssDuplicationErrorszope.testing.cleanupsCleanUpszope.componentsgetServiceDefinitionss getServicesgetGlobalServicesszope.component.servicesUndefinedServicesInvalidServicesGlobalServiceManagers GlobalServiceszope.component.exceptionssComponentLookupErrorszope.component.interfacessIServiceServicesIOnesITwos ServiceOnes ServiceTwosTestCasesTestsbbbsFalsesservices__warn__s__name__stestServiceManagersTrues test_suitesmain(sCleanUpsgetServiceDefinitionssunittestsComponentLookupErrorsTestsIServiceServicesgetGlobalServicess GlobalServicesbbbs ServiceOnes ServiceTwos InterfacesInvalidServices getServicesIOnesGlobalServiceManagersUndefinedServices implementssITwosDuplicationErrors test_suitespickle((sCbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_service.pys?s,      a     PK¶“„4F>éú55'zope/component/bbb/tests/components.pyc;ò â•2Dc@sÔdZdkZdklZlZlZdklZeii oei de dƒnde fd„ƒYZ defd „ƒYZd efd „ƒYZd e fd „ƒYZde fd„ƒYZeƒZdS(sQComponents for testing $Id: components.py 29143 2005-02-14 22:43:16Z srichter $ N(s Interfaces Attributes implements(sbbbs‡`zope.component.tests.components` has been deprecated, since the contained helper objects were very simple and did not add much value.isRecordingAdaptercBs#tZd„Zd„Zd„ZRS(NcCs g|_dS(N(sselfsrecord(sself((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pys__init__ scCs||_|SdS(N(scontextsself(sselfscontext((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pys__call__#s cGs|i}t|ƒt|ƒjotd||ƒ‚nx@t||ƒD]/\}}||jotd||ƒ‚qHqHWdS(Ns!wrong number of entries in recordsrecord entry does not match(sselfsrecordslensargssAssertionErrorszipsargsentry(sselfsargssrecordsargsentry((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pyscheck*s   (s__name__s __module__s__init__s__call__scheck(((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pysRecordingAdapters  sIAppcBstZedƒZd„ZRS(Nstest attributecCsdS(s test funcN((((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pysf7s(s__name__s __module__s Attributesasf(((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pysIApp5s sIContentcBstZRS(N(s__name__s __module__(((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pysIContent9ssContentcBstZeeƒRS(N(s__name__s __module__s implementssIContent(((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pysContent;ssCompcBs0tZeZeeƒd„ZdZd„ZRS(NcGsdS(N((sselfsargs((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pys__init__BsicCsdS(N((((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pysfGs( s__name__s __module__sIContents __used_for__s implementssIApps__init__sasf(((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pysComp>s   (s__doc__swarningsszope.interfaces Interfaces Attributes implementsszope.componentsbbbstestss__warn__swarnsDeprecationWarningsobjectsRecordingAdaptersIAppsIContentsContentsCompscomp( s implementssRecordingAdapterswarningss AttributesIContentsbbbsIAppsContentsComps Interfacescomp((sAbuild/bdist.linux-i686/egg/zope/component/bbb/tests/components.pys?s     PK·“„4çßÞ"Þ"0zope/component/bbb/tests/test_utilityservice.pyc;ò â•2Dc@sWdZdklZlZlZdklZlZlZl Z l Z lZl Z dk l Z dklZdklZlZdklZdefd„ƒYZd efd „ƒYZd efd „ƒYZd efd„ƒYZdefd„ƒYZeƒZeƒZeƒZdeefd„ƒYZd„Ze djoeddƒndS(sYUtility service tests $Id: test_utilityservice.py 29143 2005-02-14 22:43:16Z srichter $ (sTestCasesmains makeSuite(s getUtilitysgetUtilitiesFors getServices queryUtilitys getServicessgetUtilitiesForsgetGlobalServices(sComponentLookupError(s Utilities(s Interfaces implements(sCleanUps IDummyUtilitycBstZRS(N(s__name__s __module__(((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pys IDummyUtilityssIDummerUtilitycBstZRS(N(s__name__s __module__(((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pysIDummerUtilityss DummyUtilitycBstZdZeeƒRS(Ns DummyUtility(s__name__s __module__s implementss IDummyUtility(((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pys DummyUtility"ss DummyUtility2cBs!tZeeƒdZd„ZRS(Ns DummyUtility2cCsdSdS(Ni((sself((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pys__len__*s(s__name__s __module__s implementss IDummyUtilitys__len__(((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pys DummyUtility2&s s DummerUtilitycBstZdZeeƒRS(Ns DummerUtility(s__name__s __module__s implementssIDummerUtility(((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pys DummerUtility-ssTestcBsYtZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d „Z RS( NcCs…dkl}t|_t|i_ti|ƒtƒ}|i }|i }dk l }|d|ƒdkl}|d|ƒƒdS(N(sbbb(sIUtilityServices Utilities(sGlobalUtilityService(szope.componentsbbbsFalses__warn__sservicesCleanUpssetUpsselfsgetGlobalServicesssms defineServicesprovideServiceszope.component.interfacessIUtilityServiceszope.component.utilitysGlobalUtilityService(sselfsGlobalUtilityServicesbbbsIUtilityServicessms defineServicesprovideService((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pyssetUp8s          cCs9tt|ƒiƒdkl}t|_t|i_dS(N(sbbb( ssupersTestsselfscleanUpszope.componentsbbbsTrues__warn__sservice(sselfsbbb((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pyscleanUpFs  cCsIttƒ}|itttƒ|itt ƒ|i ttƒt ƒdS(N( s getServices Utilitiessussselfs assertRaisessComponentLookupErrors getUtilitys IDummyUtilitysprovideUtilitys dummyUtilitys assertEqual(sselfsus((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pystestGetUtilityLs cCshttƒ}|ittƒtƒ|ittd|ƒ|ƒ|itt ƒ|ittƒt ƒdS(Nsdefault( s getServices Utilitiessussselfs assertEquals queryUtilitys IDummyUtilitysNonesprovideUtilitys dummyUtility(sselfsus((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pystestQueryUtilitySs  cCsmttƒ}|ittƒ|itt tƒƒdtfgƒ|it|i tƒƒdtfgƒdS(Ns( s getServices UtilitiessussprovideUtilitys IDummyUtilitys dummyUtilitysselfs assertEqualslistsgetUtilitiesFor(sselfsus((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pystestgetUtilitiesForZs  cCsBttƒ}|ittƒ|itt |i ƒƒdgƒdS(Ns<UtilityRegistration('IDummyUtility', '', 'DummyUtility', '')( s getServices UtilitiessussprovideUtilitys IDummyUtilitys dummyUtilitysselfs assertEqualsmapsstrs registrations(sselfsus((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pystestregistrationsbs cCs’ttƒ}|itttƒ|itt ƒ|i ttƒt ƒ|it t ƒ|i tt ƒt ƒ|i ttƒt ƒ|itttdƒ|itt dƒ|i ttƒt dƒ|it t dƒ|i tt ƒt dƒ|i ttƒt dƒt |itƒƒ}|iƒ|i |dt fdt fgƒt |it ƒƒ}|iƒ|i |dt fdt fgƒ|SdS(Nsbobs(s getServices Utilitiessussselfs assertRaisessComponentLookupErrors getUtilitys IDummyUtilitysprovideUtilitys dummyUtilitys assertEqualsIDummerUtilitys dummerUtilityslistsgetUtilitiesForsutsssort(sselfsutssus((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pys testOverridesis(  " "cCs”|iƒ}t|itƒƒ}|i|ttgƒt|it ƒƒ}|i t ƒ|i t ƒ|i tƒ|i tƒ|i|gƒdS(N( sselfs testOverridessusslistsgetAllUtilitiesRegisteredForsIDummerUtilitysutss assertEquals dummerUtilitys IDummyUtilitysremoves dummyUtility(sselfsussuts((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pys!test_getAllUtilitiesRegisteredForŽs     cCsEttƒ}dtfd„ƒY}|it|i|ƒƒgƒdS(NsIFoocBstZRS(N(s__name__s __module__(((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pysIFoo s( s getServices Utilitiessuss InterfacesIFoosselfs assertEqualslistsgetAllUtilitiesRegisteredFor(sselfsIFoosus((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pys'test_getAllUtilitiesRegisteredFor_emptyžs ( s__name__s __module__ssetUpscleanUpstestGetUtilitystestQueryUtilitystestgetUtilitiesForstestregistrationss testOverridess!test_getAllUtilitiesRegisteredFors'test_getAllUtilitiesRegisteredFor_empty(((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pysTest6s       % cCsttƒSdS(N(s makeSuitesTest(((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pys test_suite¥ss__main__s defaultTests test_suiteN(!s__doc__sunittestsTestCasesmains makeSuiteszope.components getUtilitysgetUtilitiesFors getServices queryUtilitys getServicessgetGlobalServicesszope.component.exceptionssComponentLookupErrorszope.component.servicenamess Utilitiesszope.interfaces Interfaces implementsszope.testing.cleanupsCleanUps IDummyUtilitysIDummerUtilitysobjects DummyUtilitys DummyUtility2s DummerUtilitys dummyUtilitys dummerUtilitys dummyUtility2sTests test_suites__name__(sCleanUps DummyUtilitysComponentLookupErrors getUtilitysIDummerUtilitys dummerUtilitys test_suitesTests DummerUtilitys IDummyUtilitys UtilitiessTestCases DummyUtility2s Interfacesmains queryUtilitys makeSuitesgetGlobalServicess getServicesgetUtilitiesFors implementss dummyUtilitys dummyUtility2s getServices((sJbuild/bdist.linux-i686/egg/zope/component/bbb/tests/test_utilityservice.pys?s$1      o  PKPs„4£Iõ°÷÷$zope/component/tests/test_adapter.py############################################################################## # # Copyright (c) 2003 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Global Adapter Service Tests $Id: test_adapter.py 25177 2004-06-02 13:17:31Z jim $ """ import unittest from doctest import DocTestSuite from zope.component.adapter import GlobalAdapterService class GlobalAdapterServiceTests(unittest.TestCase): def test_pickling(self): from zope.component.tests.test_service import testServiceManager from zope.component.interfaces import IAdapterService testServiceManager.defineService('Adapters', IAdapterService) adapters = GlobalAdapterService() testServiceManager.provideService('Adapters', adapters) import pickle as = pickle.loads(pickle.dumps(adapters)) self.assert_(as is adapters) testServiceManager._clear() def test_suite(): suite = unittest.makeSuite(GlobalAdapterServiceTests) suite.addTest(DocTestSuite('zope.component.adapter')) return suite PKPs„4¨Â6å¶¶zope/component/tests/request.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Request for tests $Id: request.py 27081 2004-08-12 19:56:31Z srichter $ """ import zope.interface class Request(object): def __init__(self, type, skin=''): self._skin = skin zope.interface.directlyProvides(self, type) def getPresentationSkin(self): return self._skin PKPs„4ÊQÓšRšR zope/component/tests/test_api.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """API tests $Id: test_api.py 27165 2004-08-17 11:20:31Z hdima $ """ import unittest from zope import component from zope.component import servicenames from zope.component import getAdapter, queryAdapter from zope.component import getAdapterInContext, queryAdapterInContext from zope.component import getService from zope.component import getUtility, queryUtility from zope.component import getDefaultViewName from zope.component import queryMultiAdapter from zope.component.service import serviceManager from zope.component.exceptions import ComponentLookupError from zope.component.servicenames import Adapters from zope.component.tests.placelesssetup import PlacelessSetup from zope.component.tests.request import Request from zope.component.interfaces import IComponentArchitecture, IServiceService from zope.interface import Interface, implements from zope.interface.verify import verifyObject class I1(Interface): pass class I2(Interface): pass class I3(Interface): pass class Comp(object): implements(I2) def __init__(self, context, request=None): self.context = context class Comp2(object): implements(I3) def __init__(self, context, request=None): self.context = context comp = Comp(1) class Ob(object): implements(I1) def __conform__(self, i): if i is IServiceService: return serviceManager ob = Ob() class Conforming(Ob): def __conform__(self, i): if i is I3: return Comp(self) else: return Ob.__conform__(self, i) class StubServiceService(object): implements(IServiceService) # This is a lie. def __init__(self): self.services = {} def setService(self, name, service): self.services[name] = service def getService(self, name): try: return self.services[name] except KeyError: raise ComponentLookupError, name class ConformsToIServiceService(object): def __init__(self, serviceservice): self.serviceservice = serviceservice def __conform__(self, interface): if interface is IServiceService: return self.serviceservice class Test(PlacelessSetup, unittest.TestCase): def testInterfaces(self): import zope.component self.failUnless(verifyObject(IComponentArchitecture, zope.component)) def test_getGlobalServices(self): from zope.component import getGlobalServices from zope.component.service import IGlobalServiceManager gsm = getGlobalServices() self.assert_(IGlobalServiceManager.providedBy(gsm)) self.assert_(getGlobalServices() is gsm) def test_getServices(self): from zope.component import getServices # We don't know anything about the default service manager, except # that it is an IServiceService. self.assert_(IServiceService.providedBy(getServices())) # Calling getServices with no args is equivalent to calling it # with a context of None. self.assert_(getServices() is getServices(None)) # If the context passed to getServices is not None, it is # adapted to IServiceService and this adapter returned. # So, we create a context that can be adapted to IServiceService # using the __conform__ API. servicemanager = StubServiceService() context = ConformsToIServiceService(servicemanager) self.assert_(getServices(context) is servicemanager) # Using a context that is not adaptable to IServiceService should # fail. self.assertRaises(ComponentLookupError, getServices, object()) def test_getService(self): from zope.component import getService, getServices # Getting the adapter service with no context given is the same # as getting the adapter service from the no-context service manager. self.assert_(getService(Adapters) is getServices().getService(Adapters)) # And, a context of 'None' is the same as not providing a context. self.assert_(getService(Adapters, None) is getService(Adapters)) # If the context is adaptable to IServiceService then we use that # adapter. servicemanager = StubServiceService() adapterservice = object() servicemanager.setService(Adapters, adapterservice) context = ConformsToIServiceService(servicemanager) self.assert_(getService(Adapters, context) is adapterservice) # Using a context that is not adaptable to IServiceService should # fail. self.assertRaises(ComponentLookupError, getService, Adapters, object()) def testAdapterInContext(self): class I1(Interface): pass class I2(Interface): pass class C(object): implements(I1) def __conform__(self, iface, default=None): if iface == I2: return 42 ob = C() servicemanager = StubServiceService() context = ConformsToIServiceService(servicemanager) class I3(Interface): pass class StubAdapterService(object): def queryAdapter(self, ob, iface, name, default=None): if iface is I3: return 43 return default servicemanager.services[Adapters] = StubAdapterService() # If an object implements the interface you want to adapt to, # getAdapterInContext should simply return the object. self.assertEquals(getAdapterInContext(ob, I1, context), ob) self.assertEquals(queryAdapterInContext(ob, I1, context), ob) # If an object conforms to the interface you want to adapt to, # getAdapterInContext should simply return the conformed object. self.assertEquals(getAdapterInContext(ob, I2, context), 42) self.assertEquals(queryAdapterInContext(ob, I2, context), 42) class I4(Interface): pass # If an adapter isn't registered for the given object and interface, # and you provide no default, raise ComponentLookupError... self.assertRaises(ComponentLookupError, getAdapterInContext, ob, I4, context) # ...otherwise, you get the default self.assertEquals(queryAdapterInContext(ob, I4, context, 44), 44) # If you ask for an adapter for which something's registered # you get the registered adapter self.assertEquals(getAdapterInContext(ob, I3, context), 43) self.assertEquals(queryAdapterInContext(ob, I3, context), 43) def testAdapter(self): # If an adapter isn't registered for the given object and interface, # and you provide no default, raise ComponentLookupError... self.assertRaises(ComponentLookupError, getAdapter, ob, I2, '') # ...otherwise, you get the default self.assertEquals(queryAdapter(ob, I2, '', Test), Test) getService(Adapters).register([I1], I2, '', Comp) c = getAdapter(ob, I2, '') self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) def testInterfaceCall(self): getService(Adapters).register([I1], I2, '', Comp) c = I2(ob) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) def testNamedAdapter(self): self.testAdapter() # If an adapter isn't registered for the given object and interface, # and you provide no default, raise ComponentLookupError... self.assertRaises(ComponentLookupError, getAdapter, ob, I2, 'test') # ...otherwise, you get the default self.assertEquals(queryAdapter(ob, I2, 'test', Test), Test) class Comp2(Comp): pass getService(Adapters).register([I1], I2, 'test', Comp2) c = getAdapter(ob, I2, 'test') self.assertEquals(c.__class__, Comp2) self.assertEquals(c.context, ob) def testQueryMultiAdapter(self): # Adapting a combination of 2 objects to an interface class DoubleAdapter(object): implements(I3) def __init__(self, first, second): self.first = first self.second = second class Ob2(object): implements(I2) ob2 = Ob2() context = None getService(Adapters, context).register([I1, I2], I3, '', DoubleAdapter) c = queryMultiAdapter((ob, ob2), I3, context=context) self.assertEquals(c.__class__, DoubleAdapter) self.assertEquals(c.first, ob) self.assertEquals(c.second, ob2) def testAdapterForInterfaceNone(self): # providing an adapter for None says that your adapter can # adapt anything to I2. getService(Adapters).register([None], I2, '', Comp) c = I2(ob) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) def testUtility(self): self.assertRaises(ComponentLookupError, getUtility, I1, context=ob) self.assertRaises(ComponentLookupError, getUtility, I2, context=ob) self.assertEquals(queryUtility(I2, default=Test, context=ob), Test) getService('Utilities').provideUtility(I2, comp) self.assertEquals(id(getUtility(I2, context=ob)), id(comp)) def testNamedUtility(self): from zope.component import getUtility, queryUtility from zope.component import getService from zope.component.exceptions import ComponentLookupError self.testUtility() self.assertRaises(ComponentLookupError, getUtility, I1, 'test', context=ob) self.assertRaises(ComponentLookupError, getUtility, I2, 'test', context=ob) self.assertEquals(queryUtility(I2, 'test', Test, context=ob), Test) getService('Utilities').provideUtility(I2, comp, 'test') self.assertEquals(id(getUtility(I2, 'test', ob)), id(comp)) def test_getAllUtilitiesRegisteredFor(self): class I21(I2): pass class Comp21(Comp): implements(I21) compbob = Comp('bob') comp21 = Comp21('21') comp21bob = Comp21('21bob') getService('Utilities').provideUtility(I2, comp) getService('Utilities').provideUtility(I21, comp21) getService('Utilities').provideUtility(I2, compbob, 'bob') getService('Utilities').provideUtility(I21, comp21bob, 'bob') comps = [comp, compbob, comp21, comp21bob] comps.sort() uts = list(component.getUtilitiesFor(I2)) uts.sort() self.assertEqual(uts, [('', comp), ('bob', compbob)]) uts = list(component.getAllUtilitiesRegisteredFor(I2)) uts.sort() self.assertEqual(uts, comps) def testView(self): from zope.component import getView, queryView, getService from zope.component.exceptions import ComponentLookupError self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I1)) self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I2)) self.assertEquals(queryView(ob, 'foo', Request(I2), Test), Test) getService(servicenames.Presentation).provideView( I1, 'foo', I2, Comp) c = getView(ob, 'foo', Request(I2)) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) self.assertRaises(ComponentLookupError, getView, ob, 'foo2', Request(I1)) self.assertRaises(ComponentLookupError, getView, ob, 'foo2', Request(I2)) self.assertEquals(queryView(ob, 'foo2', Request(I2), Test), Test) self.assertEquals(queryView(ob, 'foo2', Request(I1), None), None) def testView_w_provided(self): from zope.component import getView, queryView, getService from zope.component.exceptions import ComponentLookupError self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I1), providing=I3) self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I2), providing=I3) self.assertEquals( queryView(ob, 'foo', Request(I2), Test, providing=I3), Test) getService(servicenames.Presentation).provideView( I1, 'foo', I2, Comp) self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I1), providing=I3) self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I2), providing=I3) self.assertEquals( queryView(ob, 'foo', Request(I2), Test, providing=I3), Test) getService(servicenames.Presentation).provideView( I1, 'foo', I2, Comp, providing=I3) c = getView(ob, 'foo', Request(I2), providing=I3) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) def testMultiView(self): from zope.component import queryMultiView, getService from zope.component.exceptions import ComponentLookupError class Ob2(object): implements(I2) ob2 = Ob2() class IRequest(Interface): pass request = Request(IRequest) class MV(object): implements(I3) def __init__(self, context, other, request): self.context, self.other, self.request = context, other, request self.assertEquals( queryMultiView((ob, ob2), request, I3, 'foo', 42), 42) getService(servicenames.Presentation).provideAdapter( IRequest, MV, 'foo', (I1, I2), I3) view = queryMultiView((ob, ob2), request, I3, 'foo') self.assertEquals(view.__class__, MV) self.assertEquals(view.context, ob) self.assertEquals(view.other, ob2) self.assertEquals(view.request, request) def test_viewProvidingFunctions(self): # Confirm that a call to getViewProving/queryViewProviding simply # passes its arguments through to getView/queryView - here we hack # getView and queryView to inspect the args passed through. import zope.component # hack zope.component.getView def getView(object, name, request, context, providing): self.args = [object, name, request, context, providing] savedGetView = zope.component.getView zope.component.getView = getView # confirm pass through of args to getView by way of getViewProviding zope.component.getViewProviding( object='object', providing='providing', request='request', context='context') self.assertEquals(self.args, ['object', '', 'request', 'providing', 'context']) # hack zope.component.queryView def queryView(object, name, request, default, providing, context): self.args = [object, name, request, default, providing, context] savedQueryView = zope.component.queryView zope.component.queryView = queryView # confirm pass through of args to queryView by way of queryViewProviding zope.component.queryViewProviding( object='object', providing='providing', request='request', default='default', context='context') self.assertEquals(self.args, ['object', '', 'request', 'default', 'providing', 'context']) # restore zope.component zope.component.getView = savedGetView zope.component.queryView = savedQueryView def testResource(self): from zope.component import getResource, queryResource, getService from zope.component.exceptions import ComponentLookupError r1 = Request(I1) r2 = Request(I2) self.assertRaises(ComponentLookupError, getResource, 'foo', r1) self.assertRaises(ComponentLookupError, getResource, 'foo', r2) self.assertEquals(queryResource('foo', r2, Test), Test) getService(servicenames.Presentation).provideResource( 'foo', I2, Comp) c = getResource('foo', r2) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, r2) self.assertRaises(ComponentLookupError, getResource, 'foo2', r1, ob) self.assertRaises(ComponentLookupError, getResource, 'foo2', r2) self.assertEquals(queryResource('foo2', r2, Test, ob), Test) self.assertEquals(queryResource('foo2', r1, None), None) def testResource_w_provided(self): from zope.component import getResource, queryResource, getService from zope.component.exceptions import ComponentLookupError r1 = Request(I1) r2 = Request(I2) self.assertRaises(ComponentLookupError, getResource, 'foo', r1, providing=I3) self.assertRaises(ComponentLookupError, getResource, 'foo', r2, providing=I3) self.assertEquals(queryResource('foo', r2, Test, providing=I3), Test) getService(servicenames.Presentation).provideResource( 'foo', I2, Comp) self.assertRaises(ComponentLookupError, getResource, 'foo', r1, providing=I3) self.assertRaises(ComponentLookupError, getResource, 'foo', r2, providing=I3) self.assertEquals(queryResource('foo', r2, Test, providing=I3), Test) getService(servicenames.Presentation).provideResource( 'foo', I2, Comp, providing=I3) c = getResource('foo', r2, providing=I3) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, r2) def testViewWithContextArgument(self): # Basically the same as testView, but exercising the context # argument. As this only tests global views, the context # argument is pretty much a no-operation. from zope.component import getView, queryView, getService from zope.component.exceptions import ComponentLookupError self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I1), context=ob) self.assertRaises(ComponentLookupError, getView, ob, 'foo', Request(I2), context=ob) self.assertEquals(queryView(ob, 'foo', Request(I2), Test, context=ob), Test) getService(servicenames.Presentation).provideView( I1, 'foo', I2, Comp) c = getView(ob, 'foo', Request(I2), context=ob) self.assertEquals(c.__class__, Comp) self.assertEquals(c.context, ob) self.assertRaises(ComponentLookupError, getView, ob, 'foo2', Request(I1), context=ob) self.assertRaises(ComponentLookupError, getView, ob, 'foo2', Request(I2), context=ob) self.assertEquals(queryView(ob, 'foo2', Request(I2), Test, context=ob), Test) self.assertEquals(queryView(ob, 'foo2', Request(I1), None, context=ob), None) def testDefaultViewName(self): from zope.component import getService from zope.exceptions import NotFoundError viewService = getService(servicenames.Presentation) self.assertRaises(NotFoundError, getDefaultViewName, ob, Request(I1)) viewService.setDefaultViewName(I1, I2, 'sample_name') self.assertEquals(getDefaultViewName(ob, Request(I2)), 'sample_name') self.assertRaises(NotFoundError, getDefaultViewName, ob, Request(I1)) class TestNoSetup(unittest.TestCase): def testNotBrokenWhenNoService(self): # Both of those things emit DeprecationWarnings. self.assertRaises(TypeError, I2, ob) self.assertEquals(I2(ob, 42), 42) pass def test_suite(): return unittest.TestSuite(( unittest.makeSuite(Test), unittest.makeSuite(TestNoSetup), )) if __name__ == "__main__": unittest.TextTestRunner().run(test_suite()) PKPs„4XleÙ== zope/component/tests/__init__.py# # This file is necessary to make this directory a package. PKPs„4¢WÄåÏÏ)zope/component/tests/test_presentation.py############################################################################## # # Copyright (c) 2003 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Presentation Serivce tests $Id: test_presentation.py 27309 2004-08-27 21:01:06Z jim $ """ import unittest from doctest import DocTestSuite from zope.component.presentation import GlobalPresentationService import zope.interface class IRequest(zope.interface.Interface): "Demonstration request type" class Request(object): zope.interface.implements(IRequest) def getPresentationSkin(self): return getattr(self, 'skin', None) class IContact(zope.interface.Interface): "Demonstration content type" class Contact(object): zope.interface.implements(IContact) class MyView(object): def __init__(self, context, request): self.context, self.request = context, request def test_view_lookup_fails_w_wrong_skin(): """ >>> s = GlobalPresentationService() >>> s.defineLayer('custom') >>> s.defineSkin('custom', ['custom', 'default']) >>> request = Request() >>> s.provideAdapter(IRequest, MyView, contexts=[IContact], name='foo', ... layer='custom') >>> c = Contact() >>> s.queryView(c, 'foo', request) We don't get anothing because we registered in the custom layer, but looked up in the default skin which has only the default layer. """ class ICompany(zope.interface.Interface): "Demonstration content type" class Company(object): zope.interface.implements(ICompany) class ContactInCompanyView: def __init__(self, contact, company, request): self.contact, self.company, self.request = contact, company, request class IFamily(zope.interface.Interface): "Demonstration content type" class Family(object): zope.interface.implements(IFamily) class ContactInFamilyView(object): def __init__(self, contact, family, request): self.contact, self.family, self.request = contact, family, request def test_multi_views(): """A multi-view is a view on multiple objects >>> s = GlobalPresentationService() >>> request = Request() >>> s.provideAdapter(IRequest, ContactInCompanyView, ... contexts=[IContact, ICompany], name='foo', ... info='test 1') >>> bob = Contact() >>> acme = Company() >>> v = s.queryMultiView((bob, acme), request, name='foo') >>> v.__class__.__name__ 'ContactInCompanyView' >>> v.contact is bob True >>> v.company is acme True >>> v.request is request True >>> s.provideAdapter(IRequest, ContactInFamilyView, ... contexts=[IContact, IFamily], name='foo', ... info='test 2') >>> smith = Family() >>> v = s.queryMultiView((bob, smith), request, name='foo') >>> v.__class__.__name__ 'ContactInFamilyView' >>> v.contact is bob True >>> v.family is smith True >>> v.request is request True Provided adapters (views and resources) are recorded as registrations: >>> registrations = map(str, s.registrations()) >>> registrations.sort() >>> for r in registrations: ... print r zope.component.presentation.PresentationRegistration(""" \ """default, ('IContact', 'ICompany', 'IRequest'), """ \ """'Interface', 'foo', 'ContactInCompanyView', 'test 1') zope.component.presentation.PresentationRegistration(""" \ """default, ('IContact', 'IFamily', 'IRequest'), """ \ """'Interface', 'foo', 'ContactInFamilyView', 'test 2') """ def test_provideView(): """ The provideView is a simpler and backward-compatible interface to provideAdapter. >>> s = GlobalPresentationService() >>> request = Request() >>> s.provideView(IContact, 'foo', IRequest, MyView) >>> c = Contact() >>> v = s.queryView(c, 'foo', request) >>> v.__class__.__name__ 'MyView' >>> v.request is request True >>> v.context is c True We can specify a layer and we can provide a view factory directly: >>> s.defineLayer('custom') >>> s.defineSkin('custom', ['custom', 'default']) >>> s.provideView(IContact, 'index.html', IRequest, MyView, layer='custom') >>> c = Contact() >>> request.skin = 'custom' >>> v = s.queryView(c, 'foo', request) >>> v.__class__.__name__ 'MyView' >>> v.request is request True >>> v.context is c True """ def test_default_view_names(): """ >>> s = GlobalPresentationService() >>> request = Request() >>> c = Contact() We haven't set a default view name: >>> s.queryDefaultViewName(c, request) Let's set a "default default": >>> s.setDefaultViewName(None, IRequest, 'index.html') And then we'll get it is we look something up: >>> s.queryDefaultViewName(c, request) 'index.html' Now we'll set a name for a specific interface. We'll also specify a specifioc layer: >>> s.defineLayer('custom') >>> s.defineSkin('custom', ['custom', 'default']) >>> s.setDefaultViewName(IContact, IRequest, 'hello.html', layer='custom') If we don't specify the custum skin, we'll still get the default: >>> s.queryDefaultViewName(c, request) 'index.html' But if we specify a custom skin, we'll get the custom value for a contact: >>> request.skin = 'custom' >>> s.queryDefaultViewName(c, request) 'hello.html' But not for something else: >>> s.queryDefaultViewName(42, request) 'index.html' """ def test_default_skin_affects_lookup(): """ >>> s = GlobalPresentationService() >>> s.defineLayer('custom') >>> s.defineSkin('custom', ['custom', 'default']) >>> request = Request() >>> class MyResource(object): ... def __init__(self, request): ... self.request = request >>> s.provideAdapter(IRequest, MyResource, name='foo', layer='custom') >>> s.queryResource('foo', request) >>> s.provideAdapter(IRequest, MyView, contexts=[IContact], name='foo', ... layer='custom') >>> c = Contact() >>> v = s.queryView(c, 'foo', request) >>> s.setDefaultSkin('custom') >>> r = s.queryResource('foo', request) >>> r.__class__.__name__ 'MyResource' >>> r.request is request True >>> v = s.queryView(c, 'foo', request) >>> v.__class__.__name__ 'MyView' >>> v.request is request True >>> v.context is c True """ def test_pickling(): """ >>> from zope.component.tests.test_service import testServiceManager >>> from zope.component.interfaces import IPresentationService >>> testServiceManager.defineService('Presentation', IPresentationService) >>> presentation = GlobalPresentationService() >>> testServiceManager.provideService('Presentation', presentation) >>> import pickle >>> s = pickle.loads(pickle.dumps(presentation)) >>> s is presentation True >>> layer = pickle.loads(pickle.dumps(presentation.queryLayer('default'))) >>> (layer is presentation.queryLayer('default')) and (layer is not None) True >>> testServiceManager._clear() """ def test_suite(): return unittest.TestSuite(( DocTestSuite('zope.component.presentation'), DocTestSuite(), )) if __name__ == '__main__': unittest.main() PKPs„4¶±ÀÑùù&zope/component/tests/placelesssetup.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Placeless Test Setup $Id: placelesssetup.py 27081 2004-08-12 19:56:31Z srichter $ """ from zope.testing.cleanup import CleanUp from zope.component import getGlobalServices from zope.component.servicenames import Adapters, Utilities, Presentation # A mix-in class inheriting from CleanUp that also connects the CA services class PlacelessSetup(CleanUp): def setUp(self): CleanUp.setUp(self) sm = getGlobalServices() defineService = sm.defineService provideService = sm.provideService # utility service from zope.component.interfaces import IUtilityService defineService(Utilities, IUtilityService) from zope.component.utility import GlobalUtilityService provideService(Utilities, GlobalUtilityService()) # adapter service from zope.component.interfaces import IAdapterService defineService(Adapters, IAdapterService) from zope.component.adapter import GlobalAdapterService provideService(Adapters, GlobalAdapterService()) # presentation service from zope.component.interfaces import IPresentationService defineService(Presentation, IPresentationService) from zope.component.presentation import GlobalPresentationService provideService(Presentation, GlobalPresentationService()) def tearDown(self): CleanUp.tearDown(self) PKPs„4}”ý77$zope/component/tests/test_service.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Test ServiceService component $Id: test_service.py 27082 2004-08-12 20:03:58Z srichter $ """ import unittest import pickle from zope.interface import Interface, implements from zope.exceptions import DuplicationError from zope.testing.cleanup import CleanUp from zope.component import getServiceDefinitions, getService, getGlobalServices from zope.component.service import UndefinedService, InvalidService from zope.component.service import GlobalServiceManager, GlobalService from zope.component.exceptions import ComponentLookupError from zope.component.interfaces import IServiceService class IOne(Interface): pass class ITwo(Interface): pass class ServiceOne(GlobalService): implements(IOne) class ServiceTwo(GlobalService): implements(ITwo) class Test(CleanUp, unittest.TestCase): def testNormal(self): ss = getGlobalServices() ss.defineService('one', IOne) c = ServiceOne() ss.provideService('one', c) self.assertEqual(id(getService('one')), id(c)) def testFailedLookup(self): self.assertRaises(ComponentLookupError, getService, 'two') def testDup(self): getGlobalServices().defineService('one', IOne) self.assertRaises(DuplicationError, getGlobalServices().defineService, 'one', ITwo) c = ServiceOne() getGlobalServices().provideService('one', c) c2 = ServiceOne() self.assertRaises(DuplicationError, getGlobalServices().provideService, 'one', c2) self.assertEqual(id(getService('one')), id(c)) def testUndefined(self): c = ServiceOne() self.assertRaises(UndefinedService, getGlobalServices().provideService, 'one', c) def testInvalid(self): getGlobalServices().defineService('one', IOne) getGlobalServices().defineService('two', ITwo) c = ServiceOne() self.assertRaises(InvalidService, getGlobalServices().provideService, 'two', c) def testGetService(self): # Testing looking up a service from a service manager container that # doesn't have a service manager. getGlobalServices().defineService('one', IOne) c = ServiceOne() getGlobalServices().provideService('one', c) self.assertEqual(id(getService('one')), id(c)) def testGetServiceDefinitions(self): # test that the service definitions are the ones we added sm = getGlobalServices() sm.defineService('one', IOne) c = ServiceOne() sm.provideService('one', c) sm.defineService('two', ITwo) d = ServiceTwo() sm.provideService('two', d) defs = getServiceDefinitions() defs.sort() self.assertEqual(defs, [('Services', IServiceService), ('one', IOne), ('two', ITwo)]) def testPickling(self): self.assertEqual(testServiceManager.__reduce__(), 'testServiceManager') sm = pickle.loads(pickle.dumps(testServiceManager)) self.assert_(sm is testServiceManager) s2 = ServiceTwo() sm.defineService('2', ITwo) sm.provideService('2', s2) self.assert_(s2.__parent__ is sm) self.assertEqual(s2.__name__, '2') s = pickle.loads(pickle.dumps(s2)) self.assert_(s is s2) testServiceManager._clear() testServiceManager = GlobalServiceManager('testServiceManager', __name__) def test_suite(): loader = unittest.TestLoader() return loader.loadTestsFromTestCase(Test) if __name__ == '__main__': unittest.TextTestRunner().run(test_suite()) PKPs„4y„š´"zope/component/tests/components.py############################################################################## # # Copyright (c) 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Components for testing $Id: components.py 27079 2004-08-12 19:45:55Z srichter $ """ from zope.interface import Interface, Attribute, implements class RecordingAdapter(object): def __init__(self): self.record = [] def __call__(self, context): # Note that this sets the context rather than appending to the record # so as not to assume things about adapters being cached, if this # happens in the future. self.context = context return self def check(self, *args): record = self.record if len(args) != len(record): raise AssertionError('wrong number of entries in record', args, record) for arg, entry in zip(args, record): if arg != entry: raise AssertionError('record entry does not match', args, record) class IApp(Interface): a = Attribute('test attribute') def f(): "test func" class IContent(Interface): pass class Content(object): implements(IContent) class Comp(object): __used_for__ = IContent implements(IApp) def __init__(self, *args): # Ignore arguments passed to constructor pass a = 1 def f(): pass comp = Comp() PKPs„4eƒ×ÒÒ+zope/component/tests/test_utilityservice.py############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Utility service tests $Id: test_utilityservice.py 27081 2004-08-12 19:56:31Z srichter $ """ from unittest import TestCase, main, makeSuite from zope.component import \ getUtility, getUtilitiesFor, getService, queryUtility, \ getServices, getUtilitiesFor, getGlobalServices from zope.component.exceptions import ComponentLookupError from zope.component.servicenames import Utilities from zope.interface import Interface, implements from zope.testing.cleanup import CleanUp # Base class w registry cleanup class IDummyUtility(Interface): pass class IDummerUtility(IDummyUtility): pass class DummyUtility(object): __name__ = 'DummyUtility' implements(IDummyUtility) class DummyUtility2(object): implements(IDummyUtility) __name__ = 'DummyUtility2' def __len__(self): return 0 class DummerUtility(object): __name__ = 'DummerUtility' implements(IDummerUtility) dummyUtility = DummyUtility() dummerUtility = DummerUtility() dummyUtility2 = DummyUtility2() class Test(TestCase, CleanUp): def setUp(self): CleanUp.setUp(self) sm = getGlobalServices() defineService = sm.defineService provideService = sm.provideService from zope.component.interfaces import IUtilityService defineService('Utilities',IUtilityService) from zope.component.utility import GlobalUtilityService provideService('Utilities', GlobalUtilityService()) def testGetUtility(self): us = getService(Utilities) self.assertRaises( ComponentLookupError, getUtility, IDummyUtility) us.provideUtility(IDummyUtility, dummyUtility) self.assertEqual(getUtility(IDummyUtility), dummyUtility) def testQueryUtility(self): us = getService(Utilities) self.assertEqual(queryUtility(IDummyUtility), None) self.assertEqual(queryUtility(IDummyUtility, default=self), self) us.provideUtility(IDummyUtility, dummyUtility) self.assertEqual(queryUtility(IDummyUtility), dummyUtility) def testgetUtilitiesFor(self): us = getService(Utilities) us.provideUtility(IDummyUtility, dummyUtility) self.assertEqual(list(getUtilitiesFor(IDummyUtility)), [('',dummyUtility)]) self.assertEqual(list(us.getUtilitiesFor(IDummyUtility)), [('',dummyUtility)]) def testregistrations(self): us = getService(Utilities) us.provideUtility(IDummyUtility, dummyUtility) self.assertEqual( map(str, us.registrations()), ["UtilityRegistration('IDummyUtility', '', 'DummyUtility', '')"]) def testOverrides(self): us = getService(Utilities) # fail if nothing registered: self.assertRaises( ComponentLookupError, getUtility, IDummyUtility) # set and retiev dummy us.provideUtility(IDummyUtility, dummyUtility) self.assertEqual(getUtility(IDummyUtility), dummyUtility) # dummer overrides us.provideUtility(IDummerUtility, dummerUtility) self.assertEqual(getUtility(IDummerUtility), dummerUtility) # But not if we ask for dummy self.assertEqual(getUtility(IDummyUtility), dummyUtility) # same for named: self.assertRaises( ComponentLookupError, getUtility, IDummyUtility, 'bob') us.provideUtility(IDummyUtility, dummyUtility, 'bob') self.assertEqual(getUtility(IDummyUtility), dummyUtility, 'bob') us.provideUtility(IDummerUtility, dummerUtility, 'bob') self.assertEqual(getUtility(IDummerUtility), dummerUtility, 'bob') self.assertEqual(getUtility(IDummyUtility), dummyUtility, 'bob') # getUtilitiesFor doesn the right thing: uts = list(us.getUtilitiesFor(IDummyUtility)) uts.sort() self.assertEqual(uts, [('', dummyUtility), ('bob', dummyUtility)]) uts = list(us.getUtilitiesFor(IDummerUtility)) uts.sort() self.assertEqual(uts, [('', dummerUtility), ('bob', dummerUtility)]) return us def test_getAllUtilitiesRegisteredFor(self): us = self.testOverrides() # getAllUtilitiesRegisteredFor includes overridden uts = list(us.getAllUtilitiesRegisteredFor(IDummerUtility)) self.assertEqual(uts, [dummerUtility, dummerUtility]) uts = list(us.getAllUtilitiesRegisteredFor(IDummyUtility)) uts.remove(dummyUtility) uts.remove(dummyUtility) uts.remove(dummerUtility) uts.remove(dummerUtility) self.assertEqual(uts, []) def test_getAllUtilitiesRegisteredFor_empty(self): us = getService(Utilities) class IFoo(Interface): pass self.assertEqual(list(us.getAllUtilitiesRegisteredFor(IFoo)), []) def test_suite(): return makeSuite(Test) if __name__=='__main__': main(defaultTest='test_suite') PKPs„4­´ŽüÇÇ$zope/component/tests/test_factory.py############################################################################## # # Copyright (c) 2004 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Factory-related Tests $Id: test_factory.py 27052 2004-08-12 15:45:44Z srichter $ """ import unittest from zope.interface import Interface, implements from zope.interface.interfaces import IDeclaration from zope.component import createObject, getFactoryInterfaces, getFactoriesFor from zope.component import getService, servicenames from zope.component.interfaces import IFactory from zope.component.factory import Factory from placelesssetup import PlacelessSetup class IFunction(Interface): pass class IKlass(Interface): pass class Klass(object): implements(IKlass) def __init__(self, *args, **kw): self.args = args self.kw = kw class TestFactory(unittest.TestCase): def setUp(self): self._factory = Factory(Klass, 'Klass', 'Klassier') self._factory2 = Factory(lambda x: x, 'Func', 'Function') self._factory3 = Factory(lambda x: x, 'Func', 'Function', (IFunction,)) def testCall(self): kl = self._factory(3, foo=4) self.assert_(isinstance(kl, Klass)) self.assertEqual(kl.args, (3, )) self.assertEqual(kl.kw, {'foo': 4}) self.assertEqual(self._factory2(3), 3) self.assertEqual(self._factory3(3), 3) def testTitleDescription(self): self.assertEqual(self._factory.title, 'Klass') self.assertEqual(self._factory.description, 'Klassier') self.assertEqual(self._factory2.title, 'Func') self.assertEqual(self._factory2.description, 'Function') self.assertEqual(self._factory3.title, 'Func') self.assertEqual(self._factory3.description, 'Function') def testGetInterfaces(self): implemented = self._factory.getInterfaces() self.assert_(implemented.isOrExtends(IKlass)) self.assertEqual(list(implemented), [IKlass]) self.assertEqual(implemented.__name__, 'zope.component.tests.test_factory.Klass') implemented2 = self._factory2.getInterfaces() self.assertEqual(list(implemented2), []) self.assertEqual(implemented2.__name__, '') implemented3 = self._factory3.getInterfaces() self.assertEqual(list(implemented3), [IFunction]) self.assertEqual(implemented3.__name__, '') class TestFactoryZAPIFunctions(PlacelessSetup, unittest.TestCase): def setUp(self): super(TestFactoryZAPIFunctions, self).setUp() self.factory = Factory(Klass, 'Klass', 'Klassier') utilityService = getService(servicenames.Utilities) utilityService.provideUtility(IFactory, self.factory, 'klass') def testCreateObject(self): kl = createObject(None, 'klass', 3, foo=4) self.assert_(isinstance(kl, Klass)) self.assertEqual(kl.args, (3, )) self.assertEqual(kl.kw, {'foo': 4}) def testGetFactoryInterfaces(self): implemented = getFactoryInterfaces('klass') self.assert_(implemented.isOrExtends(IKlass)) self.assertEqual([iface for iface in implemented], [IKlass]) def testGetFactoriesFor(self): self.assertEqual(list(getFactoriesFor(IKlass)), [('klass', self.factory)]) def test_suite(): return unittest.TestSuite(( unittest.makeSuite(TestFactory), unittest.makeSuite(TestFactoryZAPIFunctions) )) if __name__=='__main__': unittest.main(defaultTest='test_suite') PK·“„4)ÇNØoo%zope/component/tests/test_adapter.pyc;ò Xº2Dc@sOdZdkZdklZdklZdeifd„ƒYZd„ZdS(sTGlobal Adapter Service Tests $Id: test_adapter.py 25177 2004-06-02 13:17:31Z jim $ N(s DocTestSuite(sGlobalAdapterServicesGlobalAdapterServiceTestscBstZd„ZRS(NcCs…dkl}dkl}|id|ƒtƒ}|id|ƒdk}|i |i |ƒƒ}|i ||jƒ|iƒdS(N(stestServiceManager(sIAdapterServicesAdapters(s!zope.component.tests.test_servicestestServiceManagerszope.component.interfacessIAdapterServices defineServicesGlobalAdapterServicesadapterssprovideServicespicklesloadssdumpssassselfsassert_s_clear(sselfstestServiceManagerspicklesIAdapterServicesassadapters((s?build/bdist.linux-i686/egg/zope/component/tests/test_adapter.pys test_picklings    (s__name__s __module__s test_pickling(((s?build/bdist.linux-i686/egg/zope/component/tests/test_adapter.pysGlobalAdapterServiceTestsscCs*titƒ}|itdƒƒ|SdS(Nszope.component.adapter(sunittests makeSuitesGlobalAdapterServiceTestsssuitesaddTests DocTestSuite(ssuite((s?build/bdist.linux-i686/egg/zope/component/tests/test_adapter.pys test_suite&s( s__doc__sunittestsdoctests DocTestSuiteszope.component.adaptersGlobalAdapterServicesTestCasesGlobalAdapterServiceTestss test_suite(sunittestsGlobalAdapterServices test_suites DocTestSuitesGlobalAdapterServiceTests((s?build/bdist.linux-i686/egg/zope/component/tests/test_adapter.pys?s    PK·“„4|”ˆ zope/component/tests/request.pyc;ò Xº2Dc@s)dZdkZdefd„ƒYZdS(sIRequest for tests $Id: request.py 27081 2004-08-12 19:56:31Z srichter $ NsRequestcBstZdd„Zd„ZRS(NscCs ||_tii||ƒdS(N(sskinsselfs_skinszopes interfacesdirectlyProvidesstype(sselfstypesskin((s:build/bdist.linux-i686/egg/zope/component/tests/request.pys__init__s cCs |iSdS(N(sselfs_skin(sself((s:build/bdist.linux-i686/egg/zope/component/tests/request.pysgetPresentationSkins(s__name__s __module__s__init__sgetPresentationSkin(((s:build/bdist.linux-i686/egg/zope/component/tests/request.pysRequests (s__doc__szope.interfaceszopesobjectsRequest(szopesRequest((s:build/bdist.linux-i686/egg/zope/component/tests/request.pys?s PK·“„4÷(&¯p¯p!zope/component/tests/test_api.pyc;ò Xº2Dc@sAdZdkZdklZdklZdklZlZdklZl Z dkl Z dkl Z l Z dkl Z d klZd klZd klZd klZd klZdklZdklZlZdklZlZdkl Z defd„ƒYZ!defd„ƒYZ"defd„ƒYZ#de$fd„ƒYZ%de$fd„ƒYZ&e%dƒZ'de$fd„ƒYZ(e(ƒZ)de(fd „ƒYZ*d!e$fd"„ƒYZ+d#e$fd$„ƒYZ,d%eei-fd&„ƒYZ.d'ei-fd(„ƒYZ/d)„Z0e1d*joei2ƒi3e0ƒƒndS(+s?API tests $Id: test_api.py 27165 2004-08-17 11:20:31Z hdima $ N(s component(s servicenames(s getAdapters queryAdapter(sgetAdapterInContextsqueryAdapterInContext(s getService(s getUtilitys queryUtility(sgetDefaultViewName(squeryMultiAdapter(sserviceManager(sComponentLookupError(sAdapters(sPlacelessSetup(sRequest(sIComponentArchitecturesIServiceService(s Interfaces implements(s verifyObjectsI1cBstZRS(N(s__name__s __module__(((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pysI1&ssI2cBstZRS(N(s__name__s __module__(((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pysI2(ssI3cBstZRS(N(s__name__s __module__(((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pysI3*ssCompcBstZeeƒed„ZRS(NcCs ||_dS(N(scontextsself(sselfscontextsrequest((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pys__init__/s(s__name__s __module__s implementssI2sNones__init__(((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pysComp-s sComp2cBstZeeƒed„ZRS(NcCs ||_dS(N(scontextsself(sselfscontextsrequest((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pys__init__3s(s__name__s __module__s implementssI3sNones__init__(((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pysComp21s isObcBstZeeƒd„ZRS(NcCs|tjotSndS(N(sisIServiceServicesserviceManager(sselfsi((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pys __conform__9s (s__name__s __module__s implementssI1s __conform__(((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pysOb7s s ConformingcBstZd„ZRS(NcCs/|tjot|ƒSnti||ƒSdS(N(sisI3sCompsselfsObs __conform__(sselfsi((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pys __conform__@s (s__name__s __module__s __conform__(((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pys Conforming?ssStubServiceServicecBs-tZeeƒd„Zd„Zd„ZRS(NcCs h|_dS(N(sselfsservices(sself((s;build/bdist.linux-i686/egg/zope/component/tests/test_api.pys__init__IscCs||i|