diff options
author | Michael Howitz <mh@gocept.com> | 2023-04-14 08:03:36 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-04-14 08:03:36 +0200 |
commit | 1c6af940c08ca2fdb142916974a192ab6ff9ea7c (patch) | |
tree | 924adcafcaf497f1fa5f4c2f506ff6085caa3ae6 | |
parent | ba0550c4645c3e73f32f7cd77bbe3cc528f76ad6 (diff) | |
download | zope-component-1c6af940c08ca2fdb142916974a192ab6ff9ea7c.tar.gz |
Config with pure python template (#71)
* Lint the code, improve coverage.
* Bumped version for breaking release.
* Drop support for Python 2.7, 3.5, 3.6.
48 files changed, 1536 insertions, 732 deletions
diff --git a/.editorconfig b/.editorconfig index 615323a..c5508b9 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,5 +1,5 @@ # Generated from: -# https://github.com/zopefoundation/meta/tree/master/config/zope-product +# https://github.com/zopefoundation/meta/tree/master/config/pure-python # # EditorConfig Configuration file, for more details see: # http://EditorConfig.org @@ -28,7 +28,7 @@ max_line_length = off # 4 space indentation indent_size = 4 -[*.{yml,zpt,pt,dtml}] +[*.{yml,zpt,pt,dtml,zcml}] # 2 space indentation indent_size = 2 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 8f30882..40ac6bb 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,3 +1,5 @@ +# Generated from: +# https://github.com/zopefoundation/meta/tree/master/config/pure-python name: tests on: @@ -14,23 +16,22 @@ jobs: # We want to see all failures: fail-fast: false matrix: + os: + - ["ubuntu", "ubuntu-20.04"] config: # [Python version, tox env] - - ["2.7", "py27"] - - ["2.7", "py27-minimal"] - - ["3.5", "py35"] - - ["3.6", "py36"] + - ["3.9", "lint"] - ["3.7", "py37"] - ["3.8", "py38"] - ["3.9", "py39"] - ["3.10", "py310"] - - ["3.10", "py310-optimized"] - ["3.11", "py311"] - - ["pypy-2.7", "pypy"] - - ["pypy-3.7", "pypy3"] - - ["3.8", "coverage"] + - ["pypy-3.9", "pypy3"] + - ["3.9", "docs"] + - ["3.9", "coverage"] + - ["3.10", "py310-optimized"] - runs-on: ubuntu-20.04 + runs-on: ${{ matrix.os[1] }} if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name name: ${{ matrix.config[1] }} steps: @@ -49,14 +50,14 @@ jobs: ${{ runner.os }}-pip- - name: Install dependencies run: | - python -m pip install --upgrade pip wheel + python -m pip install --upgrade pip pip install tox - name: Test run: tox -e ${{ matrix.config[1] }} - name: Coverage if: matrix.config[1] == 'coverage' run: | - pip install coveralls coverage-python-version + pip install coveralls coveralls --service=github env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -1,9 +1,11 @@ # Generated from: -# https://github.com/zopefoundation/meta/tree/master/config/zope-product +# https://github.com/zopefoundation/meta/tree/master/config/pure-python +*.dll *.egg-info/ *.profraw *.pyc *.pyo +*.so .coverage .coverage.* .eggs/ @@ -26,4 +28,5 @@ lib64 log/ parts/ pyvenv.cfg +testing.log var/ diff --git a/.meta.toml b/.meta.toml new file mode 100644 index 0000000..a471ee6 --- /dev/null +++ b/.meta.toml @@ -0,0 +1,58 @@ +# Generated from: +# https://github.com/zopefoundation/meta/tree/master/config/pure-python +[meta] +template = "pure-python" +commit-id = "fe63cb4c" + +[python] +with-sphinx-doctests = true +with-docs = true +with-future-python = false +with-pypy = true +with-macos = false +with-windows = false + +[tox] +use-flake8 = true +additional-envlist = [ + "py310-optimized", + ] +testenv-setenv = [ + "ZOPE_INTERFACE_STRICT_IRO=1", + "optimized: PYTHONOPTIMIZE=2", + ] + +[coverage] +fail-under = 99.5 + +[coverage-run] +additional-config = [ + "omit =", + " # Runs in a subprocess:", + " src/zope/component/standalonetests.py", + " # Not used:", + " src/zope/component/eventtesting.py", + ] + +[flake8] +additional-config = [ + "# F401 imported but unused", + "per-file-ignores =", + " src/zope/component/__init__.py: F401", + ] + +[manifest] +additional-rules = [ + "recursive-include docs *.bat", + "recursive-include src *.zcml", + ] + +[check-manifest] +additional-ignores = [ + "docs/_build/html/_sources/api/*", + ] + +[github-actions] +additional-config = [ + "- [\"3.10\", \"py310-optimized\"]", + ] diff --git a/CHANGES.rst b/CHANGES.rst index 1724bfc..c81ccc9 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -2,10 +2,12 @@ Changes ========= -5.1.1 (unreleased) -================== +6.0 (unreleased) +================ + +- Drop support for Python 2.7, 3.5, 3.6. 5.1.0 (2023-01-03) ================== diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..31d95f0 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,23 @@ +<!-- +Generated from: +https://github.com/zopefoundation/meta/tree/master/config/pure-python +--> +# 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. diff --git a/MANIFEST.in b/MANIFEST.in index c7630dc..1762883 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,12 +1,16 @@ +# 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 *.bat 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 @@ -1,18 +1,29 @@ +# Generated from: +# https://github.com/zopefoundation/meta/tree/master/config/pure-python [bdist_wheel] -universal = 1 +universal = 0 + +[flake8] +doctests = 1 +# F401 imported but unused +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/* -[nosetests] -nocapture=1 -cover-package=zope.component -cover-erase=1 -with-doctest=0 -where=src - -[aliases] -dev = develop easy_install zope.component[testing] -docs = easy_install zope.component[docs] +[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 @@ -20,7 +20,10 @@ """ import os -from setuptools import setup, find_packages + +from setuptools import find_packages +from setuptools import setup + HOOK_REQUIRES = [ ] @@ -60,9 +63,10 @@ def read(*rnames): with open(os.path.join(os.path.dirname(__file__), *rnames)) as f: return f.read() + setup( name='zope.component', - version='5.1.1.dev0', + version='6.0.dev0', url='https://github.com/zopefoundation/zope.component', project_urls={ 'Documentation': 'https://zopecomponent.readthedocs.io/', @@ -73,7 +77,7 @@ setup( license='ZPL 2.1', description='Zope Component Architecture', author='Zope Foundation and Contributors', - author_email='zope-dev@zope.org', + author_email='zope-dev@zope.dev', long_description=( read('README.rst') + '\n' + @@ -89,11 +93,7 @@ setup( "License :: OSI Approved :: Zope Public License", "Operating System :: OS Independent", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", - "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", @@ -102,16 +102,16 @@ setup( "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='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*', - tests_require=TESTS_REQUIRE, + namespace_packages=['zope', ], + python_requires='>=3.7', install_requires=[ 'setuptools', 'zope.event', 'zope.hookable >= 4.2.0', - 'zope.interface >= 5.3.0a1', + 'zope.interface >= 5.3', ], include_package_data=True, zip_safe=False, diff --git a/src/zope/component/__init__.py b/src/zope/component/__init__.py index 6aee904..1d3be06 100644 --- a/src/zope/component/__init__.py +++ b/src/zope/component/__init__.py @@ -27,19 +27,8 @@ 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.component.interfaces import IComponentArchitecture from zope.interface.interfaces import IComponentLookup -from zope.component.interfaces import IComponentRegistrationConvenience -from zope.component.interfaces import IFactory - -from zope.component.globalregistry import getGlobalSiteManager -from zope.component.globalregistry import globalSiteManager -from zope.component.globalregistry import provideAdapter -from zope.component.globalregistry import provideHandler -from zope.component.globalregistry import provideSubscriptionAdapter -from zope.component.globalregistry import provideUtility from zope.component._api import adapter_hook from zope.component._api import createObject @@ -50,26 +39,32 @@ 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 getNextUtility from zope.component._api import handle from zope.component._api import queryAdapter from zope.component._api import queryAdapterInContext from zope.component._api import queryMultiAdapter -from zope.component._api import queryUtility from zope.component._api import queryNextUtility +from zope.component._api import 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', -) +__all__ = tuple(IComponentArchitecture) \ + + tuple(IComponentRegistrationConvenience) \ + + ('named', 'adapts', 'adapter', 'adaptedBy', ) diff --git a/src/zope/component/_api.py b/src/zope/component/_api.py index 7e39ffc..4db983e 100644 --- a/src/zope/component/_api.py +++ b/src/zope/component/_api.py @@ -15,6 +15,7 @@ """ import sys +import zope.interface.interface from zope.hookable import hookable from zope.interface import Interface from zope.interface.interfaces import ComponentLookupError @@ -28,6 +29,8 @@ from zope.component.interfaces import inherits_arch_docs as inherits_docs # "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): @@ -47,6 +50,8 @@ def getSiteManager(context=None): raise ComponentLookupError(*error.args) # Adapter API + + @inherits_docs def getAdapterInContext(object, interface, context): adapter = queryAdapterInContext(object, interface, context) @@ -54,6 +59,7 @@ def getAdapterInContext(object, interface, context): raise ComponentLookupError(object, interface) return adapter + @inherits_docs def queryAdapterInContext(object, interface, context, default=None): conform = getattr(object, '__conform__', None) @@ -82,30 +88,34 @@ def queryAdapterInContext(object, interface, context, default=None): return getSiteManager(context).queryAdapter(object, interface, '', default) + @inherits_docs -def getAdapter(object, interface=Interface, name=u'', context=None): +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=u'', default=None, +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=u'', context=None): +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=u'', default=None, +def queryMultiAdapter(objects, interface=Interface, name='', default=None, context=None): try: sitemanager = getSiteManager(context) @@ -115,6 +125,7 @@ def queryMultiAdapter(objects, interface=Interface, name=u'', default=None, return sitemanager.queryMultiAdapter(objects, interface, name, default) + @inherits_docs def getAdapters(objects, provided, context=None): try: @@ -124,6 +135,7 @@ def getAdapters(objects, provided, context=None): return [] return sitemanager.getAdapters(objects, provided) + @inherits_docs def subscribers(objects, interface, context=None): try: @@ -133,6 +145,7 @@ def subscribers(objects, interface, context=None): return [] return sitemanager.subscribers(objects, interface) + @inherits_docs def handle(*objects): getSiteManager(None).subscribers(objects, None) @@ -142,16 +155,18 @@ def handle(*objects): # 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 + except ComponentLookupError: # pragma: no cover w/o context, cannot test # Oh blast, no site manager. This should *never* happen! return None return sitemanager.queryAdapter(object, interface, name, default) -import zope.interface.interface + zope.interface.interface.adapter_hooks.append(adapter_hook) ############################################################################# @@ -164,14 +179,17 @@ def getUtility(interface, name='', context=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) @@ -179,6 +197,7 @@ def getAllUtilitiesRegisteredFor(interface, context=None): _marker = object() + @inherits_docs def queryNextUtility(context, interface, name='', default=None): """Query for the next available utility. @@ -198,6 +217,7 @@ def queryNextUtility(context, interface, name='', default=None): return util return default + @inherits_docs def getNextUtility(context, interface, name=''): """Get the next available utility. @@ -207,7 +227,7 @@ def getNextUtility(context, interface, name=''): util = queryNextUtility(context, interface, name, _marker) if util is _marker: raise ComponentLookupError( - "No more utilities for %s, '%s' have been found." % ( + "No more utilities for {}, '{}' have been found.".format( interface, name)) return util @@ -223,6 +243,7 @@ def createObject(__factory_name, *args, **kwargs): 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 @@ -231,6 +252,7 @@ def getFactoryInterfaces(name, context=None): """ return getUtility(IFactory, name, context).getInterfaces() + @inherits_docs def getFactoriesFor(interface, context=None): """Return info on all factories implementing the given interface. diff --git a/src/zope/component/_compat.py b/src/zope/component/_compat.py index 3fe42b9..c50985a 100644 --- a/src/zope/component/_compat.py +++ b/src/zope/component/_compat.py @@ -11,40 +11,8 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## +from zope.interface.ro import InconsistentResolutionOrderError -import sys -import types -if sys.version_info[0] < 3: #pragma NO COVER - - import cPickle as _pickle - - CLASS_TYPES = (type, types.ClassType) - - PYTHON3 = False - PYTHON2 = True - -else: #pragma NO COVER - - import pickle as _pickle - - CLASS_TYPES = (type,) - - PYTHON3 = True - PYTHON2 = False - - -# Prior to https://github.com/zopefoundation/zope.security/issues/71 -# zope.security cannot be imported if zope.interface is enforcing -# strict resolution orders. But because zope.security has a dependency -# on this library, and older versions of this library also have problems -# with strict resolution orders, we have a chicken-and-egg scenario. In the -# interim, our only choice is to skip it. (But we don't want a hard dependency -# on zope.interface 5.0, so we do a conditional import.) -ZOPE_SECURITY_NOT_AVAILABLE_EX = (ImportError,) -try: - from zope.interface.ro import InconsistentResolutionOrderError -except ImportError: - pass -else: - ZOPE_SECURITY_NOT_AVAILABLE_EX += (InconsistentResolutionOrderError,) +ZOPE_SECURITY_NOT_AVAILABLE_EX = ( + ImportError, InconsistentResolutionOrderError) diff --git a/src/zope/component/_declaration.py b/src/zope/component/_declaration.py index 5e75d85..8de5b19 100644 --- a/src/zope/component/_declaration.py +++ b/src/zope/component/_declaration.py @@ -15,9 +15,8 @@ """ import sys -from zope.component._compat import CLASS_TYPES -class adapter(object): +class adapter: """ Decorator that declares that the decorated object adapts the given *interfaces*. @@ -25,17 +24,19 @@ class adapter(object): 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, CLASS_TYPES): + 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 @@ -49,16 +50,20 @@ def adapts(*interfaces): locals['__component_adapts__'] = _adapts_descr(interfaces) + def adaptedBy(ob): """ - Return the *interfaces* that *ob* will adapt, as declared by :obj:`adapter`. + 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__', u'') + return getattr(ob, '__component_name__', '') + -class _adapts_descr(object): +class _adapts_descr: def __init__(self, interfaces): self.interfaces = interfaces diff --git a/src/zope/component/event.py b/src/zope/component/event.py index a4d6740..0b80a0e 100644 --- a/src/zope/component/event.py +++ b/src/zope/component/event.py @@ -17,8 +17,8 @@ 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 @@ -26,6 +26,7 @@ from zope.component._declaration import adapter def dispatch(*event): component_subscribers(event, None) + event_subscribers.append(dispatch) diff --git a/src/zope/component/eventtesting.py b/src/zope/component/eventtesting.py index 229c56e..3ba3057 100644 --- a/src/zope/component/eventtesting.py +++ b/src/zope/component/eventtesting.py @@ -16,11 +16,13 @@ from zope.component import provideHandler from zope.component.event import objectEventNotify -from zope.component.registry import dispatchUtilityRegistrationEvent from zope.component.registry import dispatchAdapterRegistrationEvent -from zope.component.registry import ( - dispatchSubscriptionAdapterRegistrationEvent) from zope.component.registry import dispatchHandlerRegistrationEvent +from zope.component.registry import \ + dispatchSubscriptionAdapterRegistrationEvent +from zope.component.registry import dispatchUtilityRegistrationEvent + + try: from zope.testing.cleanup import addCleanUp except ImportError: @@ -28,6 +30,8 @@ except ImportError: pass events = [] + + def getEvents(event_type=None, filter=None): r = [] for event in events: @@ -39,10 +43,14 @@ def getEvents(event_type=None, filter=None): return r + def clearEvents(): del events[:] + + addCleanUp(clearEvents) + class PlacelessSetup: def setUp(self): @@ -53,5 +61,6 @@ class PlacelessSetup: provideHandler(dispatchHandlerRegistrationEvent) provideHandler(events.append, (None,)) + def setUp(test=None): PlacelessSetup().setUp() diff --git a/src/zope/component/factory.py b/src/zope/component/factory.py index d9edce2..fd0decd 100644 --- a/src/zope/component/factory.py +++ b/src/zope/component/factory.py @@ -13,14 +13,15 @@ ############################################################################## """Factory object """ -from zope.interface import implementer 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(object): +class Factory: """Generic factory implementation. The purpose of this implementation is to provide a quick way of creating @@ -43,5 +44,5 @@ class Factory(object): return spec return implementedBy(self._callable) - def __repr__(self): #pragma NO COVER - return '<%s for %s>' % (self.__class__.__name__, repr(self._callable)) + def __repr__(self): # pragma: no cover + return f'<{self.__class__.__name__} for {self._callable!r}>' diff --git a/src/zope/component/globalregistry.py b/src/zope/component/globalregistry.py index d48d39b..43a1c26 100644 --- a/src/zope/component/globalregistry.py +++ b/src/zope/component/globalregistry.py @@ -23,6 +23,7 @@ from zope.component.interfaces import inherits_reg_docs def GAR(components, registryName): return getattr(components, registryName) + class GlobalAdapterRegistry(AdapterRegistry): """A global adapter registry @@ -32,7 +33,7 @@ class GlobalAdapterRegistry(AdapterRegistry): def __init__(self, parent, name): self.__parent__ = parent self.__name__ = name - super(GlobalAdapterRegistry, self).__init__() + super().__init__() def __reduce__(self): return GAR, (self.__parent__, self.__name__) @@ -48,17 +49,20 @@ class BaseGlobalComponents(Components): # 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 +except ImportError: # pragma: no cover pass else: addCleanUp(lambda: base.__init__('base')) del addCleanUp globalSiteManager = base + + @inherits_arch_docs def getGlobalSiteManager(): return globalSiteManager @@ -67,18 +71,22 @@ def getGlobalSiteManager(): # We eventually want to deprecate these in favor of using the global # component registry directly. + @inherits_reg_docs -def provideUtility(component, provides=None, name=u''): +def provideUtility(component, provides=None, name=''): base.registerUtility(component, provides, name, event=False) + @inherits_reg_docs -def provideAdapter(factory, adapts=None, provides=None, name=u''): +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) diff --git a/src/zope/component/hooks.py b/src/zope/component/hooks.py index b1ce3f8..671af5d 100644 --- a/src/zope/component/hooks.py +++ b/src/zope/component/hooks.py @@ -20,16 +20,19 @@ 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 +except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover def removeSecurityProxy(x): return x -from zope.component.globalregistry import getGlobalSiteManager from zope.interface.interfaces import ComponentLookupError from zope.interface.interfaces import IComponentLookup +from zope.component.globalregistry import getGlobalSiteManager + + __all__ = [ 'setSite', 'getSite', @@ -39,12 +42,14 @@ __all__ = [ 'resetHooks', ] -class read_property(object): + +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 @@ -54,6 +59,7 @@ class read_property(object): return self.func(inst) + class SiteInfo(threading.local): site = None sm = getGlobalSiteManager() @@ -64,8 +70,10 @@ class SiteInfo(threading.local): self.adapter_hook = adapter_hook return adapter_hook + siteinfo = SiteInfo() + def setSite(site=None): if site is None: sm = getGlobalSiteManager() @@ -89,6 +97,7 @@ def setSite(site=None): except AttributeError: pass + def getSite(): return siteinfo.site @@ -152,6 +161,7 @@ def setHooks(): _api.adapter_hook.sethook(adapter_hook) _api.getSiteManager.sethook(getSiteManager) + def resetHooks(): """ Reset `zope.component.getSiteManager` and interface adaptation to @@ -175,11 +185,12 @@ def resetHooks(): except AttributeError: pass + # Clear the site thread global clearSite = setSite try: from zope.testing.cleanup import addCleanUp -except ImportError: #pragma NO COVER +except ImportError: # pragma: no cover pass else: addCleanUp(resetHooks) diff --git a/src/zope/component/interface.py b/src/zope/component/interface.py index 2317149..f03770d 100644 --- a/src/zope/component/interface.py +++ b/src/zope/component/interface.py @@ -14,12 +14,11 @@ """Interface utility functions """ from zope.interface import alsoProvides +from zope.interface.interfaces import ComponentLookupError from zope.interface.interfaces import IInterface -from zope.interface.interfaces import ComponentLookupError from zope.component._api import getSiteManager from zope.component._api import queryUtility -from zope.component._compat import CLASS_TYPES def provideInterface(id, interface, iface_type=None, info=''): @@ -31,10 +30,10 @@ def provideInterface(id, interface, iface_type=None, info=''): Previously it was always registered in the global site manager. """ if not id: - id = "%s.%s" % (interface.__module__, interface.__name__) + id = "{}.{}".format(interface.__module__, interface.__name__) if not IInterface.providedBy(interface): - if not isinstance(interface, CLASS_TYPES): + if not isinstance(interface, type): raise TypeError(id, "is not an interface or class") return @@ -96,7 +95,7 @@ def searchInterfaceUtilities(context, search_string=None, base=None): def getInterfaceAllDocs(interface): - iface_id = '%s.%s' % (interface.__module__, interface.__name__) + iface_id = '{}.{}'.format(interface.__module__, interface.__name__) docs = [str(iface_id).lower(), str(interface.__doc__).lower()] @@ -118,4 +117,4 @@ def nameToInterface(context, id): def interfaceToName(context, interface): if interface is None: return 'None' - return '%s.%s' % (interface.__module__, interface.__name__) + return '{}.{}'.format(interface.__module__, interface.__name__) diff --git a/src/zope/component/interfaces.py b/src/zope/component/interfaces.py index 9819457..801edee 100644 --- a/src/zope/component/interfaces.py +++ b/src/zope/component/interfaces.py @@ -20,6 +20,7 @@ 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): @@ -76,7 +77,8 @@ class IComponentArchitecture(Interface): def getNextUtility(context, interface, name=''): """Get the next available utility. - If no utility was found, a `~zope.interface.interfaces.ComponentLookupError` is raised. + If no utility was found, a + `~zope.interface.interfaces.ComponentLookupError` is raised. """ def getUtilitiesFor(interface, context=None): @@ -97,12 +99,13 @@ class IComponentArchitecture(Interface): # Adapter API def getAdapter(object, - interface=Interface, name=u'', + 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`. + adapter cannot be found, raises + `~zope.interface.interfaces.ComponentLookupError`. """ def getAdapterInContext(object, interface, context): @@ -140,7 +143,7 @@ class IComponentArchitecture(Interface): named adapter methods with an empty string for a name. """ - def queryAdapter(object, interface=Interface, name=u'', + def queryAdapter(object, interface=Interface, name='', default=None, context=None): """Look for a named adapter to an interface for an object @@ -171,7 +174,7 @@ class IComponentArchitecture(Interface): """ def queryMultiAdapter(objects, - interface=Interface, name=u'', + interface=Interface, name='', default=None, context=None): """Look for a multi-adapter to an interface for objects @@ -256,6 +259,7 @@ class IRegistry(Interface): """Return an iterable of component registrations """ + class IComponentRegistrationConvenience(Interface): """API for registering components. @@ -266,7 +270,7 @@ class IComponentRegistrationConvenience(Interface): activity. """ - def provideUtility(component, provides=None, name=u''): + def provideUtility(component, provides=None, name=''): """Register a utility globally A utility is registered to provide an interface with a @@ -276,7 +280,7 @@ class IComponentRegistrationConvenience(Interface): provided to provide a less specific interface.) """ - def provideAdapter(factory, adapts=None, provides=None, name=u''): + def provideAdapter(factory, adapts=None, provides=None, name=''): """Register an adapter globally An adapter is registered to provide an interface with a name @@ -333,9 +337,11 @@ class IPossibleSite(Interface): 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.""" @@ -350,7 +356,6 @@ class IFactory(Interface): def __call__(*args, **kw): """Return an instance of the objects we're a factory for.""" - def getInterfaces(): """Get the interfaces implemented by the factory @@ -368,20 +373,23 @@ def _inherits_docs(func, iface): # doc can be None if the interpreter drops all docstrings when the # environment variable PYTHONOPTIMIZE is set 2. if doc is None: - return func + 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 += "\n Function `~zope.component.%s` for notes, and " % (func.__name__,) - doc += "\n `~zope.component.interfaces.%s` for the defining interface." % (iface.__name__,) - doc += "\n" + 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) diff --git a/src/zope/component/persistentregistry.py b/src/zope/component/persistentregistry.py index 4f61e3d..79eb209 100644 --- a/src/zope/component/persistentregistry.py +++ b/src/zope/component/persistentregistry.py @@ -14,11 +14,12 @@ """Persistent component managers. """ from persistent import Persistent -from persistent.mapping import PersistentMapping 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. @@ -63,14 +64,16 @@ class PersistentAdapterRegistry(VerifyingAdapterRegistry, Persistent): 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 = 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) + existing_leaf_sequence = self._leafSequenceType( + existing_leaf_sequence) without_removed = VerifyingAdapterRegistry._removeValueFromLeaf( self, @@ -90,10 +93,10 @@ class PersistentAdapterRegistry(VerifyingAdapterRegistry, Persistent): # the changed() mechanism will still result in mutating this # object via ``_generation``. self._p_changed = True - super(PersistentAdapterRegistry, self).changed(originally_changed) + super().changed(originally_changed) def __getstate__(self): - state = super(PersistentAdapterRegistry, self).__getstate__().copy() + state = super().__getstate__().copy() for name in self._delegated: state.pop(name, 0) state.pop('ro', None) @@ -101,7 +104,7 @@ class PersistentAdapterRegistry(VerifyingAdapterRegistry, Persistent): def __setstate__(self, state): bases = state.pop('__bases__', ()) - super(PersistentAdapterRegistry, self).__setstate__(state) + super().__setstate__(state) self._createLookup() self.__bases__ = bases self._v_lookup.changed(self) diff --git a/src/zope/component/registry.py b/src/zope/component/registry.py index 2eb3d6b..05c45ae 100644 --- a/src/zope/component/registry.py +++ b/src/zope/component/registry.py @@ -14,27 +14,31 @@ """Basic components support """ -from zope.component._api import handle -from zope.component._declaration import adapter - 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) diff --git a/src/zope/component/security.py b/src/zope/component/security.py index 7b8023d..609929d 100644 --- a/src/zope/component/security.py +++ b/src/zope/component/security.py @@ -19,6 +19,7 @@ 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 @@ -27,7 +28,7 @@ try: 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 +except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover def _no_security(*args, **kw): raise TypeError( "security proxied components are not " @@ -43,6 +44,7 @@ except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover PublicPermission = 'zope.Public' + class PermissionProxy(ProxyBase): __slots__ = ('__Security_checker__', ) @@ -51,6 +53,7 @@ class PermissionProxy(ProxyBase): 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__"] @@ -70,6 +73,7 @@ def _checker(_context, permission, allowed_interface, allowed_attributes): 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 @@ -87,11 +91,13 @@ def proxify(ob, checker=None, provides=None, permission=None): 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: @@ -102,6 +108,7 @@ def protectedFactory(original_factory, provides, permission): factory.factory = original_factory return factory + def securityAdapterFactory(factory, permission, locate, trusted): if permission == PublicPermission: permission = CheckerPublic diff --git a/src/zope/component/standalonetests.py b/src/zope/component/standalonetests.py index 69d72a0..94667d5 100644 --- a/src/zope/component/standalonetests.py +++ b/src/zope/component/standalonetests.py @@ -2,28 +2,28 @@ See: https://bugs.launchpad.net/zope3/+bug/98401 """ -import sys import pickle +import sys + def write(x): sys.stdout.write('%s\n' % x) + if __name__ == "__main__": - if sys.version_info[0] >= 3: - # TextIO? Are you kidding me? - data = sys.stdin.buffer.read() - else: - data = sys.stdin.read() + # 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') - import zope from zope.interface import Interface from zope.interface import implementer + import zope + class I1(Interface): pass @@ -31,14 +31,14 @@ if __name__ == "__main__": pass @implementer(I1) - class Ob(object): + class Ob: def __repr__(self): return '<instance Ob>' ob = Ob() @implementer(I2) - class Comp(object): + class Comp: def __init__(self, context): self.context = context diff --git a/src/zope/component/testfiles/__init__.py b/src/zope/component/testfiles/__init__.py index 42462f1..717d76b 100644 --- a/src/zope/component/testfiles/__init__.py +++ b/src/zope/component/testfiles/__init__.py @@ -1 +1 @@ -#Python package +# Python package diff --git a/src/zope/component/testfiles/adapter.py b/src/zope/component/testfiles/adapter.py index 6728db1..6ab72a9 100644 --- a/src/zope/component/testfiles/adapter.py +++ b/src/zope/component/testfiles/adapter.py @@ -20,49 +20,66 @@ from zope.interface import implementer from zope.component import adapter from zope.component.testfiles import components + class I1(Interface): pass + class I2(Interface): pass + class I3(Interface): - def f1(): pass - def f2(): pass - def f3(): pass + def f1(): + pass # pragma: no cover + + def f2(): + pass # pragma: no cover + + def f3(): + pass # pragma: no cover + class IS(Interface): pass -class Adapter(object): +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, ) diff --git a/src/zope/component/testfiles/components.py b/src/zope/component/testfiles/components.py index c5edf96..8e45429 100644 --- a/src/zope/component/testfiles/components.py +++ b/src/zope/component/testfiles/components.py @@ -13,53 +13,69 @@ ############################################################################## """Components for testing """ -from zope.interface import Interface 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" + + def f(): + "test func" + class IApp(IAppb): pass + class IApp2(IAppb): pass + class IApp3(IAppb): pass -class IContent(Interface): pass + +class IContent(Interface): + pass + @implementer(IContent) -class Content(object): +class Content: pass + @adapter(IContent) @implementer(IApp) -class Comp(object): +class Comp: def __init__(self, *args): # Ignore arguments passed to constructor pass a = 1 - def f(): pass -class Comp2(object): + def f(): + pass # pragma: no cover + + +class Comp2: def __init__(self, context): self.context = context + @adapter(IContent) @implementer(IApp) @named('app') -class Comp4(object): +class Comp4: def __init__(self, context=None): self.context = context + comp = Comp() comp4 = Comp4() diff --git a/src/zope/component/testfiles/views.py b/src/zope/component/testfiles/views.py index d2dd3f2..9669189 100644 --- a/src/zope/component/testfiles/views.py +++ b/src/zope/component/testfiles/views.py @@ -16,5 +16,6 @@ from zope.interface import Interface + class IC(Interface): pass diff --git a/src/zope/component/testing.py b/src/zope/component/testing.py index d04c4ce..f210b52 100644 --- a/src/zope/component/testing.py +++ b/src/zope/component/testing.py @@ -15,23 +15,27 @@ """ # HACK to make sure basicmost event subscriber is installed -import zope.component.event +import zope.component.event # noqa: F401 imported but unused + # we really don't need special setup now: -class _PlacelessSetupFallback(object): +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 +except ImportError: # pragma: no cover PlacelessSetup = _PlacelessSetupFallback + def setUp(test=None): PlacelessSetup().setUp() + def tearDown(test=None): PlacelessSetup().tearDown() diff --git a/src/zope/component/testlayer.py b/src/zope/component/testlayer.py index f9d16ea..84ef2f1 100644 --- a/src/zope/component/testlayer.py +++ b/src/zope/component/testlayer.py @@ -14,19 +14,23 @@ import os -from zope.configuration import xmlconfig, config +from zope.configuration import config +from zope.configuration import xmlconfig + + try: from zope.testing.cleanup import cleanUp -except ImportError: # pragma: no cover +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 -from zope.component.eventtesting import events, clearEvents -class LayerBase(object): +class LayerBase: """Sane layer base class. zope.testing implements an advanced mechanism so that layer setUp, @@ -75,11 +79,13 @@ class LayerBase(object): def testTearDown(self): pass + class ZCMLLayerBase(LayerBase): """Base class to load up some ZCML. """ + def __init__(self, package, name=None, features=None): - super(ZCMLLayerBase, self).__init__(package, name) + super().__init__(package, name) self.features = features or [] def setUp(self): @@ -100,6 +106,7 @@ class ZCMLLayerBase(LayerBase): def _load_zcml(self, context): raise NotImplementedError + class ZCMLFileLayer(ZCMLLayerBase): """This layer can be used to run tests with a ZCML file loaded. @@ -108,9 +115,10 @@ class ZCMLFileLayer(ZCMLLayerBase): based on another ZCMLLayer's ZCML, just use a ZCML include statement in your own ZCML to load it. """ + def __init__(self, package, zcml_file='ftesting.zcml', name=None, features=None): - super(ZCMLFileLayer, self).__init__(package, name, features) + super().__init__(package, name, features) self.zcml_file = os.path.join(os.path.dirname(package.__file__), zcml_file) diff --git a/src/zope/component/tests/__init__.py b/src/zope/component/tests/__init__.py index 724fa59..1a947f1 100644 --- a/src/zope/component/tests/__init__.py +++ b/src/zope/component/tests/__init__.py @@ -1,14 +1,16 @@ import unittest + def skipIfNoSecurity(testfunc): from zope.component._compat import ZOPE_SECURITY_NOT_AVAILABLE_EX try: - import zope.security - except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover + 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): """ diff --git a/src/zope/component/tests/examples.py b/src/zope/component/tests/examples.py index d0013d0..a2b5b58 100644 --- a/src/zope/component/tests/examples.py +++ b/src/zope/component/tests/examples.py @@ -20,11 +20,14 @@ 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 @@ -32,94 +35,115 @@ class ITestType(IInterface): 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(object): + +class U: def __init__(self, name): self.__name__ = name def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, self.__name__) + 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)) + write('handle2 ' + repr(objects)) + @adapter(I1) def handle3(x): - write( 'handle3 %s' % x) + write('handle3 %s' % x) + @adapter(I1) def handle4(x): - write( 'handle4 %s' % x) + write('handle4 %s' % x) + class GlobalRegistry: pass -from zope.component.globalregistry import GlobalAdapterRegistry + base = GlobalAdapterRegistry(GlobalRegistry, 'adapters') GlobalRegistry.adapters = base + + def clear_base(): base.__init__(GlobalRegistry, 'adapters') @implementer(I1) -class Ob(object): +class Ob: def __repr__(self): return '<instance Ob>' ob = Ob() + @implementer(I2) -class Ob2(object): +class Ob2: def __repr__(self): return '<instance Ob2>' + @implementer(IC) -class Ob3(object): +class Ob3: pass + @implementer(I2) -class Comp(object): +class Comp: def __init__(self, context): self.context = context + comp = Comp(1) -class ConformsToIComponentLookup(object): +class ConformsToIComponentLookup: """Allow a dummy sitemanager to conform/adapt to `IComponentLookup`.""" def __init__(self, sitemanager): @@ -134,6 +158,7 @@ class ConformsToIComponentLookup(object): 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 diff --git a/src/zope/component/tests/test___init__.py b/src/zope/component/tests/test___init__.py index 2ffda83..e40f112 100644 --- a/src/zope/component/tests/test___init__.py +++ b/src/zope/component/tests/test___init__.py @@ -14,33 +14,39 @@ import unittest + class Test_package(unittest.TestCase): def test_module_conforms_to_IComponentArchitecture(self): from zope.interface.verify import verifyObject - from zope.component.interfaces import IComponentArchitecture + import zope.component as zc + from zope.component.interfaces import IComponentArchitecture verifyObject(IComponentArchitecture, zc) def test_module_conforms_to_IComponentRegistrationConvenience(self): from zope.interface.verify import verifyObject - from zope.component.interfaces import IComponentRegistrationConvenience + import zope.component as zc + from zope.component.interfaces import IComponentRegistrationConvenience verifyObject(IComponentRegistrationConvenience, zc) class Test_Interface_call(unittest.TestCase): - from zope.component.testing import setUp, tearDown + 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() @@ -49,16 +55,21 @@ class Test_Interface_call(unittest.TestCase): def test_hit(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IFoo) - class Baz(object): + class Baz: def __init__(self, context): self.context = context getGlobalSiteManager().registerAdapter(Baz, (IBar,), IFoo, '') @@ -70,11 +81,14 @@ class Test_Interface_call(unittest.TestCase): def test_hit_registered_for_None(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + @implementer(IFoo) - class Baz(object): + class Baz: def __init__(self, context): self.context = context getGlobalSiteManager().registerAdapter(Baz, (None,), IFoo, '') diff --git a/src/zope/component/tests/test__api.py b/src/zope/component/tests/test__api.py index ed1f5b8..a3bb331 100644 --- a/src/zope/component/tests/test__api.py +++ b/src/zope/component/tests/test__api.py @@ -17,9 +17,11 @@ import unittest from zope.component.tests import fails_if_called + class Test_getSiteManager(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component._api import getSiteManager @@ -51,10 +53,12 @@ class Test_getSiteManager(unittest.TestCase): def test_getSiteManager_w_invalid_context_w_adapter(self): from zope.interface import Interface - from zope.component.globalregistry import getGlobalSiteManager 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, '') @@ -63,7 +67,8 @@ class Test_getSiteManager(unittest.TestCase): class Test_getAdapterInContext(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import getAdapterInContext @@ -72,6 +77,7 @@ class Test_getAdapterInContext(unittest.TestCase): def test_miss(self): from zope.interface import Interface from zope.interface.interfaces import ComponentLookupError + class IFoo(Interface): pass self.assertRaises(ComponentLookupError, @@ -81,22 +87,29 @@ class Test_getAdapterInContext(unittest.TestCase): from zope.interface import Interface from zope.interface import implementer from zope.interface.registry import Components + from zope.component import getGlobalSiteManager from zope.component.tests.examples import ConformsToIComponentLookup + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IFoo) - class Global(object): + class Global: __init__ = fails_if_called(self) + @implementer(IFoo) - class Local(object): + class Local: def __init__(self, context): self.context = context + @implementer(IBar) - class Bar(object): + class Bar: pass + class Context(ConformsToIComponentLookup): def __init__(self, sm): self.sitemanager = sm @@ -112,7 +125,8 @@ class Test_getAdapterInContext(unittest.TestCase): class Test_queryAdapterInContext(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import queryAdapterInContext @@ -128,34 +142,37 @@ class Test_queryAdapterInContext(unittest.TestCase): def test_w_object_conforming(self): from zope.interface import Interface + class IFoo(Interface): pass _adapted = object() - class Foo(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) + 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 - _adapted = object() - class Foo(object): + + 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 - _adapted = object() - class Foo(object): + + class Foo: def __conform__(self, iface, default=None): raise TypeError self.assertRaises(TypeError, @@ -167,17 +184,19 @@ class Test_queryAdapterInContext(unittest.TestCase): class IFoo(Interface): pass + @implementer(IFoo) - class Foo(object): - pass + class Foo: + pass foo = Foo() self.assertIs( - self._callFUT(foo, IFoo, context=None), foo) + self._callFUT(foo, IFoo, context=None), foo) class Test_getAdapter(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import getAdapter @@ -186,6 +205,7 @@ class Test_getAdapter(unittest.TestCase): def test_anonymous_nonesuch(self): from zope.interface import Interface from zope.interface.interfaces import ComponentLookupError + class IFoo(Interface): pass self.assertRaises(ComponentLookupError, @@ -194,6 +214,7 @@ class Test_getAdapter(unittest.TestCase): def test_named_nonesuch(self): from zope.interface import Interface from zope.interface.interfaces import ComponentLookupError + class IFoo(Interface): pass self.assertRaises(ComponentLookupError, @@ -202,16 +223,21 @@ class Test_getAdapter(unittest.TestCase): def test_anonymous_hit(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IFoo) - class Baz(object): + class Baz: def __init__(self, context): self.context = context getGlobalSiteManager().registerAdapter(Baz, (IBar,), IFoo, '') @@ -223,11 +249,14 @@ class Test_getAdapter(unittest.TestCase): def test_anonymous_hit_registered_for_None(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + @implementer(IFoo) - class Baz(object): + class Baz: def __init__(self, context): self.context = context getGlobalSiteManager().registerAdapter(Baz, (None,), IFoo, '') @@ -239,16 +268,21 @@ class Test_getAdapter(unittest.TestCase): def test_named_hit(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IFoo) - class Baz(object): + class Baz: def __init__(self, context): self.context = context getGlobalSiteManager().registerAdapter(Baz, (IBar,), IFoo, 'named') @@ -260,7 +294,8 @@ class Test_getAdapter(unittest.TestCase): class Test_queryAdapter(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import queryAdapter @@ -268,6 +303,7 @@ class Test_queryAdapter(unittest.TestCase): def test_anonymous_nonesuch(self): from zope.interface import Interface + class IFoo(Interface): pass self.assertEqual(self._callFUT(object(), IFoo, '', '<default>'), @@ -275,6 +311,7 @@ class Test_queryAdapter(unittest.TestCase): def test_named_nonesuch(self): from zope.interface import Interface + class IFoo(Interface): pass self.assertEqual(self._callFUT(object(), IFoo, 'bar'), None) @@ -282,16 +319,21 @@ class Test_queryAdapter(unittest.TestCase): def test_anonymous_hit(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IFoo) - class Baz(object): + class Baz: def __init__(self, context): self.context = context getGlobalSiteManager().registerAdapter(Baz, (IBar,), IFoo, '') @@ -303,16 +345,21 @@ class Test_queryAdapter(unittest.TestCase): def test_named_hit(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IFoo) - class Baz(object): + class Baz: def __init__(self, context): self.context = context getGlobalSiteManager().registerAdapter(Baz, (IBar,), IFoo, 'named') @@ -325,22 +372,29 @@ class Test_queryAdapter(unittest.TestCase): from zope.interface import Interface from zope.interface import implementer from zope.interface.registry import Components + from zope.component import getGlobalSiteManager from zope.component.tests.examples import ConformsToIComponentLookup + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IFoo) - class Global(object): + class Global: __init__ = fails_if_called(self) + @implementer(IFoo) - class Local(object): + class Local: def __init__(self, context): self.context = context + @implementer(IBar) - class Bar(object): + class Bar: pass + class Context(ConformsToIComponentLookup): def __init__(self, sm): self.sitemanager = sm @@ -356,7 +410,8 @@ class Test_queryAdapter(unittest.TestCase): class Test_getMultiAdapter(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import getMultiAdapter @@ -365,6 +420,7 @@ class Test_getMultiAdapter(unittest.TestCase): def test_anonymous_nonesuch(self): from zope.interface import Interface from zope.interface.interfaces import ComponentLookupError + class IFoo(Interface): pass self.assertRaises(ComponentLookupError, @@ -373,6 +429,7 @@ class Test_getMultiAdapter(unittest.TestCase): def test_named_nonesuch(self): from zope.interface import Interface from zope.interface.interfaces import ComponentLookupError + class IFoo(Interface): pass self.assertRaises(ComponentLookupError, @@ -381,25 +438,32 @@ class Test_getMultiAdapter(unittest.TestCase): def test_anonymous_hit(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + class IBaz(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IBaz) - class Baz(object): + class Baz: pass + @implementer(IFoo) - class FooAdapter(object): + class FooAdapter: def __init__(self, first, second): self.first, self.second = first, second getGlobalSiteManager().registerAdapter( - FooAdapter, (IBar, IBaz), IFoo, '') + FooAdapter, (IBar, IBaz), IFoo, '') bar = Bar() baz = Baz() adapted = self._callFUT((bar, baz), IFoo, '') @@ -410,22 +474,28 @@ class Test_getMultiAdapter(unittest.TestCase): def test_anonymous_hit_registered_for_None(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + class IBaz(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IFoo) - class FooAdapter(object): + class FooAdapter: def __init__(self, first, second): self.first, self.second = first, second getGlobalSiteManager().registerAdapter( - FooAdapter, (IBar, None), IFoo, '') + FooAdapter, (IBar, None), IFoo, '') bar = Bar() baz = object() adapted = self._callFUT((bar, baz), IFoo, '') @@ -436,25 +506,32 @@ class Test_getMultiAdapter(unittest.TestCase): def test_named_hit(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + class IBaz(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IBaz) - class Baz(object): + class Baz: pass + @implementer(IFoo) - class FooAdapter(object): + class FooAdapter: def __init__(self, first, second): self.first, self.second = first, second getGlobalSiteManager().registerAdapter( - FooAdapter, (IBar, IBaz), IFoo, 'named') + FooAdapter, (IBar, IBaz), IFoo, 'named') bar = Bar() baz = Baz() adapted = self._callFUT((bar, baz), IFoo, 'named') @@ -465,7 +542,8 @@ class Test_getMultiAdapter(unittest.TestCase): class Test_queryMultiAdapter(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import queryMultiAdapter @@ -473,14 +551,16 @@ class Test_queryMultiAdapter(unittest.TestCase): def test_anonymous_nonesuch(self): from zope.interface import Interface + class IFoo(Interface): pass self.assertEqual(self._callFUT((object(), object()), IFoo, '', - '<default>'), + '<default>'), '<default>') def test_named_nonesuch(self): from zope.interface import Interface + class IFoo(Interface): pass self.assertEqual(self._callFUT((object(), object()), IFoo, 'bar'), @@ -489,25 +569,32 @@ class Test_queryMultiAdapter(unittest.TestCase): def test_anonymous_hit(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + class IBaz(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IBaz) - class Baz(object): + class Baz: pass + @implementer(IFoo) - class FooAdapter(object): + class FooAdapter: def __init__(self, first, second): self.first, self.second = first, second getGlobalSiteManager().registerAdapter( - FooAdapter, (IBar, IBaz), IFoo, '') + FooAdapter, (IBar, IBaz), IFoo, '') bar = Bar() baz = Baz() adapted = self._callFUT((bar, baz), IFoo, '') @@ -518,25 +605,32 @@ class Test_queryMultiAdapter(unittest.TestCase): def test_named_hit(self): from zope.interface import Interface from zope.interface import implementer + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + class IBaz(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IBaz) - class Baz(object): + class Baz: pass + @implementer(IFoo) - class FooAdapter(object): + class FooAdapter: def __init__(self, first, second): self.first, self.second = first, second getGlobalSiteManager().registerAdapter( - FooAdapter, (IBar, IBaz), IFoo, 'named') + FooAdapter, (IBar, IBaz), IFoo, 'named') bar = Bar() baz = Baz() adapted = self._callFUT((bar, baz), IFoo, 'named') @@ -548,27 +642,36 @@ class Test_queryMultiAdapter(unittest.TestCase): from zope.interface import Interface from zope.interface import implementer from zope.interface.registry import Components + from zope.component import getGlobalSiteManager from zope.component.tests.examples import ConformsToIComponentLookup + class IFoo(Interface): pass + class IBar(Interface): pass + class IBaz(Interface): pass + @implementer(IBar) - class Bar(object): + class Bar: pass + @implementer(IBaz) - class Baz(object): + class Baz: pass + @implementer(IFoo) - class Global(object): + class Global: __init__ = fails_if_called(self) + @implementer(IFoo) - class Local(object): + class Local: def __init__(self, first, second): self.first, self.second = first, second + class Context(ConformsToIComponentLookup): def __init__(self, sm): self.sitemanager = sm @@ -587,19 +690,25 @@ class Test_queryMultiAdapter(unittest.TestCase): 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(object): + class Bar: pass + @implementer(IBaz) - class Baz(object): + class Baz: pass - class Context(object): + + class Context: def __conform__(self, iface): raise ComponentLookupError bar = Bar() @@ -610,7 +719,8 @@ class Test_queryMultiAdapter(unittest.TestCase): class Test_getAdapters(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import getAdapters @@ -618,19 +728,24 @@ class Test_getAdapters(unittest.TestCase): def test_nonesuch(self): from zope.interface import Interface + class IFoo(Interface): pass self.assertEqual(list(self._callFUT((object(),), IFoo)), []) def test_hit(self): from zope.interface import Interface + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass - class BarAdapter(object): + + class BarAdapter: def __init__(self, context): self.context = context - class BazAdapter(object): + + class BazAdapter: def __init__(self, context): self.context = context gsm = getGlobalSiteManager() @@ -646,19 +761,25 @@ class Test_getAdapters(unittest.TestCase): 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(object): + class Bar: pass + @implementer(IBaz) - class Baz(object): + class Baz: pass - class Context(object): + + class Context: def __conform__(self, iface): raise ComponentLookupError bar = Bar() @@ -669,7 +790,8 @@ class Test_getAdapters(unittest.TestCase): class Test_subscribers(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import subscribers @@ -677,6 +799,7 @@ class Test_subscribers(unittest.TestCase): def test_nonesuch(self): from zope.interface import Interface + class IFoo(Interface): pass subscribers = self._callFUT((object,), IFoo) @@ -684,13 +807,17 @@ class Test_subscribers(unittest.TestCase): def test_hit(self): from zope.interface import Interface + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass - class BarAdapter(object): + + class BarAdapter: def __init__(self, context): self.context = context - class BazAdapter(object): + + class BazAdapter: def __init__(self, context): self.context = context gsm = getGlobalSiteManager() @@ -705,9 +832,11 @@ class Test_subscribers(unittest.TestCase): def test_wo_sitemanager(self): from zope.interface import Interface from zope.interface.interfaces import ComponentLookupError + class IFoo(Interface): pass - class Context(object): + + class Context: def __conform__(self, iface): raise ComponentLookupError subscribers = self._callFUT((object,), IFoo, context=Context()) @@ -716,7 +845,8 @@ class Test_subscribers(unittest.TestCase): class Test_handle(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import handle @@ -724,24 +854,30 @@ class Test_handle(unittest.TestCase): def test_nonesuch(self): from zope.interface import Interface + class IFoo(Interface): pass - subscribers = self._callFUT((object,), IFoo) #doesn't raise + self._callFUT((object,), IFoo) # doesn't raise def test_hit(self): - from zope.component import getGlobalSiteManager from zope.interface import Interface from zope.interface import implementer + + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass + @implementer(IFoo) - class Foo(object): + class Foo: pass _called = [] + def _bar(context): - _called.append('_bar') + _called.append('_bar') + def _baz(context): - _called.append('_baz') + _called.append('_baz') gsm = getGlobalSiteManager() gsm.registerHandler(_bar, (IFoo,)) gsm.registerHandler(_baz, (IFoo,)) @@ -753,7 +889,8 @@ class Test_handle(unittest.TestCase): class Test_getUtility(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component._api import getUtility @@ -762,6 +899,7 @@ class Test_getUtility(unittest.TestCase): 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) @@ -769,6 +907,7 @@ class Test_getUtility(unittest.TestCase): def test_named_nonesuch(self): from zope.interface import Interface from zope.interface.interfaces import ComponentLookupError + class IFoo(Interface): pass self.assertRaises(ComponentLookupError, @@ -776,7 +915,9 @@ class Test_getUtility(unittest.TestCase): def test_anonymous_hit(self): from zope.interface import Interface + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass obj = object() @@ -785,7 +926,9 @@ class Test_getUtility(unittest.TestCase): def test_named_hit(self): from zope.interface import Interface + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass obj = object() @@ -794,13 +937,17 @@ class Test_getUtility(unittest.TestCase): def test_w_conforming_context(self): from zope.interface import Interface + from zope.component import getGlobalSiteManager from zope.component.tests.examples import ConformsToIComponentLookup - class SM(object): + + class SM: def __init__(self, obj): self._obj = obj + def queryUtility(self, interface, name, default): return self._obj + class IFoo(Interface): pass obj1 = object() @@ -813,7 +960,8 @@ class Test_getUtility(unittest.TestCase): class Test_queryUtility(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component._api import queryUtility @@ -821,12 +969,14 @@ class Test_queryUtility(unittest.TestCase): 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() @@ -834,12 +984,14 @@ class Test_queryUtility(unittest.TestCase): 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() @@ -847,7 +999,9 @@ class Test_queryUtility(unittest.TestCase): def test_anonymous_hit(self): from zope.interface import Interface + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass obj = object() @@ -856,7 +1010,9 @@ class Test_queryUtility(unittest.TestCase): def test_named_hit(self): from zope.interface import Interface + from zope.component import getGlobalSiteManager + class IFoo(Interface): pass obj = object() @@ -865,13 +1021,17 @@ class Test_queryUtility(unittest.TestCase): def test_w_conforming_context(self): from zope.interface import Interface + from zope.component import getGlobalSiteManager from zope.component.tests.examples import ConformsToIComponentLookup - class SM(object): + + class SM: def __init__(self, obj): self._obj = obj + def queryUtility(self, interface, name, default): return self._obj + class IFoo(Interface): pass obj1 = object() @@ -884,7 +1044,8 @@ class Test_queryUtility(unittest.TestCase): class Test_getUtilitiesFor(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component._api import getUtilitiesFor @@ -892,13 +1053,16 @@ class Test_getUtilitiesFor(unittest.TestCase): 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() @@ -913,7 +1077,8 @@ class Test_getUtilitiesFor(unittest.TestCase): class Test_getAllUtilitiesRegisteredFor(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import getAllUtilitiesRegisteredFor @@ -921,15 +1086,19 @@ class Test_getAllUtilitiesRegisteredFor(unittest.TestCase): 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() @@ -947,7 +1116,8 @@ class Test_getAllUtilitiesRegisteredFor(unittest.TestCase): class Test_getNextUtility(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import getNextUtility @@ -963,9 +1133,10 @@ class Test_getNextUtility(unittest.TestCase): self._callFUT, gutil, IMyUtility, 'myutil') def test_nested(self): - from zope.component import getGlobalSiteManager 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') @@ -983,7 +1154,8 @@ class Test_getNextUtility(unittest.TestCase): class Test_queryNextUtility(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import queryNextUtility @@ -997,8 +1169,9 @@ class Test_queryNextUtility(unittest.TestCase): self.assertEqual(self._callFUT(gutil, IMyUtility, 'myutil'), None) def test_nested(self): - from zope.component import getGlobalSiteManager from zope.interface.registry import Components + + from zope.component import getGlobalSiteManager gsm = getGlobalSiteManager() gutil = _makeMyUtility('global', gsm) gsm.registerUtility(gutil, IMyUtility, 'myutil') @@ -1014,15 +1187,17 @@ class Test_queryNextUtility(unittest.TestCase): 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) + 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(object): + + class Context: def __conform__(self, iface): raise ComponentLookupError self.assertEqual(self._callFUT(Context(), IFoo, 'myutil'), None) @@ -1030,7 +1205,8 @@ class Test_queryNextUtility(unittest.TestCase): class Test_createObject(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import createObject @@ -1044,12 +1220,15 @@ class Test_createObject(unittest.TestCase): from zope.component.interfaces import IFactory _object = object() _factory_called = [] + def _factory(*args, **kw): _factory_called.append((args, kw)) return _object - class Context(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') @@ -1062,7 +1241,8 @@ class Test_createObject(unittest.TestCase): class Test_getFactoryInterfaces(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import getFactoryInterfaces @@ -1073,16 +1253,21 @@ class Test_getFactoryInterfaces(unittest.TestCase): self.assertRaises(ComponentLookupError, self._callFUT, 'nonesuch') def test_hit(self): - from zope.component.interfaces import IFactory from zope.interface import Interface + + from zope.component.interfaces import IFactory + class IFoo(Interface): pass - class _Factory(object): + + class _Factory: def getInterfaces(self): return [IFoo] - class Context(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') @@ -1094,7 +1279,8 @@ class Test_getFactoryInterfaces(unittest.TestCase): class Test_getFactoriesFor(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component import getFactoriesFor @@ -1102,6 +1288,7 @@ class Test_getFactoriesFor(unittest.TestCase): def test_no_factories_registered(self): from zope.interface import Interface + class IFoo(Interface): pass self.assertEqual(list(self._callFUT(IFoo)), []) @@ -1110,19 +1297,25 @@ class Test_getFactoriesFor(unittest.TestCase): from zope.interface import Interface from zope.interface import implementer from zope.interface import providedBy + from zope.component.interfaces import IFactory + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IFoo, IBar) - class _Factory(object): + class _Factory: def getInterfaces(self): return providedBy(self) _factory = _Factory() - class Context(object): + + class Context: def __conform__(self, iface): return self + def getUtilitiesFor(self, iface): if iface is IFactory: return [('test', _factory)] @@ -1133,18 +1326,24 @@ class Test_getFactoriesFor(unittest.TestCase): def test_w_factory_returning_list_of_interfaces(self): from zope.interface import Interface + from zope.component.interfaces import IFactory + class IFoo(Interface): pass + class IBar(Interface): pass - class _Factory(object): + + class _Factory: def getInterfaces(self): return [IFoo, IBar] _factory = _Factory() - class Context(object): + + class Context: def __conform__(self, iface): return self + def getUtilitiesFor(self, iface): if iface is IFactory: return [('test', _factory)] @@ -1155,10 +1354,13 @@ class Test_getFactoriesFor(unittest.TestCase): 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: diff --git a/src/zope/component/tests/test__declaration.py b/src/zope/component/tests/test__declaration.py index 1db841d..62ee4f3 100644 --- a/src/zope/component/tests/test__declaration.py +++ b/src/zope/component/tests/test__declaration.py @@ -15,6 +15,7 @@ """ import unittest + class Test_adapter(unittest.TestCase): def _getTargetClass(self): @@ -30,8 +31,10 @@ class Test_adapter(unittest.TestCase): def test_ctor_w_interfaces(self): from zope.interface import Interface + class IFoo(Interface): pass + class IBar(Interface): pass deco = self._makeOne(IFoo, IBar) @@ -39,23 +42,29 @@ class Test_adapter(unittest.TestCase): def test__call___w_class(self): from zope.interface import Interface + class IFoo(Interface): pass + class IBar(Interface): pass + @self._makeOne(IFoo, IBar) - class Baz(object): + 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(object): + class Baz: pass baz = Baz() self.assertRaises(AttributeError, @@ -63,11 +72,14 @@ class Test_adapter(unittest.TestCase): def test__call___w_non_class(self): from zope.interface import Interface + class IFoo(Interface): pass + class IBar(Interface): pass - class Baz(object): + + class Baz: pass deco = self._makeOne(IFoo, IBar) baz = deco(Baz()) @@ -81,23 +93,28 @@ class Test_adapts(unittest.TestCase): with warnings.catch_warnings(record=True) as log: warnings.resetwarnings() exec(code, globs, locs) - self.assertEqual(len(log), 0) # no longer warn + self.assertEqual(len(log), 0) # no longer warn return True def test_instances_not_affected(self): from zope.component._declaration import adapts - class C(object): + + 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.component._declaration import adapts + from zope.interface import Interface + + from zope.component._declaration import adapts + class IFoo(Interface): pass globs = {'adapts': adapts, 'IFoo': IFoo} @@ -105,21 +122,24 @@ class Test_adapts(unittest.TestCase): 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 + self.assertEqual(len(log), 0) # no longer warn def test_called_twice_from_class(self): import warnings - from zope.component._declaration import adapts + from zope.interface import Interface - from zope.interface._compat import PYTHON3 + + from zope.component._declaration import adapts + class IFoo(Interface): pass + class IBar(Interface): pass globs = {'adapts': adapts, 'IFoo': IFoo, 'IBar': IBar} @@ -128,16 +148,18 @@ class Test_adapts(unittest.TestCase): '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 + self.assertEqual(len(log), 0) # no longer warn def test_called_once_from_class(self): - from zope.component._declaration import adapts from zope.interface import Interface + + from zope.component._declaration import adapts + class IFoo(Interface): pass globs = {'adapts': adapts, 'IFoo': IFoo} @@ -145,7 +167,7 @@ class Test_adapts(unittest.TestCase): CODE = "\n".join([ 'class Foo(object):', ' adapts(IFoo)', - ]) + ]) self._run_generated_code(CODE, globs, locs) Foo = locs['Foo'] spec = Foo.__component_adapts__ @@ -163,33 +185,43 @@ class Test_adaptedBy(unittest.TestCase): def test__call___w_class(self): from zope.interface import Interface + class IFoo(Interface): pass + class IBar(Interface): pass - class Baz(object): + + 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(object): + + 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(object): + + class Baz: pass baz = Baz() baz.__component_adapts__ = (IFoo, IBar) diff --git a/src/zope/component/tests/test_event.py b/src/zope/component/tests/test_event.py index c6d93ca..3915bc4 100644 --- a/src/zope/component/tests/test_event.py +++ b/src/zope/component/tests/test_event.py @@ -15,40 +15,47 @@ """ import unittest + class Test_dispatch(unittest.TestCase): def test_it(self): from zope.interface import Interface - from zope.component.globalregistry import getGlobalSiteManager + from zope.component.event import dispatch + 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 + del _adapted[:] # clear handler reg event = object() dispatch(event) self.assertEqual(_adapted, [event]) + class Test_objectEventNotify(unittest.TestCase): def test_it(self): from zope.interface import Interface from zope.interface import implementer - from zope.component.globalregistry import getGlobalSiteManager from zope.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 + del _adapted[:] # clear handler reg + @implementer(IObjectEvent) - class _ObjectEvent(object): + class _ObjectEvent: def __init__(self, object): self.object = object context = object() diff --git a/src/zope/component/tests/test_factory.py b/src/zope/component/tests/test_factory.py index 7c487b5..b732fb8 100644 --- a/src/zope/component/tests/test_factory.py +++ b/src/zope/component/tests/test_factory.py @@ -17,6 +17,7 @@ import unittest from zope.component.tests import fails_if_called + class FactoryTests(unittest.TestCase): def _getTargetClass(self): @@ -30,11 +31,13 @@ class FactoryTests(unittest.TestCase): 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()) @@ -53,6 +56,7 @@ class FactoryTests(unittest.TestCase): def test___call___no_args(self): _called = [] + def _callable(*args, **kw): _called.append((args, kw)) factory = self._makeOne(_callable) @@ -61,6 +65,7 @@ class FactoryTests(unittest.TestCase): def test___call___positional_args(self): _called = [] + def _callable(*args, **kw): _called.append((args, kw)) factory = self._makeOne(_callable) @@ -69,6 +74,7 @@ class FactoryTests(unittest.TestCase): def test___call___keyword_args(self): _called = [] + def _callable(*args, **kw): _called.append((args, kw)) factory = self._makeOne(_callable) @@ -78,10 +84,13 @@ class FactoryTests(unittest.TestCase): 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) @@ -95,6 +104,7 @@ class FactoryTests(unittest.TestCase): 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)) diff --git a/src/zope/component/tests/test_globalregistry.py b/src/zope/component/tests/test_globalregistry.py index 9c0924c..1876049 100644 --- a/src/zope/component/tests/test_globalregistry.py +++ b/src/zope/component/tests/test_globalregistry.py @@ -17,6 +17,7 @@ import unittest from zope.component.tests import fails_if_called + class Test_getGlobalSiteManager(unittest.TestCase): def _callFUT(self): @@ -24,8 +25,9 @@ class Test_getGlobalSiteManager(unittest.TestCase): return getGlobalSiteManager() def test_gsm_is_IComponentLookup(self): - from zope.component.globalregistry import base 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)) @@ -35,24 +37,25 @@ class Test_getGlobalSiteManager(unittest.TestCase): self.assertTrue(self._callFUT() is gsm) def test_gsm_pickling(self): - from zope.component._compat import _pickle + import pickle gsm = self._callFUT() - dumped = _pickle.dumps(gsm) - loaded = _pickle.loads(dumped) + 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) + 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) + dumped_adapters = pickle.dumps(gsm.adapters) + loaded_adapters = pickle.loads(dumped_adapters) self.assertTrue(loaded_adapters is gsm.adapters) class Test_provideUtility(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.globalregistry import provideUtility @@ -61,11 +64,14 @@ class Test_provideUtility(unittest.TestCase): def test_anonymous_no_provides(self): from zope.interface import Interface from zope.interface import implementer + from zope.component.globalregistry import getGlobalSiteManager + class IFoo(Interface): pass + @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() self._callFUT(foo) @@ -79,10 +85,13 @@ class Test_provideUtility(unittest.TestCase): def test_named_w_provides(self): from zope.interface import Interface + from zope.component.globalregistry import getGlobalSiteManager + class IFoo(Interface): pass - class Foo(object): + + class Foo: pass foo = Foo() self._callFUT(foo, IFoo, 'named') @@ -92,7 +101,8 @@ class Test_provideUtility(unittest.TestCase): class Test_provideAdapter(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.globalregistry import provideAdapter @@ -101,18 +111,23 @@ class Test_provideAdapter(unittest.TestCase): def test_anonymous_no_provides_no_adapts(self): from zope.interface import Interface from zope.interface import implementer - from zope.component.globalregistry import getGlobalSiteManager + from zope.component._declaration import adapter + from zope.component.globalregistry import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IFoo) - class Foo(object): + class Foo: pass + @adapter(IFoo) @implementer(IBar) - class Bar(object): + class Bar: def __init__(self, context): self.context = context self._callFUT(Bar) @@ -125,15 +140,20 @@ class Test_provideAdapter(unittest.TestCase): def test_named_w_provides_w_adapts(self): from zope.interface import Interface from zope.interface import implementer + from zope.component.globalregistry import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IFoo) - class Foo(object): + class Foo: pass - class Bar(object): + + class Bar: def __init__(self, context): self.context = context self._callFUT(Bar, (IFoo,), IBar, 'test') @@ -146,7 +166,8 @@ class Test_provideAdapter(unittest.TestCase): class Test_provideSubscriptionAdapter(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.globalregistry import provideSubscriptionAdapter @@ -155,18 +176,23 @@ class Test_provideSubscriptionAdapter(unittest.TestCase): def test_no_provides_no_adapts(self): from zope.interface import Interface from zope.interface import implementer - from zope.component.globalregistry import getGlobalSiteManager + from zope.component._declaration import adapter + from zope.component.globalregistry import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IFoo) - class Foo(object): + class Foo: pass + @adapter(IFoo) @implementer(IBar) - class Bar(object): + class Bar: def __init__(self, context): self.context = context self._callFUT(Bar) @@ -180,15 +206,20 @@ class Test_provideSubscriptionAdapter(unittest.TestCase): def test_w_provides_w_adapts(self): from zope.interface import Interface from zope.interface import implementer + from zope.component.globalregistry import getGlobalSiteManager + class IFoo(Interface): pass + class IBar(Interface): pass + @implementer(IFoo) - class Foo(object): + class Foo: pass - class Bar(object): + + class Bar: def __init__(self, context): self.context = context self._callFUT(Bar, (IFoo,), IBar) @@ -202,7 +233,8 @@ class Test_provideSubscriptionAdapter(unittest.TestCase): class Test_provideHandler(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.globalregistry import provideHandler @@ -212,12 +244,15 @@ class Test_provideHandler(unittest.TestCase): from zope.interface import Interface from zope.interface import implementer from zope.interface import providedBy - from zope.component.globalregistry import getGlobalSiteManager + from zope.component._declaration import adapter + from zope.component.globalregistry import getGlobalSiteManager + class IFoo(Interface): pass + @implementer(IFoo) - class Foo(object): + class Foo: pass _handler = adapter(IFoo)(fails_if_called(self)) @@ -232,7 +267,9 @@ class Test_provideHandler(unittest.TestCase): 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) @@ -248,7 +285,8 @@ class Test_provideHandler(unittest.TestCase): class TestBaseGlobalComponents(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _getTargetClass(self): from zope.component.globalregistry import BaseGlobalComponents @@ -256,8 +294,8 @@ class TestBaseGlobalComponents(unittest.TestCase): def _getTargetInterfaces(self): from zope.interface.interfaces import IComponentLookup - from zope.interface.interfaces import IComponents from zope.interface.interfaces import IComponentRegistry + from zope.interface.interfaces import IComponents return [IComponents, IComponentLookup, IComponentRegistry] def _makeOne(self): diff --git a/src/zope/component/tests/test_hooks.py b/src/zope/component/tests/test_hooks.py index f588005..4ceed1d 100644 --- a/src/zope/component/tests/test_hooks.py +++ b/src/zope/component/tests/test_hooks.py @@ -23,7 +23,7 @@ class Test_read_property(unittest.TestCase): return read_property def test_via_instance(self): - class Foo(object): + class Foo: @self._getTargetClass() def bar(self): return 'BAR' @@ -35,7 +35,7 @@ class Test_read_property(unittest.TestCase): self.assertEqual(foo.bar, 'BAR') def test_via_class(self): - class Foo(object): + class Foo: @self._getTargetClass() def bar(self): return 'BAR' @@ -62,9 +62,11 @@ class SiteInfoTests(unittest.TestCase): def test_adapter_hook(self): _hook = object() - class _Registry(object): + + class _Registry: adapter_hook = _hook - class _SiteManager(object): + + class _SiteManager: adapters = _Registry() si = self._makeOne() si.sm = _SiteManager() @@ -101,7 +103,8 @@ class Test_setSite(unittest.TestCase): def test_w_site(self): from zope.component import hooks _SM2 = object() - class _Site(object): + + class _Site: def getSiteManager(self): return _SM2 siteinfo = _DummySiteInfo() @@ -121,16 +124,12 @@ class Test_getSite(unittest.TestCase): def test_w_None(self): from zope.component import hooks - from zope.component.globalregistry import getGlobalSiteManager - gsm = getGlobalSiteManager() siteinfo = _DummySiteInfo() with _Monkey(hooks, siteinfo=siteinfo): self.assertTrue(self._callFUT() is None) def test_w_site(self): from zope.component import hooks - from zope.component.globalregistry import getGlobalSiteManager - gsm = getGlobalSiteManager() _SM2 = object() _SITE = object() siteinfo = _DummySiteInfo() @@ -151,7 +150,8 @@ class Test_site(unittest.TestCase): from zope.component.globalregistry import getGlobalSiteManager gsm = getGlobalSiteManager() _SM2 = object() - class _Site(object): + + class _Site: def getSiteManager(self): return _SM2 _site = _Site() @@ -174,8 +174,6 @@ class Test_getSiteManager(unittest.TestCase): def test_default(self): from zope.component import hooks - from zope.component.globalregistry import getGlobalSiteManager - gsm = getGlobalSiteManager() _SM2 = object() siteinfo = _DummySiteInfo() siteinfo.sm = _SM2 @@ -194,10 +192,12 @@ class Test_getSiteManager(unittest.TestCase): 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 - from zope.interface.interfaces import IComponentLookup - class _Lookup(object): + + class _Lookup: def __init__(self, context): self.context = context gsm = getGlobalSiteManager() @@ -220,15 +220,16 @@ class Test_adapter_hook(unittest.TestCase): def test_success(self): from zope.interface import Interface + from zope.component import hooks - from zope.component.globalregistry import getGlobalSiteManager + class IFoo(Interface): pass - gsm = getGlobalSiteManager() _ADAPTER = object() _DEFAULT = object() _CONTEXT = object() _called = [] + def _adapter_hook(interface, object, name, default): _called.append((interface, object, name, default)) return _ADAPTER @@ -241,15 +242,16 @@ class Test_adapter_hook(unittest.TestCase): def test_hook_raises(self): from zope.interface import Interface - from zope.component import hooks - from zope.component.globalregistry import getGlobalSiteManager from zope.interface.interfaces import ComponentLookupError + + from zope.component import hooks + class IFoo(Interface): pass - gsm = getGlobalSiteManager() _DEFAULT = object() _CONTEXT = object() _called = [] + def _adapter_hook(interface, object, name, default): _called.append((interface, object, name, default)) raise ComponentLookupError('testing') @@ -270,9 +272,11 @@ class Test_setHooks(unittest.TestCase): def test_it(self): import zope.component._api from zope.component import hooks - class _Hook(object): + + class _Hook: def __init__(self): self._hooked = None + def sethook(self, value): self._hooked = value adapter_hook = _Hook() @@ -294,9 +298,11 @@ class Test_resetHooks(unittest.TestCase): def test_it(self): import zope.component._api from zope.component import hooks - class _Hook(object): + + class _Hook: def __init__(self): self._reset = False + def reset(self): self._reset = True adapter_hook = _Hook() @@ -318,15 +324,18 @@ class Test_resetHooks(unittest.TestCase): _SM = object() -class _DummySiteInfo(object): + + +class _DummySiteInfo: sm = _SM site = None -class _Monkey(object): + +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 = dict([(key, getattr(module, key)) for key in kw]) + self.to_restore = {key: getattr(module, key) for key in kw} for key, value in kw.items(): setattr(module, key, value) diff --git a/src/zope/component/tests/test_interface.py b/src/zope/component/tests/test_interface.py index 0207357..1fad493 100644 --- a/src/zope/component/tests/test_interface.py +++ b/src/zope/component/tests/test_interface.py @@ -17,15 +17,15 @@ import os import unittest -DOCSTRINGS_REMOVED = False -if os.environ.get('PYTHONOPTIMIZE') == '2': - DOCSTRINGS_REMOVED = True +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, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.interface import provideInterface @@ -37,6 +37,7 @@ class Test_provideInterface(unittest.TestCase): 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') @@ -44,11 +45,14 @@ class Test_provideInterface(unittest.TestCase): def test_w_class(self): from zope.interface.interfaces import IInterface + from zope.component.globalregistry import getGlobalSiteManager gsm = getGlobalSiteManager() + class IBar(IInterface): pass - class Foo(object): + + class Foo: pass self._callFUT('', Foo, IBar) self.assertFalse(IBar.providedBy(Foo)) @@ -57,10 +61,13 @@ class Test_provideInterface(unittest.TestCase): 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) @@ -71,8 +78,10 @@ class Test_provideInterface(unittest.TestCase): 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) @@ -81,16 +90,18 @@ class Test_provideInterface(unittest.TestCase): self.assertIs(registered, IFoo) def test_register_in_current_site(self): - from zope.component._api import getSiteManager - from zope.component.globalregistry import getGlobalSiteManager - from zope.interface.registry import Components 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) @@ -105,10 +116,10 @@ class Test_provideInterface(unittest.TestCase): ) - class Test_getInterface(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.interface import getInterface @@ -122,8 +133,10 @@ class Test_getInterface(unittest.TestCase): 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') @@ -132,7 +145,8 @@ class Test_getInterface(unittest.TestCase): class Test_queryInterface(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.interface import queryInterface @@ -146,8 +160,10 @@ class Test_queryInterface(unittest.TestCase): 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') @@ -156,7 +172,8 @@ class Test_queryInterface(unittest.TestCase): class Test_searchInterface(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.interface import searchInterface @@ -168,8 +185,10 @@ class Test_searchInterface(unittest.TestCase): 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') @@ -178,10 +197,13 @@ class Test_searchInterface(unittest.TestCase): 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') @@ -191,12 +213,16 @@ class Test_searchInterface(unittest.TestCase): 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') @@ -204,11 +230,12 @@ class Test_searchInterface(unittest.TestCase): self.assertEqual(self._callFUT(object(), base=IBase), [IFoo]) def test_hit_in_current_site(self): - from zope.component._api import getSiteManager - from zope.component.globalregistry import getGlobalSiteManager - from zope.interface.registry import Components 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 @@ -218,12 +245,12 @@ class Test_searchInterface(unittest.TestCase): 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') @@ -241,7 +268,8 @@ class Test_searchInterface(unittest.TestCase): class Test_searchInterfaceIds(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.interface import searchInterfaceIds @@ -253,8 +281,10 @@ class Test_searchInterfaceIds(unittest.TestCase): 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') @@ -263,10 +293,13 @@ class Test_searchInterfaceIds(unittest.TestCase): 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') @@ -276,12 +309,16 @@ class Test_searchInterfaceIds(unittest.TestCase): 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') @@ -291,7 +328,8 @@ class Test_searchInterfaceIds(unittest.TestCase): class Test_searchInterfaceUtilities(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.interface import searchInterfaceUtilities @@ -303,8 +341,10 @@ class Test_searchInterfaceUtilities(unittest.TestCase): 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') @@ -313,10 +353,13 @@ class Test_searchInterfaceUtilities(unittest.TestCase): 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') @@ -326,12 +369,16 @@ class Test_searchInterfaceUtilities(unittest.TestCase): 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') @@ -341,10 +388,13 @@ class Test_searchInterfaceUtilities(unittest.TestCase): 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') @@ -361,9 +411,10 @@ class Test_getInterfaceAllDocs(unittest.TestCase): return getInterfaceAllDocs(*args, **kw) def test_w_class(self): - class Foo(object): + class Foo: """DOCSTRING""" bar = None + def baz(self): """BAZ""" self.assertEqual(self._callFUT(Foo), @@ -372,6 +423,7 @@ class Test_getInterfaceAllDocs(unittest.TestCase): def test_w_interface_no_members(self): from zope.interface import Interface + class IFoo(Interface): """DOCSTRING""" self.assertEqual(self._callFUT(IFoo), @@ -381,9 +433,11 @@ class Test_getInterfaceAllDocs(unittest.TestCase): 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), @@ -395,7 +449,8 @@ class Test_getInterfaceAllDocs(unittest.TestCase): class Test_nameToInterface(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.interface import nameToInterface @@ -412,8 +467,10 @@ class Test_nameToInterface(unittest.TestCase): 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') @@ -423,7 +480,8 @@ class Test_nameToInterface(unittest.TestCase): class Test_interfaceToName(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.interface import interfaceToName @@ -434,6 +492,7 @@ class Test_interfaceToName(unittest.TestCase): def test_w_unregistered(self): from zope.interface import Interface + class IFoo(Interface): pass self.assertEqual(self._callFUT(object(), IFoo), @@ -442,8 +501,10 @@ class Test_interfaceToName(unittest.TestCase): 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') diff --git a/src/zope/component/tests/test_interfaces.py b/src/zope/component/tests/test_interfaces.py index 4d1794d..23a7e0d 100644 --- a/src/zope/component/tests/test_interfaces.py +++ b/src/zope/component/tests/test_interfaces.py @@ -17,6 +17,7 @@ Tests for zope.component.interfaces import unittest + class TestInterfaces(unittest.TestCase): def test_nothing(self): diff --git a/src/zope/component/tests/test_persistentregistry.py b/src/zope/component/tests/test_persistentregistry.py index 46224cc..6c35ade 100644 --- a/src/zope/component/tests/test_persistentregistry.py +++ b/src/zope/component/tests/test_persistentregistry.py @@ -15,15 +15,18 @@ """ import unittest -from zope.interface.tests.test_adapter import CustomTypesBaseAdapterRegistryTests +from zope.interface.tests.test_adapter import \ + CustomTypesBaseAdapterRegistryTests + def skipIfNoPersistent(testfunc): try: - import persistent - except ImportError: # pragma: no cover + 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): @@ -37,15 +40,17 @@ class PersistentAdapterRegistryTests(unittest.TestCase): def _makeCache(self, jar): # Borrowed from persistent.tests.test_pyPersistence. - class _Cache(object): + 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" @@ -53,16 +58,18 @@ class PersistentAdapterRegistryTests(unittest.TestCase): def _makeJar(self): # Borrowed from persistent.tests.test_pyPersistence. - from zope.interface import implementer from persistent.interfaces import IPersistentDataManager + from zope.interface import implementer @implementer(IPersistentDataManager) - class _Jar(object): + 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) @@ -75,7 +82,7 @@ class PersistentAdapterRegistryTests(unittest.TestCase): OID = _makeOctets('\x01' * 8) inst = self._makeOne(**kw) jar = self._makeJar() - jar._cache.new_ghost(OID, inst) # assigns _p_jar, _p_oid + jar._cache.new_ghost(OID, inst) # assigns _p_jar, _p_oid return inst, jar, OID def test_changed_original_is_not_us(self): @@ -119,7 +126,7 @@ class PersistentAdapterRegistryTests(unittest.TestCase): registry, jar, OID = self._makeOneWithJar() state = registry.__getstate__() self.assertTrue('_v_lookup' in registry.__dict__) - registry._p_changed = None # clears volatile '_v_lookup' + 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__) @@ -191,8 +198,9 @@ class PersistentComponentsTests(unittest.TestCase): return self._getTargetClass()(*args, **kw) def test_ctor_initializes_registries_and_registrations(self): - from persistent.mapping import PersistentMapping from persistent.list import PersistentList + from persistent.mapping import PersistentMapping + from zope.component.persistentregistry import PersistentAdapterRegistry registry = self._makeOne() self.assertTrue(isinstance(registry.adapters, @@ -208,12 +216,14 @@ class PersistentComponentsTests(unittest.TestCase): 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): +class PersistentAdapterRegistryCustomTypesTest( + CustomTypesBaseAdapterRegistryTests): def _getMappingType(self): from persistent.mapping import PersistentMapping diff --git a/src/zope/component/tests/test_registry.py b/src/zope/component/tests/test_registry.py index 1d02f86..8f88c53 100644 --- a/src/zope/component/tests/test_registry.py +++ b/src/zope/component/tests/test_registry.py @@ -17,9 +17,11 @@ import unittest from zope.component.tests import fails_if_called + class Test_dispatchUtilityRegistrationEvent(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.registry import dispatchUtilityRegistrationEvent @@ -27,10 +29,12 @@ class Test_dispatchUtilityRegistrationEvent(unittest.TestCase): def test_it(self): from zope.component import registry - class _Registration(object): + + class _Registration: component = object() _EVENT = object() _handled = [] + def _handle(*args): _handled.append(args) with _Monkey(registry, handle=_handle): @@ -40,7 +44,8 @@ class Test_dispatchUtilityRegistrationEvent(unittest.TestCase): class Test_dispatchAdapterRegistrationEvent(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.registry import dispatchAdapterRegistrationEvent @@ -48,11 +53,13 @@ class Test_dispatchAdapterRegistrationEvent(unittest.TestCase): def test_it(self): from zope.component import registry - class _Registration(object): + + class _Registration: factory = fails_if_called(self) _registration = _Registration() _EVENT = object() _handled = [] + def _handle(*args): _handled.append(args) with _Monkey(registry, handle=_handle): @@ -62,20 +69,23 @@ class Test_dispatchAdapterRegistrationEvent(unittest.TestCase): class Test_dispatchSubscriptionAdapterRegistrationEvent(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): - from zope.component.registry \ - import dispatchSubscriptionAdapterRegistrationEvent + from zope.component.registry import \ + dispatchSubscriptionAdapterRegistrationEvent return dispatchSubscriptionAdapterRegistrationEvent(*args, **kw) def test_it(self): from zope.component import registry - class _Registration(object): + + class _Registration: factory = fails_if_called(self) _registration = _Registration() _EVENT = object() _handled = [] + def _handle(*args): _handled.append(args) with _Monkey(registry, handle=_handle): @@ -85,7 +95,8 @@ class Test_dispatchSubscriptionAdapterRegistrationEvent(unittest.TestCase): class Test_dispatchHandlerRegistrationEvent(unittest.TestCase): - from zope.component.testing import setUp, tearDown + from zope.component.testing import setUp + from zope.component.testing import tearDown def _callFUT(self, *args, **kw): from zope.component.registry import dispatchHandlerRegistrationEvent @@ -93,11 +104,13 @@ class Test_dispatchHandlerRegistrationEvent(unittest.TestCase): def test_it(self): from zope.component import registry - class _Registration(object): + + class _Registration: handler = fails_if_called(self) _registration = _Registration() _EVENT = object() _handled = [] + def _handle(*args): _handled.append(args) with _Monkey(registry, handle=_handle): @@ -105,7 +118,7 @@ class Test_dispatchHandlerRegistrationEvent(unittest.TestCase): self.assertEqual(_handled, [(_registration.handler, _EVENT)]) -class _Monkey(object): +class _Monkey: # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module diff --git a/src/zope/component/tests/test_security.py b/src/zope/component/tests/test_security.py index 7f999b3..b3b0053 100644 --- a/src/zope/component/tests/test_security.py +++ b/src/zope/component/tests/test_security.py @@ -16,8 +16,9 @@ Tests for zope.component.security """ import unittest -from zope.component.tests import skipIfNoSecurity from zope.component.tests import fails_if_called +from zope.component.tests import skipIfNoSecurity + @skipIfNoSecurity class PermissionProxyTests(unittest.TestCase): @@ -33,15 +34,18 @@ class PermissionProxyTests(unittest.TestCase): from zope.interface import Interface from zope.interface import implementer from zope.interface import providedBy + class IFoo(Interface): pass + @implementer(IFoo) - class Foo(object): + class Foo: pass foo = Foo() proxy = self._makeOne(foo) self.assertEqual(providedBy(proxy), providedBy(foo)) + @skipIfNoSecurity class Test__checker(unittest.TestCase): @@ -57,25 +61,29 @@ class Test__checker(unittest.TestCase): 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.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'}) + {'foo': 'testing', 'bar': 'testing'}) self.assertFalse(checker.set_permissions) + @skipIfNoSecurity class Test_proxify(unittest.TestCase): @@ -84,7 +92,7 @@ class Test_proxify(unittest.TestCase): return proxify(*args, **kw) def _makeContext(self): - class _Context(object): + class _Context: bar = fails_if_called(self) return _Context() @@ -94,6 +102,7 @@ class Test_proxify(unittest.TestCase): def test_no_checker_no_permission(self): from zope.interface import Interface + class IFoo(Interface): def bar(self): "bar" @@ -102,8 +111,9 @@ class Test_proxify(unittest.TestCase): def test_no_checker_w_provides_and_permission_public(self): from zope.interface import Interface - from zope.security.checker import CheckerPublic from zope.proxy import getProxiedObject + from zope.security.checker import CheckerPublic + class IFoo(Interface): def bar(self): "bar" @@ -117,6 +127,7 @@ class Test_proxify(unittest.TestCase): 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" @@ -135,6 +146,7 @@ class Test_proxify(unittest.TestCase): self.assertTrue(getProxiedObject(proxy) is ctx) self.assertTrue(proxy.__Security_checker__ is _CHECKER) + @skipIfNoSecurity class Test_protectedFactory(unittest.TestCase): @@ -145,24 +157,26 @@ class Test_protectedFactory(unittest.TestCase): 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(object): + 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}) + {'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(object): + class _Factory: __slots__ = ('one',) bar = fails_if_called(self) protected = self._callFUT(_Factory, IFoo, 'testing') @@ -170,6 +184,7 @@ class Test_protectedFactory(unittest.TestCase): foo = protected() self.assertEqual(getTestProxyItems(foo), [('bar', 'testing')]) + @skipIfNoSecurity class Test_securityAdapterFactory(unittest.TestCase): @@ -178,41 +193,45 @@ class Test_securityAdapterFactory(unittest.TestCase): return securityAdapterFactory(*args, **kw) def test_no_permission_untrusted_no_location(self): - class _Factory(object): + class _Factory: pass self.assertTrue(self._callFUT(_Factory, None, False, False) is _Factory) def test_public_untrusted_no_location(self): - class _Factory(object): + 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(object): + + 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(object): + + 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(object): + + 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(object): + + class _Factory: pass proxy = self._callFUT(_Factory, 'zope.Public', False, True) self.assertTrue(isinstance(proxy, LocatingTrustedAdapterFactory)) @@ -220,21 +239,24 @@ class Test_securityAdapterFactory(unittest.TestCase): def test_CheckerPublic_trusted_no_location(self): from zope.security.adapter import LocatingTrustedAdapterFactory from zope.security.checker import CheckerPublic - class _Factory(object): + + 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(object): + + 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(object): + + class _Factory: pass proxy = self._callFUT(_Factory, 'testing', True, True) self.assertTrue(isinstance(proxy, LocatingTrustedAdapterFactory)) diff --git a/src/zope/component/tests/test_standalone.py b/src/zope/component/tests/test_standalone.py index 2892f87..7a2d931 100644 --- a/src/zope/component/tests/test_standalone.py +++ b/src/zope/component/tests/test_standalone.py @@ -17,33 +17,34 @@ 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 subprocess - import sys 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) + 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 + 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 + 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() diff --git a/src/zope/component/tests/test_zcml.py b/src/zope/component/tests/test_zcml.py index 0bf4591..df50559 100644 --- a/src/zope/component/tests/test_zcml.py +++ b/src/zope/component/tests/test_zcml.py @@ -18,6 +18,7 @@ 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): @@ -26,16 +27,19 @@ class Test_handler(unittest.TestCase): def test_uses_configured_site_manager(self): from zope.interface.registry import Components + from zope.component import getSiteManager - from zope.component.testfiles.components import comp, IApp + from zope.component.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, u'') + self._callFUT('registerUtility', comp, IApp, '') self.assertTrue(registry.getUtility(IApp) is comp) finally: getSiteManager.reset() @@ -50,6 +54,7 @@ class Test__rolledUpFactory(unittest.TestCase): def test_with_one(self): _OBJ = object() _CREATED = object() + def _factory(obj): return _CREATED rolled = self._callFUT([_factory]) @@ -61,10 +66,13 @@ class Test__rolledUpFactory(unittest.TestCase): _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]) @@ -80,7 +88,9 @@ class Test_adapter(unittest.TestCase): def test_empty_factory(self): from zope.interface import Interface + from zope.component.zcml import ComponentConfigurationError + class IFoo(Interface): pass _cfg_ctx = _makeConfigContext() @@ -89,89 +99,105 @@ class Test_adapter(unittest.TestCase): def test_multiple_factory_multiple_for_(self): from zope.interface import Interface + from zope.component.zcml import ComponentConfigurationError + class IFoo(Interface): pass + class IBar(Interface): pass - class Foo(object): + + class Foo: pass - class Bar(object): + + class Bar: pass _cfg_ctx = _makeConfigContext() self.assertRaises(ComponentConfigurationError, self._callFUT, _cfg_ctx, [Foo, Bar], - [Interface, IBar], IFoo) + [Interface, IBar], IFoo) def test_no_for__factory_not_adapts(self): - #@adapter(IFoo) - class _Factory(object): + # @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.component import adapter, named from zope.interface import implementer + + from zope.component import adapter + from zope.component import named + @adapter(IFoo) @implementer(IBar) @named('bar') - class _Factory(object): + class _Factory: __init__ = fails_if_called(self) _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, [_Factory]) # Register the adapter - action =_cfg_ctx._actions[0][1] + 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(object): + 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(object): + + class Foo: pass - class Bar(object): + + 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] + 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'][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] + 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] + action = _cfg_ctx._actions[2][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', Interface)) @@ -180,17 +206,20 @@ class Test_adapter(unittest.TestCase): def test_single_factory_single_for_w_permission(self): from zope.interface import Interface from zope.security.adapter import LocatingUntrustedAdapterFactory + from zope.component.zcml import handler + class IFoo(Interface): pass - class Foo(object): + + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('adapter', (Interface,), IFoo, '')) @@ -210,17 +239,20 @@ class Test_adapter(unittest.TestCase): def test_single_factory_single_for_w_locate_no_permission(self): from zope.interface import Interface from zope.security.adapter import LocatingUntrustedAdapterFactory + from zope.component.zcml import handler + class IFoo(Interface): pass - class Foo(object): + + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('adapter', (Interface,), IFoo, '')) @@ -239,17 +271,20 @@ class Test_adapter(unittest.TestCase): def test_single_factory_single_for_w_trusted_no_permission(self): from zope.interface import Interface from zope.security.adapter import TrustedAdapterFactory + from zope.component.zcml import handler + class IFoo(Interface): pass - class Foo(object): + + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('adapter', (Interface,), IFoo, '')) @@ -266,20 +301,23 @@ class Test_adapter(unittest.TestCase): def test_no_for__no_provides_factory_adapts_factory_implements(self): from zope.interface import Interface from zope.interface import implementer + from zope.component._declaration import adapter from zope.component.zcml import handler + class IFoo(Interface): pass + @adapter(Interface) @implementer(IFoo) - class _Factory(object): + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('adapter', (Interface,), IFoo, '')) @@ -287,6 +325,7 @@ class Test_adapter(unittest.TestCase): ('registerAdapter', _Factory, (Interface,), IFoo, '', 'TESTING')) + class Test_zcml_functional(unittest.TestCase): # These mimic the snippets in the zcml.rst doctests @@ -305,15 +344,16 @@ class Test_zcml_functional(unittest.TestCase): </configure>""" % 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 - from zope.component.testfiles.adapter import I1, A1 - from zope.security.checker import ProxyFactory self._runSnippet(''' <adapter @@ -330,17 +370,18 @@ class Test_zcml_functional(unittest.TestCase): self.assertTrue(isProxy(a)) - self.assertTrue(type(removeSecurityProxy(a)) is A1) + 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.components import Content + from zope.component.testfiles.adapter import I1 - from zope.security.checker import ProxyFactory - from zope.location.location import LocationProxy + from zope.component.testfiles.components import Content self._runSnippet(''' <adapter @@ -357,7 +398,8 @@ class Test_zcml_functional(unittest.TestCase): self.assertTrue(isProxy(a)) - self.assertTrue(type(removeSecurityProxy(a)) is LocationProxy) + self.assertTrue(isinstance(removeSecurityProxy(a), LocationProxy)) + class Test_subscriber(unittest.TestCase): @@ -373,27 +415,30 @@ class Test_subscriber(unittest.TestCase): 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) + handler=_handler, provides=IFoo) def test_w_factory_w_handler(self): from zope.interface import Interface - class Foo(object): + + class Foo: pass _handler = fails_if_called(self) _cfg_ctx = _makeConfigContext() self.assertRaises(TypeError, self._callFUT, _cfg_ctx, (Interface,), Foo, - handler=_handler) + handler=_handler) def test_w_factory_no_provides(self): from zope.interface import Interface - class Foo(object): + + class Foo: pass _cfg_ctx = _makeConfigContext() self.assertRaises(TypeError, @@ -401,17 +446,20 @@ class Test_subscriber(unittest.TestCase): def test_w_factory_w_provides_no_for_factory_wo_adapter(self): from zope.interface import Interface + class IFoo(Interface): pass - class Foo(object): + + class Foo: pass _cfg_ctx = _makeConfigContext() self.assertRaises(TypeError, self._callFUT, _cfg_ctx, - factory=Foo, provides=IFoo) + 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) @@ -420,7 +468,7 @@ class Test_subscriber(unittest.TestCase): self.assertEqual(len(_cfg_ctx._actions), 2) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the adapter - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'][0], 'registerHandler') @@ -430,26 +478,29 @@ class Test_subscriber(unittest.TestCase): self.assertEqual(action['args'][4], 'TESTING') # Register the required interface(s) self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + action = _cfg_ctx._actions[1][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', Interface)) def test_w_factory_w_provides(self): from zope.interface import Interface + from zope.component.interface import provideInterface from zope.component.zcml import handler + class IFoo(Interface): pass - class Foo(object): + + class Foo: pass - _handler = fails_if_called(self) + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'][0], 'registerSubscriptionAdapter') @@ -460,13 +511,13 @@ class Test_subscriber(unittest.TestCase): self.assertEqual(action['args'][5], 'TESTING') # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + 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] + action = _cfg_ctx._actions[2][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', Interface)) @@ -475,11 +526,14 @@ class Test_subscriber(unittest.TestCase): def test_w_factory_w_provides_w_permission(self): from zope.interface import Interface from zope.security.adapter import LocatingUntrustedAdapterFactory + from zope.component.interface import provideInterface from zope.component.zcml import handler + class IFoo(Interface): pass - class Foo(object): + + class Foo: pass _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, (Interface,), Foo, @@ -487,7 +541,7 @@ class Test_subscriber(unittest.TestCase): self.assertEqual(len(_cfg_ctx._actions), 3) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the adapter - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'][0], 'registerSubscriptionAdapter') @@ -503,13 +557,13 @@ class Test_subscriber(unittest.TestCase): self.assertEqual(action['args'][5], 'TESTING') # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + 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] + action = _cfg_ctx._actions[2][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', Interface)) @@ -518,18 +572,21 @@ class Test_subscriber(unittest.TestCase): def test_w_factory_w_provides_wo_permission_w_locate(self): from zope.interface import Interface from zope.security.adapter import LocatingUntrustedAdapterFactory + from zope.component.interface import provideInterface from zope.component.zcml import handler + class IFoo(Interface): pass - class Foo(object): + + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'][0], 'registerSubscriptionAdapter') @@ -545,13 +602,13 @@ class Test_subscriber(unittest.TestCase): self.assertEqual(action['args'][5], 'TESTING') # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + 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] + action = _cfg_ctx._actions[2][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', Interface)) @@ -560,18 +617,21 @@ class Test_subscriber(unittest.TestCase): def test_w_factory_w_provides_wo_permission_w_trusted(self): from zope.interface import Interface from zope.security.adapter import TrustedAdapterFactory + from zope.component.interface import provideInterface from zope.component.zcml import handler + class IFoo(Interface): pass - class Foo(object): + + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'][0], 'registerSubscriptionAdapter') @@ -587,13 +647,13 @@ class Test_subscriber(unittest.TestCase): self.assertEqual(action['args'][5], 'TESTING') # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + 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] + action = _cfg_ctx._actions[2][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', Interface)) @@ -601,15 +661,18 @@ class Test_subscriber(unittest.TestCase): 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(object): + class _Factory: def __init__(self, context): - self.context = context + self.context = context # pragma: no cover _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, factory=_Factory) self.assertEqual(len(_cfg_ctx._actions), 3) @@ -618,9 +681,16 @@ class Test_subscriber(unittest.TestCase): action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertIsNone(action['discriminator']) - self.assertEqual(action['args'], - ('registerSubscriptionAdapter', _Factory, (Interface,), IFoo, - '', 'TESTING')) + self.assertEqual( + action['args'], + ('registerSubscriptionAdapter', + _Factory, + (Interface, + ), + IFoo, + '', + 'TESTING')) + class Test_utility(unittest.TestCase): @@ -629,16 +699,16 @@ class Test_utility(unittest.TestCase): return utility(*args, **kw) def test_w_factory_w_component(self): - class _Factory(object): + class _Factory: pass _COMPONENT = object _cfg_ctx = _makeConfigContext() self.assertRaises(TypeError, self._callFUT, _cfg_ctx, - factory=_Factory, - component=_COMPONENT) + factory=_Factory, + component=_COMPONENT) def test_w_factory_wo_provides_factory_no_implements(self): - class _Factory(object): + class _Factory: pass _cfg_ctx = _makeConfigContext() self.assertRaises(TypeError, @@ -652,18 +722,21 @@ class Test_utility(unittest.TestCase): def test_w_factory_w_provides(self): from zope.interface import Interface + from zope.component.interface import provideInterface from zope.component.zcml import handler + class IFoo(Interface): pass - class Foo(object): + + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('utility', IFoo, '')) self.assertEqual(action['args'][0], 'registerUtility') @@ -674,7 +747,7 @@ class Test_utility(unittest.TestCase): self.assertEqual(action['kw'], {'factory': Foo}) # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + action = _cfg_ctx._actions[1][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', IFoo)) @@ -682,19 +755,22 @@ class Test_utility(unittest.TestCase): def test_w_factory_wo_provides_factory_implements(self): from zope.interface import Interface from zope.interface import implementer + from zope.component.interface import provideInterface from zope.component.zcml import handler + class IFoo(Interface): pass + @implementer(IFoo) - class Foo(object): + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('utility', IFoo, '')) self.assertEqual(action['args'][0], 'registerUtility') @@ -705,15 +781,17 @@ class Test_utility(unittest.TestCase): self.assertEqual(action['kw'], {'factory': Foo}) # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + 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() @@ -723,7 +801,7 @@ class Test_utility(unittest.TestCase): self.assertEqual(len(_cfg_ctx._actions), 2) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the utility - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('utility', IFoo, 'test')) self.assertEqual(action['args'][0], 'registerUtility') @@ -733,24 +811,27 @@ class Test_utility(unittest.TestCase): self.assertEqual(action['args'][4], 'TESTING') # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + 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, implementer, named - from zope.component.zcml import handler + 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(object): + class Foo: pass foo = Foo() _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, component=foo) - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['args'][1], foo) self.assertEqual(action['args'][2], IFoo) self.assertEqual(action['args'][3], 'foo') @@ -758,11 +839,14 @@ class Test_utility(unittest.TestCase): def test_w_component_wo_provides_component_provides(self): from zope.interface import Interface from zope.interface import directlyProvides + from zope.component.interface import provideInterface from zope.component.zcml import handler + class IFoo(Interface): pass - class Foo(object): + + class Foo: pass _COMPONENT = Foo() directlyProvides(_COMPONENT, IFoo) @@ -771,7 +855,7 @@ class Test_utility(unittest.TestCase): self.assertEqual(len(_cfg_ctx._actions), 2) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the utility - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('utility', IFoo, '')) self.assertEqual(action['args'][0], 'registerUtility') @@ -781,7 +865,7 @@ class Test_utility(unittest.TestCase): self.assertEqual(action['args'][4], 'TESTING') # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + action = _cfg_ctx._actions[1][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', IFoo)) @@ -790,22 +874,24 @@ class Test_utility(unittest.TestCase): 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(object): + class Foo: bar = fails_if_called(self) _COMPONENT = Foo() _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, component=_COMPONENT, - provides=IFoo, permission='testing') + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('utility', IFoo, '')) self.assertEqual(action['args'][0], 'registerUtility') @@ -819,7 +905,7 @@ class Test_utility(unittest.TestCase): self.assertEqual(action['args'][4], 'TESTING') # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + action = _cfg_ctx._actions[1][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', IFoo)) @@ -827,11 +913,14 @@ class Test_utility(unittest.TestCase): @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(object): + + class Foo: pass _cfg_ctx = _makeConfigContext() self._callFUT(_cfg_ctx, factory=Foo, @@ -839,7 +928,7 @@ class Test_utility(unittest.TestCase): self.assertEqual(len(_cfg_ctx._actions), 2) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the utility - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('utility', IFoo, '')) self.assertEqual(action['args'][0], 'registerUtility') @@ -855,7 +944,7 @@ class Test_utility(unittest.TestCase): self.assertIsInstance(secured, Foo) # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + action = _cfg_ctx._actions[1][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', IFoo)) @@ -869,30 +958,35 @@ class Test_interface(unittest.TestCase): 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] + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('foo', IFoo, IBar)) @@ -906,89 +1000,107 @@ class Test_view(unittest.TestCase): 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(object): + 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) + for_=(Interface, Interface), + allowed_interface=IView) def test_w_allowed_attributes_wo_permission(self): from zope.interface import Interface + from zope.component.zcml import ComponentConfigurationError + class IViewType(Interface): pass - class _View(object): + + 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')) + 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)) + for_=(Interface, Interface)) def test_w_multiple_factory_multiple_for_(self): from zope.interface import Interface + from zope.component.zcml import ComponentConfigurationError + class IViewType(Interface): pass - class Foo(object): + + class Foo: pass - class Bar(object): + + class Bar: pass _cfg_ctx = _makeConfigContext() self.assertRaises(ComponentConfigurationError, self._callFUT, _cfg_ctx, (Foo, Bar), IViewType, '', - for_=(Interface, Interface)) + for_=(Interface, Interface)) def test_w_for__as_empty(self): from zope.interface import Interface + from zope.component.zcml import ComponentConfigurationError + class IViewType(Interface): pass - class _View(object): + + class _View: __init__ = fails_if_called(self) _cfg_ctx = _makeConfigContext() self.assertRaises(ComponentConfigurationError, self._callFUT, _cfg_ctx, (_View,), IViewType, '', - for_=()) + for_=()) def test_w_single_factory_single_for__wo_permission_w_name(self): from zope.interface import Interface - from zope.component.zcml import handler + from zope.component.interface import provideInterface + from zope.component.zcml import handler + class IViewType(Interface): pass - class _View(object): + + 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] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('view', (Interface, IViewType), 'test', Interface)) @@ -1000,31 +1112,35 @@ class Test_view(unittest.TestCase): self.assertEqual(action['args'][5], 'TESTING') # Register the provided interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + 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] + 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] + action = _cfg_ctx._actions[3][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', IViewType)) def test_w_multiple_factory_single_for__wo_permission(self): from zope.interface import Interface + from zope.component.zcml import handler + class IViewType(Interface): pass - class _View(object): + + class _View: def __init__(self, context): self.context = context - class _View2(object): + + class _View2: def __init__(self, context, request): self.context = context self.request = request @@ -1033,7 +1149,7 @@ class Test_view(unittest.TestCase): for_=(Interface,)) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the adapter - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('view', (Interface, IViewType), '', Interface)) @@ -1055,10 +1171,13 @@ class Test_view(unittest.TestCase): @skipIfNoSecurity def test_w_single_factory_single_for__w_permission(self): from zope.interface import Interface + from zope.component.zcml import handler + class IViewType(Interface): pass - class _View(object): + + class _View: def __init__(self, context, request): self.context = context self.request = request @@ -1067,7 +1186,7 @@ class Test_view(unittest.TestCase): permission='testing') self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the adapter - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('view', (Interface, IViewType), '', Interface)) @@ -1087,10 +1206,13 @@ class Test_view(unittest.TestCase): @skipIfNoSecurity def test_w_single_factory_single_for__w_permission_and_allowed_attrs(self): from zope.interface import Interface + from zope.component.zcml import handler + class IViewType(Interface): pass - class _View(object): + + class _View: __init__ = fails_if_called(self) bar = fails_if_called(self) _cfg_ctx = _makeConfigContext() @@ -1098,7 +1220,7 @@ class Test_view(unittest.TestCase): permission='testing', allowed_attributes=('bar',)) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the adapter - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('view', (Interface, IViewType), '', Interface)) @@ -1110,11 +1232,13 @@ class Test_view(unittest.TestCase): @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(object): + class _View: __init__ = fails_if_called(self) bar = fails_if_called(self) _cfg_ctx = _makeConfigContext() @@ -1122,7 +1246,7 @@ class Test_view(unittest.TestCase): permission='testing', allowed_interface=(IViewType,)) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the adapter - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('view', (Interface, IViewType), '', Interface)) @@ -1140,46 +1264,55 @@ class Test_resource(unittest.TestCase): 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(object): + 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) + _cfg_ctx, (_Resource,), IResourceType, '', + allowed_interface=IView) def test_w_allowed_attributes_wo_permission(self): from zope.interface import Interface + from zope.component.zcml import ComponentConfigurationError + class IResourceType(Interface): pass - class _Resource(object): + + 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')) + _cfg_ctx, (_Resource,), IResourceType, '', + allowed_attributes=('foo', 'bar')) def test_wo_permission_w_name(self): from zope.interface import Interface + from zope.component.interface import provideInterface from zope.component.zcml import handler + class IResourceType(Interface): pass - class _Resource(object): + + class _Resource: __init__ = fails_if_called(self) foo = fails_if_called(self) bar = fails_if_called(self) @@ -1188,7 +1321,7 @@ class Test_resource(unittest.TestCase): self.assertEqual(len(_cfg_ctx._actions), 3) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the resource - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('resource', 'test', IResourceType, Interface)) @@ -1200,13 +1333,13 @@ class Test_resource(unittest.TestCase): self.assertEqual(action['args'][5], 'TESTING') # Register the 'type' interface self.assertEqual(_cfg_ctx._actions[1][0], ()) - action =_cfg_ctx._actions[1][1] + 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] + action = _cfg_ctx._actions[2][1] self.assertEqual(action['callable'], provideInterface) self.assertEqual(action['discriminator'], None) self.assertEqual(action['args'], ('', Interface)) @@ -1214,10 +1347,13 @@ class Test_resource(unittest.TestCase): @skipIfNoSecurity def test_w_permission(self): from zope.interface import Interface + from zope.component.zcml import handler + class IResourceType(Interface): pass - class _Resource(object): + + class _Resource: def __init__(self, context): self.context = context foo = fails_if_called(self) @@ -1228,7 +1364,7 @@ class Test_resource(unittest.TestCase): self.assertEqual(len(_cfg_ctx._actions), 3) self.assertEqual(_cfg_ctx._actions[0][0], ()) # Register the resource - action =_cfg_ctx._actions[0][1] + action = _cfg_ctx._actions[0][1] self.assertEqual(action['callable'], handler) self.assertEqual(action['discriminator'], ('resource', 'test', IResourceType, Interface)) @@ -1247,10 +1383,12 @@ class Test_resource(unittest.TestCase): def _makeConfigContext(): - class _Context(object): + class _Context: info = 'TESTING' + def __init__(self): self._actions = [] + def action(self, *args, **kw): self._actions.append((args, kw)) return _Context() diff --git a/src/zope/component/zcml.py b/src/zope/component/zcml.py index bc02c9f..ec7f596 100644 --- a/src/zope/component/zcml.py +++ b/src/zope/component/zcml.py @@ -27,12 +27,14 @@ 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, getName +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 +except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover def _no_security(*args, **kw): raise ConfigurationError( "security proxied components are not " @@ -41,19 +43,22 @@ except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover Permission = TextLine else: from zope.component.security import _checker - from zope.component.security import proxify from zope.component.security import protectedFactory + from zope.component.security import 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( @@ -63,13 +68,13 @@ class IBasicComponentInformation(Interface): " 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"), @@ -79,7 +84,8 @@ class IBasicComponentInformation(Interface): " If specified, the ``component`` field must" " be left blank."), required=False, - ) + ) + class IAdapterDirective(Interface): """ @@ -92,14 +98,14 @@ class IAdapterDirective(Interface): " 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"), @@ -115,7 +121,7 @@ class IAdapterDirective(Interface): description=_("This adapter is only available, if the principal" " has this permission."), required=False, - ) + ) name = TextLine( title=_("Name"), @@ -123,7 +129,7 @@ class IAdapterDirective(Interface): "This attribute allows you to specify the name for" " this adapter."), required=False, - ) + ) trusted = Bool( title=_("Trusted"), @@ -137,7 +143,7 @@ class IAdapterDirective(Interface): """), required=False, default=False, - ) + ) locate = Bool( title=_("Locate"), @@ -148,7 +154,8 @@ class IAdapterDirective(Interface): """), required=False, default=False, - ) + ) + def _rolledUpFactory(factories): # This has to be named 'factory', aparently, so as not to confuse @@ -161,6 +168,7 @@ def _rolledUpFactory(factories): factory.factory = factories[0] return factory + def adapter(_context, factory, provides=None, for_=None, permission=None, name='', trusted=False, locate=False): @@ -207,24 +215,25 @@ def adapter(_context, factory, provides=None, for_=None, permission=None, factory = securityAdapterFactory(factory, permission, locate, trusted) _context.action( - discriminator = ('adapter', for_, provides, name), - callable = handler, - args = ('registerAdapter', - factory, for_, provides, name, _context.info), - ) + discriminator=('adapter', for_, provides, name), + callable=handler, + args=('registerAdapter', + factory, for_, provides, name, _context.info), + ) _context.action( - discriminator = None, - callable = provideInterface, - args = ('', provides) - ) + 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) - ) + discriminator=None, + callable=provideInterface, + args=('', iface) + ) + class ISubscriberDirective(Interface): """ @@ -235,36 +244,36 @@ class ISubscriberDirective(Interface): 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(), - ), - ) + 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"), @@ -278,7 +287,7 @@ class ISubscriberDirective(Interface): """), required=False, default=False, - ) + ) locate = Bool( title=_("Locate"), @@ -289,9 +298,12 @@ class ISubscriberDirective(Interface): """), 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: @@ -329,34 +341,35 @@ def subscriber(_context, for_=None, factory=None, handler=None, provides=None, if handler is not None: _context.action( - discriminator = None, - callable = _handler, - args = ('registerHandler', - handler, for_, u'', _context.info), - ) + discriminator=None, + callable=_handler, + args=('registerHandler', + handler, for_, '', _context.info), + ) else: _context.action( - discriminator = None, - callable = _handler, - args = ('registerSubscriptionAdapter', - factory, for_, provides, u'', _context.info), - ) + discriminator=None, + callable=_handler, + args=('registerSubscriptionAdapter', + factory, for_, provides, '', _context.info), + ) if provides is not None: _context.action( - discriminator = None, - callable = provideInterface, - args = ('', provides) - ) + 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) - ) + discriminator=None, + callable=provideInterface, + args=('', iface) + ) + class IUtilityDirective(IBasicComponentInformation): """Register a utility.""" @@ -365,14 +378,15 @@ class IUtilityDirective(IBasicComponentInformation): 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=''): @@ -403,16 +417,17 @@ def utility(_context, provides=None, component=None, factory=None, factory = protectedFactory(factory, provides, permission) _context.action( - discriminator = ('utility', provides, name), - callable = handler, - args = ('registerUtility', component, provides, name, _context.info), - kw = dict(factory=factory), - ) + 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), - ) + discriminator=None, + callable=provideInterface, + args=('', provides), + ) + class IInterfaceDirective(Interface): """ @@ -422,24 +437,26 @@ class IInterfaceDirective(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) - ) + discriminator=None, + callable=provideInterface, + args=(name, interface, type) + ) + class IBasicViewInformation(Interface): """This is the basic information for all views.""" @@ -450,21 +467,21 @@ class IBasicViewInformation(Interface): """), required=True, value_type=GlobalObject( - missing_value=object(), - ), - ) + 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."), @@ -478,7 +495,7 @@ class IBasicViewInformation(Interface): whitespace."""), required=False, value_type=GlobalInterface(), - ) + ) allowed_attributes = Tokens( title=_("View attributes that are also allowed if the user" @@ -490,7 +507,8 @@ class IBasicViewInformation(Interface): on the view object."""), required=False, value_type=PythonIdentifier(), - ) + ) + class IBasicResourceInformation(Interface): """ @@ -501,8 +519,8 @@ class IBasicResourceInformation(Interface): title=_("The name of the resource."), description=_("The name shows up in URLs/paths. For example 'foo'."), required=True, - default=u'', - ) + default='', + ) provides = GlobalInterface( title=_("The interface this component provides."), @@ -511,12 +529,12 @@ class IBasicResourceInformation(Interface): views that support other views."""), required=False, default=Interface, - ) + ) type = GlobalInterface( title=_("Request type"), required=True - ) + ) class IViewDirective(IBasicViewInformation, IBasicResourceInformation): @@ -526,17 +544,18 @@ class IViewDirective(IBasicViewInformation, IBasicResourceInformation): 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)): + and (not permission)): raise ComponentConfigurationError( "'permission' required with 'allowed_interface' or " "'allowed_attributes'") @@ -546,7 +565,7 @@ def view(_context, factory, type, name, for_, checker = _checker(_context, permission, allowed_interface, allowed_attributes) - class ProxyView(object): + class ProxyView: """Class to create simple proxy views.""" def __init__(self, factory, checker): @@ -558,9 +577,8 @@ def view(_context, factory, type, name, for_, factory[-1] = ProxyView(factory[-1], checker) - if not for_: - raise ComponentConfigurationError("No for interfaces specified"); + raise ComponentConfigurationError("No for interfaces specified") for_ = tuple(for_) # Generate a single factory from multiple factories: @@ -582,26 +600,26 @@ def view(_context, factory, type, name, for_, for_ = for_ + (type,) _context.action( - discriminator = ('view', for_, name, provides), - callable = handler, - args = ('registerAdapter', - factory, for_, provides, name, _context.info), - ) + discriminator=('view', for_, name, provides), + callable=handler, + args=('registerAdapter', + factory, for_, provides, name, _context.info), + ) _context.action( - discriminator = None, - callable = provideInterface, - args = ('', provides) - ) + 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) - ) + discriminator=None, + callable=provideInterface, + args=('', iface) + ) class IResourceDirective(IBasicComponentInformation, @@ -612,14 +630,15 @@ class IResourceDirective(IBasicComponentInformation, 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, @@ -627,11 +646,11 @@ def resource(_context, factory, type, name, provides=Interface): if ((allowed_attributes or allowed_interface) - and (not permission)): + and (not permission)): raise ComponentConfigurationError( "Must use name attribute with allowed_interface or " "allowed_attributes" - ) + ) if permission is not None: @@ -645,15 +664,15 @@ def resource(_context, factory, type, name, factory = proxyResource _context.action( - discriminator = ('resource', name, type, provides), - callable = handler, - args = ('registerAdapter', - factory, (type,), provides, name, _context.info)) + discriminator=('resource', name, type, provides), + callable=handler, + args=('registerAdapter', + factory, (type,), provides, name, _context.info)) _context.action( - discriminator = None, - callable = provideInterface, - args = ('', type)) + discriminator=None, + callable=provideInterface, + args=('', type)) _context.action( - discriminator = None, - callable = provideInterface, - args = ('', provides)) + discriminator=None, + callable=provideInterface, + args=('', provides)) @@ -1,85 +1,96 @@ +# Generated from: +# https://github.com/zopefoundation/meta/tree/master/config/pure-python [tox] minversion = 3.18 envlist = - py27 - py35 - py36 + lint py37 py38 py39 py310 py311 - py27-minimal - py310-optimized - pypy pypy3 docs coverage + py310-optimized -[mindeps] +[testenv] +usedevelop = true deps = - .[mintests] +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 -[fulldeps] +[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 = - .[test] + check-manifest + check-python-versions >= 0.19.1 + wheel + flake8 + isort -[testenv] -usedevelop = true +[testenv:isort-apply] +basepython = python3 +skip_install = true +commands_pre = deps = - !minimal: {[fulldeps]deps} - minimal: {[mindeps]deps} - .[docs] + isort commands = -# Temporary workaround. Avoid zope.testrunner pending -# IRO fixes in zope.security. https://github.com/zopefoundation/zope.security/issues/71 - python -m unittest discover -s src - !minimal: sphinx-build -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest -setenv = - ZOPE_INTERFACE_STRICT_IRO = 1 - pure: PURE_PYTHON = 1 - optimized: PYTHONOPTIMIZE = 2 + isort {toxinidir}/src {toxinidir}/setup.py [] [testenv:docs] -basepython = - python3 +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 -deps = - {[fulldeps]deps} - .[docs] -setenv = - ZOPE_INTERFACE_STRICT_IRO = 0 [testenv:coverage] -basepython = - python3 -usedevelop = true -commands = - coverage run -m unittest discover -s src - coverage run -a -m sphinx -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest - coverage report --fail-under=99 +basepython = python3 +allowlist_externals = + mkdir deps = - {[testenv]deps} coverage - coverage-python-version +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 -plugins = coverage_python_version source = zope.component omit = - # Runs in a subprocess + # Runs in a subprocess: src/zope/component/standalonetests.py - # Not used - src/zope/component/hookable.py + # Not used: src/zope/component/eventtesting.py [coverage:report] +precision = 2 exclude_lines = pragma: no cover - pragma NO COVER - if __name__ == '__main__': + pragma: nocover + except ImportError: raise NotImplementedError + if __name__ == '__main__': self.fail + raise AssertionError + +[coverage:html] +directory = parts/htmlcov |