././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681452282.1699712 zope.component-6.0/0000755000100100000240000000000014416166372013012 5ustar00macstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/CHANGES.rst0000644000100100000240000003355114416166371014622 0ustar00macstaff========= Changes ========= 6.0 (2023-04-14) ================ - Drop support for Python 2.7, 3.5, 3.6. 5.1.0 (2023-01-03) ================== - Fix crash when the environment variable `PYTHONOPTIMIZED` is set to `2` and docstrings are set to `None` by the interpreter. (`#67 `_) - Add support for Python 3.10 and 3.11. 5.0.1 (2021-07-09) ================== - Fix unregistering utilities on old persistent adapter registries. Previously this could raise ``TypeError``. See `issue 62 `_. 5.0.0 (2021-03-19) ================== - Remove backwards compatibility imports that were emitting deprecation warnings. This affects certain imports from ``zope.component.interfaces`` (which should be imported from ``zope.interface.interfaces``) as well as certain imports from ``zope.component.registery`` (import from ``zope.interface.registry``), and the entire ``zope.component.hookable`` module. See `issue 59 `_. - Respect permission value for utility factory registrations (`#54 `_) - Add support for Python 3.9 - Fix the ```` ZCML directive to allow a missing ``provides=`` attribute when a ``factory=`` is given and the Python object has been decorated with ``@implementer`` and implements a single interface. This has been documented, but hasn't worked before. See `issue 9 `_. - Make ``PersistentAdapterRegistry`` use persistent objects (``PersistentMapping`` and ``PersistentList``) for its internal data structures instead of plain dicts and lists. This helps make it scalable to larger registry sizes. This requires zope.interface 5.3.0a1 or later. New registries (and their primary users, ``PersistentComponents`` and zope.site's ``LocalSiteManager``) take full advantage of this automatically. For existing persistent registries to take advantage of this, you must call their ``rebuild()`` method and commit the transaction. See `issue 51 `_. - Fix ``zope.interface.interface.provideInterface`` and the various search and query methods to use the current site manager instead of always using the global site manager. (``provideInterface`` is called implicitly when registering components from ZCML.) The search and query methods continue to return interfaces registered in base site managers. See `issue 10 `_. 4.6.2 (2020-07-03) ================== - Improve the documentation, both published and in docstrings. See `PR 49 `_. 4.6.1 (2020-03-23) ================== - Ensure the resolution order of ``BaseGlobalComponents`` is consistent. See `issue 45 `_. 4.6.0 (2019-11-12) ================== - Add support for Python 3.8. - Drop support for Python 3.4. - Fix tests on Python 2 following changes in ZODB 5.5.0. 4.5.0 (2018-10-10) ================== - Add support for Python 3.7. - Always install ``zope.hookable`` as a dependency (the ``hook`` extra is now empty). ``zope.hookable`` respects the PURE_PYTHON environment variable, and has an optional C extension. - Make accessing names that have been moved to ``zope.interface`` produce a ``DeprecationWarning``. 4.4.1 (2017-09-26) ================== - Remove obsolete call of ``searchInterface`` from ``interfaceToName``. See https://github.com/zopefoundation/zope.component/issues/32 4.4.0 (2017-07-25) ================== - Add support for Python 3.6. - Drop support for Python 3.3. - Drop support for "setup.py test". - Code coverage reports are now `produced and hosted by coveralls.io `_, and PRs must keep them at 100%. - Internal test code in ``zope.component.testfiles`` has been adjusted and in some cases removed. 4.3.0 (2016-08-26) ================== - When testing ``PURE_PYTHON`` environments under ``tox``, avoid poisoning the user's global wheel cache. - Drop support for Python 2.6 and 3.2. - Add support for Python 3.5. 4.2.2 (2015-06-04) ================== - Fix test cases for PyPy and PyPy3. 4.2.1 (2014-03-19) ================== - Add support for Python 3.4. 4.2.0 (2014-02-05) ================== - Update ``boostrap.py`` to version 2.2. - Reset the cached ``adapter_hooks`` at ``zope.testing.cleanup.cleanUp`` time (LP1100501). - Implement ability to specify adapter and utility names in Python. Use the ``@zope.component.named(name)`` decorator to specify the name. 4.1.0 (2013-02-28) ================== - Change "ZODB3" depdendency to "persistent". - ``tox`` now runs all tests for Python 3.2 and 3.3. - Enable buildout for Python 3. - Fix new failing tests. 4.0.2 (2012-12-31) ================== - Flesh out PyPI Trove classifiers. 4.0.1 (2012-11-21) ================== - Add support for Python 3.3. 4.0.0 (2012-07-02) ================== - Add PyPy and Python 3.2 support: - Security support omitted until ``zope.security`` ported. - Persistent registry support omitted until ``ZODB`` ported (or ``persistent`` factored out). - Bring unit test coverage to 100%. - Remove the long-deprecated ``layer`` argument to the ``zope.component.zcml.view`` and ``zope.component.zcml.resource`` ZCML directives. - Add support for continuous integration using ``tox`` and ``jenkins``. - Got tests to run using ``setup.py test``. - Add ``Sphinx`` documentation. - Add ``setup.py docs`` alias (installs ``Sphinx`` and dependencies). - Add ``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) =================== - Move 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. - Move interfaces 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) =================== - Remove the ``docs`` extra and the ``sphinxdoc`` recipe. - Create a ``security`` extra to move security-related dependencies out of the ``test`` extra. - Use the new ``zope.testrunner`` package for tests. - Add 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 library ``doctest`` 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 change 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) ================== - Fix a bug introduced by recent refactoring, where passing ``CheckerPublic`` to ``securityAdapterFactory`` wrongly wrapped the factory into a ``LocatingUntrustedAdapterFactory``. 3.9.1 (2010-01-21) ================== - Modify the tests to avoid allowing the tested testrunner to be influenced by options of the outer testrunner, such a the ``-v`` option. 3.9.0 (2010-01-21) ================== - Add testlayer support. It is now possible to load a ZCML file within tests more easily. See ``src/zope/component/testlayer.py`` and ``src/zope/component/testlayer.txt``. 3.8.0 (2009-11-16) ================== - Remove the dependencies on ``zope.proxy`` and ``zope.security`` from the zcml extra: ``zope.component`` no longer has a hard dependency on them; the support for security proxied components ZCML registrations is enabled only if ``zope.security`` and ``zope.proxy`` are available. - Move 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. - Move 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) ================== - Fix a problem, where ``queryNextUtility`` could fail if the context could not be adapted to a ``IComponentLookup``. - Fix 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) ================== - Ensure that ``HookableTests`` are run by the testrunner. - Add ``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: - Move ``IView`` and ``IDefaultViewName`` to ``zope.publisher.interfaces``. - Move ``IResource`` to ``zope.app.publisher.interfaces``. - Remove ``IContextDependent``, ``IPresentation``, ``IPresentationRequest``, ``IResourceFactory``, and ``IViewFactory`` completely. If you used ``IViewFactory`` in context of ``zope.app.form``, there's now ``IWidgetFactory`` in the ``zope.app.form.interfaces`` instead. - Move ``getNextUtility`` / ``queryNextUtility`` functions here from ``zope.site`` (they were in ``zope.app.component`` even earlier). - Add a pure-Python ``hookable`` implementation, for use when ``zope.hookable`` is not present. - Remove 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. Fixes https://bugs.launchpad.net/zope3/+bug/240631 - Optimize ``un/registerUtility`` by 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. - Deprecated 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/CONTRIBUTING.md0000644000100100000240000000144414416166371015245 0ustar00macstaff # Contributing to zopefoundation projects The projects under the zopefoundation GitHub organization are open source and welcome contributions in different forms: * bug reports * code improvements and bug fixes * documentation improvements * pull request reviews For any changes in the repository besides trivial typo fixes you are required to sign the contributor agreement. See https://www.zope.dev/developer/becoming-a-committer.html for details. Please visit our [Developer Guidelines](https://www.zope.dev/developer/guidelines.html) if you'd like to contribute code changes and our [guidelines for reporting bugs](https://www.zope.dev/developer/reporting-bugs.html) if you want to file a bug report. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/COPYRIGHT.txt0000644000100100000240000000004014416166371015114 0ustar00macstaffZope Foundation and Contributors././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/LICENSE.txt0000644000100100000240000000402614416166371014636 0ustar00macstaffZope 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/MANIFEST.in0000644000100100000240000000056514416166371014555 0ustar00macstaff# Generated from: # https://github.com/zopefoundation/meta/tree/master/config/pure-python include *.md include *.rst include *.txt include buildout.cfg include tox.ini recursive-include docs *.py recursive-include docs *.rst recursive-include docs *.txt recursive-include docs Makefile recursive-include src *.py recursive-include docs *.bat recursive-include src *.zcml ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1681452282.170116 zope.component-6.0/PKG-INFO0000644000100100000240000004165314416166372014120 0ustar00macstaffMetadata-Version: 2.1 Name: zope.component Version: 6.0 Summary: Zope Component Architecture Home-page: https://github.com/zopefoundation/zope.component Author: Zope Foundation and Contributors Author-email: zope-dev@zope.dev License: ZPL 2.1 Project-URL: Documentation, https://zopecomponent.readthedocs.io/ Project-URL: Issue Tracker, https://github.com/zopefoundation/zope.component/issues Project-URL: Sources, https://github.com/zopefoundation/zope.component Keywords: interface component coupling loose utility adapter 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 :: 3 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Framework :: Zope :: 3 Classifier: Framework :: Zope :: 5 Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=3.7 Provides-Extra: hook Provides-Extra: persistentregistry Provides-Extra: security Provides-Extra: zcml Provides-Extra: mintests Provides-Extra: test Provides-Extra: docs License-File: LICENSE.txt ================ zope.component ================ .. image:: https://github.com/zopefoundation/zope.component/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.component/actions/workflows/tests.yml :alt: Unit test status .. image:: https://coveralls.io/repos/github/zopefoundation/zope.component/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.component?branch=master :alt: Coverage Status .. image:: https://img.shields.io/pypi/v/zope.component.svg :target: https://pypi.python.org/pypi/zope.component/ :alt: Current version on PyPI .. image:: https://img.shields.io/pypi/pyversions/zope.component :target: https://pypi.org/project/zope.component/ :alt: Supported Python versions .. image:: https://readthedocs.org/projects/zopecomponent/badge/?version=latest :target: http://zopecomponent.readthedocs.org/en/latest/ :alt: Documentation Status .. note:: 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 https://zopecomponent.readthedocs.io/en/latest/ for the documentation. .. _zope.interface: https://github.com/zopefoundation/zope.interface ========= Changes ========= 6.0 (2023-04-14) ================ - Drop support for Python 2.7, 3.5, 3.6. 5.1.0 (2023-01-03) ================== - Fix crash when the environment variable `PYTHONOPTIMIZED` is set to `2` and docstrings are set to `None` by the interpreter. (`#67 `_) - Add support for Python 3.10 and 3.11. 5.0.1 (2021-07-09) ================== - Fix unregistering utilities on old persistent adapter registries. Previously this could raise ``TypeError``. See `issue 62 `_. 5.0.0 (2021-03-19) ================== - Remove backwards compatibility imports that were emitting deprecation warnings. This affects certain imports from ``zope.component.interfaces`` (which should be imported from ``zope.interface.interfaces``) as well as certain imports from ``zope.component.registery`` (import from ``zope.interface.registry``), and the entire ``zope.component.hookable`` module. See `issue 59 `_. - Respect permission value for utility factory registrations (`#54 `_) - Add support for Python 3.9 - Fix the ```` ZCML directive to allow a missing ``provides=`` attribute when a ``factory=`` is given and the Python object has been decorated with ``@implementer`` and implements a single interface. This has been documented, but hasn't worked before. See `issue 9 `_. - Make ``PersistentAdapterRegistry`` use persistent objects (``PersistentMapping`` and ``PersistentList``) for its internal data structures instead of plain dicts and lists. This helps make it scalable to larger registry sizes. This requires zope.interface 5.3.0a1 or later. New registries (and their primary users, ``PersistentComponents`` and zope.site's ``LocalSiteManager``) take full advantage of this automatically. For existing persistent registries to take advantage of this, you must call their ``rebuild()`` method and commit the transaction. See `issue 51 `_. - Fix ``zope.interface.interface.provideInterface`` and the various search and query methods to use the current site manager instead of always using the global site manager. (``provideInterface`` is called implicitly when registering components from ZCML.) The search and query methods continue to return interfaces registered in base site managers. See `issue 10 `_. 4.6.2 (2020-07-03) ================== - Improve the documentation, both published and in docstrings. See `PR 49 `_. 4.6.1 (2020-03-23) ================== - Ensure the resolution order of ``BaseGlobalComponents`` is consistent. See `issue 45 `_. 4.6.0 (2019-11-12) ================== - Add support for Python 3.8. - Drop support for Python 3.4. - Fix tests on Python 2 following changes in ZODB 5.5.0. 4.5.0 (2018-10-10) ================== - Add support for Python 3.7. - Always install ``zope.hookable`` as a dependency (the ``hook`` extra is now empty). ``zope.hookable`` respects the PURE_PYTHON environment variable, and has an optional C extension. - Make accessing names that have been moved to ``zope.interface`` produce a ``DeprecationWarning``. 4.4.1 (2017-09-26) ================== - Remove obsolete call of ``searchInterface`` from ``interfaceToName``. See https://github.com/zopefoundation/zope.component/issues/32 4.4.0 (2017-07-25) ================== - Add support for Python 3.6. - Drop support for Python 3.3. - Drop support for "setup.py test". - Code coverage reports are now `produced and hosted by coveralls.io `_, and PRs must keep them at 100%. - Internal test code in ``zope.component.testfiles`` has been adjusted and in some cases removed. 4.3.0 (2016-08-26) ================== - When testing ``PURE_PYTHON`` environments under ``tox``, avoid poisoning the user's global wheel cache. - Drop support for Python 2.6 and 3.2. - Add support for Python 3.5. 4.2.2 (2015-06-04) ================== - Fix test cases for PyPy and PyPy3. 4.2.1 (2014-03-19) ================== - Add support for Python 3.4. 4.2.0 (2014-02-05) ================== - Update ``boostrap.py`` to version 2.2. - Reset the cached ``adapter_hooks`` at ``zope.testing.cleanup.cleanUp`` time (LP1100501). - Implement ability to specify adapter and utility names in Python. Use the ``@zope.component.named(name)`` decorator to specify the name. 4.1.0 (2013-02-28) ================== - Change "ZODB3" depdendency to "persistent". - ``tox`` now runs all tests for Python 3.2 and 3.3. - Enable buildout for Python 3. - Fix new failing tests. 4.0.2 (2012-12-31) ================== - Flesh out PyPI Trove classifiers. 4.0.1 (2012-11-21) ================== - Add support for Python 3.3. 4.0.0 (2012-07-02) ================== - Add PyPy and Python 3.2 support: - Security support omitted until ``zope.security`` ported. - Persistent registry support omitted until ``ZODB`` ported (or ``persistent`` factored out). - Bring unit test coverage to 100%. - Remove the long-deprecated ``layer`` argument to the ``zope.component.zcml.view`` and ``zope.component.zcml.resource`` ZCML directives. - Add support for continuous integration using ``tox`` and ``jenkins``. - Got tests to run using ``setup.py test``. - Add ``Sphinx`` documentation. - Add ``setup.py docs`` alias (installs ``Sphinx`` and dependencies). - Add ``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) =================== - Move 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. - Move interfaces 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) =================== - Remove the ``docs`` extra and the ``sphinxdoc`` recipe. - Create a ``security`` extra to move security-related dependencies out of the ``test`` extra. - Use the new ``zope.testrunner`` package for tests. - Add 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 library ``doctest`` 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 change 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) ================== - Fix a bug introduced by recent refactoring, where passing ``CheckerPublic`` to ``securityAdapterFactory`` wrongly wrapped the factory into a ``LocatingUntrustedAdapterFactory``. 3.9.1 (2010-01-21) ================== - Modify the tests to avoid allowing the tested testrunner to be influenced by options of the outer testrunner, such a the ``-v`` option. 3.9.0 (2010-01-21) ================== - Add testlayer support. It is now possible to load a ZCML file within tests more easily. See ``src/zope/component/testlayer.py`` and ``src/zope/component/testlayer.txt``. 3.8.0 (2009-11-16) ================== - Remove the dependencies on ``zope.proxy`` and ``zope.security`` from the zcml extra: ``zope.component`` no longer has a hard dependency on them; the support for security proxied components ZCML registrations is enabled only if ``zope.security`` and ``zope.proxy`` are available. - Move 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. - Move 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) ================== - Fix a problem, where ``queryNextUtility`` could fail if the context could not be adapted to a ``IComponentLookup``. - Fix 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) ================== - Ensure that ``HookableTests`` are run by the testrunner. - Add ``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: - Move ``IView`` and ``IDefaultViewName`` to ``zope.publisher.interfaces``. - Move ``IResource`` to ``zope.app.publisher.interfaces``. - Remove ``IContextDependent``, ``IPresentation``, ``IPresentationRequest``, ``IResourceFactory``, and ``IViewFactory`` completely. If you used ``IViewFactory`` in context of ``zope.app.form``, there's now ``IWidgetFactory`` in the ``zope.app.form.interfaces`` instead. - Move ``getNextUtility`` / ``queryNextUtility`` functions here from ``zope.site`` (they were in ``zope.app.component`` even earlier). - Add a pure-Python ``hookable`` implementation, for use when ``zope.hookable`` is not present. - Remove 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. Fixes https://bugs.launchpad.net/zope3/+bug/240631 - Optimize ``un/registerUtility`` by 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. - Deprecated 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/README.rst0000644000100100000240000000276414416166371014511 0ustar00macstaff================ zope.component ================ .. image:: https://github.com/zopefoundation/zope.component/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.component/actions/workflows/tests.yml :alt: Unit test status .. image:: https://coveralls.io/repos/github/zopefoundation/zope.component/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.component?branch=master :alt: Coverage Status .. image:: https://img.shields.io/pypi/v/zope.component.svg :target: https://pypi.python.org/pypi/zope.component/ :alt: Current version on PyPI .. image:: https://img.shields.io/pypi/pyversions/zope.component :target: https://pypi.org/project/zope.component/ :alt: Supported Python versions .. image:: https://readthedocs.org/projects/zopecomponent/badge/?version=latest :target: http://zopecomponent.readthedocs.org/en/latest/ :alt: Documentation Status .. note:: 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 https://zopecomponent.readthedocs.io/en/latest/ for the documentation. .. _zope.interface: https://github.com/zopefoundation/zope.interface ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/buildout.cfg0000644000100100000240000000122414416166371015320 0ustar00macstaff[buildout] develop = . parts = test test_c_hookable python 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 = py eggs = ${test:eggs} ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681452282.1468105 zope.component-6.0/docs/0000755000100100000240000000000014416166372013742 5ustar00macstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/Makefile0000644000100100000240000001275014416166371015406 0ustar00macstaff# 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." ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1681452282.151448 zope.component-6.0/docs/api/0000755000100100000240000000000014416166372014513 5ustar00macstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api/adapter.rst0000644000100100000240000002602014416166371016664 0ustar00macstaff=========================== Adapter Registration APIs =========================== This document covers a specific subset of the APIs in :mod:`zope.component`. .. currentmodule:: zope.component .. testsetup:: from zope.component.testing import setUp setUp() .. autofunction:: zope.component.provideAdapter .. autofunction:: zope.component.provideHandler .. autofunction:: zope.component.provideSubscriptionAdapter 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 `zope.interface.interface.adapter_hooks`, 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 `zope.interface.interfaces.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`` (note that the names are always text strings, meaning that on Python 2 the names will be ``unicode``): .. doctest:: >>> from zope.component import getAdapters >>> adapters = sorted(getAdapters((ob,), I5)) >>> [(str(name), adapter.__class__.__name__) for name, adapter in adapters] [('', 'Comp'), ('foo', 'Comp')] >>> try: ... text = unicode ... except NameError: ... text = str # Python 3 >>> [isinstance(name, text) for name, _ in adapters] [True, True] 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)) >>> [(str(name), adapter.__class__.__name__) for name, adapter in adapters] [('', 'Comp'), ('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() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api/factory.rst0000644000100100000240000000062314416166371016714 0ustar00macstaff============== Factory APIs ============== There are APIs for creating objects and discovering factories. .. autofunction:: zope.component.createObject .. autofunction:: zope.component.getFactoryInterfaces .. autofunction:: zope.component.getFactoriesFor Supporting APIs =============== Module ``zope.component.factory`` includes some supporting objects. .. automodule:: zope.component.factory ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api/hooks.rst0000644000100100000240000000045314416166371016371 0ustar00macstaff========================================================== ``zope.component.hooks``: The current component registry ========================================================== .. seealso:: :doc:`../hooks` for narrative documentation and examples. .. automodule:: zope.component.hooks :noindex: ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api/interface.rst0000644000100100000240000001167214416166371017213 0ustar00macstaffInterface 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 >>> [str(x) for x in searchInterfaceIds(None, 'zope.component.tests.examples.ISII')] ['zope.component.tests.examples.ISII'] .. testcleanup:: from zope.component.testing import tearDown tearDown() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api/interfaces.rst0000644000100100000240000000016214416166371017366 0ustar00macstaff======================= Interface Definitions ======================= .. automodule:: zope.component.interfaces ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api/module.rst0000644000100100000240000000070714416166371016535 0ustar00macstaff============================================ ``zope.component``: Module-level functions ============================================ This document provides a summary of the APIs available directly from ``zope.component``. For more details, see the remaining documentation. .. These are generally explored in more detail in specific documentation, so default indexing should go to that instead of here. .. automodule:: zope.component :noindex: ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api/persistent.rst0000644000100100000240000001402614416166371017447 0ustar00macstaff======================= Persistent Registries ======================= .. testsetup:: from zope.component.testing import setUp setUp() .. automodule:: zope.component.persistentregistry 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.MappingStorage >>> db = ZODB.MappingStorage.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.MappingStorage >>> db = ZODB.MappingStorage.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 implementer >>> class IFoo(Interface): ... pass >>> @implementer(IFoo) ... class Foo(persistent.Persistent): ... 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.MappingStorage >>> db = ZODB.MappingStorage.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() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api/security.rst0000644000100100000240000000505714416166371017122 0ustar00macstaffSecurity 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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api/sitemanager.rst0000644000100100000240000000444114416166371017546 0ustar00macstaffSite Manager APIs ================= .. autofunction:: zope.component.getGlobalSiteManager The API returns the module-scope global registry: .. doctest:: >>> from zope.interface.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.interface.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', , ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api/utility.rst0000644000100100000240000001665214416166371016761 0ustar00macstaff=========================== Utility Registration APIs =========================== .. autofunction:: zope.component.provideUtility .. 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.interface.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() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/api.rst0000644000100100000240000000045614416166371015251 0ustar00macstaff===================================== ``zope.component`` API Reference ===================================== .. toctree:: :maxdepth: 2 api/module api/interfaces api/sitemanager api/utility api/adapter api/factory api/interface api/security api/persistent api/hooks ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/changelog.rst0000644000100100000240000000003414416166371016417 0ustar00macstaff.. include:: ../CHANGES.rst ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/conf.py0000644000100100000240000002260014416166371015240 0ustar00macstaff# -*- coding: utf-8 -*- # # zope.component 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 # We get better doc strings and signatures from the Python components. # XXX: Except CPython 2.7 produces some warnings from CFFI with persistent 4.6.3: # From callback for ffi.gc : # Traceback (most recent call last): # File "//.tox/docs/lib/python2.7/site-packages/persistent/picklecache.py", line 105, in cleanup_hook # oid = self._addr_to_oid.pop(cdata.pobj_id, None) # AttributeError: '_WeakValueDictionary' object has no attribute '_addr_to_oid' #os.environ['PURE_PYTHON'] = "1" # Prior to https://github.com/zopefoundation/zope.security/issues/71, # zope.security cannot be imported in zope.interface's strict IRO mode. os.environ['ZOPE_INTERFACE_STRICT_IRO'] = "0" # 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('.')) sys.path.append(os.path.abspath('../src')) import pkg_resources rqmt = pkg_resources.require('zope.component')[0] # -- 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', 'sphinx.ext.extlinks', 'sphinx.ext.intersphinx', '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.component' 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 = '%s.%s' % tuple(map(int, rqmt.version.split('.')[:2])) # The full version, including alpha/beta/rc tags. release = rqmt.version # 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 = "obj" # 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 = 'zopecomponentdoc' # -- 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', 'zopecomponent.tex', u'zope.component 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', 'zopecomponent', u'zope.component 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', 'zopecomponent', u'zope.component Documentation', u'Zope Foundation Contributors', 'zopecomponent', '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 # Sphinx 1.8+ prefers this to `autodoc_default_flags`. It's documented that # either True or None mean the same thing as just setting the flag, but # only None works in 1.8 (True works in 2.0) autodoc_default_options = { 'members': None, 'show-inheritance': None, } autodoc_member_order = 'groupwise' autoclass_content = 'both' # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' intersphinx_mapping = { 'https://docs.python.org/3/': None, 'https://zopeinterface.readthedocs.io/en/latest/': None, 'https://zopesecurity.readthedocs.io/en/latest/': None, 'https://zopeevent.readthedocs.io/en/latest/': None, 'https://persistent.readthedocs.io/en/latest/': None, } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/configure.rst0000644000100100000240000000206714416166371016461 0ustar00macstaff======================= 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() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/event.rst0000644000100100000240000001002214416166371015607 0ustar00macstaff============================================== ``zope.component.events``: Event dispatching ============================================== .. currentmodule:: zope.component.event The Component Architecture provides a way to dispatch events to event handlers using :func:`zope.event.notify`. 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. .. autofunction:: objectEventNotify .. note:: This function is automatically registered as a subscriber for :class:`zope.interface.interfaces.IObjectEvent` when the ZCML configuration for this package is loaded. First create an object class: .. doctest:: >>> class IUseless(zope.interface.Interface): ... """Useless object""" >>> @zope.interface.implementer(IUseless) ... class UselessObject(object): ... """Useless object""" Then create an event class: .. doctest:: >>> class IObjectThrownEvent(zope.interface.interfaces.IObjectEvent): ... """An object has been thrown away""" >>> @zope.interface.implementer(IObjectThrownEvent) ... class ObjectThrownEvent(zope.interface.interfaces.ObjectEvent): ... """An object has been thrown away""" 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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/factory.rst0000644000100100000240000000624214416166371016146 0ustar00macstaff======================================================= ``zope.component.factory``: Object Creation Factories ======================================================= See :mod:`zope.component.factory` for API documentation. The Factory Class ================= .. doctest:: >>> from zope.interface import Interface >>> class IFunction(Interface): ... pass >>> class IKlass(Interface): ... pass >>> from zope.interface import implementer >>> @implementer(IKlass) ... class Klass(object): ... ... 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) and make sure that the correct class was used to create the object: .. doctest:: >>> kl.__class__ Since we passed in a couple positional and a keyword argument .. doctest:: >>> kl.args (1, 2) >>> kl.kw {'foo': 3} >>> 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) == [IKlass] True >>> implemented2 = factory2.getInterfaces() >>> list(implemented2) [] >>> implemented3 = factory3.getInterfaces() >>> list(implemented3) == [IFunction] True 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) >>> isinstance(kl, Klass) True >>> kl.args (1, 2) >>> kl.kw {'foo': 3} Accessing Provided Interfaces ----------------------------- .. doctest:: >>> implemented = zope.component.getFactoryInterfaces('klass') >>> implemented.isOrExtends(IKlass) True >>> [iface for iface in implemented] == [IKlass] True List of All Factories --------------------- .. doctest:: >>> [(str(name), fac.__class__) for name, fac in ... zope.component.getFactoriesFor(IKlass)] [('klass', )] ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/hacking.rst0000644000100100000240000002450214416166371016102 0ustar00macstaffHacking on :mod:`zope.component` ================================ Getting the Code ################ The main repository for :mod:`zope.component` is in the Zope Foundation Github repository: https://github.com/zopefoundation/zope.component You can get a read-only checkout from there: .. code-block:: sh $ git clone https://github.com/zopefoundation/zope.component.git or fork it and get a writeable checkout of your fork: .. code-block:: sh $ git clone git@github.com/jrandom/zope.component.git The project also mirrors the trunk from the Github 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 Working in a ``virtualenv`` ########################### Installing ---------- 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 Running the tests ----------------- Run the tests using the build-in ``setuptools`` testrunner: .. code-block:: sh $ /tmp/hack-zope.component/bin/python setup.py test -q ......................................................................................................................................................................................................................................................... ---------------------------------------------------------------------- Ran 249 tests in 0.000s 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/nosetests ....................................................................................................................................................................................................................................................................... ---------------------------------------------------------------------- Ran 263 tests in 0.000s 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/nosetests --with coverage ....................................................................................................................................................................................................................................................................... Name Stmts Miss Cover Missing -------------------------------------------------------------------- zope/component.py 42 0 100% zope/component/_api.py 132 0 100% zope/component/_compat.py 3 0 100% zope/component/_declaration.py 30 0 100% zope/component/event.py 10 0 100% zope/component/eventtesting.py 11 0 100% zope/component/factory.py 20 0 100% zope/component/globalregistry.py 38 0 100% zope/component/hookable.py 14 0 100% zope/component/hooks.py 70 0 100% zope/component/interface.py 63 0 100% zope/component/interfaces.py 63 0 100% zope/component/persistentregistry.py 32 0 100% zope/component/registry.py 24 0 100% zope/component/security.py 65 0 100% zope/component/standalonetests.py 2 0 100% zope/component/zcml.py 207 0 100% -------------------------------------------------------------------- TOTAL 826 0 100% ---------------------------------------------------------------------- Ran 263 tests in 0.000s OK Building the documentation -------------------------- :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 repoze.sphinx.autoitnerface zope.component ... $ cd docs $ PATH=/tmp/hack-zope.component/bin:$PATH make html sphinx-build -b html -d _build/doctrees . _build/html ... build succeeded. Build finished. The HTML pages are in _build/html. You can also test the code snippets in the documentation: .. code-block:: sh $ PATH=/tmp/hack-zope.component/bin:$PATH make doctest sphinx-build -b doctest -d _build/doctrees . _build/doctest ... running tests... ... Doctest summary =============== 964 tests 0 failures in tests 0 failures in setup code 0 failures in cleanup code build succeeded. Testing of doctests in the sources finished, look at the results in _build/doctest/output.txt. Using :mod:`zc.buildout` ######################## Setting up the 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.7 bootstrap.py ... Generated script '.../bin/buildout' $ bin/buildout Develop: '/home/jrandom/projects/Zope/zope.component/.' ... Got coverage 3.7.1 Running the tests ----------------- 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 249 tests with 0 failures and 0 errors in 0.000 seconds. Tearing down left over layers: Tear down zope.testing.testrunner.layer.UnitTests in 0.000 seconds. Using :mod:`tox` ################ Running Tests on Multiple Python Versions ----------------------------------------- `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``, ``py27``, ``py33``, ``py34``, and ``pypy`` environments builds a ``virtualenv`` with the appropriate interpreter, installs :mod:`zope.component` and dependencies, 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: /home/tseaver/projects/Zope/Z3/zopetoolkit/src/zope.component/setup.py py26 inst-nodeps: /home/tseaver/projects/Zope/Z3/zopetoolkit/src/zope.component/.tox/dist/zope.component-4.2.2.dev0.zip py26 runtests: PYTHONHASHSEED='3711600167' py26 runtests: commands[0] | python setup.py test -q running test ... running build_ext ......................................................................................................................................................................................................................................................... ---------------------------------------------------------------------- Ran 249 tests 0.000s 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.component/setup.py py26 sdist-reinst: .../zope.component/.tox/dist/zope.component-4.0.2dev.zip ... Doctest summary =============== 964 tests 0 failures in tests 0 failures in setup code 0 failures in cleanup code build succeeded. ___________________________________ summary ____________________________________ py26: commands succeeded py26min: commands succeeded py27: commands succeeded pypy: commands succeeded py32: commands succeeded py33: commands succeeded py34: commands succeeded coverage: commands succeeded docs: commands succeeded congratulations :) Contributing to :mod:`zope.component` ##################################### Submitting a Bug Report ----------------------- :mod:`zope.component` tracks its bugs on Github: https://github.com/zopefoundation/zope.component/issues 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 have made a change you would like to share, the best route is to fork the Githb repository, check out your fork, make your changes on a branch in your fork, and push it. You can then submit a pull request from your branch: https://github.com/zopefoundation/zope.component/pulls 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:~jrandom/zope.component/cool_feature After pushing your branch, you can link it to a bug report on Github, or request that the maintainers merge your branch using the Launchpad "merge request" feature. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/hooks.rst0000644000100100000240000000732514416166371015625 0ustar00macstaff========================================================== ``zope.component.hooks``: The current component registry ========================================================== .. currentmodule:: zope.component.hooks 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 :mod:`zope.component.hooks` module provides an API to set and access the current site as well as manipulate the adapter hook associated with it. .. autofunction:: getSite 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: .. autofunction:: getSiteManager .. 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`: .. autofunction:: setSite .. 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 However, the default `zope.component.getSiteManager` function isn't yet aware of this: .. doctest:: >>> from zope.component import getSiteManager as global_getSiteManager >>> global_getSiteManager() To integrate that with the notion of the current site, we need to call ``setHooks``: .. autofunction:: setHooks .. doctest:: >>> from zope.component.hooks import setHooks >>> setHooks() >>> getSiteManager() is site2.registry True >>> global_getSiteManager() is site2.registry True This can be reversed using ``resetHooks``: .. autofunction:: resetHooks .. doctest:: >>> from zope.component.hooks import resetHooks >>> resetHooks() >>> global_getSiteManager() 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: .. autofunction:: site .. 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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/index.rst0000644000100100000240000000053614416166371015606 0ustar00macstaff:mod:`zope.component` ===================== Contents: .. toctree:: :maxdepth: 1 changelog .. toctree:: :maxdepth: 2 narr socketexample event factory persistentregistry zcml configure hooks testlayer api hacking Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/make.bat0000644000100100000240000001177614416166371015362 0ustar00macstaff@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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/narr.rst0000644000100100000240000003105514416166371015441 0ustar00macstaffZope Component Architecture =========================== .. currentmodule:: zope.component This package, together with :mod:`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 __future__ import print_function >>> from zope import interface >>> class IGreeter(interface.Interface): ... def greet(): ... "say hello" >>> @interface.implementer(IGreeter) ... class Greeter(object): ... ... def __init__(self, other="world"): ... self.other = other ... ... def greet(self): ... print(("Hello %s" % (self.other))) We can register an instance this class using :func:`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 :func:`queryUtility` or :func:`getUtility`: .. doctest:: >>> component.queryUtility(IGreeter, 'robert').greet() Hello bob >>> component.getUtility(IGreeter, 'robert').greet() Hello bob :func:`queryUtility` and :func:`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 :func:`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") >>> @component.adapter(IPerson) ... @interface.implementer(IGreeter) ... class PersonGreeter(object): ... ... 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 :func:`adapter` 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:: >>> @interface.implementer(IPerson) ... class Person(object): ... ... 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 :func:`queryAdapter`, or :func:`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, :func:`queryAdapter` returns a default value and :func:`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:: >>> @component.adapter(IPerson, IPerson) ... @interface.implementer(IGreeter) ... class TwoPersonGreeter(object): ... ... 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 :func:`queryMultiAdapter` or :func:`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") >>> @interface.implementer(IDocument) ... class Document(object): ... 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:: >>> @component.adapter(IDocument) ... @interface.implementer(IValidate) ... class SingleLineSummary(object): ... ... 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:: >>> @component.adapter(IDocument) ... @interface.implementer(IValidate) ... class AdequateLength(object): ... 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") >>> @interface.implementer(IDocumentCreated) ... class DocumentCreated(object): ... ... 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 :func:`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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/persistentregistry.rst0000644000100100000240000000065014416166371020465 0ustar00macstaff======================================================================== ``zope.component.persistentregistry``: Persistent Component Management ======================================================================== Persistent component management allows persistent management of components. From a usage point of view, there shouldn't be any new behavior. See :mod:`zope.component.persistentregistry` for API details. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/socketexample.rst0000644000100100000240000005337114416166371017350 0ustar00macstaffThe 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 components 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, implementer >>> class IGermanSocket(Interface): ... pass >>> class Socket(object): ... def __repr__(self): ... return '' %self.__class__.__name__ >>> @implementer(IGermanSocket) ... class GermanSocket(Socket): ... """German wall socket.""" 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:: >>> @implementer(IUSSocket) ... class GermanToUSSocketAdapter(Socket): ... __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 >>> @implementer(ICzechSocket) ... class CzechSocket(Socket): ... pass >>> 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:: >>> @implementer(IUSSocket) ... class GermanToUSSocketAdapterAndTransformer(object): ... __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 = sorted([str(name) for name, socket in sockets]) >>> names ['', 'dvd', 'shaver'] :func:`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. Note that the names are always text strings, meaning ``unicode`` on Python 2: .. doctest:: >>> try: ... text = unicode ... except NameError: ... text = str >>> [isinstance(name, text) for name, _ in sockets] [True, True, True] 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 >>> @implementer(IGrounder) ... class Grounder(object): ... def __repr__(self): ... return '' Then together they will provided a grounded us socket: .. doctest:: >>> @implementer(IUSGroundedSocket) ... class GroundedGermanToUSSocketAdapter(object): ... __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 >>> @implementer(IFire) ... class Fire(object): ... pass >>> fire = Fire() We want to use all available objects to put out the fire: .. doctest:: >>> class IFireExtinguisher(Interface): ... def extinguish(): ... pass >>> from functools import total_ordering >>> @total_ordering ... class FireExtinguisher(object): ... def __init__(self, fire): ... pass ... def extinguish(self): ... "Place extinguish code here." ... print('Used ' + self.__class__.__name__ + '.') ... def __lt__(self, other): ... return type(self).__name__ < type(other).__name__ ... def __eq__(self, other): ... return self is other 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:: >>> @implementer(IUSSocket) ... class Generator(object): ... 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:: >>> @implementer(IUSSocket) ... class SolarPanel(object): ... 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 = sorted(list(zope.component.getUtilitiesFor(IUSSocket))) >>> [(str(name), socket) for name, socket in utils] [('', ), ('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 = sorted(list(zope.component.getAllUtilitiesRegisteredFor(IUSSocket)), ... key=lambda x: type(x).__name__) >>> 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 = sorted([(name, factory.__class__) for name, factory in factories]) >>> [(str(name), kind) for name, kind in factories] [('Generator', ), ('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.interface.interfaces import IComponentLookup >>> IComponentLookup.providedBy(gsm) True >>> from zope.interface.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`. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/testlayer.rst0000644000100100000240000001015014416166371016504 0ustar00macstaff=========================================== ``zope.component.testlayer``: Test Layers =========================================== .. currentmodule:: zope.component.testlayer .. module:: zope.component.testlayer ``zope.component.testlayer`` defines two things: * a `LayerBase` that makes it easier and saner to use zope.testing's test layers. * a `ZCMLFileLayer` which lets you implement a layer that loads up some ZCML. LayerBase ========= .. autoclass:: 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, 0 errors and 0 skipped in ... seconds. Tearing down left over layers: Tear down zope.component.OurLayer tearDown called in ... seconds. ZCMLFileLayer ============= .. autoclass:: ZCMLFileLayer 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``. We can also choose to provide extra ZCML features that are used `to conditionally control processing of certain directives `_ (here we use "devmode", a common condition for controlling development options like debugging output). .. doctest:: >>> from zope.component.testlayer import ZCMLFileLayer >>> import zope.component.testfiles >>> zcml_file_layer = ZCMLFileLayer( ... zope.component.testfiles, ... 'testlayer.zcml', ... features=["devmode"]) >>> class TestCase(unittest.TestCase): ... layer = zcml_file_layer ... ... def testFoo(self): ... # The feature was registered ... self.assertTrue(self.layer.context.hasFeature('devmode')) ... # we should now have the adapter registered ... from zope import component ... from zope.component.testfiles import components ... self.assertIsInstance( ... 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, 0 errors and 0 skipped in ... seconds. Tearing down left over layers: Tear down zope.component.testfiles.ZCMLFileLayer in ... seconds. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/docs/zcml.rst0000644000100100000240000010160314416166371015441 0ustar00macstaffZCML 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 io import BytesIO >>> from zope.configuration.xmlconfig import xmlconfig >>> def runSnippet(snippet): ... template = """\ ... ... %s ... """ ... xmlconfig(BytesIO((template % snippet).encode("ascii"))) 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:: >>> import zope.component >>> from zope.component.tests.examples import clearZCML >>> clearZCML() >>> 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): ... ComponentConfigurationError: No factory specified File "", line 4.2-8.8 Declaring ``for``, ``provides`` and ``name`` in Python ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The directive can figure out from the in-line Python declaration (using ``zope.component.adapts()`` or ``zope.component.adapter()``, ``zope.interface.implements`` as well as ``zope.component.named``) 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 Let's now register an adapter that has a name specified in Python: >>> runSnippet(''' ... ''') >>> zope.component.getAdapter(Content(), IApp, 'app').__class__ 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 >>> @zope.interface.implementer(IContent) ... class MyContent(object): ... pass >>> 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): ... ComponentConfigurationError: Can't use multiple factories and multiple for File "", line 4.2-11.8 And neither for null-adapters: .. doctest:: >>> clearZCML() >>> runSnippet(''' ... ''') Traceback (most recent call last): ... ComponentConfigurationError: Can't use multiple factories and multiple for File "", line 4.2-9.8 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) <... 'zope.security...proxy...Proxy...'> 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) <... 'zope.security...proxy...Proxy...'> 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) <... 'zope.security...proxy...Proxy...'> >>> 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) <... 'zope.security...proxy...Proxy...'> >>> 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), I3) >>> 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) <... 'zope.security...proxy...Proxy...'> 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) <... 'zope.security...proxy...Proxy...'> >>> 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 Declaring ``name`` in Python ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Let's now register a utility that has a name specified in Python: >>> runSnippet(''' ... ''') >>> from zope.component.testfiles.components import comp4 >>> zope.component.getUtility(IApp, name='app') is comp4 True >>> runSnippet(''' ... ''') >>> zope.component.getUtility(IApp, name='app') is comp4 False >>> zope.component.getUtility(IApp, name='app').__class__ 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 >>> try: ... from cStringIO import StringIO ... except ImportError: ... from io import StringIO >>> 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 (u''.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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/rtd.txt0000644000100100000240000000027214416166371014344 0ustar00macstaffpersistent repoze.sphinx.autointerface BTrees ZODB zope.component zope.configuration zope.hookable zope.i18nmessageid zope.location zope.proxy zope.security zope.testing zope.testrunner ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681452282.1707325 zope.component-6.0/setup.cfg0000644000100100000240000000106114416166372014631 0ustar00macstaff[bdist_wheel] universal = 0 [flake8] doctests = 1 per-file-ignores = src/zope/component/__init__.py: F401 [check-manifest] ignore = .editorconfig .meta.toml docs/_build/html/_sources/* docs/_build/doctest/* docs/_build/html/_sources/api/* [isort] force_single_line = True combine_as_imports = True sections = FUTURE,STDLIB,THIRDPARTY,ZOPE,FIRSTPARTY,LOCALFOLDER known_third_party = docutils, pkg_resources, pytz known_zope = known_first_party = default_section = ZOPE line_length = 79 lines_after_imports = 2 [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/setup.py0000644000100100000240000000755514416166371014537 0ustar00macstaff############################################################################## # # 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 find_packages from setuptools import setup HOOK_REQUIRES = [ ] PERSISTENTREGISTRY_REQUIRES = [ 'persistent', ] SECURITY_REQUIRES = [ 'zope.location', 'zope.proxy', 'zope.security', ] ZCML_REQUIRES = [ 'zope.configuration', 'zope.i18nmessageid', ] MIN_TESTS_REQUIRE = ( HOOK_REQUIRES + ZCML_REQUIRES + [ 'zope.testing', 'zope.testrunner', ] ) TESTS_REQUIRE = ( MIN_TESTS_REQUIRE + PERSISTENTREGISTRY_REQUIRES + SECURITY_REQUIRES ) def read(*rnames): with open(os.path.join(os.path.dirname(__file__), *rnames)) as f: return f.read() setup( name='zope.component', version='6.0', url='https://github.com/zopefoundation/zope.component', project_urls={ 'Documentation': 'https://zopecomponent.readthedocs.io/', 'Issue Tracker': ('https://github.com/zopefoundation/' 'zope.component/issues'), 'Sources': 'https://github.com/zopefoundation/zope.component', }, license='ZPL 2.1', description='Zope Component Architecture', author='Zope Foundation and Contributors', author_email='zope-dev@zope.dev', long_description=( read('README.rst') + '\n' + read('CHANGES.rst') ), keywords="interface component coupling loose utility adapter", 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 :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Framework :: Zope :: 3", "Framework :: Zope :: 5", "Topic :: Software Development :: Libraries :: Python Modules", ], namespace_packages=['zope', ], python_requires='>=3.7', install_requires=[ 'setuptools', 'zope.event', 'zope.hookable >= 4.2.0', 'zope.interface >= 5.3', ], include_package_data=True, zip_safe=False, extras_require={ 'hook': HOOK_REQUIRES, # BBB 'persistentregistry': PERSISTENTREGISTRY_REQUIRES, 'security': SECURITY_REQUIRES, 'zcml': ZCML_REQUIRES, 'mintests': MIN_TESTS_REQUIRE, 'test': TESTS_REQUIRE, 'docs': [ 'Sphinx', 'repoze.sphinx.autointerface', 'ZODB', ], }, ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681452282.1339717 zope.component-6.0/src/0000755000100100000240000000000014416166372013601 5ustar00macstaff././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681452282.1517465 zope.component-6.0/src/zope/0000755000100100000240000000000014416166372014556 5ustar00macstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/__init__.py0000644000100100000240000000007014416166371016663 0ustar00macstaff__import__('pkg_resources').declare_namespace(__name__) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681452282.1629124 zope.component-6.0/src/zope/component/0000755000100100000240000000000014416166372016560 5ustar00macstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/__init__.py0000644000100100000240000000614714416166371020700 0ustar00macstaff############################################################################## # # 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 This module provides an implementation of :class:`~zope.component.interfaces.IComponentArchitecture`, using the current :mod:`site `. This module also provides an implementation of :class:`~zope.component.interfaces.IComponentRegistrationConvenience` using the `global site manager `_. """ from zope.interface import Interface from zope.interface import implementedBy from zope.interface import moduleProvides from zope.interface import named from zope.interface import providedBy from zope.interface.interfaces import ComponentLookupError from zope.interface.interfaces import IComponentLookup 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 getNextUtility from zope.component._api import getSiteManager from zope.component._api import getUtilitiesFor from zope.component._api import getUtility 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 queryNextUtility from zope.component._api import queryUtility from zope.component._api import subscribers from zope.component._declaration import adaptedBy from zope.component._declaration import adapter from zope.component._declaration import adapts 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.interfaces import IComponentArchitecture from zope.component.interfaces import IComponentRegistrationConvenience from zope.component.interfaces import IFactory moduleProvides(IComponentArchitecture, IComponentRegistrationConvenience) __all__ = tuple(IComponentArchitecture) \ + tuple(IComponentRegistrationConvenience) \ + ('named', 'adapts', 'adapter', 'adaptedBy', ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/_api.py0000644000100100000240000002107714416166371020050 0ustar00macstaff############################################################################## # # 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 zope.interface.interface from zope.hookable import hookable from zope.interface import Interface from zope.interface.interfaces import ComponentLookupError from zope.interface.interfaces import IComponentLookup from zope.component.interfaces import IFactory from zope.component.interfaces import inherits_arch_docs as inherits_docs # 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 @inherits_docs 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 @inherits_docs def getAdapterInContext(object, interface, context): adapter = queryAdapterInContext(object, interface, context) if adapter is None: raise ComponentLookupError(object, interface) return adapter @inherits_docs 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) @inherits_docs def getAdapter(object, interface=Interface, name='', context=None): adapter = queryAdapter(object, interface, name, None, context) if adapter is None: raise ComponentLookupError(object, interface, name) return adapter @inherits_docs def queryAdapter(object, interface=Interface, name='', default=None, context=None): if context is None: return adapter_hook(interface, object, name, default) return getSiteManager(context).queryAdapter(object, interface, name, default) @inherits_docs def getMultiAdapter(objects, interface=Interface, name='', context=None): adapter = queryMultiAdapter(objects, interface, name, context=context) if adapter is None: raise ComponentLookupError(objects, interface, name) return adapter @inherits_docs def queryMultiAdapter(objects, interface=Interface, name='', 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) @inherits_docs 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) @inherits_docs 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) @inherits_docs 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) zope.interface.interface.adapter_hooks.append(adapter_hook) ############################################################################# # Utility API @inherits_docs def getUtility(interface, name='', context=None): utility = queryUtility(interface, name, context=context) if utility is not None: return utility raise ComponentLookupError(interface, name) @inherits_docs def queryUtility(interface, name='', default=None, context=None): return getSiteManager(context).queryUtility(interface, name, default) @inherits_docs def getUtilitiesFor(interface, context=None): return getSiteManager(context).getUtilitiesFor(interface) @inherits_docs def getAllUtilitiesRegisteredFor(interface, context=None): return getSiteManager(context).getAllUtilitiesRegisteredFor(interface) _marker = object() @inherits_docs 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 @inherits_docs 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 ComponentLookupError( "No more utilities for {}, '{}' have been found.".format( interface, name)) return util # Factories @inherits_docs 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) @inherits_docs 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() @inherits_docs 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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/_compat.py0000644000100100000240000000143114416166371020552 0ustar00macstaff############################################################################## # # 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. # ############################################################################## from zope.interface.ro import InconsistentResolutionOrderError ZOPE_SECURITY_NOT_AVAILABLE_EX = ( ImportError, InconsistentResolutionOrderError) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/_declaration.py0000644000100100000240000000420414416166371021555 0ustar00macstaff############################################################################## # # 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 class adapter: """ Decorator that declares that the decorated object adapts the given *interfaces*. This is commonly used in conjunction with :obj:`zope.interface.implementer` to declare what adapting the *interfaces* will provide. """ def __init__(self, *interfaces): self.interfaces = interfaces def __call__(self, ob): if isinstance(ob, type): 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 the *interfaces* that *ob* will adapt, as declared by :obj:`adapter`. """ return getattr(ob, '__component_adapts__', None) def getName(ob): return getattr(ob, '__component_name__', '') class _adapts_descr: def __init__(self, interfaces): self.interfaces = interfaces def __get__(self, inst, cls): if inst is None: return self.interfaces raise AttributeError('__component_adapts__') ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/configure.zcml0000644000100100000240000000067414416166371021436 0ustar00macstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/event.py0000644000100100000240000000232214416166371020251 0ustar00macstaff############################################################################## # # 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.interface.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) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/eventtesting.py0000644000100100000240000000365314416166371021657 0ustar00macstaff############################################################################## # # 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 dispatchAdapterRegistrationEvent from zope.component.registry import dispatchHandlerRegistrationEvent from zope.component.registry import \ dispatchSubscriptionAdapterRegistrationEvent from zope.component.registry import dispatchUtilityRegistrationEvent try: from zope.testing.cleanup import addCleanUp except ImportError: def addCleanUp(x): pass events = [] def getEvents(event_type=None, filter=None): 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(): del events[:] addCleanUp(clearEvents) class PlacelessSetup: def setUp(self): provideHandler(objectEventNotify) provideHandler(dispatchUtilityRegistrationEvent) provideHandler(dispatchAdapterRegistrationEvent) provideHandler(dispatchSubscriptionAdapterRegistrationEvent) provideHandler(dispatchHandlerRegistrationEvent) provideHandler(events.append, (None,)) def setUp(test=None): PlacelessSetup().setUp() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/factory.py0000644000100100000240000000331614416166371020603 0ustar00macstaff############################################################################## # # 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 implementedBy from zope.interface import implementer from zope.interface.declarations import Implements from zope.component.interfaces import IFactory @implementer(IFactory) class Factory: """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 f'<{self.__class__.__name__} for {self._callable!r}>' ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/globalregistry.py0000644000100100000240000000530214416166371022162 0ustar00macstaff############################################################################## # # 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.adapter import AdapterRegistry from zope.interface.registry import Components from zope.component.interfaces import inherits_arch_docs from zope.component.interfaces import inherits_reg_docs 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().__init__() def __reduce__(self): return GAR, (self.__parent__, self.__name__) 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 @inherits_arch_docs 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. @inherits_reg_docs def provideUtility(component, provides=None, name=''): base.registerUtility(component, provides, name, event=False) @inherits_reg_docs def provideAdapter(factory, adapts=None, provides=None, name=''): base.registerAdapter(factory, adapts, provides, name, event=False) @inherits_reg_docs def provideSubscriptionAdapter(factory, adapts=None, provides=None): base.registerSubscriptionAdapter(factory, adapts, provides, event=False) @inherits_reg_docs def provideHandler(factory, adapts=None): base.registerHandler(factory, adapts, event=False) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/hooks.py0000644000100100000240000001246514416166371020264 0ustar00macstaff############################################################################## # # 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 from zope.component._compat import ZOPE_SECURITY_NOT_AVAILABLE_EX try: from zope.security.proxy import removeSecurityProxy except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover def removeSecurityProxy(x): return x from zope.interface.interfaces import ComponentLookupError from zope.interface.interfaces import IComponentLookup from zope.component.globalregistry import getGlobalSiteManager __all__ = [ 'setSite', 'getSite', 'site', 'getSiteManager', 'setHooks', 'resetHooks', ] class read_property: """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): """ site(site) -> None Context manager that sets *site* as the current site for the duration of the ``with`` body. """ 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(): """ Make `zope.component.getSiteManager` and interface adaptation respect the current site. Most applications will want to be sure te call this early in their startup sequence. Test code that uses these APIs should also arrange to call this. .. seealso:: :mod:`zope.component.testlayer` """ from zope.component import _api _api.adapter_hook.sethook(adapter_hook) _api.getSiteManager.sethook(getSiteManager) def resetHooks(): """ Reset `zope.component.getSiteManager` and interface adaptation to their original implementations that are unaware of the current site. Use caution when calling this; most code will not need to call this. If code using the global API executes following this, it will most likely use the base global component registry instead of a site-specific registry it was expected. This can lead to failures in adaptation and utility lookup. """ # Reset hookable functions to original implementation. from zope.component import _api _api.adapter_hook.reset() _api.getSiteManager.reset() # be sure the old adapter hook isn't cached, since # it is derived from the SiteManager try: del siteinfo.adapter_hook except AttributeError: pass # Clear the site thread global clearSite = setSite try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover pass else: addCleanUp(resetHooks) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/interface.py0000644000100100000240000000745114416166371021100 0ustar00macstaff############################################################################## # # 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 ComponentLookupError from zope.interface.interfaces import IInterface from zope.component._api import getSiteManager from zope.component._api import queryUtility def provideInterface(id, interface, iface_type=None, info=''): """ Mark *interface* as a named utility providing *iface_type*'. .. versionchanged:: 5.0.0 The named utility is registered in the current site manager. Previously it was always registered in the global site manager. """ if not id: id = "{}.{}".format(interface.__module__, interface.__name__) if not IInterface.providedBy(interface): if not isinstance(interface, type): 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 site_man = getSiteManager() site_man.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): site_man = getSiteManager() iface_utilities = site_man.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 = list(iface_utilities) return res def getInterfaceAllDocs(interface): iface_id = '{}.{}'.format(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' return '{}.{}'.format(interface.__module__, interface.__name__) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/interfaces.py0000644000100100000240000003360514416166371021263 0ustar00macstaff############################################################################ # # 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 The `IComponentArchitecture` and `IComponentRegistrationConvenience` interfaces are provided by `zope.component` directly. """ from zope.interface import Attribute from zope.interface import Interface # pylint:disable=inherit-non-class,no-self-argument,no-method-argument 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 `zope.interface.interfaces.IComponents`. """ 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 :mod:`zope.interface.interfaces.IComponentLookup` can be found. If no adapter is found, a `~zope.interface.interfaces.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 `~zope.interface.interfaces.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 `~zope.interface.interfaces.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='', 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 `~zope.interface.interfaces.ComponentLookupError`. """ 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 `~zope.interface.interfaces.ComponentLookupError`. 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 `~zope.interface.interfaces.ComponentLookupError`. 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='', 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. """ 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. 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='', 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. 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. """ 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. """ 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 `~zope.interface.interfaces.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=''): """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.) """ def provideAdapter(factory, adapts=None, provides=None, name=''): """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.) """ 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.) """ 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.) """ 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. """ # Internal helpers def _inherits_docs(func, iface): doc = iface[func.__name__].__doc__ # doc can be None if the interpreter drops all docstrings when the # environment variable PYTHONOPTIMIZE is set 2. if doc is None: return func # pragma: no cover # By adding the ..seealso:: we get a link from our overview page # to the specific narrative place where the function is described, because # our overview page uses :noindex: doc += "\n .. seealso::" doc += f"\n Function `~zope.component.{func.__name__}` for" doc += " notes, and " doc += f"\n `~zope.component.interfaces.{iface.__name__}` for" doc += " the defining interface.\n" func.__doc__ = doc return func def inherits_arch_docs(func): return _inherits_docs(func, IComponentArchitecture) def inherits_reg_docs(func): return _inherits_docs(func, IComponentRegistrationConvenience) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/meta.zcml0000644000100100000240000000217714416166371020403 0ustar00macstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/persistentregistry.py0000644000100100000240000001225314416166371023125 0ustar00macstaff############################################################################## # # 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.list import PersistentList from persistent.mapping import PersistentMapping from zope.interface.adapter import VerifyingAdapterRegistry from zope.interface.registry import Components class PersistentAdapterRegistry(VerifyingAdapterRegistry, Persistent): """ An adapter registry that is also a persistent object. .. versionchanged:: 5.0.0 Internal data structures are now composed of :class:`persistent.mapping.PersistentMapping` and :class:`persistent.list.PersistentList`. This helps scale to larger registries. Previously they were :class:`dict`, :class:`list` and :class:`tuple`, meaning that as soon as this object was unpickled, the entire registry tree had to be unpickled, and when a change was made (an object registered or unregisterd), the entire registry had to be pickled. Now, only the parts that are in use are loaded, and only the parts that are modified are stored. The above applies without reservation to newly created instances. For existing persistent instances, however, the data will continue to be in dicts and tuples, with some few exceptions for newly added or changed data. To fix this, call :meth:`rebuild` and commit the transaction. This will rewrite the internal data structures to use the new types. """ # The persistent types we use, replacing the basic types inherited # from ``BaseAdapterRegistry``. _sequenceType = PersistentList _leafSequenceType = PersistentList _mappingType = PersistentMapping _providedType = PersistentMapping # The methods needed to manipulate the leaves of the subscriber # tree. When we're manipulating unmigrated data, it's safe to # migrate it, but not otherwise (we don't want to write in an # otherwise read-only transaction). def _addValueToLeaf(self, existing_leaf_sequence, new_item): if not existing_leaf_sequence: existing_leaf_sequence = self._leafSequenceType() elif isinstance(existing_leaf_sequence, tuple): # Converting from old state. existing_leaf_sequence = self._leafSequenceType( existing_leaf_sequence) existing_leaf_sequence.append(new_item) return existing_leaf_sequence def _removeValueFromLeaf(self, existing_leaf_sequence, to_remove): if isinstance(existing_leaf_sequence, tuple): # Converting from old state existing_leaf_sequence = self._leafSequenceType( existing_leaf_sequence) without_removed = VerifyingAdapterRegistry._removeValueFromLeaf( self, existing_leaf_sequence, to_remove) existing_leaf_sequence[:] = without_removed return existing_leaf_sequence def changed(self, originally_changed): if originally_changed is self: # XXX: This is almost certainly redundant, even if we # have old data consisting of plain dict/list/tuple. That's # because the super class will now increment the ``_generation`` # attribute to keep caches in sync. For this same reason, # it's not worth trying to "optimize" for the case that we're a # new or rebuilt object containing only Persistent sub-objects: # the changed() mechanism will still result in mutating this # object via ``_generation``. self._p_changed = True super().changed(originally_changed) def __getstate__(self): state = super().__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().__setstate__(state) self._createLookup() self.__bases__ = bases self._v_lookup.changed(self) class PersistentComponents(Components): """ A component implementation that uses `PersistentAdapterRegistry`. Note that this object itself is *not* `Persistent`. """ 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() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/registry.py0000644000100100000240000000324014416166371021000 0ustar00macstaff############################################################################## # # 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 """ from zope.interface.interfaces import IAdapterRegistration from zope.interface.interfaces import IHandlerRegistration from zope.interface.interfaces import IRegistrationEvent from zope.interface.interfaces import ISubscriptionAdapterRegistration from zope.interface.interfaces import IUtilityRegistration from zope.component._api import handle from zope.component._declaration import adapter @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) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/security.py0000644000100100000240000001015414416166371021001 0ustar00macstaff############################################################################## # # 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.component._compat import ZOPE_SECURITY_NOT_AVAILABLE_EX try: 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 except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover def _no_security(*args, **kw): raise TypeError( "security proxied components are not " "supported because zope.security is not available") LocatingTrustedAdapterFactory = _no_security LocatingUntrustedAdapterFactory = _no_security TrustedAdapterFactory = _no_security Checker = _no_security CheckerPublic = _no_security InterfaceChecker = _no_security 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 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/standalonetests.py0000644000100100000240000000204114416166371022341 0ustar00macstaff""" See: https://bugs.launchpad.net/zope3/+bug/98401 """ import pickle import sys def write(x): sys.stdout.write('%s\n' % x) if __name__ == "__main__": # TextIO? Are you kidding me? data = sys.stdin.buffer.read() sys.path = pickle.loads(data) write('XXXXXXXXXX') for p in sys.path: write('- %s' % p) write('XXXXXXXXXX') from zope.interface import Interface from zope.interface import implementer import zope class I1(Interface): pass class I2(Interface): pass @implementer(I1) class Ob: def __repr__(self): return '' ob = Ob() @implementer(I2) class Comp: 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 ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1681452282.164432 zope.component-6.0/src/zope/component/testfiles/0000755000100100000240000000000014416166372020562 5ustar00macstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/testfiles/__init__.py0000644000100100000240000000002114416166371022663 0ustar00macstaff# Python package ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/testfiles/adapter.py0000644000100100000240000000302714416166371022555 0ustar00macstaff############################################################################## # # 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 # pragma: no cover def f2(): pass # pragma: no cover def f3(): pass # pragma: no cover class IS(Interface): pass class Adapter: 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, ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/testfiles/components.py0000644000100100000240000000307314416166371023323 0ustar00macstaff############################################################################## # # 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 Attribute from zope.interface import Interface from zope.interface import implementer from zope.component import adapter from zope.component import named 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: pass @adapter(IContent) @implementer(IApp) class Comp: def __init__(self, *args): # Ignore arguments passed to constructor pass a = 1 def f(): pass # pragma: no cover class Comp2: def __init__(self, context): self.context = context @adapter(IContent) @implementer(IApp) @named('app') class Comp4: def __init__(self, context=None): self.context = context comp = Comp() comp4 = Comp4() content = Content() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/testfiles/testlayer.zcml0000644000100100000240000000046214416166371023466 0ustar00macstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/testfiles/views.py0000644000100100000240000000133314416166371022270 0ustar00macstaff############################################################################## # # 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 class IC(Interface): pass ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/testing.py0000644000100100000240000000237314416166371020613 0ustar00macstaff############################################################################## # # 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 # noqa: F401 imported but unused # we really don't need special setup now: class _PlacelessSetupFallback: def cleanUp(self): from zope.component.globalregistry import base base.__init__('base') setUp = tearDown = cleanUp try: from zope.testing.cleanup import CleanUp as PlacelessSetup except ImportError: # pragma: no cover PlacelessSetup = _PlacelessSetupFallback def setUp(test=None): PlacelessSetup().setUp() def tearDown(test=None): PlacelessSetup().tearDown() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/testlayer.py0000644000100100000240000001020114416166371021137 0ustar00macstaff############################################################################## # # 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 config from zope.configuration import xmlconfig try: from zope.testing.cleanup import cleanUp except ImportError: # pragma: no cover def cleanUp(): pass from zope.component import provideHandler from zope.component.eventtesting import clearEvents from zope.component.eventtesting import events from zope.component.hooks import setHooks class LayerBase: """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().__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().__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) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1681452282.1696584 zope.component-6.0/src/zope/component/tests/0000755000100100000240000000000014416166372017722 5ustar00macstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/__init__.py0000644000100100000240000000162214416166371022033 0ustar00macstaffimport unittest def skipIfNoSecurity(testfunc): from zope.component._compat import ZOPE_SECURITY_NOT_AVAILABLE_EX try: import zope.security # noqa: F401 imported but unused except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover return unittest.skip("zope.security not installed")(testfunc) return testfunc def fails_if_called(test, msg="This function must not be called.", arguments=True): """ Return a new function (accepting any arguments) that will call test.fail(msg) if it is called. :keyword bool arguments: If set to ``False``, then we will not accept any arguments. This can avoid masking when we would expect a TypeError to be raised by calling an instance method against a class. """ if not arguments: return lambda: test.fail(msg) return lambda *_args, **__kwargs: test.fail(msg) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/examples.py0000644000100100000240000000601614416166371022114 0ustar00macstaff############################################################################## # # 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.globalregistry import GlobalAdapterRegistry 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 class U: def __init__(self, name): self.__name__ = name def __repr__(self): return "{}({})".format(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 base = GlobalAdapterRegistry(GlobalRegistry, 'adapters') GlobalRegistry.adapters = base def clear_base(): base.__init__(GlobalRegistry, 'adapters') @implementer(I1) class Ob: def __repr__(self): return '' ob = Ob() @implementer(I2) class Ob2: def __repr__(self): return '' @implementer(IC) class Ob3: pass @implementer(I2) class Comp: def __init__(self, context): self.context = context comp = Comp(1) class ConformsToIComponentLookup: """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.interface.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)() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test___init__.py0000644000100100000240000000600014416166371023065 0ustar00macstaff############################################################################## # # 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 import zope.component as zc from zope.component.interfaces import IComponentArchitecture verifyObject(IComponentArchitecture, zc) def test_module_conforms_to_IComponentRegistrationConvenience(self): from zope.interface.verify import verifyObject import zope.component as zc from zope.component.interfaces import IComponentRegistrationConvenience verifyObject(IComponentRegistrationConvenience, zc) class Test_Interface_call(unittest.TestCase): from zope.component.testing import setUp from zope.component.testing import 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: pass @implementer(IFoo) class Baz: 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: 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) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test__api.py0000644000100100000240000012114714416166371022250 0ustar00macstaff############################################################################## # # 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 from zope.component.tests import fails_if_called class Test_getSiteManager(unittest.TestCase): from zope.component.testing import setUp from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component._api import getSiteManager return getSiteManager(*args, **kw) def test_sm_is_IComponentLookup(self): from zope.interface.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.interface.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.interface.interfaces import IComponentLookup from zope.component.globalregistry import getGlobalSiteManager 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 from zope.component.testing import 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.interface.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: __init__ = fails_if_called(self) @implementer(IFoo) class Local: def __init__(self, context): self.context = context @implementer(IBar) class Bar: 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 from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import queryAdapterInContext return queryAdapterInContext(*args, **kw) def test_miss(self): from zope.interface import Interface class IFoo(Interface): pass self.assertEqual( self._callFUT(object(), IFoo, context=None), None) def test_w_object_conforming(self): from zope.interface import Interface class IFoo(Interface): pass _adapted = object() class Foo: def __conform__(self, iface, default=None, _test=self): _test.assertIs(iface, IFoo) return _adapted self.assertTrue( self._callFUT(Foo(), IFoo, context=None) is _adapted) def test___conform___raises_TypeError_via_class(self): from zope.interface import Interface class IFoo(Interface): pass class Foo: __conform__ = fails_if_called(self, arguments=False) # call via class, triggering TypeError self.assertEqual(self._callFUT(Foo, IFoo, context=None), None) def test___conform___raises_TypeError_via_inst(self): from zope.interface import Interface class IFoo(Interface): pass class Foo: def __conform__(self, iface, default=None): raise TypeError self.assertRaises(TypeError, self._callFUT, Foo(), IFoo, context=None) def test_w_object_implementing(self): from zope.interface import Interface from zope.interface import implementer class IFoo(Interface): pass @implementer(IFoo) class Foo: pass foo = Foo() self.assertIs( self._callFUT(foo, IFoo, context=None), foo) class Test_getAdapter(unittest.TestCase): from zope.component.testing import setUp from zope.component.testing import 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.interface.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.interface.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: pass @implementer(IFoo) class Baz: 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: 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: pass @implementer(IFoo) class Baz: 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 from zope.component.testing import 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: pass @implementer(IFoo) class Baz: 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: pass @implementer(IFoo) class Baz: 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: __init__ = fails_if_called(self) @implementer(IFoo) class Local: def __init__(self, context): self.context = context @implementer(IBar) class Bar: 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 from zope.component.testing import 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.interface.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.interface.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: pass @implementer(IBaz) class Baz: pass @implementer(IFoo) class FooAdapter: 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: pass @implementer(IFoo) class FooAdapter: 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: pass @implementer(IBaz) class Baz: pass @implementer(IFoo) class FooAdapter: 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 from zope.component.testing import 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: pass @implementer(IBaz) class Baz: pass @implementer(IFoo) class FooAdapter: 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: pass @implementer(IBaz) class Baz: pass @implementer(IFoo) class FooAdapter: 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: pass @implementer(IBaz) class Baz: pass @implementer(IFoo) class Global: __init__ = fails_if_called(self) @implementer(IFoo) class Local: 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.interface.interfaces import ComponentLookupError class IFoo(Interface): pass class IBar(Interface): pass class IBaz(Interface): pass @implementer(IBar) class Bar: pass @implementer(IBaz) class Baz: pass class Context: 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 from zope.component.testing import 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: def __init__(self, context): self.context = context class BazAdapter: 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.interface.interfaces import ComponentLookupError class IFoo(Interface): pass class IBar(Interface): pass class IBaz(Interface): pass @implementer(IBar) class Bar: pass @implementer(IBaz) class Baz: pass class Context: 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 from zope.component.testing import 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: def __init__(self, context): self.context = context class BazAdapter: 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.interface.interfaces import ComponentLookupError class IFoo(Interface): pass class Context: 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 from zope.component.testing import 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 self._callFUT((object,), IFoo) # doesn't raise def test_hit(self): from zope.interface import Interface from zope.interface import implementer from zope.component import getGlobalSiteManager class IFoo(Interface): pass @implementer(IFoo) class Foo: 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 from zope.component.testing import 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.interface.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.interface.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: 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 from zope.component.testing import 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: 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 from zope.component.testing import 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 from zope.component.testing import 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 from zope.component.testing import 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.interface.interfaces import IComponentLookup from zope.interface.registry import Components from zope.component import getGlobalSiteManager 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 from zope.component.testing import 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.interface.registry import Components from zope.component import getGlobalSiteManager 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.interface.interfaces import ComponentLookupError class IFoo(Interface): pass class Context: 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 from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import createObject return createObject(*args, **kw) def test_miss(self): from zope.interface.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: def __conform__(self, iface): return self def queryUtility(self, iface, name, default, _test=self): _test.assertIs(iface, IFactory) _test.assertEqual(name, 'test') return _factory 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 from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import getFactoryInterfaces return getFactoryInterfaces(*args, **kw) def test_miss(self): from zope.interface.interfaces import ComponentLookupError self.assertRaises(ComponentLookupError, self._callFUT, 'nonesuch') def test_hit(self): from zope.interface import Interface from zope.component.interfaces import IFactory class IFoo(Interface): pass class _Factory: def getInterfaces(self): return [IFoo] class Context: def __conform__(self, iface): return self def queryUtility(self, iface, name, default, _test=self): _test.assertIs(iface, IFactory) _test.assertEqual(name, 'test') return _Factory() context = Context() self.assertEqual(self._callFUT('test', context=context), [IFoo]) class Test_getFactoriesFor(unittest.TestCase): from zope.component.testing import setUp from zope.component.testing import 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: def getInterfaces(self): return providedBy(self) _factory = _Factory() class Context: 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: def getInterfaces(self): return [IFoo, IBar] _factory = _Factory() class Context: 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) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test__declaration.py0000644000100100000240000001421114416166371023755 0ustar00macstaff############################################################################## # # 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: 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: 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: 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): import warnings with warnings.catch_warnings(record=True) as log: warnings.resetwarnings() exec(code, globs, locs) self.assertEqual(len(log), 0) # no longer warn return True def test_instances_not_affected(self): from zope.component._declaration import adapts class C: 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.interface import Interface from zope.component._declaration import adapts class IFoo(Interface): pass globs = {'adapts': adapts, 'IFoo': IFoo} locs = {} CODE = "\n".join([ 'def foo():', ' adapts(IFoo)' ]) self._run_generated_code(CODE, globs, locs) 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.interface import Interface from zope.component._declaration import adapts 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() with self.assertRaises(TypeError): exec(CODE, globs, locs) self.assertEqual(len(log), 0) # no longer warn def test_called_once_from_class(self): from zope.interface import Interface from zope.component._declaration import adapts class IFoo(Interface): pass globs = {'adapts': adapts, 'IFoo': IFoo} locs = {} CODE = "\n".join([ 'class Foo(object):', ' adapts(IFoo)', ]) 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: __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: __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: pass baz = Baz() baz.__component_adapts__ = (IFoo, IBar) self.assertEqual(self._callFUT(baz), (IFoo, IBar)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_event.py0000644000100100000240000000423414416166371022456 0ustar00macstaff############################################################################## # # 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.event import dispatch from zope.component.globalregistry import getGlobalSiteManager _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.interface.interfaces import IObjectEvent from zope.component.event import objectEventNotify from zope.component.globalregistry import getGlobalSiteManager _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: def __init__(self, object): self.object = object context = object() event = _ObjectEvent(context) objectEventNotify(event) self.assertEqual(_adapted, [(context, event)]) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_factory.py0000644000100100000240000000733014416166371023004 0ustar00macstaff############################################################################## # # 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 from zope.component.tests import fails_if_called 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 = fails_if_called(self) 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): func = fails_if_called(self) factory = self._makeOne(func) self.assertEqual(factory._callable, func) self.assertEqual(factory.title, '') self.assertEqual(factory.description, '') self.assertEqual(factory._interfaces, None) def test_ctor_expclit(self): factory = self._makeOne(fails_if_called(self), '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 _callable = fails_if_called(self) _callable.__name__ = '_callable' _callable = implementer(IBaz)(_callable) 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 _callable = implementer(IBaz)(fails_if_called(self)) factory = self._makeOne(_callable) spec = factory.getInterfaces() self.assertEqual(list(spec), [IBaz]) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_globalregistry.py0000644000100100000240000002271714416166371024374 0ustar00macstaff############################################################################## # # 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 from zope.component.tests import fails_if_called class Test_getGlobalSiteManager(unittest.TestCase): def _callFUT(self): from zope.component.globalregistry import getGlobalSiteManager return getGlobalSiteManager() def test_gsm_is_IComponentLookup(self): from zope.interface.interfaces import IComponentLookup from zope.component.globalregistry import base 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): 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 from zope.component.testing import 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: pass foo = Foo() self._callFUT(foo) gsm = getGlobalSiteManager() self.assertIs(gsm.getUtility(IFoo, ''), foo) # We can clean it up using the fallback and it will be gone from zope.component.testing import _PlacelessSetupFallback _PlacelessSetupFallback().cleanUp() self.assertIsNone(gsm.queryUtility(IFoo, '')) def test_named_w_provides(self): from zope.interface import Interface from zope.component.globalregistry import getGlobalSiteManager class IFoo(Interface): pass class Foo: 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 from zope.component.testing import 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._declaration import adapter from zope.component.globalregistry import getGlobalSiteManager class IFoo(Interface): pass class IBar(Interface): pass @implementer(IFoo) class Foo: pass @adapter(IFoo) @implementer(IBar) class Bar: 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: pass class Bar: 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 from zope.component.testing import 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._declaration import adapter from zope.component.globalregistry import getGlobalSiteManager class IFoo(Interface): pass class IBar(Interface): pass @implementer(IFoo) class Foo: pass @adapter(IFoo) @implementer(IBar) class Bar: 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: pass class Bar: 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 from zope.component.testing import 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._declaration import adapter from zope.component.globalregistry import getGlobalSiteManager class IFoo(Interface): pass @implementer(IFoo) class Foo: pass _handler = adapter(IFoo)(fails_if_called(self)) 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 _handler = fails_if_called(self) 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) class TestBaseGlobalComponents(unittest.TestCase): from zope.component.testing import setUp from zope.component.testing import tearDown def _getTargetClass(self): from zope.component.globalregistry import BaseGlobalComponents return BaseGlobalComponents def _getTargetInterfaces(self): from zope.interface.interfaces import IComponentLookup from zope.interface.interfaces import IComponentRegistry from zope.interface.interfaces import IComponents return [IComponents, IComponentLookup, IComponentRegistry] def _makeOne(self): return self._getTargetClass()() def test_verifyInstance(self): from zope.interface.verify import verifyObject for iface in self._getTargetInterfaces(): verifyObject(iface, self._makeOne()) def test_verifyClass(self): from zope.interface.verify import verifyClass for iface in self._getTargetInterfaces(): verifyClass(iface, self._getTargetClass()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_hooks.py0000644000100100000240000002535414416166371022466 0ustar00macstaff############################################################################## # # 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: @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: @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: adapter_hook = _hook class _SiteManager: 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: 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 siteinfo = _DummySiteInfo() with _Monkey(hooks, siteinfo=siteinfo): self.assertTrue(self._callFUT() is None) def test_w_site(self): from zope.component import hooks _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: 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 _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.interface.interfaces import IComponentLookup from zope.component import hooks from zope.component.globalregistry import getGlobalSiteManager class _Lookup: 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 class IFoo(Interface): pass _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.interface.interfaces import ComponentLookupError from zope.component import hooks class IFoo(Interface): pass _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: 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 from zope.component import hooks class _Hook: 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): # Access the adapter_hook of the site info to be # sure it caches getattr(hooks.siteinfo, 'adapter_hook') self.assertTrue('adapter_hook' in hooks.siteinfo.__dict__) self._callFUT() self.assertTrue(adapter_hook._reset) self.assertTrue(getSiteManager._reset) # adapter_hook cache also reset self.assertFalse('adapter_hook' in hooks.siteinfo.__dict__) _SM = object() class _DummySiteInfo: sm = _SM site = None class _Monkey: # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module self.to_restore = {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) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_interface.py0000644000100100000240000004002014416166371023266 0ustar00macstaff############################################################################## # # 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 os import unittest DOCSTRINGS_REMOVED = os.environ.get('PYTHONOPTIMIZE') == '2' # pylint:disable=inherit-non-class,blacklisted-name class Test_provideInterface(unittest.TestCase): from zope.component.testing import setUp from zope.component.testing import 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: 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.assertIs(registered, IFoo) def test_register_in_current_site(self): from zope.interface import Interface from zope.interface.interfaces import IInterface from zope.interface.registry import Components from zope.component._api import getSiteManager from zope.component.globalregistry import getGlobalSiteManager class IFoo(Interface): pass site_man = Components() def get(_context=None): return site_man getSiteManager.sethook(get) self.addCleanup(getSiteManager.reset) self._callFUT('foo', IFoo) self.assertIs(site_man.getUtility(IInterface, name='foo'), IFoo) self.assertIsNone( getGlobalSiteManager().queryUtility(IInterface, name='foo') ) class Test_getInterface(unittest.TestCase): from zope.component.testing import setUp from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.interface import getInterface return getInterface(*args, **kw) def test_miss(self): from zope.interface.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 from zope.component.testing import 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 from zope.component.testing import 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]) def test_hit_in_current_site(self): from zope.interface import Interface from zope.interface.interfaces import IInterface from zope.interface.registry import Components from zope.component._api import getSiteManager from zope.component.globalregistry import getGlobalSiteManager class ILocal(Interface): pass class IGlobal(Interface): pass gsm = getGlobalSiteManager() site_man = Components(bases=(gsm,)) def get(_context=None): return site_man getSiteManager.sethook(get) self.addCleanup(getSiteManager.reset) gsm.registerUtility(IGlobal, IInterface, 'foo') site_man.registerUtility(ILocal, IInterface, 'bar') result = self._callFUT(None) self.assertEqual(len(result), 2) self.assertIn(ILocal, result) self.assertIn(IGlobal, result) getSiteManager.reset() result = self._callFUT(None) self.assertEqual(len(result), 1) self.assertIn(IGlobal, result) class Test_searchInterfaceIds(unittest.TestCase): from zope.component.testing import setUp from zope.component.testing import 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 from zope.component.testing import 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)]) @unittest.skipIf(DOCSTRINGS_REMOVED, 'Skipping tests, docstrings are optimized away') 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: """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 from zope.component.testing import 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.interface.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 from zope.component.testing import 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') ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_interfaces.py0000644000100100000240000000175214416166371023462 0ustar00macstaff############################################################################## # # Copyright (c) 2017 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 zope.component.interfaces """ import unittest class TestInterfaces(unittest.TestCase): def test_nothing(self): """ This exists only so that zope.testrunner doesn't complain this module has no tests. Even though this file is empty, we want to keep it around for ease of browsing the history. """ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_persistentregistry.py0000644000100100000240000002236114416166371025327 0ustar00macstaff############################################################################## # # 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 from zope.interface.tests.test_adapter import \ CustomTypesBaseAdapterRegistryTests def skipIfNoPersistent(testfunc): try: import persistent # noqa: F401 imported but unused except ImportError: # pragma: no cover return unittest.skip("persistent not installed")(testfunc) return testfunc @skipIfNoPersistent 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: def __init__(self, jar): self._jar = jar self._mru = [] # mru(oid) is only called in pure-Python runs self.mru = self._mru.append def new_ghost(self, oid, obj): obj._p_jar = self._jar obj._p_oid = oid def update_object_size_estimation(self, oid, size): "This is only called in pure-Python runs" return _Cache(jar) def _makeJar(self): # Borrowed from persistent.tests.test_pyPersistence. from persistent.interfaces import IPersistentDataManager from zope.interface import implementer @implementer(IPersistentDataManager) class _Jar: 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.pop('__bases__'), bases) self.assertEqual(state.pop('_generation'), 1) self.assertEqual(state.pop('_provided'), {}) self.assertEqual(state.pop('_adapters'), []) self.assertEqual(state.pop('_subscribers'), []) self.assertNotIn('ro', state) self.assertEqual(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)) def test__addValueToLeaf_existing_is_tuple_converts(self): from persistent.list import PersistentList registry = self._makeOne() # It converts when the tuple is not empty... result = registry._addValueToLeaf(('a',), 'b') self.assertIsInstance(result, PersistentList) self.assertEqual(result, ['a', 'b']) # ...and when it is empty... result = registry._addValueToLeaf((), 'b') self.assertIsInstance(result, PersistentList) self.assertEqual(result, ['b']) # ...and in fact when it is even missing result = registry._addValueToLeaf(None, 'b') self.assertIsInstance(result, PersistentList) self.assertEqual(result, ['b']) def test__removeValueFromLeaf_existing_is_tuple_converts(self): from persistent.list import PersistentList registry = self._makeOne() # It converts when the item is found... result = registry._removeValueFromLeaf(('a', 'b'), 'b') self.assertIsInstance(result, PersistentList) self.assertEqual(result, ['a']) # ...and when it is not found result = registry._removeValueFromLeaf(('a',), 'b') self.assertIsInstance(result, PersistentList) self.assertEqual(result, ['a']) def test__addValueFromLeaf_preserves_identity(self): registry = self._makeOne() first = registry._addValueToLeaf(None, 'a') second = registry._addValueToLeaf(first, 'b') self.assertIs(first, second) self.assertEqual(second, ['a', 'b']) def test__removeValueFromLeaf_preserves_identity(self): registry = self._makeOne() first = registry._addValueToLeaf(None, 'a') second = registry._addValueToLeaf(first, 'b') third = registry._addValueToLeaf(second, 'c') fourth = registry._removeValueFromLeaf(third, 'c') self.assertIs(first, second) self.assertIs(third, fourth) self.assertIs(first, fourth) self.assertEqual(fourth, ['a', 'b']) @skipIfNoPersistent 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.list import PersistentList from persistent.mapping import PersistentMapping 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): return bytes(s) if bytes is str else bytes(s, 'ascii') @skipIfNoPersistent class PersistentAdapterRegistryCustomTypesTest( CustomTypesBaseAdapterRegistryTests): def _getMappingType(self): from persistent.mapping import PersistentMapping return PersistentMapping def _getProvidedType(self): return self._getMappingType() def _getMutableListType(self): from persistent.list import PersistentList return PersistentList def _getLeafSequenceType(self): return self._getMutableListType() def _getBaseAdapterRegistry(self): from zope.component.persistentregistry import PersistentAdapterRegistry return PersistentAdapterRegistry ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_registry.py0000644000100100000240000001050014416166371023176 0ustar00macstaff############################################################################## # # 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 from zope.component.tests import fails_if_called class Test_dispatchUtilityRegistrationEvent(unittest.TestCase): from zope.component.testing import setUp from zope.component.testing import 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: 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 from zope.component.testing import 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: factory = fails_if_called(self) _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 from zope.component.testing import 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: factory = fails_if_called(self) _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 from zope.component.testing import 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: handler = fails_if_called(self) _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: # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module self.to_restore = {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) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_security.py0000644000100100000240000002172414416166371023207 0ustar00macstaff############################################################################## # # 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 zope.component.security """ import unittest from zope.component.tests import fails_if_called from zope.component.tests import skipIfNoSecurity @skipIfNoSecurity 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: pass foo = Foo() proxy = self._makeOne(foo) self.assertEqual(providedBy(proxy), providedBy(foo)) @skipIfNoSecurity 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): "bar" def baz(self): "baz" class ISpam(Interface): def qux(self): "qux" 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) @skipIfNoSecurity 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: bar = fails_if_called(self) 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): "bar" 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.proxy import getProxiedObject from zope.security.checker import CheckerPublic class IFoo(Interface): def bar(self): "bar" 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): "bar" 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) @skipIfNoSecurity 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): "bar" class _Factory: bar = fails_if_called(self) 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): "bar" class _Factory: __slots__ = ('one',) bar = fails_if_called(self) protected = self._callFUT(_Factory, IFoo, 'testing') self.assertTrue(protected.factory is _Factory) foo = protected() self.assertEqual(getTestProxyItems(foo), [('bar', 'testing')]) @skipIfNoSecurity 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: pass self.assertTrue(self._callFUT(_Factory, None, False, False) is _Factory) def test_public_untrusted_no_location(self): class _Factory: 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: 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: 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: 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: 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: 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: 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: pass proxy = self._callFUT(_Factory, 'testing', True, True) self.assertTrue(isinstance(proxy, LocatingTrustedAdapterFactory)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_standalone.py0000644000100100000240000000422014416166371023460 0ustar00macstaff############################################################################## # # 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 from zope.component.tests import skipIfNoSecurity @skipIfNoSecurity class StandaloneTests(unittest.TestCase): def testStandalone(self): # See: https://bugs.launchpad.net/zope3/+bug/98401 import os import pickle import subprocess import sys 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) try: pickle.dump(sys.path, process.stdin) process.stdin.close() try: rc = process.wait() except OSError as e: # pragma: no cover # MacIntel raises apparently unimportant EINTR? if e.errno != 4: raise # TODO verify sanity of a pass on EINTR :-/ if rc != 0: # pragma: no cover output = process.stdout.read() if isinstance(output, bytes): output = output.decode() sys.stderr.write('#' * 80 + '\n') sys.stdout.write(output) sys.stderr.write('#' * 80 + '\n') self.fail('Output code: %d' % rc) finally: process.stdout.close() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/tests/test_zcml.py0000644000100100000240000015017114416166371022304 0ustar00macstaff############################################################################## # # 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 from zope.component.tests import fails_if_called from zope.component.tests import skipIfNoSecurity 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 IApp from zope.component.testfiles.components import comp registry = Components() def dummy(context=None): return registry getSiteManager.sethook(dummy) try: self._callFUT('registerUtility', comp, IApp, '') 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: pass class Bar: 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: __init__ = fails_if_called(self) _cfg_ctx = _makeConfigContext() self.assertRaises(TypeError, self._callFUT, _cfg_ctx, [_Factory]) def test_no_name(self): from zope.interface import Interface class IFoo(Interface): pass class IBar(Interface): pass from zope.interface import implementer from zope.component import adapter from zope.component import named @adapter(IFoo) @implementer(IBar) @named('bar') class _Factory: __init__ = fails_if_called(self) _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, [_Factory]) # Register the adapter action = _cfg_ctx._actions[0][1] self.assertEqual(action['args'][4], 'bar') 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: __init__ = fails_if_called(self) _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: pass class Bar: 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: 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: 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: 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: __init__ = fails_if_called(self) _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_zcml_functional(unittest.TestCase): # These mimic the snippets in the zcml.rst doctests def setUp(self): from zope.component.tests.examples import clearZCML clearZCML() tearDown = setUp def _runSnippet(self, snippet): from zope.configuration import xmlconfig template = """\ %s """ % snippet xmlconfig.string(template) @skipIfNoSecurity def test_with_proxy_factory_public_permission(self): # Using the public permission doesn't give you a location proxy from zope.proxy import isProxy from zope.security.checker import ProxyFactory from zope.security.proxy import removeSecurityProxy from zope.component.testfiles.adapter import A1 from zope.component.testfiles.adapter import I1 from zope.component.testfiles.components import Content self._runSnippet(''' ''') ob = Content() p = ProxyFactory(ob) a = I1(p) self.assertTrue(isProxy(a)) self.assertTrue(isinstance(removeSecurityProxy(a), A1)) @skipIfNoSecurity def test_located_proxy_factory(self): # Passing locate results in a security proxy around a location proxy from zope.location.location import LocationProxy from zope.proxy import isProxy from zope.security.checker import ProxyFactory from zope.security.proxy import removeSecurityProxy from zope.component.testfiles.adapter import I1 from zope.component.testfiles.components import Content self._runSnippet(''' ''') ob = Content() p = ProxyFactory(ob) a = I1(p) self.assertTrue(isProxy(a)) self.assertTrue(isinstance(removeSecurityProxy(a), LocationProxy)) 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 _handler = fails_if_called(self) _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: pass _handler = fails_if_called(self) _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: 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: 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 _handler = fails_if_called(self) _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: pass fails_if_called(self) _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: 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: 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: 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)) def test_no_for__no_provides_subscriber_adapts_subscriber_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: def __init__(self, context): self.context = context # pragma: no cover _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, factory=_Factory) self.assertEqual(len(_cfg_ctx._actions), 3) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the subscriber action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertIsNone(action['discriminator']) self.assertEqual( action['args'], ('registerSubscriptionAdapter', _Factory, (Interface, ), IFoo, '', 'TESTING')) 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: 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: 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: 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: 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_name(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_wo_name(self): from zope.interface import Interface from zope.interface import implementer from zope.interface import named class IFoo(Interface): pass @implementer(IFoo) @named('foo') class Foo: pass foo = Foo() _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, component=foo) action = _cfg_ctx._actions[0][1] self.assertEqual(action['args'][1], foo) self.assertEqual(action['args'][2], IFoo) self.assertEqual(action['args'][3], 'foo') 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: 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): "bar" class Foo: bar = fails_if_called(self) _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)) @skipIfNoSecurity def test_w_factory_w_provides_w_permission(self): from zope.interface import Interface from zope.component.interface import provideInterface from zope.component.zcml import handler class IFoo(Interface): pass class Foo: pass _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, factory=Foo, 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') self.assertEqual(action['args'][1], None) self.assertEqual(action['args'][2], IFoo) self.assertEqual(action['args'][3], '') self.assertEqual(action['args'][4], 'TESTING') fctry = action['kw']['factory'] # Factory is wrapped self.assertNotEqual(fctry, Foo) self.assertEqual(fctry.factory, Foo) secured = fctry() self.assertIsInstance(secured, 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)) 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(): "foo" def bar(): "bar" class _View: __init__ = fails_if_called(self) foo = fails_if_called(self) bar = fails_if_called(self) _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: __init__ = fails_if_called(self) foo = fails_if_called(self) bar = fails_if_called(self) _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: pass class Bar: 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: __init__ = fails_if_called(self) _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.interface import provideInterface from zope.component.zcml import handler class IViewType(Interface): pass class _View: __init__ = fails_if_called(self) _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: def __init__(self, context): self.context = context class _View2: 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: 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: __init__ = fails_if_called(self) bar = fails_if_called(self) _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): "bar" class _View: __init__ = fails_if_called(self) bar = fails_if_called(self) _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(): "foo" def bar(): "bar" class _Resource: __init__ = fails_if_called(self) foo = fails_if_called(self) bar = fails_if_called(self) _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: __init__ = fails_if_called(self) foo = fails_if_called(self) bar = fails_if_called(self) _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: __init__ = fails_if_called(self) foo = fails_if_called(self) bar = fails_if_called(self) _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: def __init__(self, context): self.context = context foo = fails_if_called(self) bar = fails_if_called(self) _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: info = 'TESTING' def __init__(self): self._actions = [] def action(self, *args, **kw): self._actions.append((args, kw)) return _Context() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/src/zope/component/zcml.py0000644000100100000240000005002014416166371020073 0ustar00macstaff############################################################################## # # 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._compat import ZOPE_SECURITY_NOT_AVAILABLE_EX from zope.component._declaration import adaptedBy from zope.component._declaration import getName from zope.component.interface import provideInterface try: from zope.security.zcml import Permission except ZOPE_SECURITY_NOT_AVAILABLE_EX: # 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 protectedFactory from zope.component.security import proxify 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") if name == '': if len(factory) == 1: name = getName(factory[0]) # 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: p = list(implementedBy(factory)) if len(p) == 1: provides = p[0] 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_, '', _context.info), ) else: _context.action( discriminator=None, callable=_handler, args=('registerSubscriptionAdapter', factory, for_, provides, '', _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 name == '': if factory: name = getName(factory) else: name = getName(component) if permission is not None: if component: component = proxify(component, provides=provides, permission=permission) if factory: factory = protectedFactory(factory, provides, 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='', ) 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: """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)) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1681452282.154597 zope.component-6.0/src/zope.component.egg-info/0000755000100100000240000000000014416166372020251 5ustar00macstaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452282.0 zope.component-6.0/src/zope.component.egg-info/PKG-INFO0000644000100100000240000004165314416166372021357 0ustar00macstaffMetadata-Version: 2.1 Name: zope.component Version: 6.0 Summary: Zope Component Architecture Home-page: https://github.com/zopefoundation/zope.component Author: Zope Foundation and Contributors Author-email: zope-dev@zope.dev License: ZPL 2.1 Project-URL: Documentation, https://zopecomponent.readthedocs.io/ Project-URL: Issue Tracker, https://github.com/zopefoundation/zope.component/issues Project-URL: Sources, https://github.com/zopefoundation/zope.component Keywords: interface component coupling loose utility adapter 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 :: 3 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Framework :: Zope :: 3 Classifier: Framework :: Zope :: 5 Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=3.7 Provides-Extra: hook Provides-Extra: persistentregistry Provides-Extra: security Provides-Extra: zcml Provides-Extra: mintests Provides-Extra: test Provides-Extra: docs License-File: LICENSE.txt ================ zope.component ================ .. image:: https://github.com/zopefoundation/zope.component/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.component/actions/workflows/tests.yml :alt: Unit test status .. image:: https://coveralls.io/repos/github/zopefoundation/zope.component/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.component?branch=master :alt: Coverage Status .. image:: https://img.shields.io/pypi/v/zope.component.svg :target: https://pypi.python.org/pypi/zope.component/ :alt: Current version on PyPI .. image:: https://img.shields.io/pypi/pyversions/zope.component :target: https://pypi.org/project/zope.component/ :alt: Supported Python versions .. image:: https://readthedocs.org/projects/zopecomponent/badge/?version=latest :target: http://zopecomponent.readthedocs.org/en/latest/ :alt: Documentation Status .. note:: 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 https://zopecomponent.readthedocs.io/en/latest/ for the documentation. .. _zope.interface: https://github.com/zopefoundation/zope.interface ========= Changes ========= 6.0 (2023-04-14) ================ - Drop support for Python 2.7, 3.5, 3.6. 5.1.0 (2023-01-03) ================== - Fix crash when the environment variable `PYTHONOPTIMIZED` is set to `2` and docstrings are set to `None` by the interpreter. (`#67 `_) - Add support for Python 3.10 and 3.11. 5.0.1 (2021-07-09) ================== - Fix unregistering utilities on old persistent adapter registries. Previously this could raise ``TypeError``. See `issue 62 `_. 5.0.0 (2021-03-19) ================== - Remove backwards compatibility imports that were emitting deprecation warnings. This affects certain imports from ``zope.component.interfaces`` (which should be imported from ``zope.interface.interfaces``) as well as certain imports from ``zope.component.registery`` (import from ``zope.interface.registry``), and the entire ``zope.component.hookable`` module. See `issue 59 `_. - Respect permission value for utility factory registrations (`#54 `_) - Add support for Python 3.9 - Fix the ```` ZCML directive to allow a missing ``provides=`` attribute when a ``factory=`` is given and the Python object has been decorated with ``@implementer`` and implements a single interface. This has been documented, but hasn't worked before. See `issue 9 `_. - Make ``PersistentAdapterRegistry`` use persistent objects (``PersistentMapping`` and ``PersistentList``) for its internal data structures instead of plain dicts and lists. This helps make it scalable to larger registry sizes. This requires zope.interface 5.3.0a1 or later. New registries (and their primary users, ``PersistentComponents`` and zope.site's ``LocalSiteManager``) take full advantage of this automatically. For existing persistent registries to take advantage of this, you must call their ``rebuild()`` method and commit the transaction. See `issue 51 `_. - Fix ``zope.interface.interface.provideInterface`` and the various search and query methods to use the current site manager instead of always using the global site manager. (``provideInterface`` is called implicitly when registering components from ZCML.) The search and query methods continue to return interfaces registered in base site managers. See `issue 10 `_. 4.6.2 (2020-07-03) ================== - Improve the documentation, both published and in docstrings. See `PR 49 `_. 4.6.1 (2020-03-23) ================== - Ensure the resolution order of ``BaseGlobalComponents`` is consistent. See `issue 45 `_. 4.6.0 (2019-11-12) ================== - Add support for Python 3.8. - Drop support for Python 3.4. - Fix tests on Python 2 following changes in ZODB 5.5.0. 4.5.0 (2018-10-10) ================== - Add support for Python 3.7. - Always install ``zope.hookable`` as a dependency (the ``hook`` extra is now empty). ``zope.hookable`` respects the PURE_PYTHON environment variable, and has an optional C extension. - Make accessing names that have been moved to ``zope.interface`` produce a ``DeprecationWarning``. 4.4.1 (2017-09-26) ================== - Remove obsolete call of ``searchInterface`` from ``interfaceToName``. See https://github.com/zopefoundation/zope.component/issues/32 4.4.0 (2017-07-25) ================== - Add support for Python 3.6. - Drop support for Python 3.3. - Drop support for "setup.py test". - Code coverage reports are now `produced and hosted by coveralls.io `_, and PRs must keep them at 100%. - Internal test code in ``zope.component.testfiles`` has been adjusted and in some cases removed. 4.3.0 (2016-08-26) ================== - When testing ``PURE_PYTHON`` environments under ``tox``, avoid poisoning the user's global wheel cache. - Drop support for Python 2.6 and 3.2. - Add support for Python 3.5. 4.2.2 (2015-06-04) ================== - Fix test cases for PyPy and PyPy3. 4.2.1 (2014-03-19) ================== - Add support for Python 3.4. 4.2.0 (2014-02-05) ================== - Update ``boostrap.py`` to version 2.2. - Reset the cached ``adapter_hooks`` at ``zope.testing.cleanup.cleanUp`` time (LP1100501). - Implement ability to specify adapter and utility names in Python. Use the ``@zope.component.named(name)`` decorator to specify the name. 4.1.0 (2013-02-28) ================== - Change "ZODB3" depdendency to "persistent". - ``tox`` now runs all tests for Python 3.2 and 3.3. - Enable buildout for Python 3. - Fix new failing tests. 4.0.2 (2012-12-31) ================== - Flesh out PyPI Trove classifiers. 4.0.1 (2012-11-21) ================== - Add support for Python 3.3. 4.0.0 (2012-07-02) ================== - Add PyPy and Python 3.2 support: - Security support omitted until ``zope.security`` ported. - Persistent registry support omitted until ``ZODB`` ported (or ``persistent`` factored out). - Bring unit test coverage to 100%. - Remove the long-deprecated ``layer`` argument to the ``zope.component.zcml.view`` and ``zope.component.zcml.resource`` ZCML directives. - Add support for continuous integration using ``tox`` and ``jenkins``. - Got tests to run using ``setup.py test``. - Add ``Sphinx`` documentation. - Add ``setup.py docs`` alias (installs ``Sphinx`` and dependencies). - Add ``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) =================== - Move 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. - Move interfaces 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) =================== - Remove the ``docs`` extra and the ``sphinxdoc`` recipe. - Create a ``security`` extra to move security-related dependencies out of the ``test`` extra. - Use the new ``zope.testrunner`` package for tests. - Add 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 library ``doctest`` 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 change 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) ================== - Fix a bug introduced by recent refactoring, where passing ``CheckerPublic`` to ``securityAdapterFactory`` wrongly wrapped the factory into a ``LocatingUntrustedAdapterFactory``. 3.9.1 (2010-01-21) ================== - Modify the tests to avoid allowing the tested testrunner to be influenced by options of the outer testrunner, such a the ``-v`` option. 3.9.0 (2010-01-21) ================== - Add testlayer support. It is now possible to load a ZCML file within tests more easily. See ``src/zope/component/testlayer.py`` and ``src/zope/component/testlayer.txt``. 3.8.0 (2009-11-16) ================== - Remove the dependencies on ``zope.proxy`` and ``zope.security`` from the zcml extra: ``zope.component`` no longer has a hard dependency on them; the support for security proxied components ZCML registrations is enabled only if ``zope.security`` and ``zope.proxy`` are available. - Move 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. - Move 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) ================== - Fix a problem, where ``queryNextUtility`` could fail if the context could not be adapted to a ``IComponentLookup``. - Fix 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) ================== - Ensure that ``HookableTests`` are run by the testrunner. - Add ``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: - Move ``IView`` and ``IDefaultViewName`` to ``zope.publisher.interfaces``. - Move ``IResource`` to ``zope.app.publisher.interfaces``. - Remove ``IContextDependent``, ``IPresentation``, ``IPresentationRequest``, ``IResourceFactory``, and ``IViewFactory`` completely. If you used ``IViewFactory`` in context of ``zope.app.form``, there's now ``IWidgetFactory`` in the ``zope.app.form.interfaces`` instead. - Move ``getNextUtility`` / ``queryNextUtility`` functions here from ``zope.site`` (they were in ``zope.app.component`` even earlier). - Add a pure-Python ``hookable`` implementation, for use when ``zope.hookable`` is not present. - Remove 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. Fixes https://bugs.launchpad.net/zope3/+bug/240631 - Optimize ``un/registerUtility`` by 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. - Deprecated 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. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452282.0 zope.component-6.0/src/zope.component.egg-info/SOURCES.txt0000644000100100000240000000462414416166372022143 0ustar00macstaffCHANGES.rst CONTRIBUTING.md COPYRIGHT.txt LICENSE.txt MANIFEST.in README.rst buildout.cfg rtd.txt setup.cfg setup.py tox.ini docs/Makefile docs/api.rst docs/changelog.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/hooks.rst docs/api/interface.rst docs/api/interfaces.rst docs/api/module.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/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_hooks.py src/zope/component/tests/test_interface.py src/zope/component/tests/test_interfaces.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././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452282.0 zope.component-6.0/src/zope.component.egg-info/dependency_links.txt0000644000100100000240000000000114416166372024317 0ustar00macstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452282.0 zope.component-6.0/src/zope.component.egg-info/namespace_packages.txt0000644000100100000240000000000514416166372024577 0ustar00macstaffzope ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452282.0 zope.component-6.0/src/zope.component.egg-info/not-zip-safe0000644000100100000240000000000114416166372022477 0ustar00macstaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452282.0 zope.component-6.0/src/zope.component.egg-info/requires.txt0000644000100100000240000000070514416166372022653 0ustar00macstaffsetuptools zope.event zope.hookable>=4.2.0 zope.interface>=5.3 [docs] Sphinx repoze.sphinx.autointerface ZODB [hook] [mintests] zope.configuration zope.i18nmessageid zope.testing zope.testrunner [persistentregistry] persistent [security] zope.location zope.proxy zope.security [test] zope.configuration zope.i18nmessageid zope.testing zope.testrunner persistent zope.location zope.proxy zope.security [zcml] zope.configuration zope.i18nmessageid ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452282.0 zope.component-6.0/src/zope.component.egg-info/top_level.txt0000644000100100000240000000000514416166372022776 0ustar00macstaffzope ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1681452281.0 zope.component-6.0/tox.ini0000644000100100000240000000400514416166371014323 0ustar00macstaff# Generated from: # https://github.com/zopefoundation/meta/tree/master/config/pure-python [tox] minversion = 3.18 envlist = lint py37 py38 py39 py310 py311 pypy3 docs coverage py310-optimized [testenv] usedevelop = true deps = setenv = ZOPE_INTERFACE_STRICT_IRO=1 optimized: PYTHONOPTIMIZE=2 commands = zope-testrunner --test-path=src {posargs:-vc} sphinx-build -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest extras = test docs [testenv:lint] basepython = python3 skip_install = true commands = isort --check-only --diff {toxinidir}/src {toxinidir}/setup.py flake8 src setup.py check-manifest check-python-versions deps = check-manifest check-python-versions >= 0.19.1 wheel flake8 isort [testenv:isort-apply] basepython = python3 skip_install = true commands_pre = deps = isort commands = isort {toxinidir}/src {toxinidir}/setup.py [] [testenv:docs] basepython = python3 skip_install = false commands_pre = 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 [testenv:coverage] basepython = python3 allowlist_externals = mkdir deps = coverage commands = mkdir -p {toxinidir}/parts/htmlcov coverage run -m zope.testrunner --test-path=src {posargs:-vc} coverage run -a -m sphinx -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest coverage html --ignore-errors coverage report --ignore-errors --show-missing --fail-under=99.5 [coverage:run] branch = True source = zope.component omit = # Runs in a subprocess: src/zope/component/standalonetests.py # Not used: src/zope/component/eventtesting.py [coverage:report] precision = 2 exclude_lines = pragma: no cover pragma: nocover except ImportError: raise NotImplementedError if __name__ == '__main__': self.fail raise AssertionError [coverage:html] directory = parts/htmlcov