[Checkins] SVN: zope.app.component/trunk/ Extract lots of code into zope.site to help clean up dependencies.
Martijn Faassen
faassen at infrae.com
Tue Jan 27 12:23:34 EST 2009
Log message for revision 95230:
Extract lots of code into zope.site to help clean up dependencies.
(with Brandon Rhodes)
Changed:
_U zope.app.component/trunk/
U zope.app.component/trunk/CHANGES.txt
U zope.app.component/trunk/README.txt
U zope.app.component/trunk/buildout.cfg
U zope.app.component/trunk/setup.py
D zope.app.component/trunk/src/zope/app/component/README.txt
U zope.app.component/trunk/src/zope/app/component/__init__.py
U zope.app.component/trunk/src/zope/app/component/configure.zcml
U zope.app.component/trunk/src/zope/app/component/hooks.py
U zope.app.component/trunk/src/zope/app/component/interfaces/__init__.py
U zope.app.component/trunk/src/zope/app/component/site.py
D zope.app.component/trunk/src/zope/app/component/site.txt
D zope.app.component/trunk/src/zope/app/component/tests/test_api.py
D zope.app.component/trunk/src/zope/app/component/tests/test_localsitemanager.py
D zope.app.component/trunk/src/zope/app/component/tests/test_registration.py
D zope.app.component/trunk/src/zope/app/component/tests/test_site.py
-=-
Property changes on: zope.app.component/trunk
___________________________________________________________________
Added: svn:externals
+ zope.site svn://svn.zope.org/repos/main/zope.site/trunk
Modified: zope.app.component/trunk/CHANGES.txt
===================================================================
--- zope.app.component/trunk/CHANGES.txt 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/CHANGES.txt 2009-01-27 17:23:33 UTC (rev 95230)
@@ -5,6 +5,10 @@
3.5.1 (Unreleased)
------------------
+- Extracted `zope.site` from zope.app.component with backwards
+ compatibility imports in place. Local site related functionality
+ is now in `zope.site` and packages should import from there.
+
- Remove more deprecated on 3.5 code:
* zope.app.component.fields module that was pointing to the
Modified: zope.app.component/trunk/README.txt
===================================================================
--- zope.app.component/trunk/README.txt 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/README.txt 2009-01-27 17:23:33 UTC (rev 95230)
@@ -1,2 +1,2 @@
-This package allows for local component registries and local component
-management.
+This package provides various ZCML directives (view, resource) and a
+user interface related to local component management.
Modified: zope.app.component/trunk/buildout.cfg
===================================================================
--- zope.app.component/trunk/buildout.cfg 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/buildout.cfg 2009-01-27 17:23:33 UTC (rev 95230)
@@ -1,5 +1,5 @@
[buildout]
-develop = .
+develop = . zope.site
parts = test coverage-test coverage-report
[test]
Modified: zope.app.component/trunk/setup.py
===================================================================
--- zope.app.component/trunk/setup.py 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/setup.py 2009-01-27 17:23:33 UTC (rev 95230)
@@ -32,10 +32,6 @@
'Detailed Documentation\n'
'**********************\n'
+ '\n\n' +
- read('src', 'zope', 'app', 'component', 'README.txt')
- + '\n\n' +
- read('src', 'zope', 'app', 'component', 'site.txt')
- + '\n\n' +
read('CHANGES.txt')
),
keywords = "zope component architecture local",
@@ -63,6 +59,7 @@
]),
install_requires=[
'setuptools',
+ 'zope.site',
'zope.annotation',
'zope.app.container',
'zope.app.interface',
Deleted: zope.app.component/trunk/src/zope/app/component/README.txt
===================================================================
--- zope.app.component/trunk/src/zope/app/component/README.txt 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/README.txt 2009-01-27 17:23:33 UTC (rev 95230)
@@ -1,158 +0,0 @@
-=====================================
-Zope 3's Local Component Architecture
-=====================================
-
-The local component architecture provides several packages that can be used
-independent of the entire component architecture framework. Thus, I decided to
-document these frameworks in different files.
-
- o Registration Framework (`registration.txt`)
-
- Provides an API for creating custom registries. The entries of the
- registries are managed via registration components. A specific
- implementation for component-based registrations is also
- provided. Finally, there are some generic container classes that allow the
- developer to manage the components and their registrations.
-
- o Local Adapter Registry (`adapterregistry.txt`)
-
- Provides a persistent adapter registry that uses the registration
- framework. Local registries can be assembled to a registry tree where
- nodes further down in the tree overrride registrations of higher-up nodes.
-
- o Sites and Local Site Managers (`site.txt`)
-
- Provides a local and persistent site manager implementation, so that one
- can register local utilities and adapters. It uses local adapter
- registries for its adapter and utility registry. The module also provides
- some facilities to organize the local software and ensures the correct
- behavior inside the ZODB.
-
-
-Local Component Architecture API
---------------------------------
-
-While the component architecture API provided by ``zope.component`` is
-sufficient most of the time, there are a couple of functions that are useful
-in the context of multiple sites and base component registries.
-
---- BBB: Deprecated on 9/26/2006 --
-
- >>> import zope.deprecation
- >>> zope.deprecation.__show__.off()
-
-A very common use case is to get the nearest site manager in a given
-context. Sometimes, however, one wants the next higher-up site manager. First,
-let's create a folder tree and create some sites from it:
-
- >>> from zope.app.testing import setup
- >>> root = setup.buildSampleFolderTree()
- >>> root_sm = setup.createSiteManager(root)
- >>> folder1_sm = setup.createSiteManager(root['folder1'])
-
-If we ask `folder1` for its nearest site manager, we get
-
- >>> from zope.component import getSiteManager
- >>> getSiteManager(root['folder1']) is folder1_sm
- True
-
-but its next site manager is
-
- >>> from zope.app import component
- >>> component.getNextSiteManager(root['folder1']) is root_sm
- True
-
-The next site manager of the local root is the global site manager:
-
- >>> from zope.component import getGlobalSiteManager
- >>> gsm = getGlobalSiteManager()
- >>> component.getNextSiteManager(root) is gsm
- True
-
-If a non-location is passed into the function, a component lookup error is
-raised, since there is no site manager beyond the global site manager:
-
- >>> component.getNextSiteManager(object())
- Traceback (most recent call last):
- ...
- ComponentLookupError: No more site managers have been found.
-
-If you use the `queryNextSiteManager()` function, you can specify a `default`
-return value:
-
- >>> component.queryNextSiteManager(object(), 'default')
- 'default'
-
- >>> zope.deprecation.__show__.on()
-
---- BBB: End of block --
-
-It is common for a utility to delegate its answer to a utility providing the
-same interface in one of the component registry's bases. Let's start by
-creating a utility and inserting it in our folder hiearchy:
-
- >>> import zope.interface
- >>> class IMyUtility(zope.interface.Interface):
- ... pass
-
- >>> class MyUtility(object):
- ... zope.interface.implements(IMyUtility)
- ... def __init__(self, id):
- ... self.id = id
- ... def __repr__(self):
- ... return "%s('%s')" %(self.__class__.__name__, self.id)
-
- >>> gutil = MyUtility('global')
- >>> gsm.registerUtility(gutil, IMyUtility, 'myutil')
-
- >>> util1 = setup.addUtility(folder1_sm, 'myutil', IMyUtility,
- ... MyUtility('one'))
-
- >>> folder1_1_sm = setup.createSiteManager(root['folder1']['folder1_1'])
- >>> util1_1 = setup.addUtility(folder1_1_sm, 'myutil', IMyUtility,
- ... MyUtility('one-one'))
-
-Now, if we ask `util1_1` for its next available utility and we get
-
- >>> component.getNextUtility(util1_1, IMyUtility, 'myutil')
- MyUtility('one')
-
-Next we ask `util1` for its next utility and we should get the global version:
-
- >>> component.getNextUtility(util1, IMyUtility, 'myutil')
- MyUtility('global')
-
-However, if we ask the global utility for the next one, an error is raised
-
- >>> component.getNextUtility(gutil, IMyUtility,
- ... 'myutil') #doctest: +NORMALIZE_WHITESPACE
- Traceback (most recent call last):
- ...
- ComponentLookupError:
- No more utilities for <InterfaceClass __builtin__.IMyUtility>,
- 'myutil' have been found.
-
-or you can simply use the `queryNextUtility` and specify a default:
-
- >>> component.queryNextUtility(gutil, IMyUtility, 'myutil', 'default')
- 'default'
-
-Let's now ensure that the function also works with multiple registries. First
-we create another base registry:
-
- >>> from zope.component import registry
- >>> myregistry = registry.Components()
-
- >>> custom_util = MyUtility('my_custom_util')
- >>> myregistry.registerUtility(custom_util, IMyUtility, 'my_custom_util')
-
-Now we add it as a base to the local site manager:
-
- >>> folder1_sm.__bases__ = (myregistry,) + folder1_sm.__bases__
-
-Both, the ``myregistry`` and global utilities should be available:
-
- >>> component.queryNextUtility(folder1_sm, IMyUtility, 'my_custom_util')
- MyUtility('my_custom_util')
- >>> component.queryNextUtility(folder1_sm, IMyUtility, 'myutil')
- MyUtility('global')
Modified: zope.app.component/trunk/src/zope/app/component/__init__.py
===================================================================
--- zope.app.component/trunk/src/zope/app/component/__init__.py 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/__init__.py 2009-01-27 17:23:33 UTC (rev 95230)
@@ -20,6 +20,8 @@
import zope.component
import zope.deprecation
+from zope.site import getNextUtility, queryNextUtility # BBB
+
_marker = object()
# BBB: Deprecated on 9/26/2006
@@ -57,31 +59,3 @@
if not bases:
return zope.component.getGlobalSiteManager()
return bases[0]
-
-
-def getNextUtility(context, interface, name=''):
- """Get the next available utility.
-
- If no utility was found, a `ComponentLookupError` is raised.
- """
- util = queryNextUtility(context, interface, name, _marker)
- if util is _marker:
- raise zope.component.interfaces.ComponentLookupError(
- "No more utilities for %s, '%s' have been found." % (
- interface, name))
- return util
-
-
-def queryNextUtility(context, interface, name='', default=None):
- """Query for the next available utility.
-
- Find the next available utility providing `interface` and having the
- specified name. If no utility was found, return the specified `default`
- value."""
- sm = zope.component.getSiteManager(context)
- bases = sm.__bases__
- for base in bases:
- util = base.queryUtility(interface, name, _marker)
- if util is not _marker:
- return util
- return default
Modified: zope.app.component/trunk/src/zope/app/component/configure.zcml
===================================================================
--- zope.app.component/trunk/src/zope/app/component/configure.zcml 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/configure.zcml 2009-01-27 17:23:33 UTC (rev 95230)
@@ -1,89 +1,3 @@
<configure xmlns="http://namespaces.zope.org/zope">
-
- <interface interface="zope.interface.Interface" />
-
- <!-- Site and Site Manager Framework -->
-
- <module module=".interfaces">
- <allow attributes="ISite" />
- </module>
-
- <class class=".site.LocalSiteManager">
- <implements
- interface="zope.annotation.interfaces.IAttributeAnnotatable" />
- <require
- permission="zope.ManageSite"
- interface="zope.app.container.interfaces.IReadContainer" />
- <require
- permission="zope.ManageSite"
- interface="zope.component.interfaces.IComponentLookup
- zope.app.container.interfaces.IWriteContainer" />
- </class>
-
- <class class="zope.component.registry.UtilityRegistration">
- <require
- permission="zope.ManageSite"
- interface="zope.component.interfaces.IUtilityRegistration"
- />
- </class>
-
- <class class=".site.SiteManagementFolder">
- <factory />
- <implements
- interface="zope.annotation.interfaces.IAttributeAnnotatable"
- />
- <require
- permission="zope.ManageSite"
- interface="zope.app.container.interfaces.IReadContainer" />
- <require
- permission="zope.ManageSite"
- interface="zope.app.container.interfaces.IWriteContainer"
- />
- </class>
-
- <adapter
- for="zope.component.interfaces.IComponentLookup"
- provides="zope.filerepresentation.interfaces.IDirectoryFactory"
- factory=".site.SMFolderFactory"
- permission="zope.ManageContent"
- />
-
- <adapter factory=".site.SiteManagerAdapter" />
-
- <subscriber
- for="zope.location.interfaces.ISite
- zope.app.publication.interfaces.IBeforeTraverseEvent"
- handler=".site.threadSiteSubscriber"
- />
-
- <subscriber
- for="zope.app.publication.interfaces.IEndRequestEvent"
- handler=".site.clearThreadSiteSubscriber"
- />
-
- <subscriber
- for="zope.location.interfaces.ISite
- zope.app.container.interfaces.IObjectMovedEvent"
- handler=".site.changeSiteConfigurationAfterMove"
- />
-
-
- <!-- the 'Interfaces' vocabulary below requires a registred IInterface -->
- <interface
- interface="zope.interface.interfaces.IInterface"
- />
-
- <!-- Vocabularies -->
-
- <utility
- component=".vocabulary.InterfacesVocabulary"
- name="Interfaces"
- />
-
- <utility
- component=".vocabulary.UtilityComponentInterfacesVocabulary"
- provides="zope.schema.interfaces.IVocabularyFactory"
- name="Utility Component Interfaces"
- />
-
+ <include package="zope.site" />
</configure>
Modified: zope.app.component/trunk/src/zope/app/component/hooks.py
===================================================================
--- zope.app.component/trunk/src/zope/app/component/hooks.py 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/hooks.py 2009-01-27 17:23:33 UTC (rev 95230)
@@ -11,106 +11,23 @@
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
-"""Hooks for getting and setting a site in the thread global namespace.
+"""This module here is for backwards compatibility.
+The real public API is now zope.site.hooks
+
$Id$
"""
__docformat__ = 'restructuredtext'
-import threading
-import zope.component
-import zope.security
-
-class read_property(object):
- def __init__(self, func):
- self.func = func
-
- def __get__(self, inst, cls):
- if inst is None:
- return self
-
- return self.func(inst)
-
-class SiteInfo(threading.local):
- site = None
- sm = zope.component.getGlobalSiteManager()
-
- def adapter_hook(self):
- adapter_hook = self.sm.adapters.adapter_hook
- self.adapter_hook = adapter_hook
- return adapter_hook
-
- adapter_hook = read_property(adapter_hook)
-
-siteinfo = SiteInfo()
-
-def setSite(site=None):
- if site is None:
- sm = zope.component.getGlobalSiteManager()
- else:
-
- # We remove the security proxy because there's no way for
- # untrusted code to get at it without it being proxied again.
-
- # We should really look look at this again though, especially
- # once site managers do less. There's probably no good reason why
- # they can't be proxied. Well, except maybe for performance.
-
- site = zope.security.proxy.removeSecurityProxy(site)
- sm = site.getSiteManager()
-
- siteinfo.site = site
- siteinfo.sm = sm
- try:
- del siteinfo.adapter_hook
- except AttributeError:
- pass
-
-def getSite():
- return siteinfo.site
-
-
-def getSiteManager(context=None):
- """A special hook for getting the site manager.
-
- Here we take the currently set site into account to find the appropriate
- site manager.
- """
- if context is None:
- return siteinfo.sm
-
- # We remove the security proxy because there's no way for
- # untrusted code to get at it without it being proxied again.
-
- # We should really look look at this again though, especially
- # once site managers do less. There's probably no good reason why
- # they can't be proxied. Well, except maybe for performance.
- sm = zope.component.interfaces.IComponentLookup(
- context, zope.component.getGlobalSiteManager())
- return zope.security.proxy.removeSecurityProxy(sm)
-
-
-def adapter_hook(interface, object, name='', default=None):
- try:
- return siteinfo.adapter_hook(interface, object, name, default)
- except zope.component.interfaces.ComponentLookupError:
- return default
-
-
-def setHooks():
- zope.component.adapter_hook.sethook(adapter_hook)
- zope.component.getSiteManager.sethook(getSiteManager)
-
-def resetHooks():
- # Reset hookable functions to original implementation.
- zope.component.adapter_hook.reset()
- zope.component.getSiteManager.reset()
-
-# Clear the site thread global
-clearSite = setSite
-try:
- from zope.testing.cleanup import addCleanUp
-except ImportError:
- pass
-else:
- addCleanUp(resetHooks)
+from zope.site.hooks import (read_property,
+ SiteInfo,
+ siteinfo,
+ setSite,
+ getSite,
+ getSiteManager,
+ adapter_hook,
+ setHooks,
+ resetHooks,
+ setSite,
+ clearSite) # BBB
+
Modified: zope.app.component/trunk/src/zope/app/component/interfaces/__init__.py
===================================================================
--- zope.app.component/trunk/src/zope/app/component/interfaces/__init__.py 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/interfaces/__init__.py 2009-01-27 17:23:33 UTC (rev 95230)
@@ -11,73 +11,21 @@
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
-"""Interfaces for the Local Component Architecture
+"""Backwards compatibility module.
+The real interfaces are defined in zope.site.interfaces.
$Id$
"""
import zope.deferredimport
-import zope.interface
-import zope.component.interfaces
-import zope.app.container.interfaces
+from zope.site.interfaces import (INewLocalSite,
+ NewLocalSite,
+ ILocalSiteManager,
+ ISiteManagementFolder)
+
zope.deferredimport.deprecatedFrom(
"Moved to zope.location.interfaces. Importing from here will stop working in Zope 3.6",
"zope.location.interfaces",
"ISite", "IPossibleSite")
-class INewLocalSite(zope.interface.Interface):
- """Event: a local site was created
- """
-
- manager = zope.interface.Attribute("The new site manager")
-
-class NewLocalSite:
- """Event: a local site was created
- """
- zope.interface.implements(INewLocalSite)
-
- def __init__(self, manager):
- self.manager = manager
-
-
-class ILocalSiteManager(zope.component.interfaces.IComponents):
- """Site Managers act as containers for registerable components.
-
- If a Site Manager is asked for an adapter or utility, it checks for those
- it contains before using a context-based lookup to find another site
- manager to delegate to. If no other site manager is found they defer to
- the global site manager which contains file based utilities and adapters.
- """
-
- subs = zope.interface.Attribute(
- "A collection of registries that describe the next level "
- "of the registry tree. They are the children of this "
- "registry node. This attribute should never be "
- "manipulated manually. Use `addSub()` and `removeSub()` "
- "instead.")
-
- def addSub(sub):
- """Add a new sub-registry to the node.
-
- Important: This method should *not* be used manually. It is
- automatically called by `setNext()`. To add a new registry to the
- tree, use `sub.setNext(self, self.base)` instead!
- """
-
- def removeSub(sub):
- """Remove a sub-registry to the node.
-
- Important: This method should *not* be used manually. It is
- automatically called by `setNext()`. To remove a registry from the
- tree, use `sub.setNext(None)` instead!
- """
-
-
-class ISiteManagementFolder(zope.app.container.interfaces.IContainer):
- """Component and component registration containers."""
-
- # XXX we need to figure out how to constrain this or, alternatively,
- # just use regular folders, which is probably the beter choice.
- # zope.app.container.constraints.containers(ILocalSiteManager)
-
Modified: zope.app.component/trunk/src/zope/app/component/site.py
===================================================================
--- zope.app.component/trunk/src/zope/app/component/site.py 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/site.py 2009-01-27 17:23:33 UTC (rev 95230)
@@ -11,247 +11,23 @@
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
-"""Site and Local Site Manager implementation
+"""This module here is for backwards compatibility.
-A local site manager has a number of roles:
+The real public API is now zope.site
- - A local site manager, that provides a local adapter and utility registry.
-
- - A place to do TTW development and/or to manage database-based code.
-
- - A registry for persistent modules. The Zope 3 import hook uses the
- SiteManager to search for modules.
-
$Id$
"""
-
-import zope.event
-import zope.interface
-import zope.component
-import zope.component.persistentregistry
-import zope.component.interfaces
-import zope.traversing.api
-import zope.deferredimport
-import zope.location
-
-from zope.component.interfaces import ComponentLookupError
-from zope.traversing.interfaces import IContainmentRoot
-from zope.lifecycleevent import ObjectCreatedEvent
-from zope.filerepresentation.interfaces import IDirectoryFactory
-
-from zope.app.component import interfaces
-from zope.app.component.hooks import setSite
-from zope.app.container.btree import BTreeContainer
-from zope.app.container.contained import Contained
-
-##############################################################################
-# from zope.app.module import resolve
-
-# Break the dependency on zope.app.module. In the long run,
-# we need to handle this better. Perhaps througha utility.
-
-## def findModule(name, context=None):
-## """Find the module matching the provided name."""
-## module = ZopeModuleRegistry.findModule(name)
-## return module or sys.modules.get(name)
-
-import sys
-
-def resolve(name, context=None):
- """Resolve a dotted name to a Python object."""
- pos = name.rfind('.')
- mod = sys.modules.get(name[:pos])
-## mod = findModule(name[:pos], context)
- return getattr(mod, name[pos+1:], None)
-
-# from zope.app.module import resolve
-##############################################################################
-
-class SiteManagementFolder(BTreeContainer):
- zope.interface.implements(interfaces.ISiteManagementFolder)
-
-
-class SMFolderFactory(object):
- zope.interface.implements(IDirectoryFactory)
-
- def __init__(self, context):
- self.context = context
-
- def __call__(self, name):
- return SiteManagementFolder()
-
-
-class SiteManagerContainer(Contained):
- """Implement access to the site manager (++etc++site).
-
- This is a mix-in that implements the IPossibleSite
- interface; for example, it is used by the Folder implementation.
- """
- zope.interface.implements(zope.location.interfaces.IPossibleSite)
-
- _sm = None
-
- def getSiteManager(self):
- if self._sm is not None:
- return self._sm
- else:
- raise ComponentLookupError('no site manager defined')
-
- def setSiteManager(self, sm):
- if zope.location.interfaces.ISite.providedBy(self):
- raise TypeError("Already a site")
-
- if zope.component.interfaces.IComponentLookup.providedBy(sm):
- self._sm = sm
- sm.__name__ = '++etc++site'
- sm.__parent__ = self
- else:
- raise ValueError('setSiteManager requires an IComponentLookup')
-
- zope.interface.directlyProvides(
- self, zope.location.interfaces.ISite,
- zope.interface.directlyProvidedBy(self))
-
- zope.event.notify(interfaces.NewLocalSite(sm))
-
-def _findNextSiteManager(site):
- while True:
- if IContainmentRoot.providedBy(site):
- # we're the root site, return None
- return None
-
- try:
- site = zope.traversing.api.getParent(site)
- except TypeError:
- # there was not enough context; probably run from a test
- return None
-
- if zope.location.interfaces.ISite.providedBy(site):
- return site.getSiteManager()
-
-
-class _LocalAdapterRegistry(
- zope.component.persistentregistry.PersistentAdapterRegistry,
- zope.location.Location,
- ):
- pass
-
-class LocalSiteManager(
- BTreeContainer,
- zope.component.persistentregistry.PersistentComponents,
- ):
- """Local Site Manager implementation"""
- zope.interface.implements(interfaces.ILocalSiteManager)
-
- subs = ()
-
- def _setBases(self, bases):
-
- # Update base subs
- for base in self.__bases__:
- if ((base not in bases)
- and interfaces.ILocalSiteManager.providedBy(base)
- ):
- base.removeSub(self)
-
- for base in bases:
- if ((base not in self.__bases__)
- and interfaces.ILocalSiteManager.providedBy(base)
- ):
- base.addSub(self)
-
- super(LocalSiteManager, self)._setBases(bases)
-
- def __init__(self, site):
- # Locate the site manager
- self.__parent__ = site
- self.__name__ = '++etc++site'
-
- BTreeContainer.__init__(self)
- zope.component.persistentregistry.PersistentComponents.__init__(self)
-
- next = _findNextSiteManager(site)
- if next is None:
- next = zope.component.getGlobalSiteManager()
- self.__bases__ = (next, )
-
- # Setup default site management folder
- folder = SiteManagementFolder()
- zope.event.notify(ObjectCreatedEvent(folder))
- self['default'] = folder
-
- def _init_registries(self):
- self.adapters = _LocalAdapterRegistry()
- self.utilities = _LocalAdapterRegistry()
- self.adapters.__parent__ = self.utilities.__parent__ = self
- self.adapters.__name__ = u'adapters'
- self.utilities.__name__ = u'utilities'
-
- def addSub(self, sub):
- """See interfaces.registration.ILocatedRegistry"""
- self.subs += (sub, )
-
- def removeSub(self, sub):
- """See interfaces.registration.ILocatedRegistry"""
- self.subs = tuple(
- [s for s in self.subs if s is not sub] )
-
- def __getRegistry(self, registration):
- """Determine the correct registry for the registration."""
- if interfaces.IUtilityRegistration.providedBy(registration):
- return self.utilities
- elif interfaces.IAdapterRegistration.providedBy(registration):
- return self.adapters
- raise ValueError("Unable to detect registration type or registration "
- "type is not supported. The registration object must "
- "provide `IAdapterRegistration` or "
- "`IUtilityRegistration`.")
-
-def threadSiteSubscriber(ob, event):
- """A subscriber to BeforeTraverseEvent
-
- Sets the 'site' thread global if the object traversed is a site.
- """
- setSite(ob)
-
-
-def clearThreadSiteSubscriber(event):
- """A subscriber to EndRequestEvent
-
- Cleans up the site thread global after the request is processed.
- """
- clearSite()
-
-# Clear the site thread global
-clearSite = setSite
-try:
- from zope.testing.cleanup import addCleanUp
-except ImportError:
- pass
-else:
- addCleanUp(clearSite)
-
-
- at zope.component.adapter(zope.interface.Interface)
- at zope.interface.implementer(zope.component.interfaces.IComponentLookup)
-def SiteManagerAdapter(ob):
- """An adapter from ILocation to IComponentLookup.
-
- The ILocation is interpreted flexibly, we just check for
- ``__parent__``.
- """
- current = ob
- while True:
- if zope.location.interfaces.ISite.providedBy(current):
- return current.getSiteManager()
- current = getattr(current, '__parent__', None)
- if current is None:
- # It is not a location or has no parent, so we return the global
- # site manager
- return zope.component.getGlobalSiteManager()
-
-def changeSiteConfigurationAfterMove(site, event):
- """After a site is moved, its site manager links have to be updated."""
- if event.newParent is not None:
- next = _findNextSiteManager(site)
- site.getSiteManager().__bases__ = (next, )
+# on the side of caution for backwards compatibility we
+# import everything defined
+from zope.site.site import (SiteManagementFolder,
+ SMFolderFactory,
+ SiteManagerContainer,
+ _findNextSiteManager,
+ _LocalAdapterRegistry,
+ LocalSiteManager,
+ threadSiteSubscriber,
+ clearThreadSiteSubscriber,
+ setSite,
+ clearSite,
+ SiteManagerAdapter,
+ changeSiteConfigurationAfterMove) # BBB
Deleted: zope.app.component/trunk/src/zope/app/component/site.txt
===================================================================
--- zope.app.component/trunk/src/zope/app/component/site.txt 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/site.txt 2009-01-27 17:23:33 UTC (rev 95230)
@@ -1,341 +0,0 @@
-=============================
-Sites and Local Site Managers
-=============================
-
-This chapter is an introduction of the location-based component
-architecture. This code uses the registration framework introduced in
-`registration.txt` and local adapter registries described in
-`adapterregistry.txt`.
-
-
-Creating and Accessing Sites
-----------------------------
-
-*Sites* are used to provide custom component setups for parts of your
-application or Web site. Every folder,
-
- >>> from zope.app.folder import folder
- >>> myfolder = folder.rootFolder()
-
-has the potential to become a site
-
- >>> from zope.location.interfaces import ISite, IPossibleSite
- >>> IPossibleSite.providedBy(myfolder)
- True
-
-but is not yet one:
-
- >>> ISite.providedBy(myfolder)
- False
-
-If you would like your custom content component to be able to become a site,
-you can use the `SiteManagerContainer` mix-in class:
-
- >>> from zope.app.component import site
- >>> class MyContentComponent(site.SiteManagerContainer):
- ... pass
-
- >>> myContent = MyContentComponent()
- >>> IPossibleSite.providedBy(myContent)
- True
- >>> ISite.providedBy(myContent)
- False
-
-To convert a possible site to a real site, we have to provide a site manager:
-
- >>> sm = site.LocalSiteManager(myfolder)
- >>> myfolder.setSiteManager(sm)
- >>> ISite.providedBy(myfolder)
- True
- >>> myfolder.getSiteManager() is sm
- True
-
-Note that an event is generated when a local site manager is created:
-
- >>> from zope.component.eventtesting import getEvents
- >>> from zope.app.component.interfaces import INewLocalSite
- >>> [event] = getEvents(INewLocalSite)
- >>> event.manager is sm
- True
-
-If one tries to set a bogus site manager, a `ValueError` will be raised:
-
- >>> myfolder2 = folder.Folder()
- >>> myfolder2.setSiteManager(object)
- Traceback (most recent call last):
- ...
- ValueError: setSiteManager requires an IComponentLookup
-
-Also, if the possible site has been changed to a site already, a `TypeError`
-is raised, when one attempts to add a new site manager:
-
- >>> myfolder.setSiteManager(site.LocalSiteManager(myfolder))
- Traceback (most recent call last):
- ...
- TypeError: Already a site
-
-There is also an adapter you can use to get the next site manager from any
-location:
-
- >>> myfolder['mysubfolder'] = folder.Folder()
- >>> import zope.component
- >>> zope.component.interfaces.IComponentLookup(myfolder['mysubfolder']) is sm
- True
-
-If the location passed is a site, the site manager of that site is returned:
-
- >>> zope.component.interfaces.IComponentLookup(myfolder) is sm
- True
-
-During traversal,
-
- >>> from zope.app import publication
- >>> request = object()
- >>> ev = publication.interfaces.BeforeTraverseEvent(myfolder, request)
- >>> site.threadSiteSubscriber(myfolder, ev)
-
-the nearest site is also recorded in a thread-global variable:
-
- >>> from zope.app.component import hooks
- >>> hooks.getSite() is myfolder
- True
-
-After a request is completed, the site setting is cleared again:
-
- >>> ev = publication.interfaces.EndRequestEvent(myfolder, request)
- >>> site.clearThreadSiteSubscriber(ev)
- >>> hooks.getSite() is None
- True
-
-
-Using the Site Manager
-----------------------
-
-A site manager contains several *site management folders*, which are used to
-logically organize the software. When a site manager is initialized, a default
-site management folder is created:
-
- >>> sm = myfolder.getSiteManager()
- >>> default = sm['default']
- >>> default.__class__
- <class 'zope.app.component.site.SiteManagementFolder'>
-
-You can easily create a new site management folder:
-
- >>> sm['mySMF'] = site.SiteManagementFolder()
- >>> sm['mySMF'].__class__
- <class 'zope.app.component.site.SiteManagementFolder'>
-
-Once you have your site management folder -- let's use the default one -- we
-can register some components. Let's start with a utility
-
- >>> import zope.interface
- >>> class IMyUtility(zope.interface.Interface):
- ... pass
-
- >>> import persistent
- >>> from zope.app.container.contained import Contained
- >>> class MyUtility(persistent.Persistent, Contained):
- ... zope.interface.implements(IMyUtility)
- ... def __init__(self, title):
- ... self.title = title
- ... def __repr__(self):
- ... return "%s('%s')" %(self.__class__.__name__, self.title)
-
-Now we can create an instance of our utility and put it in the site
-management folder and register it:
-
- >>> myutil = MyUtility('My custom utility')
- >>> default['myutil'] = myutil
- >>> sm.registerUtility(myutil, IMyUtility, 'u1')
-
-Now we can ask the site manager for the utility:
-
- >>> sm.queryUtility(IMyUtility, 'u1')
- MyUtility('My custom utility')
-
-Of course, the local site manager has also access to the global component
-registrations:
-
- >>> gutil = MyUtility('Global Utility')
- >>> from zope.component import getGlobalSiteManager
- >>> gsm = getGlobalSiteManager()
- >>> gsm.registerUtility(gutil, IMyUtility, 'gutil')
-
- >>> sm.queryUtility(IMyUtility, 'gutil')
- MyUtility('Global Utility')
-
-Next let's see whether we can also successfully register an adapter as
-well. Here the adapter will provide the size of a file:
-
- >>> class IFile(zope.interface.Interface):
- ... pass
-
- >>> class ISized(zope.interface.Interface):
- ... pass
-
- >>> class File(object):
- ... zope.interface.implements(IFile)
-
- >>> class FileSize(object):
- ... zope.interface.implements(ISized)
- ... def __init__(self, context):
- ... self.context = context
-
-Now that we have the adapter we need to register it:
-
- >>> sm.registerAdapter(FileSize, [IFile])
-
-Finally, we can get the adapter for a file:
-
- >>> file = File()
- >>> size = sm.queryAdapter(file, ISized, name='')
- >>> size.__class__
- <class 'FileSize'>
- >>> size.context is file
- True
-
-By the way, once you set a site
-
- >>> hooks.setSite(myfolder)
-
-you can simply use the zope.component's `getSiteManager()` method to get
-the nearest site manager:
-
- >>> from zope.component import getSiteManager
- >>> getSiteManager() is sm
- True
-
-This also means that you can simply use zope.component to look up your utility
-
- >>> from zope.component import getUtility
- >>> getUtility(IMyUtility, 'gutil')
- MyUtility('Global Utility')
-
-or the adapter via the interface's `__call__` method:
-
- >>> size = ISized(file)
- >>> size.__class__
- <class 'FileSize'>
- >>> size.context is file
- True
-
-
-Multiple Sites
---------------
-
-Until now we have only dealt with one local and the global site. But things
-really become interesting, once we have multiple sites. We can override other
-local configuration.
-
-Let's now create a new folder called `folder11`, add it to `myfolder` and make
-it a site:
-
- >>> myfolder11 = folder.Folder()
- >>> myfolder['myfolder11'] = myfolder11
- >>> myfolder11.setSiteManager(site.LocalSiteManager(myfolder11))
- >>> sm11 = myfolder11.getSiteManager()
-
-If we ask the second site manager for its next, we get
-
- >>> sm11.__bases__ == (sm, )
- True
-
-and the first site manager should have the folling sub manager:
-
- >>> sm.subs == (sm11,)
- True
-
-If we now register a second utility with the same name and interface with the
-new site manager folder,
-
- >>> default11 = sm11['default']
- >>> myutil11 = MyUtility('Utility, uno & uno')
- >>> default11['myutil'] = myutil11
-
- >>> sm11.registerUtility(myutil11, IMyUtility, 'u1')
-
-then it will will be available in the second site manager
-
- >>> sm11.queryUtility(IMyUtility, 'u1')
- MyUtility('Utility, uno & uno')
-
-but not in the first one:
-
- >>> sm.queryUtility(IMyUtility, 'u1')
- MyUtility('My custom utility')
-
-It is also interesting to look at the use cases of moving and copying a
-site. To do that we create a second root folder and make it a site, so that
-site hierarchy is as follows:
-
-::
-
- _____ global site _____
- / \
- myfolder1 myfolder2
- |
- myfolder11
-
-
- >>> myfolder2 = folder.rootFolder()
- >>> myfolder2.setSiteManager(site.LocalSiteManager(myfolder2))
-
-Before we can move or copy sites, we need to register two event subscribers
-that manage the wiring of site managers after moving or copying:
-
- >>> from zope.app import container
- >>> gsm.registerHandler(
- ... site.changeSiteConfigurationAfterMove,
- ... (ISite, container.interfaces.IObjectMovedEvent),
- ... )
-
-We only have to register one event listener, since the copy action causes an
-`IObjectAddedEvent` to be created, which is just a special type of
-`IObjectMovedEvent`.
-
-First, make sure that everything is setup correctly in the first place:
-
- >>> myfolder11.getSiteManager().__bases__ == (myfolder.getSiteManager(), )
- True
- >>> myfolder.getSiteManager().subs[0] is myfolder11.getSiteManager()
- True
- >>> myfolder2.getSiteManager().subs
- ()
-
-Let's now move `myfolder11` from `myfolder` to `myfolder2`:
-
- >>> myfolder2['myfolder21'] = myfolder11
- >>> del myfolder['myfolder11']
-
-Now the next site manager for `myfolder11`'s site manager should have changed:
-
- >>> myfolder21 = myfolder11
- >>> myfolder21.getSiteManager().__bases__ == (myfolder2.getSiteManager(), )
- True
- >>> myfolder2.getSiteManager().subs[0] is myfolder21.getSiteManager()
- True
- >>> myfolder.getSiteManager().subs
- ()
-
-Finally, we make a copy of `myfolder21` and add it as `myfolder11` to
-`myfolder`:
-
- # Make sure that our interfaces and classes are picklable.
-
- >>> import sys
- >>> sys.modules['zope.app.component.tests'].IMyUtility = IMyUtility
- >>> IMyUtility.__module__ = 'zope.app.component.tests'
- >>> sys.modules['zope.app.component.tests'].MyUtility = MyUtility
- >>> MyUtility.__module__ = 'zope.app.component.tests'
-
- >>> from zope.location.pickling import locationCopy
- >>> myfolder['myfolder11'] = locationCopy(myfolder2['myfolder21'])
-
- >>> myfolder11 = myfolder['myfolder11']
- >>> myfolder11.getSiteManager().__bases__ == (myfolder.getSiteManager(), )
- True
- >>> myfolder.getSiteManager().subs[0] is myfolder11.getSiteManager()
- True
- >>> myfolder2.getSiteManager().subs[0] is myfolder21.getSiteManager()
- True
Deleted: zope.app.component/trunk/src/zope/app/component/tests/test_api.py
===================================================================
--- zope.app.component/trunk/src/zope/app/component/tests/test_api.py 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/tests/test_api.py 2009-01-27 17:23:33 UTC (rev 95230)
@@ -1,38 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Registration Tests
-
-$Id$
-"""
-__docformat__ = "reStructuredText"
-import unittest
-
-from zope.testing import doctest
-from zope.app.testing import setup
-
-def setUp(test):
- setup.placefulSetUp()
-
-def tearDown(test):
- setup.placefulTearDown()
-
-def test_suite():
- return unittest.TestSuite((
- doctest.DocFileSuite('../README.txt',
- setUp=setUp, tearDown=tearDown),
- ))
-
-if __name__ == "__main__":
- unittest.main(defaultTest='test_suite')
-
Deleted: zope.app.component/trunk/src/zope/app/component/tests/test_localsitemanager.py
===================================================================
--- zope.app.component/trunk/src/zope/app/component/tests/test_localsitemanager.py 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/tests/test_localsitemanager.py 2009-01-27 17:23:33 UTC (rev 95230)
@@ -1,54 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2007 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.
-#
-##############################################################################
-"""Local sitemanager tests.
-
-$Id$
-"""
-import unittest
-
-from zope.interface import Interface
-from zope.copypastemove import ObjectCopier
-from zope.app.component import site
-from zope.app.folder import Folder
-from zope.app.testing.placelesssetup import PlacelessSetup
-
-class I1(Interface):pass
-
-class TestLocalSiteManager(PlacelessSetup, unittest.TestCase):
-
- def setUp(self):
- super(TestLocalSiteManager, self).setUp()
-
- self.util = object()
- self.root = Folder()
- self.root['site'] = Folder()
- subfolder = self.root['site']
- subfolder.setSiteManager(site.LocalSiteManager(subfolder))
- subfolder.getSiteManager().registerUtility(self.util, I1)
-
- def testCopy(self):
- self.assert_(self.root['site'].getSiteManager().getUtility(I1) is self.util)
-
- copier = ObjectCopier(self.root['site'])
- copier.copyTo(self.root, 'copied_site')
-
- self.assert_(self.root['copied_site'].getSiteManager().getUtility(I1) is not self.util)
-
-def test_suite():
- return unittest.TestSuite((
- unittest.makeSuite(TestLocalSiteManager),
- ))
-
-if __name__ == '__main__':
- unittest.main()
Deleted: zope.app.component/trunk/src/zope/app/component/tests/test_registration.py
===================================================================
--- zope.app.component/trunk/src/zope/app/component/tests/test_registration.py 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/tests/test_registration.py 2009-01-27 17:23:33 UTC (rev 95230)
@@ -1,244 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Registration Tests
-
-$Id$
-"""
-__docformat__ = "reStructuredText"
-
-import os
-import unittest
-import warnings
-
-from ZODB.DB import DB
-import ZODB.FileStorage
-from ZODB.DemoStorage import DemoStorage
-import transaction
-import persistent
-
-import zope.component.globalregistry
-import zope.component.testing as placelesssetup
-from zope.testing import doctest
-from zope.app.testing import setup
-import zope.app.container.contained
-from zope import interface
-
-import zope.app.component.site
-
-
-# test class for testing data conversion
-class IFoo(interface.Interface):
- pass
-class Foo(persistent.Persistent, zope.app.container.contained.Contained):
- interface.implements(IFoo)
- name = ''
- def __init__(self, name=''):
- self.name = name
-
- def __repr__(self):
- return 'Foo(%r)' % self.name
-
-def setUpOld(test):
- placelesssetup.setUp(test)
- setup.setUpAnnotations()
- setup.setUpDependable()
- setup.setUpTraversal()
- test.globs['showwarning'] = warnings.showwarning
- warnings.showwarning = lambda *a, **k: None
-
-def tearDown(test):
- warnings.showwarning = test.globs['showwarning']
- placelesssetup.tearDown(test)
-
-def setUp(test):
- placelesssetup.setUp(test)
- test.globs['showwarning'] = warnings.showwarning
- warnings.showwarning = lambda *a, **k: None
-
-def oldfs():
- return FileStorage(
- os.path.join(os.path.dirname(__file__), 'gen3.fs'),
- read_only=True,
- )
-
-# Work around a bug in ZODB
-# XXX fix ZODB
-class FileStorage(ZODB.FileStorage.FileStorage):
-
- def new_oid(self):
- self._lock_acquire()
- try:
- last = self._oid
- d = ord(last[-1])
- if d < 255: # fast path for the usual case
- last = last[:-1] + chr(d+1)
- else: # there's a carry out of the last byte
- last_as_long, = _structunpack(">Q", last)
- last = _structpack(">Q", last_as_long + 1)
- self._oid = last
- return last
- finally:
- self._lock_release()
-
-class GlobalRegistry:
- pass
-
-base = zope.component.globalregistry.GlobalAdapterRegistry(
- GlobalRegistry, 'adapters')
-GlobalRegistry.adapters = base
-def clear_base():
- base.__init__(GlobalRegistry, 'adapters')
-
-
-def test_deghostification_of_persistent_adapter_registries():
- """
-
-Note that this test duplicates one from zope.component.tests.
-We should be able to get rid of this one when we get rid of
-__setstate__ implementation we have in back35.
-
-We want to make sure that we see updates corrextly.
-
- >>> import ZODB.tests.util
- >>> db = ZODB.tests.util.DB()
- >>> tm1 = transaction.TransactionManager()
- >>> c1 = db.open(transaction_manager=tm1)
- >>> r1 = zope.app.component.site._LocalAdapterRegistry((base,))
- >>> r2 = zope.app.component.site._LocalAdapterRegistry((r1,))
- >>> c1.root()[1] = r1
- >>> c1.root()[2] = r2
- >>> tm1.commit()
- >>> r1._p_deactivate()
- >>> r2._p_deactivate()
-
- >>> tm2 = transaction.TransactionManager()
- >>> c2 = db.open(transaction_manager=tm2)
- >>> r1 = c2.root()[1]
- >>> r2 = c2.root()[2]
-
- >>> r1.lookup((), IFoo, '')
-
- >>> base.register((), IFoo, '', Foo(''))
- >>> r1.lookup((), IFoo, '')
- Foo('')
-
- >>> r2.lookup((), IFoo, '1')
-
- >>> r1.register((), IFoo, '1', Foo('1'))
-
- >>> r2.lookup((), IFoo, '1')
- Foo('1')
-
- >>> r1.lookup((), IFoo, '2')
- >>> r2.lookup((), IFoo, '2')
-
- >>> base.register((), IFoo, '2', Foo('2'))
-
- >>> r1.lookup((), IFoo, '2')
- Foo('2')
-
- >>> r2.lookup((), IFoo, '2')
- Foo('2')
-
-Cleanup:
-
- >>> db.close()
- >>> clear_base()
-
- """
-
-barcode = """
-from zope.interface import Interface
-class IBar(Interface): pass
-class IBaz(Interface): pass
-"""
-
-class Bar(persistent.Persistent): pass
-class Baz(persistent.Persistent): pass
-
-def test_persistent_interfaces():
- """
-Registrations for persistent interfaces are accessible from separate
-connections.
-
-Setup the DB and our first connection::
-
- >>> import ZODB.tests.util
- >>> db = ZODB.tests.util.DB()
- >>> conn1 = db.open()
- >>> root1 = conn1.root()
-
-Setup the persistent module registry and the local component
-registry::
-
- >>> from zodbcode.module import ManagedRegistry
- >>> registry = root1['registry'] = ManagedRegistry()
- >>> from zope.component.persistentregistry import PersistentComponents
- >>> manager = root1['manager'] = PersistentComponents()
-
-Create a persistent module::
-
- >>> registry.newModule('barmodule', barcode)
- >>> barmodule = registry.findModule('barmodule')
-
-Create a persistent instance::
-
- >>> bar = root1['bar'] = Bar()
- >>> from zope.interface import directlyProvides
- >>> directlyProvides(bar, barmodule.IBar)
- >>> from transaction import commit
- >>> commit()
-
-Register an adapter::
-
- >>> manager.queryAdapter(bar, barmodule.IBaz)
- >>> manager.registerAdapter(Baz, [barmodule.IBar], barmodule.IBaz)
- >>> manager.getAdapter(bar, barmodule.IBaz) # doctest: +ELLIPSIS
- <zope.app.component.tests.test_registration.Baz object at ...>
-
-Before commit, the adapter is not available from another connection::
-
- >>> conn2 = db.open()
- >>> root2 = conn2.root()
- >>> registry2 = root2['registry']
- >>> barmodule2 = registry2.findModule('barmodule')
- >>> bar2 = root2['bar']
- >>> manager2 = root2['manager']
- >>> manager2.queryAdapter(bar2, barmodule2.IBaz)
-
-After commit, it is::
-
- >>> commit()
- >>> conn2.sync()
- >>> manager2.getAdapter(bar2, barmodule2.IBaz)
- ... # doctest: +ELLIPSIS
- <zope.app.component.tests.test_registration.Baz object at ...>
-
-Cleanup::
-
- >>> conn1.close()
- >>> conn2.close()
- >>> db.close()
-"""
-
-
-def test_suite():
- suite = unittest.TestSuite((
- doctest.DocTestSuite(setUp=setUp, tearDown=tearDown)
- ))
- return suite
-
-
-if __name__ == "__main__":
- unittest.main(defaultTest='test_suite')
Deleted: zope.app.component/trunk/src/zope/app/component/tests/test_site.py
===================================================================
--- zope.app.component/trunk/src/zope/app/component/tests/test_site.py 2009-01-27 17:18:30 UTC (rev 95229)
+++ zope.app.component/trunk/src/zope/app/component/tests/test_site.py 2009-01-27 17:23:33 UTC (rev 95230)
@@ -1,172 +0,0 @@
-##############################################################################
-#
-# 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.
-#
-##############################################################################
-"""Registration Tests
-
-$Id$
-"""
-__docformat__ = "reStructuredText"
-import unittest
-
-import zope.interface
-import zope.interface.verify
-from zope.testing import doctest
-from zope.location.interfaces import ISite, IPossibleSite
-
-from zope.app.testing import setup
-from zope.app.component import interfaces, site
-from zope.app.folder import folder
-import zope.app.publication.interfaces
-
-class SiteManagerStub(object):
- zope.interface.implements(interfaces.ILocalSiteManager)
-
-class CustomFolder(folder.Folder):
-
- def __init__(self, name):
- self.__name__ = name
- super(CustomFolder, self).__init__()
-
- def __repr__(self):
- return '<%s %s>' %(self.__class__.__name__, self.__name__)
-
-
-def test_SiteManagerAdapter():
- """
- The site manager adapter is used to find the nearest site for any given
- location. If the provided context is a site,
-
- >>> site = folder.Folder()
- >>> sm = SiteManagerStub()
- >>> site.setSiteManager(sm)
-
- then the adapter simply return's the site's site manager:
-
- >>> from zope.app.component.site import SiteManagerAdapter
- >>> SiteManagerAdapter(site) is sm
- True
-
- If the context is a location (i.e. has a `__parent__` attribute),
-
- >>> ob = folder.Folder()
- >>> ob.__parent__ = site
- >>> ob2 = folder.Folder()
- >>> ob2.__parent__ = ob
-
- we 'acquire' the closest site and return its site manager:
-
- >>> SiteManagerAdapter(ob) is sm
- True
- >>> SiteManagerAdapter(ob2) is sm
- True
-
- If we are unable to find a local site manager, then the global site
- manager is returned.
-
- >>> import zope.component
- >>> orphan = CustomFolder('orphan')
- >>> SiteManagerAdapter(orphan) is zope.component.getGlobalSiteManager()
- True
- """
-
-
-def test_setThreadSite_clearThreadSite():
- """
- This test ensures that the site is corectly set and cleared in a thread
- during traversal using event subscribers. Before we start, no site is set:
-
- >>> from zope.app.component import hooks
- >>> hooks.getSite() is None
- True
-
-
- >>> request = object()
-
- >>> from zope.app import publication
- >>> from zope.app.component import site
-
-
- On the other hand, if a site is traversed,
-
- >>> sm = SiteManagerStub()
- >>> mysite = CustomFolder('mysite')
- >>> mysite.setSiteManager(sm)
-
- >>> ev = publication.interfaces.BeforeTraverseEvent(mysite, request)
- >>> site.threadSiteSubscriber(mysite, ev)
-
- >>> hooks.getSite()
- <CustomFolder mysite>
-
- Once the request is completed,
-
- >>> ev = publication.interfaces.EndRequestEvent(mysite, request)
- >>> site.clearThreadSiteSubscriber(ev)
-
- the site assignment is cleared again:
-
- >>> hooks.getSite() is None
- True
- """
-
-class BaseTestSiteManagerContainer(unittest.TestCase):
- """This test is for objects that don't have site managers by
- default and that always give back the site manager they were
- given.
-
- Subclasses need to define a method, 'makeTestObject', that takes no
- arguments and that returns a new site manager
- container that has no site manager."""
-
- def test_IPossibleSite_verify(self):
- zope.interface.verify.verifyObject(IPossibleSite,
- self.makeTestObject())
-
- def test_get_and_set(self):
- smc = self.makeTestObject()
- self.failIf(ISite.providedBy(smc))
- sm = site.LocalSiteManager(smc)
- smc.setSiteManager(sm)
- self.failUnless(ISite.providedBy(smc))
- self.failUnless(smc.getSiteManager() is sm)
- zope.interface.verify.verifyObject(ISite, smc)
-
- def test_set_w_bogus_value(self):
- smc=self.makeTestObject()
- self.assertRaises(Exception, smc.setSiteManager, self)
-
-
-
-class SiteManagerContainerTest(BaseTestSiteManagerContainer):
- def makeTestObject(self):
- from zope.app.component.site import SiteManagerContainer
- return SiteManagerContainer()
-
-
-def setUp(test):
- setup.placefulSetUp()
-
-def tearDown(test):
- setup.placefulTearDown()
-
-def test_suite():
- return unittest.TestSuite((
- doctest.DocTestSuite(),
- unittest.makeSuite(SiteManagerContainerTest),
- doctest.DocFileSuite('../site.txt',
- setUp=setUp, tearDown=tearDown),
- ))
-
-if __name__ == "__main__":
- unittest.main(defaultTest='test_suite')
-
More information about the Checkins
mailing list