[Zope3-checkins] SVN: Zope3/trunk/src/zope/component/ Changed the Component Architecture API to take context as the last

Albertas Agejevas alga at pov.lt
Fri May 21 21:54:58 EDT 2004


Log message for revision 24868:

Changed the Component Architecture API to take context as the last
optional keyword argument. Backwards compatibility hacks provided
where reasonably possible.

Context no longer needs to be passed, as the nearest site is kept in a
thread global.  More info:
http://dev.zope.org/Zope3/FixedDefaultComponentLookup

Renamed getServiceManager(context) to getServices(context=None).

Introduced getGlobalServices().

A  +   src/zope/app/component/localservice.py
D      src/zope/app/component/nextservice.py
A  +   src/zope/app/component/tests/test_localservice.py
D      src/zope/app/component/tests/test_nextservice.py

Renamed nextservice.py to localservice.py, because that's what it is
about.  Renamed ...ServiceManager() functions to ...Services() to be
in line with getServices().




-=-
Modified: Zope3/trunk/src/zope/component/__init__.py
===================================================================
--- Zope3/trunk/src/zope/component/__init__.py	2004-05-22 01:43:32 UTC (rev 24867)
+++ Zope3/trunk/src/zope/component/__init__.py	2004-05-22 01:54:58 UTC (rev 24868)
@@ -18,12 +18,14 @@
 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 dependence
+# Try to be hookable. Do so in a try/except to avoid a hard dependency.
 try:
     from zope.hookable import hookable
 except ImportError:
@@ -33,27 +35,93 @@
 moduleProvides(IComponentArchitecture)
 __all__ = tuple(IComponentArchitecture)
 
-def getServiceManager(context):
+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
-getServiceManager = hookable(getServiceManager)
 
-def getService(context, name):
-    return getServiceManager(context).getService(name)
+def getServiceManager(context):
+    # Backwards compatibility stub
+    warnings.warn("getServiceManager(context) is  deprecated,"
+                  " use getServices(context=None) instead.",
+                  DeprecationWarning, 2)
+    return getServices(context)
 
+
+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.
+
+        # We should be using the line of code below.
+        ## return getAdapter(context, IServiceService, context=None)
+        #
+        # Instead, we need to support code that has passed in an object
+        # as context, at least until the whole component API is fixed up.
+        # XXX try ripping this code out.
+        sm = queryAdapter(context, IServiceService, context=None)
+        if sm is None:
+            # Deprecated support for a context that isn't adaptable to
+            # IServiceService.  Return the default service manager.
+            # warnings.warn("getServices' context arg must be None or"
+            #               "  adaptable to IServiceService.",
+            #               DeprecationWarning, warningLevel())
+            return serviceManager
+        else:
+            return sm
+
+getServices = hookable(getServices)
+
+def getService(name, context=None):
+    # Deprecated backwards-compatibility hack.
+    if isinstance(context, basestring) and not isinstance(name, basestring):
+        name, context = context, name
+        ##warnings.warn("getService(context, name) is deprecated."
+        ##              "  Use getService(name, context=context).",
+        ##              DeprecationWarning, warningLevel())
+    return getServices(context).getService(name)
+
 def queryService(context, name, default=None):
-    sm = getServiceManager(context)
-    return sm.queryService(name, default)
+    # Leaving the API in the older style of context, name, default because
+    # this function is deprecated anyway.
+    ##warnings.warn("queryService is deprecated.  Client code should depend"
+    ##              "  on the service existing.  Use getService instead.",
+    ##              DeprecationWarning, warningLevel())
+    return getServices(context).queryService(name, default)
 
-def getServiceDefinitions(context):
-    return getServiceManager(context).getServiceDefinitions()
+def getServiceDefinitions(context=None):
+    return getServices(context).getServiceDefinitions()
 
 # Utility service
 
-def getUtility(context, interface, name=''):
-    return getService(context, Utilities).getUtility(interface, name)
+def getUtility(interface, name='', context=None):
+    if not isinstance(name, basestring):
+        context, interface, name = interface, name, context
+        if name is None:
+            name = ''
+            warnings.warn("getUtility(context, interface, name) is deprecated."
+                          "  Use getUtility(interface, name, context=context).",
+                          DeprecationWarning, warningLevel())
+    return getService(Utilities, context=context).getUtility(interface, name)
 
-def queryUtility(context, interface, default=None, name=''):
-    return getService(context, Utilities).queryUtility(
+def queryUtility(interface, default=None, name='', context=None):
+    ## XXX this check is for migration.  Remove soon.
+    if (not IInterface.providedBy(interface) or
+        not isinstance(name, basestring)):
+        raise TypeError("queryUtility got nonsense arguments."
+                        " Check that you are updated with the"
+                        " component API change.")
+    return getService(Utilities, context).queryUtility(
         interface, default, name)
 
 def getUtilitiesFor(context, interface):
@@ -70,7 +138,7 @@
 def queryAdapter(object, interface, default=None, name='', context=None):
     if name:
         warnings.warn("The name argument to queryAdapter is deprecated",
-                      DeprecationWarning, 2)
+                      DeprecationWarning, warningLevel())
         return queryNamedAdapter(object, interface, name, default, context)
 
     conform = getattr(object, '__conform__', None)
@@ -99,7 +167,6 @@
 
     return queryNamedAdapter(object, interface, name, default, context)
 
-
 def getNamedAdapter(object, interface, name, context=None):
     adapter = queryNamedAdapter(object, interface, name, context=context)
     if adapter is None:
@@ -107,12 +174,12 @@
     return adapter
 
 def queryNamedAdapter(object, interface, name, default=None, context=None):
-    if context is None:
-        context = object
     try:
-        adapters = getService(context, Adapters)
+        adapters = getService(Adapters, context)
     except ComponentLookupError:
         # Oh blast, no adapter service. We're probably just running from a test
+        #warnings.warn("There is no adapters service.  Returning the default.",
+        #              DeprecationWarning, warningLevel())
         return default
 
     return adapters.queryNamedAdapter(object, interface, name, default)
@@ -121,12 +188,12 @@
 
 def interfaceAdapterHook(iface, ob):
     try:
-        adapters = getService(ob, Adapters)
+        adapters = getService(Adapters)
     except ComponentLookupError:
-
         # Oh blast, no adapter service. We're probably just running
         # from a test
-
+        #warnings.warn("There is no adapters service.  Returning the default.",
+        #              DeprecationWarning, warningLevel())
         return None
 
     return adapters.queryNamedAdapter(ob, iface, '')
@@ -143,11 +210,8 @@
 
 def queryMultiAdapter(objects, interface, name=u'', default=None,
                       context=None):
-    if context is None and objects:
-        context = objects[0]
-
     try:
-        adapters = getService(context, Adapters)
+        adapters = getService(Adapters, context)
     except ComponentLookupError:
         # Oh blast, no adapter service. We're probably just running from a test
         return default
@@ -155,10 +219,8 @@
     return adapters.queryMultiAdapter(objects, interface, name, default)
 
 def subscribers(objects, interface, context=None):
-    if context is None and objects:
-        context = objects[0]
     try:
-        adapters = getService(context, Adapters)
+        adapters = getService(Adapters, context=context)
     except ComponentLookupError:
         # Oh blast, no adapter service. We're probably just running from a test
         return []
@@ -168,13 +230,13 @@
 # Factories
 
 def createObject(context, name, *args, **kwargs):
-    return getUtility(context, IFactory, name)(*args, **kwargs)
+    return getUtility(IFactory, name, context)(*args, **kwargs)
 
-def getFactoryInterfaces(context, name):
-    return getUtility(context, IFactory, name).getInterfaces()
+def getFactoryInterfaces(name, context=None):
+    return getUtility(IFactory, name, context).getInterfaces()
 
-def getFactoriesFor(context, interface):
-    utils = getService(context, Utilities)
+def getFactoriesFor(interface, context=None):
+    utils = getService(Utilities, context)
     for (name, factory) in utils.getUtilitiesFor(IFactory):
         interfaces = factory.getInterfaces()
         try:
@@ -190,18 +252,25 @@
     warnings.warn(
         "Use getUtility(context, IFactory, name) instead of getFactory(...)",
         DeprecationWarning, 2)
-    return getUtility(context, IFactory, name)
+    return getUtility(IFactory, name, context=context)
 
 def queryFactory(context, name, default=None):
     warnings.warn(
         "Use getUtility(context, IFactory, name) instead of getFactory(...)",
         DeprecationWarning, 2)
-    return queryUtility(context, IFactory, name=name)
+    return queryUtility(IFactory, name=name, context=context)
 
 
 # Presentation service
 
-def getView(object, name, request, context=None, providing=Interface):
+def getView(object, name, request, providing=Interface, context=None):
+    if not IInterface.providedBy(providing):
+        providing, context = context, providing
+        warnings.warn("Use getView(object, name, request,"
+                      " prodiving=Interface, context=Interface)"
+                      " instead of getView(object, name, request,"
+                      " context=None, prodiving=Interface)",
+                      DeprecationWarning, 2)
     view = queryView(object, name, request, context=context,
                      providing=providing)
     if view is not None:
@@ -211,10 +280,8 @@
                                name, object, context, request)
 
 def queryView(object, name, request,
-              default=None, context=None, providing=Interface):
-    if context is None:
-        context = object
-    s = getService(context, Presentation)
+              default=None, providing=Interface, context=None):
+    s = getService(Presentation, context=context)
     return s.queryView(object, name, request,
                        default=default, providing=providing)
 
@@ -230,17 +297,15 @@
 
 def queryMultiView(objects, request, providing=Interface, name='',
                    default=None, context=None):
-    if context is None:
-        context = objects[0]
-    s = getService(context, Presentation)
+    s = getService(Presentation, context)
     return s.queryMultiView(objects, request, providing, name, default)
 
 def getViewProviding(object, providing, request, context=None):
-    return getView(object, '', request, context, providing)
+    return getView(object, '', request, providing, context)
 
 def queryViewProviding(object, providing, request, default=None, 
                        context=None):
-    return queryView(object, '', request, default, context, providing)
+    return queryView(object, '', request, default, providing, context)
 
 def getDefaultViewName(object, request, context=None):
     view = queryDefaultViewName(object, request, context=context)
@@ -251,18 +316,23 @@
                                context, request)
 
 def queryDefaultViewName(object, request, default=None, context=None):
-    if context is None:
-        context = object
-    s = getService(context, Presentation)
+    s = getService(Presentation, context)
     return s.queryDefaultViewName(object, request, default)
 
-def getResource(wrapped_object, name, request, providing=Interface):
-    view = queryResource(wrapped_object, name, request, providing=providing)
+def getResource(name, request, providing=Interface, context=None):
+    if isinstance(request, basestring):
+        # "Backwards compatibility"
+        raise TypeError("getResource got incorrect arguments.")
+    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(context, name, request, default=None, providing=Interface):
-    s = getService(context, Presentation)
+def queryResource(name, request, default=None, providing=Interface,
+                  context=None):
+    if isinstance(request, basestring):
+        # "Backwards compatibility"
+        raise TypeError("queryResource got incorrect arguments.")
+    s = getService(Presentation, context)
     return s.queryResource(name, request, default, providing=providing)

Modified: Zope3/trunk/src/zope/component/interfaces.py
===================================================================
--- Zope3/trunk/src/zope/component/interfaces.py	2004-05-22 01:43:32 UTC (rev 24867)
+++ Zope3/trunk/src/zope/component/interfaces.py	2004-05-22 01:54:58 UTC (rev 24868)
@@ -25,33 +25,53 @@
 
     # basic service manager tools
 
-    def getServiceManager(context):
+    def getGlobalServices():
+        """Get the global service manager."""
+
+    def getServices(context=None):
         """Get the service manager
 
-        Return the nearest service manager to the context; if the
-        context is None the global service manager is always returned
+        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(context, name):
+    def getServiceManager(context):
+        """Backwards compatibility for getServices()"""
+
+    def getService(name, context=None):
         """Get a named service.
 
-        Returns the service defined by 'name' nearest to the context;
-        if the context is None the pertinent global service is always
-        returned"""
+        Returns the service defined by 'name' from the service manager.
 
-    def getServiceDefinitions(context):
+        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 pertinent to
-        the given context, in the format {nameString: serviceInterface}.
-        If the context is None the global definitions will be returned.
+        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(context, interface, name=''):
+    def getUtility(interface, name='', context=None):
         """Get the utility that provides interface
 
         Returns the nearest utility to the context that implements the
@@ -59,7 +79,7 @@
         ComponentLookupError.
         """
 
-    def queryUtility(context, interface, default=None, name=''):
+    def queryUtility(interface, default=None, name='', context=None):
         """Look for the utility that provides interface
 
         Returns the nearest utility to the context that implements
@@ -67,21 +87,25 @@
         """
 
     def getUtilitiesFor(context, interface):
-        """Return the utilitis that provide an interface
+        """Return the utilities that provide an interface
 
         An iterable of utility name-value pairs is returned.
         """
-        
+
     # Adapter service
 
     def getAdapter(object, interface, context=None):
         """Get an adapter to an interface for an object
 
-        Returns the nearest adapter to the context that can adapt
-        object to interface.  If context is not specified, attempts to
-        use  object to specify a context.  If a
-        matching adapter cannot be found, raises ComponentLookupError.
+        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.
+
         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
@@ -92,11 +116,15 @@
     def getNamedAdapter(object, interface, name, context=None):
         """Get a named adapter to an interface for an object
 
-        Returns the nearest named adapter to the context that can adapt
-        object to interface.  If context is not specified, attempts to
-        use  object to specify a context.  If a
+        Returns a named 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.
+
         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.
@@ -105,11 +133,15 @@
     def getMultiAdapter(objects, interface, name='', context=None):
         """Look for a multi-adapter to an interface for an objects
 
-        Returns the nearest multi-adapter to the context that can
-        adapt objects to interface.  If context is not specified, the
-        first object, if any, is used.  If a matching adapter cannot
-        be found, raises ComponentLookupError.
+        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.
@@ -118,11 +150,15 @@
     def queryAdapter(object, interface, default=None, context=None):
         """Look for an adapter to an interface for an object
 
-        Returns the nearest adapter to the context that can adapt
-        object to interface.  If context is not specified, attempts to
-        use  object to specify a context.  If a matching
+        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.
+
         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
@@ -134,11 +170,16 @@
                           context=None):
         """Look for a named adapter to an interface for an object
 
-        Returns the nearest named adapter to the context that can adapt
-        object to interface.  If context is not specified, attempts to
-        use  object to specify a context.  If a matching
-        adapter cannot be found, returns the default.
+        Returns a named 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.
+
         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.
@@ -148,11 +189,15 @@
                           context=None):
         """Look for a multi-adapter to an interface for objects
 
-        Returns the nearest multi-adapter to the context that can
-        adapt objects to interface.  If context is not specified, the
-        first object, if any, is used.  If a matching adapter cannot
-        be found, returns the default.
+        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.
@@ -162,16 +207,21 @@
         """Get subscribers
 
         Subscribers are returned that provide the provided interface
-        and that depend on and are comuted from the sequence of
+        and that depend on and are computed from the sequence of
         required objects.
 
-        Returns the subscribers for the context.  If context is not
-        specified, attempts to use object to specify a context.
+        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
 
+    # XXX:  Hard to make context a keyword, leaving as it is
     def createObject(context, name, *args, **kwargs):
         """Create an object using a factory
 
@@ -182,15 +232,15 @@
         ComponentLookupError
         """
 
-    def getFactoryInterfaces(context, name):
+    def getFactoryInterfaces(name, context=None):
         """Get interfaces implemented by a factory
 
-        finds the factory of the given name that is nearest to the
+        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(context, interface):
+    def getFactoriesFor(interface, context=None):
         """Return a tuple (name, factory) of registered factories that
         create objects which implement the given interface.
         """
@@ -215,21 +265,17 @@
 
     # Presentation service
 
-    def getView(object, name, request, context=None,
-                providing=Interface):
+    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.
-
-        If context is not specified, attempts to use 
-        object to specify a context.
         """
 
     def queryView(object, name, request,
-                  default=None, context=None, providing=Interface):
+                  default=None, providing=Interface, context=None):
         """Look for a named view for a given object.
 
         The request must implement IPresentationRequest: it provides
@@ -275,7 +321,7 @@
             getView(object, '', request, context, providing)
         """
 
-    def queryViewProviding(object, providing, request, 
+    def queryViewProviding(object, providing, request,
                            default=None, context=None):
         """Look for a view that provides the specified interface.
 
@@ -292,7 +338,7 @@
         If a matching default view name cannot be found, raises
         NotFoundError.
 
-        If context is not specified, attempts to use 
+        If context is not specified, attempts to use
         object to specify a context.
         """
 
@@ -308,28 +354,29 @@
         a context.
         """
 
-    def getResource(wrapped_object, name, request, providing=Interface):
+    def getResource(name, request, providing=Interface, context=None):
         """Get a named resource for a given request
 
         The request must implement IPresentationRequest.
 
-        The object provides a place to look for placeful resources.
+        The context provides a place to look for placeful resources.
 
         A ComponentLookupError will be raised if the component can't
         be found.
         """
 
-    def queryResource(wrapped_object, name, request,
-                      default=None, providing=Interface):
+    def queryResource(name, request, default=None, providing=Interface,
+                      context=None):
         """Get a named resource for a given request
 
         The request must implement IPresentationRequest.
 
-        The object provides a place to look for placeful resources.
+        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
     """
@@ -338,6 +385,7 @@
         """Return an iterable of component registrations
         """
 
+
 class IServiceService(Interface):
     """A service to manage Services."""
 
@@ -363,6 +411,7 @@
         Return the default if the service can't be found.
         """
 
+
 class IFactory(Interface):
     """A factory is responsible for creating other components."""
 
@@ -370,11 +419,6 @@
 
     description = Attribute("A brief description of the factory.")
 
-    # XXX Because __call__ does not receive a context, it is not possible
-    #     to write a factory that does its job in terms of another factory.
-    #     This functionality is needed for making advanced factories that
-    #     do what other factories do, and then mark the resultant object
-    #     with an interface.
     def __call__(*args, **kw):
         """Return an instance of the objects we're a factory for."""
 
@@ -409,6 +453,7 @@
         Returns an iterable of name-utility pairs.
         """
 
+
 class IContextDependent(Interface):
     """Components implementing this interface must have a context component.
 
@@ -423,6 +468,7 @@
         This is the object being adapted, viewed, extended, etc.
         """)
 
+
 class IAdapterService(Interface):
     """A service to manage Adapters."""
 
@@ -460,6 +506,7 @@
         required objects.
         """
 
+
 class IPresentation(Interface):
     """Presentation components provide interfaces to external actors
 
@@ -475,6 +522,7 @@
         IPresentationRequest.
         """)
 
+
 class IPresentationRequest(Interface):
     """An IPresentationRequest provides methods for getting view meta data."""
 
@@ -485,9 +533,11 @@
         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."""
 
@@ -497,9 +547,11 @@
         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"""
 
@@ -511,6 +563,7 @@
         "stands in" for the user.
         """
 
+
 class IPresentationService(Interface):
     """A service to manage Presentation components."""
 

Modified: Zope3/trunk/src/zope/component/tests/placelesssetup.py
===================================================================
--- Zope3/trunk/src/zope/component/tests/placelesssetup.py	2004-05-22 01:43:32 UTC (rev 24867)
+++ Zope3/trunk/src/zope/component/tests/placelesssetup.py	2004-05-22 01:54:58 UTC (rev 24868)
@@ -20,13 +20,14 @@
 # A mix-in class inheriting from CleanUp that also connects the CA services
 
 from zope.testing.cleanup import CleanUp
-from zope.component import getServiceManager
+from zope.component import getGlobalServices
 from zope.component.servicenames import Adapters, Utilities, Presentation
 
 class PlacelessSetup(CleanUp):
+
     def setUp(self):
         CleanUp.setUp(self)
-        sm = getServiceManager(None)
+        sm = getGlobalServices()
         defineService = sm.defineService
         provideService = sm.provideService
 

Modified: Zope3/trunk/src/zope/component/tests/test_api.py
===================================================================
--- Zope3/trunk/src/zope/component/tests/test_api.py	2004-05-22 01:43:32 UTC (rev 24867)
+++ Zope3/trunk/src/zope/component/tests/test_api.py	2004-05-22 01:54:58 UTC (rev 24868)
@@ -21,12 +21,15 @@
 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
@@ -47,6 +50,9 @@
 
 class Ob:
     implements(I1)
+    def __conform__(self, i):
+        if i is IServiceService:
+            return serviceManager
 
 ob = Ob()
 
@@ -54,12 +60,99 @@
     def __conform__(self, i):
         if i is I3:
             return Comp(self)
+        else:
+            return Ob.__conform__(self, i)
 
+class StubServiceService:
+    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:
+
+    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)
+
+        # XXX enable this test before checking in
+        # 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)
+
+        # XXX enable this test before checking in
+        # Using a context that is not adaptable to IServiceService should
+        # fail.
+        ##self.assertRaises(ComponentLookupError,
+        ##                  getService, Adapters, object())
+
     def testAdapter_via_conform(self):
-
         ob = Conforming()
 
         # If an object implements the interface you want to adapt to,
@@ -137,7 +230,6 @@
         self.assertEquals(c.context, ob)
 
     def testNamedAdapter(self):
-
         self.testAdapter()
 
         # If an object implements the interface you want to adapt to,
@@ -188,13 +280,12 @@
         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, Test, context=ob), Test)
 
-        self.assertRaises(ComponentLookupError, getUtility, ob, I1)
-        self.assertRaises(ComponentLookupError, getUtility, ob, I2)
-        self.assertEquals(queryUtility(ob, I2, Test), Test)
-
         getService(None, 'Utilities').provideUtility(I2, comp)
-        self.assertEquals(id(getUtility(ob, I2)), id(comp))
+        self.assertEquals(id(getUtility(I2, context=ob)), id(comp))
 
     def testNamedUtility(self):
         from zope.component import getUtility, queryUtility
@@ -203,12 +294,15 @@
 
         self.testUtility()
 
-        self.assertRaises(ComponentLookupError, getUtility, ob, I1, 'test')
-        self.assertRaises(ComponentLookupError, getUtility, ob, I2, 'test')
-        self.assertEquals(queryUtility(ob, I2, Test, 'test'), Test)
+        self.assertRaises(ComponentLookupError,
+                          getUtility, I1, 'test', context=ob)
+        self.assertRaises(ComponentLookupError,
+                          getUtility, I2, 'test', context=ob)
+        self.assertEquals(queryUtility(I2, Test, name='test', context=ob),
+                          Test)
 
         getService(None, 'Utilities').provideUtility(I2, comp, 'test')
-        self.assertEquals(id(getUtility(ob, I2, 'test')), id(comp))
+        self.assertEquals(id(getUtility(I2, 'test', ob)), id(comp))
 
     def testView(self):
         from zope.component import getView, queryView, getService
@@ -313,11 +407,11 @@
             object='object', providing='providing', request='request', 
             context='context')
         self.assertEquals(self.args, 
-            ['object', '', 'request', 'context', 'providing'])
+            ['object', '', 'request', 'providing', 'context'])
 
         # hack zope.component.queryView
-        def queryView(object, name, request, default, context, providing):
-            self.args = [object, name, request, default, context, providing]
+        def queryView(object, name, request, default, providing, context):
+            self.args = [object, name, request, default, providing, context]
         savedQueryView = zope.component.queryView
         zope.component.queryView = queryView
 
@@ -326,35 +420,34 @@
             object='object', providing='providing', request='request', 
             default='default', context='context')
         self.assertEquals(self.args, 
-            ['object', '', 'request', 'default', 'context', 'providing'])
+            ['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, ob, 'foo', r1)
-        self.assertRaises(ComponentLookupError, getResource, ob, 'foo', r2)
-        self.assertEquals(queryResource(ob, 'foo', r2, Test), Test)
+        self.assertRaises(ComponentLookupError, getResource, 'foo', r1)
+        self.assertRaises(ComponentLookupError, getResource, 'foo', r2)
+        self.assertEquals(queryResource('foo', r2, Test), Test)
 
         getService(None, servicenames.Presentation).provideResource(
             'foo', I2, Comp)
-        c = getResource(ob, 'foo', r2)
+        c = getResource('foo', r2)
         self.assertEquals(c.__class__, Comp)
         self.assertEquals(c.context, r2)
 
-        self.assertRaises(ComponentLookupError, getResource, ob, 'foo2', r1)
-        self.assertRaises(ComponentLookupError, getResource, ob, 'foo2', r2)
-        self.assertEquals(queryResource(ob, 'foo2', r2, Test), Test)
+        self.assertRaises(ComponentLookupError, getResource, 'foo2', r1, ob)
+        self.assertRaises(ComponentLookupError, getResource, 'foo2', r2)
+        self.assertEquals(queryResource('foo2', r2, Test, ob), Test)
 
-        self.assertEquals(queryResource(ob, 'foo2', r1, None), None)
+        self.assertEquals(queryResource('foo2', r1, None), None)
 
     def testResource_w_provided(self):
         from zope.component import getResource, queryResource, getService
@@ -364,27 +457,27 @@
         r2 = Request(I2)
 
         self.assertRaises(ComponentLookupError,
-                          getResource, ob, 'foo', r1, providing=I3)
+                          getResource, 'foo', r1, providing=I3)
         self.assertRaises(ComponentLookupError,
-                          getResource, ob, 'foo', r2, providing=I3)
-        self.assertEquals(queryResource(ob, 'foo', r2, Test, providing=I3),
+                          getResource, 'foo', r2, providing=I3)
+        self.assertEquals(queryResource('foo', r2, Test, providing=I3),
                           Test)
 
         getService(None, servicenames.Presentation).provideResource(
             'foo', I2, Comp)
 
         self.assertRaises(ComponentLookupError,
-                          getResource, ob, 'foo', r1, providing=I3)
+                          getResource, 'foo', r1, providing=I3)
         self.assertRaises(ComponentLookupError,
-                          getResource, ob, 'foo', r2, providing=I3)
-        self.assertEquals(queryResource(ob, 'foo', r2, Test, providing=I3),
+                          getResource, 'foo', r2, providing=I3)
+        self.assertEquals(queryResource('foo', r2, Test, providing=I3),
                           Test)
 
 
         getService(None, servicenames.Presentation).provideResource(
             'foo', I2, Comp, providing=I3)
 
-        c = getResource(ob, 'foo', r2, providing=I3)
+        c = getResource('foo', r2, providing=I3)
         self.assertEquals(c.__class__, Comp)
         self.assertEquals(c.context, r2)
 
@@ -438,10 +531,11 @@
 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),

Modified: Zope3/trunk/src/zope/component/tests/test_factory.py
===================================================================
--- Zope3/trunk/src/zope/component/tests/test_factory.py	2004-05-22 01:43:32 UTC (rev 24867)
+++ Zope3/trunk/src/zope/component/tests/test_factory.py	2004-05-22 01:54:58 UTC (rev 24868)
@@ -76,12 +76,12 @@
         self.assertEqual(kl.kw, {'foo': 4})
 
     def testGetFactoryInterfaces(self):
-        implemented = getFactoryInterfaces(None, 'klass')
+        implemented = getFactoryInterfaces('klass')
         self.assert_(implemented.isOrExtends(IKlass))
         self.assertEqual([iface for iface in implemented], [IKlass])
 
     def testGetFactoriesFor(self):
-        self.assertEqual(list(getFactoriesFor(None, IKlass)),
+        self.assertEqual(list(getFactoriesFor(IKlass)),
                          [('klass', self.factory)])
 
 

Modified: Zope3/trunk/src/zope/component/tests/test_service.py
===================================================================
--- Zope3/trunk/src/zope/component/tests/test_service.py	2004-05-22 01:43:32 UTC (rev 24867)
+++ Zope3/trunk/src/zope/component/tests/test_service.py	2004-05-22 01:54:58 UTC (rev 24868)
@@ -20,11 +20,10 @@
 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, getServiceManager
+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
@@ -46,9 +45,10 @@
 class Test(CleanUp, unittest.TestCase):
 
     def testNormal(self):
-        getServiceManager(None).defineService('one', IOne)
+        ss = getGlobalServices()
+        ss.defineService('one', IOne)
         c = ServiceOne()
-        getServiceManager(None).provideService('one', c)
+        ss.provideService('one', c)
         self.assertEqual(id(getService(None, 'one')), id(c))
 
     def testFailedLookup(self):
@@ -56,17 +56,17 @@
         self.assertEqual(queryService(None, 'two'), None)
 
     def testDup(self):
-        getServiceManager(None).defineService('one', IOne)
+        getGlobalServices().defineService('one', IOne)
         self.assertRaises(DuplicationError,
-                          getServiceManager(None).defineService,
+                          getGlobalServices().defineService,
                           'one', ITwo)
 
         c = ServiceOne()
-        getServiceManager(None).provideService('one', c)
+        getGlobalServices().provideService('one', c)
 
         c2 = ServiceOne()
         self.assertRaises(DuplicationError,
-                          getServiceManager(None).provideService,
+                          getGlobalServices().provideService,
                           'one', c2)
 
         self.assertEqual(id(getService(None, 'one')), id(c))
@@ -75,30 +75,28 @@
     def testUndefined(self):
         c = ServiceOne()
         self.assertRaises(UndefinedService,
-                          getServiceManager(None).provideService,
+                          getGlobalServices().provideService,
                           'one', c)
 
     def testInvalid(self):
-        getServiceManager(None).defineService('one', IOne)
-        getServiceManager(None).defineService('two', ITwo)
+        getGlobalServices().defineService('one', IOne)
+        getGlobalServices().defineService('two', ITwo)
         c = ServiceOne()
         self.assertRaises(InvalidService,
-                          getServiceManager(None).provideService,
+                          getGlobalServices().provideService,
                           'two', c)
 
     def testGetService(self):
         # Testing looking up a service from a service manager container that
         # doesn't have a service manager.
-        getServiceManager(None).defineService('one', IOne)
+        getGlobalServices().defineService('one', IOne)
         c = ServiceOne()
-        getServiceManager(None).provideService('one', c)
-        class C: pass
-        foo = C()
-        self.assertEqual(id(getService(foo, 'one')), id(c))
+        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 = getServiceManager(None)
+        sm = getGlobalServices()
         sm.defineService('one', IOne)
         c = ServiceOne()
         sm.provideService('one', c)
@@ -111,7 +109,6 @@
         self.assertEqual(defs,
             [('Services', IServiceService), ('one', IOne), ('two', ITwo)])
 
-
     def testPickling(self):
         self.assertEqual(testServiceManager.__reduce__(), 'testServiceManager')
         sm = pickle.loads(pickle.dumps(testServiceManager))

Modified: Zope3/trunk/src/zope/component/tests/test_utilityservice.py
===================================================================
--- Zope3/trunk/src/zope/component/tests/test_utilityservice.py	2004-05-22 01:43:32 UTC (rev 24867)
+++ Zope3/trunk/src/zope/component/tests/test_utilityservice.py	2004-05-22 01:54:58 UTC (rev 24868)
@@ -18,7 +18,7 @@
 from unittest import TestCase, main, makeSuite
 from zope.component import \
      getUtility, getUtilitiesFor, getService, queryUtility, \
-     getServiceManager, getUtilitiesFor
+     getServices, getUtilitiesFor, getGlobalServices
 from zope.component.exceptions import ComponentLookupError
 from zope.component.servicenames import Utilities
 from zope.interface import Interface, implements
@@ -46,9 +46,9 @@
 
     def setUp(self):
         CleanUp.setUp(self)
-        sm=getServiceManager(None)
-        defineService=sm.defineService
-        provideService=sm.provideService
+        sm = getGlobalServices()
+        defineService = sm.defineService
+        provideService = sm.provideService
         from zope.component.interfaces import IUtilityService
         defineService('Utilities',IUtilityService)
         from zope.component.utility import GlobalUtilityService
@@ -57,16 +57,16 @@
     def testGetUtility(self):
         us = getService(None, Utilities)
         self.assertRaises(
-            ComponentLookupError, getUtility, None, IDummyUtility)
+            ComponentLookupError, getUtility, IDummyUtility)
         us.provideUtility(IDummyUtility, dummyUtility)
-        self.assertEqual(getUtility(None, IDummyUtility), dummyUtility)
+        self.assertEqual(getUtility(IDummyUtility), dummyUtility)
 
     def testQueryUtility(self):
         us = getService(None, Utilities)
-        self.assertEqual(queryUtility(None, IDummyUtility), None)
-        self.assertEqual(queryUtility(None, IDummyUtility, self), self)
+        self.assertEqual(queryUtility(IDummyUtility), None)
+        self.assertEqual(queryUtility(IDummyUtility, default=self), self)
         us.provideUtility(IDummyUtility, dummyUtility)
-        self.assertEqual(queryUtility(None, IDummyUtility), dummyUtility)
+        self.assertEqual(queryUtility(IDummyUtility), dummyUtility)
 
     def testgetUtilitiesFor(self):
         us = getService(None, Utilities)




More information about the Zope3-Checkins mailing list