[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[gnue] r8287 - in trunk/gnue-navigator/src: . external external/zope ext
From: |
jamest |
Subject: |
[gnue] r8287 - in trunk/gnue-navigator/src: . external external/zope external/zope/component external/zope/component/bbb external/zope/component/bbb/tests external/zope/deprecation external/zope/exceptions external/zope/exceptions/tests external/zope/interface external/zope/interface/common external/zope/interface/common/tests foundation |
Date: |
Mon, 3 Apr 2006 18:22:17 -0500 (CDT) |
Author: jamest
Date: 2006-03-29 20:36:08 -0600 (Wed, 29 Mar 2006)
New Revision: 8287
Added:
trunk/gnue-navigator/src/external/
trunk/gnue-navigator/src/external/__init__.py
trunk/gnue-navigator/src/external/zope/
trunk/gnue-navigator/src/external/zope/component/
trunk/gnue-navigator/src/external/zope/component/DEPENDENCIES.cfg
trunk/gnue-navigator/src/external/zope/component/README.txt
trunk/gnue-navigator/src/external/zope/component/__init__.py
trunk/gnue-navigator/src/external/zope/component/bbb/
trunk/gnue-navigator/src/external/zope/component/bbb/__init__.py
trunk/gnue-navigator/src/external/zope/component/bbb/adapter.py
trunk/gnue-navigator/src/external/zope/component/bbb/contextdependent.py
trunk/gnue-navigator/src/external/zope/component/bbb/exceptions.py
trunk/gnue-navigator/src/external/zope/component/bbb/interfaces.py
trunk/gnue-navigator/src/external/zope/component/bbb/service.py
trunk/gnue-navigator/src/external/zope/component/bbb/servicenames.py
trunk/gnue-navigator/src/external/zope/component/bbb/tests/
trunk/gnue-navigator/src/external/zope/component/bbb/tests/__init__.py
trunk/gnue-navigator/src/external/zope/component/bbb/tests/components.py
trunk/gnue-navigator/src/external/zope/component/bbb/tests/placelesssetup.py
trunk/gnue-navigator/src/external/zope/component/bbb/tests/request.py
trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_adapter.py
trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_api.py
trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_service.py
trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_utilityservice.py
trunk/gnue-navigator/src/external/zope/component/bbb/utility.py
trunk/gnue-navigator/src/external/zope/component/factory.py
trunk/gnue-navigator/src/external/zope/component/factory.txt
trunk/gnue-navigator/src/external/zope/component/interfaces.py
trunk/gnue-navigator/src/external/zope/component/site.py
trunk/gnue-navigator/src/external/zope/component/socketexample.txt
trunk/gnue-navigator/src/external/zope/component/testing.py
trunk/gnue-navigator/src/external/zope/component/tests.py
trunk/gnue-navigator/src/external/zope/deprecation/
trunk/gnue-navigator/src/external/zope/deprecation/DEPENDENCIES.cfg
trunk/gnue-navigator/src/external/zope/deprecation/README.txt
trunk/gnue-navigator/src/external/zope/deprecation/__init__.py
trunk/gnue-navigator/src/external/zope/deprecation/deprecation.py
trunk/gnue-navigator/src/external/zope/deprecation/tests.py
trunk/gnue-navigator/src/external/zope/exceptions/
trunk/gnue-navigator/src/external/zope/exceptions/DEPENDENCIES.cfg
trunk/gnue-navigator/src/external/zope/exceptions/__init__.py
trunk/gnue-navigator/src/external/zope/exceptions/_duplicate.py
trunk/gnue-navigator/src/external/zope/exceptions/_notfounderror.py
trunk/gnue-navigator/src/external/zope/exceptions/exceptionformatter.py
trunk/gnue-navigator/src/external/zope/exceptions/interfaces.py
trunk/gnue-navigator/src/external/zope/exceptions/log.py
trunk/gnue-navigator/src/external/zope/exceptions/tests/
trunk/gnue-navigator/src/external/zope/exceptions/tests/__init__.py
trunk/gnue-navigator/src/external/zope/exceptions/tests/test_exceptionformatter.py
trunk/gnue-navigator/src/external/zope/interface/
trunk/gnue-navigator/src/external/zope/interface/common/
trunk/gnue-navigator/src/external/zope/interface/common/tests/
trunk/gnue-navigator/src/external/zope/interface/common/tests/__init__.py
trunk/gnue-navigator/src/external/zope/interface/common/tests/basemapping.py
trunk/gnue-navigator/src/external/zope/interface/common/tests/test_idatetime.py
trunk/gnue-navigator/src/foundation/
trunk/gnue-navigator/src/foundation/__init__.py
trunk/gnue-navigator/src/foundation/application.py
trunk/gnue-navigator/src/foundation/interfaces.py
Log:
added zope3 pieces needed
small start to make sure the z3 interface code works
Added: trunk/gnue-navigator/src/external/__init__.py
===================================================================
--- trunk/gnue-navigator/src/external/__init__.py 2006-03-30 02:24:05 UTC
(rev 8286)
+++ trunk/gnue-navigator/src/external/__init__.py 2006-03-30 02:36:08 UTC
(rev 8287)
@@ -0,0 +1,35 @@
+#
+# Copyright 2001-2006 Free Software Foundation
+#
+# This file is part of GNU Enterprise
+#
+# GNU Enterprise is free software; you can redistribute it
+# and/or modify it under the terms of the GNU General Public
+# License as published by the Free Software Foundation; either
+# version 2, or (at your option) any later version.
+#
+# GNU Enterprise is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied
+# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+# PURPOSE. See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public
+# License along with program; see the file COPYING. If not,
+# write to the Free Software Foundation, Inc., 59 Temple Place
+# - Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id: GNClient.py 8129 2006-01-18 21:25:44Z jcater $
+"""
+The 'external' package is a pure namespace package holding packages
+originating outside of the GNUe project.
+
+Packages are placed into this directory for the following reasons.
+
+ - The package isn't typically availabile as a stand alone python module
+ - The package has been modified from it's original to interact with GNUe
+ - The package is small and it's inclusion reduces the number of external
+ dependencies
+
+Unless otherwise noted in the docs of a specific package these packages can
+be imported and used indepently of any GNUe components.
+"""
\ No newline at end of file
Added: trunk/gnue-navigator/src/external/zope/component/DEPENDENCIES.cfg
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/DEPENDENCIES.cfg
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/DEPENDENCIES.cfg
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,4 @@
+zope.exceptions
+zope.interface
+zope.testing
+zope.deprecation
Added: trunk/gnue-navigator/src/external/zope/component/README.txt
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/README.txt 2006-03-30
02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/README.txt 2006-03-30
02:36:08 UTC (rev 8287)
@@ -0,0 +1,396 @@
+Zope 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: (<InterfaceClass ...IGreeter>, '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.
Added: trunk/gnue-navigator/src/external/zope/component/__init__.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/__init__.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/__init__.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,358 @@
+##############################################################################
+#
+# 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 38494 2005-09-16 20:28:02Z srichter $
+"""
+import sys
+import zope.interface
+from types import ClassType
+from gnue.navigator.external.zope.interface import moduleProvides, Interface
+from gnue.navigator.external.zope.interface import providedBy, implementedBy
+from gnue.navigator.external.zope.component.interfaces import
IComponentArchitecture
+from gnue.navigator.external.zope.component.interfaces import
IComponentRegistrationConvenience
+from gnue.navigator.external.zope.component.interfaces import IDefaultViewName
+from gnue.navigator.external.zope.component.interfaces import IFactory
+from gnue.navigator.external.zope.component.interfaces import ISiteManager
+from gnue.navigator.external.zope.component.interfaces import
ComponentLookupError
+from gnue.navigator.external.zope.component.site import globalSiteManager
+
+_class_types = type, ClassType
+
+##############################################################################
+# BBB: Import some backward-compatibility; 12/10/2004
+from gnue.navigator.external.zope.component.bbb import exceptions
+sys.modules['zope.component.exceptions'] = exceptions
+from gnue.navigator.external.zope.component.bbb import service
+sys.modules['zope.component.service'] = service
+from gnue.navigator.external.zope.component.bbb import adapter
+sys.modules['zope.component.adapter'] = adapter
+from gnue.navigator.external.zope.component.bbb import utility
+sys.modules['zope.component.utility'] = utility
+from gnue.navigator.external.zope.component.bbb import servicenames
+sys.modules['zope.component.servicenames'] = servicenames
+from gnue.navigator.external.zope.component.bbb import contextdependent
+sys.modules['zope.component.contextdependent'] = contextdependent
+
+from gnue.navigator.external.zope.component.bbb import tests as bbb_tests
+bbb_tests.__warn__ = False
+from gnue.navigator.external.zope.component.bbb.tests import placelesssetup
+sys.modules['zope.component.tests.placelesssetup'] = placelesssetup
+from gnue.navigator.external.zope.component.bbb.tests import request
+sys.modules['zope.component.tests.request'] = request
+from gnue.navigator.external.zope.component.bbb.tests import components
+sys.modules['zope.component.tests.components'] = components
+bbb_tests.__warn__ = True
+
+service.__warn__ = False
+service.serviceManager = service.GlobalServiceManager(
+ 'serviceManager', __name__, globalSiteManager)
+service.__warn__ = True
+
+from gnue.navigator.external.zope.component.bbb import getGlobalServices,
getGlobalService
+from gnue.navigator.external.zope.component.bbb import getServices, getService
+from gnue.navigator.external.zope.component.bbb import getServiceDefinitions
+from gnue.navigator.external.zope.component.bbb import getView, queryView
+from gnue.navigator.external.zope.component.bbb import getMultiView,
queryMultiView
+from gnue.navigator.external.zope.component.bbb import getViewProviding,
queryViewProviding
+from gnue.navigator.external.zope.component.bbb import getDefaultViewName,
queryDefaultViewName
+from gnue.navigator.external.zope.component.bbb import getResource,
queryResource
+##############################################################################
+
+
+# Try to be hookable. Do so in a try/except to avoid a hard dependency.
+try:
+ from gnue.navigator.external.zope.hookable import hookable
+except ImportError:
+ def hookable(ob):
+ return ob
+
+moduleProvides(IComponentArchitecture, IComponentRegistrationConvenience)
+__all__ = tuple(IComponentArchitecture)
+
+# SiteManager API
+
+def getGlobalSiteManager():
+ return globalSiteManager
+
+def getSiteManager(context=None):
+ if context is None:
+ return getGlobalSiteManager()
+ else:
+ # Use the global site manager to adapt context to `ISiteManager`
+ # to avoid the recursion implied by using a local `getAdapter()` call.
+ try:
+ return ISiteManager(context)
+ except TypeError, error:
+ raise ComponentLookupError(*error.args)
+
+getSiteManager = hookable(getSiteManager)
+
+
+# Adapter API
+
+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
+
+ return getSiteManager(context).queryAdapter(object, interface, '', default)
+
+def getAdapter(object, interface=Interface, name=u'', context=None):
+ adapter = queryAdapter(object, interface, name, None, context)
+ if adapter is None:
+ raise ComponentLookupError(object, interface, name)
+ return adapter
+
+def queryAdapter(object, interface=Interface, name=u'', default=None,
+ context=None):
+ if context is None:
+ return adapter_hook(interface, object, name, default)
+ return getSiteManager(context).queryAdapter(object, interface, name,
+ default)
+
+def getMultiAdapter(objects, interface=Interface, name=u'', context=None):
+ adapter = queryMultiAdapter(objects, interface, name, context=context)
+ if adapter is None:
+ raise ComponentLookupError(objects, interface, name)
+ return adapter
+
+def queryMultiAdapter(objects, interface=Interface, name=u'', default=None,
+ context=None):
+ try:
+ sitemanager = getSiteManager(context)
+ except ComponentLookupError:
+ # Oh blast, no site manager. This should *never* happen!
+ return default
+
+ return sitemanager.queryMultiAdapter(objects, interface, name, default)
+
+def getAdapters(objects, provided, context=None):
+ try:
+ sitemanager = getSiteManager(context)
+ except ComponentLookupError:
+ # Oh blast, no site manager. This should *never* happen!
+ return []
+ return sitemanager.getAdapters(objects, provided)
+
+def subscribers(objects, interface, context=None):
+ try:
+ sitemanager = getSiteManager(context)
+ except ComponentLookupError:
+ # Oh blast, no site manager. This should *never* happen!
+ return []
+ return sitemanager.subscribers(objects, interface)
+
+def handle(*objects):
+ sitemanager = getSiteManager(None)
+ # iterating over subscribers assures they get executed
+ for ignored in sitemanager.subscribers(objects, None):
+ pass
+
+class _adapts_descr(object):
+ def __init__(self, interfaces):
+ self.interfaces = interfaces
+
+ def __get__(self, inst, cls):
+ if inst is None:
+ return self.interfaces
+ raise AttributeError('__component_adapts__')
+
+class adapter:
+
+ def __init__(self, *interfaces):
+ self.interfaces = interfaces
+
+ def __call__(self, ob):
+ if isinstance(ob, _class_types):
+ ob.__component_adapts__ = _adapts_descr(self.interfaces)
+ else:
+ ob.__component_adapts__ = self.interfaces
+
+ return ob
+
+def adapts(*interfaces):
+ frame = sys._getframe(1)
+ locals = frame.f_locals
+
+ # Try to make sure we were called from a class def. In 2.2.0 we can't
+ # check for __module__ since it doesn't seem to be added to the locals
+ # until later on.
+ if (locals is frame.f_globals) or (
+ ('__module__' not in locals) and sys.version_info[:3] > (2, 2, 0)):
+ raise TypeError("adapts can be used only from a class definition.")
+
+ if '__component_adapts__' in locals:
+ raise TypeError("adapts can be used only once in a class definition.")
+
+ locals['__component_adapts__'] = _adapts_descr(interfaces)
+
+def adaptedBy(ob):
+ return getattr(ob, '__component_adapts__', None)
+
+#############################################################################
+# Register the component architectures adapter hook, with the adapter hook
+# registry of the `zope.inteface` package. This way we will be able to call
+# interfaces to create adapters for objects. For example, `I1(ob)` is
+# equvalent to `getAdapterInContext(I1, ob, '')`.
+def adapter_hook(interface, object, name='', default=None):
+ try:
+ sitemanager = getSiteManager()
+ except ComponentLookupError:
+ # Oh blast, no site manager. This should *never* happen!
+ return None
+ return sitemanager.queryAdapter(object, interface, name, default)
+
+# Make the component architecture's adapter hook hookable
+adapter_hook = hookable(adapter_hook)
+
+import zope.interface.interface
+zope.interface.interface.adapter_hooks.append(adapter_hook)
+#############################################################################
+
+
+# Utility API
+
+def getUtility(interface, name='', context=None):
+ utility = queryUtility(interface, name, context=context)
+ if utility is not None:
+ return utility
+ raise ComponentLookupError(interface, name)
+
+def queryUtility(interface, name='', default=None, context=None):
+ return getSiteManager(context).queryUtility(interface, name, default)
+
+def getUtilitiesFor(interface, context=None):
+ return getSiteManager(context).getUtilitiesFor(interface)
+
+
+def getAllUtilitiesRegisteredFor(interface, context=None):
+ return getSiteManager(context).getAllUtilitiesRegisteredFor(interface)
+
+
+# Factories
+
+def createObject(__factory_name, *args, **kwargs):
+ # BBB: Goes away in 3.3
+ if not isinstance(__factory_name, basestring):
+ import warnings
+ warnings.warn(
+ "Passing a context as a first argument to createObject is "
+ "deprecated. It will be unsupported in Zope X3.3. Use a "
+ "context keyword argument instead.",
+ DeprecationWarning, 2)
+ context = __factory_name
+ __factory_name, args = args[0], args[1:]
+ else:
+ context = kwargs.pop('context', None)
+
+ return getUtility(IFactory, __factory_name, context)(*args, **kwargs)
+
+def getFactoryInterfaces(name, context=None):
+ return getUtility(IFactory, name, context).getInterfaces()
+
+def getFactoriesFor(interface, context=None):
+ utils = getSiteManager(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
+
+
+# The following APIs provide registration support for Python code:
+
+def provideUtility(component, provides=None, name=u''):
+ if provides is None:
+ provides = list(providedBy(component))
+ if len(provides) == 1:
+ provides = provides[0]
+ else:
+ raise TypeError("Missing 'provides' argument")
+
+ getGlobalSiteManager().provideUtility(provides, component, name)
+
+
+def provideAdapter(factory, adapts=None, provides=None, name=''):
+ if provides is None:
+ provides = list(implementedBy(factory))
+ if len(provides) == 1:
+ provides = provides[0]
+ else:
+ raise TypeError("Missing 'provides' argument")
+
+ if adapts is None:
+ try:
+ adapts = factory.__component_adapts__
+ except AttributeError:
+ raise TypeError("Missing 'adapts' argument")
+
+ getGlobalSiteManager().provideAdapter(adapts, provides, name, factory)
+
+def provideSubscriptionAdapter(factory, adapts=None, provides=None):
+ if provides is None:
+ provides = list(implementedBy(factory))
+ if len(provides) == 1:
+ provides = provides[0]
+ else:
+ raise TypeError("Missing 'provides' argument")
+
+ if adapts is None:
+ try:
+ adapts = factory.__component_adapts__
+ except AttributeError:
+ raise TypeError("Missing 'adapts' argument")
+
+ getGlobalSiteManager().subscribe(adapts, provides, factory)
+
+def provideHandler(factory, adapts=None):
+
+ if adapts is None:
+ try:
+ adapts = factory.__component_adapts__
+ except AttributeError:
+ raise TypeError("Missing 'adapts' argument")
+
+ getGlobalSiteManager().subscribe(adapts, None, factory)
Added: trunk/gnue-navigator/src/external/zope/component/bbb/__init__.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/__init__.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/__init__.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,234 @@
+##############################################################################
+#
+# 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)
+
+
Added: trunk/gnue-navigator/src/external/zope/component/bbb/adapter.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/adapter.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/adapter.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,167 @@
+##############################################################################
+#
+# 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__
+ <class 'zope.component.bbb.adapter.O3'>
+
+ >>> registry.register((O1, O2), R1, '', O3)
+ >>> registry.queryMultiAdapter((O1(), O2()), R1, '').__class__
+ <class 'zope.component.bbb.adapter.O3'>
+ """
+ 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
Added: trunk/gnue-navigator/src/external/zope/component/bbb/contextdependent.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/contextdependent.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/contextdependent.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,27 @@
+##############################################################################
+#
+# 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
Added: trunk/gnue-navigator/src/external/zope/component/bbb/exceptions.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/exceptions.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/exceptions.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,24 @@
+##############################################################################
+#
+# 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"]
Added: trunk/gnue-navigator/src/external/zope/component/bbb/interfaces.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/interfaces.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/interfaces.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,343 @@
+##############################################################################
+#
+# 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.
+ """
Added: trunk/gnue-navigator/src/external/zope/component/bbb/service.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/service.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/service.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,172 @@
+##############################################################################
+#
+# 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)
+
Added: trunk/gnue-navigator/src/external/zope/component/bbb/servicenames.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/servicenames.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/servicenames.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,20 @@
+##############################################################################
+#
+# 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'
Added: trunk/gnue-navigator/src/external/zope/component/bbb/tests/__init__.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/tests/__init__.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/tests/__init__.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,3 @@
+# Make directory a package.
+
+__warn__ = True
Added: trunk/gnue-navigator/src/external/zope/component/bbb/tests/components.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/tests/components.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/tests/components.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,73 @@
+##############################################################################
+#
+# 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()
Added:
trunk/gnue-navigator/src/external/zope/component/bbb/tests/placelesssetup.py
===================================================================
---
trunk/gnue-navigator/src/external/zope/component/bbb/tests/placelesssetup.py
2006-03-30 02:24:05 UTC (rev 8286)
+++
trunk/gnue-navigator/src/external/zope/component/bbb/tests/placelesssetup.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,26 @@
+##############################################################################
+#
+# 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)
Added: trunk/gnue-navigator/src/external/zope/component/bbb/tests/request.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/tests/request.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/tests/request.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,43 @@
+##############################################################################
+#
+# 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
Added:
trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_adapter.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_adapter.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_adapter.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,43 @@
+##############################################################################
+#
+# 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
Added: trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_api.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_api.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_api.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,575 @@
+##############################################################################
+#
+# 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())
Added:
trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_service.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_service.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_service.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,153 @@
+##############################################################################
+#
+# 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')
Added:
trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_utilityservice.py
===================================================================
---
trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_utilityservice.py
2006-03-30 02:24:05 UTC (rev 8286)
+++
trunk/gnue-navigator/src/external/zope/component/bbb/tests/test_utilityservice.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,169 @@
+##############################################################################
+#
+# 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')
Added: trunk/gnue-navigator/src/external/zope/component/bbb/utility.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/bbb/utility.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/bbb/utility.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,72 @@
+##############################################################################
+#
+# 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
Added: trunk/gnue-navigator/src/external/zope/component/factory.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/factory.py 2006-03-30
02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/factory.py 2006-03-30
02:36:08 UTC (rev 8287)
@@ -0,0 +1,47 @@
+##############################################################################
+#
+# 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 29264 2005-02-23 21:44:09Z srichter $
+"""
+from gnue.navigator.external.zope.interface import implements, implementedBy
+from gnue.navigator.external.zope.interface.declarations import Implements
+from gnue.navigator.external.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
+ return implementedBy(self._callable)
+
+ def __repr__(self):
+ return '<%s for %s>' %(self.__class__.__name__, `self._callable`)
Added: trunk/gnue-navigator/src/external/zope/component/factory.txt
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/factory.txt
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/factory.txt
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,132 @@
+=========
+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__
+ <class 'Klass'>
+
+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)
+ [<InterfaceClass __builtin__.IKlass>]
+
+ >>> implemented2 = factory2.getInterfaces()
+ >>> list(implemented2)
+ []
+
+ >>> implemented3 = factory3.getInterfaces()
+ >>> list(implemented3)
+ [<InterfaceClass __builtin__.IFunction>]
+
+
+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]
+ [<InterfaceClass __builtin__.IKlass>]
+
+List of All Factories
++++++++++++++++++++++
+
+ >>> [(name, fac.__class__) for name, fac in
+ ... zope.component.getFactoriesFor(IKlass)]
+ [(u'klass', <class 'zope.component.factory.Factory'>)]
+
Added: trunk/gnue-navigator/src/external/zope/component/interfaces.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/interfaces.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/interfaces.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,456 @@
+############################################################################
+#
+# 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 37531 2005-07-28 14:02:49Z anguenot $
+"""
+import zope.deprecation
+
+from gnue.navigator.external.zope.interface import Interface, Attribute
+
+# BBB: Can be removed in 3.3
+zope.deprecation.__show__.off()
+from gnue.navigator.external.zope.exceptions import NotFoundError
+zope.deprecation.__show__.on()
+
+# BBB: Backward-compatibility; 12/05/2004
+from bbb.interfaces import *
+
+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."""
+
+class IComponentArchitecture(Interface, IBBBComponentArchitecture):
+ """The Component Architecture is defined by two key components: Adapters
+ and Utiltities. Both are managed by site managers. All other components
+ build on top of them.
+ """
+ # Site Manager API
+
+ def getGlobalSiteManager():
+ """Return the global site manager.
+
+ This function should never fail and always return an object that
+ provides `IGlobalSiteManager`.
+ """
+
+ def getSiteManager(context=None):
+ """Get the nearest site manager in the given context.
+
+ If `context` is `None`, return the global site manager.
+
+ If the `context` is not `None`, it is expected that an adapter from
+ the `context` to `ISiteManager` can be found. If no adapter is found,
+ a `ComponentLookupError` is raised.
+ """
+
+ # Utility API
+
+ 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 overridden utilities.
+
+ An iterable of utility instances is returned. No names are
+ returned.
+ """
+
+ # Adapter API
+
+ def getAdapter(object, interface=Interface, name=u'', context=None):
+ """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=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=Interface, name=u'', 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=Interface, name=u'', 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 getAdapters(objects, provided, context=None):
+ """Look for all matching adapters to a provided interface for objects
+
+ Return a list of adapters that match. If an adapter is named, only the
+ most specific adapter of a given name is returned.
+
+ 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 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.
+ """
+
+ def handle(*objects):
+ """Call all of the handlers for the given objects
+
+ 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.
+
+ """
+
+
+ def adapts(*interfaces):
+ """Declare that a class adapts the given interfaces.
+
+ This function can only be used in a class definition.
+
+ (TODO, allow classes to be passed as well as interfaces.)
+ """
+
+ # Factory service
+
+ def createObject(factory_name, *args, **kwargs):
+ """Create an object using a factory
+
+ Finds the named factory in the current site and calls it with
+ the given arguments. If a matching factory cannot be found
+ raises ComponentLookupError. Returns the created object.
+
+ A context keyword argument can be provided to cause the
+ factory to be looked up in a location other than the current
+ site. (Of course, this means that it is impossible to pass a
+ keyword argument named "context" to the factory.
+ """
+
+ 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.
+ """
+
+
+class ISiteManager(Interface):
+ """Component Manager for a Site
+
+ This object manages the components registered at a particular site. The
+ definition of a site is intentionally vague.
+ """
+
+ adapters = Attribute("Adapter Registry to manage all registered "
+ "adapters.")
+
+ utilities = Attribute("Adapter Registry to manage all registered "
+ "utilities.")
+
+ 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 getAdapters(objects, provided):
+ """Look for all matching adapters to a provided interface for objects
+
+ Return a list of adapters that match. If an adapter is named, only the
+ most specific adapter of a given name is returned.
+ """
+
+ 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.
+ """
+
+ 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 overridden utilities.
+
+ An iterable of utility instances is returned. No names are
+ returned.
+ """
+
+
+class IComponentRegistrationConvenience(Interface):
+ """API for registering components.
+
+ 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.
+ """
+
+ def provideUtility(component, provides=None, name=u''):
+ """Register a utility globally
+
+ A utility is registered to provide an interface with a
+ name. If a component provides only one interface, then the
+ provides argument can be omitted and the provided interface
+ will be used. (In this case, provides argument can still be
+ provided to provide a less specific interface.)
+
+ 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.
+
+ """
+
+ def provideAdapter(factory, adapts=None, provides=None, name=u''):
+ """Register an adapter globally
+
+ An adapter is registered to provide an interface with a name
+ for some number of object types. If a factory implements only
+ one interface, then the provides argument can be omitted and
+ the provided interface will be used. (In this case, a provides
+ argument can still be provided to provide a less specific
+ interface.)
+
+ If the factory has an adapts declaration, then the adapts
+ argument can be omitted and the declaration will be used. (An
+ adapts argument can be provided to override the declaration.)
+
+ 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.
+ """
+
+ def provideSubscriptionAdapter(factory, adapts=None, provides=None):
+ """Register a subscription adapter
+
+ A subscription adapter is registered to provide an interface
+ for some number of object types. If a factory implements only
+ one interface, then the provides argument can be omitted and
+ the provided interface will be used. (In this case, a provides
+ argument can still be provided to provide a less specific
+ interface.)
+
+ If the factory has an adapts declaration, then the adapts
+ argument can be omitted and the declaration will be used. (An
+ adapts argument can be provided to override the declaration.)
+
+ 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.
+ """
+
+ def provideHandler(handler, adapts=None):
+ """Register a handler
+
+ 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.
+
+ If the handler has an adapts declaration, then the adapts
+ argument can be omitted and the declaration will be used. (An
+ adapts argument can be provided to override the declaration.)
+
+ 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.
+ """
+
+class IRegistry(Interface):
+ """Object that supports component registry
+ """
+
+ def registrations():
+ """Return an iterable of component registrations
+ """
+
+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.
+ """
Added: trunk/gnue-navigator/src/external/zope/component/site.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/site.py 2006-03-30
02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/site.py 2006-03-30
02:36:08 UTC (rev 8287)
@@ -0,0 +1,346 @@
+##############################################################################
+#
+# 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 gnue.navigator.external.zope.interface import implements, providedBy,
implementedBy, declarations
+from gnue.navigator.external.zope.interface.adapter import AdapterRegistry
+from gnue.navigator.external.zope.interface.interfaces import IInterface
+
+from gnue.navigator.external.zope.component.interfaces import ISiteManager,
IRegistry
+from gnue.navigator.external.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 gnue.navigator.external.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__
+ <class 'zope.component.site.O3'>
+
+ >>> registry.provideAdapter((O1, O2), R1, '', O3)
+ >>> registry.queryMultiAdapter((O1(), O2()), R1, '').__class__
+ <class 'zope.component.site.O3'>
+ """
+ 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 gnue.navigator.external.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 gnue.navigator.external.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__())
+
Added: trunk/gnue-navigator/src/external/zope/component/socketexample.txt
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/socketexample.txt
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/socketexample.txt
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,600 @@
+==================================================
+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 '<instance of %s>' %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: (<instance of CzechSocket>,
+ <InterfaceClass __builtin__.IUSSocket>,
+ '')
+
+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: (<instance of GermanSocket>,
+ <InterfaceClass __builtin__.IUSSocket>,
+ '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 '<instance of Grounder>'
+
+
+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: ((<instance of GermanSocket>,
+ <instance of Grounder>),
+ <InterfaceClass __builtin__.IUSGroundedSocket>,
+ '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 '<instance of Generator>'
+
+ >>> 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: (<InterfaceClass __builtin__.IGermanSocket>, '')
+
+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 '<instance of Solar Panel>'
+
+ >>> 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: (<InterfaceClass __builtin__.IUSSocket>, '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'', <instance of Generator>),
+ (u'Solar Panel', <instance of 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
+ [<instance of Generator>, <instance of Solar Panel>]
+
+
+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', <class 'zope.component.factory.Factory'>),
+ (u'SolarPanel', <class 'zope.component.factory.Factory'>)]
+
+
+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`.
+
+
Added: trunk/gnue-navigator/src/external/zope/component/testing.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/testing.py 2006-03-30
02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/testing.py 2006-03-30
02:36:08 UTC (rev 8287)
@@ -0,0 +1,34 @@
+##############################################################################
+#
+# 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 gnue.navigator.external.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()
Added: trunk/gnue-navigator/src/external/zope/component/tests.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/component/tests.py 2006-03-30
02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/component/tests.py 2006-03-30
02:36:08 UTC (rev 8287)
@@ -0,0 +1,634 @@
+##############################################################################
+#
+# 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 gnue.navigator.external.zope.interface import Interface, implements
+from gnue.navigator.external.zope.interface.verify import verifyObject
+from gnue.navigator.external.zope.testing import doctest
+
+import zope.component
+from gnue.navigator.external.zope.component.interfaces import
ComponentLookupError
+from gnue.navigator.external.zope.component.interfaces import
IComponentArchitecture
+from gnue.navigator.external.zope.component.interfaces import ISiteManager
+from gnue.navigator.external.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 '<instance Ob>'
+
+
+ob = Ob()
+
+class Ob2(object):
+ implements(I2)
+ def __repr__(self):
+ return '<instance Ob2>'
+
+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 gnue.navigator.external.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', <instance Ob>,
+ <InterfaceClass zope.component.interfaces.ISiteManager>)
+ """
+
+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 '''<Component implementing 'I1'>'''
+
+ >>> 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 gnue.navigator.external.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)
+ <Component implementing 'I1'>
+ >>> zope.component.queryAdapterInContext(ob, I1, context)
+ <Component implementing 'I1'>
+
+ 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: (<Component implementing 'I1'>,
+ <InterfaceClass zope.component.tests.I4>)
+
+ ...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: (<instance Ob>,
+ <InterfaceClass zope.component.tests.I2>,
+ '')
+
+ ...otherwise, you get the default
+
+ >>> zope.component.queryAdapter(ob, I2, '', '<default>')
+ '<default>'
+
+ 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', <instance Ob2>,
+ <InterfaceClass zope.component.tests.I1>)
+
+ ...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:
+ (<instance Ob>, <InterfaceClass zope.component.tests.I2>, 'bar')
+
+ ...otherwise, you get the default
+
+ >>> zope.component.queryAdapter(ob, I2, 'bar', '<default>')
+ '<default>'
+
+ 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:
+ ((<instance Ob>, <instance Ob2>),
+ <InterfaceClass zope.component.tests.I3>,
+ u'')
+
+ ...otherwise, you get the default
+
+ >>> zope.component.queryMultiAdapter((ob, ob2), I3, default='<default>')
+ '<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: \
+ (<InterfaceClass zope.component.tests.I1>, '')
+
+ ...otherwise, you get the default
+
+ >>> zope.component.queryUtility(I1, default='<default>')
+ '<default>'
+ >>> zope.component.queryUtility(I2, default='<default>')
+ '<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:
+ (<InterfaceClass zope.component.tests.I1>, 'foo')
+
+
+ ...otherwise, you get the default
+
+ >>> zope.component.queryUtility(I1, name='foo', default='<default>')
+ '<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',
+ <instance Ob>,
+ <InterfaceClass zope.component.tests.I2>)
+
+
+ >>> 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 gnue.navigator.external.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 gnue.navigator.external.zope.component.bbb.tests import placelesssetup
Added: trunk/gnue-navigator/src/external/zope/deprecation/DEPENDENCIES.cfg
===================================================================
--- trunk/gnue-navigator/src/external/zope/deprecation/DEPENDENCIES.cfg
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/deprecation/DEPENDENCIES.cfg
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1 @@
+zope.testing
Added: trunk/gnue-navigator/src/external/zope/deprecation/README.txt
===================================================================
--- trunk/gnue-navigator/src/external/zope/deprecation/README.txt
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/deprecation/README.txt
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,187 @@
+===============
+Deprecation API
+===============
+
+When we started working on Zope 3.1, we noticed that the hardest part of the
+development process was to ensure backward-compatibility and correctly mark
+deprecated modules, classes, functions, methods and properties. This module
+provides a simple function called `deprecated(names, reason)` to deprecate the
+previously mentioned Python objects.
+
+Let's start with a demonstration of deprecating any name inside a module. To
+demonstrate the functionality, I have placed the following code inside the
+`tests.py` file of this package:
+
+ from zope.deprecation import deprecated
+ demo1 = 1
+ deprecated('demo1', 'demo1 is no more.')
+
+ demo2 = 2
+ deprecated('demo2', 'demo2 is no more.')
+
+ demo3 = 3
+ deprecated('demo3', 'demo3 is no more.')
+
+The first argument to the `deprecated()` function is a list of names that
+should be declared deprecated. If the first argument is a string, it is
+interpreted as one name. The second argument is the reason the particular name
+has been deprecated. It is good practice to also list the version in which the
+name will be removed completely.
+
+Let's now see how the deprecation warnings are displayed.
+
+ >>> from zope.deprecation import tests
+ >>> tests.demo1
+ From tests.py's showwarning():
+ ...README.txt:1: DeprecationWarning: demo1: demo1 is no more.
+ ...
+ 1
+
+ >>> import zope.deprecation.tests
+ >>> zope.deprecation.tests.demo2
+ From tests.py's showwarning():
+ ...README.txt:1: DeprecationWarning: demo2: demo2 is no more.
+ ...
+ 2
+
+You can see that merely importing the affected module or one of its parents
+does not cause a deprecation warning. Only when we try to access the name in
+the module, we get a deprecation warning. On the other hand, if we import the
+name directly, the deprecation warning will be raised immediately.
+
+ >>> from zope.deprecation.tests import demo3
+ From tests.py's showwarning():
+ ...README.txt:1: DeprecationWarning: demo3: demo3 is no more.
+ ...
+
+Also, once a deprecation warning has been displayed, it is not shown again:
+
+ >>> from zope.deprecation import tests
+ >>> tests.demo1
+ 1
+
+Deprecation can also happen inside a function. When we first access
+``demo4``, it can be accessed without problems, then we call a
+function that sets the deprecation message and we get the message upon
+the next access:
+
+ >>> tests.demo4
+ 4
+ >>> tests.deprecatedemo4()
+ >>> tests.demo4
+ From tests.py's showwarning():
+ ...README.txt:1: DeprecationWarning: demo4: demo4 is no more.
+ ...
+ 4
+
+New let's see how properties and methods can be deprecated. We are going to
+use the same function as before, except that this time, we do not pass in names
+as first argument, but the method or attribute itself. The function then
+returns a wrapper that sends out a deprecation warning when the attribute or
+method is accessed.
+
+ >>> from zope.deprecation import deprecation
+ >>> class MyComponent(object):
+ ... foo = property(lambda self: 1)
+ ... foo = deprecation.deprecated(foo, 'foo is no more.')
+ ...
+ ... bar = 2
+ ...
+ ... def blah(self):
+ ... return 3
+ ... blah = deprecation.deprecated(blah, 'blah() is no more.')
+ ...
+ ... def splat(self):
+ ... return 4
+
+And here is the result:
+
+ >>> my = MyComponent()
+ >>> my.foo
+ From tests.py's showwarning():
+ ...README.txt:1: DeprecationWarning: foo is no more.
+ ...
+ 1
+ >>> my.bar
+ 2
+ >>> my.blah()
+ From tests.py's showwarning():
+ ...README.txt:1: DeprecationWarning: blah() is no more.
+ ...
+ 3
+ >>> my.splat()
+ 4
+
+
+Temporarily Turning Off Deprecation Warnings
+--------------------------------------------
+
+In some cases it is desireable to turn off the deprecation warnings for a
+short time. To support such a feature, the `zope.deprecation` package provides
+an attribute called `__show__`. One can ask for its status by calling it:
+
+ >>> from zope.deprecation import __show__
+ >>> __show__()
+ True
+
+ >>> class Foo(object):
+ ... bar = property(lambda self: 1)
+ ... bar = deprecation.deprecated(bar, 'bar is no more.')
+ ... blah = property(lambda self: 1)
+ ... blah = deprecation.deprecated(blah, 'blah is no more.')
+ >>> foo = Foo()
+
+ >>> foo.bar
+ From tests.py's showwarning():
+ ...README.txt:1: DeprecationWarning: bar is no more.
+ ...
+ 1
+
+You can turn off the depraction warnings using
+
+ >>> __show__.off()
+ >>> __show__()
+ False
+
+ >>> foo.blah
+ 1
+
+Now, you can also nest several turn-offs, so that calling `off()` multiple
+times is meaningful:
+
+ >>> __show__.stack
+ [False]
+
+ >>> __show__.off()
+ >>> __show__.stack
+ [False, False]
+
+ >>> __show__.on()
+ >>> __show__.stack
+ [False]
+ >>> __show__()
+ False
+
+ >>> __show__.on()
+ >>> __show__.stack
+ []
+ >>> __show__()
+ True
+
+You can also reset `__show__` to `True`:
+
+ >>> __show__.off()
+ >>> __show__.off()
+ >>> __show__()
+ False
+
+ >>> __show__.reset()
+ >>> __show__()
+ True
+
+Finally, you cannot call `on()` without having called `off()` before:
+
+ >>> __show__.on()
+ Traceback (most recent call last):
+ ...
+ IndexError: pop from empty list
Added: trunk/gnue-navigator/src/external/zope/deprecation/__init__.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/deprecation/__init__.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/deprecation/__init__.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,26 @@
+##############################################################################
+#
+# Copyright (c) 2005 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.
+#
+##############################################################################
+"""Deprecation Package
+
+$Id: __init__.py 37507 2005-07-27 22:48:36Z anguenot $
+"""
+__docformat__ = "reStructuredText"
+
+from gnue.navigator.external.zope.deprecation.deprecation import deprecated,
ShowSwitch
+
+# This attribute can be used to temporarly deactivate deprecation
+# warnings, so that backward-compatibility code can import other
+# backward-compatiblity components without warnings being produced.
+
+__show__ = ShowSwitch()
Added: trunk/gnue-navigator/src/external/zope/deprecation/deprecation.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/deprecation/deprecation.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/deprecation/deprecation.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,153 @@
+##############################################################################
+#
+# Copyright (c) 2005 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.
+#
+##############################################################################
+"""Deprecation Support
+
+This module provides utilities to ease the development of backward-compatible
+code.
+
+$Id: deprecation.py 65511 2006-02-27 05:24:24Z philikon $
+"""
+__docformat__ = "reStructuredText"
+import sys
+import types
+import warnings
+
+import zope.deprecation
+
+
+class ShowSwitch(object):
+ """Simple stack-based switch."""
+
+ def __init__(self):
+ self.stack = []
+
+ def on(self):
+ self.stack.pop()
+
+ def off(self):
+ self.stack.append(False)
+
+ def reset(self):
+ self.stack = []
+
+ def __call__(self):
+ return self.stack == []
+
+ def __repr__(self):
+ return '<ShowSwitch %s>' %(self() and 'on' or 'off')
+
+
+ogetattr = object.__getattribute__
+class DeprecationProxy(object):
+
+ def __init__(self, module):
+ self.__original_module = module
+ self.__deprecated = {}
+
+ def deprecate(self, names, message):
+ """Deprecate the given names."""
+ if not isinstance(names, (tuple, list)):
+ names = (names,)
+ for name in names:
+ self.__deprecated[name] = message
+
+ def __getattribute__(self, name):
+ if name == 'deprecate' or name.startswith('_DeprecationProxy__'):
+ return ogetattr(self, name)
+
+ if name == '__class__':
+ return types.ModuleType
+
+ if name in ogetattr(self, '_DeprecationProxy__deprecated'):
+ if zope.deprecation.__show__():
+ warnings.warn(
+ name + ': ' + self.__deprecated[name],
+ DeprecationWarning, 2)
+
+ return getattr(ogetattr(self, '_DeprecationProxy__original_module'),
+ name)
+
+ def __setattr__(self, name, value):
+ if name.startswith('_DeprecationProxy__'):
+ return object.__setattr__(self, name, value)
+
+ setattr(self.__original_module, name, value)
+
+ def __delattr__(self, name):
+ if name.startswith('_DeprecationProxy__'):
+ return object.__delattr__(self, name)
+
+ delattr(self.__original_module, name)
+
+
+class DeprecatedGetProperty(object):
+
+ def __init__(self, prop, message):
+ self.message = message
+ self.prop = prop
+
+ def __get__(self, inst, klass):
+ if zope.deprecation.__show__():
+ warnings.warn(self.message, DeprecationWarning, 2)
+ return self.prop.__get__(inst, klass)
+
+class DeprecatedGetSetProperty(DeprecatedGetProperty):
+
+ def __set__(self, inst, prop):
+ if zope.deprecation.__show__():
+ warnings.warn(self.message, DeprecationWarning, 2)
+ self.prop.__set__(inst, prop)
+
+class DeprecatedGetSetDeleteProperty(DeprecatedGetSetProperty):
+
+ def __delete__(self, inst):
+ if zope.deprecation.__show__():
+ warnings.warn(self.message, DeprecationWarning, 2)
+ self.prop.__delete__(inst)
+
+def DeprecatedMethod(method, message):
+
+ def deprecated_method(self, *args, **kw):
+ if zope.deprecation.__show__():
+ warnings.warn(message, DeprecationWarning, 2)
+ return method(self, *args, **kw)
+
+ return deprecated_method
+
+
+def deprecated(specifier, message):
+ """Deprecate the given names."""
+
+ # We are inside a module
+ if isinstance(specifier, (str, unicode, list, tuple)):
+ globals = sys._getframe(1).f_globals
+ modname = globals['__name__']
+
+ if not isinstance(sys.modules[modname], DeprecationProxy):
+ sys.modules[modname] = DeprecationProxy(sys.modules[modname])
+ sys.modules[modname].deprecate(specifier, message)
+
+
+ # ... that means the specifier is a method or attribute of the class
+ if isinstance(specifier, types.FunctionType):
+ return DeprecatedMethod(specifier, message)
+ else:
+ prop = specifier
+ if hasattr(prop, '__get__') and hasattr(prop, '__set__') and \
+ hasattr(prop, '__delete__'):
+ return DeprecatedGetSetDeleteProperty(prop, message)
+ elif hasattr(prop, '__get__') and hasattr(prop, '__set__'):
+ return DeprecatedGetSetProperty(prop, message)
+ elif hasattr(prop, '__get__'):
+ return DeprecatedGetProperty(prop, message)
Added: trunk/gnue-navigator/src/external/zope/deprecation/tests.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/deprecation/tests.py 2006-03-30
02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/deprecation/tests.py 2006-03-30
02:36:08 UTC (rev 8287)
@@ -0,0 +1,60 @@
+##############################################################################
+#
+# 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: tests.py 65511 2006-02-27 05:24:24Z philikon $
+"""
+import sys
+import unittest
+import warnings
+from gnue.navigator.external.zope.testing import doctest
+
+# Used in doctests
+from deprecation import deprecated
+demo1 = 1
+deprecated('demo1', 'demo1 is no more.')
+
+demo2 = 2
+deprecated('demo2', 'demo2 is no more.')
+
+demo3 = 3
+deprecated('demo3', 'demo3 is no more.')
+
+demo4 = 4
+def deprecatedemo4():
+ """Demonstrate that deprecate() also works in a local scope."""
+ deprecated('demo4', 'demo4 is no more.')
+
+orig_showwarning = warnings.showwarning
+
+def showwarning(message, category, filename, lineno, file=None):
+ sys.stdout.write("From tests.py's showwarning():\n")
+ sys.stdout.write(
+ warnings.formatwarning(message, category, filename, lineno))
+
+def setUp(test):
+ warnings.showwarning = showwarning
+
+def tearDown(test):
+ warnings.showwarning = orig_showwarning
+
+def test_suite():
+ return unittest.TestSuite((
+ doctest.DocFileSuite('README.txt',
+ setUp=setUp, tearDown=tearDown,
+ optionflags=doctest.ELLIPSIS),
+ ))
+
+if __name__ == "__main__":
+ unittest.main(defaultTest='test_suite')
Added: trunk/gnue-navigator/src/external/zope/exceptions/DEPENDENCIES.cfg
===================================================================
--- trunk/gnue-navigator/src/external/zope/exceptions/DEPENDENCIES.cfg
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/exceptions/DEPENDENCIES.cfg
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,3 @@
+zope.interface
+zope.testing
+zope.deprecation
Added: trunk/gnue-navigator/src/external/zope/exceptions/__init__.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/exceptions/__init__.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/exceptions/__init__.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,54 @@
+##############################################################################
+#
+# 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.
+#
+##############################################################################
+"""General exceptions that wish they were standard exceptions
+
+These exceptions are so general purpose that they don't belong in Zope
+application-specific packages.
+
+$Id: __init__.py 37531 2005-07-28 14:02:49Z anguenot $
+"""
+
+import zope.deprecation
+
+zope.deprecation.deprecated('INotFoundError',
+ 'This interface has been deprecated. '
+ 'Use standard interface instead '
+ 'The reference will be gone in 3.3')
+
+zope.deprecation.deprecated('NotFoundError',
+ 'This class has been deprecated. '
+ 'Use standard exceptions instead '
+ 'The reference will be gone in 3.3')
+
+# Turn of deprecation warning here for the above import that are here for BBB
+# The depreaction above and within the _notfounderror module will do the job.
+zope.deprecation.__show__.off()
+from gnue.navigator.external.zope.exceptions._notfounderror import
NotFoundError, INotFoundError
+zope.deprecation.__show__.on()
+
+from gnue.navigator.external.zope.exceptions._duplicate import
DuplicationError, IDuplicationError
+
+# Importing these interfaces from here is deprecated!
+
+# avoid depency on zope.security:
+try:
+ import zope.security
+except ImportError, v:
+ # "ImportError: No module named security"
+ if not str(v).endswith(' security'):
+ raise
+else:
+ from gnue.navigator.external.zope.security.interfaces import
IUnauthorized, Unauthorized
+ from gnue.navigator.external.zope.security.interfaces import IForbidden,
IForbiddenAttribute
+ from gnue.navigator.external.zope.security.interfaces import Forbidden,
ForbiddenAttribute
Added: trunk/gnue-navigator/src/external/zope/exceptions/_duplicate.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/exceptions/_duplicate.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/exceptions/_duplicate.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,25 @@
+##############################################################################
+#
+# 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.
+#
+##############################################################################
+"""Duplication Error
+
+$Id: _duplicate.py 26795 2004-07-27 15:15:58Z jim $
+"""
+from gnue.navigator.external.zope.interface import implements, Interface
+
+class IDuplicationError(Interface):
+ pass
+
+class DuplicationError(Exception):
+ """A duplicate registration was attempted"""
+ implements(IDuplicationError)
Added: trunk/gnue-navigator/src/external/zope/exceptions/_notfounderror.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/exceptions/_notfounderror.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/exceptions/_notfounderror.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,48 @@
+##############################################################################
+#
+# 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.
+#
+##############################################################################
+"""Not Found Error
+
+$Id: _notfounderror.py 40520 2005-12-03 15:44:57Z benji_york $
+"""
+
+from gnue.navigator.external.zope.deprecation import deprecated
+
+from gnue.navigator.external.zope.interface.common.interfaces import IKeyError
+from gnue.navigator.external.zope.interface import implements
+
+deprecated('INotFoundError',
+ 'This interface has been deprecated. '
+ 'Use standard interface instead '
+ 'The reference will be gone in 3.3')
+
+deprecated('NotFoundError',
+ 'This class has been deprecated. '
+ 'Use standard exceptions instead '
+ 'The reference will be gone in 3.3')
+
+class INotFoundError(IKeyError):
+ pass
+
+class NotFoundError(KeyError, LookupError):
+ """A resource could not be found.
+
+ This exception is deprecated. It will, over time, be replaced
+ with more specific exception types.
+
+ Eventually, when this exception type is used as a base class, it
+ will become an alias for LookupError. Client code should not depend
+ on it extnding KeyError.
+
+ """
+ implements(INotFoundError)
Added: trunk/gnue-navigator/src/external/zope/exceptions/exceptionformatter.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/exceptions/exceptionformatter.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/exceptions/exceptionformatter.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,240 @@
+##############################################################################
+#
+# 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.
+#
+##############################################################################
+"""An exception formatter that shows traceback supplements and traceback info,
+optionally in HTML.
+
+$Id: exceptionformatter.py 41359 2006-01-19 04:36:59Z shane $
+"""
+import sys
+import cgi
+import linecache
+import traceback
+
+DEBUG_EXCEPTION_FORMATTER = 1
+
+class TextExceptionFormatter(object):
+
+ line_sep = '\n'
+ show_revisions = 0
+
+ def __init__(self, limit=None, with_filenames=False):
+ self.limit = limit
+ self.with_filenames = with_filenames
+
+ def escape(self, s):
+ return s
+
+ def getPrefix(self):
+ return 'Traceback (most recent call last):'
+
+ def getLimit(self):
+ limit = self.limit
+ if limit is None:
+ limit = getattr(sys, 'tracebacklimit', 200)
+ return limit
+
+ def formatSupplementLine(self, line):
+ return ' - %s' % line
+
+ def formatSourceURL(self, url):
+ return [self.formatSupplementLine(url)]
+
+ def formatSupplement(self, supplement, tb):
+ result = []
+ fmtLine = self.formatSupplementLine
+
+ url = getattr(supplement, 'source_url', None)
+ if url is not None:
+ result.extend(self.formatSourceURL(url))
+
+ line = getattr(supplement, 'line', 0)
+ if line == -1:
+ line = tb.tb_lineno
+ col = getattr(supplement, 'column', -1)
+ if line:
+ if col is not None and col >= 0:
+ result.append(fmtLine('Line %s, Column %s' % (
+ line, col)))
+ else:
+ result.append(fmtLine('Line %s' % line))
+ elif col is not None and col >= 0:
+ result.append(fmtLine('Column %s' % col))
+
+ expr = getattr(supplement, 'expression', None)
+ if expr:
+ result.append(fmtLine('Expression: %s' % expr))
+
+ warnings = getattr(supplement, 'warnings', None)
+ if warnings:
+ for warning in warnings:
+ result.append(fmtLine('Warning: %s' % warning))
+
+ getInfo = getattr(supplement, 'getInfo', None)
+ if getInfo is not None:
+ try:
+ extra = getInfo()
+ if extra:
+ extra = self.escape(extra)
+ if self.line_sep != "\n":
+ extra = extra.replace(" ", " ")
+ extra = extra.replace("\n", self.line_sep)
+ result.append(extra)
+ except:
+ if DEBUG_EXCEPTION_FORMATTER:
+ import traceback
+ traceback.print_exc()
+ # else just swallow the exception.
+ return result
+
+ def formatTracebackInfo(self, tbi):
+ return self.formatSupplementLine('__traceback_info__: %s' % (tbi, ))
+
+ def formatLine(self, tb):
+ f = tb.tb_frame
+ lineno = tb.tb_lineno
+ co = f.f_code
+ filename = co.co_filename
+ name = co.co_name
+ locals = f.f_locals
+ globals = f.f_globals
+
+ if self.with_filenames:
+ s = ' File "%s", line %d' % (filename, lineno)
+ else:
+ modname = globals.get('__name__', filename)
+ s = ' Module %s, line %d' % (modname, lineno)
+
+ s = s + ', in %s' % name
+
+ result = []
+ result.append(self.escape(s))
+
+ # Append the source line, if available
+ line = linecache.getline(filename, lineno)
+ if line:
+ result.append(" " + self.escape(line.strip()))
+
+ # Output a traceback supplement, if any.
+ if '__traceback_supplement__' in locals:
+ # Use the supplement defined in the function.
+ tbs = locals['__traceback_supplement__']
+ elif '__traceback_supplement__' in globals:
+ # Use the supplement defined in the module.
+ # This is used by Scripts (Python).
+ tbs = globals['__traceback_supplement__']
+ else:
+ tbs = None
+ if tbs is not None:
+ factory = tbs[0]
+ args = tbs[1:]
+ try:
+ supp = factory(*args)
+ result.extend(self.formatSupplement(supp, tb))
+ except:
+ if DEBUG_EXCEPTION_FORMATTER:
+ traceback.print_exc()
+ # else just swallow the exception.
+
+ try:
+ tbi = locals.get('__traceback_info__', None)
+ if tbi is not None:
+ result.append(self.formatTracebackInfo(tbi))
+ except:
+ if DEBUG_EXCEPTION_FORMATTER:
+ traceback.print_exc()
+ # else just swallow the exception.
+
+ return self.line_sep.join(result)
+
+ def formatExceptionOnly(self, etype, value):
+ return self.line_sep.join(
+ traceback.format_exception_only(etype, value))
+
+ def formatLastLine(self, exc_line):
+ return self.escape(exc_line)
+
+ def formatException(self, etype, value, tb):
+ # The next line provides a way to detect recursion.
+ __exception_formatter__ = 1
+ result = [self.getPrefix() + '\n']
+ limit = self.getLimit()
+ n = 0
+ while tb is not None and (limit is None or n < limit):
+ if tb.tb_frame.f_locals.get('__exception_formatter__'):
+ # Stop recursion.
+ result.append('(Recursive formatException() stopped)\n')
+ break
+ line = self.formatLine(tb)
+ result.append(line + '\n')
+ tb = tb.tb_next
+ n = n + 1
+ exc_line = self.formatExceptionOnly(etype, value)
+ result.append(self.formatLastLine(exc_line))
+ return result
+
+
+class HTMLExceptionFormatter(TextExceptionFormatter):
+
+ line_sep = '<br />\r\n'
+
+ def escape(self, s):
+ return cgi.escape(s)
+
+ def getPrefix(self):
+ return '<p>Traceback (most recent call last):\r\n<ul>'
+
+ def formatSupplementLine(self, line):
+ return '<b>%s</b>' % self.escape(str(line))
+
+ def formatTracebackInfo(self, tbi):
+ s = self.escape(str(tbi))
+ s = s.replace('\n', self.line_sep)
+ return '__traceback_info__: %s' % (s, )
+
+ def formatLine(self, tb):
+ line = TextExceptionFormatter.formatLine(self, tb)
+ return '<li>%s</li>' % line
+
+ def formatLastLine(self, exc_line):
+ return '</ul>%s</p>' % self.escape(exc_line)
+
+
+def format_exception(t, v, tb, limit=None, as_html=False,
+ with_filenames=False):
+ """Format a stack trace and the exception information.
+
+ Similar to 'traceback.format_exception', but adds supplemental
+ information to the traceback and accepts two options, 'as_html'
+ and 'with_filenames'.
+ """
+ if as_html:
+ fmt = HTMLExceptionFormatter(limit, with_filenames)
+ else:
+ fmt = TextExceptionFormatter(limit, with_filenames)
+ return fmt.formatException(t, v, tb)
+
+
+def print_exception(t, v, tb, limit=None, file=None, as_html=False,
+ with_filenames=True):
+ """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
+
+ Similar to 'traceback.print_exception', but adds supplemental
+ information to the traceback and accepts two options, 'as_html'
+ and 'with_filenames'.
+ """
+ if file is None:
+ file = sys.stderr
+ lines = format_exception(t, v, tb, limit, as_html, with_filenames)
+ for line in lines:
+ file.write(line)
Added: trunk/gnue-navigator/src/external/zope/exceptions/interfaces.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/exceptions/interfaces.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/exceptions/interfaces.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,97 @@
+##############################################################################
+#
+# 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.
+#
+##############################################################################
+"""ITracebackSupplement interface definition.
+
+$Id: interfaces.py 41470 2006-01-27 23:31:30Z shane $
+
+When zope.exceptionformatter generates a traceback, it looks for local
+variables named __traceback_info__ or __traceback_supplement__. It
+includes the information provided by those local variables in the
+traceback.
+
+__traceback_info__ is for arbitrary information.
+repr(__traceback_info__) gets dumped to the traceback.
+
+__traceback_supplement__ is more structured. It should be a tuple.
+The first item of the tuple is a callable that produces an object that
+implements ITracebackSupplement, and the rest of the tuple contains
+arguments to pass to the factory. The traceback formatter makes an
+effort to clearly present the information provided by the
+ITracebackSupplement.
+"""
+
+
+from gnue.navigator.external.zope.interface import Interface, Attribute
+
+class ITracebackSupplement(Interface):
+ """Provides valuable information to supplement an exception traceback.
+
+ The interface is geared toward providing meaningful feedback when
+ exceptions occur in user code written in mini-languages like
+ Zope page templates and restricted Python scripts.
+ """
+
+ source_url = Attribute(
+ 'source_url',
+ """Optional. Set to URL of the script where the exception occurred.
+
+ Normally this generates a URL in the traceback that the user
+ can visit to manage the object. Set to None if unknown or
+ not available.
+ """
+ )
+
+ line = Attribute(
+ 'line',
+ """Optional. Set to the line number (>=1) where the exception
+ occurred.
+
+ Set to 0 or None if the line number is unknown.
+ """
+ )
+
+ column = Attribute(
+ 'column',
+ """Optional. Set to the column offset (>=0) where the exception
+ occurred.
+
+ Set to None if the column number is unknown.
+ """
+ )
+
+ expression = Attribute(
+ 'expression',
+ """Optional. Set to the expression that was being evaluated.
+
+ Set to None if not available or not applicable.
+ """
+ )
+
+ warnings = Attribute(
+ 'warnings',
+ """Optional. Set to a sequence of warning messages.
+
+ Set to None if not available, not applicable, or if the exception
+ itself provides enough information.
+ """
+ )
+
+
+ def getInfo(as_html=0):
+ """Optional. Returns a string containing any other useful info.
+
+ If as_html is set, the implementation must HTML-quote the result
+ (normally using cgi.escape()). Returns None to provide no
+ extra info.
+ """
Added: trunk/gnue-navigator/src/external/zope/exceptions/log.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/exceptions/log.py 2006-03-30
02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/exceptions/log.py 2006-03-30
02:36:08 UTC (rev 8287)
@@ -0,0 +1,35 @@
+##############################################################################
+#
+# 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.
+#
+##############################################################################
+"""Log formatter that enhances tracebacks with extra information.
+
+$Id: $
+"""
+
+import logging
+import cStringIO
+from gnue.navigator.external.zope.exceptions.exceptionformatter import
print_exception
+
+class Formatter(logging.Formatter):
+
+ def formatException(self, ei):
+ """Format and return the specified exception information as a string.
+
+ Uses zope.exceptions.exceptionformatter to generate the traceback.
+ """
+ sio = cStringIO.StringIO()
+ print_exception(ei[0], ei[1], ei[2], file=sio, with_filenames=True)
+ s = sio.getvalue()
+ if s.endswith("\n"):
+ s = s[:-1]
+ return s
Added: trunk/gnue-navigator/src/external/zope/exceptions/tests/__init__.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/exceptions/tests/__init__.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/exceptions/tests/__init__.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,2 @@
+#
+# This file is necessary to make this directory a package.
Added:
trunk/gnue-navigator/src/external/zope/exceptions/tests/test_exceptionformatter.py
===================================================================
---
trunk/gnue-navigator/src/external/zope/exceptions/tests/test_exceptionformatter.py
2006-03-30 02:24:05 UTC (rev 8286)
+++
trunk/gnue-navigator/src/external/zope/exceptions/tests/test_exceptionformatter.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,152 @@
+##############################################################################
+#
+# 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.
+#
+##############################################################################
+"""ExceptionFormatter tests.
+
+$Id: test_exceptionformatter.py 38178 2005-08-30 21:50:19Z mj $
+"""
+import sys
+from unittest import TestCase, main, makeSuite
+
+from zope.exceptions.exceptionformatter import format_exception
+from zope.testing.cleanup import CleanUp # Base class w registry cleanup
+
+def tb(as_html=0):
+ t, v, b = sys.exc_info()
+ try:
+ return ''.join(format_exception(t, v, b, as_html=as_html))
+ finally:
+ del b
+
+
+class ExceptionForTesting (Exception):
+ pass
+
+
+
+class TestingTracebackSupplement(object):
+
+ source_url = '/somepath'
+ line = 634
+ column = 57
+ warnings = ['Repent, for the end is nigh']
+
+ def __init__(self, expression):
+ self.expression = expression
+
+
+
+class Test(CleanUp, TestCase):
+
+ def testBasicNamesText(self, as_html=0):
+ try:
+ raise ExceptionForTesting
+ except ExceptionForTesting:
+ s = tb(as_html)
+ # The traceback should include the name of this function.
+ self.assert_(s.find('testBasicNamesText') >= 0)
+ # The traceback should include the name of the exception.
+ self.assert_(s.find('ExceptionForTesting') >= 0)
+ else:
+ self.fail('no exception occurred')
+
+ def testBasicNamesHTML(self):
+ self.testBasicNamesText(1)
+
+ def testSupplement(self, as_html=0):
+ try:
+ __traceback_supplement__ = (TestingTracebackSupplement,
+ "You're one in a million")
+ raise ExceptionForTesting
+ except ExceptionForTesting:
+ s = tb(as_html)
+ # The source URL
+ self.assert_(s.find('/somepath') >= 0, s)
+ # The line number
+ self.assert_(s.find('634') >= 0, s)
+ # The column number
+ self.assert_(s.find('57') >= 0, s)
+ # The expression
+ self.assert_(s.find("You're one in a million") >= 0, s)
+ # The warning
+ self.assert_(s.find("Repent, for the end is nigh") >= 0, s)
+ else:
+ self.fail('no exception occurred')
+
+ def testSupplementHTML(self):
+ self.testSupplement(1)
+
+ def testTracebackInfo(self, as_html=0):
+ try:
+ __traceback_info__ = "Adam & Eve"
+ raise ExceptionForTesting
+ except ExceptionForTesting:
+ s = tb(as_html)
+ if as_html:
+ # Be sure quoting is happening.
+ self.assert_(s.find('Adam & Eve') >= 0, s)
+ else:
+ self.assert_(s.find('Adam & Eve') >= 0, s)
+ else:
+ self.fail('no exception occurred')
+
+ def testTracebackInfoHTML(self):
+ self.testTracebackInfo(1)
+
+ def testTracebackInfoTuple(self):
+ try:
+ __traceback_info__ = ("Adam", "Eve")
+ raise ExceptionForTesting
+ except ExceptionForTesting:
+ s = tb()
+ self.assert_(s.find('Adam') >= 0, s)
+ self.assert_(s.find('Eve') >= 0, s)
+ else:
+ self.fail('no exception occurred')
+
+ def testMultipleLevels(self):
+ # Makes sure many levels are shown in a traceback.
+ def f(n):
+ """Produces a (n + 1)-level traceback."""
+ __traceback_info__ = 'level%d' % n
+ if n > 0:
+ f(n - 1)
+ else:
+ raise ExceptionForTesting
+
+ try:
+ f(10)
+ except ExceptionForTesting:
+ s = tb()
+ for n in range(11):
+ self.assert_(s.find('level%d' % n) >= 0, s)
+ else:
+ self.fail('no exception occurred')
+
+ def testQuoteLastLine(self):
+ class C(object): pass
+ try: raise TypeError(C())
+ except:
+ s = tb(1)
+ else:
+ self.fail('no exception occurred')
+ self.assert_(s.find('<') >= 0, s)
+ self.assert_(s.find('>') >= 0, s)
+
+
+
+def test_suite():
+ return makeSuite(Test)
+
+if __name__=='__main__':
+ main(defaultTest='test_suite')
Added: trunk/gnue-navigator/src/external/zope/interface/common/tests/__init__.py
===================================================================
--- trunk/gnue-navigator/src/external/zope/interface/common/tests/__init__.py
2006-03-30 02:24:05 UTC (rev 8286)
+++ trunk/gnue-navigator/src/external/zope/interface/common/tests/__init__.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,2 @@
+#
+# This file is necessary to make this directory a package.
Added:
trunk/gnue-navigator/src/external/zope/interface/common/tests/basemapping.py
===================================================================
---
trunk/gnue-navigator/src/external/zope/interface/common/tests/basemapping.py
2006-03-30 02:24:05 UTC (rev 8286)
+++
trunk/gnue-navigator/src/external/zope/interface/common/tests/basemapping.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,115 @@
+##############################################################################
+#
+# 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.
+#
+##############################################################################
+"""Base Mapping tests
+
+$Id: basemapping.py 26560 2004-07-15 21:38:42Z srichter $
+"""
+from operator import __getitem__
+
+def testIReadMapping(self, inst, state, absent):
+ for key in state:
+ self.assertEqual(inst[key], state[key])
+ self.assertEqual(inst.get(key, None), state[key])
+ self.failUnless(key in inst)
+
+ for key in absent:
+ self.assertEqual(inst.get(key, None), None)
+ self.assertEqual(inst.get(key), None)
+ self.assertEqual(inst.get(key, self), self)
+ self.assertRaises(KeyError, __getitem__, inst, key)
+
+
+def test_keys(self, inst, state):
+ # Return the keys of the mapping object
+ inst_keys = list(inst.keys()); inst_keys.sort()
+ state_keys = list(state.keys()) ; state_keys.sort()
+ self.assertEqual(inst_keys, state_keys)
+
+def test_iter(self, inst, state):
+ # Return the keys of the mapping object
+ inst_keys = list(inst); inst_keys.sort()
+ state_keys = list(state.keys()) ; state_keys.sort()
+ self.assertEqual(inst_keys, state_keys)
+
+def test_values(self, inst, state):
+ # Return the values of the mapping object
+ inst_values = list(inst.values()); inst_values.sort()
+ state_values = list(state.values()) ; state_values.sort()
+ self.assertEqual(inst_values, state_values)
+
+def test_items(self, inst, state):
+ # Return the items of the mapping object
+ inst_items = list(inst.items()); inst_items.sort()
+ state_items = list(state.items()) ; state_items.sort()
+ self.assertEqual(inst_items, state_items)
+
+def test___len__(self, inst, state):
+ # Return the number of items
+ self.assertEqual(len(inst), len(state))
+
+def testIEnumerableMapping(self, inst, state):
+ test_keys(self, inst, state)
+ test_items(self, inst, state)
+ test_values(self, inst, state)
+ test___len__(self, inst, state)
+
+
+class BaseTestIReadMapping(object):
+ def testIReadMapping(self):
+ inst = self._IReadMapping__sample()
+ state = self._IReadMapping__stateDict()
+ absent = self._IReadMapping__absentKeys()
+ testIReadMapping(self, inst, state, absent)
+
+
+class BaseTestIEnumerableMapping(BaseTestIReadMapping):
+ # Mapping objects whose items can be enumerated
+ def test_keys(self):
+ # Return the keys of the mapping object
+ inst = self._IEnumerableMapping__sample()
+ state = self._IEnumerableMapping__stateDict()
+ test_keys(self, inst, state)
+
+ def test_values(self):
+ # Return the values of the mapping object
+ inst = self._IEnumerableMapping__sample()
+ state = self._IEnumerableMapping__stateDict()
+ test_values(self, inst, state)
+
+ def test_values(self):
+ # Return the values of the mapping object
+ inst = self._IEnumerableMapping__sample()
+ state = self._IEnumerableMapping__stateDict()
+ test_iter(self, inst, state)
+
+ def test_items(self):
+ # Return the items of the mapping object
+ inst = self._IEnumerableMapping__sample()
+ state = self._IEnumerableMapping__stateDict()
+ test_items(self, inst, state)
+
+ def test___len__(self):
+ # Return the number of items
+ inst = self._IEnumerableMapping__sample()
+ state = self._IEnumerableMapping__stateDict()
+ test___len__(self, inst, state)
+
+ def _IReadMapping__stateDict(self):
+ return self._IEnumerableMapping__stateDict()
+
+ def _IReadMapping__sample(self):
+ return self._IEnumerableMapping__sample()
+
+ def _IReadMapping__absentKeys(self):
+ return self._IEnumerableMapping__absentKeys()
Added:
trunk/gnue-navigator/src/external/zope/interface/common/tests/test_idatetime.py
===================================================================
---
trunk/gnue-navigator/src/external/zope/interface/common/tests/test_idatetime.py
2006-03-30 02:24:05 UTC (rev 8286)
+++
trunk/gnue-navigator/src/external/zope/interface/common/tests/test_idatetime.py
2006-03-30 02:36:08 UTC (rev 8287)
@@ -0,0 +1,49 @@
+##############################################################################
+#
+# 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.
+#
+##############################################################################
+"""Test for datetime interfaces
+
+$Id: test_idatetime.py 25177 2004-06-02 13:17:31Z jim $
+"""
+
+import unittest
+
+from zope.interface.verify import verifyObject, verifyClass
+from zope.interface.common.idatetime import ITimeDelta, ITimeDeltaClass
+from zope.interface.common.idatetime import IDate, IDateClass
+from zope.interface.common.idatetime import IDateTime, IDateTimeClass
+from zope.interface.common.idatetime import ITime, ITimeClass, ITZInfo
+from datetime import timedelta, date, datetime, time, tzinfo
+
+class TestDateTimeInterfaces(unittest.TestCase):
+
+ def test_interfaces(self):
+ verifyObject(ITimeDelta, timedelta(minutes=20))
+ verifyObject(IDate, date(2000, 1, 2))
+ verifyObject(IDateTime, datetime(2000, 1, 2, 10, 20))
+ verifyObject(ITime, time(20, 30, 15, 1234))
+ verifyObject(ITZInfo, tzinfo())
+ verifyClass(ITimeDeltaClass, timedelta)
+ verifyClass(IDateClass, date)
+ verifyClass(IDateTimeClass, datetime)
+ verifyClass(ITimeClass, time)
+
+
+def test_suite():
+ suite = unittest.TestSuite()
+ suite.addTest(unittest.makeSuite(TestDateTimeInterfaces))
+ return suite
+
+
+if __name__ == '__main__':
+ unittest.main()
Added: trunk/gnue-navigator/src/foundation/__init__.py
===================================================================
--- trunk/gnue-navigator/src/foundation/__init__.py 2006-03-30 02:24:05 UTC
(rev 8286)
+++ trunk/gnue-navigator/src/foundation/__init__.py 2006-03-30 02:36:08 UTC
(rev 8287)
@@ -0,0 +1,25 @@
+#
+# Copyright 2001-2006 Free Software Foundation
+#
+# This file is part of GNU Enterprise
+#
+# GNU Enterprise is free software; you can redistribute it
+# and/or modify it under the terms of the GNU General Public
+# License as published by the Free Software Foundation; either
+# version 2, or (at your option) any later version.
+#
+# GNU Enterprise is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied
+# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+# PURPOSE. See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public
+# License along with program; see the file COPYING. If not,
+# write to the Free Software Foundation, Inc., 59 Temple Place
+# - Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id: GNClient.py 8129 2006-01-18 21:25:44Z jcater $
+"""
+The 'foundation' package provides the components which make
+up the bare bones core of a GAP application.
+"""
\ No newline at end of file
Added: trunk/gnue-navigator/src/foundation/application.py
===================================================================
--- trunk/gnue-navigator/src/foundation/application.py 2006-03-30 02:24:05 UTC
(rev 8286)
+++ trunk/gnue-navigator/src/foundation/application.py 2006-03-30 02:36:08 UTC
(rev 8287)
@@ -0,0 +1,80 @@
+# GNU Application Platform
+#
+# Copyright 2001-2006 Free Software Foundation
+#
+# This file is part of GNU Enterprise
+#
+# GNU Enterprise is free software; you can redistribute it
+# and/or modify it under the terms of the GNU General Public
+# License as published by the Free Software Foundation; either
+# version 2, or (at your option) any later version.
+#
+# GNU Enterprise is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied
+# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+# PURPOSE. See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public
+# License along with program; see the file COPYING. If not,
+# write to the Free Software Foundation, Inc., 59 Temple Place
+# - Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id: GBaseApp.py 8129 2006-01-18 21:25:44Z jcater $
+"""
+The default provider of the IApplication interface in GAP
+"""
+__revision__ = "$Id$"
+
+from gnue.navigator.external.zope.interface import implements
+
+from interfaces import IApplication
+
+# =============================================================================
+# Base class for GNUe Applications
+# =============================================================================
+
+class Application:
+ """
+ The default provider of the IApplication interface in GAP
+ """
+
+ implements(IApplication)
+
+ ## Attributes to be overwritten by subclasses
+ #VERSION = "0.0.0"
+ #NAME = "GNUe Application"
+ #COMMAND_OPTIONS = [] # Should be in same format as _base_options below
+ #SUMMARY = "A brief summary of the program goes here."
+ #COMMAND = "app"
+ #USAGE = "[options]"
+ #USE_CONNECTIONS = 1 # Set to 1 if the program uses dbdrivers
+ #USE_DATABASE_OPTIONS = 0 # Also implies USE_CONNECTIONS = 1
+ #USE_RPC_OPTIONS = 0
+
+
+ ## More options, but won't be changed unless this is a non-GNUe app using
+ ## GNUe-Common
+ #AUTHOR = "GNU Enterprise Project"
+ #EMAIL = "address@hidden"
+ #REPORT_BUGS_TO = "Please report any bugs to address@hidden"
+
+ #CONFIGFILE = "gnue.conf"
+ #SYSCONFIGDIR = None
+
+
+ ## Attributes that will be set by GClientApp after __init__ has run
+ #OPTIONS = {} # Will contain a hash containing command line options
+ #ARGUMENTS = [] # Will contain an array of command line arguments
+ #connections = None # Will contain a GConnection object
+
+ # ---------------------------------------------------------------------------
+ # Create a new GNUe Application
+ # ---------------------------------------------------------------------------
+
+ def __init__ (self):
+ """
+ """
+ pass
+
+ def main(self):
+ pass
\ No newline at end of file
Added: trunk/gnue-navigator/src/foundation/interfaces.py
===================================================================
--- trunk/gnue-navigator/src/foundation/interfaces.py 2006-03-30 02:24:05 UTC
(rev 8286)
+++ trunk/gnue-navigator/src/foundation/interfaces.py 2006-03-30 02:36:08 UTC
(rev 8287)
@@ -0,0 +1,40 @@
+#
+# Copyright 2001-2006 Free Software Foundation
+#
+# This file is part of GNU Enterprise
+#
+# GNU Enterprise is free software; you can redistribute it
+# and/or modify it under the terms of the GNU General Public
+# License as published by the Free Software Foundation; either
+# version 2, or (at your option) any later version.
+#
+# GNU Enterprise is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied
+# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+# PURPOSE. See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public
+# License along with program; see the file COPYING. If not,
+# write to the Free Software Foundation, Inc., 59 Temple Place
+# - Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id: GNClient.py 8129 2006-01-18 21:25:44Z jcater $
+"""
+GAP Foundation interfaces
+"""
+
+from gnue.navigator.external.zope.interface import Interface, Attribute
+
+class IApplication(Interface):
+ """
+ Manages the startup and initialization of a GAP based application.
+
+ Is responsible for initializing the application component registry
+ instance and providing it with the applications specific component
+ configuration information.
+ """
+
+ def main():
+ """
+ Begin execution of the program
+ """
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- [gnue] r8287 - in trunk/gnue-navigator/src: . external external/zope external/zope/component external/zope/component/bbb external/zope/component/bbb/tests external/zope/deprecation external/zope/exceptions external/zope/exceptions/tests external/zope/interface external/zope/interface/common external/zope/interface/common/tests foundation,
jamest <=