zope.component-4.0.2/ 0000775 0001750 0001750 00000000000 12070353060 014375 5 ustar tseaver tseaver zope.component-4.0.2/setup.cfg 0000664 0001750 0001750 00000000411 12070353060 016212 0 ustar tseaver tseaver [egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
[nosetests]
cover-package = zope.component
nocapture = 1
cover-erase = 1
with-doctest = 0
where = src
[aliases]
dev = develop easy_install zope.component[testing]
docs = easy_install zope.component[docs]
zope.component-4.0.2/buildout.cfg 0000664 0001750 0001750 00000001321 11774312422 016711 0 ustar tseaver tseaver [buildout]
develop = .
parts = test test_c_hookable python sphinx coverage-test coverage-report
unzip = true
[test]
recipe = zc.recipe.testrunner
eggs = zope.component [test,zcml,security,persistentregistry]
[coverage-test]
recipe = zc.recipe.testrunner
eggs = ${test:eggs}
defaults = ['--coverage', '../../coverage']
[coverage-report]
recipe = zc.recipe.egg
eggs = z3c.coverage
scripts = coverage=coverage-report
arguments = ('coverage', 'coverage/report')
[test_c_hookable]
recipe = zc.recipe.testrunner
eggs = zope.component [test,zcml,security,persistentregistry,hook]
[python]
recipe = zc.recipe.egg
interpreter = python
eggs = ${test:eggs}
[sphinx]
recipe = zc.recipe.egg
eggs =
Sphinx
zope.component
zope.component-4.0.2/PKG-INFO 0000664 0001750 0001750 00000031045 12070353060 015475 0 ustar tseaver tseaver Metadata-Version: 1.0
Name: zope.component
Version: 4.0.2
Summary: Zope Component Architecture
Home-page: http://pypi.python.org/pypi/zope.component
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: *****************************
zope.component Package Readme
*****************************
*This package is intended to be independently reusable in any Python
project. It is maintained by the* `Zope Toolkit project `_.
This package represents the core of the Zope Component Architecture.
Together with the 'zope.interface' package, it provides facilities for
defining, registering and looking up components.
Please see http://docs.zope.org/zope.component/ for the documentation.
.. contents::
CHANGES
*******
4.0.2 (2012-12-31)
==================
- Fleshed out PyPI Trove classifiers.
4.0.1 (2012-11-21)
==================
- Added support for Python 3.3.
4.0.0 (2012-07-02)
==================
- Added PyPy and Python 3.2 support:
- Security support omitted until ``zope.security`` ported.
- Persistent registry support omitted until ``ZODB`` ported (or
``persistent`` factored out).
- 100% unit test coverage.
- Removed the long-deprecated ``layer`` argument to the
``zope.component.zcml.view`` and ``zope.component.zcml.resource``
ZCML directives.
- Added support for continuous integration using ``tox`` and ``jenkins``.
- Got tests to run using ``setup.py test``.
- Added ``Sphinx`` documentation.
- Added ``setup.py docs`` alias (installs ``Sphinx`` and dependencies).
- Added ``setup.py dev`` alias (runs ``setup.py develop`` plus installs
``nose`` and ``coverage``).
3.12.1 (2012-04-02)
===================
- Wrap ``with site(foo)`` in try/finally (LP768151).
3.12.0 (2011-11-16)
===================
- Add convenience function zope.component.hooks.site (a contextmanager),
so one can write ``with site(foo): ...``.
3.11.0 (2011-09-22)
===================
- Moved code from ``zope.component.registry`` which implements a basic
nonperistent component registry to ``zope.interface.registry``. This code
was moved from ``zope.component`` into ``zope.interface`` to make porting
systems (such as Pyramid) that rely only on a basic component registry to
Python 3 possible without needing to port the entirety of the
``zope.component`` package. Backwards compatibility import shims have been
left behind in ``zope.component``, so this change will not break any
existing code.
- Interfaces moved from ``zope.component.interfaces`` to
``zope.interface.interfaces``: ``ComponentLookupError``, ``Invalid``,
``IObjectEvent``, ``ObjectEvent``, ``IComponentLookup``, ``IRegistration``,
``IUtilityRegistration``, ``IAdapterRegistration``,
``ISubscriptionAdapterRegistration``, ``IHandlerRegistration``,
``IRegistrationEvent``, ``RegistrationEvent``, ``IRegistered``,
``Registered``, ``IUnregistered``, ``Unregistered``,
``IComponentRegistry``, and ``IComponents``. Backwards compatibility shims
left in place.
- Depend on zope.interface >= 3.8.0.
3.10.0 (2010-09-25)
===================
- Got rid of the docs extra and the sphinxdoc recipe.
- Created a "security" extra to move security-related dependencies out of the
"test" extra.
- Use the new zope.testrunner package for tests.
- Added a basic test for the configure.zcml file provided.
3.9.5 (2010-07-09)
==================
- Fix test requirements specification.
3.9.4 (2010-04-30)
==================
- Prefer the standard libraries doctest module to the one from zope.testing.
3.9.3 (2010-03-08)
==================
- The ZCML directives provided by zope.component now register the components in
the registry returned by getSiteManager instead of the global registry. This
allows the hooking of the getSiteManager method before the load of a ZCML
file to register the components in a custom registry.
3.9.2 (2010-01-22)
==================
- Fixed a bug introduced by recent refactoring, where passing
CheckerPublic to securityAdapterFactory wrongly wrapped the factory
into a LocatingUntrustedAdapterFactory.
3.9.1 (2010-01-21)
==================
- The tested testrunner somehow gets influenced by options of the outer
testrunner, such a the -v option. We modified the tests so that it avoids
this.
3.9.0 (2010-01-21)
==================
- Add testlayer support. It is now possible to load a ZCML file within
tests more easily. See zope.component.testlayer.py and
zope.component.testlayer.txt.
3.8.0 (2009-11-16)
==================
- Removed the dependencies on zope.proxy and zope.security from the zcml extra:
zope.component does not hard depend on them anymore; the support for security
proxied components ZCML registrations is enabled only if zope.security and
zope.proxy are available.
- Moved the IPossibleSite and ISite interfaces here from zope.location as they
are dealing with zope.component's concept of a site, but not with location.
- Moved the zope.site.hooks functionality to zope.component.hooks as it isn't
actually dealing with zope.site's concept of a site.
3.7.1 (2009-07-24)
==================
- Fixed a problem, where ``queryNextUtility`` could fail if the context could
not be adapted to a ``IComponentLookup``.
- Fixed 2 related bugs:
When a utility is registered and there was previously a utility
registered for the same interface and name, then the old utility is
unregistered. The 2 bugs related to this:
- There was no ``Unregistered`` for the implicit unregistration. Now
there is.
- The old utility was still held and returned by
getAllUtilitiesRegisteredFor. In other words, it was still
considered registered, eeven though it wasn't. A particularly
negative consequence of this is that the utility is held in memory
or in the database even though it isn't used.
3.7.0 (2009-05-21)
==================
- The HookableTests were not run by the testrunner.
- Add in zope:view and zope:resource implementations into
zope.component.zcml (dependency loaded with zope.component [zcml]).
3.6.0 (2009-03-12)
==================
- IMPORTANT: the interfaces that were defined in the
zope.component.bbb.interfaces and deprecated for years are
now (re)moved. However, some packages, including part of zope
framework were still using those interfaces. They will be adapted
for this change. If you were using some of those interfaces, you
need to adapt your code as well:
- The IView and IDefaultViewName were moved to zope.publisher.interfaces.
- The IResource was moved to zope.app.publisher.interfaces.
- IContextDependent, IPresentation, IPresentationRequest,
IResourceFactory, IViewFactory were removed completely.
If you used IViewFactory in context of zope.app.form, there's now
IWidgetFactory in the zope.app.form.interfaces instead.
- Add getNextUtility/queryNextUtility functions that used to be in zope.site
earlier (and in zope.app.component even more earlier).
- Added a pure-Python 'hookable' implementation, for use when
'zope.hookable' is not present.
- Removed use of 'zope.deferredimport' by breaking import cycles.
- Cleanup package documentation and changelog a bit. Add sphinx-based
documentation building command to the buildout.
- Remove deprecated code.
- Change package's mailing list address to zope-dev at zope.org, because
zope3-dev at zope.org is now retired.
3.5.1 (2008-07-25)
==================
- Fix bug introduced in 3.5.0: no longer supported
interfaces declared in Python and always wanted an explicit provides="..."
attribute. https://bugs.launchpad.net/zope3/+bug/251865
3.5.0 (2008-07-25)
==================
- Support registration of utilities via factories through the component registry
and return factory information in the registration information. This fixes
https://bugs.launchpad.net/zope3/+bug/240631
- Optimized un/registerUtility via storing an optimized data structure for
efficient retrieval of already registered utilities. This avoids looping over
all utilities when registering a new one.
3.4.0 (2007-09-29)
==================
No further changes since 3.4.0a1.
3.4.0a1 (2007-04-22)
====================
Corresponds to zope.component from Zope 3.4.0a1.
- In the Zope 3.3.x series, ``zope.component`` was simplified yet once
more. See http://wiki.zope.org/zope3/LocalComponentManagementSimplification
for the proposal describing the changes.
3.2.0.2 (2006-04-15)
====================
- Fix packaging bug: 'package_dir' must be a *relative* path.
3.2.0.1 (2006-04-14)
====================
- Packaging change: suppress inclusion of 'setup.cfg' in 'sdist' builds.
3.2.0 (2006-01-05)
==================
Corresponds to the verison of the zope.component package shipped as part of
the Zope 3.2.0 release.
- Deprecated services and related APIs. The adapter and utility registries
are now available directly via the site manager's 'adapters' and 'utilities'
attributes, respectively. Services are accessible, but deprecated, and
will be removed in Zope 3.3.
- Deprectaed all presentation-related APIs, including all view-related
API functions. Use the adapter API functions instead.
See http://dev.zope.org/Zope3/ImplementViewsAsAdapters`
- Deprecated 'contextdependent' package: site managers are now looked up
via a thread global, set during URL traversal. The 'context' argument
is now always optional, and should no longer be passed.
3.0.0 (2004-11-07)
==================
Corresponds to the verison of the zope.component package shipped as part of
the Zope X3.0.0 release.
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved
Classifier: License :: OSI Approved :: Zope Public License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.2
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Framework :: Zope3
Classifier: Topic :: Software Development :: Libraries :: Python Modules
zope.component-4.0.2/tox.ini 0000664 0001750 0001750 00000006754 12053235152 015726 0 ustar tseaver tseaver [tox]
envlist =
# Jython support pending 2.7 support, due 2012-07-15 or so. See:
# http://fwierzbicki.blogspot.com/2012/03/adconion-to-fund-jython-27.html
# py26,py27,py32,jython,pypy,coverage,docs
py26,py26min,py27,pypy,py32,py33,coverage,docs
[testenv]
deps =
zope.component
zope.testing
zope.hookable
ZODB3
zope.location
zope.proxy
zope.security
zope.configuration
zope.i18nmessageid
commands =
python setup.py test -q
[testenv:jython]
commands =
jython setup.py test -q
[nosy]
prep =
pip uninstall -y zope.component
python -c "import shutil; shutil.copyfile('src/zope/__init__.py', '{envdir}/lib/python2.6/site-packages/zope/__init__.py')"
pip install -e .
[testenv:py26min]
basepython =
python2.6
deps =
zope.component
zope.interface
zope.event
zope.hookable
zope.configuration
zope.schema
zope.i18nmessageid
nose
commands =
pip uninstall -y zope.component
python -c "import shutil; shutil.copyfile('src/zope/__init__.py', '{envdir}/lib/python2.6/site-packages/zope/__init__.py')"
pip install -e .
nosetests -I persistentregistry -I security
[testenv:py32]
deps =
zope.component
zope.interface
zope.event
zope.hookable
zope.configuration
zope.schema
zope.i18nmessageid
nose
commands =
pip uninstall -y zope.component
python -c "import shutil; shutil.copyfile('src/zope/__init__.py', '{envdir}/lib/python3.2/site-packages/zope/__init__.py')"
pip install -e .
nosetests -I persistentregistry -I security
[testenv:py33]
deps =
zope.component
zope.interface
zope.event
zope.hookable
zope.configuration
zope.schema
zope.i18nmessageid
nose
commands =
pip uninstall -y zope.component
python -c "import shutil; shutil.copyfile('src/zope/__init__.py', '{envdir}/lib/python3.3/site-packages/zope/__init__.py')"
pip install -e .
nosetests -I persistentregistry -I security
[testenv:pypy]
deps =
zope.component
zope.interface
zope.event
zope.hookable
zope.configuration
zope.schema
zope.i18nmessageid
nose
commands =
pip uninstall -y zope.component
python -c "import shutil; shutil.copyfile('{toxinidir}/src/zope/__init__.py', '{envdir}/site-packages/zope/__init__.py')"
pip install -e .
nosetests -I persistentregistry -I security
[testenv:coverage]
basepython =
python2.6
commands =
# The installed version messes up nose's test discovery / coverage reporting
# So, we uninstall that from the environment, and then install the editable
# version, before running nosetests.
pip uninstall -y zope.component
python -c "import shutil; shutil.copyfile('src/zope/__init__.py', '{envdir}/lib/python2.6/site-packages/zope/__init__.py')"
pip install -e .
nosetests --with-xunit --with-xcoverage
deps =
zope.component
zope.testing
zope.hookable
ZODB3
zope.location
zope.proxy
zope.security
zope.configuration
zope.i18nmessageid
nose
coverage
nosexcover
[testenv:docs]
basepython =
python2.6
commands =
sphinx-build -b html -d docs/_build/doctrees docs docs/_build/html
sphinx-build -b doctest -d docs/_build/doctrees docs docs/_build/doctest
deps =
zope.component
zope.testing
zope.hookable
ZODB3
zope.location
zope.proxy
zope.security
zope.configuration
zope.i18nmessageid
Sphinx
repoze.sphinx.autointerface
# Ugh. Need this for docs/testlayer.rst
zope.testrunner
zope.component-4.0.2/setup.py 0000664 0001750 0001750 00000010526 12070352754 016124 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2004 Zope Foundation 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.
#
##############################################################################
# This package is developed by the Zope Toolkit project, documented here:
# http://docs.zope.org/zopetoolkit
# When developing and releasing this package, please follow the documented
# Zope Toolkit policies as described by this documentation.
##############################################################################
"""Setup for zope.component package
"""
import os
from setuptools import setup, find_packages
TESTS_REQUIRE = [
'zope.testing',
'zope.component[hook]',
'zope.component[persistentregistry]',
'zope.component[security]',
'zope.component[zcml]',
]
def _modname(path, base, name=''):
if path == base:
return name
dirname, basename = os.path.split(path)
return _modname(dirname, base, basename + '.' + name)
def alltests():
import logging
import pkg_resources
import unittest
class NullHandler(logging.Handler):
level = 50
def emit(self, record):
pass
logging.getLogger().addHandler(NullHandler())
suite = unittest.TestSuite()
base = pkg_resources.working_set.find(
pkg_resources.Requirement.parse('zope.component')).location
for dirpath, dirnames, filenames in os.walk(base):
if os.path.basename(dirpath) == 'tests':
for filename in filenames:
if ( filename.endswith('.py') and
filename.startswith('test') ):
mod = __import__(
_modname(dirpath, base, os.path.splitext(filename)[0]),
{}, {}, ['*'])
suite.addTest(mod.test_suite())
return suite
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(
name='zope.component',
version='4.0.2',
url='http://pypi.python.org/pypi/zope.component',
license='ZPL 2.1',
description='Zope Component Architecture',
author='Zope Foundation and Contributors',
author_email='zope-dev@zope.org',
long_description=(
read('README.txt')
+ '\n' +
read('CHANGES.txt')
),
packages = find_packages('src'),
package_dir = {'': 'src'},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved",
"License :: OSI Approved :: Zope Public License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Framework :: Zope3",
"Topic :: Software Development :: Libraries :: Python Modules",
],
namespace_packages=['zope',],
tests_require = TESTS_REQUIRE,
test_suite='__main__.alltests',
install_requires=['setuptools',
'zope.interface>=3.8.0',
'zope.event',
],
include_package_data = True,
zip_safe = False,
extras_require = {
'hook': ['zope.hookable'],
'persistentregistry': ['ZODB3'],
'security': ['zope.location',
'zope.proxy',
'zope.security',
],
'zcml': ['zope.configuration',
'zope.i18nmessageid',
],
'test': TESTS_REQUIRE,
'testing': TESTS_REQUIRE + ['nose', 'coverage'],
'docs': ['Sphinx', 'repoze.sphinx.autointerface'],
},
)
zope.component-4.0.2/bootstrap.py 0000664 0001750 0001750 00000007330 11774312422 016776 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2006 Zope Foundation 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.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os, shutil, sys, tempfile, urllib2
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
is_jython = sys.platform.startswith('java')
# parsing arguments
parser = OptionParser()
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="distribute", default=False,
help="Use Disribute rather than Setuptools.")
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.version is not None:
VERSION = '==%s' % options.version
else:
VERSION = ''
USE_DISTRIBUTE = options.distribute
args = args + ['bootstrap']
to_reload = False
try:
import pkg_resources
if not hasattr(pkg_resources, '_distribute'):
to_reload = True
raise ImportError
except ImportError:
ez = {}
if USE_DISTRIBUTE:
exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True)
else:
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
if to_reload:
reload(pkg_resources)
else:
import pkg_resources
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
def quote (c):
return c
cmd = 'from setuptools.command.easy_install import main; main()'
ws = pkg_resources.working_set
if USE_DISTRIBUTE:
requirement = 'distribute'
else:
requirement = 'setuptools'
if is_jython:
import subprocess
assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd',
quote(tmpeggs), 'zc.buildout' + VERSION],
env=dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
).wait() == 0
else:
assert os.spawnle(
os.P_WAIT, sys.executable, quote (sys.executable),
'-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION,
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
) == 0
ws.add_entry(tmpeggs)
ws.require('zc.buildout' + VERSION)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs)
zope.component-4.0.2/.bzrignore 0000664 0001750 0001750 00000000211 11774312422 016400 0 ustar tseaver tseaver ./.installed.cfg
./bin
./eggs
./develop-eggs
./docs
./parts
*.egg-info
.coverage
docs/_build
.tox
nosetests.xml
coverage.xml
__pycache__
zope.component-4.0.2/src/ 0000775 0001750 0001750 00000000000 12070353060 015164 5 ustar tseaver tseaver zope.component-4.0.2/src/zope.component.egg-info/ 0000775 0001750 0001750 00000000000 12070353060 021634 5 ustar tseaver tseaver zope.component-4.0.2/src/zope.component.egg-info/top_level.txt 0000664 0001750 0001750 00000000005 12070353060 024361 0 ustar tseaver tseaver zope
zope.component-4.0.2/src/zope.component.egg-info/SOURCES.txt 0000664 0001750 0001750 00000004553 12070353060 023527 0 ustar tseaver tseaver .bzrignore
CHANGES.txt
COPYRIGHT.txt
LICENSE.txt
README.txt
bootstrap.py
buildout.cfg
setup.cfg
setup.py
tox.ini
docs/Makefile
docs/api.rst
docs/conf.py
docs/configure.rst
docs/event.rst
docs/factory.rst
docs/hacking.rst
docs/hooks.rst
docs/index.rst
docs/make.bat
docs/narr.rst
docs/persistentregistry.rst
docs/socketexample.rst
docs/testlayer.rst
docs/zcml.rst
docs/api/adapter.rst
docs/api/factory.rst
docs/api/interface.rst
docs/api/interfaces.rst
docs/api/persistent.rst
docs/api/security.rst
docs/api/sitemanager.rst
docs/api/utility.rst
src/zope/__init__.py
src/zope.component.egg-info/PKG-INFO
src/zope.component.egg-info/SOURCES.txt
src/zope.component.egg-info/dependency_links.txt
src/zope.component.egg-info/namespace_packages.txt
src/zope.component.egg-info/not-zip-safe
src/zope.component.egg-info/requires.txt
src/zope.component.egg-info/top_level.txt
src/zope/component/__init__.py
src/zope/component/_api.py
src/zope/component/_compat.py
src/zope/component/_declaration.py
src/zope/component/configure.zcml
src/zope/component/event.py
src/zope/component/eventtesting.py
src/zope/component/factory.py
src/zope/component/globalregistry.py
src/zope/component/hookable.py
src/zope/component/hooks.py
src/zope/component/interface.py
src/zope/component/interfaces.py
src/zope/component/meta.zcml
src/zope/component/persistentregistry.py
src/zope/component/registry.py
src/zope/component/security.py
src/zope/component/standalonetests.py
src/zope/component/testing.py
src/zope/component/testlayer.py
src/zope/component/zcml.py
src/zope/component/testfiles/__init__.py
src/zope/component/testfiles/adapter.py
src/zope/component/testfiles/components.py
src/zope/component/testfiles/testlayer.zcml
src/zope/component/testfiles/views.py
src/zope/component/tests/__init__.py
src/zope/component/tests/examples.py
src/zope/component/tests/test___init__.py
src/zope/component/tests/test__api.py
src/zope/component/tests/test__declaration.py
src/zope/component/tests/test_event.py
src/zope/component/tests/test_factory.py
src/zope/component/tests/test_globalregistry.py
src/zope/component/tests/test_hookable.py
src/zope/component/tests/test_hooks.py
src/zope/component/tests/test_interface.py
src/zope/component/tests/test_persistentregistry.py
src/zope/component/tests/test_registry.py
src/zope/component/tests/test_security.py
src/zope/component/tests/test_standalone.py
src/zope/component/tests/test_zcml.py zope.component-4.0.2/src/zope.component.egg-info/PKG-INFO 0000664 0001750 0001750 00000031045 12070353060 022734 0 ustar tseaver tseaver Metadata-Version: 1.0
Name: zope.component
Version: 4.0.2
Summary: Zope Component Architecture
Home-page: http://pypi.python.org/pypi/zope.component
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: *****************************
zope.component Package Readme
*****************************
*This package is intended to be independently reusable in any Python
project. It is maintained by the* `Zope Toolkit project `_.
This package represents the core of the Zope Component Architecture.
Together with the 'zope.interface' package, it provides facilities for
defining, registering and looking up components.
Please see http://docs.zope.org/zope.component/ for the documentation.
.. contents::
CHANGES
*******
4.0.2 (2012-12-31)
==================
- Fleshed out PyPI Trove classifiers.
4.0.1 (2012-11-21)
==================
- Added support for Python 3.3.
4.0.0 (2012-07-02)
==================
- Added PyPy and Python 3.2 support:
- Security support omitted until ``zope.security`` ported.
- Persistent registry support omitted until ``ZODB`` ported (or
``persistent`` factored out).
- 100% unit test coverage.
- Removed the long-deprecated ``layer`` argument to the
``zope.component.zcml.view`` and ``zope.component.zcml.resource``
ZCML directives.
- Added support for continuous integration using ``tox`` and ``jenkins``.
- Got tests to run using ``setup.py test``.
- Added ``Sphinx`` documentation.
- Added ``setup.py docs`` alias (installs ``Sphinx`` and dependencies).
- Added ``setup.py dev`` alias (runs ``setup.py develop`` plus installs
``nose`` and ``coverage``).
3.12.1 (2012-04-02)
===================
- Wrap ``with site(foo)`` in try/finally (LP768151).
3.12.0 (2011-11-16)
===================
- Add convenience function zope.component.hooks.site (a contextmanager),
so one can write ``with site(foo): ...``.
3.11.0 (2011-09-22)
===================
- Moved code from ``zope.component.registry`` which implements a basic
nonperistent component registry to ``zope.interface.registry``. This code
was moved from ``zope.component`` into ``zope.interface`` to make porting
systems (such as Pyramid) that rely only on a basic component registry to
Python 3 possible without needing to port the entirety of the
``zope.component`` package. Backwards compatibility import shims have been
left behind in ``zope.component``, so this change will not break any
existing code.
- Interfaces moved from ``zope.component.interfaces`` to
``zope.interface.interfaces``: ``ComponentLookupError``, ``Invalid``,
``IObjectEvent``, ``ObjectEvent``, ``IComponentLookup``, ``IRegistration``,
``IUtilityRegistration``, ``IAdapterRegistration``,
``ISubscriptionAdapterRegistration``, ``IHandlerRegistration``,
``IRegistrationEvent``, ``RegistrationEvent``, ``IRegistered``,
``Registered``, ``IUnregistered``, ``Unregistered``,
``IComponentRegistry``, and ``IComponents``. Backwards compatibility shims
left in place.
- Depend on zope.interface >= 3.8.0.
3.10.0 (2010-09-25)
===================
- Got rid of the docs extra and the sphinxdoc recipe.
- Created a "security" extra to move security-related dependencies out of the
"test" extra.
- Use the new zope.testrunner package for tests.
- Added a basic test for the configure.zcml file provided.
3.9.5 (2010-07-09)
==================
- Fix test requirements specification.
3.9.4 (2010-04-30)
==================
- Prefer the standard libraries doctest module to the one from zope.testing.
3.9.3 (2010-03-08)
==================
- The ZCML directives provided by zope.component now register the components in
the registry returned by getSiteManager instead of the global registry. This
allows the hooking of the getSiteManager method before the load of a ZCML
file to register the components in a custom registry.
3.9.2 (2010-01-22)
==================
- Fixed a bug introduced by recent refactoring, where passing
CheckerPublic to securityAdapterFactory wrongly wrapped the factory
into a LocatingUntrustedAdapterFactory.
3.9.1 (2010-01-21)
==================
- The tested testrunner somehow gets influenced by options of the outer
testrunner, such a the -v option. We modified the tests so that it avoids
this.
3.9.0 (2010-01-21)
==================
- Add testlayer support. It is now possible to load a ZCML file within
tests more easily. See zope.component.testlayer.py and
zope.component.testlayer.txt.
3.8.0 (2009-11-16)
==================
- Removed the dependencies on zope.proxy and zope.security from the zcml extra:
zope.component does not hard depend on them anymore; the support for security
proxied components ZCML registrations is enabled only if zope.security and
zope.proxy are available.
- Moved the IPossibleSite and ISite interfaces here from zope.location as they
are dealing with zope.component's concept of a site, but not with location.
- Moved the zope.site.hooks functionality to zope.component.hooks as it isn't
actually dealing with zope.site's concept of a site.
3.7.1 (2009-07-24)
==================
- Fixed a problem, where ``queryNextUtility`` could fail if the context could
not be adapted to a ``IComponentLookup``.
- Fixed 2 related bugs:
When a utility is registered and there was previously a utility
registered for the same interface and name, then the old utility is
unregistered. The 2 bugs related to this:
- There was no ``Unregistered`` for the implicit unregistration. Now
there is.
- The old utility was still held and returned by
getAllUtilitiesRegisteredFor. In other words, it was still
considered registered, eeven though it wasn't. A particularly
negative consequence of this is that the utility is held in memory
or in the database even though it isn't used.
3.7.0 (2009-05-21)
==================
- The HookableTests were not run by the testrunner.
- Add in zope:view and zope:resource implementations into
zope.component.zcml (dependency loaded with zope.component [zcml]).
3.6.0 (2009-03-12)
==================
- IMPORTANT: the interfaces that were defined in the
zope.component.bbb.interfaces and deprecated for years are
now (re)moved. However, some packages, including part of zope
framework were still using those interfaces. They will be adapted
for this change. If you were using some of those interfaces, you
need to adapt your code as well:
- The IView and IDefaultViewName were moved to zope.publisher.interfaces.
- The IResource was moved to zope.app.publisher.interfaces.
- IContextDependent, IPresentation, IPresentationRequest,
IResourceFactory, IViewFactory were removed completely.
If you used IViewFactory in context of zope.app.form, there's now
IWidgetFactory in the zope.app.form.interfaces instead.
- Add getNextUtility/queryNextUtility functions that used to be in zope.site
earlier (and in zope.app.component even more earlier).
- Added a pure-Python 'hookable' implementation, for use when
'zope.hookable' is not present.
- Removed use of 'zope.deferredimport' by breaking import cycles.
- Cleanup package documentation and changelog a bit. Add sphinx-based
documentation building command to the buildout.
- Remove deprecated code.
- Change package's mailing list address to zope-dev at zope.org, because
zope3-dev at zope.org is now retired.
3.5.1 (2008-07-25)
==================
- Fix bug introduced in 3.5.0: no longer supported
interfaces declared in Python and always wanted an explicit provides="..."
attribute. https://bugs.launchpad.net/zope3/+bug/251865
3.5.0 (2008-07-25)
==================
- Support registration of utilities via factories through the component registry
and return factory information in the registration information. This fixes
https://bugs.launchpad.net/zope3/+bug/240631
- Optimized un/registerUtility via storing an optimized data structure for
efficient retrieval of already registered utilities. This avoids looping over
all utilities when registering a new one.
3.4.0 (2007-09-29)
==================
No further changes since 3.4.0a1.
3.4.0a1 (2007-04-22)
====================
Corresponds to zope.component from Zope 3.4.0a1.
- In the Zope 3.3.x series, ``zope.component`` was simplified yet once
more. See http://wiki.zope.org/zope3/LocalComponentManagementSimplification
for the proposal describing the changes.
3.2.0.2 (2006-04-15)
====================
- Fix packaging bug: 'package_dir' must be a *relative* path.
3.2.0.1 (2006-04-14)
====================
- Packaging change: suppress inclusion of 'setup.cfg' in 'sdist' builds.
3.2.0 (2006-01-05)
==================
Corresponds to the verison of the zope.component package shipped as part of
the Zope 3.2.0 release.
- Deprecated services and related APIs. The adapter and utility registries
are now available directly via the site manager's 'adapters' and 'utilities'
attributes, respectively. Services are accessible, but deprecated, and
will be removed in Zope 3.3.
- Deprectaed all presentation-related APIs, including all view-related
API functions. Use the adapter API functions instead.
See http://dev.zope.org/Zope3/ImplementViewsAsAdapters`
- Deprecated 'contextdependent' package: site managers are now looked up
via a thread global, set during URL traversal. The 'context' argument
is now always optional, and should no longer be passed.
3.0.0 (2004-11-07)
==================
Corresponds to the verison of the zope.component package shipped as part of
the Zope X3.0.0 release.
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved
Classifier: License :: OSI Approved :: Zope Public License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.2
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Framework :: Zope3
Classifier: Topic :: Software Development :: Libraries :: Python Modules
zope.component-4.0.2/src/zope.component.egg-info/dependency_links.txt 0000664 0001750 0001750 00000000001 12070353060 025702 0 ustar tseaver tseaver
zope.component-4.0.2/src/zope.component.egg-info/not-zip-safe 0000664 0001750 0001750 00000000001 12070353036 024065 0 ustar tseaver tseaver
zope.component-4.0.2/src/zope.component.egg-info/namespace_packages.txt 0000664 0001750 0001750 00000000005 12070353060 026162 0 ustar tseaver tseaver zope
zope.component-4.0.2/src/zope.component.egg-info/requires.txt 0000664 0001750 0001750 00000000760 12070353060 024237 0 ustar tseaver tseaver setuptools
zope.interface>=3.8.0
zope.event
[persistentregistry]
ZODB3
[docs]
Sphinx
repoze.sphinx.autointerface
[testing]
zope.testing
zope.component[hook]
zope.component[persistentregistry]
zope.component[security]
zope.component[zcml]
nose
coverage
[hook]
zope.hookable
[zcml]
zope.configuration
zope.i18nmessageid
[test]
zope.testing
zope.component[hook]
zope.component[persistentregistry]
zope.component[security]
zope.component[zcml]
[security]
zope.location
zope.proxy
zope.security zope.component-4.0.2/src/zope/ 0000775 0001750 0001750 00000000000 12070353060 016141 5 ustar tseaver tseaver zope.component-4.0.2/src/zope/component/ 0000775 0001750 0001750 00000000000 12070353060 020143 5 ustar tseaver tseaver zope.component-4.0.2/src/zope/component/standalonetests.py 0000664 0001750 0001750 00000002033 11774312422 023735 0 ustar tseaver tseaver """
See: https://bugs.launchpad.net/zope3/+bug/98401
"""
import sys
import pickle
def write(x):
sys.stdout.write('%s\n' % x)
if __name__ == "__main__": #pragma NO COVER (runs in subprocess)
#sys.path = pickle.loads(sys.stdin.read())
write('XXXXXXXXXX')
for p in sys.path:
write('- %s' % p)
write('XXXXXXXXXX')
import zope
from zope.interface import Interface
from zope.interface import implementer
class I1(Interface):
pass
class I2(Interface):
pass
@implementer(I1)
class Ob(object):
def __repr__(self):
return ''
ob = Ob()
@implementer(I2)
class Comp(object):
def __init__(self, context):
self.context = context
write('YYYYYYYYY')
for p in zope.__path__:
write('- %s' % p)
write('YYYYYYYYY')
import zope.component
zope.component.provideAdapter(Comp, (I1,), I2)
adapter = I2(ob)
write('ZZZZZZZZ')
assert adapter.__class__ is Comp
assert adapter.context is ob
zope.component-4.0.2/src/zope/component/testing.py 0000664 0001750 0001750 00000002355 11774312422 022206 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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
"""
# HACK to make sure basicmost event subscriber is installed
import zope.component.event
# we really don't need special setup now:
try:
from zope.testing.cleanup import CleanUp as PlacelessSetup
except ImportError:
class PlacelessSetup(object):
def cleanUp(self):
from zope.component.globalregistry import base
base.__init__('base')
def setUp(self):
self.cleanUp()
def tearDown(self):
self.cleanUp()
def setUp(test=None):
PlacelessSetup().setUp()
def tearDown(test=None):
PlacelessSetup().tearDown()
zope.component-4.0.2/src/zope/component/testlayer.py 0000664 0001750 0001750 00000010130 11774312422 022533 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2010 Zope Foundation 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.
#
##############################################################################
import os
from zope.configuration import xmlconfig, config
try:
from zope.testing.cleanup import cleanUp
except ImportError:
def cleanUp():
pass
from zope.component import provideHandler
from zope.component.hooks import setHooks
from zope.component.eventtesting import events, clearEvents
class LayerBase(object):
"""Sane layer base class.
zope.testing implements an advanced mechanism so that layer setUp,
tearDown, testSetUp and testTearDown code gets called in the right
order. These methods are supposed to be @classmethods and should
not use super() as the test runner is supposed to take care of that.
In practice, this mechanism turns out not to be useful and
overcomplicated. It becomes difficult to pass information into
layers (such as a ZCML file to load), because the only way to pass
in information is to subclass, and subclassing these layers leads
to a range of interactions that is hard to reason about.
We'd rather just use Python and the super mechanism, as we know how
to reason about that. This base class is a hack to make this
possible.
The hack requires us to set __bases__, __module__ and
__name__. This fools zope.testing into thinking that this layer
instance is a class it can work with.
It'd be better if zope.testing just called a minimal API and
didn't try to be fancy. Fancy layer inheritance mechanisms can
then be implemented elsewhere if people want to. But unfortunately
it does implement a fancy mechanism and we need to fool it.
"""
__bases__ = ()
def __init__(self, package, name=None):
if name is None:
name = self.__class__.__name__
self.__name__ = name
self.__module__ = package.__name__
self.package = package
def setUp(self):
pass
def tearDown(self):
pass
def testSetUp(self):
pass
def testTearDown(self):
pass
class ZCMLLayerBase(LayerBase):
"""Base class to load up some ZCML.
"""
def __init__(self, package, name=None, features=None):
super(ZCMLLayerBase, self).__init__(package, name)
self.features = features or []
def setUp(self):
setHooks()
context = config.ConfigurationMachine()
xmlconfig.registerCommonDirectives(context)
for feature in self.features:
context.provideFeature(feature)
self.context = self._load_zcml(context)
provideHandler(events.append, (None,))
def testTearDown(self):
clearEvents()
def tearDown(self):
cleanUp()
def _load_zcml(self, context):
raise NotImplementedError
class ZCMLFileLayer(ZCMLLayerBase):
"""This layer can be used to run tests with a ZCML file loaded.
The ZCML file is assumed to include sufficient (meta)configuration
so that it can be interpreted itself. I.e. to create a ZCMLLayer
based on another ZCMLLayer's ZCML, just use a ZCML include
statement in your own ZCML to load it.
"""
def __init__(self, package, zcml_file='ftesting.zcml',
name=None, features=None):
super(ZCMLFileLayer, self).__init__(package, name, features)
self.zcml_file = os.path.join(os.path.dirname(package.__file__),
zcml_file)
def _load_zcml(self, context):
return xmlconfig.file(self.zcml_file,
package=self.package,
context=context, execute=True)
zope.component-4.0.2/src/zope/component/_api.py 0000664 0001750 0001750 00000021516 11774312422 021441 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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
"""
import sys
import types
from zope.interface import Interface
from zope.interface import implementedBy
from zope.interface import providedBy
from zope.component.interfaces import IComponentArchitecture
from zope.component.interfaces import IComponentRegistrationConvenience
from zope.component.interfaces import IFactory
from zope.component.interfaces import ComponentLookupError
from zope.component.interfaces import IComponentLookup
from zope.component._compat import _BLANK
from zope.component._declaration import adaptedBy
from zope.component._declaration import adapter
from zope.component._declaration import adapts
# Use the C implementation in zope.hookable, if available; fall back
# to our Python version if not.
try:
from zope.hookable import hookable
except ImportError: #pragma NO COVER
from zope.component.hookable import hookable
# getSiteManager() returns a component registry. Although the term
# "site manager" is deprecated in favor of "component registry",
# the old term is kept around to maintain a stable API.
base = None
@hookable
def getSiteManager(context=None):
""" See IComponentArchitecture.
"""
global base
if context is None:
if base is None:
from zope.component.globalregistry import base
return base
else:
# Use the global site manager to adapt context to `IComponentLookup`
# to avoid the recursion implied by using a local `getAdapter()` call.
try:
return IComponentLookup(context)
except TypeError as error:
raise ComponentLookupError(*error.args)
# 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=_BLANK, 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=_BLANK, 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=_BLANK, 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=_BLANK, 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):
getSiteManager(None).subscribers(objects, 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, '')`.
@hookable
def adapter_hook(interface, object, name='', default=None):
try:
sitemanager = getSiteManager()
except ComponentLookupError: #pragma NO COVER w/o context, cannot test
# Oh blast, no site manager. This should *never* happen!
return None
return sitemanager.queryAdapter(object, interface, name, default)
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)
_marker = object()
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.
"""
try:
sm = getSiteManager(context)
except ComponentLookupError:
return default
bases = sm.__bases__
for base in bases:
util = base.queryUtility(interface, name, _marker)
if util is not _marker:
return util
return default
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
# Factories
def createObject(__factory_name, *args, **kwargs):
"""Invoke the named factory and return the result.
``__factory_name`` is a positional-only argument.
"""
context = kwargs.pop('context', None)
return getUtility(IFactory, __factory_name, context)(*args, **kwargs)
def getFactoryInterfaces(name, context=None):
"""Return the interface provided by the named factory's objects
Result might be a single interface. XXX
"""
return getUtility(IFactory, name, context).getInterfaces()
def getFactoriesFor(interface, context=None):
"""Return info on all factories implementing the given interface.
"""
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
zope.component-4.0.2/src/zope/component/_compat.py 0000664 0001750 0001750 00000002042 11774312422 022144 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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.
#
##############################################################################
import sys
import types
if sys.version_info[0] < 3: #pragma NO COVER
import cPickle as _pickle
def _u(s):
return unicode(s, 'unicode_escape')
CLASS_TYPES = (type, types.ClassType)
PYTHON3 = False
PYTHON2 = True
else: #pragma NO COVER
import pickle as _pickle
def _u(s):
return s
CLASS_TYPES = (type,)
PYTHON3 = True
PYTHON2 = False
_BLANK = _u('')
zope.component-4.0.2/src/zope/component/meta.zcml 0000664 0001750 0001750 00000002177 11774312422 021776 0 ustar tseaver tseaver
zope.component-4.0.2/src/zope/component/__init__.py 0000664 0001750 0001750 00000005224 11774312422 022266 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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
"""
from zope.interface import Interface
from zope.interface import implementedBy
from zope.interface import moduleProvides
from zope.interface import providedBy
from zope.component.interfaces import ComponentLookupError
from zope.component.interfaces import IComponentArchitecture
from zope.component.interfaces import IComponentLookup
from zope.component.interfaces import IComponentRegistrationConvenience
from zope.component.interfaces import IFactory
from zope.component.globalregistry import getGlobalSiteManager
from zope.component.globalregistry import globalSiteManager
from zope.component.globalregistry import provideAdapter
from zope.component.globalregistry import provideHandler
from zope.component.globalregistry import provideSubscriptionAdapter
from zope.component.globalregistry import provideUtility
from zope.component._api import adapter_hook
from zope.component._api import createObject
from zope.component._api import getAdapter
from zope.component._api import getAdapterInContext
from zope.component._api import getAdapters
from zope.component._api import getAllUtilitiesRegisteredFor
from zope.component._api import getFactoriesFor
from zope.component._api import getFactoryInterfaces
from zope.component._api import getMultiAdapter
from zope.component._api import getSiteManager
from zope.component._api import getUtilitiesFor
from zope.component._api import getUtility
from zope.component._api import getNextUtility
from zope.component._api import handle
from zope.component._api import queryAdapter
from zope.component._api import queryAdapterInContext
from zope.component._api import queryMultiAdapter
from zope.component._api import queryUtility
from zope.component._api import queryNextUtility
from zope.component._api import subscribers
from zope.component._declaration import adaptedBy
from zope.component._declaration import adapter
from zope.component._declaration import adapts
moduleProvides(IComponentArchitecture, IComponentRegistrationConvenience)
__all__ = tuple(IComponentArchitecture)
zope.component-4.0.2/src/zope/component/_declaration.py 0000664 0001750 0001750 00000003450 11774312422 023152 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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.
#
##############################################################################
"""Adapter declarations
"""
import sys
from zope.component._compat import CLASS_TYPES
class adapter(object):
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
# Ensure we were called from a class def.
if locals is frame.f_globals or '__module__' not in locals:
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)
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__')
zope.component-4.0.2/src/zope/component/testfiles/ 0000775 0001750 0001750 00000000000 12070353060 022145 5 ustar tseaver tseaver zope.component-4.0.2/src/zope/component/testfiles/__init__.py 0000664 0001750 0001750 00000000020 11774312422 024255 0 ustar tseaver tseaver #Python package
zope.component-4.0.2/src/zope/component/testfiles/testlayer.zcml 0000664 0001750 0001750 00000000462 11774312422 025061 0 ustar tseaver tseaver
zope.component-4.0.2/src/zope/component/testfiles/adapter.py 0000664 0001750 0001750 00000002675 11774312422 024160 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2004 Zope Foundation 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.
#
##############################################################################
"""Sample adapter class for testing
"""
from zope.interface import Interface
from zope.interface import implementer
from zope.component import adapter
from zope.component.testfiles import components
class I1(Interface):
pass
class I2(Interface):
pass
class I3(Interface):
def f1(): pass
def f2(): pass
def f3(): pass
class IS(Interface):
pass
class Adapter(object):
def __init__(self, *args):
self.context = args
@implementer(I1)
class A1(Adapter):
pass
@implementer(I2)
class A2(Adapter):
pass
@adapter(components.IContent, I1, I2)
@implementer(I3)
class A3(Adapter):
pass
class A4:
pass
a4 = A4()
@implementer(I1, I2)
class A5:
pass
a5 = A5()
def Handler(content, *args):
# uninteresting handler
content.args = getattr(content, 'args', ()) + (args, )
zope.component-4.0.2/src/zope/component/testfiles/views.py 0000664 0001750 0001750 00000002715 11774312422 023670 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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.
#
##############################################################################
"""Views test.
"""
from zope.interface import Interface
from zope.interface import implementer
from zope.interface import directlyProvides
class Request(object):
def __init__(self, type):
directlyProvides(self, type)
class IR(Interface):
pass
class IV(Interface):
def index():
pass
class IC(Interface): pass
@implementer(IV)
class V1(object):
def __init__(self, context, request):
self.context = context
self.request = request
def index(self):
return 'V1 here'
def action(self):
return 'done'
class VZMI(V1):
def index(self):
return 'ZMI here'
@implementer(IV)
class R1(object):
def index(self):
return 'R1 here'
def action(self):
return 'R done'
def __init__(self, request):
pass
class RZMI(R1):
pass
zope.component-4.0.2/src/zope/component/testfiles/components.py 0000664 0001750 0001750 00000002705 11774312422 024717 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2002 Zope Foundation 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
"""
from zope.interface import Interface
from zope.interface import Attribute
from zope.interface import implementer
from zope.component import adapter
class IAppb(Interface):
a = Attribute('test attribute')
def f(): "test func"
class IApp(IAppb):
pass
class IApp2(IAppb):
pass
class IApp3(IAppb):
pass
class IContent(Interface): pass
@implementer(IContent)
class Content(object):
pass
@adapter(IContent)
@implementer(IApp)
class Comp(object):
pass
def __init__(self, *args):
# Ignore arguments passed to constructor
pass
a = 1
def f(): pass
class Comp2(object):
def __init__(self, context):
self.context = context
class Comp3(object):
def __init__(self, context):
self.context = context
comp = Comp()
content = Content()
zope.component-4.0.2/src/zope/component/event.py 0000664 0001750 0001750 00000002321 11774312422 021643 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2004 Zope Foundation 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-specific event dispatching
Based on subscription adapters / handlers.
"""
from zope.event import subscribers as event_subscribers
from zope.component.interfaces import IObjectEvent
from zope.component._api import subscribers as component_subscribers
from zope.component._declaration import adapter
def dispatch(*event):
component_subscribers(event, None)
event_subscribers.append(dispatch)
@adapter(IObjectEvent)
def objectEventNotify(event):
"""Dispatch ObjectEvents to interested adapters.
"""
component_subscribers((event.object, event), None)
zope.component-4.0.2/src/zope/component/registry.py 0000664 0001750 0001750 00000004214 11774312422 022375 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2006 Zope Foundation 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.
#
##############################################################################
"""Basic components support
"""
# BBB, import component-related from zope.interface
from zope.interface.registry import Components
from zope.interface.registry import _getUtilityProvided
from zope.interface.registry import _getAdapterProvided
from zope.interface.registry import _getAdapterRequired
from zope.interface.registry import UtilityRegistration
from zope.interface.registry import AdapterRegistration
from zope.interface.registry import SubscriptionRegistration
from zope.interface.registry import HandlerRegistration
from zope.component._api import handle
from zope.component._declaration import adapter
from zope.component.interfaces import IAdapterRegistration
from zope.component.interfaces import IHandlerRegistration
from zope.component.interfaces import IRegistrationEvent
from zope.component.interfaces import ISubscriptionAdapterRegistration
from zope.component.interfaces import IUtilityRegistration
@adapter(IUtilityRegistration, IRegistrationEvent)
def dispatchUtilityRegistrationEvent(registration, event):
handle(registration.component, event)
@adapter(IAdapterRegistration, IRegistrationEvent)
def dispatchAdapterRegistrationEvent(registration, event):
handle(registration.factory, event)
@adapter(ISubscriptionAdapterRegistration, IRegistrationEvent)
def dispatchSubscriptionAdapterRegistrationEvent(registration, event):
handle(registration.factory, event)
@adapter(IHandlerRegistration, IRegistrationEvent)
def dispatchHandlerRegistrationEvent(registration, event):
handle(registration.handler, event)
zope.component-4.0.2/src/zope/component/zcml.py 0000664 0001750 0001750 00000047340 11774312422 021501 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2005 Zope Foundation 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 configuration handlers
"""
from zope.configuration.exceptions import ConfigurationError
from zope.configuration.fields import Bool
from zope.configuration.fields import GlobalInterface
from zope.configuration.fields import GlobalObject
from zope.configuration.fields import PythonIdentifier
from zope.configuration.fields import Tokens
from zope.i18nmessageid import MessageFactory
from zope.interface import Interface
from zope.interface import implementedBy
from zope.interface import providedBy
from zope.schema import TextLine
from zope.component._api import getSiteManager
from zope.component._declaration import adaptedBy
from zope.component.interface import provideInterface
from zope.component._compat import _BLANK
try:
from zope.security.zcml import Permission
except ImportError: #pragma NO COVER
def _no_security(*args, **kw):
raise ConfigurationError("security proxied components are not "
"supported because zope.security is not available")
_checker = proxify = protectedFactory = security =_no_security
Permission = TextLine
else:
from zope.component.security import _checker
from zope.component.security import proxify
from zope.component.security import protectedFactory
from zope.component.security import securityAdapterFactory
_ = MessageFactory('zope')
class ComponentConfigurationError(ValueError, ConfigurationError):
pass
def handler(methodName, *args, **kwargs):
method = getattr(getSiteManager(), methodName)
method(*args, **kwargs)
class IBasicComponentInformation(Interface):
component = GlobalObject(
title=_("Component to use"),
description=_("Python name of the implementation object. This"
" must identify an object in a module using the"
" full dotted name. If specified, the"
" ``factory`` field must be left blank."),
required=False,
)
permission = Permission(
title=_("Permission"),
description=_("Permission required to use this component."),
required=False,
)
factory = GlobalObject(
title=_("Factory"),
description=_("Python name of a factory which can create the"
" implementation object. This must identify an"
" object in a module using the full dotted name."
" If specified, the ``component`` field must"
" be left blank."),
required=False,
)
class IAdapterDirective(Interface):
"""
Register an adapter
"""
factory = Tokens(
title=_("Adapter factory/factories"),
description=_("A list of factories (usually just one) that create"
" the adapter instance."),
required=True,
value_type=GlobalObject()
)
provides = GlobalInterface(
title=_("Interface the component provides"),
description=_("This attribute specifies the interface the adapter"
" instance must provide."),
required=False,
)
for_ = Tokens(
title=_("Specifications to be adapted"),
description=_("This should be a list of interfaces or classes"),
required=False,
value_type=GlobalObject(
missing_value=object(),
),
)
permission = Permission(
title=_("Permission"),
description=_("This adapter is only available, if the principal"
" has this permission."),
required=False,
)
name = TextLine(
title=_("Name"),
description=_("Adapters can have names.\n\n"
"This attribute allows you to specify the name for"
" this adapter."),
required=False,
)
trusted = Bool(
title=_("Trusted"),
description=_("""Make the adapter a trusted adapter
Trusted adapters have unfettered access to the objects they
adapt. If asked to adapt security-proxied objects, then,
rather than getting an unproxied adapter of security-proxied
objects, you get a security-proxied adapter of unproxied
objects.
"""),
required=False,
default=False,
)
locate = Bool(
title=_("Locate"),
description=_("""Make the adapter a locatable adapter
Located adapter should be used if a non-public permission
is used.
"""),
required=False,
default=False,
)
def _rolledUpFactory(factories):
# This has to be named 'factory', aparently, so as not to confuse
# apidoc :(
def factory(ob):
for f in factories:
ob = f(ob)
return ob
# Store the original factory for documentation
factory.factory = factories[0]
return factory
def adapter(_context, factory, provides=None, for_=None, permission=None,
name='', trusted=False, locate=False):
if for_ is None:
if len(factory) == 1:
for_ = adaptedBy(factory[0])
if for_ is None:
raise TypeError("No for attribute was provided and can't "
"determine what the factory adapts.")
for_ = tuple(for_)
if provides is None:
if len(factory) == 1:
p = list(implementedBy(factory[0]))
if len(p) == 1:
provides = p[0]
if provides is None:
raise TypeError("Missing 'provides' attribute")
# Generate a single factory from multiple factories:
factories = factory
if len(factories) == 1:
factory = factories[0]
elif len(factories) < 1:
raise ComponentConfigurationError("No factory specified")
elif len(factories) > 1 and len(for_) != 1:
raise ComponentConfigurationError(
"Can't use multiple factories and multiple for")
else:
factory = _rolledUpFactory(factories)
if permission is not None:
factory = protectedFactory(factory, provides, permission)
# invoke custom adapter factories
if locate or permission is not None or trusted:
factory = securityAdapterFactory(factory, permission, locate, trusted)
_context.action(
discriminator = ('adapter', for_, provides, name),
callable = handler,
args = ('registerAdapter',
factory, for_, provides, name, _context.info),
)
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', provides)
)
if for_:
for iface in for_:
if iface is not None:
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', iface)
)
class ISubscriberDirective(Interface):
"""
Register a subscriber
"""
factory = GlobalObject(
title=_("Subscriber factory"),
description=_("A factory used to create the subscriber instance."),
required=False,
)
handler = GlobalObject(
title=_("Handler"),
description=_("A callable object that handles events."),
required=False,
)
provides = GlobalInterface(
title=_("Interface the component provides"),
description=_("This attribute specifies the interface the adapter"
" instance must provide."),
required=False,
)
for_ = Tokens(
title=_("Interfaces or classes that this subscriber depends on"),
description=_("This should be a list of interfaces or classes"),
required=False,
value_type=GlobalObject(
missing_value = object(),
),
)
permission = Permission(
title=_("Permission"),
description=_("This subscriber is only available, if the"
" principal has this permission."),
required=False,
)
trusted = Bool(
title=_("Trusted"),
description=_("""Make the subscriber a trusted subscriber
Trusted subscribers have unfettered access to the objects they
adapt. If asked to adapt security-proxied objects, then,
rather than getting an unproxied subscriber of security-proxied
objects, you get a security-proxied subscriber of unproxied
objects.
"""),
required=False,
default=False,
)
locate = Bool(
title=_("Locate"),
description=_("""Make the subscriber a locatable subscriber
Located subscribers should be used if a non-public permission
is used.
"""),
required=False,
default=False,
)
_handler = handler
def subscriber(_context, for_=None, factory=None, handler=None, provides=None,
permission=None, trusted=False, locate=False):
if factory is None:
if handler is None:
raise TypeError("No factory or handler provided")
if provides is not None:
raise TypeError("Cannot use handler with provides")
factory = handler
else:
if handler is not None:
raise TypeError("Cannot use handler with factory")
if provides is None:
raise TypeError(
"You must specify a provided interface when registering "
"a factory")
if for_ is None:
for_ = adaptedBy(factory)
if for_ is None:
raise TypeError("No for attribute was provided and can't "
"determine what the factory (or handler) adapts.")
if permission is not None:
factory = protectedFactory(factory, provides, permission)
for_ = tuple(for_)
# invoke custom adapter factories
if locate or permission is not None or trusted:
factory = securityAdapterFactory(factory, permission, locate, trusted)
if handler is not None:
_context.action(
discriminator = None,
callable = _handler,
args = ('registerHandler',
handler, for_, _BLANK, _context.info),
)
else:
_context.action(
discriminator = None,
callable = _handler,
args = ('registerSubscriptionAdapter',
factory, for_, provides, _BLANK, _context.info),
)
if provides is not None:
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', provides)
)
# For each interface, state that the adapter provides that interface.
for iface in for_:
if iface is not None:
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', iface)
)
class IUtilityDirective(IBasicComponentInformation):
"""Register a utility."""
provides = GlobalInterface(
title=_("Provided interface"),
description=_("Interface provided by the utility."),
required=False,
)
name = TextLine(
title=_("Name"),
description=_("Name of the registration. This is used by"
" application code when locating a utility."),
required=False,
)
def utility(_context, provides=None, component=None, factory=None,
permission=None, name=''):
if factory and component:
raise TypeError("Can't specify factory and component.")
if provides is None:
if factory:
provides = list(implementedBy(factory))
else:
provides = list(providedBy(component))
if len(provides) == 1:
provides = provides[0]
else:
raise TypeError("Missing 'provides' attribute")
if permission is not None:
component = proxify(component, provides=provides, permission=permission)
_context.action(
discriminator = ('utility', provides, name),
callable = handler,
args = ('registerUtility', component, provides, name, _context.info),
kw = dict(factory=factory),
)
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', provides),
)
class IInterfaceDirective(Interface):
"""
Define an interface
"""
interface = GlobalInterface(
title=_("Interface"),
required=True,
)
type = GlobalInterface(
title=_("Interface type"),
required=False,
)
name = TextLine(
title=_("Name"),
required=False,
)
def interface(_context, interface, type=None, name=''):
_context.action(
discriminator = None,
callable = provideInterface,
args = (name, interface, type)
)
class IBasicViewInformation(Interface):
"""This is the basic information for all views."""
for_ = Tokens(
title=_("Specifications of the objects to be viewed"),
description=_("""This should be a list of interfaces or classes
"""),
required=True,
value_type=GlobalObject(
missing_value=object(),
),
)
permission = Permission(
title=_("Permission"),
description=_("The permission needed to use the view."),
required=False,
)
class_ = GlobalObject(
title=_("Class"),
description=_("A class that provides attributes used by the view."),
required=False,
)
allowed_interface = Tokens(
title=_("Interface that is also allowed if user has permission."),
description=_("""
By default, 'permission' only applies to viewing the view and
any possible sub views. By specifying this attribute, you can
make the permission also apply to everything described in the
supplied interface.
Multiple interfaces can be provided, separated by
whitespace."""),
required=False,
value_type=GlobalInterface(),
)
allowed_attributes = Tokens(
title=_("View attributes that are also allowed if the user"
" has permission."),
description=_("""
By default, 'permission' only applies to viewing the view and
any possible sub views. By specifying 'allowed_attributes',
you can make the permission also apply to the extra attributes
on the view object."""),
required=False,
value_type=PythonIdentifier(),
)
class IBasicResourceInformation(Interface):
"""
Basic information for resources
"""
name = TextLine(
title=_("The name of the resource."),
description=_("The name shows up in URLs/paths. For example 'foo'."),
required=True,
default=_BLANK,
)
provides = GlobalInterface(
title=_("The interface this component provides."),
description=_("""
A view can provide an interface. This would be used for
views that support other views."""),
required=False,
default=Interface,
)
type = GlobalInterface(
title=_("Request type"),
required=True
)
class IViewDirective(IBasicViewInformation, IBasicResourceInformation):
"""Register a view for a component"""
factory = Tokens(
title=_("Factory"),
required=False,
value_type=GlobalObject(),
)
def view(_context, factory, type, name, for_,
permission=None,
allowed_interface=None,
allowed_attributes=None,
provides=Interface,
):
if ((allowed_attributes or allowed_interface)
and (not permission)):
raise ComponentConfigurationError(
"'permission' required with 'allowed_interface' or "
"'allowed_attributes'")
if permission is not None:
checker = _checker(_context, permission,
allowed_interface, allowed_attributes)
class ProxyView(object):
"""Class to create simple proxy views."""
def __init__(self, factory, checker):
self.factory = factory
self.checker = checker
def __call__(self, *objects):
return proxify(self.factory(*objects), self.checker)
factory[-1] = ProxyView(factory[-1], checker)
if not for_:
raise ComponentConfigurationError("No for interfaces specified");
for_ = tuple(for_)
# Generate a single factory from multiple factories:
factories = factory
if len(factories) == 1:
factory = factories[0]
elif len(factories) < 1:
raise ComponentConfigurationError("No view factory specified")
elif len(factories) > 1 and len(for_) > 1:
raise ComponentConfigurationError(
"Can't use multiple factories and multiple for")
else:
def factory(ob, request):
for f in factories[:-1]:
ob = f(ob)
return factories[-1](ob, request)
factory.factory = factories[0]
for_ = for_ + (type,)
_context.action(
discriminator = ('view', for_, name, provides),
callable = handler,
args = ('registerAdapter',
factory, for_, provides, name, _context.info),
)
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', provides)
)
if for_ is not None:
for iface in for_:
if iface is not None:
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', iface)
)
class IResourceDirective(IBasicComponentInformation,
IBasicResourceInformation):
"""Register a resource"""
allowed_interface = Tokens(
title=_("Interface that is also allowed if user has permission."),
required=False,
value_type=GlobalInterface(),
)
allowed_attributes = Tokens(
title=_("View attributes that are also allowed if user"
" has permission."),
required=False,
value_type=PythonIdentifier(),
)
def resource(_context, factory, type, name,
permission=None,
allowed_interface=None, allowed_attributes=None,
provides=Interface):
if ((allowed_attributes or allowed_interface)
and (not permission)):
raise ComponentConfigurationError(
"Must use name attribute with allowed_interface or "
"allowed_attributes"
)
if permission is not None:
checker = _checker(_context, permission,
allowed_interface, allowed_attributes)
def proxyResource(request, factory=factory, checker=checker):
return proxify(factory(request), checker)
proxyResource.factory = factory
factory = proxyResource
_context.action(
discriminator = ('resource', name, type, provides),
callable = handler,
args = ('registerAdapter',
factory, (type,), provides, name, _context.info))
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', type))
_context.action(
discriminator = None,
callable = provideInterface,
args = ('', provides))
zope.component-4.0.2/src/zope/component/globalregistry.py 0000664 0001750 0001750 00000005256 11774312422 023565 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2006 Zope Foundation 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 components support
"""
from zope.interface import implementer
from zope.interface.adapter import AdapterRegistry
from zope.interface.registry import Components
from zope.component.interfaces import IComponentLookup
from zope.component._compat import _BLANK
def GAR(components, registryName):
return getattr(components, 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, name):
self.__parent__ = parent
self.__name__ = name
super(GlobalAdapterRegistry, self).__init__()
def __reduce__(self):
return GAR, (self.__parent__, self.__name__)
@implementer(IComponentLookup)
class BaseGlobalComponents(Components):
def _init_registries(self):
self.adapters = GlobalAdapterRegistry(self, 'adapters')
self.utilities = GlobalAdapterRegistry(self, 'utilities')
def __reduce__(self):
# Global site managers are pickled as global objects
return self.__name__
base = BaseGlobalComponents('base')
try:
from zope.testing.cleanup import addCleanUp
except ImportError: #pragma NO COVER
pass
else:
addCleanUp(lambda: base.__init__('base'))
del addCleanUp
globalSiteManager = base
def getGlobalSiteManager():
return globalSiteManager
# The following APIs provide global registration support for Python code.
# We eventually want to deprecate these in favor of using the global
# component registry directly.
def provideUtility(component, provides=None, name=_BLANK):
base.registerUtility(component, provides, name, event=False)
def provideAdapter(factory, adapts=None, provides=None, name=_BLANK):
base.registerAdapter(factory, adapts, provides, name, event=False)
def provideSubscriptionAdapter(factory, adapts=None, provides=None):
base.registerSubscriptionAdapter(factory, adapts, provides, event=False)
def provideHandler(factory, adapts=None):
base.registerHandler(factory, adapts, event=False)
zope.component-4.0.2/src/zope/component/hookable.py 0000664 0001750 0001750 00000002444 11774312422 022314 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2009 Zope Foundation 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.
#
##############################################################################
""" This module supplies a pure-Python version of zope.hookable.hookable.
"""
class hookable(object):
__slots__ = ('__original', '__implementation')
original = property(lambda self: self.__original,)
implementation = property(lambda self: self.__implementation,)
def __init__(self, implementation):
self.__original = self.__implementation = implementation
def sethook(self, newimplementation):
old, self.__implementation = self.__implementation, newimplementation
return old
def reset(self):
self.__implementation = self.__original
def __call__(self, *args, **kw):
return self.__implementation(*args, **kw)
zope.component-4.0.2/src/zope/component/interfaces.py 0000664 0001750 0001750 00000040440 11774312422 022651 0 ustar tseaver tseaver ############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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
"""
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface import implements
# BBB 2011-09-09, import interfaces from zope.interface
from zope.interface.interfaces import ComponentLookupError
from zope.interface.interfaces import Invalid
from zope.interface.interfaces import IObjectEvent
from zope.interface.interfaces import ObjectEvent
from zope.interface.interfaces import IComponentLookup
from zope.interface.interfaces import IRegistration
from zope.interface.interfaces import IUtilityRegistration
from zope.interface.interfaces import _IBaseAdapterRegistration
from zope.interface.interfaces import IAdapterRegistration
from zope.interface.interfaces import ISubscriptionAdapterRegistration
from zope.interface.interfaces import IHandlerRegistration
from zope.interface.interfaces import IRegistrationEvent
from zope.interface.interfaces import RegistrationEvent
from zope.interface.interfaces import IRegistered
from zope.interface.interfaces import Registered
from zope.interface.interfaces import IUnregistered
from zope.interface.interfaces import Unregistered
from zope.interface.interfaces import IComponentRegistry
from zope.interface.interfaces import IComponents
from zope.component._compat import _BLANK
class IComponentArchitecture(Interface):
"""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 `IComponentLookup` 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 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.
"""
def getNextUtility(context, interface, name=''):
"""Get the next available utility.
If no utility was found, a `ComponentLookupError` is raised.
"""
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=_BLANK,
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=_BLANK,
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=_BLANK,
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 IRegistry(Interface):
"""Object that supports component registry
"""
def registrations():
"""Return an iterable of component registrations
"""
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=_BLANK):
"""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=_BLANK):
"""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 IPossibleSite(Interface):
"""An object that could be a site.
"""
def setSiteManager(sitemanager):
"""Sets the site manager for this object.
"""
def getSiteManager():
"""Returns the site manager contained in this object.
If there isn't a site manager, raise a component lookup.
"""
class ISite(IPossibleSite):
"""Marker interface to indicate that we have a site"""
class Misused(Exception):
"""A component is being used (registered) for the wrong interface."""
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.
"""
zope.component-4.0.2/src/zope/component/eventtesting.py 0000664 0001750 0001750 00000004047 11774312422 023250 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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
"""
from zope.component import provideHandler
from zope.component.event import objectEventNotify
from zope.component.registry import dispatchUtilityRegistrationEvent
from zope.component.registry import dispatchAdapterRegistrationEvent
from zope.component.registry import (
dispatchSubscriptionAdapterRegistrationEvent)
from zope.component.registry import dispatchHandlerRegistrationEvent
try:
from zope.testing.cleanup import addCleanUp
except ImportError: #pragma NO COVER
def addCleanUp(x):
pass
events = []
def getEvents(event_type=None, filter=None): #pragma NO COVER going aaway
r = []
for event in events:
if event_type is not None and not event_type.providedBy(event):
continue
if filter is not None and not filter(event):
continue
r.append(event)
return r
def clearEvents(): #pragma NO COVER going aaway
del events[:]
addCleanUp(clearEvents)
class PlacelessSetup: #pragma NO COVER going aaway
def setUp(self):
provideHandler(objectEventNotify)
provideHandler(dispatchUtilityRegistrationEvent)
provideHandler(dispatchAdapterRegistrationEvent)
provideHandler(dispatchSubscriptionAdapterRegistrationEvent)
provideHandler(dispatchHandlerRegistrationEvent)
provideHandler(events.append, (None,))
def setUp(test=None): #pragma NO COVER going aaway
PlacelessSetup().setUp()
zope.component-4.0.2/src/zope/component/hooks.py 0000664 0001750 0001750 00000010003 11774312422 021641 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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.
#
##############################################################################
"""Hooks for getting and setting a site in the thread global namespace.
"""
__docformat__ = 'restructuredtext'
import contextlib
import threading
try:
from zope.security.proxy import removeSecurityProxy
except ImportError: #pragma NO COVER
def removeSecurityProxy(x):
return x
from zope.component.globalregistry import getGlobalSiteManager
from zope.component.interfaces import ComponentLookupError
from zope.component.interfaces import IComponentLookup
class read_property(object):
"""Descriptor for property-like computed attributes.
Unlike the standard 'property', this descriptor allows assigning a
value to the instance, shadowing the property getter function.
"""
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 = getGlobalSiteManager()
@read_property
def adapter_hook(self):
adapter_hook = self.sm.adapters.adapter_hook
self.adapter_hook = adapter_hook
return adapter_hook
siteinfo = SiteInfo()
def setSite(site=None):
if site is None:
sm = 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 = removeSecurityProxy(site)
# The getSiteManager method is defined by IPossibleSite.
sm = site.getSiteManager()
siteinfo.site = site
siteinfo.sm = sm
try:
del siteinfo.adapter_hook
except AttributeError:
pass
def getSite():
return siteinfo.site
@contextlib.contextmanager
def site(site):
old_site = getSite()
setSite(site)
try:
yield
finally:
setSite(old_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 = IComponentLookup(
context, getGlobalSiteManager())
sm = removeSecurityProxy(sm)
return sm
def adapter_hook(interface, object, name='', default=None):
try:
return siteinfo.adapter_hook(interface, object, name, default)
except ComponentLookupError:
return default
def setHooks():
from zope.component import _api
_api.adapter_hook.sethook(adapter_hook)
_api.getSiteManager.sethook(getSiteManager)
def resetHooks():
# Reset hookable functions to original implementation.
from zope.component import _api
_api.adapter_hook.reset()
_api.getSiteManager.reset()
# Clear the site thread global
clearSite = setSite
try:
from zope.testing.cleanup import addCleanUp
except ImportError: #pragma NO COVER
pass
else:
addCleanUp(resetHooks)
zope.component-4.0.2/src/zope/component/tests/ 0000775 0001750 0001750 00000000000 12070353060 021305 5 ustar tseaver tseaver zope.component-4.0.2/src/zope/component/tests/test__declaration.py 0000664 0001750 0001750 00000016010 11774312422 025347 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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 adapter declaration helpers
"""
import unittest
class Test_adapter(unittest.TestCase):
def _getTargetClass(self):
from zope.component._declaration import adapter
return adapter
def _makeOne(self, *interfaces):
return self._getTargetClass()(*interfaces)
def test_ctor_no_interfaces(self):
deco = self._makeOne()
self.assertEqual(list(deco.interfaces), [])
def test_ctor_w_interfaces(self):
from zope.interface import Interface
class IFoo(Interface):
pass
class IBar(Interface):
pass
deco = self._makeOne(IFoo, IBar)
self.assertEqual(list(deco.interfaces), [IFoo, IBar])
def test__call___w_class(self):
from zope.interface import Interface
class IFoo(Interface):
pass
class IBar(Interface):
pass
@self._makeOne(IFoo, IBar)
class Baz(object):
pass
self.assertEqual(Baz.__component_adapts__, (IFoo, IBar))
def test__call___w_inst_of_decorated_class(self):
from zope.interface import Interface
class IFoo(Interface):
pass
class IBar(Interface):
pass
@self._makeOne(IFoo, IBar)
class Baz(object):
pass
baz = Baz()
self.assertRaises(AttributeError,
getattr, baz, '__component_adapts_')
def test__call___w_non_class(self):
from zope.interface import Interface
class IFoo(Interface):
pass
class IBar(Interface):
pass
class Baz(object):
pass
deco = self._makeOne(IFoo, IBar)
baz = deco(Baz())
self.assertEqual(baz.__component_adapts__, (IFoo, IBar))
class Test_adapts(unittest.TestCase):
def _run_generated_code(self, code, globs, locs,
fails_under_py3k=True,
):
import warnings
#from zope.component._compat import PYTHON3
PYTHON3 = False
with warnings.catch_warnings(record=True) as log:
warnings.resetwarnings()
if not PYTHON3:
exec(code, globs, locs)
self.assertEqual(len(log), 0) # no longer warn
return True
else:
try:
exec(code, globs, locs)
except TypeError:
return False
else:
if fails_under_py3k:
self.fail("Didn't raise TypeError")
def test_instances_not_affected(self):
from zope.component._declaration import adapts
class C(object):
adapts()
self.assertEqual(C.__component_adapts__, ())
def _try():
return C().__component_adapts__
self.assertRaises(AttributeError, _try)
def test_called_from_function(self):
import warnings
from zope.component._declaration import adapts
from zope.interface import Interface
class IFoo(Interface):
pass
globs = {'adapts': adapts, 'IFoo': IFoo}
locs = {}
CODE = "\n".join([
'def foo():',
' adapts(IFoo)'
])
if self._run_generated_code(CODE, globs, locs, False):
foo = locs['foo']
with warnings.catch_warnings(record=True) as log:
warnings.resetwarnings()
self.assertRaises(TypeError, foo)
self.assertEqual(len(log), 0) # no longer warn
def test_called_twice_from_class(self):
import warnings
from zope.component._declaration import adapts
from zope.interface import Interface
from zope.interface._compat import PYTHON3
class IFoo(Interface):
pass
class IBar(Interface):
pass
globs = {'adapts': adapts, 'IFoo': IFoo, 'IBar': IBar}
locs = {}
CODE = "\n".join([
'class Foo(object):',
' adapts(IFoo)',
' adapts(IBar)',
])
with warnings.catch_warnings(record=True) as log:
warnings.resetwarnings()
try:
exec(CODE, globs, locs)
except TypeError:
if not PYTHON3:
self.assertEqual(len(log), 0) # no longer warn
else:
self.fail("Didn't raise TypeError")
def test_called_once_from_class(self):
from zope.component._declaration import adapts
from zope.interface import Interface
class IFoo(Interface):
pass
globs = {'adapts': adapts, 'IFoo': IFoo}
locs = {}
CODE = "\n".join([
'class Foo(object):',
' adapts(IFoo)',
])
if self._run_generated_code(CODE, globs, locs):
Foo = locs['Foo']
spec = Foo.__component_adapts__
self.assertEqual(list(spec), [IFoo])
class Test_adaptedBy(unittest.TestCase):
def _callFUT(self, obj):
from zope.component._declaration import adaptedBy
return adaptedBy(obj)
def test_obj_w_no_attr(self):
self.assertEqual(self._callFUT(object()), None)
def test__call___w_class(self):
from zope.interface import Interface
class IFoo(Interface):
pass
class IBar(Interface):
pass
class Baz(object):
__component_adapts__ = (IFoo, IBar)
self.assertEqual(self._callFUT(Baz), (IFoo, IBar))
def test__call___w_inst_of_decorated_class(self):
from zope.interface import Interface
from zope.component._declaration import _adapts_descr
class IFoo(Interface):
pass
class IBar(Interface):
pass
class Baz(object):
__component_adapts__ = _adapts_descr((IFoo, IBar))
baz = Baz()
self.assertEqual(self._callFUT(baz), None)
def test__call___w_non_class(self):
from zope.interface import Interface
class IFoo(Interface):
pass
class IBar(Interface):
pass
class Baz(object):
pass
baz = Baz()
baz.__component_adapts__ = (IFoo, IBar)
self.assertEqual(self._callFUT(baz), (IFoo, IBar))
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test_adapter),
unittest.makeSuite(Test_adapts),
unittest.makeSuite(Test_adaptedBy),
))
zope.component-4.0.2/src/zope/component/tests/test_globalregistry.py 0000664 0001750 0001750 00000020743 11774312422 025764 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
""" Tests for z.c._api
"""
import unittest
class Test_getGlobalSiteManager(unittest.TestCase):
def _callFUT(self):
from zope.component.globalregistry import getGlobalSiteManager
return getGlobalSiteManager()
def test_gsm_is_IComponentLookup(self):
from zope.component.globalregistry import base
from zope.component.interfaces import IComponentLookup
gsm = self._callFUT()
self.assertTrue(gsm is base)
self.assertTrue(IComponentLookup.providedBy(gsm))
def test_gsm_is_singleton(self):
gsm = self._callFUT()
self.assertTrue(self._callFUT() is gsm)
def test_gsm_pickling(self):
from zope.component._compat import _pickle
gsm = self._callFUT()
dumped = _pickle.dumps(gsm)
loaded = _pickle.loads(dumped)
self.assertTrue(loaded is gsm)
dumped_utilities = _pickle.dumps(gsm.utilities)
loaded_utilities = _pickle.loads(dumped_utilities)
self.assertTrue(loaded_utilities is gsm.utilities)
dumped_adapters = _pickle.dumps(gsm.adapters)
loaded_adapters = _pickle.loads(dumped_adapters)
self.assertTrue(loaded_adapters is gsm.adapters)
class Test_provideUtility(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.globalregistry import provideUtility
return provideUtility(*args, **kw)
def test_anonymous_no_provides(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component.globalregistry import getGlobalSiteManager
class IFoo(Interface):
pass
@implementer(IFoo)
class Foo(object):
pass
foo = Foo()
self._callFUT(foo)
gsm = getGlobalSiteManager()
self.assertTrue(gsm.getUtility(IFoo, '') is foo)
def test_named_w_provides(self):
from zope.interface import Interface
from zope.component.globalregistry import getGlobalSiteManager
class IFoo(Interface):
pass
class Foo(object):
pass
foo = Foo()
self._callFUT(foo, IFoo, 'named')
gsm = getGlobalSiteManager()
self.assertTrue(gsm.getUtility(IFoo, 'named') is foo)
class Test_provideAdapter(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.globalregistry import provideAdapter
return provideAdapter(*args, **kw)
def test_anonymous_no_provides_no_adapts(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component.globalregistry import getGlobalSiteManager
from zope.component._api import adapter
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IFoo)
class Foo(object):
pass
@adapter(IFoo)
@implementer(IBar)
class Bar(object):
def __init__(self, context):
self.context = context
self._callFUT(Bar)
gsm = getGlobalSiteManager()
foo = Foo()
adapted = gsm.getAdapter(foo, IBar)
self.assertTrue(isinstance(adapted, Bar))
self.assertTrue(adapted.context is foo)
def test_named_w_provides_w_adapts(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component.globalregistry import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IFoo)
class Foo(object):
pass
class Bar(object):
def __init__(self, context):
self.context = context
self._callFUT(Bar, (IFoo,), IBar, 'test')
gsm = getGlobalSiteManager()
foo = Foo()
adapted = gsm.getAdapter(foo, IBar, name='test')
self.assertTrue(isinstance(adapted, Bar))
self.assertTrue(adapted.context is foo)
class Test_provideSubscriptionAdapter(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.globalregistry import provideSubscriptionAdapter
return provideSubscriptionAdapter(*args, **kw)
def test_no_provides_no_adapts(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component.globalregistry import getGlobalSiteManager
from zope.component._api import adapter
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IFoo)
class Foo(object):
pass
@adapter(IFoo)
@implementer(IBar)
class Bar(object):
def __init__(self, context):
self.context = context
self._callFUT(Bar)
gsm = getGlobalSiteManager()
foo = Foo()
adapted = gsm.subscribers((foo,), IBar)
self.assertEqual(len(adapted), 1)
self.assertTrue(isinstance(adapted[0], Bar))
self.assertTrue(adapted[0].context is foo)
def test_w_provides_w_adapts(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component.globalregistry import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IFoo)
class Foo(object):
pass
class Bar(object):
def __init__(self, context):
self.context = context
self._callFUT(Bar, (IFoo,), IBar)
gsm = getGlobalSiteManager()
foo = Foo()
adapted = gsm.subscribers((foo,), IBar)
self.assertEqual(len(adapted), 1)
self.assertTrue(isinstance(adapted[0], Bar))
self.assertTrue(adapted[0].context is foo)
class Test_provideHandler(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.globalregistry import provideHandler
return provideHandler(*args, **kw)
def test_no_adapts(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.interface import providedBy
from zope.component.globalregistry import getGlobalSiteManager
from zope.component._api import adapter
class IFoo(Interface):
pass
@implementer(IFoo)
class Foo(object):
pass
@adapter(IFoo)
def _handler(context):
assert 0, "DON'T GO HERE"
self._callFUT(_handler)
gsm = getGlobalSiteManager()
regs = list(gsm.registeredHandlers())
self.assertEqual(len(regs), 1)
hr = regs[0]
self.assertEqual(list(hr.required), list(providedBy(Foo())))
self.assertEqual(hr.name, '')
self.assertTrue(hr.factory is _handler)
def test_w_adapts(self):
from zope.interface import Interface
from zope.component.globalregistry import getGlobalSiteManager
class IFoo(Interface):
pass
def _handler(context):
assert 0, "DON'T GO HERE"
self._callFUT(_handler, (IFoo,))
gsm = getGlobalSiteManager()
regs = list(gsm.registeredHandlers())
self.assertEqual(len(regs), 1)
hr = regs[0]
self.assertEqual(list(hr.required), [IFoo])
self.assertEqual(hr.name, '')
self.assertTrue(hr.factory is _handler)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test_getGlobalSiteManager),
unittest.makeSuite(Test_provideUtility),
unittest.makeSuite(Test_provideAdapter),
unittest.makeSuite(Test_provideSubscriptionAdapter),
unittest.makeSuite(Test_provideHandler),
))
zope.component-4.0.2/src/zope/component/tests/test_standalone.py 0000664 0001750 0001750 00000003651 11774312422 025062 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002, 2009 Zope Foundation 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
"""
import unittest
class StandaloneTests(unittest.TestCase):
def testStandalone(self):
# See: https://bugs.launchpad.net/zope3/+bug/98401
import subprocess
import sys
import os
import pickle
executable = os.path.abspath(sys.executable)
where = os.path.dirname(os.path.dirname(__file__))
program = os.path.join(where, 'standalonetests.py')
process = subprocess.Popen([executable, program],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE)
pickle.dump(sys.path, process.stdin)
process.stdin.close()
try:
rc = process.wait()
except OSError as e:
if e.errno != 4: # MacIntel raises apparently unimportant EINTR?
raise # TODO verify sanity of a pass on EINTR :-/
if rc != 0:
output = process.stdout.read()
sys.stderr.write('#' * 80 + '\n')
sys.stdout.write(output)
sys.stderr.write('#' * 80 + '\n')
self.fail('Output code: %d' % rc)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(StandaloneTests),
))
zope.component-4.0.2/src/zope/component/tests/test__api.py 0000664 0001750 0001750 00000123530 11774312422 023641 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
""" Tests for z.c._api
"""
import unittest
class Test_getSiteManager(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component._api import getSiteManager
return getSiteManager(*args, **kw)
def test_sm_is_IComponentLookup(self):
from zope.component.interfaces import IComponentLookup
sm = self._callFUT()
self.assertTrue(IComponentLookup.providedBy(sm))
def test_sm_is_singleton(self):
from zope.component.globalregistry import base
sm = self._callFUT()
self.assertTrue(sm is base)
self.assertTrue(self._callFUT() is sm)
def test_w_None(self):
self.assertTrue(self._callFUT(None) is self._callFUT())
def test_getSiteManager_w_conforming_context(self):
from zope.component.tests.examples import ConformsToIComponentLookup
sitemanager = object()
context = ConformsToIComponentLookup(sitemanager)
self.assertTrue(self._callFUT(context) is sitemanager)
def test_getSiteManager_w_invalid_context_no_adapter(self):
from zope.component.interfaces import ComponentLookupError
self.assertRaises(ComponentLookupError, self._callFUT, object())
def test_getSiteManager_w_invalid_context_w_adapter(self):
from zope.interface import Interface
from zope.component.globalregistry import getGlobalSiteManager
from zope.component.interfaces import IComponentLookup
gsm = getGlobalSiteManager()
sm = object()
def _adapt(x):
return sm
gsm.registerAdapter(_adapt, (Interface,), IComponentLookup, '')
self.assertTrue(self._callFUT(object()) is sm)
class Test_getAdapterInContext(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import getAdapterInContext
return getAdapterInContext(*args, **kw)
def test_miss(self):
from zope.interface import Interface
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
self.assertRaises(ComponentLookupError,
self._callFUT, object(), IFoo, context=None)
def test_hit_via_sm(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.interface.registry import Components
from zope.component import getGlobalSiteManager
from zope.component.tests.examples import ConformsToIComponentLookup
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IFoo)
class Global(object):
def __init__(self, context):
self.context = context
@implementer(IFoo)
class Local(object):
def __init__(self, context):
self.context = context
@implementer(IBar)
class Bar(object):
pass
class Context(ConformsToIComponentLookup):
def __init__(self, sm):
self.sitemanager = sm
gsm = getGlobalSiteManager()
gsm.registerAdapter(Global, (IBar,), IFoo, '')
sm1 = Components('sm1', bases=(gsm, ))
sm1.registerAdapter(Local, (IBar,), IFoo, '')
bar = Bar()
adapted = self._callFUT(bar, IFoo, context=Context(sm1))
self.assertTrue(adapted.__class__ is Local)
self.assertTrue(adapted.context is bar)
class Test_queryAdapterInContext(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import queryAdapterInContext
return queryAdapterInContext(*args, **kw)
def test_miss(self):
from zope.interface import Interface
from zope.component import queryAdapterInContext
class IFoo(Interface):
pass
self.assertEqual(
queryAdapterInContext(object(), IFoo, context=None), None)
def test_w_object_conforming(self):
from zope.interface import Interface
from zope.component import queryAdapterInContext
class IFoo(Interface):
pass
_adapted = object()
class Foo(object):
def __conform__(self, iface, default=None):
if iface is IFoo:
return _adapted
return default
self.assertTrue(
queryAdapterInContext(Foo(), IFoo, context=None) is _adapted)
def test___conform___raises_TypeError_via_class(self):
from zope.interface import Interface
from zope.component import queryAdapterInContext
class IFoo(Interface):
pass
_adapted = object()
class Foo(object):
def __conform__(self, iface, default=None):
if iface is IFoo:
return _adapted
return default
# call via class, triggering TypeError
self.assertEqual(queryAdapterInContext(Foo, IFoo, context=None), None)
def test___conform___raises_TypeError_via_inst(self):
from zope.interface import Interface
from zope.component import queryAdapterInContext
class IFoo(Interface):
pass
_adapted = object()
class Foo(object):
def __conform__(self, iface, default=None):
raise TypeError
self.assertRaises(TypeError,
queryAdapterInContext, Foo(), IFoo, context=None)
def test_w_object_implementing(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import queryAdapterInContext
class IFoo(Interface):
pass
@implementer(IFoo)
class Foo(object):
pass
foo = Foo()
self.assertTrue(
queryAdapterInContext(foo, IFoo, context=None) is foo)
class Test_getAdapter(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import getAdapter
return getAdapter(*args, **kw)
def test_anonymous_nonesuch(self):
from zope.interface import Interface
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
self.assertRaises(ComponentLookupError,
self._callFUT, object(), IFoo, '')
def test_named_nonesuch(self):
from zope.interface import Interface
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
self.assertRaises(ComponentLookupError,
self._callFUT, object(), IFoo, 'bar')
def test_anonymous_hit(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IFoo)
class Baz(object):
def __init__(self, context):
self.context = context
getGlobalSiteManager().registerAdapter(Baz, (IBar,), IFoo, '')
bar = Bar()
adapted = self._callFUT(bar, IFoo, '')
self.assertTrue(adapted.__class__ is Baz)
self.assertTrue(adapted.context is bar)
def test_anonymous_hit_registered_for_None(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
@implementer(IFoo)
class Baz(object):
def __init__(self, context):
self.context = context
getGlobalSiteManager().registerAdapter(Baz, (None,), IFoo, '')
ctx = object()
adapted = self._callFUT(ctx, IFoo, '')
self.assertTrue(adapted.__class__ is Baz)
self.assertTrue(adapted.context is ctx)
def test_named_hit(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IFoo)
class Baz(object):
def __init__(self, context):
self.context = context
getGlobalSiteManager().registerAdapter(Baz, (IBar,), IFoo, 'named')
bar = Bar()
adapted = self._callFUT(bar, IFoo, 'named')
self.assertTrue(adapted.__class__ is Baz)
self.assertTrue(adapted.context is bar)
class Test_queryAdapter(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import queryAdapter
return queryAdapter(*args, **kw)
def test_anonymous_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(self._callFUT(object(), IFoo, '', ''),
'')
def test_named_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(self._callFUT(object(), IFoo, 'bar'), None)
def test_anonymous_hit(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IFoo)
class Baz(object):
def __init__(self, context):
self.context = context
getGlobalSiteManager().registerAdapter(Baz, (IBar,), IFoo, '')
bar = Bar()
adapted = self._callFUT(bar, IFoo, '')
self.assertTrue(adapted.__class__ is Baz)
self.assertTrue(adapted.context is bar)
def test_named_hit(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IFoo)
class Baz(object):
def __init__(self, context):
self.context = context
getGlobalSiteManager().registerAdapter(Baz, (IBar,), IFoo, 'named')
bar = Bar()
adapted = self._callFUT(bar, IFoo, 'named')
self.assertTrue(adapted.__class__ is Baz)
self.assertTrue(adapted.context is bar)
def test_nested(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.interface.registry import Components
from zope.component import getGlobalSiteManager
from zope.component.tests.examples import ConformsToIComponentLookup
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IFoo)
class Global(object):
def __init__(self, context):
self.context = context
@implementer(IFoo)
class Local(object):
def __init__(self, context):
self.context = context
@implementer(IBar)
class Bar(object):
pass
class Context(ConformsToIComponentLookup):
def __init__(self, sm):
self.sitemanager = sm
gsm = getGlobalSiteManager()
gsm.registerAdapter(Global, (IBar,), IFoo, '')
sm1 = Components('sm1', bases=(gsm, ))
sm1.registerAdapter(Local, (IBar,), IFoo, '')
bar = Bar()
adapted = self._callFUT(bar, IFoo, '', context=Context(sm1))
self.assertTrue(adapted.__class__ is Local)
self.assertTrue(adapted.context is bar)
class Test_getMultiAdapter(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import getMultiAdapter
return getMultiAdapter(*args, **kw)
def test_anonymous_nonesuch(self):
from zope.interface import Interface
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
self.assertRaises(ComponentLookupError,
self._callFUT, (object(), object()), IFoo, '')
def test_named_nonesuch(self):
from zope.interface import Interface
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
self.assertRaises(ComponentLookupError,
self._callFUT, (object(), object()), IFoo, 'bar')
def test_anonymous_hit(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
class IBaz(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IBaz)
class Baz(object):
pass
@implementer(IFoo)
class FooAdapter(object):
def __init__(self, first, second):
self.first, self.second = first, second
getGlobalSiteManager().registerAdapter(
FooAdapter, (IBar, IBaz), IFoo, '')
bar = Bar()
baz = Baz()
adapted = self._callFUT((bar, baz), IFoo, '')
self.assertTrue(adapted.__class__ is FooAdapter)
self.assertTrue(adapted.first is bar)
self.assertTrue(adapted.second is baz)
def test_anonymous_hit_registered_for_None(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
class IBaz(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IFoo)
class FooAdapter(object):
def __init__(self, first, second):
self.first, self.second = first, second
getGlobalSiteManager().registerAdapter(
FooAdapter, (IBar, None), IFoo, '')
bar = Bar()
baz = object()
adapted = self._callFUT((bar, baz), IFoo, '')
self.assertTrue(adapted.__class__ is FooAdapter)
self.assertTrue(adapted.first is bar)
self.assertTrue(adapted.second is baz)
def test_named_hit(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
class IBaz(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IBaz)
class Baz(object):
pass
@implementer(IFoo)
class FooAdapter(object):
def __init__(self, first, second):
self.first, self.second = first, second
getGlobalSiteManager().registerAdapter(
FooAdapter, (IBar, IBaz), IFoo, 'named')
bar = Bar()
baz = Baz()
adapted = self._callFUT((bar, baz), IFoo, 'named')
self.assertTrue(adapted.__class__ is FooAdapter)
self.assertTrue(adapted.first is bar)
self.assertTrue(adapted.second is baz)
class Test_queryMultiAdapter(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import queryMultiAdapter
return queryMultiAdapter(*args, **kw)
def test_anonymous_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(self._callFUT((object(), object()), IFoo, '',
''),
'')
def test_named_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(self._callFUT((object(), object()), IFoo, 'bar'),
None)
def test_anonymous_hit(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
class IBaz(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IBaz)
class Baz(object):
pass
@implementer(IFoo)
class FooAdapter(object):
def __init__(self, first, second):
self.first, self.second = first, second
getGlobalSiteManager().registerAdapter(
FooAdapter, (IBar, IBaz), IFoo, '')
bar = Bar()
baz = Baz()
adapted = self._callFUT((bar, baz), IFoo, '')
self.assertTrue(adapted.__class__ is FooAdapter)
self.assertTrue(adapted.first is bar)
self.assertTrue(adapted.second is baz)
def test_named_hit(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
class IBaz(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IBaz)
class Baz(object):
pass
@implementer(IFoo)
class FooAdapter(object):
def __init__(self, first, second):
self.first, self.second = first, second
getGlobalSiteManager().registerAdapter(
FooAdapter, (IBar, IBaz), IFoo, 'named')
bar = Bar()
baz = Baz()
adapted = self._callFUT((bar, baz), IFoo, 'named')
self.assertTrue(adapted.__class__ is FooAdapter)
self.assertTrue(adapted.first is bar)
self.assertTrue(adapted.second is baz)
def test_nested(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.interface.registry import Components
from zope.component import getGlobalSiteManager
from zope.component.tests.examples import ConformsToIComponentLookup
class IFoo(Interface):
pass
class IBar(Interface):
pass
class IBaz(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IBaz)
class Baz(object):
pass
@implementer(IFoo)
class Global(object):
def __init__(self, first, second):
self.first, self.second = first, second
@implementer(IFoo)
class Local(object):
def __init__(self, first, second):
self.first, self.second = first, second
class Context(ConformsToIComponentLookup):
def __init__(self, sm):
self.sitemanager = sm
gsm = getGlobalSiteManager()
gsm.registerAdapter(Global, (IBar, IBaz), IFoo, '')
sm1 = Components('sm1', bases=(gsm, ))
sm1.registerAdapter(Local, (IBar, IBaz), IFoo, '')
bar = Bar()
baz = Baz()
adapted = self._callFUT((bar, baz), IFoo, '', context=Context(sm1))
self.assertTrue(adapted.__class__ is Local)
self.assertTrue(adapted.first is bar)
self.assertTrue(adapted.second is baz)
def test_wo_sitemanager(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
class IBar(Interface):
pass
class IBaz(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IBaz)
class Baz(object):
pass
class Context(object):
def __conform__(self, iface):
raise ComponentLookupError
bar = Bar()
baz = Baz()
adapted = self._callFUT((bar, baz), IFoo, '', context=Context())
self.assertTrue(adapted is None)
class Test_getAdapters(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import getAdapters
return getAdapters(*args, **kw)
def test_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(list(self._callFUT((object(),), IFoo)), [])
def test_hit(self):
from zope.interface import Interface
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class BarAdapter(object):
def __init__(self, context):
self.context = context
class BazAdapter(object):
def __init__(self, context):
self.context = context
gsm = getGlobalSiteManager()
gsm.registerAdapter(BarAdapter, (None,), IFoo)
gsm.registerAdapter(BazAdapter, (None,), IFoo, name='bar')
tuples = list(self._callFUT((object(),), IFoo))
self.assertEqual(len(tuples), 2)
names = [(x, y.__class__.__name__) for x, y in tuples]
self.assertTrue(('', 'BarAdapter') in names)
self.assertTrue(('bar', 'BazAdapter') in names)
def test_wo_sitemanager(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
class IBar(Interface):
pass
class IBaz(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IBaz)
class Baz(object):
pass
class Context(object):
def __conform__(self, iface):
raise ComponentLookupError
bar = Bar()
baz = Baz()
adapted = self._callFUT((bar, baz), IFoo, context=Context())
self.assertEqual(adapted, [])
class Test_subscribers(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import subscribers
return subscribers(*args, **kw)
def test_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
subscribers = self._callFUT((object,), IFoo)
self.assertEqual(subscribers, [])
def test_hit(self):
from zope.interface import Interface
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class BarAdapter(object):
def __init__(self, context):
self.context = context
class BazAdapter(object):
def __init__(self, context):
self.context = context
gsm = getGlobalSiteManager()
gsm.registerSubscriptionAdapter(BarAdapter, (None,), IFoo)
gsm.registerSubscriptionAdapter(BazAdapter, (None,), IFoo)
subscribers = self._callFUT((object(),), IFoo)
self.assertEqual(len(subscribers), 2)
names = [(x.__class__.__name__) for x in subscribers]
self.assertTrue('BarAdapter' in names)
self.assertTrue('BazAdapter' in names)
def test_wo_sitemanager(self):
from zope.interface import Interface
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
class Context(object):
def __conform__(self, iface):
raise ComponentLookupError
subscribers = self._callFUT((object,), IFoo, context=Context())
self.assertEqual(subscribers, [])
class Test_handle(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import handle
return handle(*args, **kw)
def test_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
subscribers = self._callFUT((object,), IFoo) #doesn't raise
def test_hit(self):
from zope.component import getGlobalSiteManager
from zope.interface import Interface
from zope.interface import implementer
class IFoo(Interface):
pass
@implementer(IFoo)
class Foo(object):
pass
_called = []
def _bar(context):
_called.append('_bar')
def _baz(context):
_called.append('_baz')
gsm = getGlobalSiteManager()
gsm.registerHandler(_bar, (IFoo,))
gsm.registerHandler(_baz, (IFoo,))
self._callFUT(Foo())
self.assertEqual(len(_called), 2, _called)
self.assertTrue('_bar' in _called)
self.assertTrue('_baz' in _called)
class Test_getUtility(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component._api import getUtility
return getUtility(*args, **kw)
def test_anonymous_nonesuch(self):
from zope.interface import Interface
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
self.assertRaises(ComponentLookupError, self._callFUT, IFoo)
def test_named_nonesuch(self):
from zope.interface import Interface
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
self.assertRaises(ComponentLookupError,
self._callFUT, IFoo, name='bar')
def test_anonymous_hit(self):
from zope.interface import Interface
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
obj = object()
getGlobalSiteManager().registerUtility(obj, IFoo)
self.assertTrue(self._callFUT(IFoo) is obj)
def test_named_hit(self):
from zope.interface import Interface
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
obj = object()
getGlobalSiteManager().registerUtility(obj, IFoo, name='bar')
self.assertTrue(self._callFUT(IFoo, name='bar') is obj)
def test_w_conforming_context(self):
from zope.interface import Interface
from zope.component import getGlobalSiteManager
from zope.component.tests.examples import ConformsToIComponentLookup
class SM(object):
def __init__(self, obj):
self._obj = obj
def queryUtility(self, interface, name, default):
return self._obj
class IFoo(Interface):
pass
obj1 = object()
obj2 = object()
sm = SM(obj2)
context = ConformsToIComponentLookup(sm)
getGlobalSiteManager().registerUtility(obj1, IFoo)
self.assertTrue(self._callFUT(IFoo, context=context) is obj2)
class Test_queryUtility(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component._api import queryUtility
return queryUtility(*args, **kw)
def test_anonymous_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(self._callFUT(IFoo), None)
def test_anonymous_nonesuch_w_default(self):
from zope.interface import Interface
class IFoo(Interface):
pass
obj = object()
self.assertTrue(self._callFUT(IFoo, default=obj) is obj)
def test_named_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(self._callFUT(IFoo, name='bar'), None)
def test_named_nonesuch_w_default(self):
from zope.interface import Interface
class IFoo(Interface):
pass
obj = object()
self.assertTrue(self._callFUT(IFoo, name='bar', default=obj) is obj)
def test_anonymous_hit(self):
from zope.interface import Interface
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
obj = object()
getGlobalSiteManager().registerUtility(obj, IFoo)
self.assertTrue(self._callFUT(IFoo) is obj)
def test_named_hit(self):
from zope.interface import Interface
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
obj = object()
getGlobalSiteManager().registerUtility(obj, IFoo, name='bar')
self.assertTrue(self._callFUT(IFoo, name='bar') is obj)
def test_w_conforming_context(self):
from zope.interface import Interface
from zope.component import getGlobalSiteManager
from zope.component.tests.examples import ConformsToIComponentLookup
class SM(object):
def __init__(self, obj):
self._obj = obj
def queryUtility(self, interface, name, default):
return self._obj
class IFoo(Interface):
pass
obj1 = object()
obj2 = object()
sm = SM(obj2)
context = ConformsToIComponentLookup(sm)
getGlobalSiteManager().registerUtility(obj1, IFoo)
self.assertTrue(self._callFUT(IFoo, context=context) is obj2)
class Test_getUtilitiesFor(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component._api import getUtilitiesFor
return getUtilitiesFor(*args, **kw)
def test_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(list(self._callFUT(IFoo)), [])
def test_hit(self):
from zope.interface import Interface
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
obj = object()
obj1 = object()
getGlobalSiteManager().registerUtility(obj, IFoo)
getGlobalSiteManager().registerUtility(obj1, IFoo, name='bar')
tuples = list(self._callFUT(IFoo))
self.assertEqual(len(tuples), 2)
self.assertTrue(('', obj) in tuples)
self.assertTrue(('bar', obj1) in tuples)
class Test_getAllUtilitiesRegisteredFor(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import getAllUtilitiesRegisteredFor
return getAllUtilitiesRegisteredFor(*args, **kw)
def test_nonesuch(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(list(self._callFUT(IFoo)), [])
def test_hit(self):
from zope.interface import Interface
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(IFoo):
pass
obj = object()
obj1 = object()
obj2 = object()
getGlobalSiteManager().registerUtility(obj, IFoo)
getGlobalSiteManager().registerUtility(obj1, IFoo, name='bar')
getGlobalSiteManager().registerUtility(obj2, IBar)
uts = list(self._callFUT(IFoo))
self.assertEqual(len(uts), 3)
self.assertTrue(obj in uts)
self.assertTrue(obj1 in uts)
self.assertTrue(obj2 in uts)
class Test_getNextUtility(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import getNextUtility
return getNextUtility(*args, **kw)
def test_global(self):
from zope.component import getGlobalSiteManager
from zope.component.interface import ComponentLookupError
gsm = getGlobalSiteManager()
gutil = _makeMyUtility('global', gsm)
gsm.registerUtility(gutil, IMyUtility, 'myutil')
self.assertRaises(ComponentLookupError,
self._callFUT, gutil, IMyUtility, 'myutil')
def test_nested(self):
from zope.component import getGlobalSiteManager
from zope.component.interfaces import IComponentLookup
from zope.interface.registry import Components
gsm = getGlobalSiteManager()
gutil = _makeMyUtility('global', gsm)
gsm.registerUtility(gutil, IMyUtility, 'myutil')
sm1 = Components('sm1', bases=(gsm, ))
sm1_1 = Components('sm1_1', bases=(sm1, ))
util1 = _makeMyUtility('one', sm1)
sm1.registerUtility(util1, IMyUtility, 'myutil')
self.assertTrue(IComponentLookup(util1) is sm1)
self.assertTrue(self._callFUT(util1, IMyUtility, 'myutil') is gutil)
util1_1 = _makeMyUtility('one-one', sm1_1)
sm1_1.registerUtility(util1_1, IMyUtility, 'myutil')
self.assertTrue(IComponentLookup(util1_1) is sm1_1)
self.assertTrue(self._callFUT(util1_1, IMyUtility, 'myutil') is util1)
class Test_queryNextUtility(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import queryNextUtility
return queryNextUtility(*args, **kw)
def test_global(self):
from zope.component import getGlobalSiteManager
gsm = getGlobalSiteManager()
gutil = _makeMyUtility('global', gsm)
gsm.registerUtility(gutil, IMyUtility, 'myutil')
self.assertEqual(self._callFUT(gutil, IMyUtility, 'myutil'), None)
def test_nested(self):
from zope.component import getGlobalSiteManager
from zope.interface.registry import Components
gsm = getGlobalSiteManager()
gutil = _makeMyUtility('global', gsm)
gsm.registerUtility(gutil, IMyUtility, 'myutil')
sm1 = Components('sm1', bases=(gsm, ))
sm1_1 = Components('sm1_1', bases=(sm1, ))
util1 = _makeMyUtility('one', sm1)
sm1.registerUtility(util1, IMyUtility, 'myutil')
util1_1 = _makeMyUtility('one-one', sm1_1)
sm1_1.registerUtility(util1_1, IMyUtility, 'myutil')
myregistry = Components()
custom_util = _makeMyUtility('my_custom_util', myregistry)
myregistry.registerUtility(custom_util, IMyUtility, 'my_custom_util')
sm1.__bases__ = (myregistry,) + sm1.__bases__
# Both the ``myregistry`` and global utilities should be available:
self.assertTrue(self._callFUT(sm1, IMyUtility, 'my_custom_util')
is custom_util)
self.assertTrue(self._callFUT(sm1, IMyUtility, 'myutil') is gutil)
def test_wo_sitemanager(self):
from zope.interface import Interface
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
class Context(object):
def __conform__(self, iface):
raise ComponentLookupError
self.assertEqual(self._callFUT(Context(), IFoo, 'myutil'), None)
class Test_createObject(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import createObject
return createObject(*args, **kw)
def test_miss(self):
from zope.component.interfaces import ComponentLookupError
self.assertRaises(ComponentLookupError, self._callFUT, 'nonesuch')
def test_hit(self):
from zope.component.interfaces import IFactory
_object = object()
_factory_called = []
def _factory(*args, **kw):
_factory_called.append((args, kw))
return _object
class Context(object):
def __conform__(self, iface):
return self
def queryUtility(self, iface, name, default):
if iface is IFactory and name == 'test':
return _factory
return default
context = Context()
self.assertTrue(self._callFUT('test', context=context) is _object)
self.assertEqual(_factory_called, [((), {})])
class Test_getFactoryInterfaces(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import getFactoryInterfaces
return getFactoryInterfaces(*args, **kw)
def test_miss(self):
from zope.component.interfaces import ComponentLookupError
self.assertRaises(ComponentLookupError, self._callFUT, 'nonesuch')
def test_hit(self):
from zope.component.interfaces import IFactory
from zope.interface import Interface
class IFoo(Interface):
pass
class _Factory(object):
def getInterfaces(self):
return [IFoo]
class Context(object):
def __conform__(self, iface):
return self
def queryUtility(self, iface, name, default):
if iface is IFactory and name == 'test':
return _Factory()
return default
context = Context()
self.assertEqual(self._callFUT('test', context=context), [IFoo])
class Test_getFactoriesFor(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component import getFactoriesFor
return getFactoriesFor(*args, **kw)
def test_no_factories_registered(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(list(self._callFUT(IFoo)), [])
def test_w_factory_returning_spec(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.interface import providedBy
from zope.component.interfaces import IFactory
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IFoo, IBar)
class _Factory(object):
def getInterfaces(self):
return providedBy(self)
_factory = _Factory()
class Context(object):
def __conform__(self, iface):
return self
def getUtilitiesFor(self, iface):
if iface is IFactory:
return [('test', _factory)]
self.assertEqual(list(self._callFUT(IFoo, context=Context())),
[('test', _factory)])
self.assertEqual(list(self._callFUT(IBar, context=Context())),
[('test', _factory)])
def test_w_factory_returning_list_of_interfaces(self):
from zope.interface import Interface
from zope.component.interfaces import IFactory
class IFoo(Interface):
pass
class IBar(Interface):
pass
class _Factory(object):
def getInterfaces(self):
return [IFoo, IBar]
_factory = _Factory()
class Context(object):
def __conform__(self, iface):
return self
def getUtilitiesFor(self, iface):
if iface is IFactory:
return [('test', _factory)]
self.assertEqual(list(self._callFUT(IFoo, context=Context())),
[('test', _factory)])
self.assertEqual(list(self._callFUT(IBar, context=Context())),
[('test', _factory)])
IMyUtility = None
def _makeMyUtility(name, sm):
global IMyUtility
from zope.interface import Interface
from zope.interface import implementer
from zope.component.tests.examples import ConformsToIComponentLookup
if IMyUtility is None:
class IMyUtility(Interface):
pass
@implementer(IMyUtility)
class MyUtility(ConformsToIComponentLookup):
def __init__(self, id, sm):
self.id = id
self.sitemanager = sm
return MyUtility(name, sm)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test_getSiteManager),
unittest.makeSuite(Test_getAdapterInContext),
unittest.makeSuite(Test_queryAdapterInContext),
unittest.makeSuite(Test_getAdapter),
unittest.makeSuite(Test_queryAdapter),
unittest.makeSuite(Test_getMultiAdapter),
unittest.makeSuite(Test_queryMultiAdapter),
unittest.makeSuite(Test_getAdapters),
unittest.makeSuite(Test_subscribers),
unittest.makeSuite(Test_handle),
unittest.makeSuite(Test_getUtility),
unittest.makeSuite(Test_queryUtility),
unittest.makeSuite(Test_getUtilitiesFor),
unittest.makeSuite(Test_getAllUtilitiesRegisteredFor),
unittest.makeSuite(Test_getNextUtility),
unittest.makeSuite(Test_queryNextUtility),
unittest.makeSuite(Test_createObject),
unittest.makeSuite(Test_getFactoryInterfaces),
unittest.makeSuite(Test_getFactoriesFor),
))
zope.component-4.0.2/src/zope/component/tests/test_persistentregistry.py 0000664 0001750 0001750 00000014421 12024145570 026715 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
"""Tests for z.c.hooks
"""
import unittest
class PersistentAdapterRegistryTests(unittest.TestCase):
def _getTargetClass(self):
from zope.component.persistentregistry import PersistentAdapterRegistry
return PersistentAdapterRegistry
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def _makeCache(self, jar):
# Borrowed from persistent.tests.test_pyPersistence.
class _Cache(object):
def __init__(self, jar):
self._jar = jar
self._mru = []
def mru(self, oid):
self._mru.append(oid)
def new_ghost(self, oid, obj):
obj._p_jar = self._jar
obj._p_oid = oid
return _Cache(jar)
def _makeJar(self):
# Borrowed from persistent.tests.test_pyPersistence.
from zope.interface import implements
from persistent.interfaces import IPersistentDataManager
class _Jar(object):
implements(IPersistentDataManager)
def __init__(self):
self._loaded = []
self._registered = []
def setstate(self, obj):
self._loaded.append(obj._p_oid)
def register(self, obj):
self._registered.append(obj._p_oid)
jar = _Jar()
jar._cache = self._makeCache(jar)
return jar
def _makeOneWithJar(self, dirty=False, **kw):
# Borrowed from persistent.tests.test_pyPersistence.
OID = _makeOctets('\x01' * 8)
inst = self._makeOne(**kw)
jar = self._makeJar()
jar._cache.new_ghost(OID, inst) # assigns _p_jar, _p_oid
return inst, jar, OID
def test_changed_original_is_not_us(self):
registry, jar, OID = self._makeOneWithJar()
self.assertEqual(registry._generation, 1)
registry.changed(object())
# 'originally_changed' is not us, but we are still dirty because
# '_generation' gets bumped.
self.assertEqual(registry._p_changed, True)
# base class gets called
self.assertEqual(registry._generation, 2)
def test_changed_original_is_us(self):
registry, jar, OID = self._makeOneWithJar()
self.assertEqual(registry._generation, 1)
registry.changed(registry)
# 'originally_changed' is not us, so not dirty
self.assertEqual(registry._p_changed, True)
# base class gets called
self.assertEqual(registry._generation, 2)
def test___getstate___simple(self):
from zope.component import globalSiteManager
bases = (globalSiteManager.adapters, globalSiteManager.utilities)
registry, jar, OID = self._makeOneWithJar(bases=bases)
state = registry.__getstate__()
self.assertEqual(state['__bases__'], bases)
self.assertEqual(state['_generation'], 1)
self.assertEqual(state['_provided'], {})
self.assertEqual(state['_adapters'], [])
self.assertEqual(state['_subscribers'], [])
self.assertFalse('ro' in state)
def test___getstate___skips_delegated_names(self):
registry, jar, OID = self._makeOneWithJar()
registry.names = lambda *args: ['a', 'b', 'c']
self.assertFalse('names' in registry.__getstate__())
def test___setstate___rebuilds__v_lookup(self):
registry, jar, OID = self._makeOneWithJar()
state = registry.__getstate__()
self.assertTrue('_v_lookup' in registry.__dict__)
registry._p_changed = None # clears volatile '_v_lookup'
self.assertFalse('_v_lookup' in registry.__dict__)
registry.__setstate__(state)
self.assertTrue('_v_lookup' in registry.__dict__)
def test___setstate___rebuilds__ro(self):
from zope.component import globalSiteManager
bases = (globalSiteManager.adapters, globalSiteManager.utilities)
registry, jar, OID = self._makeOneWithJar(bases=bases)
state = registry.__getstate__()
registry.__setstate__(state)
self.assertEqual(registry.__bases__, bases)
self.assertEqual(registry.ro, [registry] + list(bases))
class PersistentComponentsTests(unittest.TestCase):
def _getTargetClass(self):
from zope.component.persistentregistry import PersistentComponents
return PersistentComponents
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_ctor_initializes_registries_and_registrations(self):
from persistent.mapping import PersistentMapping
from persistent.list import PersistentList
from zope.component.persistentregistry import PersistentAdapterRegistry
registry = self._makeOne()
self.assertTrue(isinstance(registry.adapters,
PersistentAdapterRegistry))
self.assertTrue(isinstance(registry.utilities,
PersistentAdapterRegistry))
self.assertTrue(isinstance(registry._adapter_registrations,
PersistentMapping))
self.assertTrue(isinstance(registry._utility_registrations,
PersistentMapping))
self.assertTrue(isinstance(registry._subscription_registrations,
PersistentList))
self.assertTrue(isinstance(registry._handler_registrations,
PersistentList))
def _makeOctets(s):
import sys
if sys.version_info < (3,):
return bytes(s)
return bytes(s, 'ascii') #pragma NO COVERAGE
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(PersistentAdapterRegistryTests),
unittest.makeSuite(PersistentComponentsTests),
))
zope.component-4.0.2/src/zope/component/tests/test_event.py 0000664 0001750 0001750 00000004467 11774312422 024061 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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 adapter declaration helpers
"""
import unittest
class Test_dispatch(unittest.TestCase):
def test_it(self):
from zope.interface import Interface
from zope.component.globalregistry import getGlobalSiteManager
from zope.component.event import dispatch
_adapted = []
def _adapter(context):
_adapted.append(context)
return object()
gsm = getGlobalSiteManager()
gsm.registerHandler(_adapter, (Interface,))
del _adapted[:] # clear handler reg
event = object()
dispatch(event)
self.assertEqual(_adapted, [event])
class Test_objectEventNotify(unittest.TestCase):
def test_it(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component.globalregistry import getGlobalSiteManager
from zope.component.interfaces import IObjectEvent
from zope.component.event import objectEventNotify
_adapted = []
def _adapter(context, event):
_adapted.append((context, event))
return object()
gsm = getGlobalSiteManager()
gsm.registerHandler(_adapter, (Interface, IObjectEvent))
del _adapted[:] # clear handler reg
@implementer(IObjectEvent)
class _ObjectEvent(object):
def __init__(self, object):
self.object = object
context = object()
event = _ObjectEvent(context)
objectEventNotify(event)
self.assertEqual(_adapted, [(context, event)])
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test_dispatch),
unittest.makeSuite(Test_objectEventNotify),
))
zope.component-4.0.2/src/zope/component/tests/__init__.py 0000664 0001750 0001750 00000000020 11774312422 023415 0 ustar tseaver tseaver # tests package
zope.component-4.0.2/src/zope/component/tests/test_hooks.py 0000664 0001750 0001750 00000026663 11774312422 024065 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
"""Tests for z.c.hooks
"""
import unittest
class Test_read_property(unittest.TestCase):
def _getTargetClass(self):
from zope.component.hooks import read_property
return read_property
def test_via_instance(self):
class Foo(object):
@self._getTargetClass()
def bar(self):
return 'BAR'
foo = Foo()
self.assertEqual(foo.bar, 'BAR')
foo.bar = 'BAZ'
self.assertEqual(foo.bar, 'BAZ')
del foo.bar
self.assertEqual(foo.bar, 'BAR')
def test_via_class(self):
class Foo(object):
@self._getTargetClass()
def bar(self):
return 'BAR'
bar = Foo.bar
self.assertTrue(isinstance(bar, self._getTargetClass()))
self.assertEqual(bar.func(object()), 'BAR')
class SiteInfoTests(unittest.TestCase):
def _getTargetClass(self):
from zope.component.hooks import SiteInfo
return SiteInfo
def _makeOne(self):
return self._getTargetClass()()
def test_initial(self):
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
si = self._makeOne()
self.assertEqual(si.site, None)
self.assertTrue(si.sm is gsm)
def test_adapter_hook(self):
_hook = object()
class _Registry(object):
adapter_hook = _hook
class _SiteManager(object):
adapters = _Registry()
si = self._makeOne()
si.sm = _SiteManager()
self.assertFalse('adapter_hook' in si.__dict__)
self.assertTrue(si.adapter_hook is _hook)
self.assertTrue('adapter_hook' in si.__dict__)
del si.adapter_hook
self.assertFalse('adapter_hook' in si.__dict__)
class Test_setSite(unittest.TestCase):
def _callFUT(self, site):
from zope.component.hooks import setSite
return setSite(site)
def test_w_None(self):
from zope.component import hooks
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
_SM2 = object()
_SITE = object()
_HOOK = object()
siteinfo = _DummySiteInfo()
siteinfo.sm = _SM2
siteinfo.site = _SITE
siteinfo.adapterhook = _HOOK
with _Monkey(hooks, siteinfo=siteinfo):
self._callFUT(None)
self.assertTrue(siteinfo.sm is gsm)
self.assertTrue(siteinfo.site is None)
self.assertFalse('adapter_hook' in siteinfo.__dict__)
def test_w_site(self):
from zope.component import hooks
_SM2 = object()
class _Site(object):
def getSiteManager(self):
return _SM2
siteinfo = _DummySiteInfo()
_site = _Site()
with _Monkey(hooks, siteinfo=siteinfo):
self._callFUT(_site)
self.assertTrue(siteinfo.sm is _SM2)
self.assertTrue(siteinfo.site is _site)
self.assertFalse('adapter_hook' in siteinfo.__dict__)
class Test_getSite(unittest.TestCase):
def _callFUT(self):
from zope.component.hooks import getSite
return getSite()
def test_w_None(self):
from zope.component import hooks
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
siteinfo = _DummySiteInfo()
with _Monkey(hooks, siteinfo=siteinfo):
self.assertTrue(self._callFUT() is None)
def test_w_site(self):
from zope.component import hooks
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
_SM2 = object()
_SITE = object()
siteinfo = _DummySiteInfo()
siteinfo.sm = _SM2
siteinfo.site = _SITE
with _Monkey(hooks, siteinfo=siteinfo):
self.assertTrue(self._callFUT() is _SITE)
class Test_site(unittest.TestCase):
def _callFUT(self, new_site):
from zope.component.hooks import site
return site(new_site)
def test_it(self):
from zope.component import hooks
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
_SM2 = object()
class _Site(object):
def getSiteManager(self):
return _SM2
_site = _Site()
siteinfo = _DummySiteInfo()
self.assertTrue(siteinfo.site is None)
self.assertTrue(siteinfo.sm is _SM)
with _Monkey(hooks, siteinfo=siteinfo):
with self._callFUT(_site):
self.assertTrue(siteinfo.site is _site)
self.assertTrue(siteinfo.sm is _SM2)
self.assertTrue(siteinfo.site is None)
self.assertTrue(siteinfo.sm is gsm)
class Test_getSiteManager(unittest.TestCase):
def _callFUT(self, context=None):
from zope.component.hooks import getSiteManager
return getSiteManager(context)
def test_default(self):
from zope.component import hooks
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
_SM2 = object()
siteinfo = _DummySiteInfo()
siteinfo.sm = _SM2
with _Monkey(hooks, siteinfo=siteinfo):
self.assertTrue(self._callFUT() is _SM2)
def test_w_explicit_context_no_IComponentLookup(self):
from zope.component import hooks
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
_SM2 = object()
siteinfo = _DummySiteInfo()
siteinfo.sm = _SM2
with _Monkey(hooks, siteinfo=siteinfo):
self.assertTrue(self._callFUT(object()) is gsm)
def test_w_explicit_context_w_IComponentLookup(self):
from zope.interface import Interface
from zope.component import hooks
from zope.component.globalregistry import getGlobalSiteManager
from zope.component.interfaces import IComponentLookup
class _Lookup(object):
def __init__(self, context):
self.context = context
gsm = getGlobalSiteManager()
gsm.registerAdapter(_Lookup, (Interface,), IComponentLookup, '')
_SM2 = object()
siteinfo = _DummySiteInfo()
siteinfo.sm = _SM2
context = object()
with _Monkey(hooks, siteinfo=siteinfo):
sm = self._callFUT(context)
self.assertTrue(isinstance(sm, _Lookup))
self.assertTrue(sm.context is context)
class Test_adapter_hook(unittest.TestCase):
def _callFUT(self, interface, object, name='', default=None):
from zope.component.hooks import adapter_hook
return adapter_hook(interface, object, name, default)
def test_success(self):
from zope.interface import Interface
from zope.component import hooks
from zope.component.globalregistry import getGlobalSiteManager
class IFoo(Interface):
pass
gsm = getGlobalSiteManager()
_ADAPTER = object()
_DEFAULT = object()
_CONTEXT = object()
_called = []
def _adapter_hook(interface, object, name, default):
_called.append((interface, object, name, default))
return _ADAPTER
siteinfo = _DummySiteInfo()
siteinfo.adapter_hook = _adapter_hook
with _Monkey(hooks, siteinfo=siteinfo):
adapter = self._callFUT(IFoo, _CONTEXT, 'bar', _DEFAULT)
self.assertTrue(adapter is _ADAPTER)
self.assertEqual(_called, [(IFoo, _CONTEXT, 'bar', _DEFAULT)])
def test_hook_raises(self):
from zope.interface import Interface
from zope.component import hooks
from zope.component.globalregistry import getGlobalSiteManager
from zope.component.interfaces import ComponentLookupError
class IFoo(Interface):
pass
gsm = getGlobalSiteManager()
_DEFAULT = object()
_CONTEXT = object()
_called = []
def _adapter_hook(interface, object, name, default):
_called.append((interface, object, name, default))
raise ComponentLookupError('testing')
siteinfo = _DummySiteInfo()
siteinfo.adapter_hook = _adapter_hook
with _Monkey(hooks, siteinfo=siteinfo):
adapter = self._callFUT(IFoo, _CONTEXT, 'bar', _DEFAULT)
self.assertTrue(adapter is _DEFAULT)
self.assertEqual(_called, [(IFoo, _CONTEXT, 'bar', _DEFAULT)])
class Test_setHooks(unittest.TestCase):
def _callFUT(self):
from zope.component.hooks import setHooks
return setHooks()
def test_it(self):
import zope.component._api
from zope.component import hooks
class _Hook(object):
def __init__(self):
self._hooked = None
def sethook(self, value):
self._hooked = value
adapter_hook = _Hook()
getSiteManager = _Hook()
with _Monkey(zope.component._api,
adapter_hook=adapter_hook,
getSiteManager=getSiteManager):
self._callFUT()
self.assertEqual(adapter_hook._hooked, hooks.adapter_hook)
self.assertEqual(getSiteManager._hooked, hooks.getSiteManager)
class Test_resetHooks(unittest.TestCase):
def _callFUT(self):
from zope.component.hooks import resetHooks
return resetHooks()
def test_it(self):
import zope.component._api
class _Hook(object):
def __init__(self):
self._reset = False
def reset(self):
self._reset = True
adapter_hook = _Hook()
getSiteManager = _Hook()
with _Monkey(zope.component._api,
adapter_hook=adapter_hook,
getSiteManager=getSiteManager):
self._callFUT()
self.assertTrue(adapter_hook._reset)
self.assertTrue(getSiteManager._reset)
_SM = object()
class _DummySiteInfo(object):
sm = _SM
site = None
class _Monkey(object):
# context-manager for replacing module names in the scope of a test.
def __init__(self, module, **kw):
self.module = module
self.to_restore = dict([(key, getattr(module, key)) for key in kw])
for key, value in kw.items():
setattr(module, key, value)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
for key, value in self.to_restore.items():
setattr(self.module, key, value)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test_read_property),
unittest.makeSuite(SiteInfoTests),
unittest.makeSuite(Test_setSite),
unittest.makeSuite(Test_getSite),
unittest.makeSuite(Test_site),
unittest.makeSuite(Test_getSiteManager),
unittest.makeSuite(Test_adapter_hook),
unittest.makeSuite(Test_setHooks),
unittest.makeSuite(Test_resetHooks),
))
zope.component-4.0.2/src/zope/component/tests/test_registry.py 0000664 0001750 0001750 00000011057 11774312422 024601 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
"""Tests for z.c.registry
"""
import unittest
class Test_dispatchUtilityRegistrationEvent(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.registry import dispatchUtilityRegistrationEvent
return dispatchUtilityRegistrationEvent(*args, **kw)
def test_it(self):
from zope.component import registry
class _Registration(object):
component = object()
_EVENT = object()
_handled = []
def _handle(*args):
_handled.append(args)
with _Monkey(registry, handle=_handle):
self._callFUT(_Registration(), _EVENT)
self.assertEqual(_handled, [(_Registration.component, _EVENT)])
class Test_dispatchAdapterRegistrationEvent(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.registry import dispatchAdapterRegistrationEvent
return dispatchAdapterRegistrationEvent(*args, **kw)
def test_it(self):
from zope.component import registry
class _Registration(object):
def factory(self, *args, **kw):
pass
_registration = _Registration()
_EVENT = object()
_handled = []
def _handle(*args):
_handled.append(args)
with _Monkey(registry, handle=_handle):
self._callFUT(_registration, _EVENT)
self.assertEqual(_handled, [(_registration.factory, _EVENT)])
class Test_dispatchSubscriptionAdapterRegistrationEvent(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.registry \
import dispatchSubscriptionAdapterRegistrationEvent
return dispatchSubscriptionAdapterRegistrationEvent(*args, **kw)
def test_it(self):
from zope.component import registry
class _Registration(object):
def factory(self, *args, **kw):
pass
_registration = _Registration()
_EVENT = object()
_handled = []
def _handle(*args):
_handled.append(args)
with _Monkey(registry, handle=_handle):
self._callFUT(_registration, _EVENT)
self.assertEqual(_handled, [(_registration.factory, _EVENT)])
class Test_dispatchHandlerRegistrationEvent(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.registry import dispatchHandlerRegistrationEvent
return dispatchHandlerRegistrationEvent(*args, **kw)
def test_it(self):
from zope.component import registry
class _Registration(object):
def handler(self, *args, **kw):
pass
_registration = _Registration()
_EVENT = object()
_handled = []
def _handle(*args):
_handled.append(args)
with _Monkey(registry, handle=_handle):
self._callFUT(_registration, _EVENT)
self.assertEqual(_handled, [(_registration.handler, _EVENT)])
class _Monkey(object):
# context-manager for replacing module names in the scope of a test.
def __init__(self, module, **kw):
self.module = module
self.to_restore = dict([(key, getattr(module, key)) for key in kw])
for key, value in kw.items():
setattr(module, key, value)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
for key, value in self.to_restore.items():
setattr(self.module, key, value)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test_dispatchUtilityRegistrationEvent),
unittest.makeSuite(Test_dispatchAdapterRegistrationEvent),
unittest.makeSuite(Test_dispatchSubscriptionAdapterRegistrationEvent),
unittest.makeSuite(Test_dispatchHandlerRegistrationEvent),
))
zope.component-4.0.2/src/zope/component/tests/examples.py 0000664 0001750 0001750 00000006246 11774312422 023514 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002, 2009 Zope Foundation 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.
#
##############################################################################
"""Examples supporting Sphinx doctest snippets.
"""
import sys
from zope.interface import Interface
from zope.interface import implementer
from zope.interface.interfaces import IInterface
from zope.component._declaration import adapter
from zope.component.testfiles.views import IC
def write(x):
sys.stdout.write('%s\n' % x)
class ITestType(IInterface):
pass
class I1(Interface):
pass
class I2(Interface):
pass
class I3(Interface):
pass
class I4(Interface):
pass
class IGI(Interface):
pass
class IQI(Interface):
pass
class ISI(Interface):
pass
class ISII(Interface):
pass
def noop(*args):
pass
class U(object):
def __init__(self, name):
self.__name__ = name
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, self.__name__)
@implementer(I1)
class U1(U):
pass
@implementer(I1, I2)
class U12(U):
pass
@adapter(I1)
def handle1(x):
write('handle1 %s' % x)
def handle2(*objects):
write( 'handle2 ' + repr(objects))
@adapter(I1)
def handle3(x):
write( 'handle3 %s' % x)
@adapter(I1)
def handle4(x):
write( 'handle4 %s' % x)
class GlobalRegistry:
pass
from zope.component.globalregistry import GlobalAdapterRegistry
base = GlobalAdapterRegistry(GlobalRegistry, 'adapters')
GlobalRegistry.adapters = base
def clear_base():
base.__init__(GlobalRegistry, 'adapters')
@implementer(I1)
class Ob(object):
def __repr__(self):
return ''
ob = Ob()
@implementer(I2)
class Ob2(object):
def __repr__(self):
return ''
@implementer(IC)
class Ob3(object):
pass
@implementer(I2)
class Comp(object):
def __init__(self, context):
self.context = context
comp = Comp(1)
@implementer(I3)
class Comp2(object):
def __init__(self, context):
self.context = context
class ConformsToIComponentLookup(object):
"""Allow a dummy sitemanager to conform/adapt to `IComponentLookup`."""
def __init__(self, sitemanager):
self.sitemanager = sitemanager
def __conform__(self, interface):
"""This method is specified by the adapter PEP to do the adaptation."""
from zope.component.interfaces import IComponentLookup
if interface is IComponentLookup:
return self.sitemanager
def clearZCML(test=None):
from zope.configuration.xmlconfig import XMLConfig
import zope.component
from zope.component.testing import setUp
from zope.component.testing import tearDown
tearDown()
setUp()
XMLConfig('meta.zcml', zope.component)()
zope.component-4.0.2/src/zope/component/tests/test_factory.py 0000664 0001750 0001750 00000007310 11774312422 024375 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
"""Tests for z.c.factory
"""
import unittest
class FactoryTests(unittest.TestCase):
def _getTargetClass(self):
from zope.component.factory import Factory
return Factory
def _makeOne(self, callable=None, *args, **kw):
if callable is None:
callable = _test_callable
return self._getTargetClass()(callable, *args, **kw)
def test_class_conforms_to_IFactory(self):
from zope.interface.verify import verifyClass
from zope.component.interfaces import IFactory
verifyClass(IFactory, self._getTargetClass())
def test_instance_conforms_to_IFactory(self):
from zope.interface.verify import verifyObject
from zope.component.interfaces import IFactory
verifyObject(IFactory, self._makeOne())
def test_ctor_defaults(self):
factory = self._makeOne()
self.assertEqual(factory._callable, _test_callable)
self.assertEqual(factory.title, '')
self.assertEqual(factory.description, '')
self.assertEqual(factory._interfaces, None)
def test_ctor_expclit(self):
factory = self._makeOne(_test_callable, 'TITLE', 'DESCRIPTION')
self.assertEqual(factory.title, 'TITLE')
self.assertEqual(factory.description, 'DESCRIPTION')
def test___call___no_args(self):
_called = []
def _callable(*args, **kw):
_called.append((args, kw))
factory = self._makeOne(_callable)
factory()
self.assertEqual(_called, [((), {})])
def test___call___positional_args(self):
_called = []
def _callable(*args, **kw):
_called.append((args, kw))
factory = self._makeOne(_callable)
factory('one', 'two')
self.assertEqual(_called, [(('one', 'two'), {})])
def test___call___keyword_args(self):
_called = []
def _callable(*args, **kw):
_called.append((args, kw))
factory = self._makeOne(_callable)
factory(foo='bar')
self.assertEqual(_called, [((), {'foo': 'bar'})])
def test_getInterfaces_explicit(self):
from zope.interface import Interface
from zope.interface import implementer
class IFoo(Interface):
pass
class IBar(Interface):
pass
class IBaz(Interface):
pass
@implementer(IBaz)
def _callable():
pass
factory = self._makeOne(_callable, interfaces=(IFoo, IBar))
spec = factory.getInterfaces()
self.assertEqual(spec.__name__, '_callable')
self.assertEqual(list(spec), [IFoo, IBar])
def test_getInterfaces_implicit(self):
from zope.interface import Interface
from zope.interface import implementer
class IBaz(Interface):
pass
@implementer(IBaz)
def _callable():
pass
factory = self._makeOne(_callable)
spec = factory.getInterfaces()
self.assertEqual(list(spec), [IBaz])
def _test_callable(*args, **kw):
pass
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(FactoryTests),
))
zope.component-4.0.2/src/zope/component/tests/test_hookable.py 0000664 0001750 0001750 00000010001 11774312422 024501 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
"""Pure-Python hookable tests
"""
import unittest
class HookableTests(unittest.TestCase):
def test_ctor_no_func(self):
from zope.component.hookable import hookable
self.assertRaises(TypeError, hookable)
def test_ctor_simple(self):
from zope.component.hookable import hookable
def foo():
pass
hooked = hookable(foo)
self.failUnless(hooked.original is foo)
self.failUnless(hooked.implementation is foo)
def test_ctor_extra_arg(self):
from zope.component.hookable import hookable
def foo():
pass
self.assertRaises(TypeError, hookable, foo, foo)
def test_ctor_extra_arg_miss(self):
from zope.component.hookable import hookable
def foo():
pass
self.assertRaises(TypeError, hookable, foo, nonesuch=foo)
def test_sethook(self):
from zope.component.hookable import hookable
def foo():
pass
def bar():
pass
hooked = hookable(foo)
hooked.sethook(bar)
self.failUnless(hooked.original is foo)
self.failUnless(hooked.implementation is bar)
def test_reset(self):
from zope.component.hookable import hookable
def foo():
pass
def bar():
pass
hooked = hookable(foo)
hooked.sethook(bar)
hooked.reset()
self.failUnless(hooked.original is foo)
self.failUnless(hooked.implementation is foo)
def test_cant_assign_original(self):
from zope.component.hookable import hookable
def foo():
pass
def bar():
pass
hooked = hookable(foo)
try:
hooked.original = bar
except TypeError:
pass
except AttributeError:
pass
else:
self.fail('Assigned original')
def test_cant_delete_original(self):
from zope.component.hookable import hookable
def foo():
pass
hooked = hookable(foo)
try:
del hooked.original
except TypeError:
pass
except AttributeError:
pass
else:
self.fail('Deleted original')
def test_cant_assign_implementation(self):
from zope.component.hookable import hookable
def foo():
pass
def bar():
pass
hooked = hookable(foo)
try:
hooked.implementation = bar
except TypeError:
pass
except AttributeError:
pass
else:
self.fail('Assigned implementation')
def test_cant_delete_implementation(self):
from zope.component.hookable import hookable
def foo():
pass
hooked = hookable(foo)
try:
del hooked.implementation
except TypeError:
pass
except AttributeError:
pass
else:
self.fail('Deleted implementation')
def test_ctor___call__(self):
from zope.component.hookable import hookable
_called = []
def foo(*args, **kw):
_called.append((args, kw))
hooked = hookable(foo)
hooked('one', 'two', bar='baz')
self.assertEqual(_called, [(('one', 'two'), {'bar': 'baz'})])
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(HookableTests),
))
zope.component-4.0.2/src/zope/component/tests/test___init__.py 0000664 0001750 0001750 00000006174 11774312422 024474 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
import unittest
class Test_package(unittest.TestCase):
def test_module_conforms_to_IComponentArchitecture(self):
from zope.interface.verify import verifyObject
from zope.component.interfaces import IComponentArchitecture
import zope.component as zc
verifyObject(IComponentArchitecture, zc)
def test_module_conforms_to_IComponentRegistrationConvenience(self):
from zope.interface.verify import verifyObject
from zope.component.interfaces import IComponentRegistrationConvenience
import zope.component as zc
verifyObject(IComponentRegistrationConvenience, zc)
class Test_Interface_call(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def test_miss(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertRaises(TypeError, IFoo, object())
def test_miss_w_default(self):
from zope.interface import Interface
class IFoo(Interface):
pass
marker = object()
self.assertTrue(IFoo(object(), marker) is marker)
def test_hit(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
class IBar(Interface):
pass
@implementer(IBar)
class Bar(object):
pass
@implementer(IFoo)
class Baz(object):
def __init__(self, context):
self.context = context
getGlobalSiteManager().registerAdapter(Baz, (IBar,), IFoo, '')
bar = Bar()
adapted = IFoo(bar)
self.assertTrue(adapted.__class__ is Baz)
self.assertTrue(adapted.context is bar)
def test_hit_registered_for_None(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component import getGlobalSiteManager
class IFoo(Interface):
pass
@implementer(IFoo)
class Baz(object):
def __init__(self, context):
self.context = context
getGlobalSiteManager().registerAdapter(Baz, (None,), IFoo, '')
ctx = object()
adapted = IFoo(ctx)
self.assertTrue(adapted.__class__ is Baz)
self.assertTrue(adapted.context is ctx)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test_package),
unittest.makeSuite(Test_Interface_call),
))
zope.component-4.0.2/src/zope/component/tests/test_security.py 0000664 0001750 0001750 00000022234 11774312422 024577 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
"""Pure-Python hookable tests
"""
import unittest
class PermissionProxyTests(unittest.TestCase):
def _getTargetClass(self):
from zope.component.security import PermissionProxy
return PermissionProxy
def _makeOne(self, wrapped):
return self._getTargetClass()(wrapped)
def test_proxy_delegates___provided_by__(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.interface import providedBy
class IFoo(Interface):
pass
@implementer(IFoo)
class Foo(object):
pass
foo = Foo()
proxy = self._makeOne(foo)
self.assertEqual(providedBy(proxy), providedBy(foo))
class Test__checker(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.security import _checker
return _checker(*args, **kw)
def test_no_allowed_attributes_no_allowed_interfaces(self):
from zope.security.checker import CheckerPublic
checker = self._callFUT(object(), 'zope.Public', (), ())
self.assertEqual(checker.get_permissions, {'__call__': CheckerPublic})
self.assertFalse(checker.set_permissions)
def test_w_allowed_interfaces(self):
from zope.interface import Interface
class IFoo(Interface):
def bar(self):
pass
def baz(self):
pass
class ISpam(Interface):
def qux(self):
pass
checker = self._callFUT(object(), 'testing', (IFoo, ISpam), ())
self.assertEqual(checker.get_permissions,
{'bar': 'testing', 'baz': 'testing', 'qux': 'testing'})
self.assertFalse(checker.set_permissions)
def test_w_allowed_attributes(self):
checker = self._callFUT(object(), 'testing', (), ('foo', 'bar'))
self.assertEqual(checker.get_permissions,
{'foo': 'testing', 'bar': 'testing'})
self.assertFalse(checker.set_permissions)
class Test_proxify(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.security import proxify
return proxify(*args, **kw)
def _makeContext(self):
class _Context(object):
def bar(self):
pass
return _Context()
def test_no_checker_no_provides(self):
ctx = self._makeContext()
self.assertRaises(ValueError, self._callFUT, ctx, permission='testing')
def test_no_checker_no_permission(self):
from zope.interface import Interface
class IFoo(Interface):
def bar(self):
pass
ctx = self._makeContext()
self.assertRaises(ValueError, self._callFUT, ctx, provides=IFoo)
def test_no_checker_w_provides_and_permission_public(self):
from zope.interface import Interface
from zope.security.checker import CheckerPublic
from zope.proxy import getProxiedObject
class IFoo(Interface):
def bar(self):
pass
ctx = self._makeContext()
proxy = self._callFUT(ctx, provides=IFoo, permission='zope.Public')
self.assertTrue(getProxiedObject(proxy) is ctx)
checker = proxy.__Security_checker__
self.assertEqual(checker.get_permissions, {'bar': CheckerPublic})
self.assertFalse(checker.set_permissions)
def test_no_checker_w_provides_and_permission_protected(self):
from zope.interface import Interface
from zope.proxy import getProxiedObject
class IFoo(Interface):
def bar(self):
pass
ctx = self._makeContext()
proxy = self._callFUT(ctx, provides=IFoo, permission='testing')
self.assertTrue(getProxiedObject(proxy) is ctx)
checker = proxy.__Security_checker__
self.assertEqual(checker.get_permissions, {'bar': 'testing'})
self.assertFalse(checker.set_permissions)
def test_w_checker(self):
from zope.proxy import getProxiedObject
_CHECKER = object()
ctx = self._makeContext()
proxy = self._callFUT(ctx, _CHECKER)
self.assertTrue(getProxiedObject(proxy) is ctx)
self.assertTrue(proxy.__Security_checker__ is _CHECKER)
class Test_protectedFactory(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.security import protectedFactory
return protectedFactory(*args, **kw)
def test_public_not_already_proxied(self):
from zope.interface import Interface
from zope.security.checker import CheckerPublic
class IFoo(Interface):
def bar(self):
pass
class _Factory(object):
def bar(self):
pass
protected = self._callFUT(_Factory, IFoo, 'zope.Public')
self.assertTrue(protected.factory is _Factory)
foo = protected()
self.assertEqual(foo.__Security_checker__.get_permissions,
{'bar': CheckerPublic})
def test_nonpublic_already_proxied(self):
from zope.interface import Interface
from zope.security.proxy import getTestProxyItems
class IFoo(Interface):
def bar(self):
pass
class _Factory(object):
__slots__ = ('one',)
def bar(self):
pass
protected = self._callFUT(_Factory, IFoo, 'testing')
self.assertTrue(protected.factory is _Factory)
foo = protected()
self.assertEqual(getTestProxyItems(foo), [('bar', 'testing')])
class Test_securityAdapterFactory(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.security import securityAdapterFactory
return securityAdapterFactory(*args, **kw)
def test_no_permission_untrusted_no_location(self):
class _Factory(object):
pass
self.assertTrue(self._callFUT(_Factory, None, False, False)
is _Factory)
def test_public_untrusted_no_location(self):
class _Factory(object):
pass
self.assertTrue(self._callFUT(_Factory, 'zope.Public', False, False)
is _Factory)
def test_CheckerPublic_untrusted_no_location(self):
from zope.security.checker import CheckerPublic
class _Factory(object):
pass
self.assertTrue(self._callFUT(_Factory, CheckerPublic, False, False)
is _Factory)
def test_protected_untrusted_no_location(self):
from zope.security.adapter import LocatingUntrustedAdapterFactory
class _Factory(object):
pass
proxy = self._callFUT(_Factory, 'testing', False, False)
self.assertTrue(isinstance(proxy, LocatingUntrustedAdapterFactory))
def test_no_permission_trusted_no_location(self):
from zope.security.adapter import LocatingTrustedAdapterFactory
class _Factory(object):
pass
proxy = self._callFUT(_Factory, None, False, True)
self.assertTrue(isinstance(proxy, LocatingTrustedAdapterFactory))
def test_public_trusted_no_location(self):
from zope.security.adapter import LocatingTrustedAdapterFactory
class _Factory(object):
pass
proxy = self._callFUT(_Factory, 'zope.Public', False, True)
self.assertTrue(isinstance(proxy, LocatingTrustedAdapterFactory))
def test_CheckerPublic_trusted_no_location(self):
from zope.security.adapter import LocatingTrustedAdapterFactory
from zope.security.checker import CheckerPublic
class _Factory(object):
pass
proxy = self._callFUT(_Factory, CheckerPublic, False, True)
self.assertTrue(isinstance(proxy, LocatingTrustedAdapterFactory))
def test_protected_trusted_no_location(self):
from zope.security.adapter import LocatingTrustedAdapterFactory
class _Factory(object):
pass
proxy = self._callFUT(_Factory, 'testing', False, True)
self.assertTrue(isinstance(proxy, LocatingTrustedAdapterFactory))
def test_protected_trusted_w_location(self):
from zope.security.adapter import LocatingTrustedAdapterFactory
class _Factory(object):
pass
proxy = self._callFUT(_Factory, 'testing', True, True)
self.assertTrue(isinstance(proxy, LocatingTrustedAdapterFactory))
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(PermissionProxyTests),
unittest.makeSuite(Test__checker),
unittest.makeSuite(Test_proxify),
unittest.makeSuite(Test_protectedFactory),
unittest.makeSuite(Test_securityAdapterFactory),
))
zope.component-4.0.2/src/zope/component/tests/test_interface.py 0000664 0001750 0001750 00000034231 11774312422 024670 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
"""Tests for z.c.interface
"""
import unittest
class Test_provideInterface(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.interface import provideInterface
return provideInterface(*args, **kw)
def test_w_interface_not_IInterface(self):
self.assertRaises(TypeError, self._callFUT, 'xxx', object())
def test_w_iface_type_not_IInterface(self):
from zope.interface import Interface
from zope.interface.interface import InterfaceClass
class IFoo(Interface):
pass
IBar = InterfaceClass('IBar')
self.assertRaises(TypeError, self._callFUT, 'xxx', IFoo, IBar)
def test_w_class(self):
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IBar(IInterface):
pass
class Foo(object):
pass
self._callFUT('', Foo, IBar)
self.assertFalse(IBar.providedBy(Foo))
self.assertEqual(len(list(gsm.getUtilitiesFor(IBar))), 0)
def test_wo_name_w_iface_type(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
class IBar(IInterface):
pass
self._callFUT('', IFoo, IBar)
self.assertTrue(IBar.providedBy(IFoo))
nm = 'zope.component.tests.test_interface.IFoo'
self.assertTrue(gsm.getUtility(IBar, nm) is IFoo)
def test_w_name_wo_ifact_type(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
self._callFUT('foo', IFoo)
self.assertTrue(IInterface.providedBy(IFoo))
registered = gsm.getUtility(IInterface, name='foo')
self.assertTrue(registered is IFoo)
class Test_getInterface(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.interface import getInterface
return getInterface(*args, **kw)
def test_miss(self):
from zope.component.interfaces import ComponentLookupError
self.assertRaises(ComponentLookupError,
self._callFUT, object(), 'nonesuch')
def test_hit(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
self.assertTrue(self._callFUT(object(), 'foo') is IFoo)
class Test_queryInterface(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.interface import queryInterface
return queryInterface(*args, **kw)
def test_miss(self):
_DEFAULT = object()
self.assertTrue(
self._callFUT('nonesuch', default=_DEFAULT) is _DEFAULT)
def test_hit(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
self.assertTrue(self._callFUT('foo') is IFoo)
class Test_searchInterface(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.interface import searchInterface
return searchInterface(*args, **kw)
def test_empty(self):
self.assertEqual(self._callFUT(object()), [])
def test_no_search_string_no_base(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
self.assertEqual(self._callFUT(object()), [IFoo])
def test_w_search_string_no_base(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
class IBar(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
gsm.registerUtility(IBar, IInterface, 'bar')
self.assertEqual(self._callFUT(object(), 'IFoo'), [IFoo])
def test_no_search_string_w_base(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IBase(Interface):
pass
class IFoo(IBase):
pass
class IBar(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
gsm.registerUtility(IBar, IInterface, 'bar')
self.assertEqual(self._callFUT(object(), base=IBase), [IFoo])
class Test_searchInterfaceIds(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.interface import searchInterfaceIds
return searchInterfaceIds(*args, **kw)
def test_empty(self):
self.assertEqual(self._callFUT(object()), [])
def test_no_search_string_no_base(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
self.assertEqual(self._callFUT(object()), ['foo'])
def test_w_search_string_no_base(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
class IBar(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
gsm.registerUtility(IBar, IInterface, 'bar')
self.assertEqual(self._callFUT(object(), 'IFoo'), ['foo'])
def test_no_search_string_w_base(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IBase(Interface):
pass
class IFoo(IBase):
pass
class IBar(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
gsm.registerUtility(IBar, IInterface, 'bar')
self.assertEqual(self._callFUT(object(), base=IBase), ['foo'])
class Test_searchInterfaceUtilities(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.interface import searchInterfaceUtilities
return searchInterfaceUtilities(*args, **kw)
def test_empty(self):
self.assertEqual(self._callFUT(object()), [])
def test_no_search_string_no_base(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
self.assertEqual(self._callFUT(object()), [('foo', IFoo)])
def test_w_search_string_no_base(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
class IBar(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
gsm.registerUtility(IBar, IInterface, 'bar')
self.assertEqual(self._callFUT(object(), 'IFoo'), [('foo', IFoo)])
def test_no_search_string_w_base(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IBase(Interface):
pass
class IFoo(IBase):
pass
class IBar(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
gsm.registerUtility(IBar, IInterface, 'bar')
self.assertEqual(self._callFUT(object(), base=IBase), [('foo', IFoo)])
def test_no_search_string_w_base_is_same(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
class IBar(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
gsm.registerUtility(IBar, IInterface, 'bar')
self.assertEqual(self._callFUT(object(), base=IFoo), [('foo', IFoo)])
class Test_getInterfaceAllDocs(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.interface import getInterfaceAllDocs
return getInterfaceAllDocs(*args, **kw)
def test_w_class(self):
class Foo(object):
"""DOCSTRING"""
bar = None
def baz(self):
"""BAZ"""
self.assertEqual(self._callFUT(Foo),
'zope.component.tests.test_interface.foo\n' +
'docstring')
def test_w_interface_no_members(self):
from zope.interface import Interface
class IFoo(Interface):
"""DOCSTRING"""
self.assertEqual(self._callFUT(IFoo),
'zope.component.tests.test_interface.ifoo\n' +
'docstring')
def test_w_interface_w_members(self):
from zope.interface import Attribute
from zope.interface import Interface
class IFoo(Interface):
"""DOCSTRING"""
bar = Attribute('bar', 'Do bar')
def baz(self):
"""BAZ"""
self.assertEqual(self._callFUT(IFoo),
'zope.component.tests.test_interface.ifoo\n' +
'docstring\n' +
'do bar\n' +
'baz')
class Test_nameToInterface(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.interface import nameToInterface
return nameToInterface(*args, **kw)
def test_w_None(self):
self.assertTrue(self._callFUT(object(), 'None') is None)
def test_miss(self):
from zope.component.interfaces import ComponentLookupError
self.assertRaises(ComponentLookupError,
self._callFUT, object(), 'nonesuch')
def test_hit(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
found = self._callFUT(object(), 'foo')
self.assertTrue(found is IFoo)
class Test_interfaceToName(unittest.TestCase):
from zope.component.testing import setUp, tearDown
def _callFUT(self, *args, **kw):
from zope.component.interface import interfaceToName
return interfaceToName(*args, **kw)
def test_w_None(self):
self.assertEqual(self._callFUT(object(), None), 'None')
def test_w_unregistered(self):
from zope.interface import Interface
class IFoo(Interface):
pass
self.assertEqual(self._callFUT(object(), IFoo),
'zope.component.tests.test_interface.IFoo')
def test_w_registered(self):
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
gsm = getGlobalSiteManager()
class IFoo(Interface):
pass
gsm.registerUtility(IFoo, IInterface, 'foo')
self.assertEqual(self._callFUT(object(), IFoo),
'zope.component.tests.test_interface.IFoo')
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test_provideInterface),
unittest.makeSuite(Test_getInterface),
unittest.makeSuite(Test_queryInterface),
unittest.makeSuite(Test_searchInterface),
unittest.makeSuite(Test_searchInterfaceIds),
unittest.makeSuite(Test_searchInterfaceUtilities),
unittest.makeSuite(Test_getInterfaceAllDocs),
unittest.makeSuite(Test_nameToInterface),
unittest.makeSuite(Test_interfaceToName),
))
zope.component-4.0.2/src/zope/component/tests/test_zcml.py 0000664 0001750 0001750 00000136335 11774312422 023705 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2012 Zope Foundation 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.
#
##############################################################################
"""Tests for ZCML directives.
"""
import unittest
def skipIfNoSecurity(testfunc):
try:
import zope.security
except ImportError:
return lambda self: None
return testfunc
class Test_handler(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.zcml import handler
return handler(*args, **kw)
def test_uses_configured_site_manager(self):
from zope.interface.registry import Components
from zope.component import getSiteManager
from zope.component.testfiles.components import comp, IApp
from zope.component._compat import _BLANK
registry = Components()
def dummy(context=None):
return registry
getSiteManager.sethook(dummy)
try:
self._callFUT('registerUtility', comp, IApp, _BLANK)
self.assertTrue(registry.getUtility(IApp) is comp)
finally:
getSiteManager.reset()
class Test__rolledUpFactory(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.zcml import _rolledUpFactory
return _rolledUpFactory(*args, **kw)
def test_with_one(self):
_OBJ = object()
_CREATED = object()
def _factory(obj):
return _CREATED
rolled = self._callFUT([_factory])
self.assertTrue(rolled.factory is _factory)
self.assertTrue(rolled(_OBJ) is _CREATED)
def test_with_multiple(self):
_OBJ = object()
_CREATED1 = object()
_CREATED2 = object()
_CREATED3 = object()
def _factory1(obj):
return _CREATED1
def _factory2(obj):
return _CREATED2
def _factory3(obj):
return _CREATED3
rolled = self._callFUT([_factory1, _factory2, _factory3])
self.assertTrue(rolled.factory is _factory1)
self.assertTrue(rolled(_OBJ) is _CREATED3)
class Test_adapter(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.zcml import adapter
return adapter(*args, **kw)
def test_empty_factory(self):
from zope.interface import Interface
from zope.component.zcml import ComponentConfigurationError
class IFoo(Interface):
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(ComponentConfigurationError,
self._callFUT, _cfg_ctx, [], [Interface], IFoo)
def test_multiple_factory_multiple_for_(self):
from zope.interface import Interface
from zope.component.zcml import ComponentConfigurationError
class IFoo(Interface):
pass
class IBar(Interface):
pass
class Foo(object):
pass
class Bar(object):
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(ComponentConfigurationError,
self._callFUT, _cfg_ctx, [Foo, Bar],
[Interface, IBar], IFoo)
def test_no_for__factory_not_adapts(self):
#@adapter(IFoo)
class _Factory(object):
def __init__(self, context):
self.context = context
_cfg_ctx = _makeConfigContext()
self.assertRaises(TypeError, self._callFUT, _cfg_ctx, [_Factory])
def test_no_for__factory_adapts_no_provides_factory_not_implements(self):
from zope.interface import Interface
from zope.component._declaration import adapter
@adapter(Interface)
class _Factory(object):
def __init__(self, context):
self.context = context
_cfg_ctx = _makeConfigContext()
self.assertRaises(TypeError, self._callFUT, _cfg_ctx, [_Factory])
def test_multiple_factory_single_for__w_name(self):
from zope.interface import Interface
from zope.component.interface import provideInterface
from zope.component.zcml import handler
class IFoo(Interface):
pass
class Foo(object):
pass
class Bar(object):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, [Foo, Bar], IFoo, [Interface], name='test')
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('adapter', (Interface,), IFoo, 'test'))
self.assertEqual(action['args'][0], 'registerAdapter')
self.assertEqual(action['args'][1].factory, Foo) #rolled up
self.assertEqual(action['args'][2], (Interface,))
self.assertEqual(action['args'][3], IFoo)
self.assertEqual(action['args'][4], 'test')
self.assertEqual(action['args'][5], 'TESTING')
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo))
# Register the required interface(s)
self.assertEqual(_cfg_ctx._actions[2][0], ())
action =_cfg_ctx._actions[2][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', Interface))
@skipIfNoSecurity
def test_single_factory_single_for_w_permission(self):
from zope.interface import Interface
from zope.security.adapter import LocatingUntrustedAdapterFactory
from zope.component.zcml import handler
class IFoo(Interface):
pass
class Foo(object):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, [Foo], IFoo, [Interface], permission='testing')
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('adapter', (Interface,), IFoo, ''))
self.assertEqual(action['args'][0], 'registerAdapter')
factory_proxy = action['args'][1]
# Foo wraped by 'protected_factory' plus
# 'LocatingUntrustedAdapterFactory'
self.assertTrue(isinstance(factory_proxy,
LocatingUntrustedAdapterFactory))
self.assertTrue(factory_proxy.factory.factory is Foo)
self.assertEqual(action['args'][2], (Interface,))
self.assertEqual(action['args'][3], IFoo)
self.assertEqual(action['args'][4], '')
self.assertEqual(action['args'][5], 'TESTING')
@skipIfNoSecurity
def test_single_factory_single_for_w_locate_no_permission(self):
from zope.interface import Interface
from zope.security.adapter import LocatingUntrustedAdapterFactory
from zope.component.zcml import handler
class IFoo(Interface):
pass
class Foo(object):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, [Foo], IFoo, [Interface], locate=True)
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('adapter', (Interface,), IFoo, ''))
self.assertEqual(action['args'][0], 'registerAdapter')
factory_proxy = action['args'][1]
# Foo wraped by 'LocatingUntrustedAdapterFactory'
self.assertTrue(isinstance(factory_proxy,
LocatingUntrustedAdapterFactory))
self.assertTrue(factory_proxy.factory is Foo)
self.assertEqual(action['args'][2], (Interface,))
self.assertEqual(action['args'][3], IFoo)
self.assertEqual(action['args'][4], '')
self.assertEqual(action['args'][5], 'TESTING')
@skipIfNoSecurity
def test_single_factory_single_for_w_trusted_no_permission(self):
from zope.interface import Interface
from zope.security.adapter import TrustedAdapterFactory
from zope.component.zcml import handler
class IFoo(Interface):
pass
class Foo(object):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, [Foo], IFoo, [Interface], trusted=True)
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('adapter', (Interface,), IFoo, ''))
self.assertEqual(action['args'][0], 'registerAdapter')
factory_proxy = action['args'][1]
# Foo wraped by 'LocatingUntrustedAdapterFactory'
self.assertTrue(isinstance(factory_proxy, TrustedAdapterFactory))
self.assertTrue(factory_proxy.factory is Foo)
self.assertEqual(action['args'][2], (Interface,))
self.assertEqual(action['args'][3], IFoo)
self.assertEqual(action['args'][4], '')
self.assertEqual(action['args'][5], 'TESTING')
def test_no_for__no_provides_factory_adapts_factory_implements(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component._declaration import adapter
from zope.component.zcml import handler
class IFoo(Interface):
pass
@adapter(Interface)
@implementer(IFoo)
class _Factory(object):
def __init__(self, context):
self.context = context
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, [_Factory])
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('adapter', (Interface,), IFoo, ''))
self.assertEqual(action['args'],
('registerAdapter', _Factory, (Interface,), IFoo,
'', 'TESTING'))
class Test_subscriber(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.zcml import subscriber
return subscriber(*args, **kw)
def test_no_factory_no_handler(self):
from zope.interface import Interface
_cfg_ctx = _makeConfigContext()
self.assertRaises(TypeError,
self._callFUT, _cfg_ctx, (Interface,))
def test_no_factory_w_handler_w_provides(self):
from zope.interface import Interface
class IFoo(Interface):
pass
def _handler(*args):
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(TypeError,
self._callFUT, _cfg_ctx, (Interface,),
handler=_handler, provides=IFoo)
def test_w_factory_w_handler(self):
from zope.interface import Interface
class Foo(object):
pass
def _handler(*args):
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(TypeError,
self._callFUT, _cfg_ctx, (Interface,), Foo,
handler=_handler)
def test_w_factory_no_provides(self):
from zope.interface import Interface
class Foo(object):
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(TypeError,
self._callFUT, _cfg_ctx, (Interface,), Foo)
def test_w_factory_w_provides_no_for_factory_wo_adapter(self):
from zope.interface import Interface
class IFoo(Interface):
pass
class Foo(object):
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(TypeError,
self._callFUT, _cfg_ctx,
factory=Foo, provides=IFoo)
def test_no_factory_w_handler_no_provides(self):
from zope.interface import Interface
from zope.component.interface import provideInterface
from zope.component.zcml import handler
def _handler(*args):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, (Interface,), handler=_handler)
self.assertEqual(len(_cfg_ctx._actions), 2)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'][0], 'registerHandler')
self.assertEqual(action['args'][1], _handler)
self.assertEqual(action['args'][2], (Interface,))
self.assertEqual(action['args'][3], '')
self.assertEqual(action['args'][4], 'TESTING')
# Register the required interface(s)
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', Interface))
def test_w_factory_w_provides(self):
from zope.interface import Interface
from zope.component.interface import provideInterface
from zope.component.zcml import handler
class IFoo(Interface):
pass
class Foo(object):
pass
def _handler(*args):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, (Interface,), Foo, provides=IFoo)
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'][0], 'registerSubscriptionAdapter')
self.assertEqual(action['args'][1], Foo)
self.assertEqual(action['args'][2], (Interface,))
self.assertEqual(action['args'][3], IFoo)
self.assertEqual(action['args'][4], '')
self.assertEqual(action['args'][5], 'TESTING')
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo))
# Register the required interface(s)
self.assertEqual(_cfg_ctx._actions[2][0], ())
action =_cfg_ctx._actions[2][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', Interface))
@skipIfNoSecurity
def test_w_factory_w_provides_w_permission(self):
from zope.interface import Interface
from zope.security.adapter import LocatingUntrustedAdapterFactory
from zope.component.interface import provideInterface
from zope.component.zcml import handler
class IFoo(Interface):
pass
class Foo(object):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, (Interface,), Foo,
provides=IFoo, permission='testing')
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'][0], 'registerSubscriptionAdapter')
factory_proxy = action['args'][1]
# Foo wraped by 'protected_factory' plus
# 'LocatingUntrustedAdapterFactory'
self.assertTrue(isinstance(factory_proxy,
LocatingUntrustedAdapterFactory))
self.assertTrue(factory_proxy.factory.factory is Foo)
self.assertEqual(action['args'][2], (Interface,))
self.assertEqual(action['args'][3], IFoo)
self.assertEqual(action['args'][4], '')
self.assertEqual(action['args'][5], 'TESTING')
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo))
# Register the required interface(s)
self.assertEqual(_cfg_ctx._actions[2][0], ())
action =_cfg_ctx._actions[2][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', Interface))
@skipIfNoSecurity
def test_w_factory_w_provides_wo_permission_w_locate(self):
from zope.interface import Interface
from zope.security.adapter import LocatingUntrustedAdapterFactory
from zope.component.interface import provideInterface
from zope.component.zcml import handler
class IFoo(Interface):
pass
class Foo(object):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, (Interface,), Foo, provides=IFoo, locate=True)
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'][0], 'registerSubscriptionAdapter')
factory_proxy = action['args'][1]
# Foo wraped by 'protected_factory' plus
# 'LocatingUntrustedAdapterFactory'
self.assertTrue(isinstance(factory_proxy,
LocatingUntrustedAdapterFactory))
self.assertTrue(factory_proxy.factory is Foo)
self.assertEqual(action['args'][2], (Interface,))
self.assertEqual(action['args'][3], IFoo)
self.assertEqual(action['args'][4], '')
self.assertEqual(action['args'][5], 'TESTING')
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo))
# Register the required interface(s)
self.assertEqual(_cfg_ctx._actions[2][0], ())
action =_cfg_ctx._actions[2][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', Interface))
@skipIfNoSecurity
def test_w_factory_w_provides_wo_permission_w_trusted(self):
from zope.interface import Interface
from zope.security.adapter import TrustedAdapterFactory
from zope.component.interface import provideInterface
from zope.component.zcml import handler
class IFoo(Interface):
pass
class Foo(object):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, (Interface,), Foo, provides=IFoo, trusted=True)
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'][0], 'registerSubscriptionAdapter')
factory_proxy = action['args'][1]
# Foo wraped by 'protected_factory' plus
# 'TrustedAdapterFactory'
self.assertTrue(isinstance(factory_proxy,
TrustedAdapterFactory))
self.assertTrue(factory_proxy.factory is Foo)
self.assertEqual(action['args'][2], (Interface,))
self.assertEqual(action['args'][3], IFoo)
self.assertEqual(action['args'][4], '')
self.assertEqual(action['args'][5], 'TESTING')
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo))
# Register the required interface(s)
self.assertEqual(_cfg_ctx._actions[2][0], ())
action =_cfg_ctx._actions[2][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', Interface))
class Test_utility(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.zcml import utility
return utility(*args, **kw)
def test_w_factory_w_component(self):
class _Factory(object):
pass
_COMPONENT = object
_cfg_ctx = _makeConfigContext()
self.assertRaises(TypeError, self._callFUT, _cfg_ctx,
factory=_Factory,
component=_COMPONENT)
def test_w_factory_wo_provides_factory_no_implements(self):
class _Factory(object):
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(TypeError,
self._callFUT, _cfg_ctx, factory=_Factory)
def test_w_component_wo_provides_component_no_provides(self):
_COMPONENT = object
_cfg_ctx = _makeConfigContext()
self.assertRaises(TypeError,
self._callFUT, _cfg_ctx, component=_COMPONENT)
def test_w_factory_w_provides(self):
from zope.interface import Interface
from zope.component.interface import provideInterface
from zope.component.zcml import handler
class IFoo(Interface):
pass
class Foo(object):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, factory=Foo, provides=IFoo)
self.assertEqual(len(_cfg_ctx._actions), 2)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the utility
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'], ('utility', IFoo, ''))
self.assertEqual(action['args'][0], 'registerUtility')
self.assertEqual(action['args'][1], None)
self.assertEqual(action['args'][2], IFoo)
self.assertEqual(action['args'][3], '')
self.assertEqual(action['args'][4], 'TESTING')
self.assertEqual(action['kw'], {'factory': Foo})
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo))
def test_w_factory_wo_provides_factory_implements(self):
from zope.interface import Interface
from zope.interface import implementer
from zope.component.interface import provideInterface
from zope.component.zcml import handler
class IFoo(Interface):
pass
@implementer(IFoo)
class Foo(object):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, factory=Foo)
self.assertEqual(len(_cfg_ctx._actions), 2)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the utility
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'], ('utility', IFoo, ''))
self.assertEqual(action['args'][0], 'registerUtility')
self.assertEqual(action['args'][1], None)
self.assertEqual(action['args'][2], IFoo)
self.assertEqual(action['args'][3], '')
self.assertEqual(action['args'][4], 'TESTING')
self.assertEqual(action['kw'], {'factory': Foo})
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo))
def test_w_component_w_provides_w_naem(self):
from zope.interface import Interface
from zope.component.interface import provideInterface
from zope.component.zcml import handler
class IFoo(Interface):
pass
_COMPONENT = object()
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, component=_COMPONENT,
name='test', provides=IFoo)
self.assertEqual(len(_cfg_ctx._actions), 2)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the utility
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'], ('utility', IFoo, 'test'))
self.assertEqual(action['args'][0], 'registerUtility')
self.assertEqual(action['args'][1], _COMPONENT)
self.assertEqual(action['args'][2], IFoo)
self.assertEqual(action['args'][3], 'test')
self.assertEqual(action['args'][4], 'TESTING')
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo))
def test_w_component_wo_provides_component_provides(self):
from zope.interface import Interface
from zope.interface import directlyProvides
from zope.component.interface import provideInterface
from zope.component.zcml import handler
class IFoo(Interface):
pass
class Foo(object):
pass
_COMPONENT = Foo()
directlyProvides(_COMPONENT, IFoo)
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, component=_COMPONENT)
self.assertEqual(len(_cfg_ctx._actions), 2)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the utility
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'], ('utility', IFoo, ''))
self.assertEqual(action['args'][0], 'registerUtility')
self.assertEqual(action['args'][1], _COMPONENT)
self.assertEqual(action['args'][2], IFoo)
self.assertEqual(action['args'][3], '')
self.assertEqual(action['args'][4], 'TESTING')
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo))
@skipIfNoSecurity
def test_w_component_w_provides_w_permission(self):
from zope.interface import Interface
from zope.proxy import removeAllProxies
from zope.component.interface import provideInterface
from zope.component.security import PermissionProxy
from zope.component.zcml import handler
class IFoo(Interface):
def bar(self):
pass
class Foo(object):
def bar(self):
pass
_COMPONENT = Foo()
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, component=_COMPONENT,
provides=IFoo, permission='testing')
self.assertEqual(len(_cfg_ctx._actions), 2)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the utility
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'], ('utility', IFoo, ''))
self.assertEqual(action['args'][0], 'registerUtility')
component_proxy = action['args'][1]
self.assertTrue(isinstance(component_proxy, PermissionProxy))
self.assertTrue(removeAllProxies(component_proxy) is _COMPONENT)
self.assertEqual(component_proxy.__Security_checker__.get_permissions,
{'bar': 'testing'})
self.assertEqual(action['args'][2], IFoo)
self.assertEqual(action['args'][3], '')
self.assertEqual(action['args'][4], 'TESTING')
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo))
class Test_interface(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.zcml import interface
return interface(*args, **kw)
def test_wo_name_wo_type(self):
from zope.interface import Interface
from zope.component.interface import provideInterface
class IFoo(Interface):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, IFoo)
self.assertEqual(len(_cfg_ctx._actions), 1)
self.assertEqual(_cfg_ctx._actions[0][0], ())
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IFoo, None))
def test_w_name_w_type(self):
from zope.interface import Interface
from zope.component.interface import provideInterface
class IFoo(Interface):
pass
class IBar(Interface):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, IFoo, name='foo', type=IBar)
self.assertEqual(len(_cfg_ctx._actions), 1)
self.assertEqual(_cfg_ctx._actions[0][0], ())
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('foo', IFoo, IBar))
class Test_view(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.zcml import view
return view(*args, **kw)
def test_w_allowed_interface_wo_permission(self):
from zope.interface import Interface
from zope.component.zcml import ComponentConfigurationError
class IViewType(Interface):
pass
class IView(Interface):
def foo():
pass
def bar():
pass
class _View(object):
def __init__(self, context):
self.context = context
def foo():
pass
def bar():
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(ComponentConfigurationError,
self._callFUT, _cfg_ctx, (_View,), IViewType, '',
for_=(Interface, Interface),
allowed_interface=IView)
def test_w_allowed_attributes_wo_permission(self):
from zope.interface import Interface
from zope.component.zcml import ComponentConfigurationError
class IViewType(Interface):
pass
class _View(object):
def __init__(self, context):
self.context = context
def foo():
pass
def bar():
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(ComponentConfigurationError,
self._callFUT, _cfg_ctx, (_View,), IViewType, '',
for_=(Interface, Interface),
allowed_attributes=('foo', 'bar'))
def test_w_factory_as_empty(self):
from zope.interface import Interface
from zope.component.zcml import ComponentConfigurationError
class IViewType(Interface):
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(ComponentConfigurationError,
self._callFUT, _cfg_ctx, (), IViewType, '',
for_=(Interface, Interface))
def test_w_multiple_factory_multiple_for_(self):
from zope.interface import Interface
from zope.component.zcml import ComponentConfigurationError
class IViewType(Interface):
pass
class Foo(object):
pass
class Bar(object):
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(ComponentConfigurationError,
self._callFUT, _cfg_ctx, (Foo, Bar), IViewType, '',
for_=(Interface, Interface))
def test_w_for__as_empty(self):
from zope.interface import Interface
from zope.component.zcml import ComponentConfigurationError
class IViewType(Interface):
pass
class _View(object):
def __init__(self, context):
self.context = context
_cfg_ctx = _makeConfigContext()
self.assertRaises(ComponentConfigurationError,
self._callFUT, _cfg_ctx, (_View,), IViewType, '',
for_=())
def test_w_single_factory_single_for__wo_permission_w_name(self):
from zope.interface import Interface
from zope.component.zcml import handler
from zope.component.interface import provideInterface
class IViewType(Interface):
pass
class _View(object):
def __init__(self, context):
self.context = context
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, (_View,), IViewType, 'test', for_=(Interface,))
self.assertEqual(len(_cfg_ctx._actions), 4)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('view', (Interface, IViewType), 'test', Interface))
self.assertEqual(action['args'][0], 'registerAdapter')
self.assertEqual(action['args'][1], _View)
self.assertEqual(action['args'][2], (Interface, IViewType))
self.assertEqual(action['args'][3], Interface)
self.assertEqual(action['args'][4], 'test')
self.assertEqual(action['args'][5], 'TESTING')
# Register the provided interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', Interface))
# Register the required interface(s)
self.assertEqual(_cfg_ctx._actions[2][0], ())
action =_cfg_ctx._actions[2][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', Interface))
self.assertEqual(_cfg_ctx._actions[3][0], ())
action =_cfg_ctx._actions[3][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IViewType))
def test_w_multiple_factory_single_for__wo_permission(self):
from zope.interface import Interface
from zope.component.zcml import handler
class IViewType(Interface):
pass
class _View(object):
def __init__(self, context):
self.context = context
class _View2(object):
def __init__(self, context, request):
self.context = context
self.request = request
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, [_View, _View2], IViewType, '',
for_=(Interface,))
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('view', (Interface, IViewType), '', Interface))
self.assertEqual(action['args'][0], 'registerAdapter')
factory = action['args'][1]
self.assertTrue(factory.factory is _View)
context = object()
request = object()
view = factory(context, request)
self.assertTrue(isinstance(view, _View2))
self.assertTrue(view.request is request)
self.assertTrue(isinstance(view.context, _View))
self.assertTrue(view.context.context is context)
self.assertEqual(action['args'][2], (Interface, IViewType))
self.assertEqual(action['args'][3], Interface)
self.assertEqual(action['args'][4], '')
self.assertEqual(action['args'][5], 'TESTING')
@skipIfNoSecurity
def test_w_single_factory_single_for__w_permission(self):
from zope.interface import Interface
from zope.component.zcml import handler
class IViewType(Interface):
pass
class _View(object):
def __init__(self, context, request):
self.context = context
self.request = request
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, [_View], IViewType, '', for_=(Interface,),
permission='testing')
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('view', (Interface, IViewType), '', Interface))
self.assertEqual(action['args'][0], 'registerAdapter')
factory = action['args'][1]
context = object()
request = object()
view = factory(context, request)
self.assertTrue(view.context is context)
self.assertTrue(view.request is request)
self.assertTrue(factory.factory is _View)
self.assertEqual(action['args'][2], (Interface, IViewType))
self.assertEqual(action['args'][3], Interface)
self.assertEqual(action['args'][4], '')
self.assertEqual(action['args'][5], 'TESTING')
@skipIfNoSecurity
def test_w_single_factory_single_for__w_permission_and_allowed_attrs(self):
from zope.interface import Interface
from zope.component.zcml import handler
class IViewType(Interface):
pass
class _View(object):
def __init__(self, context, request):
self.context = context
self.request = request
def bar(self):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, [_View], IViewType, '', for_=(Interface,),
permission='testing', allowed_attributes=('bar',))
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('view', (Interface, IViewType), '', Interface))
self.assertEqual(action['args'][0], 'registerAdapter')
factory = action['args'][1]
checker = factory.checker
self.assertEqual(checker.get_permissions, {'bar': 'testing'})
@skipIfNoSecurity
def test_w_single_factory_single_for__w_permission_and_allowed_iface(self):
from zope.interface import Interface
from zope.component.zcml import handler
class IViewType(Interface):
def bar(self):
pass
class _View(object):
def __init__(self, context, request):
self.context = context
self.request = request
def bar(self):
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, [_View], IViewType, '', for_=(Interface,),
permission='testing', allowed_interface=(IViewType,))
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the adapter
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('view', (Interface, IViewType), '', Interface))
self.assertEqual(action['args'][0], 'registerAdapter')
factory = action['args'][1]
checker = factory.checker
self.assertEqual(checker.get_permissions, {'bar': 'testing'})
class Test_resource(unittest.TestCase):
def _callFUT(self, *args, **kw):
from zope.component.zcml import resource
return resource(*args, **kw)
def test_w_allowed_interface_wo_permission(self):
from zope.interface import Interface
from zope.component.zcml import ComponentConfigurationError
class IResourceType(Interface):
pass
class IView(Interface):
def foo():
pass
def bar():
pass
class _Resource(object):
def __init__(self, context):
self.context = context
def foo():
pass
def bar():
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(ComponentConfigurationError,
self._callFUT,
_cfg_ctx, (_Resource,), IResourceType, '',
allowed_interface=IView)
def test_w_allowed_attributes_wo_permission(self):
from zope.interface import Interface
from zope.component.zcml import ComponentConfigurationError
class IResourceType(Interface):
pass
class _Resource(object):
def __init__(self, context):
self.context = context
def foo():
pass
def bar():
pass
_cfg_ctx = _makeConfigContext()
self.assertRaises(ComponentConfigurationError,
self._callFUT,
_cfg_ctx, (_Resource,), IResourceType, '',
allowed_attributes=('foo', 'bar'))
def test_wo_permission_w_name(self):
from zope.interface import Interface
from zope.component.interface import provideInterface
from zope.component.zcml import handler
class IResourceType(Interface):
pass
class _Resource(object):
def __init__(self, context):
self.context = context
def foo():
pass
def bar():
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, _Resource, IResourceType, 'test')
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the resource
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('resource', 'test', IResourceType, Interface))
self.assertEqual(action['args'][0], 'registerAdapter')
self.assertEqual(action['args'][1], _Resource)
self.assertEqual(action['args'][2], (IResourceType,))
self.assertEqual(action['args'][3], Interface)
self.assertEqual(action['args'][4], 'test')
self.assertEqual(action['args'][5], 'TESTING')
# Register the 'type' interface
self.assertEqual(_cfg_ctx._actions[1][0], ())
action =_cfg_ctx._actions[1][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', IResourceType))
# Register the required interface(s)
self.assertEqual(_cfg_ctx._actions[2][0], ())
action =_cfg_ctx._actions[2][1]
self.assertEqual(action['callable'], provideInterface)
self.assertEqual(action['discriminator'], None)
self.assertEqual(action['args'], ('', Interface))
@skipIfNoSecurity
def test_w_permission(self):
from zope.interface import Interface
from zope.component.zcml import handler
class IResourceType(Interface):
pass
class _Resource(object):
def __init__(self, context):
self.context = context
def foo():
pass
def bar():
pass
_cfg_ctx = _makeConfigContext()
self._callFUT(_cfg_ctx, _Resource, IResourceType, 'test',
permission='testing', allowed_attributes=('foo',))
self.assertEqual(len(_cfg_ctx._actions), 3)
self.assertEqual(_cfg_ctx._actions[0][0], ())
# Register the resource
action =_cfg_ctx._actions[0][1]
self.assertEqual(action['callable'], handler)
self.assertEqual(action['discriminator'],
('resource', 'test', IResourceType, Interface))
self.assertEqual(action['args'][0], 'registerAdapter')
factory = action['args'][1]
self.assertTrue(factory.factory is _Resource)
context = object()
resource = factory(context)
checker = resource.__Security_checker__
self.assertEqual(checker.get_permissions, {'foo': 'testing'})
self.assertTrue(resource.context is context)
self.assertEqual(action['args'][2], (IResourceType,))
self.assertEqual(action['args'][3], Interface)
self.assertEqual(action['args'][4], 'test')
self.assertEqual(action['args'][5], 'TESTING')
def _makeConfigContext():
class _Context(object):
info = 'TESTING'
def __init__(self):
self._actions = []
def action(self, *args, **kw):
self._actions.append((args, kw))
return _Context()
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test_handler),
unittest.makeSuite(Test__rolledUpFactory),
unittest.makeSuite(Test_adapter),
unittest.makeSuite(Test_subscriber),
unittest.makeSuite(Test_utility),
unittest.makeSuite(Test_interface),
unittest.makeSuite(Test_view),
unittest.makeSuite(Test_resource),
))
zope.component-4.0.2/src/zope/component/factory.py 0000664 0001750 0001750 00000003334 11774312422 022176 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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
"""
from zope.interface import implementer
from zope.interface import implementedBy
from zope.interface.declarations import Implements
from zope.component.interfaces import IFactory
@implementer(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.
"""
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): #pragma NO COVER
return '<%s for %s>' % (self.__class__.__name__, repr(self._callable))
zope.component-4.0.2/src/zope/component/persistentregistry.py 0000664 0001750 0001750 00000004066 12024145570 024520 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2004 Zope Foundation 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.
#
##############################################################################
"""Persistent component managers
"""
from persistent import Persistent
from persistent.mapping import PersistentMapping
from persistent.list import PersistentList
from zope.interface.adapter import VerifyingAdapterRegistry
from zope.interface.registry import Components
class PersistentAdapterRegistry(VerifyingAdapterRegistry, Persistent):
def changed(self, originally_changed):
if originally_changed is self:
self._p_changed = True
super(PersistentAdapterRegistry, self).changed(originally_changed)
def __getstate__(self):
state = super(PersistentAdapterRegistry, self).__getstate__().copy()
for name in self._delegated:
state.pop(name, 0)
state.pop('ro', None)
return state
def __setstate__(self, state):
bases = state.pop('__bases__', ())
super(PersistentAdapterRegistry, self).__setstate__(state)
self._createLookup()
self.__bases__ = bases
self._v_lookup.changed(self)
class PersistentComponents(Components):
def _init_registries(self):
self.adapters = PersistentAdapterRegistry()
self.utilities = PersistentAdapterRegistry()
def _init_registrations(self):
self._utility_registrations = PersistentMapping()
self._adapter_registrations = PersistentMapping()
self._subscription_registrations = PersistentList()
self._handler_registrations = PersistentList()
zope.component-4.0.2/src/zope/component/configure.zcml 0000664 0001750 0001750 00000000674 11774312422 023031 0 ustar tseaver tseaver
zope.component-4.0.2/src/zope/component/interface.py 0000664 0001750 0001750 00000010374 12053235152 022464 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation 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.
#
##############################################################################
"""Interface utility functions
"""
from zope.interface import alsoProvides
from zope.interface.interfaces import IInterface
from zope.component.globalregistry import getGlobalSiteManager
from zope.component.interfaces import ComponentLookupError
from zope.component._api import queryUtility
from zope.component._compat import CLASS_TYPES
def provideInterface(id, interface, iface_type=None, info=''):
""" Mark 'interface' as a named utilty providing 'iface_type'.
"""
if not id:
id = "%s.%s" % (interface.__module__, interface.__name__)
if not IInterface.providedBy(interface):
if not isinstance(interface, CLASS_TYPES):
raise TypeError(id, "is not an interface or class")
return
if iface_type is not None:
if not iface_type.extends(IInterface):
raise TypeError(iface_type, "is not an interface type")
alsoProvides(interface, iface_type)
else:
iface_type = IInterface
gsm = getGlobalSiteManager()
gsm.registerUtility(interface, iface_type, id, info)
def getInterface(context, id):
"""Return interface or raise ComponentLookupError
"""
iface = queryInterface(id, None)
if iface is None:
raise ComponentLookupError(id)
return iface
def queryInterface(id, default=None):
"""Return an interface or ``None``
"""
return queryUtility(IInterface, id, default)
def searchInterface(context, search_string=None, base=None):
"""Interfaces search
"""
return [iface_util[1] for iface_util in
searchInterfaceUtilities(context, search_string, base)]
def searchInterfaceIds(context, search_string=None, base=None):
"""Interfaces search
"""
return [iface_util[0] for iface_util in
searchInterfaceUtilities(context, search_string, base)]
def searchInterfaceUtilities(context, search_string=None, base=None):
gsm = getGlobalSiteManager()
iface_utilities = gsm.getUtilitiesFor(IInterface)
if search_string:
search_string = search_string.lower()
iface_utilities = [iface_util for iface_util in iface_utilities
if (getInterfaceAllDocs(iface_util[1]).\
find(search_string) >= 0)]
if base:
res = [iface_util for iface_util in iface_utilities
if iface_util[1].isOrExtends(base)]
else:
res = [iface_util for iface_util in iface_utilities]
return res
def getInterfaceAllDocs(interface):
iface_id = '%s.%s' %(interface.__module__, interface.__name__)
docs = [str(iface_id).lower(),
str(interface.__doc__).lower()]
if IInterface.providedBy(interface):
for name in sorted(interface):
docs.append(
str(interface.getDescriptionFor(name).__doc__).lower())
return '\n'.join(docs)
def nameToInterface(context, id):
if id == 'None':
return None
iface = getInterface(context, id)
return iface
def interfaceToName(context, interface):
if interface is None:
return 'None'
# XXX this search is pointless: we are always going to return the
# same value whether or not we find anything.
items = searchInterface(context, base=interface)
ids = [('%s.%s' %(iface.__module__, iface.__name__))
for iface in items
if iface == interface]
if not ids:
# Do not fail badly, instead resort to the standard
# way of getting the interface name, cause not all interfaces
# may be registered as utilities.
return interface.__module__ + '.' + interface.__name__
assert len(ids) == 1, "Ambiguous interface names: %s" % ids
return ids[0]
zope.component-4.0.2/src/zope/component/security.py 0000664 0001750 0001750 00000007051 11774312422 022376 0 ustar tseaver tseaver ##############################################################################
#
# Copyright (c) 2005 Zope Foundation 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.security support for the configuration handlers
"""
from zope.interface import providedBy
from zope.proxy import ProxyBase
from zope.proxy import getProxiedObject
from zope.security.adapter import LocatingTrustedAdapterFactory
from zope.security.adapter import LocatingUntrustedAdapterFactory
from zope.security.adapter import TrustedAdapterFactory
from zope.security.checker import Checker
from zope.security.checker import CheckerPublic
from zope.security.checker import InterfaceChecker
from zope.security.proxy import Proxy
PublicPermission = 'zope.Public'
class PermissionProxy(ProxyBase):
__slots__ = ('__Security_checker__', )
def __providedBy__(self):
return providedBy(getProxiedObject(self))
__providedBy__ = property(__providedBy__)
def _checker(_context, permission, allowed_interface, allowed_attributes):
if (not allowed_attributes) and (not allowed_interface):
allowed_attributes = ["__call__"]
if permission == PublicPermission:
permission = CheckerPublic
require={}
if allowed_attributes:
for name in allowed_attributes:
require[name] = permission
if allowed_interface:
for i in allowed_interface:
for name in i.names(all=True):
require[name] = permission
checker = Checker(require)
return checker
def proxify(ob, checker=None, provides=None, permission=None):
"""Try to get the object proxied with the `checker`, but not too soon
We really don't want to proxy the object unless we need to.
"""
if checker is None:
if provides is None or permission is None:
raise ValueError('Required arguments: '
'checker or both provides and permissions')
if permission == PublicPermission:
permission = CheckerPublic
checker = InterfaceChecker(provides, permission)
ob = PermissionProxy(ob)
ob.__Security_checker__ = checker
return ob
def protectedFactory(original_factory, provides, permission):
if permission == PublicPermission:
permission = CheckerPublic
checker = InterfaceChecker(provides, permission)
# This has to be named 'factory', aparently, so as not to confuse apidoc :(
def factory(*args):
ob = original_factory(*args)
try:
ob.__Security_checker__ = checker
except AttributeError:
ob = Proxy(ob, checker)
return ob
factory.factory = original_factory
return factory
def securityAdapterFactory(factory, permission, locate, trusted):
if permission == PublicPermission:
permission = CheckerPublic
if locate or (permission is not None and permission is not CheckerPublic):
if trusted:
return LocatingTrustedAdapterFactory(factory)
else:
return LocatingUntrustedAdapterFactory(factory)
elif trusted:
return TrustedAdapterFactory(factory)
else:
return factory
zope.component-4.0.2/src/zope/__init__.py 0000664 0001750 0001750 00000000070 11774312422 020256 0 ustar tseaver tseaver __import__('pkg_resources').declare_namespace(__name__)
zope.component-4.0.2/README.txt 0000664 0001750 0001750 00000001024 12024146015 016067 0 ustar tseaver tseaver *****************************
zope.component Package Readme
*****************************
*This package is intended to be independently reusable in any Python
project. It is maintained by the* `Zope Toolkit project `_.
This package represents the core of the Zope Component Architecture.
Together with the 'zope.interface' package, it provides facilities for
defining, registering and looking up components.
Please see http://docs.zope.org/zope.component/ for the documentation.
.. contents::
zope.component-4.0.2/COPYRIGHT.txt 0000664 0001750 0001750 00000000040 11774312422 016507 0 ustar tseaver tseaver Zope Foundation and Contributors zope.component-4.0.2/LICENSE.txt 0000664 0001750 0001750 00000004026 11774312422 016231 0 ustar tseaver tseaver Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zope.component-4.0.2/CHANGES.txt 0000664 0001750 0001750 00000021277 12070352740 016223 0 ustar tseaver tseaver CHANGES
*******
4.0.2 (2012-12-31)
==================
- Fleshed out PyPI Trove classifiers.
4.0.1 (2012-11-21)
==================
- Added support for Python 3.3.
4.0.0 (2012-07-02)
==================
- Added PyPy and Python 3.2 support:
- Security support omitted until ``zope.security`` ported.
- Persistent registry support omitted until ``ZODB`` ported (or
``persistent`` factored out).
- 100% unit test coverage.
- Removed the long-deprecated ``layer`` argument to the
``zope.component.zcml.view`` and ``zope.component.zcml.resource``
ZCML directives.
- Added support for continuous integration using ``tox`` and ``jenkins``.
- Got tests to run using ``setup.py test``.
- Added ``Sphinx`` documentation.
- Added ``setup.py docs`` alias (installs ``Sphinx`` and dependencies).
- Added ``setup.py dev`` alias (runs ``setup.py develop`` plus installs
``nose`` and ``coverage``).
3.12.1 (2012-04-02)
===================
- Wrap ``with site(foo)`` in try/finally (LP768151).
3.12.0 (2011-11-16)
===================
- Add convenience function zope.component.hooks.site (a contextmanager),
so one can write ``with site(foo): ...``.
3.11.0 (2011-09-22)
===================
- Moved code from ``zope.component.registry`` which implements a basic
nonperistent component registry to ``zope.interface.registry``. This code
was moved from ``zope.component`` into ``zope.interface`` to make porting
systems (such as Pyramid) that rely only on a basic component registry to
Python 3 possible without needing to port the entirety of the
``zope.component`` package. Backwards compatibility import shims have been
left behind in ``zope.component``, so this change will not break any
existing code.
- Interfaces moved from ``zope.component.interfaces`` to
``zope.interface.interfaces``: ``ComponentLookupError``, ``Invalid``,
``IObjectEvent``, ``ObjectEvent``, ``IComponentLookup``, ``IRegistration``,
``IUtilityRegistration``, ``IAdapterRegistration``,
``ISubscriptionAdapterRegistration``, ``IHandlerRegistration``,
``IRegistrationEvent``, ``RegistrationEvent``, ``IRegistered``,
``Registered``, ``IUnregistered``, ``Unregistered``,
``IComponentRegistry``, and ``IComponents``. Backwards compatibility shims
left in place.
- Depend on zope.interface >= 3.8.0.
3.10.0 (2010-09-25)
===================
- Got rid of the docs extra and the sphinxdoc recipe.
- Created a "security" extra to move security-related dependencies out of the
"test" extra.
- Use the new zope.testrunner package for tests.
- Added a basic test for the configure.zcml file provided.
3.9.5 (2010-07-09)
==================
- Fix test requirements specification.
3.9.4 (2010-04-30)
==================
- Prefer the standard libraries doctest module to the one from zope.testing.
3.9.3 (2010-03-08)
==================
- The ZCML directives provided by zope.component now register the components in
the registry returned by getSiteManager instead of the global registry. This
allows the hooking of the getSiteManager method before the load of a ZCML
file to register the components in a custom registry.
3.9.2 (2010-01-22)
==================
- Fixed a bug introduced by recent refactoring, where passing
CheckerPublic to securityAdapterFactory wrongly wrapped the factory
into a LocatingUntrustedAdapterFactory.
3.9.1 (2010-01-21)
==================
- The tested testrunner somehow gets influenced by options of the outer
testrunner, such a the -v option. We modified the tests so that it avoids
this.
3.9.0 (2010-01-21)
==================
- Add testlayer support. It is now possible to load a ZCML file within
tests more easily. See zope.component.testlayer.py and
zope.component.testlayer.txt.
3.8.0 (2009-11-16)
==================
- Removed the dependencies on zope.proxy and zope.security from the zcml extra:
zope.component does not hard depend on them anymore; the support for security
proxied components ZCML registrations is enabled only if zope.security and
zope.proxy are available.
- Moved the IPossibleSite and ISite interfaces here from zope.location as they
are dealing with zope.component's concept of a site, but not with location.
- Moved the zope.site.hooks functionality to zope.component.hooks as it isn't
actually dealing with zope.site's concept of a site.
3.7.1 (2009-07-24)
==================
- Fixed a problem, where ``queryNextUtility`` could fail if the context could
not be adapted to a ``IComponentLookup``.
- Fixed 2 related bugs:
When a utility is registered and there was previously a utility
registered for the same interface and name, then the old utility is
unregistered. The 2 bugs related to this:
- There was no ``Unregistered`` for the implicit unregistration. Now
there is.
- The old utility was still held and returned by
getAllUtilitiesRegisteredFor. In other words, it was still
considered registered, eeven though it wasn't. A particularly
negative consequence of this is that the utility is held in memory
or in the database even though it isn't used.
3.7.0 (2009-05-21)
==================
- The HookableTests were not run by the testrunner.
- Add in zope:view and zope:resource implementations into
zope.component.zcml (dependency loaded with zope.component [zcml]).
3.6.0 (2009-03-12)
==================
- IMPORTANT: the interfaces that were defined in the
zope.component.bbb.interfaces and deprecated for years are
now (re)moved. However, some packages, including part of zope
framework were still using those interfaces. They will be adapted
for this change. If you were using some of those interfaces, you
need to adapt your code as well:
- The IView and IDefaultViewName were moved to zope.publisher.interfaces.
- The IResource was moved to zope.app.publisher.interfaces.
- IContextDependent, IPresentation, IPresentationRequest,
IResourceFactory, IViewFactory were removed completely.
If you used IViewFactory in context of zope.app.form, there's now
IWidgetFactory in the zope.app.form.interfaces instead.
- Add getNextUtility/queryNextUtility functions that used to be in zope.site
earlier (and in zope.app.component even more earlier).
- Added a pure-Python 'hookable' implementation, for use when
'zope.hookable' is not present.
- Removed use of 'zope.deferredimport' by breaking import cycles.
- Cleanup package documentation and changelog a bit. Add sphinx-based
documentation building command to the buildout.
- Remove deprecated code.
- Change package's mailing list address to zope-dev at zope.org, because
zope3-dev at zope.org is now retired.
3.5.1 (2008-07-25)
==================
- Fix bug introduced in 3.5.0: no longer supported
interfaces declared in Python and always wanted an explicit provides="..."
attribute. https://bugs.launchpad.net/zope3/+bug/251865
3.5.0 (2008-07-25)
==================
- Support registration of utilities via factories through the component registry
and return factory information in the registration information. This fixes
https://bugs.launchpad.net/zope3/+bug/240631
- Optimized un/registerUtility via storing an optimized data structure for
efficient retrieval of already registered utilities. This avoids looping over
all utilities when registering a new one.
3.4.0 (2007-09-29)
==================
No further changes since 3.4.0a1.
3.4.0a1 (2007-04-22)
====================
Corresponds to zope.component from Zope 3.4.0a1.
- In the Zope 3.3.x series, ``zope.component`` was simplified yet once
more. See http://wiki.zope.org/zope3/LocalComponentManagementSimplification
for the proposal describing the changes.
3.2.0.2 (2006-04-15)
====================
- Fix packaging bug: 'package_dir' must be a *relative* path.
3.2.0.1 (2006-04-14)
====================
- Packaging change: suppress inclusion of 'setup.cfg' in 'sdist' builds.
3.2.0 (2006-01-05)
==================
Corresponds to the verison of the zope.component package shipped as part of
the Zope 3.2.0 release.
- Deprecated services and related APIs. The adapter and utility registries
are now available directly via the site manager's 'adapters' and 'utilities'
attributes, respectively. Services are accessible, but deprecated, and
will be removed in Zope 3.3.
- Deprectaed all presentation-related APIs, including all view-related
API functions. Use the adapter API functions instead.
See http://dev.zope.org/Zope3/ImplementViewsAsAdapters`
- Deprecated 'contextdependent' package: site managers are now looked up
via a thread global, set during URL traversal. The 'context' argument
is now always optional, and should no longer be passed.
3.0.0 (2004-11-07)
==================
Corresponds to the verison of the zope.component package shipped as part of
the Zope X3.0.0 release.
zope.component-4.0.2/docs/ 0000775 0001750 0001750 00000000000 12070353060 015325 5 ustar tseaver tseaver zope.component-4.0.2/docs/configure.rst 0000664 0001750 0001750 00000002034 11774411574 020056 0 ustar tseaver tseaver Package configuration
=====================
.. testsetup::
from zope.component.testing import setUp
setUp()
The ``zope.component`` package provides a ZCML file that configures some basic
event handlers.
.. doctest::
>>> from zope.configuration.xmlconfig import XMLConfig
>>> import zope.component
>>> from zope.component import event
>>> from zope.component import registry
>>> XMLConfig('configure.zcml', zope.component)()
>>> gsm = zope.component.getGlobalSiteManager()
>>> registered = list(gsm.registeredHandlers())
>>> len(registered)
5
>>> handlers = [x.handler for x in registered]
>>> event.objectEventNotify in handlers
True
>>> registry.dispatchUtilityRegistrationEvent in handlers
True
>>> registry.dispatchAdapterRegistrationEvent in handlers
True
>>> registry.dispatchSubscriptionAdapterRegistrationEvent in handlers
True
>>> registry.dispatchHandlerRegistrationEvent in handlers
True
.. testcleanup::
from zope.component.testing import tearDown
tearDown()
zope.component-4.0.2/docs/api.rst 0000664 0001750 0001750 00000000355 11774312422 016642 0 ustar tseaver tseaver :mod:`zope.component` API Reference
===================================
.. toctree::
:maxdepth: 2
api/interfaces
api/sitemanager
api/utility
api/adapter
api/factory
api/interface
api/security
api/persistent
zope.component-4.0.2/docs/make.bat 0000664 0001750 0001750 00000011776 11774312422 016755 0 ustar tseaver tseaver @ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^` where ^ is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\zopeconfiguration.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\zopeconfiguration.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end
zope.component-4.0.2/docs/Makefile 0000664 0001750 0001750 00000012750 11774312422 017001 0 ustar tseaver tseaver # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/zopeconfiguration.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/zopeconfiguration.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/zopeconfiguration"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/zopeconfiguration"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
zope.component-4.0.2/docs/hooks.rst 0000664 0001750 0001750 00000005347 11774312422 017222 0 ustar tseaver tseaver ==============================
The current component registry
==============================
There can be any number of component registries in an application. One of them
is the global component registry, and there is also the concept of a currently
used component registry. Component registries other than the global one are
associated with objects called sites. The ``zope.component.hooks`` module
provides an API to set and access the current site as well as manipulate the
adapter hook associated with it.
As long as we haven't set a site, none is being considered current:
.. doctest::
>>> from zope.component.hooks import getSite
>>> print getSite()
None
We can also ask for the current component registry (aka site manager
historically); it will return the global one if no current site is set:
.. doctest::
>>> from zope.component.hooks import getSiteManager
>>> getSiteManager()
Let's set a site now. A site has to be an object that provides the
``getSiteManager`` method, which is specified by
``zope.component.interfaces.IPossibleSite``:
.. doctest::
>>> from zope.interface.registry import Components
>>> class Site(object):
... def __init__(self):
... self.registry = Components('components')
... def getSiteManager(self):
... return self.registry
>>> from zope.component.hooks import setSite
>>> site1 = Site()
>>> setSite(site1)
After this, the newly set site is considered the currently active one:
.. doctest::
>>> getSite() is site1
True
>>> getSiteManager() is site1.registry
True
If we set another site, that one will be considered current:
.. doctest::
>>> site2 = Site()
>>> site2.registry is not site1.registry
True
>>> setSite(site2)
>>> getSite() is site2
True
>>> getSiteManager() is site2.registry
True
Finally we can unset the site and the global component registry is used again:
.. doctest::
>>> setSite()
>>> print getSite()
None
>>> getSiteManager()
Context manager
===============
There also is a context manager for setting the site, which is especially
useful when writing tests:
.. doctest::
>>> import zope.component.hooks
>>> print getSite()
None
>>> with zope.component.hooks.site(site2):
... getSite() is site2
True
>>> print getSite()
None
The site is properly restored even if the body of the with statement
raises an exception:
.. doctest::
>>> print getSite()
None
>>> with zope.component.hooks.site(site2):
... getSite() is site2
... raise ValueError('An error in the body')
Traceback (most recent call last):
...
ValueError: An error in the body
>>> print getSite()
None
zope.component-4.0.2/docs/socketexample.rst 0000664 0001750 0001750 00000052407 11774312422 020742 0 ustar tseaver tseaver The Zope 3 Component Architecture (Socket Example)
==================================================
The component architecture provides an application framework that provides its
functionality through loosely-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 you 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 initial 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:
.. doctest::
>>> from zope.interface import Interface, implements
>>> class IGermanSocket(Interface):
... pass
>>> class Socket(object):
... def __repr__(self):
... return '' %self.__class__.__name__
>>> class GermanSocket(Socket):
... """German wall socket."""
... implements(IGermanSocket)
and we want to convert it to an US socket
.. doctest::
>>> 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:
.. doctest::
>>> class GermanToUSSocketAdapter(Socket):
... implements(IUSSocket)
... __used_for__ = 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:
.. doctest::
>>> import zope.component
>>> gsm = zope.component.getGlobalSiteManager()
>>> gsm.registerAdapter(GermanToUSSocketAdapter, (IGermanSocket,), IUSSocket)
`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:
.. doctest::
>>> bathroomDE = GermanSocket()
>>> IGermanSocket.providedBy(bathroomDE)
True
You now insert the adapter in the German socket
.. doctest::
>>> bathroomUS = zope.component.getAdapter(bathroomDE, IUSSocket, '')
so that the socket now provides the US version:
.. doctest::
>>> 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:
.. doctest::
>>> 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:
.. doctest::
>>> zope.component.getAdapter(czech, IUSSocket, '') \
... #doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ComponentLookupError: (,
,
'')
or the more graceful way:
.. doctest::
>>> 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:
.. doctest::
>>> class GermanToUSSocketAdapterAndTransformer(object):
... implements(IUSSocket)
... __used_for__ = 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:
.. doctest::
>>> gsm.registerAdapter(GermanToUSSocketAdapter,
... (IGermanSocket,), IUSSocket, 'shaver',)
>>> gsm.registerAdapter(GermanToUSSocketAdapterAndTransformer,
... (IGermanSocket,), IUSSocket, 'dvd')
Now we simply look up the adapters using their labels (called *name*):
.. doctest::
>>> 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
.. doctest::
>>> zope.component.getAdapter(bathroomDE, IUSSocket, 'mp3') \
... #doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ComponentLookupError: (,
,
'mp3')
but you could use the 'dvd' adapter in this case of course. ;)
Sometimes you want to know all adapters that are available. Let's say you want
to know about all the adapters that convert a German to a US socket type:
.. doctest::
>>> sockets = list(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:
.. doctest::
>>> 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:
.. doctest::
>>> class IGrounder(Interface):
... pass
>>> class Grounder(object):
... implements(IGrounder)
... def __repr__(self):
... return ''
Then together they will provided a grounded us socket:
.. doctest::
>>> 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`:
.. doctest::
>>> gsm.registerAdapter(GroundedGermanToUSSocketAdapter,
... (IGermanSocket, IGrounder), IUSGroundedSocket, 'mp3')
Given the grounder
.. doctest::
>>> grounder = Grounder()
and a German socket
.. doctest::
>>> livingroom = GermanSocket()
we can now get a grounded US socket:
.. doctest::
>>> socket = zope.component.getMultiAdapter((livingroom, grounder),
... IUSGroundedSocket, 'mp3')
.. doctest::
>>> 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:
.. doctest::
>>> zope.component.getMultiAdapter((livingroom, grounder),
... IUSGroundedSocket, 'dvd') \
... #doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ComponentLookupError: ((,
),
,
'dvd')
.. doctest::
>>> 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:
.. doctest::
>>> class IFire(Interface):
... pass
>>> class Fire(object):
... implements(IFire)
>>> fire = Fire()
We want to use all available objects to put out the fire:
.. doctest::
>>> 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:
.. doctest::
>>> class PowderExtinguisher(FireExtinguisher):
... pass
>>> gsm.registerSubscriptionAdapter(PowderExtinguisher,
... (IFire,), IFireExtinguisher)
>>> class Blanket(FireExtinguisher):
... pass
>>> gsm.registerSubscriptionAdapter(Blanket, (IFire,), IFireExtinguisher)
>>> class SprinklerSystem(FireExtinguisher):
... pass
>>> gsm.registerSubscriptionAdapter(SprinklerSystem,
... (IFire,), IFireExtinguisher)
Now let use all these things to put out the fire:
.. doctest::
>>> 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:
.. doctest::
>>> 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 contrast 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 Hurricane 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:
.. doctest::
>>> class Generator(object):
... implements(IUSSocket)
... def __repr__(self):
... return ''
>>> generator = Generator()
Like for adapters, we now have to add the newly-acquired generator to our
inventory by registering it as a utility:
.. doctest::
>>> gsm.registerUtility(generator, IUSSocket)
We can now get the utility using
.. doctest::
>>> 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 exist for a particular interface, such as the German socket,
then the lookup fails
.. doctest::
>>> zope.component.getUtility(IGermanSocket)
Traceback (most recent call last):
...
ComponentLookupError: (, '')
or more gracefully when specifying a default value:
.. doctest::
>>> 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:
.. doctest::
>>> class SolarPanel(object):
... implements(IUSSocket)
... def __repr__(self):
... return ''
>>> panel = SolarPanel()
Once it arrives, we add it to our inventory:
.. doctest::
>>> gsm.registerUtility(panel, IUSSocket, 'Solar Panel')
You can now access the solar panel using
.. doctest::
>>> 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
.. doctest::
>>> zope.component.getUtility(IUSSocket, 'Wind Mill')
Traceback (most recent call last):
...
ComponentLookupError: (, 'Wind Mill')
or more gracefully when specifying a default value:
.. doctest::
>>> 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:
.. doctest::
>>> utils = list(zope.component.getUtilitiesFor(IUSSocket))
>>> utils.sort()
>>> utils #doctest: +NORMALIZE_WHITESPACE
[(u'', ),
(u'Solar Panel', )]
Another method of looking up all utilities is by using
`getAllUtilitiesRegisteredFor(iface)`. This function will return an iterable
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.
.. doctest::
>>> utils = list(zope.component.getAllUtilitiesRegisteredFor(IUSSocket))
>>> utils.sort()
>>> utils
[, ]
Factories
~~~~~~~~~
A *factory* is a special kind of utility that exists to create other
components. A factory is always identified by a name. It also provides a title
and description and is able to tell the developer what interfaces the created
object will provide. The advantage of using a factory to create an object
instead of directly instantiating 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:
.. doctest::
>>> from zope.component.factory import Factory
>>> factory = Factory(SolarPanel,
... 'Solar Panel',
... 'This factory creates a solar panel.')
Optionally, I could have also specified 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:
.. doctest::
>>> from zope.component.interfaces import IFactory
>>> gsm.registerUtility(factory, IFactory, 'SolarPanel')
We can now get a list of interfaces the produced object will provide:
.. doctest::
>>> ifaces = zope.component.getFactoryInterfaces('SolarPanel')
>>> IUSSocket in ifaces
True
By the way, this is equivalent to
.. doctest::
>>> ifaces2 = factory.getInterfaces()
>>> ifaces is ifaces2
True
Of course you can also just create an object:
.. doctest::
>>> 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
.. doctest::
>>> gsm.registerUtility(Factory(Generator), IFactory, 'Generator')
you can also determine, which available factories will create objects
providing a certain interface:
.. doctest::
>>> factories = zope.component.getFactoriesFor(IUSSocket)
>>> factories = [(name, factory.__class__) for name, factory in factories]
>>> factories.sort()
>>> factories #doctest: +NORMALIZE_WHITESPACE
[(u'Generator', ),
(u'SolarPanel', )]
Site Managers
-------------
Why do we need site managers? Why is the component architecture API not
sufficient? Some applications, including Zope 3, have a concept of
locations. It is often desirable 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:
.. doctest::
>>> gsm = zope.component.getGlobalSiteManager()
>>> from zope.component import globalSiteManager
>>> gsm is globalSiteManager
True
>>> from zope.component.interfaces import IComponentLookup
>>> IComponentLookup.providedBy(gsm)
True
>>> from zope.component.interfaces import IComponents
>>> IComponents.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:
.. doctest::
>>> from zope.component.globalregistry import BaseGlobalComponents
>>> sm = BaseGlobalComponents()
Now we create a context that adapts to the site manager via the `__conform__`
method as specified in PEP 246.
.. doctest::
>>> class Context(object):
... def __init__(self, sm):
... self.sm = sm
... def __conform__(self, interface):
... if interface.isOrExtends(IComponentLookup):
... return self.sm
We now instantiate the `Context` with our special site manager:
.. doctest::
>>> context = Context(sm)
>>> context.sm is sm
True
We can now ask for the site manager of this context:
.. doctest::
>>> lsm = zope.component.getSiteManager(context)
>>> lsm is sm
True
The site manager instance `lsm` is formally known as a *local site manager* of
`context`.
zope.component-4.0.2/docs/testlayer.rst 0000664 0001750 0001750 00000006547 11774312422 020116 0 ustar tseaver tseaver Layers
======
zope.component.testlayer defines two things:
* a LayerBase that makes it easier and saner to use zope.testing's
test layers.
* a ZCMLLayer which lets you implement a layer that loads up some
ZCML.
LayerBase
---------
We check whether our LayerBase can be used to create layers of our
own. We do this simply by subclassing:
.. doctest::
>>> from zope.component.testlayer import LayerBase
>>> class OurLayer(LayerBase):
... def setUp(self):
... super(OurLayer, self).setUp()
... print "setUp called"
... def tearDown(self):
... super(OurLayer, self).tearDown()
... print "tearDown called"
... def testSetUp(self):
... super(OurLayer, self).testSetUp()
... print "testSetUp called"
... def testTearDown(self):
... super(OurLayer, self).testTearDown()
... print "testTearDown called"
Note that if we wanted to ensure that the methods of the superclass
were called we have to use super(). In this case we actually wouldn't
need to, as these methods do nothing at all, but we just ensure that
they are there in the first place.
Let's instantiate our layer. We need to supply it with the package the
layer is defined in:
.. doctest::
>>> import zope.component
>>> layer = OurLayer(zope.component)
Now we run some tests with this layer:
.. doctest::
>>> import unittest
>>> class TestCase(unittest.TestCase):
... layer = layer
...
... def testFoo(self):
... print "testFoo"
>>> suite = unittest.TestSuite()
>>> suite.addTest(unittest.makeSuite(TestCase))
>>> from zope.testrunner.runner import Runner
>>> runner = Runner(args=[], found_suites=[suite])
>>> succeeded = runner.run()
Running zope.component.OurLayer tests:
Set up zope.component.OurLayer setUp called
in ... seconds.
testSetUp called
testFoo
testTearDown called
Ran 1 tests with 0 failures and 0 errors in ... seconds.
Tearing down left over layers:
Tear down zope.component.OurLayer tearDown called
in ... seconds.
ZCMLLayer
---------
We now want a layer that loads up some ZCML from a file. The default
is ``ftesting.zcml``, but here we'll load a test ``testlayer.zcml``.
.. doctest::
>>> from zope.component.testlayer import ZCMLFileLayer
>>> import zope.component.testfiles
>>> zcml_file_layer = ZCMLFileLayer(
... zope.component.testfiles,
... 'testlayer.zcml')
>>> class TestCase(unittest.TestCase):
... layer = zcml_file_layer
...
... def testFoo(self):
... # we should now have the adapter registered
... from zope import component
... from zope.component.testfiles import components
... self.assert_(isinstance(
... components.IApp2(components.content), components.Comp2))
Since the ZCML sets up an adapter, we expect the tests to pass:
.. doctest::
>>> suite = unittest.TestSuite()
>>> suite.addTest(unittest.makeSuite(TestCase))
>>> runner = Runner(args=[], found_suites=[suite])
>>> succeeded = runner.run()
Running zope.component.testfiles.ZCMLFileLayer tests:
Set up zope.component.testfiles.ZCMLFileLayer in ... seconds.
Ran 1 tests with 0 failures and 0 errors in ... seconds.
Tearing down left over layers:
Tear down zope.component.testfiles.ZCMLFileLayer in ... seconds.
zope.component-4.0.2/docs/persistentregistry.rst 0000664 0001750 0001750 00000000317 11774312422 022060 0 ustar tseaver tseaver Persistent Component Management
===============================
Persistent component management allows persistent management of
components. From a usage point of view, there shouldn't be any new
behavior.
zope.component-4.0.2/docs/api/ 0000775 0001750 0001750 00000000000 12070353060 016076 5 ustar tseaver tseaver zope.component-4.0.2/docs/api/interface.rst 0000664 0001750 0001750 00000011654 11774312422 020606 0 ustar tseaver tseaver Interface Registration APIs
===========================
.. testsetup::
from zope.component.testing import setUp
setUp()
Registering Interfaces as Utilities
-----------------------------------
.. autofunction:: zope.component.interface.provideInterface
We can register a given interface with the global site manager as a utility.
First, declare a new interface, which itself provides only the core API,
:class:`zope.interface.interfaces.IInterface`:
.. doctest::
>>> from zope.interface import Interface
>>> from zope.interface.interfaces import IInterface
>>> from zope.component.tests.examples import ITestType
>>> from zope.component import getGlobalSiteManager
>>> gsm = getGlobalSiteManager()
>>> class IDemo(Interface):
... pass
>>> IInterface.providedBy(IDemo)
True
>>> ITestType.providedBy(IDemo)
False
>>> list(gsm.getUtilitiesFor(ITestType))
[]
Now, register ``IDemo`` as providing ``ITestType``
.. doctest::
>>> from zope.component.interface import provideInterface
>>> provideInterface('', IDemo, ITestType)
>>> ITestType.providedBy(IDemo)
True
>>> interfaces = list(gsm.getUtilitiesFor(ITestType))
>>> [iface.__name__ for (name, iface) in interfaces]
['IDemo']
We can register ``IDemo`` as providing more than one interface:
.. doctest::
>>> class IOtherType(IInterface):
... pass
>>> provideInterface('', IDemo, IOtherType)
>>> ITestType.providedBy(IDemo)
True
>>> IOtherType.providedBy(IDemo)
True
>>> interfaces = list(gsm.getUtilitiesFor(ITestType))
>>> [iface.__name__ for (name, iface) in interfaces]
['IDemo']
>>> interfaces = list(gsm.getUtilitiesFor(IOtherType))
>>> [iface.__name__ for (name, iface) in interfaces]
['IDemo']
.. testcleanup::
from zope.component.testing import tearDown
tearDown()
.. autofunction:: zope.component.interface.getInterface
.. doctest::
>>> from zope.interface import Interface
>>> from zope.component.interface import getInterface
>>> from zope.component.tests.examples import ITestType
>>> from zope.component.tests.examples import IGI
>>> IInterface.providedBy(IGI)
True
>>> ITestType.providedBy(IGI)
False
>>> getInterface(None, 'zope.component.tests.examples.IGI')
Traceback (most recent call last):
...
ComponentLookupError: zope.component.tests.examples.interface.IGI
>>> provideInterface('', IGI, ITestType)
>>> ITestType.providedBy(IGI)
True
>>> iface = getInterface(None,
... 'zope.component.tests.examples.IGI')
>>> iface.__name__
'IGI'
.. testcleanup::
from zope.component.testing import tearDown
tearDown()
.. autofunction:: zope.component.interface.queryInterface
.. doctest::
>>> from zope.interface import Interface
>>> from zope.interface.interfaces import IInterface
>>> from zope.component.interface import queryInterface
>>> from zope.component.tests.examples import ITestType
>>> from zope.component.tests.examples import IQI
>>> IInterface.providedBy(IQI)
True
>>> ITestType.providedBy(IQI)
False
>>> queryInterface('zope.component.tests.examples.IQI') is None
True
>>> provideInterface('', IQI, ITestType)
>>> ITestType.providedBy(IQI)
True
>>> iface = queryInterface('zope.component.tests.examples.IQI')
>>> iface.__name__
'IQI'
.. testcleanup::
from zope.component.testing import tearDown
tearDown()
.. autofunction:: zope.component.interface.searchInterface
.. doctest::
>>> from zope.interface import Interface
>>> from zope.interface.interfaces import IInterface
>>> from zope.component.interface import searchInterface
>>> from zope.component.tests.examples import ITestType
>>> from zope.component.tests.examples import ISI
>>> IInterface.providedBy(ISI)
True
>>> ITestType.providedBy(ISI)
False
>>> searchInterface(None, 'zope.component.tests.examples.ISI')
[]
>>> provideInterface('', ISI, ITestType)
>>> ITestType.providedBy(ISI)
True
>>> searchInterface(None, 'zope.component.tests.examples.ISI') == [ISI]
True
.. testcleanup::
from zope.component.testing import tearDown
tearDown()
.. autofunction:: zope.component.interface.searchInterfaceIds
.. doctest::
>>> from zope.interface import Interface
>>> from zope.interface.interfaces import IInterface
>>> from zope.component.interface import searchInterfaceIds
>>> from zope.component.tests.examples import ITestType
>>> from zope.component.tests.examples import ISII
>>> IInterface.providedBy(ISII)
True
>>> ITestType.providedBy(ISII)
False
>>> searchInterfaceIds(None, 'zope.component.tests.examples.ISII')
[]
>>> provideInterface('', ISII, ITestType)
>>> ITestType.providedBy(ISII)
True
>>> searchInterfaceIds(None, 'zope.component.tests.examples.ISII')
[u'zope.component.tests.examples.ISII']
.. testcleanup::
from zope.component.testing import tearDown
tearDown()
zope.component-4.0.2/docs/api/persistent.rst 0000664 0001750 0001750 00000013660 11774312422 021045 0 ustar tseaver tseaver Persistent Registries
=====================
.. testsetup::
from zope.component.testing import setUp
setUp()
Conforming Adapter Lookup
-------------------------
Here, we'll demonstrate that changes work even when data are stored in
a database and when accessed from multiple connections.
Start by setting up a database and creating two transaction
managers and database connections to work with.
.. doctest::
>>> import ZODB.tests.util
>>> db = ZODB.tests.util.DB()
>>> import transaction
>>> t1 = transaction.TransactionManager()
>>> c1 = db.open(transaction_manager=t1)
>>> r1 = c1.root()
>>> t2 = transaction.TransactionManager()
>>> c2 = db.open(transaction_manager=t2)
>>> r2 = c2.root()
Create a set of components registries in the database, alternating
connections.
.. doctest::
>>> from zope.component.persistentregistry import PersistentComponents
>>> from zope.component.tests.examples import I1
>>> from zope.component.tests.examples import I2
>>> from zope.component.tests.examples import U
>>> from zope.component.tests.examples import U1
>>> from zope.component.tests.examples import U12
>>> from zope.component.tests.examples import handle1
>>> from zope.component.tests.examples import handle2
>>> from zope.component.tests.examples import handle3
>>> from zope.component.tests.examples import handle4
>>> _ = t1.begin()
>>> r1[1] = PersistentComponents('1')
>>> t1.commit()
>>> _ = t2.begin()
>>> r2[2] = PersistentComponents('2', (r2[1], ))
>>> t2.commit()
>>> _ = t1.begin()
>>> r1[3] = PersistentComponents('3', (r1[1], ))
>>> t1.commit()
>>> _ = t2.begin()
>>> r2[4] = PersistentComponents('4', (r2[2], r2[3]))
>>> t2.commit()
>>> _ = t1.begin()
>>> r1[1].__bases__
()
>>> r1[2].__bases__ == (r1[1], )
True
>>> r1[1].registerUtility(U1(1))
>>> r1[1].queryUtility(I1)
U1(1)
>>> r1[2].queryUtility(I1)
U1(1)
>>> t1.commit()
>>> _ = t2.begin()
>>> r2[1].registerUtility(U1(2))
>>> r2[2].queryUtility(I1)
U1(2)
>>> r2[4].queryUtility(I1)
U1(2)
>>> t2.commit()
>>> _ = t1.begin()
>>> r1[1].registerUtility(U12(1), I2)
>>> r1[4].queryUtility(I2)
U12(1)
>>> t1.commit()
>>> _ = t2.begin()
>>> r2[3].registerUtility(U12(3), I2)
>>> r2[4].queryUtility(I2)
U12(3)
>>> t2.commit()
>>> _ = t1.begin()
>>> r1[1].registerHandler(handle1, info="First handler")
>>> r1[2].registerHandler(handle2, required=[U])
>>> r1[3].registerHandler(handle3)
>>> r1[4].registerHandler(handle4)
>>> r1[4].handle(U1(1))
handle1 U1(1)
handle3 U1(1)
handle2 (U1(1),)
handle4 U1(1)
>>> t1.commit()
>>> _ = t2.begin()
>>> r2[4].handle(U1(1))
handle1 U1(1)
handle3 U1(1)
handle2 (U1(1),)
handle4 U1(1)
>>> t2.abort()
>>> db.close()
Subscription to Events in Persistent Registries
-----------------------------------------------
.. doctest::
>>> import ZODB.tests.util
>>> db = ZODB.tests.util.DB()
>>> import transaction
>>> t1 = transaction.TransactionManager()
>>> c1 = db.open(transaction_manager=t1)
>>> r1 = c1.root()
>>> t2 = transaction.TransactionManager()
>>> c2 = db.open(transaction_manager=t2)
>>> r2 = c2.root()
>>> from zope.component.persistentregistry import PersistentComponents
>>> _ = t1.begin()
>>> r1[1] = PersistentComponents('1')
>>> r1[1].registerHandler(handle1)
>>> r1[1].registerSubscriptionAdapter(handle1, provided=I2)
>>> _ = r1[1].unregisterHandler(handle1)
>>> _ = r1[1].unregisterSubscriptionAdapter(handle1, provided=I2)
>>> t1.commit()
>>> _ = t1.begin()
>>> r1[1].registerHandler(handle1)
>>> r1[1].registerSubscriptionAdapter(handle1, provided=I2)
>>> t1.commit()
>>> _ = t2.begin()
>>> len(list(r2[1].registeredHandlers()))
1
>>> len(list(r2[1].registeredSubscriptionAdapters()))
1
>>> t2.abort()
Adapter Registrations after Serialization / Deserialization
-----------------------------------------------------------
We want to make sure that we see updates corrextly.
.. doctest::
>>> import persistent
>>> import transaction
>>> from zope.interface import Interface
>>> from zope.interface import implements
>>> class IFoo(Interface):
... pass
>>> class Foo(persistent.Persistent):
... implements(IFoo)
... name = ''
... def __init__(self, name=''):
... self.name = name
... def __repr__(self):
... return 'Foo(%r)' % self.name
>>> from zope.component.tests.examples import base
>>> from zope.component.tests.examples import clear_base
>>> len(base._v_subregistries)
0
>>> import ZODB.tests.util
>>> db = ZODB.tests.util.DB()
>>> tm1 = transaction.TransactionManager()
>>> c1 = db.open(transaction_manager=tm1)
>>> from zope.component.persistentregistry import PersistentAdapterRegistry
>>> r1 = PersistentAdapterRegistry((base,))
>>> r2 = PersistentAdapterRegistry((r1,))
>>> c1.root()[1] = r1
>>> c1.root()[2] = r2
>>> tm1.commit()
>>> r1._p_deactivate()
>>> len(base._v_subregistries)
0
>>> 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')
>>> db.close()
>>> clear_base()
.. testcleanup::
from zope.component.testing import tearDown
tearDown()
zope.component-4.0.2/docs/api/security.rst 0000664 0001750 0001750 00000005057 11774312422 020515 0 ustar tseaver tseaver Security APIs
=============
.. automodule:: zope.component.security
.. autofunction:: securityAdapterFactory
If a permission is provided when wrapping the adapter, it will be
wrapped in a LocatingAdapterFactory.
.. doctest::
>>> class Factory(object):
... pass
If both locate and trusted are False and a non-public
permission is provided, then the factory is wrapped into a
LocatingUntrustedAdapterFactory:
.. doctest::
>>> from zope.component.security import securityAdapterFactory
>>> from zope.security.adapter import LocatingUntrustedAdapterFactory
>>> factory = securityAdapterFactory(Factory, 'zope.AnotherPermission',
... locate=False, trusted=False)
>>> isinstance(factory, LocatingUntrustedAdapterFactory)
True
If a PublicPermission is provided, then the factory is not touched.
.. doctest::
>>> from zope.component.security import PublicPermission
>>> factory = securityAdapterFactory(Factory, PublicPermission,
... locate=False, trusted=False)
>>> factory is Factory
True
Same for CheckerPublic:
.. doctest::
>>> from zope.security.checker import CheckerPublic
>>> factory = securityAdapterFactory(Factory, CheckerPublic,
... locate=False, trusted=False)
>>> factory is Factory
True
If the permission is None, the factory isn't touched:
.. doctest::
>>> factory = securityAdapterFactory(Factory, None,
... locate=False, trusted=False)
>>> factory is Factory
True
If the factory is trusted and a no permission is provided then the
adapter is wrapped into a TrustedAdapterFactory:
.. doctest::
>>> from zope.security.adapter import TrustedAdapterFactory
>>> factory = securityAdapterFactory(Factory, None,
... locate=False, trusted=True)
>>> isinstance(factory, TrustedAdapterFactory)
True
Same for PublicPermission:
.. doctest::
>>> factory = securityAdapterFactory(Factory, PublicPermission,
... locate=False, trusted=True)
>>> isinstance(factory, TrustedAdapterFactory)
True
Same for CheckerPublic:
.. doctest::
>>> factory = securityAdapterFactory(Factory, CheckerPublic,
... locate=False, trusted=True)
>>> isinstance(factory, TrustedAdapterFactory)
True
If the factory is trusted and a locate is true, then the
adapter is wrapped into a LocatingTrustedAdapterFactory:
.. doctest::
>>> from zope.security.adapter import LocatingTrustedAdapterFactory
>>> factory = securityAdapterFactory(Factory, 'zope.AnotherPermission',
... locate=True, trusted=True)
>>> isinstance(factory, LocatingTrustedAdapterFactory)
True
zope.component-4.0.2/docs/api/adapter.rst 0000664 0001750 0001750 00000024637 11774312422 020273 0 ustar tseaver tseaver Adapter Registration APIs
=========================
.. testsetup::
from zope.component.testing import setUp
setUp()
Conforming Adapter Lookup
-------------------------
.. autofunction:: zope.component.getAdapterInContext
.. autofunction:: zope.component.queryAdapterInContext
The :func:`~zope.component.getAdapterInContext` and
:func:`~zope.component.queryAdapterInContext` APIs first check the
context object to see if it already conforms to the requested interface.
If so, the object is returned immediately. Otherwise, the adapter factory
is looked up in the site manager, and called.
Let's start by creating a component that supports the `__conform__()` method:
.. doctest::
>>> from zope.interface import implementer
>>> from zope.component.tests.examples import I1
>>> from zope.component.tests.examples import I2
>>> @implementer(I1)
... class Component(object):
... def __conform__(self, iface, default=None):
... if iface == I2:
... return 42
>>> 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`.
.. doctest::
>>> from zope.component.globalregistry import BaseGlobalComponents
>>> sitemanager = BaseGlobalComponents()
Now we create a new `context` that knows how to get to our custom site
manager.
.. doctest::
>>> from zope.component.tests.examples import ConformsToIComponentLookup
>>> context = ConformsToIComponentLookup(sitemanager)
If an object implements the interface you want to adapt to,
`getAdapterInContext()` should simply return the object.
.. doctest::
>>> from zope.component import getAdapterInContext
>>> from zope.component import queryAdapterInContext
>>> getAdapterInContext(ob, I1, context) is ob
True
>>> queryAdapterInContext(ob, I1, context) is ob
True
If an object conforms to the interface you want to adapt to,
`getAdapterInContext()` should simply return the conformed object.
.. doctest::
>>> getAdapterInContext(ob, I2, context)
42
>>> queryAdapterInContext(ob, I2, context)
42
If an adapter isn't registered for the given object and interface, and you
provide no default, the `getAdapterInContext` API raises ComponentLookupError:
.. doctest::
>>> from zope.interface import Interface
>>> class I4(Interface):
... pass
>>> getAdapterInContext(ob, I4, context)
Traceback (most recent call last):
...
ComponentLookupError: (,
)
While the `queryAdapterInContext` API returns the default:
.. doctest::
>>> queryAdapterInContext(ob, I4, context, 44)
44
If you ask for an adapter for which something's registered you get the
registered adapter:
.. doctest::
>>> from zope.component.tests.examples import I3
>>> sitemanager.registerAdapter(lambda x: 43, (I1,), I3, '')
>>> getAdapterInContext(ob, I3, context)
43
>>> queryAdapterInContext(ob, I3, context)
43
Named Adapter Lookup
--------------------
.. autofunction:: zope.component.getAdapter
.. autofunction:: zope.component.queryAdapter
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 no adapter is registered for the given object, interface, and name,
``getAdapter`` raises ``ComponentLookupError``, while ``queryAdapter``
returns the default:
.. doctest::
>>> from zope.component import getAdapter
>>> from zope.component import queryAdapter
>>> from zope.component.tests.examples import I2
>>> from zope.component.tests.examples import ob
>>> getAdapter(ob, I2, '')
Traceback (most recent call last):
...
ComponentLookupError: (,
,
'')
>>> queryAdapter(ob, I2, '', '')
''
The 'requires' argument to `registerAdapter` must be a sequence, rather than
a single interface:
.. doctest::
>>> from zope.component import getGlobalSiteManager
>>> from zope.component.tests.examples import Comp
>>> gsm = getGlobalSiteManager()
>>> gsm.registerAdapter(Comp, I1, I2, '')
Traceback (most recent call last):
...
TypeError: the required argument should be a list of interfaces, not a single interface
After register an adapter from `I1` to `I2` with the global site manager:
.. doctest::
>>> from zope.component import getGlobalSiteManager
>>> from zope.component.tests.examples import Comp
>>> gsm = getGlobalSiteManager()
>>> gsm.registerAdapter(Comp, (I1,), I2, '')
We can access the adapter using the `getAdapter()` API:
.. doctest::
>>> adapted = getAdapter(ob, I2, '')
>>> adapted.__class__ is Comp
True
>>> adapted.context is ob
True
>>> adapted = queryAdapter(ob, I2, '')
>>> adapted.__class__ is Comp
True
>>> adapted.context is ob
True
If we search using a non-anonymous name, before registering:
.. doctest::
>>> getAdapter(ob, I2, 'named')
Traceback (most recent call last):
...
ComponentLookupError: (,
,
'named')
>>> queryAdapter(ob, I2, 'named', '')
''
After registering under that name:
.. doctest::
>>> gsm.registerAdapter(Comp, (I1,), I2, 'named')
>>> adapted = getAdapter(ob, I2, 'named')
>>> adapted.__class__ is Comp
True
>>> adapted.context is ob
True
>>> adapted = queryAdapter(ob, I2, 'named')
>>> adapted.__class__ is Comp
True
>>> adapted.context is ob
True
Invoking an Interface to Perform Adapter Lookup
-----------------------------------------------
:mod:`zope.component` registers an adapter hook with
:mod:`zope.interface.interface`, allowing a convenient spelling for
adapter lookup: just "call" the interface, passing the context:
.. doctest::
>>> adapted = I2(ob)
>>> adapted.__class__ is Comp
True
>>> adapted.context is ob
True
If the lookup fails, we get a `TypeError`:
.. doctest::
>>> I2(object())
Traceback (most recent call last):
...
TypeError: ('Could not adapt'...
unless we pass a default:
.. doctest::
>>> marker = object()
>>> adapted = I2(object(), marker)
>>> adapted is marker
True
Registering Adapters For Arbitrary Objects
------------------------------------------
Providing an adapter for None says that your adapter can adapt anything
to `I2`.
.. doctest::
>>> gsm.registerAdapter(Comp, (None,), I2, '')
>>> adapter = I2(ob)
>>> adapter.__class__ is Comp
True
>>> adapter.context is ob
True
It can really adapt any arbitrary object:
.. doctest::
>>> something = object()
>>> adapter = I2(something)
>>> adapter.__class__ is Comp
True
>>> adapter.context is something
True
Looking Up Adapters Using Multiple Objects
------------------------------------------
.. autofunction:: zope.component.getMultiAdapter
.. autofunction:: zope.component.queryMultiAdapter
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:
.. doctest::
>>> from zope.component.tests.examples import Ob2
>>> ob2 = Ob2()
As with regular adapters, if an adapter isn't registered for the given
objects and interface, the :func:`~zope.component.getMultiAdapter` API
raises `ComponentLookupError`:
.. doctest::
>>> from zope.component import getMultiAdapter
>>> getMultiAdapter((ob, ob2), I3)
Traceback (most recent call last):
...
ComponentLookupError:
((, ),
,
u'')
while the :func:`~zope.component.queryMultiAdapter` API returns the default:
.. doctest::
>>> from zope.component import queryMultiAdapter
>>> queryMultiAdapter((ob, ob2), I3, default='')
''
Note that ``name`` is not a required attribute here.
To test multi-adapters, we also have to create an adapter class that
handles to context objects:
.. doctest::
>>> from zope.interface import implementer
>>> @implementer(I3)
... class DoubleAdapter(object):
... def __init__(self, first, second):
... self.first = first
... self.second = second
Now we can register the multi-adapter:
.. doctest::
>>> from zope.component import getGlobalSiteManager
>>> getGlobalSiteManager().registerAdapter(DoubleAdapter, (I1, I2), I3, '')
Notice how the required interfaces are simply provided by a tuple.
Now we can get the adapter:
.. doctest::
>>> adapter = getMultiAdapter((ob, ob2), I3)
>>> adapter.__class__ is DoubleAdapter
True
>>> adapter.first is ob
True
>>> adapter.second is ob2
True
Finding More Than One Adapter
-----------------------------
.. autofunction:: zope.component.getAdapters
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:
.. doctest::
>>> class I5(I1):
... pass
>>> gsm.registerAdapter(Comp, [I1], I5, '')
>>> gsm.registerAdapter(Comp, [None], I5, 'foo')
Now we get all the adapters that are registered for ``ob`` that provide
``I5``:
.. doctest::
>>> from zope.component import getAdapters
>>> adapters = sorted(getAdapters((ob,), I5))
>>> [(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.
.. doctest::
>>> gsm.registerAdapter(lambda context: None, [I1], I5, 'nah')
>>> adapters = sorted(getAdapters((ob,), I5))
>>> [(name, adapter.__class__.__name__) for name, adapter in adapters]
[(u'', 'Comp'), (u'foo', 'Comp')]
Subscription Adapters
---------------------
.. autofunction:: zope.component.subscribers
Event handlers
--------------
.. autofunction:: zope.component.handle
Helpers for Declaring / Testing Adapters
----------------------------------------
.. autofunction:: zope.component.adapter
.. autofunction:: zope.component.adaptedBy
.. autofunction:: zope.component.adapts
.. testcleanup::
from zope.component.testing import tearDown
tearDown()
zope.component-4.0.2/docs/api/utility.rst 0000664 0001750 0001750 00000016532 11774312422 020351 0 ustar tseaver tseaver Utility Registration APIs
=========================
.. autofunction:: zope.component.getUtility
.. autofunction:: zope.component.queryUtility
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`.
.. testsetup::
from zope.component.testing import setUp
setUp()
.. doctest::
>>> from zope.component import getUtility
>>> from zope.component import queryUtility
>>> from zope.component.tests.examples import I1
>>> getUtility(I1) #doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ComponentLookupError: \
(, '')
Otherwise, you get the default:
.. doctest::
>>> queryUtility(I1, default='')
''
Now we declare `ob` to be the utility providing `I1`:
.. doctest::
>>> ob = object()
>>> from zope.component import getGlobalSiteManager
>>> getGlobalSiteManager().registerUtility(ob, I1)
Now the component is available:
.. doctest::
>>> getUtility(I1) is ob
True
>>> queryUtility(I1) is ob
True
Named Utilities
---------------
Registering a utility without a name does not mean that it is available
when looking for the utility with a name:
.. doctest::
>>> getUtility(I1, name='foo')
Traceback (most recent call last):
...
ComponentLookupError:
(, 'foo')
>>> queryUtility(I1, name='foo', default='')
''
Registering the utility under the correct name makes it available:
.. doctest::
>>> ob2 = object()
>>> getGlobalSiteManager().registerUtility(ob2, I1, name='foo')
>>> getUtility(I1, 'foo') is ob2
True
>>> queryUtility(I1, 'foo') is ob2
True
Querying Multiple Utilities
---------------------------
.. autofunction:: zope.component.getUtilitiesFor
.. autofunction:: zope.component.getAllUtilitiesRegisteredFor
Sometimes it may be useful to query all utilities, both anonymous and named
for a given interface. The :func:`~zope.component.getUtilitiesFor` API
returns a sequence of ``(name, utility)`` tuples, where ``name`` is the
empty string for the anonymous utility:
.. doctest::
>>> from zope.component import getUtilitiesFor
>>> tuples = list(getUtilitiesFor(I1))
>>> len(tuples)
2
>>> ('', ob) in tuples
True
>>> ('foo', ob2) in tuples
True
The :func:`~zope.component.getAllUtilitiesRegisteredFor` API returns
utilities that have been registered for a particular interface. Utilities
providing a derived interface are also listed.
.. doctest::
>>> from zope.interface import implementer
>>> from zope.component.tests.examples import Comp
>>> from zope.component.tests.examples import I2
>>> from zope.component.tests.examples import Ob
>>> class I11(I1):
... pass
>>> @implementer(I11)
... class Ob11(Ob):
... pass
>>> ob11 = Ob11()
>>> ob_bob = Ob()
Now we register the new utilities:
.. doctest::
>>> from zope.component import getGlobalSiteManager
>>> gsm = getGlobalSiteManager()
>>> gsm.registerUtility(ob, I1)
>>> gsm.registerUtility(ob11, I11)
>>> gsm.registerUtility(ob_bob, I1, name='bob')
>>> gsm.registerUtility(Comp(2), I2)
We can now get all the utilities that provide interface `I1`:
.. doctest::
>>> from zope.component import getAllUtilitiesRegisteredFor
>>> uts = list(getAllUtilitiesRegisteredFor(I1))
>>> len(uts)
4
>>> ob in uts
True
>>> ob2 in uts
True
>>> ob_bob in uts
True
>>> ob11 in uts
True
Note that `getAllUtilitiesRegisteredFor()` does not return the names of
the utilities.
Delegated Utility Lookup
------------------------
.. autofunction:: zope.component.getNextUtility
.. autofunction:: zope.component.queryNextUtility
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 first create a global utility:
.. doctest::
>>> from zope.interface import Interface
>>> from zope.interface import implementer
>>> class IMyUtility(Interface):
... pass
>>> from zope.component.tests.examples import ConformsToIComponentLookup
>>> @implementer(IMyUtility)
... class MyUtility(ConformsToIComponentLookup):
... def __init__(self, id, sm):
... self.id = id
... self.sitemanager = sm
... def __repr__(self):
... return "%s('%s')" % (self.__class__.__name__, self.id)
>>> gutil = MyUtility('global', gsm)
>>> gsm.registerUtility(gutil, IMyUtility, 'myutil')
Now, let's create two registries and set up the bases hierarchy:
.. doctest::
>>> from zope.interface.registry import Components
>>> sm1 = Components('sm1', bases=(gsm, ))
>>> sm1_1 = Components('sm1_1', bases=(sm1, ))
Now we create two utilities and insert them in our folder hierarchy:
.. doctest::
>>> from zope.component.interfaces import IComponentLookup
>>> util1 = MyUtility('one', sm1)
>>> sm1.registerUtility(util1, IMyUtility, 'myutil')
>>> IComponentLookup(util1) is sm1
True
>>> util1_1 = MyUtility('one-one', sm1_1)
>>> sm1_1.registerUtility(util1_1, IMyUtility, 'myutil')
>>> IComponentLookup(util1_1) is sm1_1
True
Now, if we ask `util1_1` for its next available utility we get the
``one`` utility:
.. doctest::
>>> from zope.component import getNextUtility
>>> getNextUtility(util1_1, IMyUtility, 'myutil')
MyUtility('one')
Next we ask `util1` for its next utility and we should get the global version:
.. doctest::
>>> getNextUtility(util1, IMyUtility, 'myutil')
MyUtility('global')
However, if we ask the global utility for the next one, an error is raised
.. doctest::
>>> getNextUtility(gutil, IMyUtility,
... 'myutil') #doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ComponentLookupError:
No more utilities for ,
'myutil' have been found.
You can also use `queryNextUtility` and specify a default:
.. doctest::
>>> from zope.component import queryNextUtility
>>> queryNextUtility(gutil, IMyUtility, 'myutil', 'default')
'default'
Let's now ensure that the function also works with multiple registries. First
we create another base registry:
.. doctest::
>>> myregistry = Components()
We now set up another utility into that registry:
.. doctest::
>>> custom_util = MyUtility('my_custom_util', myregistry)
>>> myregistry.registerUtility(custom_util, IMyUtility, 'my_custom_util')
We add it as a base to the local site manager:
.. doctest::
>>> sm1.__bases__ = (myregistry,) + sm1.__bases__
Both the ``myregistry`` and global utilities should be available:
.. doctest::
>>> queryNextUtility(sm1, IMyUtility, 'my_custom_util')
MyUtility('my_custom_util')
>>> queryNextUtility(sm1, IMyUtility, 'myutil')
MyUtility('global')
Note, if the context cannot be converted to a site manager, the default is
retruned:
.. doctest::
>>> queryNextUtility(object(), IMyUtility, 'myutil', 'default')
'default'
.. testcleanup::
from zope.component.testing import tearDown
tearDown()
zope.component-4.0.2/docs/api/sitemanager.rst 0000664 0001750 0001750 00000004442 11774312422 021142 0 ustar tseaver tseaver Site Manager APIs
=================
.. autofunction:: zope.component.getGlobalSiteManager
The API returns the module-scope global registry:
.. doctest::
>>> from zope.component.interfaces import IComponentLookup
>>> from zope.component.globalregistry import base
>>> from zope.component import getGlobalSiteManager
>>> gsm = getGlobalSiteManager()
>>> gsm is base
True
The registry implements the
:class:`~zope.component.interfaces.IComponentLookup` interface:
.. doctest::
>>> IComponentLookup.providedBy(gsm)
True
The same registry is returned each time we call the function:
.. doctest::
>>> getGlobalSiteManager() is gsm
True
.. autofunction:: zope.component.getSiteManager(context=None)
We don't know anything about the default service manager, except that it
is an `IComponentLookup`.
.. doctest::
>>> from zope.component import getSiteManager
>>> from zope.component.interfaces import IComponentLookup
>>> IComponentLookup.providedBy(getSiteManager())
True
Calling `getSiteManager()` with no args is equivalent to calling it with a
context of `None`.
.. doctest::
>>> getSiteManager() is getSiteManager(None)
True
If the context passed to `getSiteManager()` is not `None`, it is
adapted to `IComponentLookup` and this adapter returned. So, we
create a context that can be adapted to `IComponentLookup` using
the `__conform__` API.
Let's create the simplest stub-implementation of a site manager possible:
.. doctest::
>>> sitemanager = object()
Now create a context that knows how to adapt to our newly created site
manager.
.. doctest::
>>> from zope.component.tests.examples import ConformsToIComponentLookup
>>> context = ConformsToIComponentLookup(sitemanager)
Now make sure that the `getSiteManager()` API call returns the correct
site manager.
.. doctest::
>>> getSiteManager(context) is sitemanager
True
Using a context that is not adaptable to `IComponentLookup` should fail.
.. doctest::
>>> getSiteManager(sitemanager)
Traceback (most recent call last):
...
ComponentLookupError: ('Could not adapt', ,
)
zope.component-4.0.2/docs/api/factory.rst 0000664 0001750 0001750 00000000263 11774312422 020307 0 ustar tseaver tseaver Factory APIs
============
.. autofunction:: zope.component.createObject
.. autofunction:: zope.component.getFactoryInterfaces
.. autofunction:: zope.component.getFactoriesFor
zope.component-4.0.2/docs/api/interfaces.rst 0000664 0001750 0001750 00000001165 11774312422 020765 0 ustar tseaver tseaver Interface Definitions
=====================
.. automodule:: zope.component.interfaces
.. autointerface:: IComponentArchitecture
:members:
:member-order: bysource
.. autointerface:: IRegistry
:members:
:member-order: bysource
.. autointerface:: IComponentRegistrationConvenience
:members:
:member-order: bysource
.. autointerface:: IPossibleSite
:members:
:member-order: bysource
.. autointerface:: ISite
:members:
:member-order: bysource
.. autoexception:: Misused
.. autointerface:: IFactory
:members:
:member-order: bysource
zope.component-4.0.2/docs/conf.py 0000664 0001750 0001750 00000017535 11774312422 016646 0 ustar tseaver tseaver # -*- coding: utf-8 -*-
#
# zope.configuration documentation build configuration file, created by
# sphinx-quickstart on Thu May 10 21:03:35 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.todo',
'sphinx.ext.viewcode',
'repoze.sphinx.autointerface',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'zope.configuration'
copyright = u'2012, Zope Foundation Contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '4.0'
# The full version, including alpha/beta/rc tags.
release = '4.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'zopeconfigurationdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'zopeconfiguration.tex', u'zope.configuration Documentation',
u'Zope Foundation Contributors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'zopeconfiguration', u'zope.configuration Documentation',
[u'Zope Foundation Contributors'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'zopeconfiguration', u'zope.configuration Documentation',
u'Zope Foundation Contributors', 'zopeconfiguration', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
zope.component-4.0.2/docs/zcml.rst 0000664 0001750 0001750 00000077551 11774312422 017052 0 ustar tseaver tseaver ZCML directives
===============
Components may be registered using the registration API exposed by
``zope.component`` (provideAdapter, provideUtility, etc.). They may
also be registered using configuration files. The common way to do
that is by using ZCML (Zope Configuration Markup Language), an XML
spelling of component registration.
In ZCML, each XML element is a *directive*. There are different
top-level directives that let us register components. We will
introduce them one by one here.
This helper will let us easily execute ZCML snippets:
.. doctest::
>>> from cStringIO import StringIO
>>> from zope.configuration.xmlconfig import xmlconfig
>>> def runSnippet(snippet):
... template = """\
...
... %s
... """
... xmlconfig(StringIO(template % snippet))
adapter
-------
Adapters play a key role in the Component Architecture. In ZCML, they
are registered with the directive.
.. doctest::
>>> from zope.component.testfiles.adapter import A1, A2, A3, Handler
>>> from zope.component.testfiles.adapter import I1, I2, I3, IS
>>> from zope.component.testfiles.components import IContent, Content, Comp, comp
Before we register the first test adapter, we can verify that adapter
lookup doesn't work yet:
.. doctest::
>>> from zope.component.tests.examples import clearZCML
>>> clearZCML()
>>> from zope.component.testfiles.components import IApp
>>> IApp(Content(), None) is None
True
Then we register the adapter and see that the lookup works:
.. doctest::
>>> runSnippet('''
... ''')
>>> IApp(Content()).__class__
It is also possible to give adapters names. Then the combination of
required interface, provided interface and name makes the adapter
lookup unique. The name is supplied using the ``name`` argument to
the directive:
.. doctest::
>>> from zope.component.tests.examples import clearZCML
>>> clearZCML()
>>> import zope.component
>>> zope.component.queryAdapter(Content(), IApp, 'test') is None
True
>>> runSnippet('''
... ''')
>>> zope.component.getAdapter(Content(), IApp, 'test').__class__
Adapter factories
~~~~~~~~~~~~~~~~~
It is possible to supply more than one adapter factory. In this case,
during adapter lookup each factory will be called and the return value
will be given to the next factory. The return value of the last
factory is returned as the result of the adapter lookup. For examle:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
The resulting adapter is an A3, around an A2, around an A1, around the
adapted object:
.. doctest::
>>> content = Content()
>>> a3 = IApp(content)
>>> a3.__class__ is A3
True
>>> a2 = a3.context[0]
>>> a2.__class__ is A2
True
>>> a1 = a2.context[0]
>>> a1.__class__ is A1
True
>>> a1.context[0] is content
True
Of course, if no factory is provided at all, we will get an error:
.. doctest::
>>> runSnippet('''
... ''')
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "", line 4.2-8.8
ValueError: No factory specified
Declaring ``for`` and ``provides`` in Python
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The directive can figure out from the in-line Python
declaration (using ``zope.component.adapts()`` or
``zope.component.adapter()`` as well as ``zope.interface.implements``)
what the adapter should be registered for and what it provides:
.. doctest::
>>> clearZCML()
>>> IApp(Content(), None) is None
True
>>> runSnippet('''
... ''')
>>> IApp(Content()).__class__
Of course, if the adapter has no ``implements()`` declaration, ZCML
can't figure out what it provides:
.. doctest::
>>> runSnippet('''
... ''')
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "", line 4.2-7.8
TypeError: Missing 'provides' attribute
On the other hand, if the factory implements more than one interface,
ZCML can't figure out what it should provide either:
.. doctest::
>>> runSnippet('''
... ''')
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "", line 4.2-7.8
TypeError: Missing 'provides' attribute
A not so common edge case is registering adapters directly for
classes, not for interfaces. For example:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> content = Content()
>>> a1 = zope.component.getAdapter(content, I1, '')
>>> isinstance(a1, A1)
True
This time, any object providing ``IContent`` won't work if it's not an
instance of the ``Content`` class:
.. doctest::
>>> import zope.interface
>>> class MyContent:
... zope.interface.implements(IContent)
>>> zope.component.getAdapter(MyContent(), I1, '') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ComponentLookupError: ...
Multi-adapters
~~~~~~~~~~~~~~
Conventional adapters adapt one object to provide another interface.
Multi-adapters adapt several objects at once:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> content = Content()
>>> a1 = A1()
>>> a2 = A2()
>>> a3 = zope.component.queryMultiAdapter((content, a1, a2), I3)
>>> a3.__class__ is A3
True
>>> a3.context == (content, a1, a2)
True
You can even adapt an empty list of objects (we call this a
null-adapter):
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> a3 = zope.component.queryMultiAdapter((), I3)
>>> a3.__class__ is A3
True
>>> a3.context == ()
True
Even with multi-adapters, ZCML can figure out the ``for`` and
``provides`` parameters from the Python declarations:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> a3 = zope.component.queryMultiAdapter((content, a1, a2), I3)
>>> a3.__class__ is A3
True
>>> a3.context == (content, a1, a2)
True
Chained factories are not supported for multi-adapters, though:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "", line 4.2-11.8
ValueError: Can't use multiple factories and multiple for
And neither for null-adapters:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "", line 4.2-9.8
ValueError: Can't use multiple factories and multiple for
Protected adapters
~~~~~~~~~~~~~~~~~~
Adapters can be protected with a permission. First we have to define
a permission for which we'll have to register the
directive:
.. doctest::
>>> clearZCML()
>>> IApp(Content(), None) is None
True
>>> import zope.security
>>> from zope.configuration.xmlconfig import XMLConfig
>>> XMLConfig('meta.zcml', zope.security)()
>>> runSnippet('''
...
... ''')
We see that the adapter is a location proxy now so that the
appropriate permissions can be found from the context:
.. doctest::
>>> IApp(Content()).__class__
>>> type(IApp(Content()))
We can also go about it a different way. Let's make a public adapter
and wrap the adapter in a security proxy. That often happens when
an adapter is turned over to untrusted code:
.. doctest::
>>> clearZCML()
>>> IApp(Content(), None) is None
True
>>> runSnippet('''
... ''')
>>> from zope.security.checker import ProxyFactory
>>> adapter = ProxyFactory(IApp(Content()))
>>> from zope.security.proxy import getTestProxyItems
>>> items = [item[0] for item in getTestProxyItems(adapter)]
>>> items
['a', 'f']
>>> from zope.security.proxy import removeSecurityProxy
>>> removeSecurityProxy(adapter).__class__ is Comp
True
Of course, this still works when we let the ZCML directive handler
figure out ``for`` and ``provides`` from the Python declarations:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> adapter = ProxyFactory(IApp(Content()))
>>> [item[0] for item in getTestProxyItems(adapter)]
['a', 'f']
>>> removeSecurityProxy(adapter).__class__ is Comp
True
It also works with multi adapters:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> content = Content()
>>> a1 = A1()
>>> a2 = A2()
>>> a3 = ProxyFactory(zope.component.queryMultiAdapter((content, a1, a2), I3))
>>> a3.__class__ == A3
True
>>> [item[0] for item in getTestProxyItems(a3)]
['f1', 'f2', 'f3']
It's probably not worth mentioning, but when we try to protect an
adapter with a permission that doesn't exist, we'll obviously get an
error:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
Traceback (most recent call last):
...
ConfigurationExecutionError: exceptions.ValueError: ('Undefined permission id', 'zope.UndefinedPermission')
in:
File "", line 4.2-9.8
Could not read source.
Trusted adapters
~~~~~~~~~~~~~~~~
Trusted adapters are adapters that are trusted to do anything with the
objects they are given so that these objects are not security-proxied.
They are registered using the ``trusted`` argument to the
directive:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
With an unproxied object, it's business as usual:
.. doctest::
>>> ob = Content()
>>> type(I1(ob)) is A1
True
With a security-proxied object, however, we get a security-proxied
adapter:
.. doctest::
>>> p = ProxyFactory(ob)
>>> a = I1(p)
>>> type(a)
While the adapter is security-proxied, the object it adapts is now
proxy-free. The adapter has umlimited access to it:
.. doctest::
>>> a = removeSecurityProxy(a)
>>> type(a) is A1
True
>>> a.context[0] is ob
True
We can also protect the trusted adapter with a permission:
.. doctest::
>>> clearZCML()
>>> XMLConfig('meta.zcml', zope.security)()
>>> runSnippet('''
...
... ''')
Again, with an unproxied object, it's business as usual:
.. doctest::
>>> ob = Content()
>>> type(I1(ob)) is A1
True
With a security-proxied object, we again get a security-proxied
adapter:
.. doctest::
>>> p = ProxyFactory(ob)
>>> a = I1(p)
>>> type(a)
Since we protected the adapter with a permission, we now encounter a
location proxy behind the security proxy:
.. doctest::
>>> a = removeSecurityProxy(a)
>>> type(a)
>>> a.context[0] is ob
True
There's one exception to all of this: When you use the public
permission (``zope.Public``), there will be no location proxy:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> ob = Content()
>>> p = ProxyFactory(ob)
>>> a = I1(p)
>>> type(a)
>>> a = removeSecurityProxy(a)
>>> type(a) is A1
True
We can also explicitply pass the ``locate`` argument to make sure we
get location proxies:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> ob = Content()
>>> p = ProxyFactory(ob)
>>> a = I1(p)
>>> type(a)
>>> a = removeSecurityProxy(a)
>>> type(a)
subscriber
----------
With the directive you can register subscription
adapters or event subscribers with the adapter registry. Consider
this very typical example of a directive:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> content = Content()
>>> a1 = A1()
>>> subscribers = zope.component.subscribers((content, a1), IS)
>>> a3 = subscribers[0]
>>> a3.__class__ is A3
True
>>> a3.context == (content, a1)
True
Note how ZCML provides some additional information when registering
components, such as the ZCML filename and line numbers:
.. doctest::
>>> sm = zope.component.getSiteManager()
>>> doc = [reg.info for reg in sm.registeredSubscriptionAdapters()
... if reg.provided is IS][0]
>>> print doc
File "", line 4.2-9.8
Could not read source.
The "fun" behind subscription adapters/subscribers is that when
several ones are declared for the same for/provides, they are all
found. With regular adapters, the most specific one (and in doubt the
one registered last) wins. Consider these two subscribers:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
...
... ''')
>>> subscribers = zope.component.subscribers((content, a1), IS)
>>> len(subscribers)
2
>>> sorted([a.__class__.__name__ for a in subscribers])
['A2', 'A3']
Declaring ``for`` and ``provides`` in Python
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Like the directive, the directive can
figure out from the in-line Python declaration (using
``zope.component.adapts()`` or ``zope.component.adapter()``) what the
subscriber should be registered for:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> content = Content()
>>> a2 = A2()
>>> subscribers = zope.component.subscribers((content, a1, a2), IS)
>>> a3 = subscribers[0]
>>> a3.__class__ is A3
True
>>> a3.context == (content, a1, a2)
True
In the same way the directive can figure out what a subscriber
provides:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> sm = zope.component.getSiteManager()
>>> a3 = sm.adapters.subscriptions((IContent, I1, I2), None)[0]
>>> a3 is A3
True
A not so common edge case is declaring subscribers directly for
classes, not for interfaces. For example:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> subs = list(zope.component.subscribers((Content(),), I1))
>>> isinstance(subs[0], A1)
True
This time, any object providing ``IContent`` won't work if it's not an
instance of the ``Content`` class:
.. doctest::
>>> list(zope.component.subscribers((MyContent(),), I1))
[]
Protected subscribers
~~~~~~~~~~~~~~~~~~~~~
Subscribers can also be protected with a permission. First we have to
define a permission for which we'll have to register the
directive:
.. doctest::
>>> clearZCML()
>>> XMLConfig('meta.zcml', zope.security)()
>>> runSnippet('''
...
... ''')
>>> subscribers = zope.component.subscribers((content, a1), IS)
>>> a3 = subscribers[0]
>>> a3.__class__ is A3
True
>>> type(a3)
>>> a3.context == (content, a1)
True
Trusted subscribers
~~~~~~~~~~~~~~~~~~~
Like trusted adapters, trusted subscribers are subscribers that are
trusted to do anything with the objects they are given so that these
objects are not security-proxied. In analogy to the
directive, they are registered using the ``trusted`` argument to the
directive:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
With an unproxied object, it's business as usual:
.. doctest::
>>> subscribers = zope.component.subscribers((content, a1), IS)
>>> a3 = subscribers[0]
>>> a3.__class__ is A3
True
>>> a3.context == (content, a1)
True
>>> type(a3) is A3
True
Now with a proxied object. We will see that the subscriber has
unproxied access to it, but the subscriber itself is proxied:
.. doctest::
>>> p = ProxyFactory(content)
>>> a3 = zope.component.subscribers((p, a1), IS)[0]
>>> type(a3)
There's no location proxy behind the security proxy:
.. doctest::
>>> removeSecurityProxy(a3).context[0] is content
True
>>> type(removeSecurityProxy(a3)) is A3
True
If you want the trusted subscriber to be located, you'll also have to
use the ``locate`` argument:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
Again, it's business as usual with an unproxied object:
.. doctest::
>>> subscribers = zope.component.subscribers((content, a1), IS)
>>> a3 = subscribers[0]
>>> a3.__class__ is A3
True
>>> a3.context == (content, a1)
True
>>> type(a3) is A3
True
With a proxied object, we again get a security-proxied subscriber:
.. doctest::
>>> p = ProxyFactory(content)
>>> a3 = zope.component.subscribers((p, a1), IS)[0]
>>> type(a3)
>>> removeSecurityProxy(a3).context[0] is content
True
However, thanks to the ``locate`` argument, we now have a location
proxy behind the security proxy:
.. doctest::
>>> type(removeSecurityProxy(a3))
Event subscriber (handlers)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes, subscribers don't need to be adapters that actually provide
anything. It's enough that a callable is called for a certain event.
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
In this case, simply getting the subscribers is enough to invoke them:
.. doctest::
>>> list(zope.component.subscribers((content, a1), None))
[]
>>> content.args == ((a1,),)
True
utility
-------
Apart from adapters (and subscription adapters), the Component
Architecture knows a second kind of component: utilities. They are
registered using the directive.
Before we register the first test utility, we can verify that utility
lookup doesn't work yet:
.. doctest::
>>> clearZCML()
>>> zope.component.queryUtility(IApp) is None
True
Then we register the utility:
.. doctest::
>>> runSnippet('''
... ''')
>>> zope.component.getUtility(IApp) is comp
True
Like adapters, utilities can also have names. There can be more than
one utility registered for a certain interface, as long as they each
have a different name.
First, we make sure that there's no utility yet:
.. doctest::
>>> clearZCML()
>>> zope.component.queryUtility(IApp, 'test') is None
True
Then we register it:
.. doctest::
>>> runSnippet('''
... ''')
>>> zope.component.getUtility(IApp, 'test') is comp
True
Utilities can also be registered from a factory. In this case, the
ZCML handler calls the factory (without any arguments) and registers
the returned value as a utility. Typically, you'd pass a class for
the factory:
.. doctest::
>>> clearZCML()
>>> zope.component.queryUtility(IApp) is None
True
>>> runSnippet('''
... ''')
>>> zope.component.getUtility(IApp).__class__ is Comp
True
Declaring ``provides`` in Python
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Like other directives, can also figure out which interface
a utility provides from the Python declaration:
.. doctest::
>>> clearZCML()
>>> zope.component.queryUtility(IApp) is None
True
>>> runSnippet('''
... ''')
>>> zope.component.getUtility(IApp) is comp
True
It won't work if the component that is to be registered doesn't
provide anything:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "", line 4.2-4.61
TypeError: Missing 'provides' attribute
Or if more than one interface is provided (then the ZCML directive
handler doesn't know under which the utility should be registered):
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "", line 4.2-4.61
TypeError: Missing 'provides' attribute
We can repeat the same drill for utility factories:
.. doctest::
>>> clearZCML()
>>> runSnippet('''
... ''')
>>> zope.component.getUtility(IApp).__class__ is Comp
True
>>> runSnippet('''
... ''')
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "", line 4.2-4.59
TypeError: Missing 'provides' attribute
>>> clearZCML()
>>> runSnippet('''
... ''')
Traceback (most recent call last):
...
ZopeXMLConfigurationError: File "", line 4.2-4.59
TypeError: Missing 'provides' attribute
Protected utilities
~~~~~~~~~~~~~~~~~~~
TODO::
def testProtectedUtility(self):
"""Test that we can protect a utility.
Also:
Check that multiple configurations for the same utility and
don't interfere.
"""
self.assertEqual(zope.component.queryUtility(IV), None)
xmlconfig(StringIO(template % (
'''
'''
)))
utility = ProxyFactory(zope.component.getUtility(IApp))
items = getTestProxyItems(utility)
self.assertEqual(items, [('a', 'tell.everyone'),
('f', 'tell.everyone')
])
self.assertEqual(removeSecurityProxy(utility), comp)
def testUtilityUndefinedPermission(self):
config = StringIO(template % (
'''
'''
))
self.assertRaises(ValueError, xmlconfig, config,
testing=1)
interface
---------
The directive lets us register an interface. Interfaces
are registered as named utilities. We therefore needn't go though all
the lookup details again, it is sufficient to see whether the
directive handler emits the right actions.
First we provide a stub configuration context:
.. doctest::
>>> import re, pprint
>>> atre = re.compile(' at [0-9a-fA-Fx]+')
>>> class Context(object):
... actions = ()
... def action(self, discriminator, callable, args):
... self.actions += ((discriminator, callable, args), )
... def __repr__(self):
... stream = StringIO()
... pprinter = pprint.PrettyPrinter(stream=stream, width=60)
... pprinter.pprint(self.actions)
... r = stream.getvalue()
... return (''.join(atre.split(r))).strip()
>>> context = Context()
Then we provide a test interface that we'd like to register:
.. doctest::
>>> from zope.interface import Interface
>>> class I(Interface):
... pass
It doesn't yet provide ``ITestType``:
.. doctest::
>>> from zope.component.tests.examples import ITestType
>>> ITestType.providedBy(I)
False
However, after calling the directive handler...
.. doctest::
>>> from zope.component.zcml import interface
>>> interface(context, I, ITestType)
>>> context
((None,
,
('',
,
)),)
...it does provide ``ITestType``:
.. doctest::
>>> from zope.interface.interfaces import IInterface
>>> ITestType.extends(IInterface)
True
>>> IInterface.providedBy(I)
True
zope.component-4.0.2/docs/index.rst 0000664 0001750 0001750 00000000462 11774411574 017207 0 ustar tseaver tseaver :mod:`zope.component`
=====================
Contents:
.. toctree::
:maxdepth: 2
narr
socketexample
event
factory
persistentregistry
zcml
configure
hooks
testlayer
api
hacking
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
zope.component-4.0.2/docs/factory.rst 0000664 0001750 0001750 00000006101 11774312422 017533 0 ustar tseaver tseaver Factories
=========
The Factory Class
-----------------
.. doctest::
>>> 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:
.. doctest::
>>> factory = Factory(Klass, 'Klass', 'Klassier')
Now we use the factory to create the instance
.. doctest::
>>> kl = factory(1, 2, foo=3, bar=4)
and make sure that the correct class was used to create the object:
.. doctest::
>>> kl.__class__
Since we passed in a couple positional and keyword arguments
.. doctest::
>>> kl.args
(1, 2)
>>> kl.kw
{'foo': 3, 'bar': 4}
>>> factory2(3)
3
>>> factory3(3)
3
Title and Description
~~~~~~~~~~~~~~~~~~~~~
.. doctest::
>>> factory.title
'Klass'
>>> factory.description
'Klassier'
>>> factory2.title
'Func'
>>> factory2.description
'Function'
>>> factory3.title
'Func'
>>> factory3.description
'Function'
Provided Interfaces
~~~~~~~~~~~~~~~~~~~
.. doctest::
>>> implemented = factory.getInterfaces()
>>> implemented.isOrExtends(IKlass)
True
>>> list(implemented)
[]
>>> implemented2 = factory2.getInterfaces()
>>> list(implemented2)
[]
>>> implemented3 = factory3.getInterfaces()
>>> list(implemented3)
[]
The Component Architecture Factory API
--------------------------------------
.. doctest::
>>> import zope.component
>>> factory = Factory(Klass, 'Klass', 'Klassier')
>>> gsm = zope.component.getGlobalSiteManager()
>>> from zope.component.interfaces import IFactory
>>> gsm.registerUtility(factory, IFactory, 'klass')
Creating an Object
~~~~~~~~~~~~~~~~~~
.. doctest::
>>> 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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doctest::
>>> implemented = zope.component.getFactoryInterfaces('klass')
>>> implemented.isOrExtends(IKlass)
True
>>> [iface for iface in implemented]
[]
List of All Factories
~~~~~~~~~~~~~~~~~~~~~
.. doctest::
>>> [(name, fac.__class__) for name, fac in
... zope.component.getFactoriesFor(IKlass)]
[(u'klass', )]
zope.component-4.0.2/docs/event.rst 0000664 0001750 0001750 00000007117 11774312422 017215 0 ustar tseaver tseaver Events
======
The Component Architecture provides a way to dispatch events to event
handlers. Event handlers are registered as *subscribers*
a.k.a. *handlers*.
Before we can start we need to import ``zope.component.event`` to make
the dispatching effective:
.. doctest::
>>> import zope.component.event
Consider two event classes:
.. doctest::
>>> class Event1(object):
... pass
>>> class Event2(Event1):
... pass
Now consider two handlers for these event classes:
.. doctest::
>>> called = []
>>> import zope.component
>>> @zope.component.adapter(Event1)
... def handler1(event):
... called.append(1)
>>> @zope.component.adapter(Event2)
... def handler2(event):
... called.append(2)
We can register them with the Component Architecture:
.. doctest::
>>> zope.component.provideHandler(handler1)
>>> zope.component.provideHandler(handler2)
Now let's go through the events. We'll see that the handlers have been
called accordingly:
.. doctest::
>>> from zope.event import notify
>>> notify(Event1())
>>> called
[1]
>>> del called[:]
>>> notify(Event2())
>>> called.sort()
>>> called
[1, 2]
Object events
-------------
The ``objectEventNotify`` function is a subscriber to dispatch
ObjectEvents to interested adapters.
First create an object class:
.. doctest::
>>> class IUseless(zope.interface.Interface):
... """Useless object"""
>>> class UselessObject(object):
... """Useless object"""
... zope.interface.implements(IUseless)
Then create an event class:
.. doctest::
>>> class IObjectThrownEvent(zope.component.interfaces.IObjectEvent):
... """An object has been thrown away"""
>>> class ObjectThrownEvent(zope.component.interfaces.ObjectEvent):
... """An object has been thrown away"""
... zope.interface.implements(IObjectThrownEvent)
Create an object and an event:
.. doctest::
>>> hammer = UselessObject()
>>> event = ObjectThrownEvent(hammer)
Then notify the event to the subscribers.
Since the subscribers list is empty, nothing happens.
.. doctest::
>>> zope.component.event.objectEventNotify(event)
Now create an handler for the event:
.. doctest::
>>> events = []
>>> def record(*args): #*
... events.append(args)
>>> zope.component.provideHandler(record, [IUseless, IObjectThrownEvent])
The event is notified to the subscriber:
.. doctest::
>>> zope.component.event.objectEventNotify(event)
>>> events == [(hammer, event)]
True
Following test demonstrates how a subscriber can raise an exception
to prevent an action.
.. doctest::
>>> zope.component.provideHandler(zope.component.event.objectEventNotify)
Let's create a container:
.. doctest::
>>> class ToolBox(dict):
... def __delitem__(self, key):
... notify(ObjectThrownEvent(self[key]))
... return super(ToolBox,self).__delitem__(key)
>>> container = ToolBox()
And put the object into the container:
.. doctest::
>>> container['Red Hammer'] = hammer
Create an handler function that will raise an error when called:
.. doctest::
>>> class Veto(Exception):
... pass
>>> def callback(item, event):
... assert(item == event.object)
... raise Veto
Register the handler:
.. doctest::
>>> zope.component.provideHandler(callback, [IUseless, IObjectThrownEvent])
Then if we try to remove the object, an ObjectThrownEvent is fired:
.. doctest::
>>> del container['Red Hammer']
... # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
raise Veto
Veto
zope.component-4.0.2/docs/narr.rst 0000664 0001750 0001750 00000030547 11774312422 017041 0 ustar tseaver tseaver 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:
.. doctest::
>>> 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]_:
.. doctest::
>>> 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`:
.. doctest::
>>> component.queryUtility(IGreeter, 'robert').greet()
Hello bob
>>> component.getUtility(IGreeter, 'robert').greet()
Hello bob
`queryUtility` and `getUtility` differ in how failed lookups are handled:
.. doctest::
>>> component.queryUtility(IGreeter, 'ted')
>>> component.queryUtility(IGreeter, 'ted', 42)
42
>>> component.getUtility(IGreeter, 'ted')
... # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ComponentLookupError: (, 'ted')
If a component provides only one interface, as in the example above,
then we can omit the provided interface from the call to `provideUtility`:
.. doctest::
>>> ted = Greeter('ted')
>>> component.provideUtility(ted, name='ted')
>>> component.queryUtility(IGreeter, 'ted').greet()
Hello ted
The name defaults to an empty string:
.. doctest::
>>> 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:
.. doctest::
>>> 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:
.. doctest::
>>> list(component.adaptedBy(PersonGreeter)) == [IPerson]
True
If an object makes no declaration, then None is returned:
.. doctest::
>>> 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]_:
.. doctest::
>>> 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:
.. doctest::
>>> 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.
.. doctest::
>>> 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:
.. doctest::
>>> class TedPersonGreeter(BobPersonGreeter):
... name = "Ted"
>>> component.provideAdapter(
... factory=TedPersonGreeter, adapts=[IPerson],
... provides=IGreeter, name='ted')
For named adapters, use `queryAdapter`, or `getAdapter`:
.. doctest::
>>> 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:
.. doctest::
>>> 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:
.. doctest::
>>> 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)
Note that the declaration-order of the Interfaces beeing adapted to is
important for adapter look up. It must be the the same as the order of
parameters given to the adapter and used to query the adapter. This is
especially the case when different Interfaces are adapt to (opposed to
this example).
To look up a multi-adapter, use either `queryMultiAdapter` or
`getMultiAdapter`:
.. doctest::
>>> 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 to declare that a callable object adapts some interfaces
(or classes):
.. doctest::
>>> class IJob(interface.Interface):
... "A job"
>>> @interface.implementer(IJob)
... class Job:
... pass
>>> @interface.implementer(IJob)
... @component.adapter(IPerson)
... def personJob(person):
... return getattr(person, 'job', None)
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:
.. doctest::
>>> 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:
.. doctest::
>>> 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:
.. doctest::
>>> 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:
.. doctest::
>>> 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:
.. doctest::
>>> 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:
.. doctest::
>>> 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]_:
.. doctest::
>>> component.provideSubscriptionAdapter(SingleLineSummary)
>>> component.provideSubscriptionAdapter(AdequateLength)
We can then use the subscribers to validate objects:
.. doctest::
>>> 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:
.. doctest::
>>> 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:
.. doctest::
>>> 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:
.. doctest::
>>> @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]_:
.. doctest::
>>> component.provideHandler(documentCreated)
Now, if we can create an event and use the `handle` function to call
handlers registered for the event:
.. doctest::
>>> 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.
zope.component-4.0.2/docs/hacking.rst 0000664 0001750 0001750 00000024241 11774411574 017505 0 ustar tseaver tseaver Hacking on :mod:`zope.component`
================================
Getting the Code
-----------------
The main repository for :mod:`zope.component` is in the Zope Subversion
repository:
http://svn.zope.org/zope.component
You can get a read-only Subversion checkout from there:
.. code-block:: sh
$ svn checkout svn://svn.zope.org/repos/main/zope.component/trunk zope.component
The project also mirrors the trunk from the Subversion repository as a
Bazaar branch on Launchpad:
https://code.launchpad.net/zope.component
You can branch the trunk from there using Bazaar:
.. code-block:: sh
$ bzr branch lp:zope.component
Running the tests in a ``virtualenv``
-------------------------------------
If you use the ``virtualenv`` package to create lightweight Python
development environments, you can run the tests using nothing more
than the ``python`` binary in a virtualenv. First, create a scratch
environment:
.. code-block:: sh
$ /path/to/virtualenv --no-site-packages /tmp/hack-zope.component
Next, get this package registered as a "development egg" in the
environment:
.. code-block:: sh
$ /tmp/hack-zope.component/bin/python setup.py develop
Finally, run the tests using the build-in ``setuptools`` testrunner:
.. code-block:: sh
$ /tmp/hack-zope.component/bin/python setup.py test
running test
........
----------------------------------------------------------------------
Ran 246 tests in 0.233s
OK
If you have the :mod:`nose` package installed in the virtualenv, you can
use its testrunner too:
.. code-block:: sh
$ /tmp/hack-zope.component/bin/easy_install nose
...
$ /tmp/hack-zope.component/bin/python setup.py nosetests
running nosetests
.......
----------------------------------------------------------------------
Ran 246 tests in 0.233s
OK
or:
.. code-block:: sh
$ /tmp/hack-zope.component/bin/nosetests
.......
----------------------------------------------------------------------
Ran 246 tests in 0.233s
OK
If you have the :mod:`coverage` pacakge installed in the virtualenv,
you can see how well the tests cover the code:
.. code-block:: sh
$ /tmp/hack-zope.component/bin/easy_install nose coverage
...
$ /tmp/hack-zope.component/bin/python setup.py nosetests \
--with coverage --cover-package=zope.component
running nosetests
...
Name Stmts Miss Cover Missing
-----------------------------------------------------------------
zope.component 41 0 100%
zope.component._api 132 0 100%
zope.component._compat 3 0 100%
zope.component._declaration 28 0 100%
zope.component.event 10 0 100%
zope.component.eventtesting 11 0 100%
zope.component.factory 20 0 100%
zope.component.globalregistry 38 0 100%
zope.component.hookable 14 0 100%
zope.component.hooks 66 0 100%
zope.component.interface 63 0 100%
zope.component.interfaces 63 0 100%
zope.component.persistentregistry 29 0 100%
zope.component.registry 24 0 100%
zope.component.security 65 0 100%
zope.component.standalonetests 4 1 75% 8
zope.component.zcml 200 0 100%
-----------------------------------------------------------------
TOTAL 811 1 99%
----------------------------------------------------------------------
Ran 260 tests in 1.308s
OK
Building the documentation in a ``virtualenv``
----------------------------------------------
:mod:`zope.component` uses the nifty :mod:`Sphinx` documentation system
for building its docs. Using the same virtualenv you set up to run the
tests, you can build the docs:
.. code-block:: sh
$ /tmp/hack-zope.component/bin/easy_install Sphinx
...
$ bin/sphinx-build -b html -d docs/_build/doctrees docs docs/_build/html
...
build succeeded.
You can also test the code snippets in the documentation:
.. code-block:: sh
$ bin/sphinx-build -b doctest -d docs/_build/doctrees docs docs/_build/doctest
...
Doctest summary
===============
130 tests
0 failures in tests
0 failures in setup code
build succeeded.
Testing of doctests in the sources finished, look at the \
results in _build/doctest/output.txt.
Running the tests using :mod:`zc.buildout`
-------------------------------------------
:mod:`zope.component` ships with its own :file:`buildout.cfg` file and
:file:`bootstrap.py` for setting up a development buildout:
.. code-block:: sh
$ /path/to/python2.6 bootstrap.py
...
Generated script '.../bin/buildout'
$ bin/buildout
Develop: '/home/tseaver/projects/Zope/BTK/component/.'
...
Generated script '.../bin/sphinx-quickstart'.
Generated script '.../bin/sphinx-build'.
You can now run the tests:
.. code-block:: sh
$ bin/test --all
Running zope.testing.testrunner.layer.UnitTests tests:
Set up zope.testing.testrunner.layer.UnitTests in 0.000 seconds.
Ran 246 tests with 0 failures and 0 errors in 0.366 seconds.
Tearing down left over layers:
Tear down zope.testing.testrunner.layer.UnitTests in 0.000 seconds.
Building the documentation using :mod:`zc.buildout`
---------------------------------------------------
The :mod:`zope.component` buildout installs the Sphinx scripts required to build
the documentation, including testing its code snippets:
.. code-block:: sh
$ cd docs
$ bin/sphinx-build -b doctest -d docs/_build/doctrees docs docs/_build/doctest
...
Doctest summary
===============
140 tests
0 failures in tests
0 failures in setup code
build succeeded.
Testing of doctests in the sources finished, look at the results in .../docs/_build/doctest/output.txt.
.../bin/sphinx-build -b html -d .../docs/_build/doctrees .../docs .../docs/_build/html
...
build succeeded.
Running Tests on Multiple Python Versions via :mod:`tox`
--------------------------------------------------------
`tox `_ is a Python-based test automation
tool designed to run tests against multiple Python versions. It creates
a ``virtualenv`` for each configured version, installs the current package
and configured dependencies into each ``virtualenv``, and then runs the
configured commands.
:mod:`zope.component` configures the following :mod:`tox` environments via
its ``tox.ini`` file:
- The ``py26`` environment builds a ``virtualenv`` with ``python2.6``,
installs :mod:`zope.component`, and runs the tests
via ``python setup.py test -q``.
- The ``py27`` environment builds a ``virtualenv`` with ``python2.7``,
installs :mod:`zope.component`, and runs the tests
via ``python setup.py test -q``.
- The ``py32`` environment builds a ``virtualenv`` with ``python3.2``,
installs :mod:`zope.component` and dependencies, and runs the tests
via ``python setup.py test -q``.
- The ``pypy`` environment builds a ``virtualenv`` with ``pypy``,
installs :mod:`zope.component`, and runs the tests
via ``python setup.py test -q``.
- The ``coverage`` environment builds a ``virtualenv`` with ``python2.6``,
installs :mod:`zope.component`, installs
:mod:`nose` and :mod:`coverage`, and runs ``nosetests`` with statement
coverage.
- The ``docs`` environment builds a virtualenv with ``python2.6``, installs
:mod:`zope.component`, installs ``Sphinx`` and
dependencies, and then builds the docs and exercises the doctest snippets.
This example requires that you have a working ``python2.6`` on your path,
as well as installing ``tox``:
.. code-block:: sh
$ tox -e py26
GLOB sdist-make: .../zope.interface/setup.py
py26 sdist-reinst: .../zope.interface/.tox/dist/zope.interface-4.0.2dev.zip
py26 runtests: commands[0]
..........
----------------------------------------------------------------------
Ran 246 tests in 0.233s
OK
___________________________________ summary ____________________________________
py26: commands succeeded
congratulations :)
Running ``tox`` with no arguments runs all the configured environments,
including building the docs and testing their snippets:
.. code-block:: sh
$ tox
GLOB sdist-make: .../zope.interface/setup.py
py26 sdist-reinst: .../zope.interface/.tox/dist/zope.interface-4.0.2dev.zip
py26 runtests: commands[0]
...
Doctest summary
===============
140 tests
0 failures in tests
0 failures in setup code
0 failures in cleanup code
build succeeded.
___________________________________ summary ____________________________________
py26: commands succeeded
py27: commands succeeded
py32: commands succeeded
pypy: commands succeeded
coverage: commands succeeded
docs: commands succeeded
congratulations :)
Submitting a Bug Report
-----------------------
:mod:`zope.component` tracks its bugs on Launchpad:
https://bugs.launchpad.net/zope.component
Please submit bug reports and feature requests there.
Sharing Your Changes
--------------------
.. note::
Please ensure that all tests are passing before you submit your code.
If possible, your submission should include new tests for new features
or bug fixes, although it is possible that you may have tested your
new code by updating existing tests.
If you got a read-only checkout from the Subversion repository, and you
have made a change you would like to share, the best route is to let
Subversion help you make a patch file:
.. code-block:: sh
$ svn diff > zope.component-cool_feature.patch
You can then upload that patch file as an attachment to a Launchpad bug
report.
If you branched the code from Launchpad using Bazaar, you have another
option: you can "push" your branch to Launchpad:
.. code-block:: sh
$ bzr push lp:~tseaver/zope.component/cool_feature
After pushing your branch, you can link it to a bug report on Launchpad,
or request that the maintainers merge your branch using the Launchpad
"merge request" feature.