From 1cb817cbdc452ea4d70815f910611484895f5f88 Mon Sep 17 00:00:00 2001 From: Steffen Allner Date: Thu, 21 Sep 2023 14:28:11 +0200 Subject: [PATCH 01/12] Move all linters to pre-commit. --- .github/workflows/pre-commit.yaml | 15 +++++++++++ .github/workflows/tests.yml | 3 --- .pre-commit-config.yaml | 33 ++++++++++++++++++++++- src/OFS/DTMLDocument.py | 2 ++ src/Shared/DC/Scripts/Signature.py | 5 +++- src/ZPublisher/HTTPRequest.py | 8 +++--- tox.ini | 43 +----------------------------- 7 files changed, 58 insertions(+), 51 deletions(-) create mode 100644 .github/workflows/pre-commit.yaml diff --git a/.github/workflows/pre-commit.yaml b/.github/workflows/pre-commit.yaml new file mode 100644 index 0000000000..48d2f6d19a --- /dev/null +++ b/.github/workflows/pre-commit.yaml @@ -0,0 +1,15 @@ +on: + pull_request: + +jobs: + pre-commit: + name: pre-commit linting + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: 3.x + - uses: pre-commit/action@v3.0.0 + - uses: pre-commit-ci/lite-action@v1.0.1 + if: always() diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index dffa2b81f2..307c33fc23 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -22,7 +22,6 @@ jobs: - ["macos", "macos-11"] config: # [Python version, tox env] - - ["3.9", "lint"] - ["3.7", "py37"] - ["3.8", "py38"] - ["3.9", "py39"] @@ -32,10 +31,8 @@ jobs: - ["3.9", "docs"] - ["3.9", "coverage"] exclude: - - { os: ["windows", "windows-latest"], config: ["3.9", "lint"] } - { os: ["windows", "windows-latest"], config: ["3.9", "docs"] } - { os: ["windows", "windows-latest"], config: ["3.9", "coverage"] } - - { os: ["macos", "macos-11"], config: ["3.9", "lint"] } - { os: ["macos", "macos-11"], config: ["3.9", "docs"] } - { os: ["macos", "macos-11"], config: ["3.9", "coverage"] } # macOS/Python 3.11+ is set up for universal2 architecture diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7ec6849357..2089cb479d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,37 @@ +ci: + autofix_prs: true + repos: - repo: https://github.com/asottile/pyupgrade - rev: v2.6.2 + rev: "v2.6.2" hooks: - id: pyupgrade args: [--py36-plus] + - repo: https://github.com/pycqa/isort + rev: "5.12.0" + hooks: + - id: isort + - repo: https://github.com/PyCQA/docformatter + rev: "v1.7.5" + hooks: + - id: docformatter + - repo: https://github.com/pre-commit/mirrors-autopep8 + rev: "v2.0.2" + hooks: + - id: autopep8 + args: [--in-place, --aggressive, --aggressive] + - repo: https://github.com/PyCQA/flake8 + rev: "6.1.0" + hooks: + - id: flake8 + additional_dependencies: + - flake8-coding + - flake8-debugger + - repo: https://github.com/mgedmin/check-manifest + rev: "0.49" + hooks: + - id: check-manifest + - repo: https://github.com/mgedmin/check-python-versions + rev: "0.21.3" + hooks: + - id: check-python-versions diff --git a/src/OFS/DTMLDocument.py b/src/OFS/DTMLDocument.py index cb0eab113f..00ede85eba 100644 --- a/src/OFS/DTMLDocument.py +++ b/src/OFS/DTMLDocument.py @@ -48,8 +48,10 @@ class DTMLDocument(PropertyManager, DTMLMethod): # Replace change_dtml_methods by change_dtml_documents __ac_permissions__ = tuple([ + # fmt: off (perms[0] == change_dtml_methods) and # NOQA: W504 (change_dtml_documents, perms[1]) or perms + # fmt: on for perms in DTMLMethod.__ac_permissions__]) def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw): diff --git a/src/Shared/DC/Scripts/Signature.py b/src/Shared/DC/Scripts/Signature.py index af0d81b829..c64b68c77b 100644 --- a/src/Shared/DC/Scripts/Signature.py +++ b/src/Shared/DC/Scripts/Signature.py @@ -32,15 +32,18 @@ def __init__(self, varnames=(), argcount=-1): def __eq__(self, other): if not isinstance(other, FuncCode): return False + # fmt: off return ((self.co_argcount, self.co_varnames) == # NOQA: W504 (other.co_argcount, other.co_varnames)) + # fmt: on def __lt__(self, other): if not isinstance(other, FuncCode): return False + # fmt: off return ((self.co_argcount, self.co_varnames) < # NOQA: W504 (other.co_argcount, other.co_varnames)) - + # fmt: on def _setFuncSignature(self, defaults=None, varnames=(), argcount=-1): # This is meant to be imported directly into a class. diff --git a/src/ZPublisher/HTTPRequest.py b/src/ZPublisher/HTTPRequest.py index 20421a14b5..bfc9de01e6 100644 --- a/src/ZPublisher/HTTPRequest.py +++ b/src/ZPublisher/HTTPRequest.py @@ -465,16 +465,16 @@ def processInputs( hasattr=hasattr, getattr=getattr, setattr=setattr): - """Process request inputs + """Process request inputs. - See the `Zope Developer Guide Object Publishing chapter - `_ + See the + `Zope Developer Guide Object Publishing chapter `_ for a detailed explanation in the section `Marshalling Arguments from the Request`. We need to delay input parsing so that it is done under publisher control for error handling purposes. - """ + """ # noqa: E501 response = self.response environ = self.environ method = environ.get('REQUEST_METHOD', 'GET') diff --git a/tox.ini b/tox.ini index 0e004349e7..98eeac6bd1 100644 --- a/tox.ini +++ b/tox.ini @@ -3,7 +3,6 @@ [tox] minversion = 3.18 envlist = - lint py37 py38 py39 @@ -39,47 +38,7 @@ deps = pre-commit commands_pre = commands = - pre-commit run --all-files --show-diff-on-failure - -[testenv:autopep8] -basepython = python3.8 -skip_install = true -deps = - -cconstraints.txt - autopep8 - docformatter -commands = - autopep8 --verbose --in-place --recursive --aggressive --aggressive {toxinidir}/src setup.py - docformatter --in-place --recursive {toxinidir}/src setup.py - -[testenv:lint] -basepython = python3 -commands_pre = - mkdir -p {toxinidir}/parts/flake8 -allowlist_externals = - mkdir -commands = - isort --check-only --diff {toxinidir}/src {toxinidir}/setup.py - flake8 {toxinidir}/src {toxinidir}/setup.py - check-manifest - check-python-versions -deps = - check-manifest - check-python-versions - flake8 - isort - # Useful flake8 plugins that are Python and Plone specific: - flake8-coding - flake8-debugger - mccabe - -[testenv:isort-apply] -basepython = python3 -commands_pre = -deps = - isort -commands = - isort {toxinidir}/src {toxinidir}/setup.py [] + pre-commit run {posargs} --all-files [testenv:docs] basepython = python3 From afe29e386d7cbfac7846de19a4ed53ff6d2389f5 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci-lite[bot]" <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com> Date: Thu, 21 Sep 2023 13:29:29 +0000 Subject: [PATCH 02/12] [pre-commit.ci lite] apply automatic fixes --- docs/zdgbook/examples/PollImplementation.py | 9 +- docs/zdgbook/examples/PollProduct.py | 9 +- src/App/ApplicationManager.py | 20 +- src/App/CacheManager.py | 16 +- src/App/Dialogs.py | 42 +- src/App/Extensions.py | 2 +- src/App/FactoryDispatcher.py | 14 +- src/App/ImageFile.py | 6 +- src/App/Management.py | 10 +- src/App/ProductContext.py | 6 +- src/App/Undo.py | 6 +- src/App/ZApplication.py | 6 +- src/App/config.py | 10 +- src/App/interfaces.py | 7 +- src/App/special_dtml.py | 6 +- src/App/tests/test_cachemanager.py | 3 +- src/App/tests/test_class_init.py | 3 +- src/App/tests/test_setConfiguration.py | 3 +- src/App/version_txt.py | 2 +- src/OFS/Application.py | 22 +- src/OFS/Cache.py | 77 ++- src/OFS/CopySupport.py | 27 +- src/OFS/DTMLDocument.py | 14 +- src/OFS/DTMLMethod.py | 30 +- src/OFS/EtagSupport.py | 52 +- src/OFS/FindSupport.py | 9 +- src/OFS/Folder.py | 16 +- src/OFS/History.py | 32 +- src/OFS/Image.py | 69 +-- src/OFS/Lockable.py | 11 +- src/OFS/Moniker.py | 30 +- src/OFS/ObjectManager.py | 39 +- src/OFS/OrderSupport.py | 31 +- src/OFS/OrderedFolder.py | 10 +- src/OFS/PropertyManager.py | 24 +- src/OFS/PropertySheets.py | 60 +-- src/OFS/SimpleItem.py | 36 +- src/OFS/Traversable.py | 17 +- src/OFS/Uninstalled.py | 4 +- src/OFS/__init__.py | 1 - src/OFS/absoluteurl.py | 15 +- src/OFS/browser/__init__.py | 2 +- src/OFS/event.py | 8 +- src/OFS/interfaces.py | 452 ++++++++---------- src/OFS/metaconfigure.py | 6 +- src/OFS/metadirectives.py | 8 +- src/OFS/owner.py | 6 +- src/OFS/role.py | 18 +- src/OFS/subscribers.py | 31 +- src/OFS/tests/applicationproduct/__init__.py | 8 +- src/OFS/tests/testAppInitializer.py | 2 +- src/OFS/tests/testCopySupport.py | 6 +- src/OFS/tests/testCopySupportEvents.py | 4 +- src/OFS/tests/testCopySupportHooks.py | 4 +- src/OFS/tests/testFileAndImage.py | 2 +- src/OFS/tests/testFindSupport.py | 2 +- src/OFS/tests/testHistory.py | 4 +- src/OFS/tests/testObjectManager.py | 1 + src/OFS/tests/testProperties.py | 3 +- src/OFS/tests/testSorting.py | 2 +- src/OFS/tests/testTraverse.py | 41 +- src/OFS/tests/test_DTMLDocument.py | 2 +- src/OFS/tests/test_DTMLMethod.py | 4 +- src/OFS/tests/test_Uninstalled.py | 3 +- src/OFS/tests/test_event.py | 3 +- src/OFS/tests/test_registerclass.py | 9 +- src/OFS/tests/test_registerpackage.py | 6 +- src/OFS/tests/test_userfolder.py | 3 +- src/OFS/userfolder.py | 72 +-- src/Products/Five/__init__.py | 3 +- src/Products/Five/browser/__init__.py | 3 +- src/Products/Five/browser/adding.py | 16 +- src/Products/Five/browser/metaconfigure.py | 2 +- src/Products/Five/browser/pagetemplatefile.py | 8 +- src/Products/Five/browser/resource.py | 18 +- src/Products/Five/browser/tests/classes.py | 6 +- src/Products/Five/browser/tests/i18n.py | 3 +- src/Products/Five/browser/tests/pages.py | 33 +- src/Products/Five/browser/tests/skin.py | 3 +- .../Five/browser/tests/test_absoluteurl.py | 7 +- .../Five/browser/tests/test_adding.py | 3 +- .../Five/browser/tests/test_defaultview.py | 11 +- src/Products/Five/browser/tests/test_i18n.py | 6 +- src/Products/Five/browser/tests/test_menu.py | 6 +- src/Products/Five/browser/tests/test_pages.py | 8 +- .../Five/browser/tests/test_provider.py | 3 +- .../Five/browser/tests/test_recurse.py | 6 +- .../Five/browser/tests/test_resource.py | 3 +- .../Five/browser/tests/test_scriptsecurity.py | 9 +- src/Products/Five/browser/tests/test_skin.py | 3 +- .../Five/browser/tests/test_traversable.py | 9 +- .../Five/browser/tests/test_zope3security.py | 12 +- src/Products/Five/component/__init__.py | 18 +- src/Products/Five/component/browser.py | 3 +- src/Products/Five/component/interfaces.py | 3 +- src/Products/Five/component/tests.py | 3 +- src/Products/Five/fiveconfigure.py | 5 +- src/Products/Five/fivedirectives.py | 9 +- src/Products/Five/sizeconfigure.py | 9 +- src/Products/Five/skin/standardmacros.py | 3 +- src/Products/Five/skin/tests/demomacros.py | 3 +- .../Five/skin/tests/test_standardmacros.py | 5 +- src/Products/Five/tests/adapters.py | 21 +- src/Products/Five/tests/classes.py | 9 +- src/Products/Five/tests/metaconfigure.py | 6 +- src/Products/Five/tests/test_directives.py | 6 +- src/Products/Five/tests/test_i18n.py | 3 +- src/Products/Five/tests/test_size.py | 6 +- src/Products/Five/tests/testing/__init__.py | 3 +- .../Five/tests/testing/fancycontent.py | 15 +- src/Products/Five/tests/testing/folder.py | 8 +- .../Five/tests/testing/simplecontent.py | 14 +- src/Products/Five/utilities/browser/marker.py | 6 +- .../utilities/browser/tests/test_marker.py | 3 +- src/Products/Five/utilities/interfaces.py | 40 +- src/Products/Five/utilities/marker.py | 9 +- src/Products/Five/viewlet/manager.py | 9 +- src/Products/Five/viewlet/metaconfigure.py | 3 +- src/Products/Five/viewlet/tests.py | 8 +- src/Products/Five/viewlet/viewlet.py | 6 +- src/Products/PageTemplates/Expressions.py | 52 +- src/Products/PageTemplates/PageTemplate.py | 3 +- .../PageTemplates/PageTemplateFile.py | 8 +- src/Products/PageTemplates/ZRPythonExpr.py | 2 +- .../PageTemplates/ZopePageTemplate.py | 12 +- src/Products/PageTemplates/__init__.py | 2 +- src/Products/PageTemplates/engine.py | 15 +- src/Products/PageTemplates/expression.py | 1 + src/Products/PageTemplates/interfaces.py | 17 +- src/Products/PageTemplates/tests/batch.py | 2 +- .../PageTemplates/tests/testDTMLTests.py | 5 +- .../PageTemplates/tests/testHTMLTests.py | 5 +- .../PageTemplates/tests/testTranslation.py | 2 +- .../PageTemplates/tests/testVariables.py | 2 +- .../PageTemplates/tests/testZRPythonExpr.py | 3 +- .../tests/testZopePageTemplate.py | 5 +- .../tests/testZopeTalesExpressions.py | 2 + .../PageTemplates/unicodeconflictresolver.py | 22 +- src/Products/PageTemplates/utils.py | 30 +- src/Products/SiteAccess/VirtualHostMonster.py | 13 +- .../tests/testVirtualHostMonster.py | 4 +- src/Shared/DC/Scripts/Bindings.py | 20 +- src/Shared/DC/Scripts/BindingsUI.py | 3 +- src/Shared/DC/Scripts/Script.py | 8 +- src/Shared/DC/Scripts/Signature.py | 3 +- src/Testing/ZopeTestCase/PortalTestCase.py | 54 ++- src/Testing/ZopeTestCase/ZopeLite.py | 33 +- src/Testing/ZopeTestCase/ZopeTestCase.py | 35 +- src/Testing/ZopeTestCase/__init__.py | 3 +- src/Testing/ZopeTestCase/base.py | 80 ++-- src/Testing/ZopeTestCase/connections.py | 14 +- src/Testing/ZopeTestCase/functional.py | 21 +- src/Testing/ZopeTestCase/interfaces.py | 101 ++-- src/Testing/ZopeTestCase/layer.py | 48 +- src/Testing/ZopeTestCase/placeless.py | 8 +- src/Testing/ZopeTestCase/sandbox.py | 9 +- src/Testing/ZopeTestCase/testBaseTestCase.py | 16 +- src/Testing/ZopeTestCase/testFunctional.py | 6 +- src/Testing/ZopeTestCase/testInterfaces.py | 3 +- src/Testing/ZopeTestCase/testPlaceless.py | 17 +- .../ZopeTestCase/testPortalTestCase.py | 37 +- src/Testing/ZopeTestCase/testSkeleton.py | 3 +- src/Testing/ZopeTestCase/testZODBCompat.py | 48 +- src/Testing/ZopeTestCase/testZopeTestCase.py | 37 +- src/Testing/ZopeTestCase/tests.py | 3 +- src/Testing/ZopeTestCase/utils.py | 9 +- .../ZopeTestCase/zopedoctest/__init__.py | 3 +- .../ZopeTestCase/zopedoctest/functional.py | 8 +- .../zopedoctest/testAuthHeaderTest.py | 3 +- .../zopedoctest/testFunctionalDocTest.py | 3 +- .../zopedoctest/testLayerExtraction.py | 8 +- .../zopedoctest/testPackageAsProduct.py | 6 +- .../zopedoctest/testWarningsTest.py | 3 +- .../zopedoctest/testZopeDocTest.py | 7 +- src/Testing/ZopeTestCase/zopedoctest/tests.py | 3 +- src/Testing/__init__.py | 4 +- src/Testing/custom_zodb.py | 11 +- src/Testing/makerequest.py | 12 +- src/Testing/testbrowser.py | 5 +- src/Testing/tests/test_makerequest.py | 3 +- src/Testing/tests/test_testbrowser.py | 6 +- src/Testing/utils.py | 3 +- src/ZPublisher/BaseRequest.py | 51 +- src/ZPublisher/BaseResponse.py | 22 +- src/ZPublisher/BeforeTraverse.py | 22 +- src/ZPublisher/Converters.py | 3 +- src/ZPublisher/HTTPRangeSupport.py | 31 +- src/ZPublisher/HTTPRequest.py | 99 ++-- src/ZPublisher/HTTPResponse.py | 182 ++++--- src/ZPublisher/Iterators.py | 44 +- src/ZPublisher/WSGIPublisher.py | 3 +- src/ZPublisher/__init__.py | 3 +- src/ZPublisher/cookie.py | 21 +- src/ZPublisher/interfaces.py | 46 +- src/ZPublisher/mapply.py | 3 +- src/ZPublisher/pubevents.py | 27 +- src/ZPublisher/tests/testBaseRequest.py | 14 +- src/ZPublisher/tests/testBeforeTraverse.py | 13 +- src/ZPublisher/tests/testHTTPRequest.py | 46 +- src/ZPublisher/tests/testHTTPResponse.py | 20 +- src/ZPublisher/tests/testPostTraversal.py | 9 +- src/ZPublisher/tests/test_cookie.py | 2 +- src/ZPublisher/tests/test_pubevents.py | 2 +- src/ZPublisher/tests/test_utils.py | 4 +- src/ZPublisher/xmlrpc.py | 21 +- src/ZTUtils/Batch.py | 9 +- src/ZTUtils/Lazy.py | 14 +- src/ZTUtils/SimpleTree.py | 5 +- src/ZTUtils/Tree.py | 65 ++- src/ZTUtils/Zope.py | 71 ++- src/ZTUtils/__init__.py | 3 +- src/ZTUtils/tests/testBatch.py | 8 +- src/ZTUtils/tests/testZope.py | 8 +- src/Zope2/App/schema.py | 6 +- src/Zope2/App/startup.py | 3 +- src/Zope2/Startup/datatypes.py | 25 +- src/Zope2/Startup/handlers.py | 4 +- src/Zope2/Startup/options.py | 12 +- src/Zope2/Startup/run.py | 14 +- src/Zope2/Startup/serve.py | 8 +- src/Zope2/Startup/tests/test_schema.py | 3 +- src/Zope2/__init__.py | 6 +- src/Zope2/utilities/adduser.py | 2 +- src/Zope2/utilities/copyzopeskel.py | 4 +- src/Zope2/utilities/mkwsgiinstance.py | 11 +- src/webdav/Collection.py | 33 +- src/webdav/NullResource.py | 39 +- src/webdav/PropertySheets.py | 2 +- src/webdav/Resource.py | 82 ++-- src/webdav/__init__.py | 36 +- src/webdav/common.py | 4 +- src/webdav/davcmds.py | 25 +- src/webdav/hookable_PUT.py | 3 +- src/webdav/interfaces.py | 118 +++-- src/webdav/tests/testCopySupportEvents.py | 4 +- src/webdav/tests/testCopySupportHooks.py | 4 +- src/webdav/tests/test_davcmds.py | 4 +- src/webdav/xmltools.py | 15 +- src/zmi/styles/tests.py | 1 + util.py | 4 +- 240 files changed, 1971 insertions(+), 2221 deletions(-) diff --git a/docs/zdgbook/examples/PollImplementation.py b/docs/zdgbook/examples/PollImplementation.py index c34a8a0d16..30ab35ee41 100644 --- a/docs/zdgbook/examples/PollImplementation.py +++ b/docs/zdgbook/examples/PollImplementation.py @@ -2,12 +2,11 @@ class PollImplementation: - """ - A multiple choice poll, implements the Poll interface. + """A multiple choice poll, implements the Poll interface. - The poll has a question and a sequence of responses. Votes - are stored in a dictionary which maps response indexes to a - number of votes. + The poll has a question and a sequence of responses. Votes are + stored in a dictionary which maps response indexes to a number of + votes. """ __implements__ = Poll diff --git a/docs/zdgbook/examples/PollProduct.py b/docs/zdgbook/examples/PollProduct.py index 11ae1b75ff..00ab40bd12 100644 --- a/docs/zdgbook/examples/PollProduct.py +++ b/docs/zdgbook/examples/PollProduct.py @@ -8,12 +8,11 @@ class PollProduct(Implicit, Persistent, RoleManager, Item): - """ - Poll product class, implements Poll interface. + """Poll product class, implements Poll interface. - The poll has a question and a sequence of responses. Votes - are stored in a dictionary which maps response indexes to a - number of votes. + The poll has a question and a sequence of responses. Votes are + stored in a dictionary which maps response indexes to a number of + votes. """ __implements__ = Poll diff --git a/src/App/ApplicationManager.py b/src/App/ApplicationManager.py index 07a2e75026..89b997b437 100644 --- a/src/App/ApplicationManager.py +++ b/src/App/ApplicationManager.py @@ -45,8 +45,7 @@ def db(self): class DatabaseChooser(Tabs, Traversable, Implicit): - """ Choose which database to view - """ + """Choose which database to view.""" __allow_access_to_unprotected_subobjects__ = 1 @@ -69,8 +68,7 @@ class DatabaseChooser(Tabs, Traversable, Implicit): def getDatabaseNames(self, quote=False): configuration = getConfiguration() - names = configuration.dbtab.listDatabaseNames() - names.sort() + names = sorted(configuration.dbtab.listDatabaseNames()) if quote: return [(name, parse.quote(name)) for name in names] return names @@ -94,8 +92,7 @@ def __bobo_traverse__(self, request, name): class ConfigurationViewer(Tabs, Traversable, Implicit): - """ Provides information about the running configuration - """ + """Provides information about the running configuration.""" manage = manage_main = manage_workspace = DTMLFile('dtml/cpConfiguration', globals()) manage_main._setName('manage_main') @@ -145,8 +142,7 @@ def manage_getConfiguration(self): class DebugManager(Tabs, Traversable, Implicit): - """ Debug and profiling information - """ + """Debug and profiling information.""" manage = manage_main = manage_workspace = DTMLFile('dtml/debug', globals()) manage_main._setName('manage_main') id = 'DebugInfo' @@ -240,8 +236,7 @@ class ApplicationManager(CacheManager, Tabs, Traversable, Implicit): - """System management - """ + """System management.""" __allow_access_to_unprotected_subobjects__ = 1 __roles__ = ('Manager',) @@ -312,8 +307,7 @@ def getCLIENT_HOME(self): class AltDatabaseManager(Traversable, UndoSupport): - """ Database management DBTab-style - """ + """Database management DBTab-style.""" id = 'DatabaseManagement' name = title = 'Database Management' meta_type = 'Database Management' @@ -371,7 +365,7 @@ def manage_minimize(self, value=1, REQUEST=None): @requestmethod('POST') def manage_pack(self, days=0, REQUEST=None): - """Pack the database""" + """Pack the database.""" if not isinstance(days, (int, float)): try: days = float(days) diff --git a/src/App/CacheManager.py b/src/App/CacheManager.py index ebbe1c379f..59d8c6cb6a 100644 --- a/src/App/CacheManager.py +++ b/src/App/CacheManager.py @@ -12,7 +12,8 @@ ############################################################################## """Cache management support. -This class is mixed into the application manager in App.ApplicationManager. +This class is mixed into the application manager in +App.ApplicationManager. """ from AccessControl.class_init import InitializeClass @@ -20,8 +21,7 @@ class CacheManager: - """Cache management mix-in - """ + """Cache management mix-in.""" def _getDB(self): try: @@ -34,10 +34,8 @@ def cache_size(self): return db.getCacheSize() def cache_detail(self, REQUEST=None): - """ - Returns the name of the classes of the objects in the cache - and the number of objects in the cache for each class. - """ + """Returns the name of the classes of the objects in the cache and the + number of objects in the cache for each class.""" detail = self._getDB().cacheDetail() if REQUEST is not None: # format as text @@ -48,9 +46,7 @@ def cache_detail(self, REQUEST=None): return detail def cache_extreme_detail(self, REQUEST=None): - """ - Returns information about each object in the cache. - """ + """Returns information about each object in the cache.""" detail = self._getDB().cacheExtremeDetail() if REQUEST is not None: # sort the list. diff --git a/src/App/Dialogs.py b/src/App/Dialogs.py index b5d440562d..4fdc611e21 100644 --- a/src/App/Dialogs.py +++ b/src/App/Dialogs.py @@ -10,37 +10,37 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## +"""Common HTML dialog boxes. -"""Common HTML dialog boxes +MessageDialog(title, message, action, [target]) - MessageDialog(title, message, action, [target]) +A very simple dialog used to display an HTML page titled title, +displaying message message and an OK button. Clicking the OK +button will take the browser to the URL specified in action. +The *optional* target argument can be used to force a (frames +capable) browser to load the URL specified in action into a specific +frame. (Specifying '_new' will cause the browser to load the +specified URL into a new window, for example). - A very simple dialog used to display an HTML page titled title, - displaying message message and an OK button. Clicking the OK - button will take the browser to the URL specified in action. - The *optional* target argument can be used to force a (frames - capable) browser to load the URL specified in action into a specific - frame. (Specifying '_new' will cause the browser to load the - specified URL into a new window, for example). - - example usage: -
-    return MessageDialog(title='Just thought you should know...',
-                         message='You have wiped out your data.',
-                         action='/paid_tech_support/prices.html',
-                         target='_top')
-    
""" +example usage: +
+return MessageDialog(title='Just thought you should know...',
+                     message='You have wiped out your data.',
+                     action='/paid_tech_support/prices.html',
+                     target='_top')
+
+""" from App.special_dtml import HTML class MessageDialogHTML(HTML): - """A special version of HTML which is always published as text/html - """ + """A special version of HTML which is always published as text/html.""" + def __call__(self, *args, **kw): class _HTMLString(str): - """A special string that will be published as text/html - """ + """A special string that will be published as text/html.""" + def asHTML(self): return self return _HTMLString(super().__call__(*args, **kw)) diff --git a/src/App/Extensions.py b/src/App/Extensions.py index dce6b121d6..a88f1587b1 100644 --- a/src/App/Extensions.py +++ b/src/App/Extensions.py @@ -63,7 +63,7 @@ def _getPath(home, prefix, name, suffixes): def getPath(prefix, name, checkProduct=1, suffixes=('',), cfg=None): - """Find a file in one of several relative locations + """Find a file in one of several relative locations. Arguments: diff --git a/src/App/FactoryDispatcher.py b/src/App/FactoryDispatcher.py index fb090afa9e..22768da8e8 100644 --- a/src/App/FactoryDispatcher.py +++ b/src/App/FactoryDispatcher.py @@ -28,9 +28,8 @@ def _product_packages(): - """Returns all product packages including the regularly defined - zope2 packages and those without the Products namespace package. - """ + """Returns all product packages including the regularly defined zope2 + packages and those without the Products namespace package.""" import Products _packages = {} @@ -46,8 +45,7 @@ def _product_packages(): class Product(Base): - """Model a non-persistent product wrapper. - """ + """Model a non-persistent product wrapper.""" security = ClassSecurityInfo() @@ -96,8 +94,7 @@ def __bobo_traverse__(self, REQUEST, name): class FactoryDispatcher(Implicit): - """Provide a namespace for product "methods" - """ + """Provide a namespace for product "methods".""" security = ClassSecurityInfo() @@ -158,8 +155,7 @@ def __getattr__(self, name): # Provide a replacement for manage_main that does a redirection: def manage_main(trueself, self, REQUEST, update_menu=0): - """Implement a contents view by redirecting to the true view - """ + """Implement a contents view by redirecting to the true view.""" REQUEST.RESPONSE.redirect(self.DestinationURL() + '/manage_main') diff --git a/src/App/ImageFile.py b/src/App/ImageFile.py index c60d4a557a..87556218bb 100644 --- a/src/App/ImageFile.py +++ b/src/App/ImageFile.py @@ -10,7 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Image object that is stored in a file""" +"""Image object that is stored in a file.""" import os.path import stat @@ -87,7 +87,7 @@ def __init__(self, path, _prefix=None): self.lmh = rfc1123_date(self.lmt) def index_html(self, REQUEST, RESPONSE): - """Default document""" + """Default document.""" # HTTP If-Modified-Since header handling. This is duplicated # from OFS.Image.Image - it really should be consolidated # somewhere... @@ -122,7 +122,7 @@ def index_html(self, REQUEST, RESPONSE): @security.public def HEAD(self, REQUEST, RESPONSE): - """ """ + """""" RESPONSE.setHeader('Content-Type', self.content_type) RESPONSE.setHeader('Last-Modified', self.lmh) return '' diff --git a/src/App/Management.py b/src/App/Management.py index 02b469c21e..3629d92b52 100644 --- a/src/App/Management.py +++ b/src/App/Management.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Standard management interface support -""" +"""Standard management interface support.""" import html import itertools @@ -69,8 +68,7 @@ def filtered_manage_options(self, REQUEST=None): manage_workspace__roles__ = ('Authenticated',) def manage_workspace(self, REQUEST): - """Dispatch to first interface in manage_options - """ + """Dispatch to first interface in manage_options.""" options = self.filtered_manage_options(REQUEST) try: m = options[0]['action'] @@ -138,7 +136,7 @@ def tabs_path_info(self, script, path): @implementer(INavigation) class Navigation(Base): - """Basic navigation UI support""" + """Basic navigation UI support.""" security = ClassSecurityInfo() @@ -183,7 +181,7 @@ def manage_page_header(self, *args, **kw): @security.public def manage_zmi_logout(self, REQUEST, RESPONSE): - """Logout current user""" + """Logout current user.""" p = getattr(REQUEST, '_logout_path', None) if p is not None: return self.restrictedTraverse(*p) diff --git a/src/App/ProductContext.py b/src/App/ProductContext.py index 325f35aa60..7a5865b850 100644 --- a/src/App/ProductContext.py +++ b/src/App/ProductContext.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Objects providing context for product initialization -""" +"""Objects providing context for product initialization.""" import os from logging import getLogger @@ -47,7 +46,7 @@ def registerClass(self, instance_class=None, meta_type='', icon=None, permissions=None, legacy=(), visibility="Global", interfaces=_marker, container_filter=None): - """Register a constructor + """Register a constructor. Keyword arguments are used to provide meta data: @@ -92,7 +91,6 @@ class will be registered. filter is called before showing ObjectManager's Add list, and before pasting (after object copy or cut), but not before calling an object's constructor. - """ pack = self.__pack initial = constructors[0] diff --git a/src/App/Undo.py b/src/App/Undo.py index a162858f4d..9d9bf2521e 100644 --- a/src/App/Undo.py +++ b/src/App/Undo.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Undo support. -""" +"""Undo support.""" import binascii @@ -99,8 +98,7 @@ def undoable_transactions(self, first_transaction=None, @security.protected(undo_changes) def manage_undo_transactions(self, transaction_info=(), REQUEST=None): - """ - """ + """""" tids = [] descriptions = [] for tid in transaction_info: diff --git a/src/App/ZApplication.py b/src/App/ZApplication.py index 37ac18443f..11836770d7 100644 --- a/src/App/ZApplication.py +++ b/src/App/ZApplication.py @@ -11,10 +11,10 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Implement an bobo_application object that is BoboPOS3 aware +"""Implement an bobo_application object that is BoboPOS3 aware. -This module provides a wrapper that causes a database connection to be created -and used when bobo publishes a bobo_application object. +This module provides a wrapper that causes a database connection to be +created and used when bobo publishes a bobo_application object. """ diff --git a/src/App/config.py b/src/App/config.py index f29b0e55cb..30ddafb93f 100644 --- a/src/App/config.py +++ b/src/App/config.py @@ -33,9 +33,8 @@ def getConfiguration(): def setConfiguration(cfg): """Set the global configuration object. - Legacy sources of common configuration values are updated to - reflect the new configuration; this may be removed in some future - version. + Legacy sources of common configuration values are updated to reflect + the new configuration; this may be removed in some future version. """ global _config _config = cfg @@ -52,9 +51,8 @@ def setConfiguration(cfg): class DefaultConfiguration: - """ - This configuration should be used effectively only during unit tests - """ + """This configuration should be used effectively only during unit tests.""" + def __init__(self): from App import FindHomes self.clienthome = FindHomes.CLIENT_HOME diff --git a/src/App/interfaces.py b/src/App/interfaces.py index ddfc81c79e..a017d32e06 100644 --- a/src/App/interfaces.py +++ b/src/App/interfaces.py @@ -10,15 +10,14 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""App interfaces. -""" +"""App interfaces.""" from zope.interface import Attribute from zope.interface import Interface class INavigation(Interface): - """Basic navigation UI support""" + """Basic navigation UI support.""" manage = Attribute(""" """) manage_menu = Attribute(""" """) @@ -27,7 +26,7 @@ class INavigation(Interface): manage_form_title = Attribute("""Add Form""") def manage_zmi_logout(REQUEST, RESPONSE): - """Logout current user""" + """Logout current user.""" class ICSSPaths(Interface): diff --git a/src/App/special_dtml.py b/src/App/special_dtml.py index 25a0104612..9e974ccae7 100644 --- a/src/App/special_dtml.py +++ b/src/App/special_dtml.py @@ -134,10 +134,8 @@ def __init__(self, name, _prefix=None, **kw): DTMLFile.inheritedAttribute('__init__')(self, name, _prefix, **kw) def getOwner(self, info=0): - ''' - This method is required of all objects that go into - the security context stack. - ''' + """This method is required of all objects that go into the security + context stack.""" return None def _exec(self, bound_data, args, kw): diff --git a/src/App/tests/test_cachemanager.py b/src/App/tests/test_cachemanager.py index 05ed7cab3e..fde648662b 100644 --- a/src/App/tests/test_cachemanager.py +++ b/src/App/tests/test_cachemanager.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Tests for the CacheManager. -""" +"""Tests for the CacheManager.""" import unittest diff --git a/src/App/tests/test_class_init.py b/src/App/tests/test_class_init.py index b5ee090e0b..777015b408 100644 --- a/src/App/tests/test_class_init.py +++ b/src/App/tests/test_class_init.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Tests class initialization. -""" +"""Tests class initialization.""" import unittest diff --git a/src/App/tests/test_setConfiguration.py b/src/App/tests/test_setConfiguration.py index 06c7fce84f..d13890c3c3 100644 --- a/src/App/tests/test_setConfiguration.py +++ b/src/App/tests/test_setConfiguration.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Tests for App.config.setConfiguration() -""" +"""Tests for App.config.setConfiguration()""" import unittest from Testing.ZopeTestCase.layer import ZopeLite diff --git a/src/App/version_txt.py b/src/App/version_txt.py index 9067dbb1c7..8755954c1a 100644 --- a/src/App/version_txt.py +++ b/src/App/version_txt.py @@ -88,7 +88,7 @@ def version_txt(): def getZopeVersion(): - """return information about the Zope version as a named tuple. + """Return information about the Zope version as a named tuple. Format of zope_version tuple: (major , minor , micro , status , release ) diff --git a/src/OFS/Application.py b/src/OFS/Application.py index 0bc289b3d0..d015aa2ade 100644 --- a/src/OFS/Application.py +++ b/src/OFS/Application.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Application support -""" +"""Application support.""" import os import sys @@ -53,7 +52,7 @@ @implementer(IApplication) class Application(ApplicationDefaultPermissions, Folder.Folder, FindSupport): - """Top-level system object""" + """Top-level system object.""" security = ClassSecurityInfo() @@ -109,7 +108,7 @@ def Redirect(self, destination, URL1): @security.protected(view_management_screens) def getZMIMainFrameTarget(self, REQUEST): - """Utility method to get the right hand side ZMI frame source URL + """Utility method to get the right hand side ZMI frame source URL. For cases where JavaScript is disabled the ZMI uses a simple REQUEST variable ``came_from`` to set the source URL for the right hand side @@ -181,12 +180,12 @@ def __bobo_traverse__(self, REQUEST, name=None): raise KeyError(name) def ZopeTime(self, *args): - """Utility function to return current date/time""" + """Utility function to return current date/time.""" return DateTime(*args) @security.protected(view_management_screens) def ZopeVersion(self, major=False): - """Utility method to return the Zope version + """Utility method to return the Zope version. Restricted to ZMI to prevent information disclosure """ @@ -211,8 +210,7 @@ def MOVE(self, REQUEST, RESPONSE): raise Forbidden('This resource cannot be moved.') def absolute_url(self, relative=0): - """The absolute URL of the root object is BASE1 or "/". - """ + """The absolute URL of the root object is BASE1 or "/".""" if relative: return '' try: @@ -222,16 +220,14 @@ def absolute_url(self, relative=0): return '/' def absolute_url_path(self): - """The absolute URL path of the root object is BASEPATH1 or "/". - """ + """The absolute URL path of the root object is BASEPATH1 or "/".""" try: return self.REQUEST['BASEPATH1'] or '/' except (AttributeError, KeyError): return '/' def virtual_url_path(self): - """The virtual URL path of the root object is empty. - """ + """The virtual URL path of the root object is empty.""" return '' def getPhysicalRoot(self): @@ -258,7 +254,7 @@ def initialize(app): class AppInitializer: - """ Initialize an Application object (called at startup) """ + """Initialize an Application object (called at startup)""" def __init__(self, app): self.app = (app,) diff --git a/src/OFS/Cache.py b/src/OFS/Cache.py index aca6ef9998..03b1b8cb00 100644 --- a/src/OFS/Cache.py +++ b/src/OFS/Cache.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Cacheable object and cache management base classes. -""" +"""Cacheable object and cache management base classes.""" import sys import time @@ -53,10 +52,10 @@ def filterCacheTab(ob): def filterCacheManagers(orig, container, name, value, extra): - """ - This is a filter method for aq_acquire. - It causes objects to be found only if they are - in the list of cache managers. + """This is a filter method for aq_acquire. + + It causes objects to be found only if they are in the list of cache + managers. """ if hasattr(aq_base(container), ZCM_MANAGERS) and \ name in getattr(container, ZCM_MANAGERS): @@ -123,8 +122,7 @@ def ZCacheable_getManager(self): @security.private def ZCacheable_getCache(self): - """Gets the cache associated with this object. - """ + """Gets the cache associated with this object.""" if self.__manager_id is None: return None c = self._v_ZCacheable_cache @@ -144,10 +142,8 @@ def ZCacheable_getCache(self): @security.private def ZCacheable_isCachingEnabled(self): - """ - Returns true only if associated with a cache manager and - caching of this method is enabled. - """ + """Returns true only if associated with a cache manager and caching of + this method is enabled.""" return self.__enabled and self.ZCacheable_getCache() @security.private @@ -163,9 +159,10 @@ def ZCacheable_get( mtime_func=None, default=None ): - """Retrieves the cached view for the object under the - conditions specified by keywords. If the value is - not yet cached, returns the default. + """Retrieves the cached view for the object under the conditions + specified by keywords. + + If the value is not yet cached, returns the default. """ c = self.ZCacheable_getCache() if c is not None and self.__enabled: @@ -187,8 +184,10 @@ def ZCacheable_set( keywords=None, mtime_func=None ): - """Cacheable views should call this method after generating - cacheable results. The data argument can be of any Python type. + """Cacheable views should call this method after generating cacheable + results. + + The data argument can be of any Python type. """ c = self.ZCacheable_getCache() if c is not None and self.__enabled: @@ -201,9 +200,10 @@ def ZCacheable_set( @security.protected(ViewManagementScreensPermission) def ZCacheable_invalidate(self, view_name='', REQUEST=None): - """Called after a cacheable object is edited. Causes all - cache entries that apply to the view_name to be removed. - Returns a status message. + """Called after a cacheable object is edited. + + Causes all cache entries that apply to the view_name to be + removed. Returns a status message. """ c = self.ZCacheable_getCache() if c is not None: @@ -263,8 +263,8 @@ def ZCacheable_getManagerURL(self): @security.protected(ViewManagementScreensPermission) def ZCacheable_getManagerIds(self): - """Returns a list of mappings containing the id and title - of the available ZCacheManagers.""" + """Returns a list of mappings containing the id and title of the + available ZCacheManagers.""" rval = [] ob = self used_ids = {} @@ -320,9 +320,8 @@ def ZCacheable_setEnabled(self, enabled=0, REQUEST=None): @security.protected(ViewManagementScreensPermission) def ZCacheable_configHTML(self): - """Override to provide configuration of caching - behavior that can only be specific to the cacheable object. - """ + """Override to provide configuration of caching behavior that can only + be specific to the cacheable object.""" return '' @@ -338,9 +337,10 @@ def findCacheables( rval, path ): - """ - Used by the CacheManager UI. Recursive. Similar to the Zope - "Find" function. Finds all Cacheable objects in a hierarchy. + """Used by the CacheManager UI. + + Recursive. Similar to the Zope "Find" function. Finds all + Cacheable objects in a hierarchy. """ try: if meta_types: @@ -387,10 +387,10 @@ def findCacheables( class Cache: - """ - A base class (and interface description) for caches. - Note that Cache objects are not intended to be visible by - restricted code. + """A base class (and interface description) for caches. + + Note that Cache objects are not intended to be visible by restricted + code. """ def ZCache_invalidate(self, ob): @@ -421,8 +421,9 @@ def ZCache_set(self, ob, data, view_name, keywords, mtime_func): class CacheManager: - """ - A base class for cache managers. Implement ZCacheManager_getCache(). + """A base class for cache managers. + + Implement ZCacheManager_getCache(). """ security = ClassSecurityInfo() @@ -476,8 +477,7 @@ def ZCacheManager_locate( meta_types=[], REQUEST=None ): - """Locates cacheable objects. - """ + """Locates cacheable objects.""" ob = aq_parent(aq_inner(self)) rval = [] manager_id = self.getId() @@ -506,9 +506,8 @@ def ZCacheManager_locate( @security.protected(ChangeCacheSettingsPermission) def ZCacheManager_setAssociations(self, props=None, REQUEST=None): - """Associates and un-associates cacheable objects with this - cache manager. - """ + """Associates and un-associates cacheable objects with this cache + manager.""" addcount = 0 remcount = 0 parent = aq_parent(aq_inner(self)) diff --git a/src/OFS/CopySupport.py b/src/OFS/CopySupport.py index 1dc46d71a9..0e6f86180e 100644 --- a/src/OFS/CopySupport.py +++ b/src/OFS/CopySupport.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Copy interface -""" +"""Copy interface.""" import base64 import logging @@ -64,8 +63,7 @@ class CopyError(Exception): @implementer(ICopyContainer) class CopyContainer(Base): - - """Interface for containerish objects which allow cut/copy/paste""" + """Interface for containerish objects which allow cut/copy/paste.""" security = ClassSecurityInfo() @@ -92,7 +90,7 @@ def manage_CopyContainerAllItems(self, REQUEST): @security.protected(delete_objects) def manage_cutObjects(self, ids=None, REQUEST=None): - """Put a reference to the objects named in ids in the clip board""" + """Put a reference to the objects named in ids in the clip board.""" if ids is None and REQUEST is not None: raise BadRequest('No items specified') elif ids is None: @@ -122,7 +120,7 @@ def manage_cutObjects(self, ids=None, REQUEST=None): @security.protected(view_management_screens) def manage_copyObjects(self, ids=None, REQUEST=None, RESPONSE=None): - """Put a reference to the objects named in ids in the clip board""" + """Put a reference to the objects named in ids in the clip board.""" if ids is None and REQUEST is not None: raise BadRequest('No items specified') elif ids is None: @@ -157,7 +155,7 @@ def _get_id(self, id): else: n = 0 orig_id = id - while 1: + while True: if self._getOb(id, None) is None: return id id = 'copy{}_of_{}'.format(n and n + 1 or '', orig_id) @@ -335,7 +333,7 @@ def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None): @security.protected(view_management_screens) def manage_renameObjects(self, ids=[], new_ids=[], REQUEST=None): - """Rename several sub-objects""" + """Rename several sub-objects.""" if len(ids) != len(new_ids): raise BadRequest('Please rename each listed object.') for i in range(len(ids)): @@ -346,8 +344,7 @@ def manage_renameObjects(self, ids=[], new_ids=[], REQUEST=None): @security.protected(view_management_screens) def manage_renameObject(self, id, new_id, REQUEST=None): - """Rename a particular sub-object. - """ + """Rename a particular sub-object.""" try: self._checkId(new_id) except Exception: @@ -401,8 +398,7 @@ def manage_renameObject(self, id, new_id, REQUEST=None): @security.public def manage_clone(self, ob, id, REQUEST=None): - """Clone an object, creating a new object with the given id. - """ + """Clone an object, creating a new object with the given id.""" if not ob.cb_isCopyable(): raise CopyError('Not Supported') try: @@ -517,7 +513,6 @@ def _verifyObjectPaste(self, object, validate_src=1): @implementer(ICopySource) class CopySource(Base): - """Interface for objects which allow themselves to be copied.""" # declare a dummy permission for Copy or Move here that we check @@ -535,8 +530,8 @@ def _canCopy(self, op=0): def _notifyOfCopyTo(self, container, op=0): """Overide this to be pickly about where you go! - If you dont want to go there, raise an exception. The op variable is 0 - for a copy, 1 for a move. + If you dont want to go there, raise an exception. The op + variable is 0 for a copy, 1 for a move. """ pass @@ -643,7 +638,7 @@ def sanity_check(c, ob): # an object is not cut and pasted into itself or one of its # subobjects, which is an undefined situation. ob = aq_base(ob) - while 1: + while True: if aq_base(c) is ob: return 0 inner = aq_inner(c) diff --git a/src/OFS/DTMLDocument.py b/src/OFS/DTMLDocument.py index 00ede85eba..2cd02d7d52 100644 --- a/src/OFS/DTMLDocument.py +++ b/src/OFS/DTMLDocument.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""DTML Document objects. -""" +"""DTML Document objects.""" from urllib.parse import quote @@ -36,8 +35,7 @@ class DTMLDocument(PropertyManager, DTMLMethod): - """ DocumentTemplate.HTML objects whose 'self' is the DTML object. - """ + """DocumentTemplate.HTML objects whose 'self' is the DTML object.""" meta_type = 'DTML Document' zmi_icon = 'far fa-file-alt' _locked_error_text = 'This document has been locked.' @@ -57,7 +55,8 @@ class DTMLDocument(PropertyManager, DTMLMethod): def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw): """Render the document with the given client object. - o If supplied, use REQUEST mapping, Response, and key word arguments. + o If supplied, use REQUEST mapping, Response, and key word + arguments. """ if not self._cache_namespace_keys: data = self.ZCacheable_get(default=_marker) @@ -134,8 +133,9 @@ def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw): def addDTMLDocument(self, id, title='', file='', REQUEST=None, submit=None): - """Add a DTML Document object with the contents of file. If - 'file' is empty, default document text is used. + """Add a DTML Document object with the contents of file. + + If 'file' is empty, default document text is used. """ data = safe_file_data(file) if not data: diff --git a/src/OFS/DTMLMethod.py b/src/OFS/DTMLMethod.py index 7a7e299ac1..fcea5aae06 100644 --- a/src/OFS/DTMLMethod.py +++ b/src/OFS/DTMLMethod.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""DTML Method objects. -""" +"""DTML Method objects.""" import re from urllib.parse import quote @@ -61,8 +60,8 @@ class DTMLMethod( Historical, Cacheable ): - """ DocumentTemplate.HTML objects that act as methods of their containers. - """ + """DocumentTemplate.HTML objects that act as methods of their + containers.""" meta_type = 'DTML Method' zmi_icon = 'far fa-file-alt' _proxy_roles = () @@ -114,10 +113,10 @@ def errQuote(self, s): @security.protected(View) def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw): - """Render using the given client object + """Render using the given client object. - o If client is not passed, we are being called as a sub-template: - don't do any error propagation. + o If client is not passed, we are being called as a sub- + template: don't do any error propagation. o If supplied, use the REQUEST mapping, Response, and key word arguments. @@ -267,8 +266,7 @@ def get_size(self): @security.protected(change_dtml_methods) def manage_edit(self, data, title, SUBMIT='Change', REQUEST=None): - """ Replace contents with 'data', title with 'title'. - """ + """Replace contents with 'data', title with 'title'.""" self._validateProxy() if self.wl_isLocked(): raise ResourceLockedError(self._locked_error_text) @@ -295,7 +293,7 @@ def manage_edit(self, data, title, SUBMIT='Change', REQUEST=None): @security.protected(change_dtml_methods) def manage_upload(self, file='', REQUEST=None): - """ Replace the contents of the document with the text in 'file'. + """Replace the contents of the document with the text in 'file'. Store `file` as a native `str`. """ @@ -339,7 +337,7 @@ def _validateProxy(self, roles=None): @security.protected(change_proxy_roles) @requestmethod('POST') def manage_proxy(self, roles=(), REQUEST=None): - """Change Proxy Roles""" + """Change Proxy Roles.""" user = getSecurityManager().getUser() if 'Manager' not in user.getRolesInContext(self): self._validateProxy(roles) @@ -365,8 +363,7 @@ def document_src(self, REQUEST=None, RESPONSE=None): @security.protected(change_dtml_methods) def PUT(self, REQUEST, RESPONSE): - """ Handle HTTP PUT requests. - """ + """Handle HTTP PUT requests.""" self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) body = safe_file_data(REQUEST.get('BODY', '')) @@ -394,7 +391,7 @@ def decapitate(html, RESPONSE=None): headers = [] spos = 0 eolen = 1 - while 1: + while True: m = hdr_start(html, spos) if not m: if html[spos:spos + 2] == '\r\n': @@ -454,8 +451,9 @@ def safe_file_data(data): def addDTMLMethod(self, id, title='', file='', REQUEST=None, submit=None): - """Add a DTML Method object with the contents of file. If - 'file' is empty, default document text is used. + """Add a DTML Method object with the contents of file. + + If 'file' is empty, default document text is used. """ data = safe_file_data(file) if not data: diff --git a/src/OFS/EtagSupport.py b/src/OFS/EtagSupport.py index 549574c20d..ca4baa537a 100644 --- a/src/OFS/EtagSupport.py +++ b/src/OFS/EtagSupport.py @@ -20,24 +20,23 @@ class EtagBaseInterface(Interface): - """\ - Basic Etag support interface, meaning the object supports generating - an Etag that can be used by certain HTTP and WebDAV Requests. - """ + """\\ Basic Etag support interface, meaning the object supports generating + an Etag that can be used by certain HTTP and WebDAV Requests.""" def http__etag(): - """\ - Entity tags are used for comparing two or more entities from - the same requested resource. Predominantly used for Caching, - Etags can also be used to deal with the 'Lost Updates Problem'. - An HTTP Client such as Amaya that supports PUT for editing can - use the Etag value returned in the head of a GET response in the - 'if-match' header submitted with a PUT request. If the Etag - for the requested resource in the PUT request's 'if-match' header - is different from the current Etag value returned by this method, - the PUT will fail (it means that the state of the resource has - changed since the last copy the Client recieved) because the - precondition (the 'if-match') fails (the submitted Etag does not - match the current Etag). + """\\ Entity tags are used for comparing two or more entities from the + same requested resource. + + Predominantly used for Caching, Etags can also be used to deal + with the 'Lost Updates Problem'. An HTTP Client such as Amaya + that supports PUT for editing can use the Etag value returned in + the head of a GET response in the 'if-match' header submitted + with a PUT request. If the Etag for the requested resource in + the PUT request's 'if-match' header is different from the + current Etag value returned by this method, the PUT will fail + (it means that the state of the resource has changed since the + last copy the Client recieved) because the precondition (the + 'if-match') fails (the submitted Etag does not match the current + Etag). """ def http__refreshEtag(): @@ -58,16 +57,15 @@ def http__refreshEtag(): @implementer(EtagBaseInterface) class EtagSupport: - """ - This class is the basis for supporting Etags in Zope. It's main - function right now is to support the *Lost Updates Problem* by - allowing Etags and If-Match headers to be checked on PUT calls to - provide a *Seatbelt* style functionality. The Etags is based on - the databaes mtime, and thus is updated whenever the - object is updated. If a PUT request, or other HTTP or Dav request - comes in with an Etag different than the current one, that request - can be rejected according to the type of header (If-Match, - If-None-Match). + """This class is the basis for supporting Etags in Zope. + + It's main function right now is to support the *Lost Updates + Problem* by allowing Etags and If-Match headers to be checked on PUT + calls to provide a *Seatbelt* style functionality. The Etags is + based on the databaes mtime, and thus is updated whenever the object + is updated. If a PUT request, or other HTTP or Dav request comes in + with an Etag different than the current one, that request can be + rejected according to the type of header (If-Match, If-None-Match). """ def http__etag(self, readonly=0): diff --git a/src/OFS/FindSupport.py b/src/OFS/FindSupport.py index 842a2594c8..2c52409c17 100644 --- a/src/OFS/FindSupport.py +++ b/src/OFS/FindSupport.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Find support -""" +"""Find support.""" from AccessControl import ClassSecurityInfo from AccessControl.class_init import InitializeClass from AccessControl.Permission import getPermissionIdentifier @@ -208,16 +207,16 @@ def role_match(ob, permission, roles, lt=type([]), tt=type(())): pr = [] fn = pr.append - while 1: + while True: if hasattr(ob, permission): p = getattr(ob, permission) - if type(p) is lt: + if isinstance(p, lt): list(map(fn, p)) if hasattr(ob, '__parent__'): ob = aq_parent(ob) continue break - if type(p) is tt: + if isinstance(p, tt): list(map(fn, p)) break if p is None: diff --git a/src/OFS/Folder.py b/src/OFS/Folder.py index f577fc7b45..a540e37cb2 100644 --- a/src/OFS/Folder.py +++ b/src/OFS/Folder.py @@ -10,9 +10,10 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Folder object +"""Folder object. -Folders are the basic container objects and are analogous to directories. +Folders are the basic container objects and are analogous to +directories. """ from AccessControl.class_init import InitializeClass @@ -40,8 +41,7 @@ def manage_addFolder( createUserF=0, REQUEST=None ): - """Add a new Folder object with id *id*. - """ + """Add a new Folder object with id *id*.""" ob = Folder(id) ob.title = title self._setObject(id, ob) @@ -61,9 +61,11 @@ class Folder( Item, FindSupport ): - """Folders are basic container objects that provide a standard - interface for object management. Folder objects also implement - a management interface and can have arbitrary properties. + """Folders are basic container objects that provide a standard interface + for object management. + + Folder objects also implement a management interface and can have + arbitrary properties. """ meta_type = 'Folder' zmi_icon = 'far fa-folder' diff --git a/src/OFS/History.py b/src/OFS/History.py index e58faec7f5..a001a95b9f 100644 --- a/src/OFS/History.py +++ b/src/OFS/History.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Object Histories -""" +"""Object Histories.""" import difflib from html import escape @@ -40,8 +39,8 @@ class HistorySelectionError(Exception): class HystoryJar: - """A ZODB Connection-like object that provides access to data - but prevents history from being changed.""" + """A ZODB Connection-like object that provides access to data but prevents + history from being changed.""" def __init__(self, base): self.__base__ = base @@ -78,8 +77,8 @@ def historicalRevision(self, serial): class Historian(Implicit): - """An Historian's job is to find hysterical revisions of - objects, given a time.""" + """An Historian's job is to find hysterical revisions of objects, given a + time.""" def __getitem__(self, key): self = self.aq_parent @@ -94,18 +93,19 @@ def __getitem__(self, key): return rev.__of__(self.aq_parent) def manage_workspace(self, REQUEST): - """ We aren't real, so we delegate to that that spawned us! """ + """We aren't real, so we delegate to that that spawned us!""" raise Redirect('/%s/manage_change_history_page' % REQUEST['URL2']) class Historical(Base): - """Mix-in class to provide a veiw that shows hystorical changes - The display is similar to that used for undo, except that the transactions - are limited to those that effect the displayed object and that the - interface doesn't provide an undo capability. - This interface is generally *only* interesting for objects, such - as methods, and documents, that are self-contained, meaning that - they don't have persistent sub-objects. + """Mix-in class to provide a veiw that shows hystorical changes The display + is similar to that used for undo, except that the transactions are limited + to those that effect the displayed object and that the interface doesn't + provide an undo capability. + + This interface is generally *only* interesting for objects, such as + methods, and documents, that are self-contained, meaning that they + don't have persistent sub-objects. """ security = ClassSecurityInfo() HistoricalRevisions = Historian() @@ -147,7 +147,7 @@ def manage_beforeHistoryCopy(self): pass def manage_historyCopy(self, keys=[], RESPONSE=None, URL1=None): - """ Copy a selected revision to the present """ + """Copy a selected revision to the present.""" if not keys: raise HistorySelectionError('No historical revision selected.') @@ -188,7 +188,7 @@ def manage_historyCompare(self, rev1, rev2, REQUEST, @security.protected(view_history) def manage_historicalComparison(self, REQUEST, keys=[]): - """ Compare two selected revisions """ + """Compare two selected revisions.""" if not keys: raise HistorySelectionError('No historical revision selected.') if len(keys) > 2: diff --git a/src/OFS/Image.py b/src/OFS/Image.py index bb9c428967..8a3c1c1084 100644 --- a/src/OFS/Image.py +++ b/src/OFS/Image.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Image object -""" +"""Image object.""" import html import os @@ -54,10 +53,10 @@ def _get_list_from_env(name, default=None): """Get list from environment variable. - Supports splitting on comma or white space. - Use the default as fallback only when the variable is not set. - So if the env variable is set to an empty string, this will ignore the - default and return an empty list. + Supports splitting on comma or white space. Use the default as + fallback only when the variable is not set. So if the env variable + is set to an empty string, this will ignore the default and return + an empty list. """ value = os.environ.get(name) if value is None: @@ -128,7 +127,8 @@ def manage_addFile( ): """Add a new File object. - Creates a new File object 'id' with the contents of 'file'""" + Creates a new File object 'id' with the contents of 'file' + """ id = str(id) title = str(title) @@ -486,8 +486,7 @@ def _should_force_download(self): @security.protected(View) def index_html(self, REQUEST, RESPONSE): - """ - The default view of the contents of a File or Image. + """The default view of the contents of a File or Image. Returns the contents of the file or image. Also, sets the Content-Type HTTP header to the objects content type. @@ -601,9 +600,8 @@ def manage_edit( filedata=None, REQUEST=None ): - """ - Changes the title and content type attributes of the File or Image. - """ + """Changes the title and content type attributes of the File or + Image.""" if self.wl_isLocked(): raise ResourceLockedError("File is locked.") @@ -629,10 +627,10 @@ def manage_edit( @security.protected(change_images_and_files) def manage_upload(self, file='', REQUEST=None): - """ - Replaces the current contents of the File or Image object with file. + """Replaces the current contents of the File or Image object with file. - The file or images contents are replaced with the contents of 'file'. + The file or images contents are replaced with the contents of + 'file'. """ if self.wl_isLocked(): raise ResourceLockedError("File is locked.") @@ -737,7 +735,7 @@ def _read_data(self, file): @security.protected(change_images_and_files) def PUT(self, REQUEST, RESPONSE): - """Handle HTTP PUT requests""" + """Handle HTTP PUT requests.""" self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) type = REQUEST.get_header('content-type', None) @@ -776,7 +774,10 @@ def __bytes__(self): return bytes(self.data) def __str__(self): - """In most cases, this is probably not what you want. Use ``bytes``.""" + """In most cases, this is probably not what you want. + + Use ``bytes``. + """ if isinstance(self.data, Pdata): return bytes(self.data).decode(self._get_encoding()) else: @@ -838,8 +839,7 @@ def manage_addImage( content_type='', REQUEST=None ): - """ - Add a new Image object. + """Add a new Image object. Creates a new Image object 'id' with the contents of 'file'. """ @@ -972,9 +972,11 @@ def getImageInfo(data): class Image(File): - """Image objects can be GIF, PNG or JPEG and have the same methods - as File objects. Images also have a string representation that - renders an HTML 'IMG' tag. + """Image objects can be GIF, PNG or JPEG and have the same methods as File + objects. + + Images also have a string representation that renders an HTML 'IMG' + tag. """ meta_type = 'Image' @@ -1075,18 +1077,17 @@ def tag( ): """Generate an HTML IMG tag for this image, with customization. - Arguments to self.tag() can be any valid attributes of an IMG tag. - 'src' will always be an absolute pathname, to prevent redundant - downloading of images. Defaults are applied intelligently for - 'height', 'width', and 'alt'. If specified, the 'scale', 'xscale', - and 'yscale' keyword arguments will be used to automatically adjust - the output height and width values of the image tag. - # - Since 'class' is a Python reserved word, it cannot be passed in - directly in keyword arguments which is a problem if you are - trying to use 'tag()' to include a CSS class. The tag() method - will accept a 'css_class' argument that will be converted to - 'class' in the output tag to work around this. + Arguments to self.tag() can be any valid attributes of an IMG + tag. 'src' will always be an absolute pathname, to prevent + redundant downloading of images. Defaults are applied + intelligently for 'height', 'width', and 'alt'. If specified, + the 'scale', 'xscale', and 'yscale' keyword arguments will be + used to automatically adjust the output height and width values + of the image tag. # Since 'class' is a Python reserved word, it + cannot be passed in directly in keyword arguments which is a + problem if you are trying to use 'tag()' to include a CSS class. + The tag() method will accept a 'css_class' argument that will be + converted to 'class' in the output tag to work around this. """ if height is None: height = self.height diff --git a/src/OFS/Lockable.py b/src/OFS/Lockable.py index c45b37a677..6da65eed4b 100644 --- a/src/OFS/Lockable.py +++ b/src/OFS/Lockable.py @@ -26,8 +26,7 @@ @implementer(IWriteLock) class LockableItem(EtagSupport): - """Implements the WriteLock interface. - """ + """Implements the WriteLock interface.""" # Protect methods using declarative security security = ClassSecurityInfo() @@ -39,8 +38,8 @@ class LockableItem(EtagSupport): @security.private def wl_lockmapping(self, killinvalids=0, create=0): - """ if 'killinvalids' is 1, locks who are no longer valid - will be deleted """ + """If 'killinvalids' is 1, locks who are no longer valid will be + deleted.""" try: locks = getattr(self, '_dav_writelocks', None) @@ -144,8 +143,8 @@ def wl_clearLocks(self): def wl_isLocked(ob): - """ Returns true if the object is locked, returns 0 if the object - is not locked or does not implement the WriteLockInterface """ + """Returns true if the object is locked, returns 0 if the object is not + locked or does not implement the WriteLockInterface.""" return wl_isLockable(ob) and ob.wl_isLocked() diff --git a/src/OFS/Moniker.py b/src/OFS/Moniker.py index cea296817a..e7f5bce0b8 100644 --- a/src/OFS/Moniker.py +++ b/src/OFS/Moniker.py @@ -10,20 +10,21 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Object monikers +"""Object monikers. - An object moniker is an intelligent reference to a - persistent object. A moniker can be turned back into - a real object that retains its correct version context - and aquisition relationships via a simple interface. +An object moniker is an intelligent reference to a persistent object. A +moniker can be turned back into a real object that retains its correct +version context and aquisition relationships via a simple interface. """ class Moniker: - """An object moniker is an intelligent reference to a - persistent object. A moniker can be turned back into - a real object that retains its correct version context - and acquisition relationships via a simple interface.""" + """An object moniker is an intelligent reference to a persistent object. + + A moniker can be turned back into a real object that retains its + correct version context and acquisition relationships via a simple + interface. + """ def __init__(self, ob=None): if ob is None: @@ -36,15 +37,16 @@ def bind(self, app): return ob def dump(self): - '''Returns an object which can be reconstituted by - loadMoniker(). Result must be compatible with marshal.dump(). - ''' + """Returns an object which can be reconstituted by loadMoniker(). + + Result must be compatible with marshal.dump(). + """ return self.idpath def loadMoniker(data): - '''Re-creates a Moniker object from the given data which had been - generated by Moniker.dump().''' + """Re-creates a Moniker object from the given data which had been generated + by Moniker.dump().""" m = Moniker() m.idpath = data return m diff --git a/src/OFS/ObjectManager.py b/src/OFS/ObjectManager.py index dac5f3971d..7c475e5f23 100644 --- a/src/OFS/ObjectManager.py +++ b/src/OFS/ObjectManager.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Object Manager -""" +"""Object Manager.""" import html import os @@ -157,9 +156,10 @@ class ObjectManager( LockableItem, Traversable ): - """Generic object manager + """Generic object manager. - This class provides core behavior for collections of heterogeneous objects. + This class provides core behavior for collections of heterogeneous + objects. """ security = ClassSecurityInfo() @@ -526,7 +526,7 @@ def superValues(self, t): @security.protected(delete_objects) def manage_delObjects(self, ids=[], REQUEST=None): - """Delete a subordinate object + """Delete a subordinate object. The objects specified in 'ids' get deleted. """ @@ -576,8 +576,7 @@ def tpValues(self): if hasattr(self, id): r.append(self._getOb(id)) else: - obj_ids = self.objectIds() - obj_ids.sort() + obj_ids = sorted(self.objectIds()) for id in obj_ids: o = self._getOb(id) if hasattr(aq_base(o), 'isPrincipiaFolderish') and \ @@ -635,7 +634,7 @@ def manage_exportObject( @security.protected(import_export_objects) def manage_importObject(self, file, REQUEST=None, set_owner=1, suppress_events=False): - """Import an object from a file""" + """Import an object from a file.""" dirname, file = os.path.split(file) if dirname: raise BadRequest('Invalid file name %s' % html.escape(file, True)) @@ -797,15 +796,14 @@ def last_modified(self, ob): @security.protected(view_management_screens) def manage_get_sortedObjects(self, sortkey, revkey): - ''' - Return dictionaries used for the management page, sorted by sortkey - (which is 'id' or an attribute of the objects). The direction is - determined by rkey, which can be 'asc' for ascending or 'desc' for - descending. - It returns a list of dictionaries, with keys 'id' and 'obj', where 'id' - is the ID of the object as known by the parent and 'obj' is the child - object. - ''' + """Return dictionaries used for the management page, sorted by sortkey + (which is 'id' or an attribute of the objects). + + The direction is determined by rkey, which can be 'asc' for + ascending or 'desc' for descending. It returns a list of + dictionaries, with keys 'id' and 'obj', where 'id' is the ID of + the object as known by the parent and 'obj' is the child object. + """ if sortkey not in ['position', 'title', 'meta_type', 'get_size', '_p_mtime']: sortkey = 'id' @@ -848,7 +846,7 @@ def manage_get_sortedObjects(self, sortkey, revkey): @security.protected(view_management_screens) def getBookmarkableURLs(self): - """ Helper method to expose a configuration flag """ + """Helper method to expose a configuration flag.""" return getattr(CONFIG, 'zmi_bookmarkable_urls', True) # Don't InitializeClass, there is a specific __class_init__ on ObjectManager @@ -856,9 +854,8 @@ def getBookmarkableURLs(self): def findChildren(obj, dirname=''): - """ recursive walk through the object hierarchy to - find all children of an object (ajung) - """ + """Recursive walk through the object hierarchy to find all children of an + object (ajung)""" lst = [] for name, child in obj.objectItems(): diff --git a/src/OFS/OrderSupport.py b/src/OFS/OrderSupport.py index 27c3734141..82d1201c40 100644 --- a/src/OFS/OrderSupport.py +++ b/src/OFS/OrderSupport.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -""" Order support for 'Object Manager'. -""" +"""Order support for 'Object Manager'.""" from AccessControl.class_init import InitializeClass from AccessControl.Permissions import access_contents_information @@ -26,13 +25,12 @@ @implementer(IOrderedContainer) class OrderSupport: + """Ordered container mixin class. - """ Ordered container mixin class. - - This is an extension to the regular ObjectManager. It saves the objects in - order and lets you change the order of the contained objects. This is - particular helpful, if the order does not depend on object attributes, but - is totally user-specific. + This is an extension to the regular ObjectManager. It saves the + objects in order and lets you change the order of the contained + objects. This is particular helpful, if the order does not depend on + object attributes, but is totally user-specific. """ security = ClassSecurityInfo() @@ -49,8 +47,7 @@ class OrderSupport: @security.protected(manage_properties) def manage_move_objects_up(self, REQUEST, ids=None, delta=1): - """ Move specified sub-objects up by delta in container. - """ + """Move specified sub-objects up by delta in container.""" if ids: try: attempt = self.moveObjectsUp(ids, delta) @@ -68,8 +65,7 @@ def manage_move_objects_up(self, REQUEST, ids=None, delta=1): @security.protected(manage_properties) def manage_move_objects_down(self, REQUEST, ids=None, delta=1): - """ Move specified sub-objects down by delta in container. - """ + """Move specified sub-objects down by delta in container.""" if ids: try: attempt = self.moveObjectsDown(ids, delta) @@ -87,8 +83,7 @@ def manage_move_objects_down(self, REQUEST, ids=None, delta=1): @security.protected(manage_properties) def manage_move_objects_to_top(self, REQUEST, ids=None): - """ Move specified sub-objects to top of container. - """ + """Move specified sub-objects to top of container.""" if ids: try: attempt = self.moveObjectsToTop(ids) @@ -103,8 +98,7 @@ def manage_move_objects_to_top(self, REQUEST, ids=None): @security.protected(manage_properties) def manage_move_objects_to_bottom(self, REQUEST, ids=None): - """ Move specified sub-objects to bottom of container. - """ + """Move specified sub-objects to bottom of container.""" if ids: try: attempt = self.moveObjectsToBottom(ids) @@ -119,7 +113,7 @@ def manage_move_objects_to_bottom(self, REQUEST, ids=None): @security.protected(manage_properties) def manage_set_default_sorting(self, REQUEST, key, reverse): - """ Set default sorting key and direction.""" + """Set default sorting key and direction.""" self.setDefaultSorting(key, reverse) return self.manage_main(self, REQUEST) @@ -238,8 +232,7 @@ def setDefaultSorting(self, key, reverse): self._default_sort_reverse = reverse and 1 or 0 def manage_renameObject(self, id, new_id, REQUEST=None): - """ Rename a particular sub-object without changing its position. - """ + """Rename a particular sub-object without changing its position.""" old_position = self.getObjectPosition(id) result = super().manage_renameObject(id, new_id, REQUEST) self.moveObjectToPosition( diff --git a/src/OFS/OrderedFolder.py b/src/OFS/OrderedFolder.py index 8cb75db5ff..b19a8246dd 100644 --- a/src/OFS/OrderedFolder.py +++ b/src/OFS/OrderedFolder.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -""" 'Folder' with order support. -""" +"""'Folder' with order support.""" from App.special_dtml import DTMLFile from OFS.Folder import Folder @@ -25,8 +24,7 @@ def manage_addOrderedFolder(self, id, title='', createPublic=0, createUserF=0, REQUEST=None): - """Add a new ordered Folder object with id *id*. - """ + """Add a new ordered Folder object with id *id*.""" ob = OrderedFolder(id) ob.title = title self._setObject(id, ob) @@ -37,9 +35,7 @@ def manage_addOrderedFolder(self, id, title='', createPublic=0, createUserF=0, @implementer(IOrderedFolder) class OrderedFolder(OrderSupport, Folder): - - """ Extends the default Folder by order support. - """ + """Extends the default Folder by order support.""" meta_type = 'Folder (Ordered)' zmi_icon = 'far fa-folder zmi-icon-folder-ordered' diff --git a/src/OFS/PropertyManager.py b/src/OFS/PropertyManager.py index 6f6895b158..45470f2af7 100644 --- a/src/OFS/PropertyManager.py +++ b/src/OFS/PropertyManager.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Property management -""" +"""Property management.""" import html @@ -32,10 +31,9 @@ @implementer(IPropertyManager) class PropertyManager(Base): - """ - The PropertyManager mixin class provides an object with - transparent property management. An object which wants to - have properties should inherit from PropertyManager. + """The PropertyManager mixin class provides an object with transparent + property management. An object which wants to have properties should + inherit from PropertyManager. An object may specify that it has one or more predefined properties, by specifying an _properties structure in its @@ -148,8 +146,8 @@ def hasProperty(self, id): def getProperty(self, id, d=None): """Get the property 'id'. - Returns the optional second argument or None if no such property is - found. + Returns the optional second argument or None if no such property + is found. """ if self.hasProperty(id): return getattr(self, id) @@ -252,8 +250,7 @@ def propertyMap(self): @security.protected(access_contents_information) def propertyLabel(self, id): - """Return a label for the given property id - """ + """Return a label for the given property id.""" for p in self._properties: if p['id'] == id: return p.get('label', id) @@ -261,8 +258,7 @@ def propertyLabel(self, id): @security.protected(access_contents_information) def propertyDescription(self, id): - """Return a description for the given property id - """ + """Return a description for the given property id.""" for p in self._properties: if p['id'] == id: return p.get('description', '') @@ -292,8 +288,8 @@ def manage_editProperties(self, REQUEST): """Edit object properties via the web. The purpose of this method is to change all property values, - even those not listed in REQUEST; otherwise checkboxes that - get turned off will be ignored. Use manage_changeProperties() + even those not listed in REQUEST; otherwise checkboxes that get + turned off will be ignored. Use manage_changeProperties() instead for most situations. """ for prop in self._propertyMap(): diff --git a/src/OFS/PropertySheets.py b/src/OFS/PropertySheets.py index a0b0b26f5e..0e6acde2f2 100644 --- a/src/OFS/PropertySheets.py +++ b/src/OFS/PropertySheets.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Property sheets -""" +"""Property sheets.""" import html @@ -44,23 +43,21 @@ def v_self(self): class View(Tabs, Base): - """A view of an object, typically used for management purposes + """A view of an object, typically used for management purposes. - This class provides bits of management framework needed by propertysheets - to be used as a view on an object. + This class provides bits of management framework needed by + propertysheets to be used as a view on an object. """ def manage_workspace(self, URL1, RESPONSE): - '''Implement a "management" interface - ''' + """Implement a "management" interface.""" RESPONSE.redirect(URL1 + '/manage') def tpURL(self): return self.getId() def manage_options(self): - """Return a manage option data structure for me instance - """ + """Return a manage option data structure for me instance.""" try: request = self.REQUEST except Exception: @@ -107,8 +104,11 @@ def meta_type(self): class PropertySheet(Traversable, Persistent, Implicit, DAVPropertySheetMixin): """A PropertySheet is a container for a set of related properties and - metadata describing those properties. PropertySheets may or may not - provide a web interface for managing its properties.""" + metadata describing those properties. + + PropertySheets may or may not provide a web interface for managing + its properties. + """ _properties = () _extensible = 1 @@ -143,8 +143,8 @@ def getId(self): @security.protected(access_contents_information) def xml_namespace(self): - """Return a namespace string usable as an xml namespace - for this property set.""" + """Return a namespace string usable as an xml namespace for this + property set.""" return self._md.get('xmlns', '') def v_self(self): @@ -329,8 +329,10 @@ def manage_propertiesForm(self, URL1, RESPONSE): @security.protected(manage_properties) def manage_addProperty(self, id, value, type, REQUEST=None): - """Add a new property via the web. Sets a new property with - the given id, type, and value.""" + """Add a new property via the web. + + Sets a new property with the given id, type, and value. + """ if type in type_converters: value = type_converters[type](value) self._setProperty(id, value, type) @@ -408,8 +410,8 @@ class DefaultProperties(Virtual, PropertySheet, View): class PropertySheets(Traversable, Implicit, Tabs): - """A tricky container to keep property sets from polluting - an object's direct attribute namespace.""" + """A tricky container to keep property sets from polluting an object's + direct attribute namespace.""" id = 'propertysheets' @@ -468,7 +470,7 @@ def get(self, name, default=None): @security.protected(manage_properties) def manage_addPropertySheet(self, id, ns, REQUEST=None): - """ """ + """""" md = {'xmlns': ns} ps = self.PropertySheetClass(id, md) self.addPropertySheet(ps) @@ -492,9 +494,12 @@ def delPropertySheet(self, name): aq_parent(self).__propsets__ = tuple(result) def isDeletable(self, name): - '''currently, we say that *name* is deletable when it is not a - default sheet. Later, we may further restrict deletability - based on an instance attribute.''' + """Currently, we say that *name* is deletable when it is not a default + sheet. + + Later, we may further restrict deletability based on an instance + attribute. + """ ps = self.get(name) if ps is None: return 0 @@ -503,7 +508,7 @@ def isDeletable(self, name): return 1 def manage_delPropertySheets(self, ids=(), REQUEST=None): - '''delete all sheets identified by *ids*.''' + """Delete all sheets identified by *ids*.""" for id in ids: if not self.isDeletable(id): raise BadRequest( @@ -522,8 +527,7 @@ def getId(self): manage = DTMLFile('dtml/propertysheets', globals()) def manage_options(self): - """Return a manage option data structure for me instance - """ + """Return a manage option data structure for me instance.""" try: request = self.REQUEST except Exception: @@ -555,9 +559,9 @@ def tabs_path_info(self, script, path): class DefaultPropertySheets(PropertySheets): - """A PropertySheets container that contains a default property - sheet for compatibility with the arbitrary property mgmt - design of Zope PropertyManagers.""" + """A PropertySheets container that contains a default property sheet for + compatibility with the arbitrary property mgmt design of Zope + PropertyManagers.""" default = DefaultProperties() webdav = DAVProperties() @@ -570,7 +574,7 @@ def _get_defaults(self): class vps(Base): - """Virtual Propertysheets + """Virtual Propertysheets. The vps object implements a "computed attribute" - it ensures that a PropertySheets instance is returned when the propertysheets diff --git a/src/OFS/SimpleItem.py b/src/OFS/SimpleItem.py index 525dac24a1..f09c26cd6b 100644 --- a/src/OFS/SimpleItem.py +++ b/src/OFS/SimpleItem.py @@ -10,9 +10,9 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""This module implements a simple item mix-in for objects that have a -very simple (e.g. one-screen) management interface, like documents, -Aqueduct database adapters, etc. +"""This module implements a simple item mix-in for objects that have a very +simple (e.g. one-screen) management interface, like documents, Aqueduct +database adapters, etc. This module can also be used as a simple template for implementing new item types. @@ -132,8 +132,8 @@ def manage_afterClone(self, item): def getId(self): """Return the id of the object as a string. - This method should be used in preference to accessing an id attribute - of an object directly. The getId method is public. + This method should be used in preference to accessing an id + attribute of an object directly. The getId method is public. """ name = self.id if name is not None: @@ -159,8 +159,7 @@ def getId(self): __allow_access_to_unprotected_subobjects__ = 1 def title_or_id(self): - """Return the title if it is not blank and the id otherwise. - """ + """Return the title if it is not blank and the id otherwise.""" title = self.title if callable(title): title = title() @@ -178,7 +177,7 @@ def title_and_id(self): title = title() id = self.getId() # Make sure we don't blindly concatenate encoded and unencoded data - if title and type(id) is not type(title): + if title and not isinstance(id, type(title)): if isinstance(id, bytes): id = id.decode(default_encoding) if isinstance(title, bytes): @@ -304,8 +303,7 @@ def raise_standardErrorMessage( tb = None def manage(self, URL1): - """ - """ + """""" raise Redirect("%s/manage_main" % URL1) # This keeps simple items from acquiring their parents @@ -319,8 +317,11 @@ def __len__(self): @security.protected(access_contents_information) def getParentNode(self): - """The parent of this node. All nodes except Document - DocumentFragment and Attr may have a parent""" + """The parent of this node. + + All nodes except Document DocumentFragment and Attr may have a + parent + """ return getattr(self, '__parent__', None) @@ -329,11 +330,10 @@ def getParentNode(self): @implementer(IItemWithName) class Item_w__name__(Item): - """Mixin class to support common name/id functions""" + """Mixin class to support common name/id functions.""" def getId(self): - """Return the id of the object as a string. - """ + """Return the id of the object as a string.""" return self.__name__ # Alias (deprecated) `id` to `getId()` (but avoid recursion) @@ -341,8 +341,7 @@ def getId(self): lambda self: self.getId() if "__name__" in self.__dict__ else "") def title_or_id(self): - """Return the title if it is not blank and the id otherwise. - """ + """Return the title if it is not blank and the id otherwise.""" return self.title or self.__name__ def title_and_id(self): @@ -384,8 +383,7 @@ class SimpleItem( Implicit, RoleManager, ): - """Mix-in class combining the most common set of basic mix-ins - """ + """Mix-in class combining the most common set of basic mix-ins.""" security = ClassSecurityInfo() security.setPermissionDefault(View, ('Manager',)) diff --git a/src/OFS/Traversable.py b/src/OFS/Traversable.py index b46cd237e6..ba4eca11bb 100644 --- a/src/OFS/Traversable.py +++ b/src/OFS/Traversable.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""This module implements a mix-in for traversable objects. -""" +"""This module implements a mix-in for traversable objects.""" from urllib.parse import quote @@ -51,18 +50,18 @@ class Traversable: def absolute_url(self, relative=0): """Return the absolute URL of the object. - This a canonical URL based on the object's physical - containment path. It is affected by the virtual host - configuration, if any, and can be used by external - agents, such as a browser, to address the object. + This a canonical URL based on the object's physical containment + path. It is affected by the virtual host configuration, if any, + and can be used by external agents, such as a browser, to + address the object. If the relative argument is provided, with a true value, then the value of virtual_url_path() is returned. Some Products incorrectly use '/'+absolute_url(1) as an - absolute-path reference. This breaks in certain virtual - hosting situations, and should be changed to use - absolute_url_path() instead. + absolute-path reference. This breaks in certain virtual hosting + situations, and should be changed to use absolute_url_path() + instead. """ if relative: return self.virtual_url_path() diff --git a/src/OFS/Uninstalled.py b/src/OFS/Uninstalled.py index c5e9f3132e..3afec8a743 100644 --- a/src/OFS/Uninstalled.py +++ b/src/OFS/Uninstalled.py @@ -10,9 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -""" -Objects for packages that have been uninstalled. -""" +"""Objects for packages that have been uninstalled.""" import html from _thread import allocate_lock from logging import getLogger diff --git a/src/OFS/__init__.py b/src/OFS/__init__.py index 94521452c9..f008b1737c 100644 --- a/src/OFS/__init__.py +++ b/src/OFS/__init__.py @@ -1,7 +1,6 @@ zodbupdate_decode_dict = { 'OFS.Image File data': 'binary', 'OFS.Image Image data': 'binary', - 'OFS.Application Application title': 'utf-8', 'OFS.DTMLDocument DTMLDocument title': 'utf-8', 'OFS.DTMLMethod DTMLMethod title': 'utf-8', diff --git a/src/OFS/absoluteurl.py b/src/OFS/absoluteurl.py index d35ae361e4..543411ef32 100644 --- a/src/OFS/absoluteurl.py +++ b/src/OFS/absoluteurl.py @@ -26,12 +26,12 @@ @implementer(IAbsoluteURL) class AbsoluteURL(BrowserView): - """An absolute_url adapter for generic objects in Zope 2 that - aren't OFS.Traversable (e.g. views, resources, etc.). + """An absolute_url adapter for generic objects in Zope 2 that aren't + OFS.Traversable (e.g. views, resources, etc.). This is very close to the generic implementation from - zope.traversing.browser, but the Zope 2 request doesn't support - all the methods that it uses yet. + zope.traversing.browser, but the Zope 2 request doesn't support all + the methods that it uses yet. """ def __str__(self): @@ -86,8 +86,7 @@ def breadcrumbs(self): @implementer(IAbsoluteURL) class OFSTraversableAbsoluteURL(BrowserView): - """An absolute_url adapter for OFS.Traversable subclasses - """ + """An absolute_url adapter for OFS.Traversable subclasses.""" def __str__(self): return self.context.absolute_url() @@ -122,8 +121,8 @@ def _isVirtualHostRoot(self): class RootAbsoluteURL(OFSTraversableAbsoluteURL): - """An absolute_url adapter for the root object (OFS.Application) - """ + """An absolute_url adapter for the root object (OFS.Application)""" + def breadcrumbs(self): context = self.context diff --git a/src/OFS/browser/__init__.py b/src/OFS/browser/__init__.py index 3727bcca6c..29439ff88f 100644 --- a/src/OFS/browser/__init__.py +++ b/src/OFS/browser/__init__.py @@ -20,7 +20,7 @@ class StandardErrorMessageView(BrowserView): - """ View rendered on SiteError. + """View rendered on SiteError. Requires a callable object named ``standard_error_message`` on the published object's acquisition path. The callable can be a DTML Method, diff --git a/src/OFS/event.py b/src/OFS/event.py index 9e5dc2d34a..dc0fa685dd 100644 --- a/src/OFS/event.py +++ b/src/OFS/event.py @@ -11,9 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -""" -OFS event definitions. -""" +"""OFS event definitions.""" import OFS.interfaces from zope.interface import implementer @@ -22,7 +20,6 @@ @implementer(OFS.interfaces.IObjectWillBeMovedEvent) class ObjectWillBeMovedEvent(ObjectEvent): - """An object will be moved.""" def __init__(self, object, oldParent, oldName, newParent, newName): @@ -35,7 +32,6 @@ def __init__(self, object, oldParent, oldName, newParent, newName): @implementer(OFS.interfaces.IObjectWillBeAddedEvent) class ObjectWillBeAddedEvent(ObjectWillBeMovedEvent): - """An object will be added to a container.""" def __init__(self, object, newParent=None, newName=None): @@ -45,7 +41,6 @@ def __init__(self, object, newParent=None, newName=None): @implementer(OFS.interfaces.IObjectWillBeRemovedEvent) class ObjectWillBeRemovedEvent(ObjectWillBeMovedEvent): - """An object will be removed from a container.""" def __init__(self, object, oldParent=None, oldName=None): @@ -55,5 +50,4 @@ def __init__(self, object, oldParent=None, oldName=None): @implementer(OFS.interfaces.IObjectClonedEvent) class ObjectClonedEvent(ObjectEvent): - """An object has been cloned into a container.""" diff --git a/src/OFS/interfaces.py b/src/OFS/interfaces.py index 921aa3bb80..2b0bc91fa4 100644 --- a/src/OFS/interfaces.py +++ b/src/OFS/interfaces.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""OFS interfaces. -""" +"""OFS interfaces.""" from AccessControl.interfaces import IOwned from AccessControl.interfaces import IRoleManager @@ -30,15 +29,14 @@ class IOrderedContainer(Interface): - - """ Ordered Container interface. + """Ordered Container interface. This interface provides a common mechanism for maintaining ordered collections. """ def moveObjectsByDelta(ids, delta, subset_ids=None): - """ Move specified sub-objects by delta. + """Move specified sub-objects by delta. If delta is higher than the possible maximum, objects will be moved to the bottom. If delta is lower than the possible minimum, objects will @@ -60,7 +58,7 @@ def moveObjectsByDelta(ids, delta, subset_ids=None): """ def moveObjectsUp(ids, delta=1, subset_ids=None): - """ Move specified sub-objects up by delta in container. + """Move specified sub-objects up by delta in container. If no delta is specified, delta is 1. See moveObjectsByDelta for more details. @@ -71,7 +69,7 @@ def moveObjectsUp(ids, delta=1, subset_ids=None): """ def moveObjectsDown(ids, delta=1, subset_ids=None): - """ Move specified sub-objects down by delta in container. + """Move specified sub-objects down by delta in container. If no delta is specified, delta is 1. See moveObjectsByDelta for more details. @@ -82,7 +80,7 @@ def moveObjectsDown(ids, delta=1, subset_ids=None): """ def moveObjectsToTop(ids, subset_ids=None): - """ Move specified sub-objects to top of container. + """Move specified sub-objects to top of container. See moveObjectsByDelta for more details. @@ -92,7 +90,7 @@ def moveObjectsToTop(ids, subset_ids=None): """ def moveObjectsToBottom(ids, subset_ids=None): - """ Move specified sub-objects to bottom of container. + """Move specified sub-objects to bottom of container. See moveObjectsByDelta for more details. @@ -102,7 +100,7 @@ def moveObjectsToBottom(ids, subset_ids=None): """ def orderObjects(key, reverse=None): - """ Order sub-objects by key and direction. + """Order sub-objects by key and direction. Permission -- Manage properties @@ -110,7 +108,7 @@ def orderObjects(key, reverse=None): """ def getObjectPosition(id): - """ Get the position of an object by its id. + """Get the position of an object by its id. Permission -- Access contents information @@ -118,7 +116,7 @@ def getObjectPosition(id): """ def moveObjectToPosition(id, position): - """ Move specified object to absolute position. + """Move specified object to absolute position. Permission -- Manage properties @@ -130,7 +128,6 @@ def moveObjectToPosition(id, position): # not synced with ZopeBook API Reference; # based on OFS.CopySupport.CopySource class ICopySource(Interface): - """Interface for objects which allow themselves to be copied.""" def _canCopy(op=0): @@ -142,34 +139,36 @@ def _canCopy(op=0): def _notifyOfCopyTo(container, op=0): """Overide this to be pickly about where you go! - If you dont want to go there, raise an exception. The op variable is 0 - for a copy, 1 for a move. + If you dont want to go there, raise an exception. The op + variable is 0 for a copy, 1 for a move. """ def _getCopy(container): - """ - """ + """""" def _postCopy(container, op=0): """Called after the copy is finished to accomodate special cases. + The op var is 0 for a copy, 1 for a move. """ def _setId(id): - """Called to set the new id of a copied object. - """ + """Called to set the new id of a copied object.""" def cb_isCopyable(): - """Is object copyable? Returns 0 or 1 + """Is object copyable? + + Returns 0 or 1 """ def cb_isMoveable(): - """Is object moveable? Returns 0 or 1 + """Is object moveable? + + Returns 0 or 1 """ def cb_userHasCopyOrMovePermission(): - """ - """ + """""" # XXX: might contain non-API methods and outdated comments; @@ -180,18 +179,18 @@ class ITraversable(Interface): def absolute_url(relative=0): """Return the absolute URL of the object. - This a canonical URL based on the object's physical - containment path. It is affected by the virtual host - configuration, if any, and can be used by external - agents, such as a browser, to address the object. + This a canonical URL based on the object's physical containment + path. It is affected by the virtual host configuration, if any, + and can be used by external agents, such as a browser, to + address the object. If the relative argument is provided, with a true value, then the value of virtual_url_path() is returned. Some Products incorrectly use '/'+absolute_url(1) as an - absolute-path reference. This breaks in certain virtual - hosting situations, and should be changed to use - absolute_url_path() instead. + absolute-path reference. This breaks in certain virtual hosting + situations, and should be changed to use absolute_url_path() + instead. """ def absolute_url_path(): @@ -212,10 +211,10 @@ def virtual_url_path(): def getPhysicalPath(): """Get the physical path of the object. - Returns a path (an immutable sequence of strings) that can be used to - access this object again later, for example in a copy/paste operation. - getPhysicalRoot() and getPhysicalPath() are designed to operate - together. + Returns a path (an immutable sequence of strings) that can be + used to access this object again later, for example in a + copy/paste operation. getPhysicalRoot() and getPhysicalPath() + are designed to operate together. """ def unrestrictedTraverse(path, default=None, restricted=0): @@ -239,8 +238,7 @@ def unrestrictedTraverse(path, default=None, restricted=0): """ def restrictedTraverse(path, default=None): - """Trusted code traversal code, always enforces security. - """ + """Trusted code traversal code, always enforces security.""" # XXX: might contain non-API methods and outdated comments; @@ -263,40 +261,35 @@ class IZopeObject(Interface): # not synced with ZopeBook API Reference; # based on OFS.SimpleItem.Item and App.Management.Tabs class IManageable(Interface): - - """Something that is manageable in the ZMI""" + """Something that is manageable in the ZMI.""" manage_tabs = Attribute("""Management tabs""") manage_options = Tuple(title="Manage options") def manage(URL1): - """Show management screen""" + """Show management screen.""" def manage_afterAdd(item, container): - """Gets called after being added to a container""" + """Gets called after being added to a container.""" def manage_beforeDelete(item, container): - """Gets called before being deleted""" + """Gets called before being deleted.""" def manage_afterClone(item): - """Gets called after being cloned""" + """Gets called after being cloned.""" def filtered_manage_options(REQUEST=None): - """ - """ + """""" def manage_workspace(REQUEST): - """Dispatch to first interface in manage_options - """ + """Dispatch to first interface in manage_options.""" def tabs_path_default(REQUEST): - """ - """ + """""" def tabs_path_info(script, path): - """ - """ + """""" class IWriteLock(Interface): @@ -331,38 +324,47 @@ class IWriteLock(Interface): """ def wl_lockItems(killinvalids=0): - """ Returns (key, value) pairs of locktoken, lock. + """Returns (key, value) pairs of locktoken, lock. if 'killinvalids' is true, invalid locks (locks whose timeout - has been exceeded) will be deleted""" + has been exceeded) will be deleted + """ def wl_lockValues(killinvalids=0): - """ Returns a sequence of locks. if 'killinvalids' is true, - invalid locks will be deleted""" + """Returns a sequence of locks. + + if 'killinvalids' is true, invalid locks will be deleted + """ def wl_lockTokens(killinvalids=0): - """ Returns a sequence of lock tokens. if 'killinvalids' is true, - invalid locks will be deleted""" + """Returns a sequence of lock tokens. + + if 'killinvalids' is true, invalid locks will be deleted + """ def wl_hasLock(token, killinvalids=0): - """ Returns true if the lock identified by the token is attached - to the object. """ + """Returns true if the lock identified by the token is attached to the + object.""" def wl_isLocked(): - """ Returns true if 'self' is locked at all. If invalid locks - still exist, they should be deleted.""" + """Returns true if 'self' is locked at all. + + If invalid locks still exist, they should be deleted. + """ def wl_setLock(locktoken, lock): - """ Store the LockItem, 'lock'. The locktoken will be used to fetch - and delete the lock. If the lock exists, this MUST - overwrite it if all of the values except for the 'timeout' on the - old and new lock are the same. """ + """Store the LockItem, 'lock'. + + The locktoken will be used to fetch and delete the lock. If the + lock exists, this MUST overwrite it if all of the values except + for the 'timeout' on the old and new lock are the same. + """ def wl_getLock(locktoken): - """ Returns the locktoken identified by the locktokenuri """ + """Returns the locktoken identified by the locktokenuri.""" def wl_delLock(locktoken): - """ Deletes the locktoken identified by the locktokenuri """ + """Deletes the locktoken identified by the locktokenuri.""" def wl_clearLocks(): """ Deletes ALL locks on the object - should only be called @@ -370,7 +372,6 @@ def wl_clearLocks(): class ILockItem(Interface): - """A LockItem contains information about a lock. This includes: @@ -388,14 +389,12 @@ class ILockItem(Interface): o Modified time (for calculating timeouts) o LockType (only EXCLUSIVE is supported right now) - """ # XXX: WAAAA! What is a ctor doing in the interface? def __init__(creator, owner, depth=0, timeout='Infinity', locktype='write', lockscope='exclusive', token=None): - """\ - If any of the following are untrue, a **ValueError** exception + """\\ If any of the following are untrue, a **ValueError** exception will be raised. - **creator** MUST be a Zope user object or string to find a @@ -426,54 +425,61 @@ def __init__(creator, owner, depth=0, timeout='Infinity', """ def getCreator(): - """ Returns the Zope user who created the lock. This is returned - in a tuple containing the Users ID and the path to the user folder - they came from.""" + """Returns the Zope user who created the lock. + + This is returned in a tuple containing the Users ID and the path + to the user folder they came from. + """ def getCreatorPath(): - """ Returns a string of the path to the user object in the user - folder they were found in. """ + """Returns a string of the path to the user object in the user folder + they were found in.""" def getOwner(): - """ Returns the string value of the 'owner' property sent - in by WebDAV """ + """Returns the string value of the 'owner' property sent in by + WebDAV.""" def getLockToken(): - """ returns the opaque lock token """ + """Returns the opaque lock token.""" def getDepth(): - """ returns the depth of the lock """ + """Returns the depth of the lock.""" def getTimeout(): - """ returns an integer value of the timeout setting """ + """Returns an integer value of the timeout setting.""" def getTimeoutString(): """ returns the timeout value in a form acceptable by WebDAV (ie - 'Seconds-40800') """ def setTimeout(newtimeout): - """ refreshes the timeout information """ + """Refreshes the timeout information.""" def getModifiedTime(): - """ returns a time.time value of the last time the Lock was - modified. From RFC 2518: + """Returns a time.time value of the last time the Lock was modified. + From RFC 2518: - The timeout counter SHOULD be restarted any time an owner of the - lock sends a method to any member of the lock, including unsupported - methods or methods which are unsucscessful. The lock MUST be - refreshed if a refresh LOCK method is successfully received. + The timeout counter SHOULD be restarted any time an owner of the + lock sends a method to any member of the lock, including + unsupported methods or methods which are unsucscessful. The + lock MUST be refreshed if a refresh LOCK method is successfully + received. - The modified time is used to calculate the refreshed value """ + The modified time is used to calculate the refreshed value + """ def refresh(): - """ Tickles the locks modified time by setting it to the current - time.time() value. (As stated in the RFC, the timeout counter - SHOULD be restarted for any HTTP method called by the lock owner - on the locked object). """ + """Tickles the locks modified time by setting it to the current + time.time() value. + + (As stated in the RFC, the timeout counter SHOULD be restarted + for any HTTP method called by the lock owner on the locked + object). + """ def isValid(): - """ Returns true if (self.getModifiedTime() + self.getTimeout()) - is greater than the current time.time() value. """ + """Returns true if (self.getModifiedTime() + self.getTimeout()) is + greater than the current time.time() value.""" # now = time.time() # modified = self.getModifiedTime() # timeout = self.getTimeout() @@ -481,19 +487,21 @@ def isValid(): # return (modified + timeout > now) # there's time remaining def getLockType(): - """ returns the lock type ('write') """ + """Returns the lock type ('write')""" def getLockScope(): - """ returns the lock scope ('exclusive') """ + """Returns the lock scope ('exclusive')""" def asLockDiscoveryProperty(ns='d'): - """ Return the lock rendered as an XML representation of a - WebDAV 'lockdiscovery' property. 'ns' is the namespace identifier - used on the XML elements.""" + """Return the lock rendered as an XML representation of a WebDAV + 'lockdiscovery' property. + + 'ns' is the namespace identifier used on the XML elements. + """ def asXML(): - """ Render a full XML representation of a lock for WebDAV, - used when returning the value of a newly created lock. """ + """Render a full XML representation of a lock for WebDAV, used when + returning the value of a newly created lock.""" # XXX: might contain non-API methods and outdated comments; @@ -514,8 +522,7 @@ def getId(): """ def title_or_id(): - """Return the title if it is not blank and the id otherwise. - """ + """Return the title if it is not blank and the id otherwise.""" def title_and_id(): """Return the title if it is not blank and the id otherwise. @@ -524,113 +531,96 @@ def title_and_id(): """ def manage_editedDialog(REQUEST, **args): - """Show an 'edited' dialog. - """ + """Show an 'edited' dialog.""" def raise_standardErrorMessage(client=None, REQUEST={}, error_type=None, error_value=None, tb=None, error_tb=None, error_message='', tagSearch=None, error_log_url=''): - """Raise standard error message. - """ + """Raise standard error message.""" # XXX: based on OFS.SimpleItem.Item_w__name__ class IItemWithName(IItem): - - """Item with name. - """ + """Item with name.""" # XXX: based on OFS.SimpleItem.SimpleItem class ISimpleItem(IItem, IPersistent, IAcquirer, IRoleManager): - - """Not-so-simple item. - """ + """Not-so-simple item.""" # XXX: might contain non-API methods and outdated comments; # not synced with ZopeBook API Reference; # based on OFS.CopySupport.CopyContainer class ICopyContainer(Interface): - - """Interface for containerish objects which allow cut/copy/paste""" + """Interface for containerish objects which allow cut/copy/paste.""" # The following three methods should be overridden to store sub-objects # as non-attributes. def _setOb(id, object): - """ - """ + """""" def _delOb(id): - """ - """ + """""" def _getOb(id, default=None): - """ - """ + """""" def manage_CopyContainerFirstItem(REQUEST): - """ - """ + """""" def manage_CopyContainerAllItems(REQUEST): - """ - """ + """""" def manage_cutObjects(ids=None, REQUEST=None): - """Put a reference to the objects named in ids in the clip board""" + """Put a reference to the objects named in ids in the clip board.""" def manage_copyObjects(ids=None, REQUEST=None, RESPONSE=None): - """Put a reference to the objects named in ids in the clip board""" + """Put a reference to the objects named in ids in the clip board.""" def _get_id(id): """Allow containers to override the generation of object copy id by - attempting to call its _get_id method, if it exists. - """ + attempting to call its _get_id method, if it exists.""" def manage_pasteObjects(cb_copy_data=None, REQUEST=None): """Paste previously copied objects into the current object. - If calling manage_pasteObjects from python code, pass the result of a - previous call to manage_cutObjects or manage_copyObjects as the first - argument. + If calling manage_pasteObjects from python code, pass the result + of a previous call to manage_cutObjects or manage_copyObjects as + the first argument. """ manage_renameForm = Attribute("""Rename management view""") def manage_renameObjects(ids=[], new_ids=[], REQUEST=None): - """Rename several sub-objects""" + """Rename several sub-objects.""" def manage_renameObject(id, new_id, REQUEST=None): - """Rename a particular sub-object""" + """Rename a particular sub-object.""" def manage_clone(ob, id, REQUEST=None): - """Clone an object, creating a new object with the given id. - """ + """Clone an object, creating a new object with the given id.""" def cb_dataValid(): - """Return true if clipboard data seems valid. - """ + """Return true if clipboard data seems valid.""" def cb_dataItems(): - """List of objects in the clip board. - """ + """List of objects in the clip board.""" def _verifyObjectPaste(object, validate_src=1): """Verify whether the current user is allowed to paste the passed - object into self. This is determined by checking to see if the - user could create a new object of the same meta_type of the - object passed in and checking that the user actually is - allowed to access the passed in object in its existing - context. + object into self. This is determined by checking to see if the user + could create a new object of the same meta_type of the object passed in + and checking that the user actually is allowed to access the passed in + object in its existing context. Passing a false value for the validate_src argument will skip checking the passed in object in its existing context. This is mainly useful for situations where the passed in object has no existing context, such as checking an object during an import - (the object will not yet have been connected to the - acquisition hierarchy). + (the object will not yet have been connected to the acquisition + hierarchy). """ @@ -640,10 +630,11 @@ def _verifyObjectPaste(object, validate_src=1): class IObjectManager(IZopeObject, ICopyContainer, INavigation, IManageable, IAcquirer, IPersistent, ITraversable, IPossibleSite, IContainer): - """Generic object manager + """Generic object manager. - This interface provides core behavior for collections of heterogeneous - objects.""" + This interface provides core behavior for collections of + heterogeneous objects. + """ meta_types = Tuple( title="Meta types", @@ -660,96 +651,83 @@ class IObjectManager(IZopeObject, ICopyContainer, INavigation, IManageable, manage_importExportForm = Attribute(""" """) def all_meta_types(interfaces=None): - """ - """ + """""" def _subobject_permissions(): - """ - """ + """""" def filtered_meta_types(user=None): """Return a list of the types for which the user has adequate - permission to add that type of object. - """ + permission to add that type of object.""" def _setOb(id, object): - """ - """ + """""" def _delOb(id): - """ - """ + """""" def _getOb(id, default=None): - """ - """ + """""" def _setObject(id, object, roles=None, user=None, set_owner=1): - """ - """ + """""" def _delObject(id, dp=1): - """ - """ + """""" def hasObject(id): - """Indicate whether the folder has an item by ID. - """ + """Indicate whether the folder has an item by ID.""" def objectIds(spec=None): """List the IDs of the subobjects of the current object. - If 'spec' is specified, returns only objects whose meta_types match - 'spec'. + If 'spec' is specified, returns only objects whose meta_types + match 'spec'. """ def objectValues(spec=None): """List the subobjects of the current object. - If 'spec' is specified, returns only objects whose meta_types match - 'spec'. + If 'spec' is specified, returns only objects whose meta_types + match 'spec'. """ def objectItems(spec=None): """List (ID, subobject) tuples for subobjects of the current object. - If 'spec' is specified, returns only objects whose meta_types match - 'spec'. + If 'spec' is specified, returns only objects whose meta_types + match 'spec'. """ def objectMap(): - """Return a tuple of mappings containing subobject meta-data. - """ + """Return a tuple of mappings containing subobject meta-data.""" def superValues(t): - """Return all of the objects of a given type located in this object - and containing objects. - """ + """Return all of the objects of a given type located in this object and + containing objects.""" def manage_delObjects(ids=[], REQUEST=None): - """Delete a subordinate object + """Delete a subordinate object. The objects specified in 'ids' get deleted. """ def tpValues(): - """Return a list of subobjects, used by tree tag. - """ + """Return a list of subobjects, used by tree tag.""" def manage_exportObject(id='', download=None, RESPONSE=None, REQUEST=None): """Exports an object to a file and returns that file.""" def manage_importObject(file, REQUEST=None, set_owner=1): - """Import an object from a file""" + """Import an object from a file.""" def _importObjectFromFile(filepath, verify=1, set_owner=1): - """ - """ + """""" class IFindSupport(Interface): - """Find support for Zope Folders""" + """Find support for Zope Folders.""" manage_findForm = Attribute(""" """) @@ -759,7 +737,7 @@ def ZopeFind(obj, obj_ids=None, obj_metatypes=None, obj_permission=None, obj_roles=None, search_sub=0, REQUEST=None, result=None, pre=''): - """Zope Find interface""" + """Zope Find interface.""" def ZopeFindAndApply(obj, obj_ids=None, obj_metatypes=None, obj_searchterm=None, obj_expr=None, @@ -768,18 +746,16 @@ def ZopeFindAndApply(obj, obj_ids=None, obj_metatypes=None, search_sub=0, REQUEST=None, result=None, pre='', apply_func=None, apply_path=''): - """Zope Find interface and apply""" + """Zope Find interface and apply.""" # XXX: might contain non-API methods and outdated comments; # not synced with ZopeBook API Reference; # based on OFS.PropertyManager.PropertyManager class IPropertyManager(Interface): - - """ - The PropertyManager mixin class provides an object with - transparent property management. An object which wants to - have properties should inherit from PropertyManager. + """The PropertyManager mixin class provides an object with transparent + property management. An object which wants to have properties should + inherit from PropertyManager. An object may specify that it has one or more predefined properties, by specifying an _properties structure in its @@ -848,18 +824,16 @@ class IPropertyManager(Interface): propertysheets = Attribute(" ") def valid_property_id(id): - """ - """ + """""" def hasProperty(id): - """Return true if object has a property 'id'. - """ + """Return true if object has a property 'id'.""" def getProperty(id, d=None): """Get the property 'id'. - Returns the optional second argument or None if no such property is - found. + Returns the optional second argument or None if no such property + is found. """ def getPropertyType(id): @@ -869,50 +843,42 @@ def getPropertyType(id): """ def _wrapperCheck(object): - """Raise an error if an object is wrapped. - """ + """Raise an error if an object is wrapped.""" def _setPropValue(id, value): - """ - """ + """""" def _delPropValue(id): - """ - """ + """""" def _setProperty(id, value, type='string'): """Set property. - For selection and multiple selection properties the value argument - indicates the select variable of the property. + For selection and multiple selection properties the value + argument indicates the select variable of the property. """ def _updateProperty(id, value): """Update the value of an existing property. - If value is a string, an attempt will be made to convert the value to - the type of the existing property. + If value is a string, an attempt will be made to convert the + value to the type of the existing property. """ def _delProperty(id): - """ - """ + """""" def propertyIds(): - """Return a list of property ids. - """ + """Return a list of property ids.""" def propertyValues(): - """Return a list of actual property objects. - """ + """Return a list of actual property objects.""" def propertyItems(): - """Return a list of (id,property) tuples. - """ + """Return a list of (id,property) tuples.""" def _propertyMap(): - """Return a tuple of mappings, giving meta-data for properties. - """ + """Return a tuple of mappings, giving meta-data for properties.""" def propertyMap(): """Return a tuple of mappings, giving meta-data for properties. @@ -921,12 +887,10 @@ def propertyMap(): """ def propertyLabel(id): - """Return a label for the given property id - """ + """Return a label for the given property id.""" def propdict(): - """ - """ + """""" # Web interface @@ -940,8 +904,8 @@ def manage_editProperties(REQUEST): """Edit object properties via the web. The purpose of this method is to change all property values, - even those not listed in REQUEST; otherwise checkboxes that - get turned off will be ignored. Use manage_changeProperties() + even those not listed in REQUEST; otherwise checkboxes that get + turned off will be ignored. Use manage_changeProperties() instead for most situations. """ @@ -953,7 +917,7 @@ def manage_changeProperties(REQUEST=None, **kw): """ def manage_changePropertyTypes(old_ids, props, REQUEST=None): - """Replace one set of properties with another + """Replace one set of properties with another. Delete all properties that have ids in old_ids, then add a property for each item in props. Each item has a new_id, @@ -967,25 +931,24 @@ def manage_delProperties(ids=None, REQUEST=None): class IFolder(IObjectManager, IPropertyManager, IRoleManager, IItem, IFindSupport): - """Folders are basic container objects that provide a standard - interface for object management. Folder objects also implement a - management interface and can have arbitrary properties. + """Folders are basic container objects that provide a standard interface + for object management. + + Folder objects also implement a management interface and can have + arbitrary properties. """ # XXX: based on OFS.OrderedFolder.OrderedFolder class IOrderedFolder(IOrderedContainer, IFolder): - - """Ordered folder. - """ + """Ordered folder.""" # XXX: might contain non-API methods and outdated comments; # not synced with ZopeBook API Reference; # based on OFS.Application.Application class IApplication(IFolder, IRoot): - - """Top-level system object""" + """Top-level system object.""" isTopLevelPrincipiaApplicationObject = Bool( title="Is top level application object", @@ -995,32 +958,27 @@ class IApplication(IFolder, IRoot): misc_ = Attribute("Misc.") def Redirect(destination, URL1): - """Utility function to allow user-controlled redirects""" + """Utility function to allow user-controlled redirects.""" ZopeRedirect = Redirect def __bobo_traverse__(REQUEST, name=None): - """Bobo traverse. - """ + """Bobo traverse.""" def ZopeTime(*args): - """Utility function to return current date/time""" + """Utility function to return current date/time.""" def absolute_url(relative=0): - """The absolute URL of the root object is BASE1 or "/". - """ + """The absolute URL of the root object is BASE1 or "/".""" def absolute_url_path(): - """The absolute URL path of the root object is BASEPATH1 or "/". - """ + """The absolute URL path of the root object is BASEPATH1 or "/".""" def virtual_url_path(): - """The virtual URL path of the root object is empty. - """ + """The virtual URL path of the root object is empty.""" def getPhysicalRoot(): - """ - """ + """""" ################################################## @@ -1039,7 +997,7 @@ class IObjectWillBeAddedEvent(IObjectWillBeMovedEvent): class IObjectWillBeRemovedEvent(IObjectWillBeMovedEvent): - """An object will be removed from a container""" + """An object will be removed from a container.""" class IObjectClonedEvent(IObjectEvent): diff --git a/src/OFS/metaconfigure.py b/src/OFS/metaconfigure.py index ba87573191..155dad378a 100644 --- a/src/OFS/metaconfigure.py +++ b/src/OFS/metaconfigure.py @@ -87,8 +87,7 @@ def package_initialized(module, init_func): def _registerPackage(module_, init_func=None): - """Registers the given python package as a Zope 2 style product - """ + """Registers the given python package as a Zope 2 style product.""" if not hasattr(module_, '__path__'): raise ValueError("Must be a package and the " "package must be filesystem based") @@ -105,8 +104,7 @@ def _registerPackage(module_, init_func=None): def registerPackage(_context, package, initialize=None): - """ZCML directive function for registering a python package product - """ + """ZCML directive function for registering a python package product.""" _context.action( discriminator=('registerPackage', package), diff --git a/src/OFS/metadirectives.py b/src/OFS/metadirectives.py index d74ec5ae56..278453e3dd 100644 --- a/src/OFS/metadirectives.py +++ b/src/OFS/metadirectives.py @@ -6,15 +6,14 @@ class IDeprecatedManageAddDeleteDirective(Interface): - """Call manage_afterAdd & co for these contained content classes. - """ + """Call manage_afterAdd & co for these contained content classes.""" class_ = GlobalObject( title="Class", required=True) class IRegisterClassDirective(Interface): - """registerClass directive schema. + """RegisterClass directive schema. Register content with Zope 2. """ @@ -57,8 +56,7 @@ class IRegisterClassDirective(Interface): class IRegisterPackageDirective(Interface): """Registers the given Python package which at a minimum fools zope2 into - thinking of it as a zope2 product. - """ + thinking of it as a zope2 product.""" package = GlobalObject( title='Target package', diff --git a/src/OFS/owner.py b/src/OFS/owner.py index 7c0b38a045..ad01c1ce47 100644 --- a/src/OFS/owner.py +++ b/src/OFS/owner.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Support for owned objects -""" +"""Support for owned objects.""" from urllib import parse @@ -51,7 +50,8 @@ class Owned(BaseOwned): def manage_takeOwnership(self, REQUEST, RESPONSE, recursive=0): """Take ownership (responsibility) for an object. - If 'recursive' is true, then also take ownership of all sub-objects. + If 'recursive' is true, then also take ownership of all sub- + objects. """ security = getSecurityManager() want_referer = REQUEST['URL1'] + '/manage_owner' diff --git a/src/OFS/role.py b/src/OFS/role.py index f8131308f1..260653daa5 100644 --- a/src/OFS/role.py +++ b/src/OFS/role.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Role manager -""" +"""Role manager.""" import html @@ -28,7 +27,7 @@ class RoleManager(BaseRoleManager): - """An object that has configurable permissions""" + """An object that has configurable permissions.""" security = ClassSecurityInfo() @@ -49,8 +48,7 @@ class RoleManager(BaseRoleManager): @security.protected(change_permissions) @requestmethod('POST') def manage_role(self, role_to_manage, permissions=[], REQUEST=None): - """Change the permissions given to the given role. - """ + """Change the permissions given to the given role.""" BaseRoleManager.manage_role( self, role_to_manage, permissions=permissions) if REQUEST is not None: @@ -66,8 +64,7 @@ def manage_role(self, role_to_manage, permissions=[], REQUEST=None): @security.protected(change_permissions) @requestmethod('POST') def manage_acquiredPermissions(self, permissions=[], REQUEST=None): - """Change the permissions that acquire. - """ + """Change the permissions that acquire.""" BaseRoleManager.manage_acquiredPermissions( self, permissions=permissions) if REQUEST is not None: @@ -91,9 +88,10 @@ def manage_permission( ): """Change the settings for the given permission. - If optional arg acquire is true, then the roles for the permission - are acquired, in addition to the ones specified, otherwise the - permissions are restricted to only the designated roles. + If optional arg acquire is true, then the roles for the + permission are acquired, in addition to the ones specified, + otherwise the permissions are restricted to only the designated + roles. """ BaseRoleManager.manage_permission( self, permission_to_manage, roles=roles, acquire=acquire) diff --git a/src/OFS/subscribers.py b/src/OFS/subscribers.py index 3c099a9660..7127d59818 100644 --- a/src/OFS/subscribers.py +++ b/src/OFS/subscribers.py @@ -11,9 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -""" -Subscriber definitions. -""" +"""Subscriber definitions.""" from logging import getLogger @@ -53,8 +51,7 @@ def compatibilityCall(method_name, *args): def maybeWarnDeprecated(ob, method_name): - """Send a warning if a method is deprecated. - """ + """Send a warning if a method is deprecated.""" if not deprecatedManageAddDeleteClasses: # Directives not fully loaded return @@ -72,8 +69,7 @@ def maybeWarnDeprecated(ob, method_name): @zope.interface.implementer(zope.location.interfaces.ISublocations) @zope.component.adapter(OFS.interfaces.IObjectManager) class ObjectManagerSublocations: - """Get the sublocations for an ObjectManager. - """ + """Get the sublocations for an ObjectManager.""" def __init__(self, container): self.container = container @@ -95,8 +91,7 @@ def sublocations(self): @zope.component.adapter(OFS.interfaces.IItem, OFS.interfaces.IObjectWillBeMovedEvent) def dispatchObjectWillBeMovedEvent(ob, event): - """Multi-subscriber for IItem + IObjectWillBeMovedEvent. - """ + """Multi-subscriber for IItem + IObjectWillBeMovedEvent.""" # First, dispatch to sublocations if OFS.interfaces.IObjectManager.providedBy(ob): dispatchToSublocations(ob, event) @@ -106,8 +101,7 @@ def dispatchObjectWillBeMovedEvent(ob, event): @zope.component.adapter(OFS.interfaces.IItem, IObjectMovedEvent) def dispatchObjectMovedEvent(ob, event): - """Multi-subscriber for IItem + IObjectMovedEvent. - """ + """Multi-subscriber for IItem + IObjectMovedEvent.""" # First, do the manage_afterAdd dance callManageAfterAdd(ob, event.object, event.newParent) # Next, dispatch to sublocations @@ -118,8 +112,7 @@ def dispatchObjectMovedEvent(ob, event): @zope.component.adapter(OFS.interfaces.IItem, OFS.interfaces.IObjectClonedEvent) def dispatchObjectClonedEvent(ob, event): - """Multi-subscriber for IItem + IObjectClonedEvent. - """ + """Multi-subscriber for IItem + IObjectClonedEvent.""" # First, do the manage_afterClone dance callManageAfterClone(ob, event.object) # Next, dispatch to sublocations @@ -129,16 +122,14 @@ def dispatchObjectClonedEvent(ob, event): @zope.component.adapter(OFS.interfaces.IItem, IObjectCopiedEvent) def dispatchObjectCopiedEvent(ob, event): - """Multi-subscriber for IItem + IObjectCopiedEvent. - """ + """Multi-subscriber for IItem + IObjectCopiedEvent.""" # Dispatch to sublocations if OFS.interfaces.IObjectManager.providedBy(ob): dispatchToSublocations(ob, event) def callManageAfterAdd(ob, item, container): - """Compatibility subscriber for manage_afterAdd. - """ + """Compatibility subscriber for manage_afterAdd.""" if container is None: return if getattr(aq_base(ob), 'manage_afterAdd', None) is None: @@ -148,8 +139,7 @@ def callManageAfterAdd(ob, item, container): def callManageBeforeDelete(ob, item, container): - """Compatibility subscriber for manage_beforeDelete. - """ + """Compatibility subscriber for manage_beforeDelete.""" if container is None: return if getattr(aq_base(ob), 'manage_beforeDelete', None) is None: @@ -171,8 +161,7 @@ def callManageBeforeDelete(ob, item, container): def callManageAfterClone(ob, item): - """Compatibility subscriber for manage_afterClone. - """ + """Compatibility subscriber for manage_afterClone.""" if getattr(aq_base(ob), 'manage_afterClone', None) is None: return maybeWarnDeprecated(ob, 'manage_afterClone') diff --git a/src/OFS/tests/applicationproduct/__init__.py b/src/OFS/tests/applicationproduct/__init__.py index 72368866ff..52ca8dec74 100644 --- a/src/OFS/tests/applicationproduct/__init__.py +++ b/src/OFS/tests/applicationproduct/__init__.py @@ -1,6 +1,8 @@ -""" This product uses the application during product initialization - to create a subfolder in the root folder. This is similar to what - Producs.Sessions and Products.TemporaryFolder are doing. +"""This product uses the application during product initialization to create a +subfolder in the root folder. + +This is similar to what Producs.Sessions and Products.TemporaryFolder +are doing. """ diff --git a/src/OFS/tests/testAppInitializer.py b/src/OFS/tests/testAppInitializer.py index c305793e71..01c256fc02 100644 --- a/src/OFS/tests/testAppInitializer.py +++ b/src/OFS/tests/testAppInitializer.py @@ -45,7 +45,7 @@ def getApp(): class TestInitialization(unittest.TestCase): - """ Test the application initializer object """ + """Test the application initializer object.""" def setUp(self): global original_config diff --git a/src/OFS/tests/testCopySupport.py b/src/OFS/tests/testCopySupport.py index a6905e8cb7..1b644544bc 100644 --- a/src/OFS/tests/testCopySupport.py +++ b/src/OFS/tests/testCopySupport.py @@ -22,8 +22,7 @@ class UnitTestSecurityPolicy: - """Stub out the existing security policy for unit testing purposes. - """ + """Stub out the existing security policy for unit testing purposes.""" # Standard SecurityPolicy interface def validate( @@ -44,8 +43,7 @@ def checkPermission(self, permission, object, context): class UnitTestUser(Implicit): - """Stubbed out manager for unit testing purposes. - """ + """Stubbed out manager for unit testing purposes.""" def getId(self): return 'unit_tester' diff --git a/src/OFS/tests/testCopySupportEvents.py b/src/OFS/tests/testCopySupportEvents.py index f85c7a36ce..883bdf8e9f 100644 --- a/src/OFS/tests/testCopySupportEvents.py +++ b/src/OFS/tests/testCopySupportEvents.py @@ -95,7 +95,7 @@ def tearDown(self): class TestCopySupport(EventTest): - '''Tests the order in which events are fired''' + """Tests the order in which events are fired.""" def setUp(self): EventTest.setUp(self) @@ -161,7 +161,7 @@ def test_4_Rename(self): class TestCopySupportSublocation(EventTest): - '''Tests the order in which events are fired''' + """Tests the order in which events are fired.""" def setUp(self): EventTest.setUp(self) diff --git a/src/OFS/tests/testCopySupportHooks.py b/src/OFS/tests/testCopySupportHooks.py index eeb7e6a24d..f6054b0577 100644 --- a/src/OFS/tests/testCopySupportHooks.py +++ b/src/OFS/tests/testCopySupportHooks.py @@ -102,7 +102,7 @@ def tearDown(self): class TestCopySupport(HookTest): - '''Tests the order in which add/clone/del hooks are called''' + """Tests the order in which add/clone/del hooks are called.""" def setUp(self): HookTest.setUp(self) @@ -159,7 +159,7 @@ def test_4_Rename(self): class TestCopySupportSublocation(HookTest): - '''Tests the order in which add/clone/del hooks are called''' + """Tests the order in which add/clone/del hooks are called.""" def setUp(self): HookTest.setUp(self) diff --git a/src/OFS/tests/testFileAndImage.py b/src/OFS/tests/testFileAndImage.py index 17d65fd8f4..1e744f9dec 100644 --- a/src/OFS/tests/testFileAndImage.py +++ b/src/OFS/tests/testFileAndImage.py @@ -444,7 +444,7 @@ def testViewImageOrFile_with_empty_denylist(self): class FileEditTests(Testing.ZopeTestCase.FunctionalTestCase): - """Browser testing ..Image.File""" + """Browser testing ..Image.File.""" def setUp(self): super().setUp() diff --git a/src/OFS/tests/testFindSupport.py b/src/OFS/tests/testFindSupport.py index a133c57a7f..b09b5796cd 100644 --- a/src/OFS/tests/testFindSupport.py +++ b/src/OFS/tests/testFindSupport.py @@ -4,7 +4,7 @@ class DummyItem(FindSupport): - """ """ + """""" def __init__(self, id, text=''): self.id = id diff --git a/src/OFS/tests/testHistory.py b/src/OFS/tests/testHistory.py index 845702d566..710d7c3fa1 100644 --- a/src/OFS/tests/testHistory.py +++ b/src/OFS/tests/testHistory.py @@ -164,8 +164,8 @@ def test_manage_historicalComparison(self): class HistoryItemWithSetState(HistoryItem): - """A class with a data migration on __setstate__ - """ + """A class with a data migration on __setstate__""" + def __setstate__(self, state): super().__setstate__(state) self.changed_something = True diff --git a/src/OFS/tests/testObjectManager.py b/src/OFS/tests/testObjectManager.py index 20c1ccd802..edb26b350d 100644 --- a/src/OFS/tests/testObjectManager.py +++ b/src/OFS/tests/testObjectManager.py @@ -615,6 +615,7 @@ def test_export_import(self): class _CallResult: """Auxiliary class to provide defined call results.""" + def __init__(self, result): self.result = result diff --git a/src/OFS/tests/testProperties.py b/src/OFS/tests/testProperties.py index ab698b31ff..4365417330 100644 --- a/src/OFS/tests/testProperties.py +++ b/src/OFS/tests/testProperties.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Properties unit tests. -""" +"""Properties unit tests.""" import unittest diff --git a/src/OFS/tests/testSorting.py b/src/OFS/tests/testSorting.py index d5263b9de0..72e71385dd 100644 --- a/src/OFS/tests/testSorting.py +++ b/src/OFS/tests/testSorting.py @@ -4,7 +4,7 @@ class SortingTests(Testing.ZopeTestCase.FunctionalTestCase): - """Browser testing ..Image.File""" + """Browser testing ..Image.File.""" def setUp(self): super().setUp() diff --git a/src/OFS/tests/testTraverse.py b/src/OFS/tests/testTraverse.py index 1ba8819b1b..304cd3756c 100644 --- a/src/OFS/tests/testTraverse.py +++ b/src/OFS/tests/testTraverse.py @@ -10,17 +10,15 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Traverse unit tests. -""" +"""Traverse unit tests.""" import unittest class UnitTestSecurityPolicy: - """ - Stub out the existing security policy for unit testing purposes. - """ + """Stub out the existing security policy for unit testing purposes.""" # Standard SecurityPolicy interface + def validate(self, accessed=None, container=None, name=None, value=None, context=None, roles=None, *args, **kw): return 1 @@ -30,9 +28,9 @@ def checkPermission(self, permission, object, context): class CruelSecurityPolicy: - """Denies everything - """ + """Denies everything.""" # Standard SecurityPolicy interface + def validate(self, accessed, container, name, value, *args): from AccessControl import Unauthorized raise Unauthorized(name) @@ -42,8 +40,8 @@ def checkPermission(self, permission, object, context): class ProtectedMethodSecurityPolicy: - """Check security strictly on bound methods. - """ + """Check security strictly on bound methods.""" + def validate(self, accessed, container, name, value, *args): from AccessControl import Unauthorized from Acquisition import aq_base @@ -132,9 +130,8 @@ def _makeUser(self): from Acquisition import Implicit class UnitTestUser(Implicit): - """ - Stubbed out manager for unit testing purposes. - """ + """Stubbed out manager for unit testing purposes.""" + def getId(self): return 'unit_tester' getUserName = getId @@ -163,7 +160,7 @@ def __bobo_traverse__(self, request, name): raise KeyError def bb_method(self): - """Test Method""" + """Test Method.""" pass bb_status = 'screechy' @@ -174,7 +171,7 @@ def _makeBoboTraversableWithAcquisition(self): from OFS.SimpleItem import SimpleItem class BoboTraversableWithAcquisition(SimpleItem): - """ A BoboTraversable which may use acquisition to find objects. + """A BoboTraversable which may use acquisition to find objects. This is similar to how the __bobo_traverse__ behaves). """ @@ -192,10 +189,12 @@ class Restricted(SimpleItem): """Instance we'll check with ProtectedMethodSecurityPolicy.""" getId__roles__ = None # ACCESS_PUBLIC + def getId(self): # NOQA: E306 # pseudo decorator return self.id private__roles__ = () # ACCESS_PRIVATE + def private(self): # NOQA: E306 # pseudo decorator return 'private!' @@ -346,11 +345,9 @@ def testBoboTraverseTraversalDefault(self): from ZPublisher.interfaces import UseTraversalDefault class BoboTraversableUseTraversalDefault(SimpleItem): - """ - A BoboTraversable class which may use "UseTraversalDefault" - (dependent on "name") to indicate that standard traversal should - be used. - """ + """A BoboTraversable class which may use "UseTraversalDefault" + (dependent on "name") to indicate that standard traversal should be + used.""" default = 'Default' def __bobo_traverse__(self, request, name): @@ -451,8 +448,7 @@ class SimpleClass: def test_traversable(): - """ - Test the behaviour of unrestrictedTraverse and views. The tests don't + """Test the behaviour of unrestrictedTraverse and views. The tests don't use publishing but do unrestrictedTraverse instead. >>> import Products.Five @@ -609,8 +605,7 @@ def test_traversable(): def test_view_doesnt_shadow_attribute(): - """ - Test that views don't shadow attributes, e.g. items in a folder. + """Test that views don't shadow attributes, e.g. items in a folder. Let's first define a browser page for object managers called ``eagle``: diff --git a/src/OFS/tests/test_DTMLDocument.py b/src/OFS/tests/test_DTMLDocument.py index 86c8b76864..20984e65f7 100644 --- a/src/OFS/tests/test_DTMLDocument.py +++ b/src/OFS/tests/test_DTMLDocument.py @@ -52,7 +52,7 @@ def test_manage_upload__BytesIO(self): self.assertIsInstance(doc.read(), str) def test__call__missing_encoding_old_instances(self): - """ Existing DTML documents have no "encoding" attribute """ + """Existing DTML documents have no "encoding" attribute.""" from OFS.Folder import Folder client = makerequest(Folder('client')) response = client.REQUEST['RESPONSE'] diff --git a/src/OFS/tests/test_DTMLMethod.py b/src/OFS/tests/test_DTMLMethod.py index af2064cd35..fc9001b2c4 100644 --- a/src/OFS/tests/test_DTMLMethod.py +++ b/src/OFS/tests/test_DTMLMethod.py @@ -101,7 +101,7 @@ def test_manage_edit__invalid_code(self): str(err.exception)) def test__call__missing_encoding_old_instances(self): - """ Existing DTML methods have no "encoding" attribute """ + """Existing DTML methods have no "encoding" attribute.""" from OFS.Folder import Folder client = makerequest(Folder('client')) response = client.REQUEST['RESPONSE'] @@ -115,7 +115,7 @@ def test__call__missing_encoding_old_instances(self): class DTMLMethodBrowserTests(Testing.ZopeTestCase.FunctionalTestCase): - """Browser testing ..OFS.DTMLMethod""" + """Browser testing ..OFS.DTMLMethod.""" def setUp(self): from OFS.DTMLMethod import addDTMLMethod diff --git a/src/OFS/tests/test_Uninstalled.py b/src/OFS/tests/test_Uninstalled.py index 7ea9937577..6e2a9525bf 100644 --- a/src/OFS/tests/test_Uninstalled.py +++ b/src/OFS/tests/test_Uninstalled.py @@ -22,8 +22,7 @@ class ToBreak(SimpleItem): class TestsOfBroken(unittest.TestCase): - """Tests for the factory for "broken" classes. - """ + """Tests for the factory for "broken" classes.""" def setUp(self): from OFS.Uninstalled import broken_klasses diff --git a/src/OFS/tests/test_event.py b/src/OFS/tests/test_event.py index 6be9aa5274..35c8806028 100644 --- a/src/OFS/tests/test_event.py +++ b/src/OFS/tests/test_event.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test events -""" +"""Test events.""" from OFS.Folder import Folder from OFS.OrderedFolder import OrderedFolder from OFS.SimpleItem import SimpleItem diff --git a/src/OFS/tests/test_registerclass.py b/src/OFS/tests/test_registerclass.py index cdb590ab89..1756a28063 100644 --- a/src/OFS/tests/test_registerclass.py +++ b/src/OFS/tests/test_registerclass.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Unit tests for the registerClass directive. -""" +"""Unit tests for the registerClass directive.""" from AccessControl.class_init import InitializeClass from AccessControl.SecurityInfo import ClassSecurityInfo @@ -41,8 +40,7 @@ def mymethod(self): @security.public def direct(self): - """Should be able to traverse directly to this as there is no view. - """ + """Should be able to traverse directly to this as there is no view.""" return "Direct traversal worked" @@ -50,8 +48,7 @@ def direct(self): def test_registerClass(): - """ - Testing registerClass + """Testing registerClass. >>> from zope.component.testing import setUp, tearDown >>> setUp() diff --git a/src/OFS/tests/test_registerpackage.py b/src/OFS/tests/test_registerpackage.py index 8daf6c0d28..5776e252cb 100644 --- a/src/OFS/tests/test_registerpackage.py +++ b/src/OFS/tests/test_registerpackage.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Unit tests for the registerPackage directive. -""" +"""Unit tests for the registerPackage directive.""" import sys @@ -25,8 +24,7 @@ def test_registerPackage(): - """ - Testing registerPackage + """Testing registerPackage. >>> from zope.component.testing import setUp, tearDown >>> setUp() diff --git a/src/OFS/tests/test_userfolder.py b/src/OFS/tests/test_userfolder.py index b9217a2dbc..6749e143f8 100644 --- a/src/OFS/tests/test_userfolder.py +++ b/src/OFS/tests/test_userfolder.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -""" Unit tests for OFS.userfolder -""" +"""Unit tests for OFS.userfolder.""" import unittest diff --git a/src/OFS/userfolder.py b/src/OFS/userfolder.py index c05efb87a9..3109fe1f0d 100644 --- a/src/OFS/userfolder.py +++ b/src/OFS/userfolder.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""User folders -""" +"""User folders.""" import os @@ -41,7 +40,7 @@ class BasicUserFolder( RoleManager, accesscontrol_userfolder.BasicUserFolder ): - """Base class for UserFolder-like objects""" + """Base class for UserFolder-like objects.""" security = ClassSecurityInfo() @@ -57,9 +56,11 @@ class BasicUserFolder( @requestmethod('POST') def userFolderAddUser(self, name, password, roles, domains, REQUEST=None, **kw): - """API method for creating a new user object. Note that not all - user folder implementations support dynamic creation of user - objects.""" + """API method for creating a new user object. + + Note that not all user folder implementations support dynamic + creation of user objects. + """ if hasattr(self, '_doAddUser'): return self._doAddUser(name, password, roles, domains, **kw) raise NotImplementedError @@ -75,9 +76,11 @@ def userFolderEditUser( REQUEST=None, **kw ): - """API method for changing user object attributes. Note that not - all user folder implementations support changing of user object - attributes.""" + """API method for changing user object attributes. + + Note that not all user folder implementations support changing + of user object attributes. + """ if hasattr(self, '_doChangeUser'): return self._doChangeUser(name, password, roles, domains, **kw) raise NotImplementedError @@ -85,8 +88,11 @@ def userFolderEditUser( @security.protected(ManageUsers) @requestmethod('POST') def userFolderDelUsers(self, names, REQUEST=None): - """API method for deleting one or more user objects. Note that not - all user folder implementations support deletion of user objects.""" + """API method for deleting one or more user objects. + + Note that not all user folder implementations support deletion + of user objects. + """ if hasattr(self, '_doDelUsers'): return self._doDelUsers(names) raise NotImplementedError @@ -106,8 +112,7 @@ def manage_userFolderProperties( REQUEST=None, manage_tabs_message=None ): - """ - """ + """""" return self._userFolderProperties( self, REQUEST, @@ -123,9 +128,7 @@ def manage_setUserFolderProperties( maxlistusers=DEFAULTMAXLISTUSERS, REQUEST=None ): - """ - Sets the properties of the user folder. - """ + """Sets the properties of the user folder.""" self.encrypt_passwords = not not encrypt_passwords try: self.maxlistusers = int(maxlistusers) @@ -215,10 +218,13 @@ def _delUsers(self, names, REQUEST=None): @security.protected(ManageUsers) def manage_users(self, submit=None, REQUEST=None, RESPONSE=None): - """This method handles operations on users for the web based forms - of the ZMI. Application code (code that is outside of the forms - that implement the UI of a user folder) are encouraged to use - manage_std_addUser""" + """This method handles operations on users for the web based forms of + the ZMI. + + Application code (code that is outside of the forms that + implement the UI of a user folder) are encouraged to use + manage_std_addUser + """ if submit == 'Add...': return self._add_User(self, REQUEST) @@ -274,12 +280,13 @@ def _setId(self, id): class UserFolder(accesscontrol_userfolder.UserFolder, BasicUserFolder): - """Standard UserFolder object + """Standard UserFolder object. - A UserFolder holds User objects which contain information - about users including name, password domain, and roles. - UserFolders function chiefly to control access by authenticating - users and binding them to a collection of roles.""" + A UserFolder holds User objects which contain information about + users including name, password domain, and roles. UserFolders + function chiefly to control access by authenticating users and + binding them to a collection of roles. + """ _ofs_migrated = False @@ -288,14 +295,13 @@ def __init__(self): self._ofs_migrated = True def _createInitialUser(self): - """ - If there are no users or only one user in this user folder, + """If there are no users or only one user in this user folder, populates from the 'inituser' file in the instance home. - We have to do this even when there is already a user - just in case the initial user ignored the setup messages. - We don't do it for more than one user to avoid - abuse of this mechanism. - Called only by OFS.Application.initialize(). + + We have to do this even when there is already a user just in + case the initial user ignored the setup messages. We don't do it + for more than one user to avoid abuse of this mechanism. Called + only by OFS.Application.initialize(). """ if len(self.data) <= 1: info = readUserAccessFile('inituser') @@ -315,7 +321,7 @@ def _createInitialUser(self): def manage_addUserFolder(self, dtself=None, REQUEST=None, **ignored): - """ """ + """""" f = UserFolder() self = self.this() try: diff --git a/src/Products/Five/__init__.py b/src/Products/Five/__init__.py index 2e641e0e93..256e588e37 100644 --- a/src/Products/Five/__init__.py +++ b/src/Products/Five/__init__.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Initialize the Five product -""" +"""Initialize the Five product.""" from Products.Five.browser import BrowserView # NOQA from Products.Five.skin.standardmacros import StandardMacros # NOQA diff --git a/src/Products/Five/browser/__init__.py b/src/Products/Five/browser/__init__.py index f68d54d7b8..7a2d744100 100644 --- a/src/Products/Five/browser/__init__.py +++ b/src/Products/Five/browser/__init__.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Provide basic browser functionality -""" +"""Provide basic browser functionality.""" from zope.publisher import browser diff --git a/src/Products/Five/browser/adding.py b/src/Products/Five/browser/adding.py index 6d138f92b8..1d4ac841ba 100644 --- a/src/Products/Five/browser/adding.py +++ b/src/Products/Five/browser/adding.py @@ -11,10 +11,10 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Adding View +"""Adding View. -The Adding View is used to add new objects to a container. It is sort of a -factory screen. +The Adding View is used to add new objects to a container. It is sort of +a factory screen. (original: zope.app.container.browser.adding) """ @@ -49,8 +49,7 @@ class Adding(BrowserView): def add(self, content): - """See zope.browser.interfaces.IAdding - """ + """See zope.browser.interfaces.IAdding.""" container = self.context name = self.contentName chooser = INameChooser(container) @@ -84,7 +83,7 @@ def add(self, content): contentName = None # usually set by Adding traverser def nextURL(self): - """See zope.browser.interfaces.IAdding""" + """See zope.browser.interfaces.IAdding.""" # XXX this is definitely not right for all or even most uses # of Five, but can be overridden by an AddView subclass return absoluteURL(self.context, self.request) + '/manage_main' @@ -94,7 +93,7 @@ def nextURL(self): context = None def publishTraverse(self, request, name): - """See zope.publisher.interfaces.IPublishTraverse""" + """See zope.publisher.interfaces.IPublishTraverse.""" if '=' in name: view_name, content_name = name.split("=", 1) self.contentName = content_name @@ -199,8 +198,7 @@ class ContentAdding(Adding, SimpleItem): @implementer(INameChooser) class ObjectManagerNameChooser: - """A name chooser for a Zope object manager. - """ + """A name chooser for a Zope object manager.""" def __init__(self, context): self.context = context diff --git a/src/Products/Five/browser/metaconfigure.py b/src/Products/Five/browser/metaconfigure.py index c1e8d5e597..1190bf4c6b 100644 --- a/src/Products/Five/browser/metaconfigure.py +++ b/src/Products/Five/browser/metaconfigure.py @@ -11,7 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Browser directives +"""Browser directives. Directives to emulate the 'http://namespaces.zope.org/browser' namespace in ZCML known from zope.app. diff --git a/src/Products/Five/browser/pagetemplatefile.py b/src/Products/Five/browser/pagetemplatefile.py index fb66857db1..4da51a2099 100644 --- a/src/Products/Five/browser/pagetemplatefile.py +++ b/src/Products/Five/browser/pagetemplatefile.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""A 'PageTemplateFile' without security restrictions. -""" +"""A 'PageTemplateFile' without security restrictions.""" from os.path import basename @@ -33,8 +32,9 @@ def getEngine(): class ViewPageTemplateFile(TrustedAppPT, PageTemplateFile): - """Page Template used as class variable of views defined as Python classes. - """ + """Page Template used as class variable of views defined as Python + classes.""" + def __init__(self, filename, _prefix=None, content_type=None): _prefix = self.get_path_from_prefix(_prefix) super().__init__(filename, _prefix) diff --git a/src/Products/Five/browser/resource.py b/src/Products/Five/browser/resource.py index 8bd38c859c..7b73e2cb86 100644 --- a/src/Products/Five/browser/resource.py +++ b/src/Products/Five/browser/resource.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Provide basic resource functionality -""" +"""Provide basic resource functionality.""" import os from urllib.parse import unquote @@ -35,14 +34,15 @@ class Resource: """A mixin that changes the URL-rendering of resources (__call__). In zope.browserresource, resource URLs are of the form - nearest_site/@@/resource_name. Since Zope 2 didn't have support - for sites from the beginning of the Five integration, resource - URLs in Zope 2 are of the form context/++resource++resource_name. + nearest_site/@@/resource_name. Since Zope 2 didn't have support for + sites from the beginning of the Five integration, resource URLs in + Zope 2 are of the form context/++resource++resource_name. TODO It would be good if that could be changed in the long term, thus making this mixin (and probably the other classes in this module) obsolete. """ + def __call__(self): name = self.__name__ container = self.__parent__ @@ -63,7 +63,7 @@ def publishTraverse(self, request, name): raise NotFound(self, name, request) def render(self): - """Rendered content""" + """Rendered content.""" # ZPublisher might have called setBody with an incorrect URL # we definitely don't want that if we are plain html self.request.response.setBase(None) @@ -101,21 +101,21 @@ def _PageTemplate(self, path, name): class PageTemplateResourceFactory(ResourceFactory): - """A factory for Page Template resources""" + """A factory for Page Template resources.""" factory = _PageTemplate resource = PageTemplateResource class FileResourceFactory(ResourceFactory): - """A factory for File resources""" + """A factory for File resources.""" factory = File resource = FileResource class ImageResourceFactory(ResourceFactory): - """A factory for Image resources""" + """A factory for Image resources.""" factory = File resource = FileResource diff --git a/src/Products/Five/browser/tests/classes.py b/src/Products/Five/browser/tests/classes.py index 31ea622029..b643a51e1d 100644 --- a/src/Products/Five/browser/tests/classes.py +++ b/src/Products/Five/browser/tests/classes.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test fixtures -""" +"""Test fixtures.""" from Products.Five import BrowserView from zope.interface import Interface @@ -20,8 +19,7 @@ class IOne(Interface): - """This is an interface. - """ + """This is an interface.""" @implementer(IOne) diff --git a/src/Products/Five/browser/tests/i18n.py b/src/Products/Five/browser/tests/i18n.py index 1d8f33d11c..734f23ee86 100644 --- a/src/Products/Five/browser/tests/i18n.py +++ b/src/Products/Five/browser/tests/i18n.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test i18n. -""" +"""Test i18n.""" from Products.Five import BrowserView from zope.i18nmessageid import MessageFactory diff --git a/src/Products/Five/browser/tests/pages.py b/src/Products/Five/browser/tests/pages.py index a105f95810..1318f1b237 100644 --- a/src/Products/Five/browser/tests/pages.py +++ b/src/Products/Five/browser/tests/pages.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test browser pages -""" +"""Test browser pages.""" import zope.interface from AccessControl.class_init import InitializeClass @@ -23,25 +22,26 @@ class SimpleView(BrowserView): + """More docstring. - """More docstring. Please Zope""" + Please Zope + """ def eagle(self): - """Docstring""" + """Docstring.""" return "The eagle has landed" def eagle2(self): - """Docstring""" + """Docstring.""" return "The eagle has landed:\n%s" % self.context.absolute_url() def mouse(self): - """Docstring""" + """Docstring.""" return "The mouse has been eaten by the eagle" class FancyView(BrowserView): - - """Fancy, fancy stuff""" + """Fancy, fancy stuff.""" def view(self): return "Fancy, fancy" @@ -85,19 +85,16 @@ def method(self): class NewStyleClass: - - """ - This is a testclass to verify that new style classes work - in browser:page - """ + """This is a testclass to verify that new style classes work in + browser:page.""" def __init__(self, context, request): - """Docstring""" + """Docstring.""" self.context = context self.request = request def method(self): - """Docstring""" + """Docstring.""" return @@ -107,17 +104,17 @@ class ProtectedView: @security.public def public_method(self): - """Docstring""" + """Docstring.""" return 'PUBLIC' @security.protected('View') def protected_method(self): - """Docstring""" + """Docstring.""" return 'PROTECTED' @security.private def private_method(self): - """Docstring""" + """Docstring.""" return 'PRIVATE' diff --git a/src/Products/Five/browser/tests/skin.py b/src/Products/Five/browser/tests/skin.py index 32b068e000..7b010294cc 100644 --- a/src/Products/Five/browser/tests/skin.py +++ b/src/Products/Five/browser/tests/skin.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test skins -""" +"""Test skins.""" from zope.publisher.interfaces.browser import IDefaultBrowserLayer diff --git a/src/Products/Five/browser/tests/test_absoluteurl.py b/src/Products/Five/browser/tests/test_absoluteurl.py index a010f88769..1b246f6680 100644 --- a/src/Products/Five/browser/tests/test_absoluteurl.py +++ b/src/Products/Five/browser/tests/test_absoluteurl.py @@ -11,13 +11,12 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test AbsoluteURL -""" +"""Test AbsoluteURL.""" def test_absoluteurl(): - """This tests the absolute url view (IAbsoluteURL or @@absolute_url), - in particular the breadcrumb functionality. + """This tests the absolute url view (IAbsoluteURL or @@absolute_url), in + particular the breadcrumb functionality. First we make some preparations: diff --git a/src/Products/Five/browser/tests/test_adding.py b/src/Products/Five/browser/tests/test_adding.py index 9ffb8cb88b..10cef35c8e 100644 --- a/src/Products/Five/browser/tests/test_adding.py +++ b/src/Products/Five/browser/tests/test_adding.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test adding views -""" +"""Test adding views.""" def test_suite(): diff --git a/src/Products/Five/browser/tests/test_defaultview.py b/src/Products/Five/browser/tests/test_defaultview.py index 62659434f9..49573309ed 100644 --- a/src/Products/Five/browser/tests/test_defaultview.py +++ b/src/Products/Five/browser/tests/test_defaultview.py @@ -11,13 +11,11 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test Default View functionality -""" +"""Test Default View functionality.""" def test_default_view(): - """ - Test default view functionality + """Test default view functionality. Let's register a couple of default views and make our stub classes default viewable: @@ -90,9 +88,8 @@ def test_default_view(): def test_default_method_args_marshalling(): - """\ - Test the default call method of a view, with respect to possible - breakage of argument marshalling from other components + """\\ Test the default call method of a view, with respect to possible + breakage of argument marshalling from other components. This is not directly a bug in Five, just a change that enables components have simpler code to imitate ZPublisher's arguments diff --git a/src/Products/Five/browser/tests/test_i18n.py b/src/Products/Five/browser/tests/test_i18n.py index dd7df6b3a2..389e274b5f 100644 --- a/src/Products/Five/browser/tests/test_i18n.py +++ b/src/Products/Five/browser/tests/test_i18n.py @@ -11,13 +11,11 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Unit tests for the i18n framework -""" +"""Unit tests for the i18n framework.""" def test_zpt_i18n(): - """ - Test i18n functionality in ZPTs + """Test i18n functionality in ZPTs. >>> configure_zcml = ''' ... >> import Products.Five.browser.tests >>> from Zope2.App import zcml diff --git a/src/Products/Five/browser/tests/test_provider.py b/src/Products/Five/browser/tests/test_provider.py index 2cff2109b5..361ff67322 100644 --- a/src/Products/Five/browser/tests/test_provider.py +++ b/src/Products/Five/browser/tests/test_provider.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test browser pages -""" +"""Test browser pages.""" def test_suite(): diff --git a/src/Products/Five/browser/tests/test_recurse.py b/src/Products/Five/browser/tests/test_recurse.py index ab4c193947..f827611a6b 100644 --- a/src/Products/Five/browser/tests/test_recurse.py +++ b/src/Products/Five/browser/tests/test_recurse.py @@ -11,13 +11,11 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test default view recursion -""" +"""Test default view recursion.""" def test_recursion(): - """ - Test recursion + """Test recursion. This test makes sure that recursion is avoided for view lookup. First, we need to set up a stub interface... diff --git a/src/Products/Five/browser/tests/test_resource.py b/src/Products/Five/browser/tests/test_resource.py index 54a69482cd..f82d3b0767 100644 --- a/src/Products/Five/browser/tests/test_resource.py +++ b/src/Products/Five/browser/tests/test_resource.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test browser resources -""" +"""Test browser resources.""" import unittest diff --git a/src/Products/Five/browser/tests/test_scriptsecurity.py b/src/Products/Five/browser/tests/test_scriptsecurity.py index 2f72c13e5e..4692029a56 100644 --- a/src/Products/Five/browser/tests/test_scriptsecurity.py +++ b/src/Products/Five/browser/tests/test_scriptsecurity.py @@ -24,8 +24,10 @@ def checkRestricted(folder, path, method=''): def checkUnauthorized(folder, path, method=''): - """Perform a check by running restricted Python code. Expect to - encounter an Unauthorized exception.""" + """Perform a check by running restricted Python code. + + Expect to encounter an Unauthorized exception. + """ traverse = "_.this.restrictedTraverse('%s')" % path if not method: body = '' % traverse @@ -114,8 +116,7 @@ def test_resource_restricted_code(): def test_view_restricted_code(): - """ - Let's register a quite large amount of test pages: + """Let's register a quite large amount of test pages: >>> import Products.Five.browser.tests >>> from Zope2.App import zcml diff --git a/src/Products/Five/browser/tests/test_skin.py b/src/Products/Five/browser/tests/test_skin.py index 0b8017d74d..cd59b4d2f7 100644 --- a/src/Products/Five/browser/tests/test_skin.py +++ b/src/Products/Five/browser/tests/test_skin.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test browser pages -""" +"""Test browser pages.""" def test_suite(): diff --git a/src/Products/Five/browser/tests/test_traversable.py b/src/Products/Five/browser/tests/test_traversable.py index c8839bea23..ef2cb62fa4 100644 --- a/src/Products/Five/browser/tests/test_traversable.py +++ b/src/Products/Five/browser/tests/test_traversable.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test Five-traversable classes -""" +"""Test Five-traversable classes.""" class SimpleClass: @@ -20,8 +19,7 @@ class SimpleClass: def test_traversable(): - """ - Test the behaviour of Five-traversable classes. + """Test the behaviour of Five-traversable classes. >>> import Products.Five >>> from Zope2.App import zcml @@ -188,8 +186,7 @@ def test_traversable(): def test_view_doesnt_shadow_attribute(): - """ - Test that views don't shadow attributes, e.g. items in a folder. + """Test that views don't shadow attributes, e.g. items in a folder. Let's first define a browser page for object managers called ``eagle``: diff --git a/src/Products/Five/browser/tests/test_zope3security.py b/src/Products/Five/browser/tests/test_zope3security.py index 45b47d9e8d..89e6aec5ba 100644 --- a/src/Products/Five/browser/tests/test_zope3security.py +++ b/src/Products/Five/browser/tests/test_zope3security.py @@ -1,9 +1,8 @@ def test_check_permission(): """Code (in Zope packages) often uses - zope.security.management.checkPermission to determine whether the - current user has a certain permission in a given context. Five - inserts its own interaction that assures that such calls still - work. + zope.security.management.checkPermission to determine whether the current + user has a certain permission in a given context. Five inserts its own + interaction that assures that such calls still work. >>> configure_zcml = ''' ... >> from zope.component.testing import tearDown >>> tearDown() - """ def test_allowed_interface(): - """This test demonstrates that allowed_interface security declarations - work as expected. + """This test demonstrates that allowed_interface security declarations work + as expected. >>> from zope.component.testing import setUp, tearDown >>> setUp() diff --git a/src/Products/Five/component/__init__.py b/src/Products/Five/component/__init__.py index 2a3f1a8ac0..2b9ec1a38e 100644 --- a/src/Products/Five/component/__init__.py +++ b/src/Products/Five/component/__init__.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Five local component look-up support -""" +"""Five local component look-up support.""" import ExtensionClass import zope.component @@ -36,8 +35,8 @@ def findSite(obj, iface=ISite): - """Find a site by walking up the object hierarchy, supporting both - the ``ILocation`` API and Zope 2 Acquisition.""" + """Find a site by walking up the object hierarchy, supporting both the + ``ILocation`` API and Zope 2 Acquisition.""" while obj is not None and not iface.providedBy(obj): obj = aq_parent(aq_inner(obj)) return obj @@ -46,8 +45,9 @@ def findSite(obj, iface=ISite): @zope.component.adapter(zope.interface.Interface) @zope.interface.implementer(IComponentLookup) def siteManagerAdapter(ob): - """Look-up a site manager/component registry for local component - lookup. This is registered in place of the one in zope.site so that + """Look-up a site manager/component registry for local component lookup. + + This is registered in place of the one in zope.site so that we lookup using acquisition in addition to the ``ILocation`` API. """ site = findSite(ob) @@ -66,8 +66,7 @@ def __call__(self, container, request): def enableSite(obj, iface=ISite): - """Install __before_traverse__ hook for Local Site - """ + """Install __before_traverse__ hook for Local Site.""" # We want the original object, not stuff in between, and no acquisition obj = aq_base(obj) if not IPossibleSite.providedBy(obj): @@ -82,8 +81,7 @@ def enableSite(obj, iface=ISite): def disableSite(obj, iface=ISite): - """Remove __before_traverse__ hook for Local Site - """ + """Remove __before_traverse__ hook for Local Site.""" # We want the original object, not stuff in between, and no acquisition obj = aq_base(obj) if not iface.providedBy(obj): diff --git a/src/Products/Five/component/browser.py b/src/Products/Five/component/browser.py index 2d48f0cae1..012459a356 100644 --- a/src/Products/Five/component/browser.py +++ b/src/Products/Five/component/browser.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Component browser views -""" +"""Component browser views.""" from Products.Five.browser import BrowserView from Products.Five.component import disableSite diff --git a/src/Products/Five/component/interfaces.py b/src/Products/Five/component/interfaces.py index 00d3d20818..14a5bdd16d 100644 --- a/src/Products/Five/component/interfaces.py +++ b/src/Products/Five/component/interfaces.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Component interfaces -""" +"""Component interfaces.""" from OFS.interfaces import IObjectManager from zope.component.interfaces import ISite diff --git a/src/Products/Five/component/tests.py b/src/Products/Five/component/tests.py index 7c50f4d6ee..bd34465a16 100644 --- a/src/Products/Five/component/tests.py +++ b/src/Products/Five/component/tests.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Component tests -""" +"""Component tests.""" import unittest from doctest import DocFileSuite diff --git a/src/Products/Five/fiveconfigure.py b/src/Products/Five/fiveconfigure.py index a801875933..26376c6b2e 100644 --- a/src/Products/Five/fiveconfigure.py +++ b/src/Products/Five/fiveconfigure.py @@ -11,9 +11,10 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Five-specific directive handlers +"""Five-specific directive handlers. -These directives are specific to Five and have no equivalents outside of it. +These directives are specific to Five and have no equivalents outside of +it. """ import glob diff --git a/src/Products/Five/fivedirectives.py b/src/Products/Five/fivedirectives.py index 263c1729de..983d61649e 100644 --- a/src/Products/Five/fivedirectives.py +++ b/src/Products/Five/fivedirectives.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Five ZCML directive schemas -""" +"""Five ZCML directive schemas.""" from zope.browserresource.metadirectives import IBasicResourceInformation from zope.configuration.fields import GlobalObject @@ -21,8 +20,7 @@ class ISizableDirective(Interface): - """Attach sizable adapters to classes. - """ + """Attach sizable adapters to classes.""" class_ = GlobalObject( title="Class", @@ -31,8 +29,7 @@ class ISizableDirective(Interface): class IPagesFromDirectoryDirective(IBasicResourceInformation): - """Register each file in a skin directory as a page resource - """ + """Register each file in a skin directory as a page resource.""" for_ = GlobalObject( title="The interface this view is for.", diff --git a/src/Products/Five/sizeconfigure.py b/src/Products/Five/sizeconfigure.py index d61343b673..bd15c04bbc 100644 --- a/src/Products/Five/sizeconfigure.py +++ b/src/Products/Five/sizeconfigure.py @@ -11,9 +11,8 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Use structured monkey-patching to enable ``ISized`` adapters for -Zope 2 objects. -""" +"""Use structured monkey-patching to enable ``ISized`` adapters for Zope 2 +objects.""" from Products.Five import fivemethod from Products.Five import isFiveMethod @@ -38,7 +37,7 @@ def get_size(self): def classSizable(class_): - """Monkey the class to be sizable through Five""" + """Monkey the class to be sizable through Five.""" # tuck away the original method if necessary if hasattr(class_, "get_size") and not isFiveMethod(class_.get_size): class_.__five_original_get_size = class_.get_size @@ -78,7 +77,7 @@ def killMonkey(class_, name, fallback, attr=None): def unsizable(class_): - """Restore class's initial state with respect to being sizable""" + """Restore class's initial state with respect to being sizable.""" killMonkey(class_, 'get_size', '__five_original_get_size') diff --git a/src/Products/Five/skin/standardmacros.py b/src/Products/Five/skin/standardmacros.py index dbfc258bc7..7c6290296f 100644 --- a/src/Products/Five/skin/standardmacros.py +++ b/src/Products/Five/skin/standardmacros.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Mimick the zope.app.basicskin skinning system. -""" +"""Mimick the zope.app.basicskin skinning system.""" import zope.component import zope.interface diff --git a/src/Products/Five/skin/tests/demomacros.py b/src/Products/Five/skin/tests/demomacros.py index 964bb82d93..086e7bd7f8 100644 --- a/src/Products/Five/skin/tests/demomacros.py +++ b/src/Products/Five/skin/tests/demomacros.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Demo StandardMacros -""" +"""Demo StandardMacros.""" from Products.Five import StandardMacros as BaseMacros diff --git a/src/Products/Five/skin/tests/test_standardmacros.py b/src/Products/Five/skin/tests/test_standardmacros.py index e4e2f8d314..895e647d08 100644 --- a/src/Products/Five/skin/tests/test_standardmacros.py +++ b/src/Products/Five/skin/tests/test_standardmacros.py @@ -11,12 +11,11 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test standard macros -""" +"""Test standard macros.""" def test_standard_macros(): - """Test standard macros + """Test standard macros. >>> folder = self.folder # NOQA: F821 >>> uf = folder.acl_users diff --git a/src/Products/Five/tests/adapters.py b/src/Products/Five/tests/adapters.py index 4e80f283b4..936c6b6db3 100644 --- a/src/Products/Five/tests/adapters.py +++ b/src/Products/Five/tests/adapters.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Adapter test fixtures -""" +"""Adapter test fixtures.""" from zope.component import adapter from zope.interface import Interface @@ -20,31 +19,27 @@ class IAdaptable(Interface): - """This is a Zope interface. - """ + """This is a Zope interface.""" def method(): - """This method will be adapted - """ + """This method will be adapted.""" class IAdapted(Interface): - """The interface we adapt to. - """ + """The interface we adapt to.""" def adaptedMethod(): - """A method to adapt. - """ + """A method to adapt.""" class IOrigin(Interface): - """Something we'll adapt""" + """Something we'll adapt.""" class IDestination(Interface): - """The result of an adaption""" + """The result of an adaption.""" def method(): - """Do something""" + """Do something.""" @implementer(IAdaptable) diff --git a/src/Products/Five/tests/classes.py b/src/Products/Five/tests/classes.py index bb83a9643f..a0113d6539 100644 --- a/src/Products/Five/tests/classes.py +++ b/src/Products/Five/tests/classes.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Interfaces test fixtures -""" +"""Interfaces test fixtures.""" from zope.interface import Interface @@ -26,10 +25,8 @@ class Two: class IOne(Interface): - """This is a Zope interface. - """ + """This is a Zope interface.""" class ITwo(Interface): - """This is another Zope interface. - """ + """This is another Zope interface.""" diff --git a/src/Products/Five/tests/metaconfigure.py b/src/Products/Five/tests/metaconfigure.py index 8086349fa1..d9727e4145 100644 --- a/src/Products/Five/tests/metaconfigure.py +++ b/src/Products/Five/tests/metaconfigure.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Parrot directive and support classes -""" +"""Parrot directive and support classes.""" from zope.configuration.fields import GlobalObject from zope.interface import Interface @@ -20,8 +19,7 @@ class IParrotDirective(Interface): - """State that a class implements something. - """ + """State that a class implements something.""" class_ = GlobalObject( title="Class", required=True, diff --git a/src/Products/Five/tests/test_directives.py b/src/Products/Five/tests/test_directives.py index 217d25036c..62b6c2fd0b 100644 --- a/src/Products/Five/tests/test_directives.py +++ b/src/Products/Five/tests/test_directives.py @@ -11,13 +11,11 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test the basic ZCML directives -""" +"""Test the basic ZCML directives.""" def test_directives(): - """ - Test ZCML directives + """Test ZCML directives. There isn't much to test here since the actual directive handlers are either tested in other, more specific tests, or they're already tested in diff --git a/src/Products/Five/tests/test_i18n.py b/src/Products/Five/tests/test_i18n.py index b044f9fa40..7eb0344638 100644 --- a/src/Products/Five/tests/test_i18n.py +++ b/src/Products/Five/tests/test_i18n.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Unit tests for the i18n framework -""" +"""Unit tests for the i18n framework.""" from zope.component.testing import setUp from zope.component.testing import tearDown diff --git a/src/Products/Five/tests/test_size.py b/src/Products/Five/tests/test_size.py index caf2726588..2f7efb4d28 100644 --- a/src/Products/Five/tests/test_size.py +++ b/src/Products/Five/tests/test_size.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Size adapters for testing -""" +"""Size adapters for testing.""" from zope.interface import implementer from zope.size.interfaces import ISized @@ -46,8 +45,7 @@ def sizeForDisplay(self): def test_size(): - """ - Test size adapters + """Test size adapters. Set up: diff --git a/src/Products/Five/tests/testing/__init__.py b/src/Products/Five/tests/testing/__init__.py index 8bd5032ef6..7b99987d79 100644 --- a/src/Products/Five/tests/testing/__init__.py +++ b/src/Products/Five/tests/testing/__init__.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test helpers -""" +"""Test helpers.""" from .folder import FiveTraversableFolder # NOQA: F401 from .folder import NoVerifyPasteFolder # NOQA: F401 diff --git a/src/Products/Five/tests/testing/fancycontent.py b/src/Products/Five/tests/testing/fancycontent.py index dc1971960b..d666df9762 100644 --- a/src/Products/Five/tests/testing/fancycontent.py +++ b/src/Products/Five/tests/testing/fancycontent.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test content objects. -""" +"""Test content objects.""" from AccessControl.class_init import InitializeClass from AccessControl.SecurityInfo import ClassSecurityInfo @@ -27,7 +26,7 @@ class IFancyContent(Interface): class FancyAttribute(Explicit): - """Doc test fanatics""" + """Doc test fanatics.""" def __init__(self, name): self.name = name @@ -36,7 +35,7 @@ def __init__(self, name): @security.public def index_html(self, REQUEST): - """Doc test fanatics""" + """Doc test fanatics.""" return self.name @@ -45,8 +44,8 @@ def index_html(self, REQUEST): @implementer(IFancyContent) class FancyContent(SimpleItem): - """A class that already comes with its own __bobo_traverse__ handler. - Quite fancy indeed. + """A class that already comes with its own __bobo_traverse__ handler. Quite + fancy indeed. It also comes with its own get_size method. """ @@ -72,8 +71,8 @@ def get_size(self): @implementer(IFancyContent) class NonTraversableFancyContent(SimpleItem): - """A class that already comes with its own __bobo_traverse__ handler. - Quite fancy indeed. + """A class that already comes with its own __bobo_traverse__ handler. Quite + fancy indeed. It also comes with its own get_size method. """ diff --git a/src/Products/Five/tests/testing/folder.py b/src/Products/Five/tests/testing/folder.py index c356a792fb..4b3018277b 100644 --- a/src/Products/Five/tests/testing/folder.py +++ b/src/Products/Five/tests/testing/folder.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test folders -""" +"""Test folders.""" from OFS.Folder import Folder from OFS.interfaces import IFolder @@ -21,8 +20,10 @@ class NoVerifyPasteFolder(Folder): """Folder that does not perform paste verification. + Used by test_events """ + def _verifyObjectPaste(self, object, validate_src=1): pass @@ -36,8 +37,7 @@ def manage_addNoVerifyPasteFolder(container, id, title=''): @implementer(IFolder) class FiveTraversableFolder(Folder): - """Folder that is five-traversable - """ + """Folder that is five-traversable.""" def manage_addFiveTraversableFolder(container, id, title=''): diff --git a/src/Products/Five/tests/testing/simplecontent.py b/src/Products/Five/tests/testing/simplecontent.py index 6845656fbd..dba8de5414 100644 --- a/src/Products/Five/tests/testing/simplecontent.py +++ b/src/Products/Five/tests/testing/simplecontent.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Simple content class(es) for browser tests -""" +"""Simple content class(es) for browser tests.""" from AccessControl.class_init import InitializeClass from AccessControl.SecurityInfo import ClassSecurityInfo @@ -49,8 +48,7 @@ def mymethod(self): @security.public def direct(self): - """Should be able to traverse directly to this as there is no view. - """ + """Should be able to traverse directly to this as there is no view.""" return "Direct traversal worked" @@ -59,12 +57,12 @@ def direct(self): @implementer(ICallableSimpleContent) class CallableSimpleContent(SimpleItem): - """A Viewable piece of content""" + """A Viewable piece of content.""" meta_type = "Five CallableSimpleContent" def __call__(self, *args, **kw): - """ """ + """""" return "Default __call__ called" @@ -73,12 +71,12 @@ def __call__(self, *args, **kw): @implementer(IIndexSimpleContent) class IndexSimpleContent(SimpleItem): - """A Viewable piece of content""" + """A Viewable piece of content.""" meta_type = 'Five IndexSimpleContent' def index_html(self, *args, **kw): - """ """ + """""" return "Default index_html called" diff --git a/src/Products/Five/utilities/browser/marker.py b/src/Products/Five/utilities/browser/marker.py index 838c705f15..c18ab6314a 100644 --- a/src/Products/Five/utilities/browser/marker.py +++ b/src/Products/Five/utilities/browser/marker.py @@ -11,15 +11,13 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Marker interfaces adapter views. -""" +"""Marker interfaces adapter views.""" from Products.Five.utilities.interfaces import IMarkerInterfaces class EditView: - """Marker interface edit view. - """ + """Marker interface edit view.""" def __init__(self, context, request): self.context = context diff --git a/src/Products/Five/utilities/browser/tests/test_marker.py b/src/Products/Five/utilities/browser/tests/test_marker.py index f67b90138c..e2ab725467 100644 --- a/src/Products/Five/utilities/browser/tests/test_marker.py +++ b/src/Products/Five/utilities/browser/tests/test_marker.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -""" Tests for the marker interface edit views -""" +"""Tests for the marker interface edit views.""" import AccessControl import Products.Five import Products.Five.utilities diff --git a/src/Products/Five/utilities/interfaces.py b/src/Products/Five/utilities/interfaces.py index 74cf654583..62dc5099b9 100644 --- a/src/Products/Five/utilities/interfaces.py +++ b/src/Products/Five/utilities/interfaces.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Utility Interface Definitions. -""" +"""Utility Interface Definitions.""" from zope.interface import Interface @@ -20,54 +19,41 @@ class IReadInterface(Interface): def getDirectlyProvided(): - """List the interfaces directly implemented by the object. - """ + """List the interfaces directly implemented by the object.""" def getDirectlyProvidedNames(): - """List the names of interfaces directly implemented by the object. - """ + """List the names of interfaces directly implemented by the object.""" def getAvailableInterfaces(): - """List the marker interfaces available for the object. - """ + """List the marker interfaces available for the object.""" def getAvailableInterfaceNames(): - """List the names of marker interfaces available for the object. - """ + """List the names of marker interfaces available for the object.""" def getInterfaces(): - """List interfaces provided by the class of the object. - """ + """List interfaces provided by the class of the object.""" def getInterfaceNames(): - """List the names of interfaces provided by the class of the object. - """ + """List the names of interfaces provided by the class of the object.""" def getProvided(): - """List interfaces provided by the object. - """ + """List interfaces provided by the object.""" def getProvidedNames(): - """List the names of interfaces provided by the object. - """ + """List the names of interfaces provided by the object.""" class IWriteInterface(Interface): def update(add=(), remove=()): - """Update directly provided interfaces of the object. - """ + """Update directly provided interfaces of the object.""" def mark(interface): - """Add interface to interfaces the object directly provides. - """ + """Add interface to interfaces the object directly provides.""" def erase(interface): - """Remove interfaces from interfaces the object directly provides. - """ + """Remove interfaces from interfaces the object directly provides.""" class IMarkerInterfaces(IReadInterface, IWriteInterface): - - """Provides methods for inspecting and assigning marker interfaces. - """ + """Provides methods for inspecting and assigning marker interfaces.""" diff --git a/src/Products/Five/utilities/marker.py b/src/Products/Five/utilities/marker.py index ccc2585fad..efd40b5e8e 100644 --- a/src/Products/Five/utilities/marker.py +++ b/src/Products/Five/utilities/marker.py @@ -86,8 +86,7 @@ def getAvailableInterfaces(self): return tuple(results) def getAvailableInterfaceNames(self): - names = self._getInterfaceNames(self.getAvailableInterfaces()) - names.sort() + names = sorted(self._getInterfaceNames(self.getAvailableInterfaces())) return names def getInterfaces(self): @@ -103,8 +102,7 @@ def getProvidedNames(self): return self._getInterfaceNames(self.getProvided()) def update(self, add=(), remove=()): - """Currently update adds and then removes, rendering duplicate null. - """ + """Currently update adds and then removes, rendering duplicate null.""" marker_ifaces = self.getAvailableInterfaces() if len(add): [mark(self.context, interface) @@ -119,8 +117,7 @@ def _getInterfaceNames(self, interfaces): return [interfaceToName(self, iface) for iface in interfaces] def _getDirectMarkersOf(self, base): - """Get empty interfaces directly inheriting from the given one. - """ + """Get empty interfaces directly inheriting from the given one.""" results = [] interfaces = searchInterface(None, base=base) for interface in interfaces: diff --git a/src/Products/Five/viewlet/manager.py b/src/Products/Five/viewlet/manager.py index 5173a0e0aa..82df13c2a3 100644 --- a/src/Products/Five/viewlet/manager.py +++ b/src/Products/Five/viewlet/manager.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Viewlet manager. -""" +"""Viewlet manager.""" from operator import itemgetter @@ -25,12 +24,12 @@ class ViewletManagerBase(origManagerBase): - """A base class for Viewlet managers to work in Zope2""" + """A base class for Viewlet managers to work in Zope2.""" template = None def __getitem__(self, name): - """See zope.interface.common.mapping.IReadMapping""" + """See zope.interface.common.mapping.IReadMapping.""" # Find the viewlet viewlet = zope.component.queryMultiAdapter( (self.context, self.request, self.__parent__, self), @@ -52,7 +51,7 @@ def __getitem__(self, name): return viewlet def filter(self, viewlets): - """Sort out all content providers + """Sort out all content providers. ``viewlets`` is a list of tuples of the form (name, viewlet). """ diff --git a/src/Products/Five/viewlet/metaconfigure.py b/src/Products/Five/viewlet/metaconfigure.py index 0b4269184a..7fca0e950f 100644 --- a/src/Products/Five/viewlet/metaconfigure.py +++ b/src/Products/Five/viewlet/metaconfigure.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Viewlet ZCML directives. -""" +"""Viewlet ZCML directives.""" import os diff --git a/src/Products/Five/viewlet/tests.py b/src/Products/Five/viewlet/tests.py index 2328ce657a..522954d727 100644 --- a/src/Products/Five/viewlet/tests.py +++ b/src/Products/Five/viewlet/tests.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Viewlet tests -""" +"""Viewlet tests.""" import unittest @@ -29,10 +28,9 @@ class Content(SimpleItem): class UnitTestSecurityPolicy: - """ - Stub out the existing security policy for unit testing purposes. - """ + """Stub out the existing security policy for unit testing purposes.""" # Standard SecurityPolicy interface + def validate(self, accessed=None, container=None, diff --git a/src/Products/Five/viewlet/viewlet.py b/src/Products/Five/viewlet/viewlet.py index e0a616cc9e..506f904aca 100644 --- a/src/Products/Five/viewlet/viewlet.py +++ b/src/Products/Five/viewlet/viewlet.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Viewlet. -""" +"""Viewlet.""" import os @@ -35,8 +34,7 @@ class simple(zope.viewlet.viewlet.simple): def SimpleViewletClass(template, bases=(), attributes=None, name=''): """A function that can be used to generate a viewlet from a set of - information. - """ + information.""" # Create the base class hierarchy bases += (simple, ViewletBase) diff --git a/src/Products/PageTemplates/Expressions.py b/src/Products/PageTemplates/Expressions.py index 39102017c1..500928ab3f 100644 --- a/src/Products/PageTemplates/Expressions.py +++ b/src/Products/PageTemplates/Expressions.py @@ -10,10 +10,10 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Page Template Expression Engine +"""Page Template Expression Engine. -Page Template-specific implementation of TALES, with handlers -for Python expressions, string literals, and paths. +Page Template-specific implementation of TALES, with handlers for Python +expressions, string literals, and paths. """ import logging @@ -66,9 +66,9 @@ def boboAwareZopeTraverse(object, path_items, econtext): """Traverses a sequence of names, first trying attributes then items. - This uses zope.traversing path traversal where possible and interacts - correctly with objects providing OFS.interface.ITraversable when - necessary (bobo-awareness). + This uses zope.traversing path traversal where possible and + interacts correctly with objects providing + OFS.interface.ITraversable when necessary (bobo-awareness). """ request = getattr(econtext, 'request', None) validate = getSecurityManager().validate @@ -114,9 +114,9 @@ def boboAwareZopeTraverse(object, path_items, econtext): def trustedBoboAwareZopeTraverse(object, path_items, econtext): """Traverses a sequence of names, first trying attributes then items. - This uses zope.traversing path traversal where possible and interacts - correctly with objects providing OFS.interface.ITraversable when - necessary (bobo-awareness). + This uses zope.traversing path traversal where possible and + interacts correctly with objects providing + OFS.interface.ITraversable when necessary (bobo-awareness). """ request = getattr(econtext, 'request', None) path_items = list(path_items) @@ -133,8 +133,10 @@ def trustedBoboAwareZopeTraverse(object, path_items, econtext): def render(ob, ns): - """Calls the object, possibly a document template, or just returns - it if not callable. (From DT_Util.py) + """Calls the object, possibly a document template, or just returns it if + not callable. + + (From DT_Util.py) """ if hasattr(ob, '__render_with_namespace__'): ob = ZRPythonExpr.call_with_ns(ob.__render_with_namespace__, ns) @@ -160,6 +162,7 @@ class _CombinedMapping: Earlier mappings take precedence. """ + def __init__(self, *ms): self.mappings = ms @@ -241,10 +244,10 @@ class TrustedZopePathExpr(ZopePathExpr): class SafeMapping(MultiMapping): """Mapping with security declarations and limited method exposure. - Since it subclasses MultiMapping, this class can be used to wrap - one or more mapping objects. Restricted Python code will not be - able to mutate the SafeMapping or the wrapped mappings, but will be - able to read any value. + Since it subclasses MultiMapping, this class can be used to wrap one + or more mapping objects. Restricted Python code will not be able to + mutate the SafeMapping or the wrapped mappings, but will be able to + read any value. """ __allow_access_to_unprotected_subobjects__ = True push = pop = None @@ -282,16 +285,14 @@ def evaluateBoolean(self, expr): return bool(value) def evaluateStructure(self, expr): - """ customized version in order to get rid of unicode - errors for all and ever - """ + """Customized version in order to get rid of unicode errors for all and + ever.""" text = super().evaluateStructure(expr) return self._handleText(text, expr) def evaluateText(self, expr): - """ customized version in order to get rid of unicode - errors for all and ever - """ + """Customized version in order to get rid of unicode errors for all and + ever.""" text = self.evaluate(expr) return self._handleText(text, expr) @@ -339,7 +340,7 @@ def createErrorInfo(self, err, position): return ErrorInfo(err, position) def evaluateCode(self, lang, code): - """ See ITALExpressionEngine. + """See ITALExpressionEngine. o This method is a fossil: nobody actually calls it, but the interface requires it. @@ -348,8 +349,7 @@ def evaluateCode(self, lang, code): class ErrorInfo(BaseErrorInfo): - """Information about an exception passed to an on-error handler. - """ + """Information about an exception passed to an on-error handler.""" __allow_access_to_unprotected_subobjects__ = True @@ -425,8 +425,8 @@ def next(self): @implementer(ITraversable) class PathIterator(ZopeIterator): - """A TALES Iterator with the ability to use first() and last() on - subpaths of elements.""" + """A TALES Iterator with the ability to use first() and last() on subpaths + of elements.""" def traverse(self, name, furtherPath): if name in ('first', 'last'): diff --git a/src/Products/PageTemplates/PageTemplate.py b/src/Products/PageTemplates/PageTemplate.py index 55dc528d14..ee5e973ea8 100644 --- a/src/Products/PageTemplates/PageTemplate.py +++ b/src/Products/PageTemplates/PageTemplate.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Page Template module -""" +"""Page Template module.""" import sys diff --git a/src/Products/PageTemplates/PageTemplateFile.py b/src/Products/PageTemplates/PageTemplateFile.py index ae5d9520db..a83d37d43e 100644 --- a/src/Products/PageTemplates/PageTemplateFile.py +++ b/src/Products/PageTemplates/PageTemplateFile.py @@ -120,7 +120,7 @@ def pt_getContext(self): return c def _exec(self, bound_names, args, kw): - """Call a Page Template""" + """Call a Page Template.""" self._cook_check() if 'args' not in kw: kw['args'] = args @@ -225,9 +225,9 @@ def _get__roles__(self): def getOwner(self, info=0): """Gets the owner of the executable object. - This method is required of all objects that go into - the security context stack. Since this object came from the - filesystem, it is owned by no one managed by Zope. + This method is required of all objects that go into the security + context stack. Since this object came from the filesystem, it + is owned by no one managed by Zope. """ return None diff --git a/src/Products/PageTemplates/ZRPythonExpr.py b/src/Products/PageTemplates/ZRPythonExpr.py index dffd47727c..57a6adcba0 100644 --- a/src/Products/PageTemplates/ZRPythonExpr.py +++ b/src/Products/PageTemplates/ZRPythonExpr.py @@ -10,7 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Zope-specific Python Expression Handler +"""Zope-specific Python Expression Handler. Handler for Python expressions that uses the RestrictedPython package. """ diff --git a/src/Products/PageTemplates/ZopePageTemplate.py b/src/Products/PageTemplates/ZopePageTemplate.py index bbd13e0ac6..c94e539c0c 100644 --- a/src/Products/PageTemplates/ZopePageTemplate.py +++ b/src/Products/PageTemplates/ZopePageTemplate.py @@ -10,8 +10,8 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Zope Page Template module (wrapper for the zope.pagetemplate implementation) -""" +"""Zope Page Template module (wrapper for the zope.pagetemplate +implementation)""" import os @@ -47,7 +47,7 @@ class Src(Explicit): - """ I am scary code """ + """I am scary code.""" security = ClassSecurityInfo() security.declareObjectProtected(view_management_screens) @@ -174,7 +174,7 @@ def pt_setTitle(self, title, encoding='utf-8'): self._setPropValue('title', title) def _setPropValue(self, id, value): - """ set a property and invalidate the cache """ + """Set a property and invalidate the cache.""" PropertyManager._setPropValue(self, id, value) self.ZCacheable_invalidate() @@ -247,7 +247,7 @@ def write(self, text): ZopePageTemplate.inheritedAttribute('write')(self, text) def _exec(self, bound_names, args, kw): - """Call a Page Template""" + """Call a Page Template.""" if 'args' not in kw: kw['args'] = args bound_names['options'] = kw @@ -346,7 +346,7 @@ def pt_render(self, source=False, extra_context={}): @security.protected(change_page_templates) def PUT(self, REQUEST, RESPONSE): - """ Handle HTTP PUT requests """ + """Handle HTTP PUT requests.""" self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) diff --git a/src/Products/PageTemplates/__init__.py b/src/Products/PageTemplates/__init__.py index 62cac12138..77c3168192 100644 --- a/src/Products/PageTemplates/__init__.py +++ b/src/Products/PageTemplates/__init__.py @@ -10,7 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Package wrapper for Page Templates +"""Package wrapper for Page Templates. This wrapper allows the Page Template modules to be segregated in a separate package. diff --git a/src/Products/PageTemplates/engine.py b/src/Products/PageTemplates/engine.py index df1d1d3390..3eb7c64427 100644 --- a/src/Products/PageTemplates/engine.py +++ b/src/Products/PageTemplates/engine.py @@ -42,7 +42,7 @@ class _PseudoContext: - """auxiliary context object. + """Auxiliary context object. Used to bridge between ``chameleon`` and ``zope.tales`` iterators. """ @@ -69,8 +69,8 @@ class RepeatDictWrapper(RepeatDict): # Logic (mostly) from ``chameleon.tal.RepeatDict`` def __call__(self, key, iterable): - """We coerce the iterable to a tuple and return an iterator - after registering it in the repeat dictionary.""" + """We coerce the iterable to a tuple and return an iterator after + registering it in the repeat dictionary.""" iterable = list(iterable) if iterable is not None else () length = len(iterable) @@ -86,6 +86,7 @@ def __call__(self, key, iterable): class RepeatItem(PathIterator): """Iterator compatible with ``chameleon`` and ``zope.tales``.""" + def __iter__(self): return self @@ -124,7 +125,7 @@ def __next__(self): def _compile_zt_expr(type, expression, engine=None, econtext=None): - """compile *expression* of type *type*. + """Compile *expression* of type *type*. The engine is derived either directly from *engine* or the execution content *econtext*. One of them must be given. @@ -151,7 +152,7 @@ def _compile_zt_expr(type, expression, engine=None, econtext=None): def _with_vars_from_chameleon(context): - """prepare *context* to get its ``vars`` from ``chameleon``.""" + """Prepare *context* to get its ``vars`` from ``chameleon``.""" cc = context.__class__ wc = _context_class_registry.get(cc) if wc is None: @@ -209,7 +210,7 @@ def setGlobal(self, name, value): # unsupported methods def beginScope(self, *args, **kw): - """will not work as the scope is controlled by ``chameleon``.""" + """Will not work as the scope is controlled by ``chameleon``.""" raise NotImplementedError() endScope = beginScope @@ -241,6 +242,7 @@ def _C2ZContextWrapper(c_context, attrs): class MappedExpr: """map expression: ``zope.tales`` --> ``chameleon.tales``.""" + def __init__(self, type, expression, zt_engine): self.type = type # At this place, *expression* is a `chameleon.tokenize.Token` @@ -315,6 +317,7 @@ def __call__(self, target, c_engine): class MappedExprType: """map expression type: ``zope.tales`` --> ``chameleon.tales``.""" + def __init__(self, engine, type): self.engine = engine self.type = type diff --git a/src/Products/PageTemplates/expression.py b/src/Products/PageTemplates/expression.py index da01002c60..0cc3230690 100644 --- a/src/Products/PageTemplates/expression.py +++ b/src/Products/PageTemplates/expression.py @@ -215,6 +215,7 @@ class ChameleonEngine(ExpressionEngine): Only partially implemented: its ``compile`` is currently unusable """ + def compile(self, expression): raise NotImplementedError() diff --git a/src/Products/PageTemplates/interfaces.py b/src/Products/PageTemplates/interfaces.py index bad375c742..0f478689ed 100644 --- a/src/Products/PageTemplates/interfaces.py +++ b/src/Products/PageTemplates/interfaces.py @@ -15,17 +15,18 @@ class IUnicodeEncodingConflictResolver(Interface): - """ A utility that tries to convert a non-unicode string into - a Python unicode by implementing some policy in order - to figure out a possible encoding - either through the - calling context, the location or the system environment + """A utility that tries to convert a non-unicode string into. + + a Python unicode by implementing some policy in order + to figure out a possible encoding - either through the + calling context, the location or the system environment """ def resolve(context, text, expression): - """ Returns 'text' as unicode string. - 'context' is the current context object. - 'expression' is the original expression (can be used for - logging purposes) + """Returns 'text' as unicode string. + + 'context' is the current context object. 'expression' is the + original expression (can be used for logging purposes) """ diff --git a/src/Products/PageTemplates/tests/batch.py b/src/Products/PageTemplates/tests/batch.py index 42454f9871..bccedccffc 100644 --- a/src/Products/PageTemplates/tests/batch.py +++ b/src/Products/PageTemplates/tests/batch.py @@ -22,7 +22,7 @@ class batch(util.Base): - """Create a sequence batch""" + """Create a sequence batch.""" def __init__(self, sequence, size, start=0, end=0, orphan=3, overlap=0): diff --git a/src/Products/PageTemplates/tests/testDTMLTests.py b/src/Products/PageTemplates/tests/testDTMLTests.py index f91a870ed9..d748e025a8 100644 --- a/src/Products/PageTemplates/tests/testDTMLTests.py +++ b/src/Products/PageTemplates/tests/testDTMLTests.py @@ -34,12 +34,11 @@ class AqPageTemplate(Implicit, PageTemplate): class UnitTestSecurityPolicy: - """ - Stub out the existing security policy for unit testing purposes. - """ + """Stub out the existing security policy for unit testing purposes.""" # # Standard SecurityPolicy interface # + def validate(self, accessed=None, container=None, diff --git a/src/Products/PageTemplates/tests/testHTMLTests.py b/src/Products/PageTemplates/tests/testHTMLTests.py index 47a359d449..a2a33fdfc1 100644 --- a/src/Products/PageTemplates/tests/testHTMLTests.py +++ b/src/Products/PageTemplates/tests/testHTMLTests.py @@ -48,10 +48,9 @@ class Folder(util.Base): class UnitTestSecurityPolicy: - """ - Stub out the existing security policy for unit testing purposes. - """ + """Stub out the existing security policy for unit testing purposes.""" # Standard SecurityPolicy interface + def validate(self, accessed=None, container=None, diff --git a/src/Products/PageTemplates/tests/testTranslation.py b/src/Products/PageTemplates/tests/testTranslation.py index f45f674d93..ea2f572682 100644 --- a/src/Products/PageTemplates/tests/testTranslation.py +++ b/src/Products/PageTemplates/tests/testTranslation.py @@ -28,7 +28,7 @@ def translate(*args, **kw): class TranslationLayer: - """set up our translation function.""" + """Set up our translation function.""" @classmethod def setUp(cls): cls._saved_translate = pagetemplate.fast_translate diff --git a/src/Products/PageTemplates/tests/testVariables.py b/src/Products/PageTemplates/tests/testVariables.py index 77d0c054e8..63ae35ceae 100644 --- a/src/Products/PageTemplates/tests/testVariables.py +++ b/src/Products/PageTemplates/tests/testVariables.py @@ -14,7 +14,7 @@ def pt_getEngine(self): class TestPredefinedVariables(PlacelessSetup, TestCase): - """test predefined variables + """Test predefined variables. as documented by `>> getattr(self.app, 'LAYER_EXTRACTED', False) # NOQA: F821 True diff --git a/src/Testing/ZopeTestCase/zopedoctest/testPackageAsProduct.py b/src/Testing/ZopeTestCase/zopedoctest/testPackageAsProduct.py index 8343ee4c97..a659defd43 100644 --- a/src/Testing/ZopeTestCase/zopedoctest/testPackageAsProduct.py +++ b/src/Testing/ZopeTestCase/zopedoctest/testPackageAsProduct.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Tests for installPackage -""" +"""Tests for installPackage.""" import sys from unittest import TestSuite @@ -24,8 +23,7 @@ def testInstallPackage(): - """ - Test if installPackage works. + """Test if installPackage works. >>> from Testing import ZopeTestCase >>> from Zope2.App import zcml diff --git a/src/Testing/ZopeTestCase/zopedoctest/testWarningsTest.py b/src/Testing/ZopeTestCase/zopedoctest/testWarningsTest.py index a4105bff42..00b84a4abb 100644 --- a/src/Testing/ZopeTestCase/zopedoctest/testWarningsTest.py +++ b/src/Testing/ZopeTestCase/zopedoctest/testWarningsTest.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Example doctest -""" +"""Example doctest.""" from unittest import TestSuite diff --git a/src/Testing/ZopeTestCase/zopedoctest/testZopeDocTest.py b/src/Testing/ZopeTestCase/zopedoctest/testZopeDocTest.py index 5118e7de35..bbc1ab2445 100644 --- a/src/Testing/ZopeTestCase/zopedoctest/testZopeDocTest.py +++ b/src/Testing/ZopeTestCase/zopedoctest/testZopeDocTest.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Example Zope doctest -""" +"""Example Zope doctest.""" from unittest import TestSuite @@ -20,14 +19,14 @@ def setUp(self): - '''This method will run after the test_class' setUp. + """This method will run after the test_class' setUp. >>> 'object' in self.folder.objectIds() # NOQA: F821 True >>> foo # NOQA: F821 1 - ''' + """ self.folder.manage_addFolder('object', '') self.globs['foo'] = 1 diff --git a/src/Testing/ZopeTestCase/zopedoctest/tests.py b/src/Testing/ZopeTestCase/zopedoctest/tests.py index 50f059cce0..b5585bfb76 100644 --- a/src/Testing/ZopeTestCase/zopedoctest/tests.py +++ b/src/Testing/ZopeTestCase/zopedoctest/tests.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Test runner that works with zope.testrunner -""" +"""Test runner that works with zope.testrunner.""" import os import unittest diff --git a/src/Testing/__init__.py b/src/Testing/__init__.py index b9953bd6bf..6875e9cd8f 100644 --- a/src/Testing/__init__.py +++ b/src/Testing/__init__.py @@ -10,9 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -""" -Set up testing environment -""" +"""Set up testing environment.""" import os diff --git a/src/Testing/custom_zodb.py b/src/Testing/custom_zodb.py index 11cbccd2cb..32d07046d8 100644 --- a/src/Testing/custom_zodb.py +++ b/src/Testing/custom_zodb.py @@ -6,11 +6,12 @@ def getStorage(): - """ Return a storage instance for running ZopeTestCase based - tests. By default a DemoStorage is used. Setting - $TEST_ZEO_HOST/TEST_ZEO_PORT environment variables allows you - to use a ZEO server instead. A file storage can be configured - by settting the $TEST_FILESTORAGE environment variable. + """Return a storage instance for running ZopeTestCase based tests. + + By default a DemoStorage is used. Setting + $TEST_ZEO_HOST/TEST_ZEO_PORT environment variables allows you to use + a ZEO server instead. A file storage can be configured by settting + the $TEST_FILESTORAGE environment variable. """ get = os.environ.get diff --git a/src/Testing/makerequest.py b/src/Testing/makerequest.py index c2526d98a9..2c2bf4291c 100644 --- a/src/Testing/makerequest.py +++ b/src/Testing/makerequest.py @@ -10,10 +10,8 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -""" -Facilitates unit tests which requires an acquirable REQUEST from -ZODB objects -""" +"""Facilitates unit tests which requires an acquirable REQUEST from ZODB +objects.""" from io import BytesIO @@ -23,10 +21,8 @@ def makerequest(app, stdout=None, environ=None): - """ - Adds an HTTPRequest at app.REQUEST, and returns - app.__of__(app.REQUEST). Useful for tests that need to acquire - REQUEST. + """Adds an HTTPRequest at app.REQUEST, and returns app.__of__(app.REQUEST). + Useful for tests that need to acquire REQUEST. Usage: import makerequest diff --git a/src/Testing/testbrowser.py b/src/Testing/testbrowser.py index f4b20380ed..5284e05aa9 100644 --- a/src/Testing/testbrowser.py +++ b/src/Testing/testbrowser.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Support for using zope.testbrowser from Zope2. -""" +"""Support for using zope.testbrowser from Zope2.""" import codecs @@ -66,7 +65,7 @@ def __init__(self, url=None, wsgi_app=None): super().__init__(url=url, wsgi_app=wsgi_app) def login(self, username, password): - """Set up a correct HTTP Basic Auth Authorization header""" + """Set up a correct HTTP Basic Auth Authorization header.""" if not isinstance(username, bytes): username = username.encode('UTF-8') if not isinstance(password, bytes): diff --git a/src/Testing/tests/test_makerequest.py b/src/Testing/tests/test_makerequest.py index 160584d48e..fe169c1126 100644 --- a/src/Testing/tests/test_makerequest.py +++ b/src/Testing/tests/test_makerequest.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Unit tests of makequest. -""" +"""Unit tests of makequest.""" import unittest diff --git a/src/Testing/tests/test_testbrowser.py b/src/Testing/tests/test_testbrowser.py index 7165291454..5fd0630bb0 100644 --- a/src/Testing/tests/test_testbrowser.py +++ b/src/Testing/tests/test_testbrowser.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Tests for the testbrowser module. -""" +"""Tests for the testbrowser module.""" import unittest from urllib.error import HTTPError @@ -137,7 +136,8 @@ def test_handle_errors_false_redirect(self): def test_handle_errors_false_HTTPExceptionHandler_in_app(self): """HTTPExceptionHandler does not handle errors if requested via WSGI. - This is needed when HTTPExceptionHandler is part of the WSGI pipeline. + This is needed when HTTPExceptionHandler is part of the WSGI + pipeline. """ class WSGITestAppWithHTTPExceptionHandler: """Minimized testbrowser.WSGITestApp with HTTPExceptionHandler.""" diff --git a/src/Testing/utils.py b/src/Testing/utils.py index 2e76b6457a..ec74e26514 100644 --- a/src/Testing/utils.py +++ b/src/Testing/utils.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -""" Some utility functions for unit tests -""" +"""Some utility functions for unit tests.""" import contextlib import sys diff --git a/src/ZPublisher/BaseRequest.py b/src/ZPublisher/BaseRequest.py index 7063cd0153..a2849389f3 100644 --- a/src/ZPublisher/BaseRequest.py +++ b/src/ZPublisher/BaseRequest.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -""" Basic ZPublisher request management. -""" +"""Basic ZPublisher request management.""" import types from urllib.parse import quote as urllib_quote @@ -169,16 +168,16 @@ def browserDefault(self, request): class BaseRequest: - """Provide basic ZPublisher request management + """Provide basic ZPublisher request management. - This object provides access to request data. Request data may - vary depending on the protocol used. + This object provides access to request data. Request data may vary + depending on the protocol used. Request objects are created by the object publisher and will be passed to published objects through the argument name, REQUEST. - The request object is a mapping object that represents a - collection of variable to value mappings. + The request object is a mapping object that represents a collection + of variable to value mappings. """ maybe_webdav_client = 1 @@ -197,8 +196,7 @@ class BaseRequest: __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, other=None, **kw): - """The constructor is not allowed to raise errors - """ + """The constructor is not allowed to raise errors.""" self.__doc__ = None # Make BaseRequest objects unpublishable if other is None: other = kw @@ -219,14 +217,13 @@ def close(self): self.clear() def processInputs(self): - """Do any input processing that could raise errors - """ + """Do any input processing that could raise errors.""" def __len__(self): return 1 def __setitem__(self, key, value): - """Set application variables + """Set application variables. This method is used to set a variable in the requests "other" category. @@ -236,13 +233,12 @@ def __setitem__(self, key, value): set = __setitem__ def get(self, key, default=None): - """Get a variable value - - Return a value for the required variable name. - The value will be looked up from one of the request data - categories. The search order is environment variables, - other variables, form data, and then cookies. + """Get a variable value. + Return a value for the required variable name. The value will be + looked up from one of the request data categories. The search + order is environment variables, other variables, form data, and + then cookies. """ if key == 'REQUEST': return self @@ -312,8 +308,7 @@ def values(self): return result def __str__(self): - L1 = list(self.items()) - L1.sort() + L1 = sorted(self.items()) return '\n'.join("%s:\t%s" % item for item in L1) __repr__ = __str__ @@ -351,7 +346,7 @@ def traverseName(self, ob, name): traverseName__roles__ = () def traverse(self, path, response=None, validated_hook=None): - """Traverse the object space + """Traverse the object space. The REQUEST must already have a PARENTS item with at least one object in it. This is typically the root object. @@ -440,7 +435,7 @@ def traverse(self, path, response=None, validated_hook=None): try: # We build parents in the wrong order, so we # need to make sure we reverse it when we're done. - while 1: + while True: bpth = getattr(object, '__before_publishing_traverse__', None) if bpth is not None: bpth(object, self) @@ -661,10 +656,10 @@ def post_traverse(self, f, args=()): """Add a callable object and argument tuple to be post-traversed. If traversal and authentication succeed, each post-traversal - pair is processed in the order in which they were added. - Each argument tuple is passed to its callable. If a callable - returns a value other than None, no more pairs are processed, - and the return value replaces the traversal result. + pair is processed in the order in which they were added. Each + argument tuple is passed to its callable. If a callable returns + a value other than None, no more pairs are processed, and the + return value replaces the traversal result. """ try: pairs = self._post_traverse @@ -680,8 +675,8 @@ def supports_retry(self): return 0 def _hold(self, object): - """Hold a reference to an object to delay it's destruction until mine - """ + """Hold a reference to an object to delay it's destruction until + mine.""" if self._held is not None: self._held = self._held + (object, ) diff --git a/src/ZPublisher/BaseResponse.py b/src/ZPublisher/BaseResponse.py index a637d95543..0b38202857 100644 --- a/src/ZPublisher/BaseResponse.py +++ b/src/ZPublisher/BaseResponse.py @@ -10,7 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""CGI Response Output formatter""" +"""CGI Response Output formatter.""" from zExceptions import BadRequest from zExceptions import Forbidden @@ -19,8 +19,7 @@ class BaseResponse: - """Base Response Class - """ + """Base Response Class.""" body = b'' debug_mode = None _auth = None @@ -67,9 +66,9 @@ def setCookie(self, name, value, **kw): """Set an HTTP cookie on the browser. The response will include an HTTP header that sets a cookie on - cookie-enabled browsers with a key "name" and value - "value". This overwrites any previously set value for the - cookie in the Response object. + cookie-enabled browsers with a key "name" and value "value". + This overwrites any previously set value for the cookie in the + Response object. """ cookies = self.cookies if name in cookies: @@ -87,8 +86,7 @@ def getHeader(self, name): """Get a header value. Returns the value associated with a HTTP return header, or - "None" if no such header has been set in the response - yet. + "None" if no such header has been set in the response yet. """ return self.headers.get(name, None) @@ -119,8 +117,8 @@ def write(self, data): The published object should first set any output headers or cookies on the response object. - Note that published objects must not generate any errors - after beginning stream-oriented output. + Note that published objects must not generate any errors after + beginning stream-oriented output. """ if isinstance(data, str): raise ValueError('Data must be binary.') @@ -131,8 +129,8 @@ def exception(self, fatal=0, info=None): The fatal argument indicates whether the error is fatal. - The info argument, if given should be a tuple with an - error type, value, and traceback. + The info argument, if given should be a tuple with an error + type, value, and traceback. """ def notFoundError(self, v=''): diff --git a/src/ZPublisher/BeforeTraverse.py b/src/ZPublisher/BeforeTraverse.py index ae2362d11a..1611dad8fe 100644 --- a/src/ZPublisher/BeforeTraverse.py +++ b/src/ZPublisher/BeforeTraverse.py @@ -10,7 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""BeforeTraverse interface and helper classes""" +"""BeforeTraverse interface and helper classes.""" from logging import getLogger @@ -24,11 +24,11 @@ def registerBeforeTraverse(container, object, app_handle, priority=99): """Register an object to be called before a container is traversed. 'app_handle' should be a string or other hashable value that - distinguishes the application of this object, and which must - be used in order to unregister the object. + distinguishes the application of this object, and which must be used + in order to unregister the object. - If the container will be pickled, the object must be a callable class - instance, not a function or method. + If the container will be pickled, the object must be a callable + class instance, not a function or method. 'priority' is optional, and determines the relative order in which registered objects will be called. @@ -41,7 +41,8 @@ def registerBeforeTraverse(container, object, app_handle, priority=99): def unregisterBeforeTraverse(container, app_handle): """Unregister a __before_traverse__ hook object, given its 'app_handle'. - Returns a list of unregistered objects.""" + Returns a list of unregistered objects. + """ btr = getattr(container, '__before_traverse__', {}) objects = [] for k in list(btr.keys()): @@ -56,7 +57,8 @@ def unregisterBeforeTraverse(container, app_handle): def queryBeforeTraverse(container, app_handle): """Find __before_traverse__ hook objects, given an 'app_handle'. - Returns a list of (priority, object) pairs.""" + Returns a list of (priority, object) pairs. + """ btr = getattr(container, '__before_traverse__', {}) objects = [] for k in btr.keys(): @@ -66,7 +68,7 @@ def queryBeforeTraverse(container, app_handle): def rewriteBeforeTraverse(container, btr): - """Rewrite the list of __before_traverse__ hook objects""" + """Rewrite the list of __before_traverse__ hook objects.""" container.__before_traverse__ = btr hookname = '__before_publishing_traverse__' dic = hasattr(container.__class__, hookname) @@ -76,8 +78,7 @@ def rewriteBeforeTraverse(container, btr): bpth = MultiHook(hookname, bpth, dic) setattr(container, hookname, bpth) - keys = list(btr.keys()) - keys.sort() + keys = sorted(btr.keys()) for key in keys: bpth.add(btr[key]) @@ -88,6 +89,7 @@ class MultiHook: MultiHook calls the named hook from the class of the container, then the prior hook, then all the hooks in its list. """ + def __init__(self, hookname='', prior=None, defined_in_class=False): # The default values are needed for unpickling instances of this class diff --git a/src/ZPublisher/Converters.py b/src/ZPublisher/Converters.py index df8845a3f3..4e96af8612 100644 --- a/src/ZPublisher/Converters.py +++ b/src/ZPublisher/Converters.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## - -"""Converters +"""Converters. Used by `ZPublisher.HTTPRequest` and `OFS.PropertyManager`. diff --git a/src/ZPublisher/HTTPRangeSupport.py b/src/ZPublisher/HTTPRangeSupport.py index 4f1d9f1cf3..b0b0a39c95 100644 --- a/src/ZPublisher/HTTPRangeSupport.py +++ b/src/ZPublisher/HTTPRangeSupport.py @@ -12,9 +12,10 @@ ############################################################################## """HTTP Range support utilities. -The RFC 2616 specification defines the 'Range' and 'If-Range' headers for -enabeling partial download of published resources. This module provides a -flag-interface and some support functions for implementing this functionality. +The RFC 2616 specification defines the 'Range' and 'If-Range' headers +for enabeling partial download of published resources. This module +provides a flag-interface and some support functions for implementing +this functionality. For an implementation example, see the File class in OFS/Image.py. """ @@ -31,11 +32,12 @@ def parseRange(header): """RFC 2616 (HTTP 1.1) Range header parsing. - Convert a range header to a list of slice indexes, returned as (start, end) - tuples. If no end was given, end is None. Note that the RFC specifies the - end offset to be inclusive, we return python convention indexes, where the - end is exclusive. Syntactically incorrect headers are to be ignored, so if - we encounter one we return None. + Convert a range header to a list of slice indexes, returned as + (start, end) tuples. If no end was given, end is None. Note that the + RFC specifies the end offset to be inclusive, we return python + convention indexes, where the end is exclusive. Syntactically + incorrect headers are to be ignored, so if we encounter one we + return None. """ ranges = [] @@ -131,11 +133,12 @@ def expandRanges(ranges, size): class HTTPRangeInterface(Interface): """Objects implementing this Interface support the HTTP Range header. - Objects implementing support for the HTTP Range header will return partial - content as specified in RFC 2616. Note that the'If-Range' header must - either be implemented correctly or result in a normal '200 OK' response at - all times. + Objects implementing support for the HTTP Range header will return + partial content as specified in RFC 2616. Note that the'If-Range' + header must either be implemented correctly or result in a normal + '200 OK' response at all times. - This interface specifies no methods, as this functionality can either be - implemented in the index_html or __call__ methods of a published object. + This interface specifies no methods, as this functionality can + either be implemented in the index_html or __call__ methods of a + published object. """ diff --git a/src/ZPublisher/HTTPRequest.py b/src/ZPublisher/HTTPRequest.py index bfc9de01e6..7bb16a30ef 100644 --- a/src/ZPublisher/HTTPRequest.py +++ b/src/ZPublisher/HTTPRequest.py @@ -11,8 +11,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -""" HTTP request management. -""" +"""HTTP request management.""" import codecs import html @@ -113,7 +112,7 @@ class NestedLoopExit(Exception): @implementer(IBrowserRequest) class HTTPRequest(BaseRequest): - """ Model HTTP request data. + """Model HTTP request data. This object provides access to request data. This includes, the input headers, form data, server data, and cookies. @@ -200,7 +199,7 @@ def clear(self): BaseRequest.clear(self) def setServerURL(self, protocol=None, hostname=None, port=None): - """ Set the parts of generated URLs. """ + """Set the parts of generated URLs.""" other = self.other server_url = other.get('SERVER_URL', '') if protocol is None and hostname is None and port is None: @@ -222,7 +221,7 @@ def setServerURL(self, protocol=None, hostname=None, port=None): return server_url def setVirtualRoot(self, path, hard=0): - """ Treat the current publishing object as a VirtualRoot """ + """Treat the current publishing object as a VirtualRoot.""" other = self.other if isinstance(path, str): path = path.split('/') @@ -235,14 +234,14 @@ def setVirtualRoot(self, path, hard=0): self._resetURLS() def getVirtualRoot(self): - """ Return a slash-separated virtual root. + """Return a slash-separated virtual root. If it is same as the physical root, return ''. """ return '/'.join([''] + self._script) def physicalPathToVirtualPath(self, path): - """ Remove the path to the VirtualRoot from a physical path """ + """Remove the path to the VirtualRoot from a physical path.""" if isinstance(path, str): path = path.split('/') rpp = self.other.get('VirtualRootPhysicalPath', ('',)) @@ -255,7 +254,7 @@ def physicalPathToVirtualPath(self, path): return path[i:] def physicalPathToURL(self, path, relative=0): - """ Convert a physical path into a URL in the current context """ + """Convert a physical path into a URL in the current context.""" path = self._script + list( map(quote, self.physicalPathToVirtualPath(path))) if relative: @@ -265,9 +264,11 @@ def physicalPathToURL(self, path, relative=0): return '/'.join(path) def physicalPathFromURL(self, URL): - """ Convert a URL into a physical path in the current context. - If the URL makes no sense in light of the current virtual - hosting context, a ValueError is raised.""" + """Convert a URL into a physical path in the current context. + + If the URL makes no sense in light of the current virtual + hosting context, a ValueError is raised. + """ other = self.other path = [_p for _p in URL.split('/') if _p] @@ -293,8 +294,7 @@ def _resetURLS(self): self._urls = () def getClientAddr(self): - """ The IP address of the client. - """ + """The IP address of the client.""" return self._client_addr def setupLocale(self): @@ -611,7 +611,7 @@ def processInputs( elif has_codec(type_name): # recode: assert not isinstance(item, FileUpload), \ - "cannot recode files" + "cannot recode files" item = item.encode( character_encoding, "surrogateescape") character_encoding = type_name @@ -955,11 +955,13 @@ def clone(self): return clone def getHeader(self, name, default=None, literal=False): - """Return the named HTTP header, or an optional default - argument or None if the header is not found. Note that - both original and CGI-ified header names are recognized, - e.g. 'Content-Type', 'CONTENT_TYPE' and 'HTTP_CONTENT_TYPE' - should all return the Content-Type header, if available. + """Return the named HTTP header, or an optional default argument or + None if the header is not found. + + Note that both original and CGI-ified header names are + recognized, e.g. 'Content-Type', 'CONTENT_TYPE' and + 'HTTP_CONTENT_TYPE' should all return the Content-Type header, + if available. """ environ = self.environ if not literal: @@ -977,24 +979,21 @@ def get(self, key, default=None, returnTaints=0, URLmatch=re.compile('URL(PATH)?([0-9]+)$').match, BASEmatch=re.compile('BASE(PATH)?([0-9]+)$').match, ): - """Get a variable value + """Get a variable value. Return a value for the variable key, or default if not found. - If key is "REQUEST", return the request. - Otherwise, the value will be looked up from one of the request data - categories. The search order is: - other (the target for explicitly set variables), - the special URL and BASE variables, - environment variables, - common variables (defined by the request class), - lazy variables (set with set_lazy), - form data and cookies. - - If returnTaints has a true value, then the access to - form and cookie variables returns values with special - protection against embedded HTML fragments to counter - some cross site scripting attacks. + If key is "REQUEST", return the request. Otherwise, the value + will be looked up from one of the request data categories. The + search order is: other (the target for explicitly set + variables), the special URL and BASE variables, environment + variables, common variables (defined by the request class), lazy + variables (set with set_lazy), form data and cookies. + + If returnTaints has a true value, then the access to form and + cookie variables returns values with special protection against + embedded HTML fragments to counter some cross site scripting + attacks. """ if key == 'REQUEST': @@ -1151,14 +1150,14 @@ def keys(self, returnTaints=0): # Cache URLN and BASEN in self.other. # This relies on a side effect of has_key. n = 0 - while 1: + while True: n = n + 1 key = "URL%s" % n if key not in self: # NOQA break n = 0 - while 1: + while True: n = n + 1 key = "BASE%s" % n if key not in self: # NOQA @@ -1172,8 +1171,7 @@ def keys(self, returnTaints=0): if returnTaints: keys.update(self.taintedform) - keys = list(keys.keys()) - keys.sort() + keys = sorted(keys.keys()) return keys @@ -1266,7 +1264,7 @@ def taintWrapper(self, enabled=TAINTING_ENABLED): # Original version: zope.publisher.http.HTTPRequest.shiftNameToApplication def shiftNameToApplication(self): - """see zope.publisher.interfaces.http.IVirtualHostRequest""" + """See zope.publisher.interfaces.http.IVirtualHostRequest.""" if len(self._steps) == 1: self._script.append(self._steps.pop()) self._resetURLS() @@ -1354,6 +1352,7 @@ def sane_environment(env): class ValueDescriptor: """(non data) descriptor to compute `value` from `file`.""" + def __get__(self, inst, owner=None): if inst is None: return self @@ -1381,8 +1380,9 @@ def __get__(self, inst, owner=None): class Global: """(non data) descriptor to access a (modul) global attribute.""" + def __init__(self, name): - """access global *name*.""" + """Access global *name*.""" self.name = name def __get__(self, inst, owner=None): @@ -1396,7 +1396,7 @@ class ValueAccessor: class FormField(SimpleNamespace, ValueAccessor): - """represent a single form field. + """Represent a single form field. Typical attributes: name @@ -1494,7 +1494,7 @@ def __init__(self, fp, environ): def _mp_charset(part): - """the charset of *part*.""" + """The charset of *part*.""" content_type = part.headers.get("Content-Type", "") _, options = parse_options_header(content_type) return options.get("charset") @@ -1502,7 +1502,7 @@ def _mp_charset(part): # Original version: zope.publisher.browser.FileUpload class FileUpload: - '''File upload objects + """File upload objects. File upload objects are used to represent file-uploaded data. @@ -1514,7 +1514,7 @@ class FileUpload: Note that file names in HTTP/1.1 use latin-1 as charset. See https://github.com/zopefoundation/Zope/pull/1094#issuecomment-1459654636 - ''' + """ # Allow access to attributes such as headers and filename so # that protected code can use DTML to work with FileUploads. @@ -1557,9 +1557,8 @@ def __iter__(self): return self.file.__iter__() def __bool__(self): - """FileUpload objects are considered false if their - filename is empty. - """ + """FileUpload objects are considered false if their filename is + empty.""" return bool(self.filename) def __next__(self): @@ -1680,14 +1679,14 @@ def use_builtin_xmlrpc(request): def taint(d): - """return as ``dict`` the items from *d* which require tainting. + """Return as ``dict`` the items from *d* which require tainting. *d* must be a ``dict`` with ``str`` keys and values recursively build from elementary values, ``list``, ``tuple``, ``record`` and ``dict``. """ def should_taint(v): - """check whether *v* needs tainting.""" + """Check whether *v* needs tainting.""" if isinstance(v, (list, tuple)): return any(should_taint(x) for x in v) if isinstance(v, (record, dict)): @@ -1699,7 +1698,7 @@ def should_taint(v): return should_be_tainted(v) def _taint(v): - """return a copy of *v* with tainted replacements. + """Return a copy of *v* with tainted replacements. In the copy, each ``str`` which requires tainting is replaced by the corresponding ``taint_string``. diff --git a/src/ZPublisher/HTTPResponse.py b/src/ZPublisher/HTTPResponse.py index 34f3072d88..ba2bb91dcc 100644 --- a/src/ZPublisher/HTTPResponse.py +++ b/src/ZPublisher/HTTPResponse.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -""" CGI Response Output formatter -""" +"""CGI Response Output formatter.""" import html import os import re @@ -153,7 +152,7 @@ def make_content_disposition(disposition, file_name): class HTTPBaseResponse(BaseResponse): - """ An object representation of an HTTP response. + """An object representation of an HTTP response. The Response type encapsulates all possible responses to HTTP requests. Responses are normally created by the object publisher. @@ -192,8 +191,7 @@ def __init__(self, headers=None, stdout=None, stderr=None): - """ Create a new response using the given values. - """ + """Create a new response using the given values.""" self.accumulated_headers = [] self.cookies = {} self.headers = {} @@ -224,7 +222,7 @@ def text(self, value): self.body = value.encode(self.charset) def redirect(self, location, status=302, lock=0): - """Cause a redirection without raising an error""" + """Cause a redirection without raising an error.""" if isinstance(location, HTTPRedirection): status = location.getStatus() location = location.headers['Location'] @@ -260,19 +258,18 @@ def redirect(self, location, status=302, lock=0): return location def retry(self): - """ Return a cloned response object to be used in a retry attempt. - """ + """Return a cloned response object to be used in a retry attempt.""" # This implementation is a bit lame, because it assumes that # only stdout stderr were passed to the constructor. OTOH, I # think that that's all that is ever passed. return self.__class__(stdout=self.stdout, stderr=self.stderr) def setStatus(self, status, reason=None, lock=None): - """ Set the HTTP status code of the response + """Set the HTTP status code of the response. o The argument may either be an integer or a string from the - 'status_reasons' dict values: status messages will be converted - to the correct integer value. + 'status_reasons' dict values: status messages will be converted + to the correct integer value. """ if self._locked_status: # Don't change the response status. @@ -304,7 +301,7 @@ def setStatus(self, status, reason=None, lock=None): self._locked_status = 1 def setCookie(self, name, value, quoted=True, **kw): - """ Set an HTTP cookie. + """Set an HTTP cookie. The response will include an HTTP header that sets a cookie on cookie-enabled browsers with a key "name" and value @@ -335,7 +332,7 @@ def setCookie(self, name, value, quoted=True, **kw): cookies[name] = cookie def appendCookie(self, name, value): - """ Set an HTTP cookie. + """Set an HTTP cookie. Returns an HTTP header that sets a cookie on cookie-enabled browsers with a key "name" and value "value". If a value for the @@ -358,7 +355,7 @@ def appendCookie(self, name, value): cookie['value'] = value def expireCookie(self, name, **kw): - """ Clear an HTTP cookie. + """Clear an HTTP cookie. The response will include an HTTP header that will remove the cookie corresponding to "name" on the client, if one exists. This is @@ -379,25 +376,25 @@ def expireCookie(self, name, **kw): self.setCookie(name, value='deleted', **d) def getHeader(self, name, literal=0): - """ Get a previously set header value. + """Get a previously set header value. - Return the value associated with a HTTP return header, or - None if no such header has been set in the response - yet. + Return the value associated with a HTTP return header, or None + if no such header has been set in the response yet. - If the 'literal' flag is true, preserve the case of the header name; - otherwise lower-case the header name before looking up the value. + If the 'literal' flag is true, preserve the case of the header + name; otherwise lower-case the header name before looking up the + value. """ key = literal and name or name.lower() return self.headers.get(key, None) def setHeader(self, name, value, literal=0, scrubbed=False): - """ Set an HTTP return header on the response. + """Set an HTTP return header on the response. Replay any existing value set for the header. - If the 'literal' flag is true, preserve the case of the header name; - otherwise the header name will be lowercased. + If the 'literal' flag is true, preserve the case of the header + name; otherwise the header name will be lowercased. 'scrubbed' is for internal use, to indicate that another API has already removed any CRLF from the name and value. @@ -421,11 +418,11 @@ def setHeader(self, name, value, literal=0, scrubbed=False): self.headers[name] = value def appendHeader(self, name, value, delimiter=", "): - """ Append a value to an HTTP return header. + """Append a value to an HTTP return header. - Set an HTTP return header "name" with value "value", - appending it following a comma if there was a previous value - set for the header. + Set an HTTP return header "name" with value "value", appending + it following a comma if there was a previous value set for the + header. 'name' is always lowercased before use. """ @@ -441,12 +438,12 @@ def appendHeader(self, name, value, delimiter=", "): self.setHeader(name, h, scrubbed=True) def addHeader(self, name, value): - """ Set a new HTTP return header with the given value, + """Set a new HTTP return header with the given value, Retain any previously set headers with the same name. - Note that this API appends to the 'accumulated_headers' attribute; - it does not update the 'headers' mapping. + Note that this API appends to the 'accumulated_headers' + attribute; it does not update the 'headers' mapping. """ name, value = _scrubHeader(name, value) self.accumulated_headers.append((name, value)) @@ -503,13 +500,13 @@ def isHTML(self, text): return False def setBody(self, body, title='', is_error=False, lock=None): - """ Set the body of the response + """Set the body of the response. Sets the return body equal to the (string) argument "body". Also updates the "content-length" return header. - If the body is already locked via a previous call, do nothing and - return None. + If the body is already locked via a previous call, do nothing + and return None. You can also specify a title, in which case the title and body will be wrapped up in html, head, title, and body tags. @@ -517,13 +514,13 @@ def setBody(self, body, title='', is_error=False, lock=None): If body has an 'asHTML' method, replace it by the result of that method. - If body is now bytes, bytearray or memoryview, convert it to bytes. - Else, either try to convert it to bytes or use an intermediate string - representation which is then converted to bytes, depending on the - content type. + If body is now bytes, bytearray or memoryview, convert it to + bytes. Else, either try to convert it to bytes or use an + intermediate string representation which is then converted to + bytes, depending on the content type. - If is_error is true, format the HTML as a Zope error message instead - of a generic HTML page. + If is_error is true, format the HTML as a Zope error message + instead of a generic HTML page. Return 'self' (XXX as a true value?). """ @@ -620,39 +617,39 @@ def setBody(self, body, title='', is_error=False, lock=None): return self def enableHTTPCompression(self, REQUEST={}, force=0, disable=0, query=0): - """Enable HTTP Content Encoding with gzip compression if possible - - REQUEST -- used to check if client can accept compression - force -- set true to ignore REQUEST headers - disable -- set true to disable compression - query -- just return if compression has been previously requested - - returns -- 1 if compression will be attempted, 2 if compression - is forced, 0 if no compression - - The HTTP specification allows for transfer encoding and content - encoding. Unfortunately many web browsers still do not support - transfer encoding, but they all seem to support content encoding. - - This function is designed to be called on each request to specify - on a request-by-request basis that the response content should - be compressed. - - The REQUEST headers are used to determine if the client accepts - gzip content encoding. The force parameter can force the use - of gzip encoding regardless of REQUEST, and the disable parameter - can be used to "turn off" previously enabled encoding (but note - that any existing content-encoding header will not be changed). - The query parameter can be used to determine the if compression - has been previously requested. - - In setBody, the major mime type is used to determine if content - encoding should actually be performed. - - By default, image types are not compressed. - Additional major mime types can be specified by setting the - environment variable DONT_GZIP_MAJOR_MIME_TYPES to a comma-seperated - list of major mime types that should also not be gzip compressed. + """Enable HTTP Content Encoding with gzip compression if possible. + + REQUEST -- used to check if client can accept compression + force -- set true to ignore REQUEST headers + disable -- set true to disable compression + query -- just return if compression has been previously requested + + returns -- 1 if compression will be attempted, 2 if compression + is forced, 0 if no compression + + The HTTP specification allows for transfer encoding and content + encoding. Unfortunately many web browsers still do not support + transfer encoding, but they all seem to support content encoding. + + This function is designed to be called on each request to specify + on a request-by-request basis that the response content should + be compressed. + + The REQUEST headers are used to determine if the client accepts + gzip content encoding. The force parameter can force the use + of gzip encoding regardless of REQUEST, and the disable parameter + can be used to "turn off" previously enabled encoding (but note + that any existing content-encoding header will not be changed). + The query parameter can be used to determine the if compression + has been previously requested. + + In setBody, the major mime type is used to determine if content + encoding should actually be performed. + + By default, image types are not compressed. + Additional major mime types can be specified by setting the + environment variable DONT_GZIP_MAJOR_MIME_TYPES to a comma-seperated + list of major mime types that should also not be gzip compressed. """ if query: return self.use_HTTP_content_compression @@ -700,7 +697,7 @@ def _cookie_list(self): return cookie_list def listHeaders(self): - """ Return a list of (key, value) pairs for our headers. + """Return a list of (key, value) pairs for our headers. o Do appropriate case normalization. @@ -921,8 +918,7 @@ def exception(self, fatal=0, info=None, abort=1): return body def finalize(self): - """ Set headers required by various parts of protocol. - """ + """Set headers required by various parts of protocol.""" body = self.body if 'content-length' not in self.headers and \ 'transfer-encoding' not in self.headers: @@ -930,8 +926,7 @@ def finalize(self): return "%d %s" % (self.status, self.errmsg), self.listHeaders() def write(self, data): - """ - Return data as a stream + """Return data as a stream. HTML data may be returned using a stream-oriented interface. This allows the browser to display partial results while @@ -940,8 +935,8 @@ def write(self, data): The published object should first set any output headers or cookies on the response object. - Note that published objects must not generate any errors - after beginning stream-oriented output. + Note that published objects must not generate any errors after + beginning stream-oriented output. """ if not self._wrote: notify(pubevents.PubBeforeStreaming(self)) @@ -954,8 +949,7 @@ def write(self, data): class WSGIResponse(HTTPBaseResponse): - """A response object for WSGI - """ + """A response object for WSGI.""" _streaming = 0 _http_version = None _server_version = None @@ -1127,7 +1121,7 @@ class HeaderEncodingRegistry(dict): """ def register(self, header, encoder, **kw): - """register *encoder* as encoder for header *header*. + """Register *encoder* as encoder for header *header*. If *encoder* is `None`, this indicates that *header* should not get encoded. @@ -1143,7 +1137,7 @@ def register(self, header, encoder, **kw): self[header] = encoder, kw def unregister(self, header): - """remove any registration for *header*. + """Remove any registration for *header*. *header* can be either a header name or `None`. In the latter case, a default registration is removed. @@ -1154,9 +1148,10 @@ def unregister(self, header): del self[header] def encode(self, header, value): - """encode *value* as specified for *header*. + """Encode *value* as specified for *header*. - encoding takes only place if *value* contains non ISO-8859-1 chars. + encoding takes only place if *value* contains non ISO-8859-1 + chars. """ if not isinstance(value, str): return value @@ -1184,16 +1179,15 @@ def encode_words(value): def encode_params(value): """RFC 5987(8187) (specialized from RFC 2231) parameter encoding. - This encodes parameters as specified by RFC 5987 using - fixed `UTF-8` encoding (as required by RFC 8187). - However, all parameters with non latin-1 values are - automatically transformed and a `*` suffixed parameter is added - (RFC 8187 allows this only for parameters explicitly specified - to have this behavior). + This encodes parameters as specified by RFC 5987 using fixed `UTF-8` + encoding (as required by RFC 8187). However, all parameters with non + latin-1 values are automatically transformed and a `*` suffixed + parameter is added (RFC 8187 allows this only for parameters + explicitly specified to have this behavior). - Many HTTP headers use `,` separated lists. For simplicity, - such headers are not supported (we would need to recognize - `,` inside quoted strings as special). + Many HTTP headers use `,` separated lists. For simplicity, such + headers are not supported (we would need to recognize `,` inside + quoted strings as special). """ params = [] for p in _parseparam(";" + value): diff --git a/src/ZPublisher/Iterators.py b/src/ZPublisher/Iterators.py index e549ad5b45..187b5cbbcf 100644 --- a/src/ZPublisher/Iterators.py +++ b/src/ZPublisher/Iterators.py @@ -5,45 +5,35 @@ class IUnboundStreamIterator(Interface): - """ - An iterator with unknown length that can be published. - """ + """An iterator with unknown length that can be published.""" def __next__(): - """ - Return a sequence of bytes out of the bytestream, or raise - StopIeration if we've reached the end of the bytestream. - """ + """Return a sequence of bytes out of the bytestream, or raise + StopIeration if we've reached the end of the bytestream.""" class IStreamIterator(IUnboundStreamIterator): - """ - An iterator with known length that can be published. - - IStreamIterators must not read from the object database. - After the application finishes interpreting a request and - returns an iterator to be processed asynchronously, it closes - the ZODB connection. If the iterator then tries to load some - ZODB object, ZODB would do one of two things. If the connection - is still closed, ZODB would raise an error. If the connection - happens to be re-opened by another thread, ZODB might allow it, - but it has a chance of going insane if it happens to be loading - or storing something in the other thread at the same time. + """An iterator with known length that can be published. + + IStreamIterators must not read from the object database. After the + application finishes interpreting a request and returns an iterator + to be processed asynchronously, it closes the ZODB connection. If + the iterator then tries to load some ZODB object, ZODB would do one + of two things. If the connection is still closed, ZODB would raise + an error. If the connection happens to be re-opened by another + thread, ZODB might allow it, but it has a chance of going insane if + it happens to be loading or storing something in the other thread at + the same time. """ def __len__(): - """ - Return an integer representing the length of the object - in bytes. - """ + """Return an integer representing the length of the object in bytes.""" @implementer(IStreamIterator) class filestream_iterator(io.FileIO): - """ - A FileIO subclass which implements an iterator that returns a - fixed-sized sequence of bytes. - """ + """A FileIO subclass which implements an iterator that returns a fixed- + sized sequence of bytes.""" def __init__(self, name, mode='rb', bufsize=-1, streamsize=1 << 16): super().__init__(name, mode) diff --git a/src/ZPublisher/WSGIPublisher.py b/src/ZPublisher/WSGIPublisher.py index af66908f61..1e976246ad 100644 --- a/src/ZPublisher/WSGIPublisher.py +++ b/src/ZPublisher/WSGIPublisher.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -""" Python Object Publisher -- Publish Python objects on web servers -""" +"""Python Object Publisher -- Publish Python objects on web servers.""" import sys from _thread import allocate_lock from contextlib import closing diff --git a/src/ZPublisher/__init__.py b/src/ZPublisher/__init__.py index cf4b87548e..d60eac129a 100644 --- a/src/ZPublisher/__init__.py +++ b/src/ZPublisher/__init__.py @@ -13,8 +13,7 @@ class Retry(Exception): - """Raise this to retry a request - """ + """Raise this to retry a request.""" def __init__(self, t=None, v=None, tb=None): self._args = t, v, tb diff --git a/src/ZPublisher/cookie.py b/src/ZPublisher/cookie.py index 60c9dac85c..bef7d95442 100644 --- a/src/ZPublisher/cookie.py +++ b/src/ZPublisher/cookie.py @@ -53,7 +53,7 @@ class DefaultCookieParamPolicy: @staticmethod def parameters(name, attrs): - """adds ``Expires`` if not present and ``Max-Age`` is set.""" + """Adds ``Expires`` if not present and ``Max-Age`` is set.""" for pn, pv in attrs.items(): if pn != "value": yield (pn, pv) @@ -77,12 +77,12 @@ class DefaultCookieValuePolicy: @staticmethod def dump(name, value): - """simply quote *value*.""" + """Simply quote *value*.""" return quote(value) @staticmethod def load(name, value): - """simply unquote *value*.""" + """Simply unquote *value*.""" return unquote(value) @@ -107,12 +107,13 @@ class CookieParameterRegistry: It maintains 2 maps: one to normalize parameter names and one to check and convert parameter values. """ + def __init__(self): self._normalize = {} self._convert = {} def register(self, name, converter, aliases=()): - """register cookie parameter *name* with *converter* and *aliases*. + """Register cookie parameter *name* with *converter* and *aliases*. *converter* is a function which will be applied to parameter values and which is expected to either @@ -136,7 +137,7 @@ def register(self, name, converter, aliases=()): self._normalize[a] = name def convert(self, name, value): - """check and convert *name* and *value* for parameter *name*. + """Check and convert *name* and *value* for parameter *name*. Raises an exception in case of errors; otherwise, returns *normalized name*, *converted value*. @@ -186,7 +187,7 @@ def tzname(self, dt): def rfc1123_converter(value): - """convert *value* into an RFC1123 date. + """Convert *value* into an RFC1123 date. *value* can be a string (assumed already in the required form), a Python `datetime` (assumed to be in the UTC time zone, if naive), @@ -216,7 +217,7 @@ def rfc1123_converter(value): # ``Max-Age`` def int_converter(value): - """check for *int* value.""" + """Check for *int* value.""" int(value) return str(value) @@ -226,7 +227,7 @@ def int_converter(value): # ``Domain`` def domain_converter(value): - """convert *value* into an internationalized domain name. + """Convert *value* into an internationalized domain name. Note: The Python infrastructure supports IDNA2003, but RFC6265 calls for IDNA2008. IDNA2008 is implemented by @@ -259,7 +260,7 @@ def domain_converter(value): def path_converter(value): - """convert *value* to a cookie path. + """Convert *value* to a cookie path. The convertion is based on ``absolute_url_path``. If *value* lacks this method, it is assumed to be a string. @@ -344,7 +345,7 @@ def str_converter(value): ########################################################################### # Auxiliaries def to_str(s): - """convert bytes to ``str``.""" + """Convert bytes to ``str``.""" if not isinstance(s, str): s = s.decode("utf-8") return s diff --git a/src/ZPublisher/interfaces.py b/src/ZPublisher/interfaces.py index 46f30e1c20..f24309fbec 100644 --- a/src/ZPublisher/interfaces.py +++ b/src/ZPublisher/interfaces.py @@ -8,55 +8,53 @@ class IPubEvent(Interface): - '''Base class for publication events. + """Base class for publication events. Publication events are notified in 'ZPublisher.Publish.publish' to inform about publications (aka requests) and their fate. - ''' + """ request = Attribute('The request being affected') class IPubStart(IPubEvent): - '''Event notified at the beginning of 'ZPublisher.Publish.publish'.''' + """Event notified at the beginning of 'ZPublisher.Publish.publish'.""" class IPubEnd(IPubEvent): - '''Event notified after request processing. + """Event notified after request processing. Note that a retried request ends before the retrial, the retrial itself is considered a new event. - ''' + """ class IPubSuccess(IPubEnd): - '''A successful request processing.''' + """A successful request processing.""" class IPubFailure(IPubEnd): - '''A failed request processing. + """A failed request processing. Note: If a subscriber to 'IPubSuccess' raises an exception, then 'IPubFailure' may be notified in addition to 'IPubSuccess'. - ''' + """ exc_info = Attribute( '''The exception info as returned by 'sys.exc_info()'.''') retry = Attribute('Whether the request will be retried') class IPubAfterTraversal(IPubEvent): - """notified after traversal and an (optional) authentication.""" + """Notified after traversal and an (optional) authentication.""" class IPubBeforeCommit(IPubEvent): - """notified immediately before the transaction commit (i.e. after the main - request processing is finished). - """ + """Notified immediately before the transaction commit (i.e. after the main + request processing is finished).""" class IPubBeforeAbort(IPubEvent): - """notified immediately before the transaction abort (i.e. after the main - request processing is finished, and there was an error). - """ + """Notified immediately before the transaction abort (i.e. after the main + request processing is finished, and there was an error).""" exc_info = Attribute( '''The exception info as returned by 'sys.exc_info()'.''') retry = Attribute('Whether the request will be retried') @@ -64,8 +62,10 @@ class IPubBeforeAbort(IPubEvent): class IPubBeforeStreaming(Interface): """Event fired just before a streaming response is initiated, i.e. when - something calls response.write() for the first time. Note that this is - carries a reference to the *response*, not the request. + something calls response.write() for the first time. + + Note that this is carries a reference to the *response*, not the + request. """ response = Attribute("The current HTTP response") @@ -73,9 +73,9 @@ class IPubBeforeStreaming(Interface): class UseTraversalDefault(Exception): """Indicate default traversal in ``__bobo_traverse__`` - This exception can be raised by '__bobo_traverse__' implementations to - indicate that it has no special casing for the given name and that standard - traversal logic should be applied. + This exception can be raised by '__bobo_traverse__' implementations + to indicate that it has no special casing for the given name and + that standard traversal logic should be applied. """ @@ -85,7 +85,7 @@ class UseTraversalDefault(Exception): class IXmlrpcChecker(Interface): """Utility interface to control Zope's built-in XML-RPC support.""" def __call__(request): - """return true, when Zope's internal XML-RPC support should be used. + """Return true, when Zope's internal XML-RPC support should be used. Only called for a non-SOAP POST request whose `Content-Type` contains `text/xml` (any other request automatically does not @@ -107,7 +107,7 @@ class ICookieParamPolicy(Interface): """Utility interface to customize cookie parameter handling.""" def parameters(name, attrs): - """generate the parameters for the cookie with *name* and *attrs*. + """Generate the parameters for the cookie with *name* and *attrs*. Each parameter is described by a pair *normalized_name*, *normalized_value*. @@ -137,7 +137,7 @@ def parameters(name, attrs): """ def check_consistency(name, attrs): - """raise ``ValueError`` if the cookie definition is inconsistent. + """Raise ``ValueError`` if the cookie definition is inconsistent. E.g. ``SameSite=None`` is allowed only together with ``Secure``. """ diff --git a/src/ZPublisher/mapply.py b/src/ZPublisher/mapply.py index d2259adcee..4f75e1b166 100644 --- a/src/ZPublisher/mapply.py +++ b/src/ZPublisher/mapply.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Provide an apply-like facility that works with any mapping object -""" +"""Provide an apply-like facility that works with any mapping object.""" from inspect import getfullargspec import zope.publisher.publish diff --git a/src/ZPublisher/pubevents.py b/src/ZPublisher/pubevents.py index b097929593..a29f544acc 100644 --- a/src/ZPublisher/pubevents.py +++ b/src/ZPublisher/pubevents.py @@ -1,12 +1,12 @@ -'''Publication events. +"""Publication events. -They are notified in 'ZPublisher.Publish.publish' and -inform about publications and their fate. +They are notified in 'ZPublisher.Publish.publish' and inform about +publications and their fate. -Subscriptions can be used for all kinds of request supervision, -e.g. request and error rate determination, writing high resolution logfiles +Subscriptions can be used for all kinds of request supervision, e.g. +request and error rate determination, writing high resolution logfiles for detailed time related analysis, inline request monitoring. -''' +""" from zope.interface import implementer from ZPublisher.interfaces import IPubAfterTraversal from ZPublisher.interfaces import IPubBeforeAbort @@ -26,17 +26,17 @@ def __init__(self, request): @implementer(IPubStart) class PubStart(_Base): - '''notified at the beginning of 'ZPublisher.Publish.publish'.''' + """Notified at the beginning of 'ZPublisher.Publish.publish'.""" @implementer(IPubSuccess) class PubSuccess(_Base): - '''notified at successful request end.''' + """Notified at successful request end.""" @implementer(IPubFailure) class PubFailure: - '''notified at failed request end.''' + """Notified at failed request end.""" def __init__(self, request, exc_info, retry): self.request, self.exc_info, self.retry = request, exc_info, retry @@ -44,17 +44,17 @@ def __init__(self, request, exc_info, retry): @implementer(IPubAfterTraversal) class PubAfterTraversal(_Base): - """notified after traversal and an (optional) authentication.""" + """Notified after traversal and an (optional) authentication.""" @implementer(IPubBeforeCommit) class PubBeforeCommit(_Base): - """notified immediately before the commit.""" + """Notified immediately before the commit.""" @implementer(IPubBeforeAbort) class PubBeforeAbort(_Base): - """notified immediately before an abort.""" + """Notified immediately before an abort.""" def __init__(self, request, exc_info, retry): self.request, self.exc_info, self.retry = request, exc_info, retry @@ -62,8 +62,7 @@ def __init__(self, request, exc_info, retry): @implementer(IPubBeforeStreaming) class PubBeforeStreaming: - """Notified immediately before streaming via response.write() commences - """ + """Notified immediately before streaming via response.write() commences.""" def __init__(self, response): self.response = response diff --git a/src/ZPublisher/tests/testBaseRequest.py b/src/ZPublisher/tests/testBaseRequest.py index 32fdbfcb3f..a7b52e0813 100644 --- a/src/ZPublisher/tests/testBaseRequest.py +++ b/src/ZPublisher/tests/testBaseRequest.py @@ -116,6 +116,7 @@ def __before_publishing_traverse__(self, object, REQUEST): def _makeObjectWithBD(self): class DummyObjectWithBD(self._makeBasicObjectClass()): """Dummy class with __browser_default__.""" + def __browser_default__(self, REQUEST): if REQUEST['_test_counter'] < 100: REQUEST['_test_counter'] += 1 @@ -128,13 +129,13 @@ def _makeObjectWithBBT(self): from ZPublisher.interfaces import UseTraversalDefault class _DummyResult: - ''' ''' + """""" + def __init__(self, tag): self.tag = tag class DummyObjectWithBBT(self._makeBasicObjectClass()): - """ Dummy class with __bobo_traverse__ - """ + """Dummy class with __bobo_traverse__""" default = _DummyResult('Default') def __bobo_traverse__(self, REQUEST, name): @@ -167,6 +168,7 @@ def _makeObjectWithEmptyDocstring(self): class DummyObjectWithEmptyDocstring(Implicit): "" + def view(self): """Attribute with docstring.""" return 'view content' @@ -508,7 +510,7 @@ def _dummyInterface(self): return self._dummy_interface class IDummy(Interface): - """IDummy""" + """IDummy.""" self._dummy_interface = IDummy return IDummy @@ -534,11 +536,11 @@ def __init__(self, name): self.name = name def meth(self): - """doc""" + """doc.""" return 'meth on %s' % self.name def methonly(self): - """doc""" + """doc.""" return 'methonly on %s' % self.name return DummyObjectZ3WithAttr(name) diff --git a/src/ZPublisher/tests/testBeforeTraverse.py b/src/ZPublisher/tests/testBeforeTraverse.py index 1e40e7f009..6ca7aa498b 100644 --- a/src/ZPublisher/tests/testBeforeTraverse.py +++ b/src/ZPublisher/tests/testBeforeTraverse.py @@ -19,8 +19,7 @@ def makeBaseRequest(root): class DummyObjectBasic(Implicit): - """ Dummy class with docstring. - """ + """Dummy class with docstring.""" pass @@ -32,11 +31,10 @@ def __call__(self, *args): def testBeforeTraverse(self): - """ - Zope supports a 'before traverse' hook that is used for several - features, including 'Site Access Rules'. It is implemented using a - special API for registering hooks, and the hooks themselves are - called during traversal by ZPublisher. + """Zope supports a 'before traverse' hook that is used for several + features, including 'Site Access Rules'. It is implemented using a special + API for registering hooks, and the hooks themselves are called during + traversal by ZPublisher. >>> import sys >>> import logging @@ -136,7 +134,6 @@ def testBeforeTraverse(self): >>> logger.setLevel(level) >>> logger.handlers = handlers[:] - """ diff --git a/src/ZPublisher/tests/testHTTPRequest.py b/src/ZPublisher/tests/testHTTPRequest.py index d7fe18e4d3..3e2db76480 100644 --- a/src/ZPublisher/tests/testHTTPRequest.py +++ b/src/ZPublisher/tests/testHTTPRequest.py @@ -275,8 +275,7 @@ def test_processInputs_wo_marshalling(self): ('multi', '1'), ('multi', '2')) req = self._processInputs(inputs) - formkeys = list(req.form.keys()) - formkeys.sort() + formkeys = sorted(req.form.keys()) self.assertEqual( formkeys, ['foo', 'key', 'multi', 'number', 'spacey key', 'spam']) @@ -299,8 +298,7 @@ def test_processInputs_w_simple_marshalling(self): ('morewords:text', 'one\ntwo\n')) req = self._processInputs(inputs) - formkeys = list(req.form.keys()) - formkeys.sort() + formkeys = sorted(req.form.keys()) self.assertEqual( formkeys, ['2tokens', 'accountedfor', 'aday', 'bign', @@ -336,8 +334,7 @@ def test_processInputs_w_unicode_conversions(self): warnings.simplefilter('ignore') req = self._processInputs(inputs) - formkeys = list(req.form.keys()) - formkeys.sort() + formkeys = sorted(req.form.keys()) self.assertEqual( formkeys, ['nouconverter', 'ulines', 'ustring', 'utext', 'utokens']) @@ -364,8 +361,7 @@ def test_processInputs_w_simple_containers(self): ('setrec.foo:records', 'spam'), ('setrec.bar:records', 'eggs')) req = self._processInputs(inputs) - formkeys = list(req.form.keys()) - formkeys.sort() + formkeys = sorted(req.form.keys()) self.assertEqual( formkeys, ['alist', 'atuple', 'oneitem', 'oneitemtuple', 'onerec', 'setrec']) @@ -394,8 +390,7 @@ def test_processInputs_w_marshalling_into_sequences(self): ('tlist:tokens:list', 'one two'), ('tlist:list:tokens', '3 4')) req = self._processInputs(inputs) - formkeys = list(req.form.keys()) - formkeys.sort() + formkeys = sorted(req.form.keys()) self.assertEqual(formkeys, ['ftuple', 'ilist', 'tlist']) self.assertEqual(req['ilist'], [1, 2, 3]) @@ -424,8 +419,7 @@ def test_processInputs_w_records_w_sequences(self): ('setrec.ituple:tuple:int:records', '2')) req = self._processInputs(inputs) - formkeys = list(req.form.keys()) - formkeys.sort() + formkeys = sorted(req.form.keys()) self.assertEqual(formkeys, ['onerec', 'setrec']) self.assertEqual(req['onerec'].name, 'foo') @@ -471,8 +465,7 @@ def test_processInputs_w_defaults(self): ) req = self._processInputs(inputs) - formkeys = list(req.form.keys()) - formkeys.sort() + formkeys = sorted(req.form.keys()) self.assertEqual( formkeys, ['alist', 'bar', 'explicitlist', 'foo', 'setrec']) @@ -504,8 +497,7 @@ def test_processInputs_wo_marshalling_w_Taints(self): ('tallmulti', '<1>'), ('tallmulti', '<2>')) req = self._processInputs(inputs) - taintedformkeys = list(req.taintedform.keys()) - taintedformkeys.sort() + taintedformkeys = sorted(req.taintedform.keys()) self.assertEqual( taintedformkeys, ['', 'tainted', @@ -526,8 +518,7 @@ def test_processInputs_w_simple_marshalling_w_taints(self): ('tmorewords:text', '\n')) req = self._processInputs(inputs) - taintedformkeys = list(req.taintedform.keys()) - taintedformkeys.sort() + taintedformkeys = sorted(req.taintedform.keys()) self.assertEqual( taintedformkeys, ['', '', '', @@ -557,8 +548,7 @@ def test_processInputs_w_unicode_w_taints(self): warnings.simplefilter('ignore') req = self._processInputs(inputs) - taintedformkeys = list(req.taintedform.keys()) - taintedformkeys.sort() + taintedformkeys = sorted(req.taintedform.keys()) self.assertEqual( taintedformkeys, ['tdeferulines', 'tdeferutokens', @@ -605,8 +595,7 @@ def test_processInputs_w_simple_containers_w_taints(self): ('tdeferdefersetrec.bar:records', '')) req = self._processInputs(inputs) - taintedformkeys = list(req.taintedform.keys()) - taintedformkeys.sort() + taintedformkeys = sorted(req.taintedform.keys()) self.assertEqual( taintedformkeys, ['', 'tdeferalist', @@ -657,8 +646,7 @@ def test_processInputs_w_records_w_sequences_tainted(self): ) req = self._processInputs(inputs) - taintedformkeys = list(req.taintedform.keys()) - taintedformkeys.sort() + taintedformkeys = sorted(req.taintedform.keys()) self.assertEqual( taintedformkeys, ['tdeferfirstsetrec', 'tdeferonerec', @@ -711,8 +699,7 @@ def test_processInputs_w_defaults_w_taints(self): ('srdoesnotapply.foo:records', 'ham')) req = self._processInputs(inputs) - taintedformkeys = list(req.taintedform.keys()) - taintedformkeys.sort() + taintedformkeys = sorted(req.taintedform.keys()) self.assertEqual( taintedformkeys, ['tdeferbar', 'tdeferlist', @@ -753,8 +740,7 @@ def test_processInputs_w_dotted_name_as_tuple(self): ('name.:tuple', 'name with dot as tuple'),) req = self._processInputs(inputs) - formkeys = list(req.form.keys()) - formkeys.sort() + formkeys = sorted(req.form.keys()) self.assertEqual(formkeys, ['name.']) self.assertEqual(req['name.'], ('name with dot as tuple',)) @@ -1547,6 +1533,7 @@ class TestSearchType(unittest.TestCase): see "https://github.com/zopefoundation/Zope/pull/512" """ + def check(self, val, expect): mo = search_type(val) if expect is None: @@ -1571,7 +1558,8 @@ def test_special(self): class _Unseekable: - """Auxiliary class emulating an unseekable file like object""" + """Auxiliary class emulating an unseekable file like object.""" + def __init__(self, file): for m in ("read", "readline", "close", "__del__"): setattr(self, m, getattr(file, m)) diff --git a/src/ZPublisher/tests/testHTTPResponse.py b/src/ZPublisher/tests/testHTTPResponse.py index f0fcd301fa..71a6a7dcdb 100644 --- a/src/ZPublisher/tests/testHTTPResponse.py +++ b/src/ZPublisher/tests/testHTTPResponse.py @@ -628,9 +628,8 @@ def test_setBody_list(self): self.assertEqual(resp.body, str(body).encode('ascii')) def test_setBody_io(self): - """ - Test that BytesIO.getbuffer() can be used to write a binary response. - """ + """Test that BytesIO.getbuffer() can be used to write a binary + response.""" from io import BytesIO resp = self._makeOne() value = b'\x00\x01' @@ -639,10 +638,8 @@ def test_setBody_io(self): self.assertEqual(resp.body, value) def test_setBody_by_content_type(self): - """ - Check that a list as response is treated differently depending on the - content type. - """ + """Check that a list as response is treated differently depending on + the content type.""" resp = self._makeOne() body = [1, 2, 3] @@ -1433,11 +1430,12 @@ def test_latin_one(self): ) def test_unicode(self): - """HTTP headers need to be latin-1 compatible + """HTTP headers need to be latin-1 compatible. - In order to offer file downloads which contain unicode file names, - the file name has to be treated in a special way, see - https://stackoverflow.com/questions/1361604 . + In order to offer file downloads which contain unicode file + names, the file name has to be treated in a special way, see + https://stackoverflow.com/questions/1361604 + . """ self.assertEqual( make_content_disposition('inline', 'ıq.png'), diff --git a/src/ZPublisher/tests/testPostTraversal.py b/src/ZPublisher/tests/testPostTraversal.py index b6c5c806f7..c4abe90cc5 100644 --- a/src/ZPublisher/tests/testPostTraversal.py +++ b/src/ZPublisher/tests/testPostTraversal.py @@ -35,22 +35,19 @@ def pt_chain_test(request, string): class DummyObjectBasic(Implicit): - """ Dummy class with docstring. - """ + """Dummy class with docstring.""" def _setObject(self, id, object): setattr(self, id, object) return getattr(self, id) def view(self): - """ Attribute with docstring. - """ + """Attribute with docstring.""" return 'view content' class DummyObjectWithPTHook(DummyObjectBasic): - """ Dummy class with docstring. - """ + """Dummy class with docstring.""" traversal = [] diff --git a/src/ZPublisher/tests/test_cookie.py b/src/ZPublisher/tests/test_cookie.py index addb62449d..460cc882ab 100644 --- a/src/ZPublisher/tests/test_cookie.py +++ b/src/ZPublisher/tests/test_cookie.py @@ -29,7 +29,7 @@ def assertRfc1123(self, s): - """check *s* is an RFC1123 date.""" + """Check *s* is an RFC1123 date.""" m = match(r"(.{3}), \d{2} (.{3}) \d{4} \d{2}:\d{2}:\d{2} GMT$", s) self.assertIsNotNone(m) self.assertIn(m.group(1), tuple(wdmap.values())) diff --git a/src/ZPublisher/tests/test_pubevents.py b/src/ZPublisher/tests/test_pubevents.py index fad2f32eca..fa86ed26bc 100644 --- a/src/ZPublisher/tests/test_pubevents.py +++ b/src/ZPublisher/tests/test_pubevents.py @@ -306,7 +306,7 @@ def cleanup(): def _succeed(): - ''' ''' + """""" return 'success' diff --git a/src/ZPublisher/tests/test_utils.py b/src/ZPublisher/tests/test_utils.py index e53718a67d..c0ab76b6dc 100644 --- a/src/ZPublisher/tests/test_utils.py +++ b/src/ZPublisher/tests/test_utils.py @@ -39,8 +39,8 @@ def test_utf_8(self): class NoUpdatePropertyManager: """PropertyManager without _updateProperty method. - This is a simplified version of the original PropertyManager, - with only the methods we need. + This is a simplified version of the original PropertyManager, with + only the methods we need. """ _properties = () diff --git a/src/ZPublisher/xmlrpc.py b/src/ZPublisher/xmlrpc.py index fb6ab37c4d..1850c5d8c8 100644 --- a/src/ZPublisher/xmlrpc.py +++ b/src/ZPublisher/xmlrpc.py @@ -10,12 +10,15 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""XML-RPC support module +"""XML-RPC support module. -Written by Eric Kidd at UserLand software, with much help from Jim Fulton -at DC. This code hooks Zope up to Fredrik Lundh's Python XML-RPC library. +Written by Eric Kidd at UserLand software, with much help from Jim +Fulton at DC. This code hooks Zope up to Fredrik Lundh's Python XML-RPC +library. -See http://www.xmlrpc.com/ and http://linux.userland.com/ for more +See +http://www.xmlrpc.com/ +and http://linux.userland.com/ for more information about XML-RPC and Zope. """ @@ -69,7 +72,7 @@ def dump_instance(self, value, write): def parse_input(data): - """Parse input data and return a method path and argument tuple + """Parse input data and return a method path and argument tuple. The data is a string. """ @@ -119,15 +122,15 @@ def is_xmlrpc_response(response): class Response: """Customized Response that handles XML-RPC-specific details. - We override setBody to marshall Python objects into XML-RPC. We - also override exception to convert errors to XML-RPC faults. + We override setBody to marshall Python objects into XML-RPC. We also + override exception to convert errors to XML-RPC faults. If these methods stop getting called, make sure that ZPublisher is using the xmlrpc.Response object created above and not the original HTTPResponse object from which it was cloned. - It's probably possible to improve the 'exception' method quite a bit. - The current implementation, however, should suffice for now. + It's probably possible to improve the 'exception' method quite a + bit. The current implementation, however, should suffice for now. """ _error_format = 'text/plain' # No html in error values diff --git a/src/ZTUtils/Batch.py b/src/ZTUtils/Batch.py index 01a6843c6e..e6b10c8e07 100644 --- a/src/ZTUtils/Batch.py +++ b/src/ZTUtils/Batch.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Batch class, for iterating over a sequence in batches -""" +"""Batch class, for iterating over a sequence in batches.""" from ExtensionClass import Base @@ -41,7 +40,7 @@ def __of__(self, parent): class Batch(Base): - """Create a sequence batch""" + """Create a sequence batch.""" __allow_access_to_unprotected_subobjects__ = 1 previous = LazyPrevBatch() @@ -50,7 +49,7 @@ class Batch(Base): def __init__(self, sequence, size, start=0, end=0, orphan=0, overlap=0): - '''Encapsulate "sequence" in batches of "size". + """Encapsulate "sequence" in batches of "size". Arguments: "start" and "end" are 0-based indexes into the sequence. If the next batch would contain no more than @@ -65,7 +64,7 @@ def __init__(self, sequence, size, start=0, end=0, the batch. "sequence_length" is the length of the original, unbatched, sequence - ''' + """ start = start + 1 diff --git a/src/ZTUtils/Lazy.py b/src/ZTUtils/Lazy.py index 47e27a3d4d..3865a09757 100644 --- a/src/ZTUtils/Lazy.py +++ b/src/ZTUtils/Lazy.py @@ -39,7 +39,7 @@ def __len__(self): if self._len is not _marker: return self._len dl = len(self._data) - while 1: + while True: try: self[dl] dl += 1 @@ -70,8 +70,9 @@ def __getitem__(self, index): class LazyCat(Lazy): - """Lazy concatenation of one or more sequences. Should be handy - for accessing small parts of big searches. + """Lazy concatenation of one or more sequences. + + Should be handy for accessing small parts of big searches. """ def __init__(self, sequences, length=None, actual_result_count=None): @@ -171,6 +172,7 @@ def __len__(self): class LazyMap(Lazy): """Act like a sequence, but get data from a filtering process. + Don't access data until necessary """ @@ -200,6 +202,7 @@ def __getitem__(self, index): class LazyFilter(Lazy): """Act like a sequence, but get data from a filtering process. + Don't access data until necessary. Only data for which test(data) returns true will be considered part of the set. """ @@ -251,6 +254,7 @@ def __getitem__(self, index): class LazyMop(Lazy): """Act like a sequence, but get data from a filtering process. + Don't access data until necessary. If the filter raises an exception for a given item, then that item isn't included in the sequence. """ @@ -304,8 +308,8 @@ def __getitem__(self, index): class LazyValues(Lazy): - """Given a sequence of two tuples typically (key, value) act as - though we are just a list of the values lazily""" + """Given a sequence of two tuples typically (key, value) act as though we + are just a list of the values lazily.""" def __init__(self, seq): self._seq = seq diff --git a/src/ZTUtils/SimpleTree.py b/src/ZTUtils/SimpleTree.py index aa4e1d2730..077db5d25d 100644 --- a/src/ZTUtils/SimpleTree.py +++ b/src/ZTUtils/SimpleTree.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Simple Tree classes -""" +"""Simple Tree classes.""" from Acquisition import aq_acquire @@ -41,7 +40,7 @@ def branch(self): class SimpleTreeMaker(TreeMaker): - '''Generate Simple Trees''' + """Generate Simple Trees.""" def __init__(self, tree_pre="tree"): self.tree_pre = tree_pre diff --git a/src/ZTUtils/Tree.py b/src/ZTUtils/Tree.py index b9895aa1dc..62b926f628 100644 --- a/src/ZTUtils/Tree.py +++ b/src/ZTUtils/Tree.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Tree manipulation classes -""" +"""Tree manipulation classes.""" import base64 import zlib @@ -66,7 +65,7 @@ def __len__(self): class TreeMaker: - '''Class for mapping a hierarchy of objects into a tree of nodes.''' + """Class for mapping a hierarchy of objects into a tree of nodes.""" __allow_access_to_unprotected_subobjects__ = 1 @@ -88,17 +87,17 @@ def setIdAttr(self, id): as a string using Tree.encodeExpansion(). The returned id should be unique and stable across Zope requests. - If the attribute or method isn't found on an object, either - the objects persistence Id or the result of id() on the object - is used instead. + If the attribute or method isn't found on an object, either the + objects persistence Id or the result of id() on the object is + used instead. """ self._id = id def setExpandRoot(self, expand): """Set wether or not to expand the root node by default. - When no expanded flag or mapping is passed to .tree(), assume the root - node is expanded, and leave all subnodes closed. + When no expanded flag or mapping is passed to .tree(), assume + the root node is expanded, and leave all subnodes closed. The default is to expand the root node. """ @@ -108,8 +107,8 @@ def setAssumeChildren(self, assume): """Set wether or not to assume nodes have children. When a node is not expanded, when assume children is set, don't - determine if it is a leaf node, but assume it can be opened. Use this - when determining the children for a node is expensive. + determine if it is a leaf node, but assume it can be opened. Use + this when determining the children for a node is expensive. The default is to not assume there are children. """ @@ -117,12 +116,12 @@ def setAssumeChildren(self, assume): def setChildAccess(self, attrname=_marker, filter=_marker, function=_marker): - '''Set the criteria for fetching child nodes. + """Set the criteria for fetching child nodes. - Child nodes can be accessed through either an attribute name - or callback function. Children fetched by attribute name can - be filtered through a callback function. - ''' + Child nodes can be accessed through either an attribute name or + callback function. Children fetched by attribute name can be + filtered through a callback function. + """ if function is _marker: self._values_function = None if attrname is not _marker: @@ -196,13 +195,12 @@ def getChildren(self, object): return self.filterChildren(children) def tree(self, root, expanded=None, subtree=0): - '''Create a tree from root, with specified nodes expanded. + """Create a tree from root, with specified nodes expanded. - "expanded" must be false, true, or a mapping. - Each key of the mapping is the id of a top-level expanded - node, and each value is the "expanded" value for the - children of that node. - ''' + "expanded" must be false, true, or a mapping. Each key of the + mapping is the id of a top-level expanded node, and each value + is the "expanded" value for the children of that node. + """ node = self.node(root) child_exp = expanded if not simple_type(expanded): @@ -233,10 +231,10 @@ def simple_type(ob): def b2a(s): - '''Encode a bytes/string as a cookie- and url-safe string. + """Encode a bytes/string as a cookie- and url-safe string. Encoded string use only alphanumeric characters, and "._-". - ''' + """ if not isinstance(s, bytes): s = str(s) if isinstance(s, str): @@ -245,7 +243,7 @@ def b2a(s): def a2b(s): - '''Decode a b2a-encoded value to bytes.''' + """Decode a b2a-encoded value to bytes.""" if not isinstance(s, bytes): if isinstance(s, str): s = s.encode('ascii') @@ -253,13 +251,13 @@ def a2b(s): def encodeExpansion(nodes, compress=1): - '''Encode the expanded node ids of a tree into bytes. + """Encode the expanded node ids of a tree into bytes. - Accepts a list of nodes, such as that produced by root.flat(). - Marks each expanded node with an expansion_number attribute. - Since node ids are encoded, the resulting string is safe for - use in cookies and URLs. - ''' + Accepts a list of nodes, such as that produced by root.flat(). Marks + each expanded node with an expansion_number attribute. Since node + ids are encoded, the resulting string is safe for use in cookies and + URLs. + """ steps = [] last_depth = -1 for n, node in enumerate(nodes): @@ -280,10 +278,11 @@ def encodeExpansion(nodes, compress=1): def decodeExpansion(s, nth=None, maxsize=8192): - '''Decode an expanded node map from bytes. + """Decode an expanded node map from bytes. - If nth is an integer, also return the (map, key) pair for the nth entry. - ''' + If nth is an integer, also return the (map, key) pair for the nth + entry. + """ if len(s) > maxsize: # Set limit to avoid DoS attacks. raise ValueError('Encoded node map too large') diff --git a/src/ZTUtils/Zope.py b/src/ZTUtils/Zope.py index d1e79c8787..275f00a5f4 100644 --- a/src/ZTUtils/Zope.py +++ b/src/ZTUtils/Zope.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -"""Zope-specific versions of ZTUtils classes -""" +"""Zope-specific versions of ZTUtils classes.""" import html from urllib.parse import quote @@ -92,8 +91,8 @@ def __getitem__(self, index): class TreeSkipMixin: - '''Mixin class to make trees test security, and allow - skipping of unauthorized objects. ''' + """Mixin class to make trees test security, and allow skipping of + unauthorized objects.""" skip = None def setSkip(self, skip): @@ -117,7 +116,7 @@ class SimpleTreeMaker(TreeSkipMixin, SimpleTreeMaker): _getChildren = SimpleTreeMaker.getChildren def cookieTree(self, root_object, default_state=None): - '''Make a tree with state stored in a cookie.''' + """Make a tree with state stored in a cookie.""" tree_pre = self.tree_pre state_name = '%s-state' % tree_pre set_name = '%s-setstate' % tree_pre @@ -174,7 +173,7 @@ def __init__(self, sequence, size, start=0, end=0, def _default_encoding(): - ''' Retrieve default encoding from config ''' + """Retrieve default encoding from config.""" global _DEFAULT_ENCODING if _DEFAULT_ENCODING is None: from App.config import getConfiguration @@ -187,18 +186,18 @@ def _default_encoding(): def make_query(*args, **kwargs): - '''Construct a URL query string, with marshalling markup. + """Construct a URL query string, with marshalling markup. - If there are positional arguments, they must be dictionaries. - They are combined with the dictionary of keyword arguments to form - a dictionary of query names and values. + If there are positional arguments, they must be dictionaries. They + are combined with the dictionary of keyword arguments to form a + dictionary of query names and values. Query names (the keys) must be strings. Values may be strings, integers, floats, or DateTimes, and they may also be lists or - namespaces containing these types. Names and string values - should not be URL-quoted. All arguments are marshalled with + namespaces containing these types. Names and string values should + not be URL-quoted. All arguments are marshalled with complex_marshal(). - ''' + """ d = {} for arg in args: @@ -214,17 +213,17 @@ def make_query(*args, **kwargs): def make_hidden_input(*args, **kwargs): - '''Construct a set of hidden input elements, with marshalling markup. + """Construct a set of hidden input elements, with marshalling markup. - If there are positional arguments, they must be dictionaries. - They are combined with the dictionary of keyword arguments to form - a dictionary of query names and values. + If there are positional arguments, they must be dictionaries. They + are combined with the dictionary of keyword arguments to form a + dictionary of query names and values. Query names (the keys) must be strings. Values may be strings, integers, floats, or DateTimes, and they may also be lists or - namespaces containing these types. All arguments are marshalled with - complex_marshal(). - ''' + namespaces containing these types. All arguments are marshalled + with complex_marshal(). + """ d = {} for arg in args: @@ -244,20 +243,20 @@ def hq(x): def complex_marshal(pairs): - '''Add request marshalling information to a list of name-value pairs. - - Names must be strings. Values may be strings, - integers, floats, or DateTimes, and they may also be lists or - namespaces containing these types. - - The list is edited in place so that each (name, value) pair - becomes a (name, marshal, value) triple. The middle value is the - request marshalling string. Integer, float, and DateTime values - will have ":int", ":float", or ":date" as their marshal string. - Lists will be flattened, and the elements given ":list" in - addition to their simple marshal string. Dictionaries will be - flattened and marshalled using ":record". - ''' + """Add request marshalling information to a list of name-value pairs. + + Names must be strings. Values may be strings, integers, floats, or + DateTimes, and they may also be lists or namespaces containing these + types. + + The list is edited in place so that each (name, value) pair becomes + a (name, marshal, value) triple. The middle value is the request + marshalling string. Integer, float, and DateTime values will have + ":int", ":float", or ":date" as their marshal string. Lists will be + flattened, and the elements given ":list" in addition to their + simple marshal string. Dictionaries will be flattened and + marshalled using ":record". + """ i = len(pairs) while i > 0: i = i - 1 @@ -309,14 +308,14 @@ def simple_marshal(v): def url_query(request, req_name="URL", omit=None): - '''Construct a URL with a query string, using the current request. + """Construct a URL with a query string, using the current request. request: the request object req_name: the name, such as "URL1" or "BASEPATH1", to get from request omit: sequence of name of query arguments to omit. If a name contains a colon, it is treated literally. Otherwise, it will match each argument name that starts with the name and a period or colon. - ''' + """ base = request[req_name] qs = request.get('QUERY_STRING', '') diff --git a/src/ZTUtils/__init__.py b/src/ZTUtils/__init__.py index f79838fea3..b3b1958413 100644 --- a/src/ZTUtils/__init__.py +++ b/src/ZTUtils/__init__.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Package of template utility classes and functions. -""" +"""Package of template utility classes and functions.""" from AccessControl.SecurityInfo import ModuleSecurityInfo from .Tree import a2b # NOQA: F401 diff --git a/src/ZTUtils/tests/testBatch.py b/src/ZTUtils/tests/testBatch.py index e45e7e17f9..c8b7d6628b 100644 --- a/src/ZTUtils/tests/testBatch.py +++ b/src/ZTUtils/tests/testBatch.py @@ -6,14 +6,14 @@ class BatchTests(unittest.TestCase): def testEmpty(self): - '''Test empty Batch''' + """Test empty Batch.""" b = Batch([], 5) assert b.previous is None assert b.next is None assert len(b) == b.start == b.end == 0, (len(b), b.start, b.end) def testSingle(self): - '''Test single Batch''' + """Test single Batch.""" for bsize in range(1, 6): seq = list(range(bsize)) b = Batch(seq, 5) @@ -28,7 +28,7 @@ def testSingle(self): assert b[neg] == (bsize + neg), (b[neg], (bsize + neg)) def testOrphan(self): - '''Test orphan collection''' + """Test orphan collection.""" for bsize in (6, 7): b = Batch(list(range(bsize)), 5, orphan=3) assert b.next is None @@ -41,7 +41,7 @@ def testOrphan(self): assert len(b.next) == 3 def testLengthEqualsSizePlusOrphans(self): - '''Test limit case where batch length is equal to size + orphans''' + """Test limit case where batch length is equal to size + orphans.""" for bsize, length in ((12, 11), (13, 12), (14, 13), (15, 10)): b = Batch(list(range(bsize)), size=10, start=1, end=0, orphan=3, overlap=0) diff --git a/src/ZTUtils/tests/testZope.py b/src/ZTUtils/tests/testZope.py index 9c90614b53..f9f4e07b81 100644 --- a/src/ZTUtils/tests/testZope.py +++ b/src/ZTUtils/tests/testZope.py @@ -30,7 +30,7 @@ def testMarshalUnicode(self): self.assertEqual(simple_marshal('unic\xF3de'), arg_type) def testMarshallLists(self): - '''Test marshalling lists''' + """Test marshalling lists.""" test_date = DateTime() list_ = [1, test_date, 'str', 'unic\xF3de'] result = complex_marshal([('list', list_), ]) @@ -42,7 +42,7 @@ def testMarshallLists(self): ('list', arg4_type, 'unic\xF3de')]) def testMarshallRecords(self): - '''Test marshalling records''' + """Test marshalling records.""" test_date = DateTime() record = { 'arg1': 1, 'arg2': test_date, @@ -58,7 +58,7 @@ def testMarshallRecords(self): ('record.arg4', arg4_type, 'unic\xF3de')}) def testMarshallListsInRecords(self): - '''Test marshalling lists inside of records''' + """Test marshalling lists inside of records.""" test_date = DateTime() record = {'arg1': [1, test_date, 'str', 'unic\xF3de'], 'arg2': 1} result = complex_marshal([('record', record), ]) @@ -72,7 +72,7 @@ def testMarshallListsInRecords(self): ('record.arg2', ':int:record', 1)}) def testMakeComplexQuery(self): - '''Test that make_query returns sane results''' + """Test that make_query returns sane results.""" test_date = DateTime() quote_date = quote(str(test_date)) record = {'arg1': [1, test_date, 'str'], 'arg2': 1} diff --git a/src/Zope2/App/schema.py b/src/Zope2/App/schema.py index 4463be481a..fb7e014661 100644 --- a/src/Zope2/App/schema.py +++ b/src/Zope2/App/schema.py @@ -21,13 +21,11 @@ @implementer(IVocabularyRegistry) class Zope2VocabularyRegistry: - """IVocabularyRegistry that supports global and local utilities. - """ + """IVocabularyRegistry that supports global and local utilities.""" __slots__ = () def get(self, context, name): - """See zope.schema.interfaces.IVocabularyRegistry. - """ + """See zope.schema.interfaces.IVocabularyRegistry.""" factory = getUtility(IVocabularyFactory, name) return factory(context) diff --git a/src/Zope2/App/startup.py b/src/Zope2/App/startup.py index bcf11d1b1a..d73e79d437 100644 --- a/src/Zope2/App/startup.py +++ b/src/Zope2/App/startup.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""Initialize the Zope2 Package and provide a published module -""" +"""Initialize the Zope2 Package and provide a published module.""" import os import sys diff --git a/src/Zope2/Startup/datatypes.py b/src/Zope2/Startup/datatypes.py index fb3635f464..93fbd1ebe7 100644 --- a/src/Zope2/Startup/datatypes.py +++ b/src/Zope2/Startup/datatypes.py @@ -130,8 +130,8 @@ def root_wsgi_config(section): class ZopeDatabase(ZODBDatabase): - """ A ZODB database datatype that can handle an extended set of - attributes for use by DBTab """ + """A ZODB database datatype that can handle an extended set of attributes + for use by DBTab.""" def createDB(self, database_name, databases): self.config.database_name = database_name @@ -170,9 +170,8 @@ def getVirtualMountPaths(self): return [item[0] for item in self.computeMountPaths()] def getMountParams(self, mount_path): - """Returns (real_root, real_path, container_class) for a virtual - mount path. - """ + """Returns (real_root, real_path, container_class) for a virtual mount + path.""" for (virtual_path, real_root, real_path) in self.computeMountPaths(): if virtual_path == mount_path: container_class = self.config.container_class @@ -202,8 +201,7 @@ def default_zpublisher_encoding(value): class DBTab: - """A Zope database configuration, similar in purpose to /etc/fstab. - """ + """A Zope database configuration, similar in purpose to /etc/fstab.""" def __init__(self, db_factories, mount_paths): self.db_factories = db_factories # { name -> DatabaseFactory } @@ -211,13 +209,11 @@ def __init__(self, db_factories, mount_paths): self.databases = {} # { name -> DB instance } def listMountPaths(self): - """Returns a sequence of (virtual_mount_path, database_name). - """ + """Returns a sequence of (virtual_mount_path, database_name).""" return list(self.mount_paths.items()) def listDatabaseNames(self): - """Returns a sequence of names. - """ + """Returns a sequence of names.""" return list(self.db_factories.keys()) def hasDatabase(self, name): @@ -235,7 +231,9 @@ def _mountPathError(self, mount_path): % mount_path) def getDatabase(self, mount_path=None, name=None, is_root=0): - """Returns an opened database. Requires either mount_path or name. + """Returns an opened database. + + Requires either mount_path or name. """ if name is None: name = self.getName(mount_path) @@ -260,7 +258,6 @@ def getName(self, mount_path): def simpleClassFactory(jar, module, name, _silly=('__doc__',), _globals={}): - """Class factory. - """ + """Class factory.""" m = __import__(module, _globals, _globals, _silly) return getattr(m, name) diff --git a/src/Zope2/Startup/handlers.py b/src/Zope2/Startup/handlers.py index 35b4a4f660..b877a647ef 100644 --- a/src/Zope2/Startup/handlers.py +++ b/src/Zope2/Startup/handlers.py @@ -72,8 +72,8 @@ def _name_to_ips(host): """Map a name *host* to the sequence of its IP addresses. Use *host* itself (as sequence) if it already is an IP address. - Thus, if only a specific interface on a host is trusted, - identify it by its IP (and not the host name). + Thus, if only a specific interface on a host is trusted, identify it + by its IP (and not the host name). """ if isinstance(host, bytes): host = host.decode('utf-8') diff --git a/src/Zope2/Startup/options.py b/src/Zope2/Startup/options.py index 18f0b2693c..7fcd1143af 100644 --- a/src/Zope2/Startup/options.py +++ b/src/Zope2/Startup/options.py @@ -21,10 +21,11 @@ class ConditionalSchemaParser(SchemaParser): - """ - A SchemaParser with support for conditionally executing import - directives based on a Python import condition. This is similar to - ZCML's condition="installed foo" support, shortened to condition="foo". + """A SchemaParser with support for conditionally executing import + directives based on a Python import condition. + + This is similar to ZCML's condition="installed foo" support, + shortened to condition="foo". """ def start_import(self, attrs): @@ -41,8 +42,7 @@ def start_import(self, attrs): class ZopeWSGIOptions: - """ZopeWSGIOptions parses a ZConfig schema and config file. - """ + """ZopeWSGIOptions parses a ZConfig schema and config file.""" configfile = None confighandlers = None configroot = None diff --git a/src/Zope2/Startup/run.py b/src/Zope2/Startup/run.py index e3d14a7671..5cd4e07009 100644 --- a/src/Zope2/Startup/run.py +++ b/src/Zope2/Startup/run.py @@ -14,8 +14,10 @@ def configure_wsgi(configfile): - """ Provide an API which allows scripts to configure Zope - before attempting to do 'app = Zope2.app(). Should be used as + """Provide an API which allows scripts to configure Zope before attempting + to do 'app = Zope2.app(). + + Should be used as follows: from Zope2.Startup.run import configure_wsgi; configure_wsgi('/path/to/configfile'); import Zope2; app = Zope2.app() @@ -29,9 +31,11 @@ def configure_wsgi(configfile): def _set_wsgi_config(configfile=None): - """ Configure a Zope instance based on ZopeWSGIOptions. - Optionally accept a configfile argument (string path) in order - to specify where the configuration file exists. """ + """Configure a Zope instance based on ZopeWSGIOptions. + + Optionally accept a configfile argument (string path) in order to + specify where the configuration file exists. + """ from Zope2.Startup import handlers from Zope2.Startup import options opts = options.ZopeWSGIOptions(configfile=configfile)() diff --git a/src/Zope2/Startup/serve.py b/src/Zope2/Startup/serve.py index 9734fbe478..c265afbd81 100644 --- a/src/Zope2/Startup/serve.py +++ b/src/Zope2/Startup/serve.py @@ -29,8 +29,8 @@ def parse_vars(args): - """ - Given variables like ``['a=b', 'c=d']`` turns it into ``{'a': + """Given variables like ``['a=b', 'c=d']`` turns it into ``{'a': + 'b', 'c': 'd'}`` """ result = {} @@ -57,10 +57,10 @@ def _getpathsec(config_uri, name): def setup_logging(config_uri, global_conf=None, # NOQA fileConfig=fileConfig, configparser=configparser): - """ - Set up logging via :func:`logging.config.fileConfig` with the filename + """Set up logging via :func:`logging.config.fileConfig` with the filename specified via ``config_uri`` (a string in the form ``filename#sectionname``). + ConfigParser defaults are specified for the special ``__file__`` and ``here`` variables, similar to PasteDeploy config loading. Extra defaults can optionally be specified as a dict in ``global_conf``. diff --git a/src/Zope2/Startup/tests/test_schema.py b/src/Zope2/Startup/tests/test_schema.py index cf76478645..756f44002e 100644 --- a/src/Zope2/Startup/tests/test_schema.py +++ b/src/Zope2/Startup/tests/test_schema.py @@ -78,8 +78,7 @@ def test_environment(self): NSYNC doesnt """) - items = list(conf.environment.items()) - items.sort() + items = sorted(conf.environment.items()) self.assertEqual( items, [("FEARFACTORY", "rocks"), ("NSYNC", "doesnt")]) diff --git a/src/Zope2/__init__.py b/src/Zope2/__init__.py index 679a7db921..937c9393d2 100644 --- a/src/Zope2/__init__.py +++ b/src/Zope2/__init__.py @@ -25,7 +25,7 @@ def startup_wsgi(): - """Initialize the Zope Package and provide a published module""" + """Initialize the Zope Package and provide a published module.""" global _began_startup if _began_startup: # Already began (and maybe finished) startup, so don't run again @@ -37,13 +37,13 @@ def startup_wsgi(): def app(*args, **kw): - """Utility for scripts to open a connection to the database""" + """Utility for scripts to open a connection to the database.""" startup_wsgi() return bobo_application(*args, **kw) def debug(*args, **kw): - """Utility to try a Zope request using the interactive interpreter""" + """Utility to try a Zope request using the interactive interpreter.""" startup_wsgi() import ZPublisher return ZPublisher.test('Zope2', *args, **kw) diff --git a/src/Zope2/utilities/adduser.py b/src/Zope2/utilities/adduser.py index 74eb18951e..51cd9aba2a 100644 --- a/src/Zope2/utilities/adduser.py +++ b/src/Zope2/utilities/adduser.py @@ -10,7 +10,7 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -""" Add a Zope management user to the root Zope user folder """ +"""Add a Zope management user to the root Zope user folder.""" import argparse import sys diff --git a/src/Zope2/utilities/copyzopeskel.py b/src/Zope2/utilities/copyzopeskel.py index 2d38f158f9..96c385ed71 100755 --- a/src/Zope2/utilities/copyzopeskel.py +++ b/src/Zope2/utilities/copyzopeskel.py @@ -165,8 +165,8 @@ def main(): def copyskel(sourcedir, targetdir, uid, gid, **replacements): - """ This is an independent function because we'd like to - import and call it from mkzopeinstance """ + """This is an independent function because we'd like to import and call it + from mkzopeinstance.""" # Create the top of the instance: if not os.path.exists(targetdir): os.makedirs(targetdir) diff --git a/src/Zope2/utilities/mkwsgiinstance.py b/src/Zope2/utilities/mkwsgiinstance.py index faf76b3962..107d48072d 100644 --- a/src/Zope2/utilities/mkwsgiinstance.py +++ b/src/Zope2/utilities/mkwsgiinstance.py @@ -10,7 +10,6 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## - """%(program)s: Create a Zope WSGI instance home. usage: %(program)s [options] @@ -157,7 +156,7 @@ def get_skeltarget(): print('Please choose a directory in which you\'d like to install') print('Zope "instance home" files such as database files, configuration') print('files, etc.\n') - while 1: + while True: skeltarget = input("Directory: ").strip() if skeltarget == '': print('You must specify a directory') @@ -175,7 +174,7 @@ def get_inituser(): user = input("Username: ").strip() if user == '': return None, None - while 1: + while True: passwd = getpass.getpass("Password: ") verify = getpass.getpass("Verify password: ") if verify == passwd: @@ -201,8 +200,7 @@ def write_inituser(fn, user, password): def check_buildout(script_path): - """ Are we running from within a buildout which supplies 'zopepy'? - """ + """Are we running from within a buildout which supplies 'zopepy'?""" buildout_cfg = os.path.join(os.path.dirname(script_path), 'buildout.cfg') if os.path.exists(buildout_cfg): parser = RawConfigParser() @@ -221,8 +219,7 @@ def check_buildout(script_path): def get_zope2path(python): - """ Get Zope2 path from selected Python interpreter. - """ + """Get Zope2 path from selected Python interpreter.""" zope2file = '' try: output = subprocess.check_output( diff --git a/src/webdav/Collection.py b/src/webdav/Collection.py index 429f8e6179..f0d668a156 100644 --- a/src/webdav/Collection.py +++ b/src/webdav/Collection.py @@ -35,12 +35,13 @@ @implementer(IDAVCollection) class Collection(Resource): + """The Collection class provides basic WebDAV support for collection + objects. - """The Collection class provides basic WebDAV support for - collection objects. It provides default implementations - for all supported WebDAV HTTP methods. The behaviors of some - WebDAV HTTP methods for collections are slightly different - than those for non-collection resources.""" + It provides default implementations for all supported WebDAV HTTP + methods. The behaviors of some WebDAV HTTP methods for collections + are slightly different than those for non-collection resources. + """ security = ClassSecurityInfo() __dav_collection__ = 1 @@ -74,19 +75,25 @@ def HEAD(self, REQUEST, RESPONSE): raise NotFound('The requested resource does not exist.') def PUT(self, REQUEST, RESPONSE): - """The PUT method has no inherent meaning for collection - resources, though collections are not specifically forbidden - to handle PUT requests. The default response to a PUT request - for collections is 405 (Method Not Allowed).""" + """The PUT method has no inherent meaning for collection resources, + though collections are not specifically forbidden to handle PUT + requests. + + The default response to a PUT request for collections is 405 + (Method Not Allowed). + """ self.dav__init(REQUEST, RESPONSE) raise MethodNotAllowed('Method not supported for collections.') @security.protected(delete_objects) def DELETE(self, REQUEST, RESPONSE): - """Delete a collection resource. For collection resources, DELETE - may return either 200 (OK) or 204 (No Content) to indicate total - success, or may return 207 (Multistatus) to indicate partial - success. Note that in Zope a DELETE currently never returns 207.""" + """Delete a collection resource. + + For collection resources, DELETE may return either 200 (OK) or + 204 (No Content) to indicate total success, or may return 207 + (Multistatus) to indicate partial success. Note that in Zope a + DELETE currently never returns 207. + """ from webdav.davcmds import DeleteCollection diff --git a/src/webdav/NullResource.py b/src/webdav/NullResource.py index fc0444cd82..5efd32daa9 100644 --- a/src/webdav/NullResource.py +++ b/src/webdav/NullResource.py @@ -60,9 +60,8 @@ class NullResource(Persistent, Implicit, Resource): - - """Null resources are used to handle HTTP method calls on - objects which do not yet exist in the url namespace.""" + """Null resources are used to handle HTTP method calls on objects which do + not yet exist in the url namespace.""" __null_resource__ = 1 zmi_icon = 'fas fa-edit' @@ -124,8 +123,7 @@ def _default_PUT_factory(self, name, typ, body): @security.public def PUT(self, REQUEST, RESPONSE): - """Create a new non-collection resource. - """ + """Create a new non-collection resource.""" self.dav__init(REQUEST, RESPONSE) name = self.__name__ @@ -239,7 +237,7 @@ def MKCOL(self, REQUEST, RESPONSE): @security.protected(webdav_lock_items) def LOCK(self, REQUEST, RESPONSE): - """ LOCK on a Null Resource makes a LockNullResource instance """ + """LOCK on a Null Resource makes a LockNullResource instance.""" self.dav__init(REQUEST, RESPONSE) security = getSecurityManager() creator = security.getUser() @@ -303,10 +301,12 @@ def LOCK(self, REQUEST, RESPONSE): class LockNullResource(NullResource, Item_w__name__): - """ A Lock-Null Resource is created when a LOCK command is succesfully - executed on a NullResource, essentially locking the Name. A PUT or - MKCOL deletes the LockNull resource from its container and replaces it - with the target object. An UNLOCK deletes it. """ + """A Lock-Null Resource is created when a LOCK command is succesfully + executed on a NullResource, essentially locking the Name. + + A PUT or MKCOL deletes the LockNull resource from its container and + replaces it with the target object. An UNLOCK deletes it. + """ __locknull_resource__ = 1 meta_type = 'WebDAV LockNull Resource' @@ -345,8 +345,8 @@ def PROPFIND(self, REQUEST, RESPONSE): @security.protected(webdav_lock_items) def LOCK(self, REQUEST, RESPONSE): - """ A Lock command on a LockNull resource should only be a - refresh request (one without a body) """ + """A Lock command on a LockNull resource should only be a refresh + request (one without a body)""" self.dav__init(REQUEST, RESPONSE) body = REQUEST.get('BODY', '') ifhdr = REQUEST.get_header('If', '') @@ -383,7 +383,7 @@ def LOCK(self, REQUEST, RESPONSE): @security.protected(webdav_unlock_items) def UNLOCK(self, REQUEST, RESPONSE): - """ Unlocking a Null Resource removes it from its parent """ + """Unlocking a Null Resource removes it from its parent.""" self.dav__init(REQUEST, RESPONSE) token = REQUEST.get_header('Lock-Token', '') url = REQUEST['URL'] @@ -408,8 +408,8 @@ def UNLOCK(self, REQUEST, RESPONSE): @security.public def PUT(self, REQUEST, RESPONSE): - """ Create a new non-collection resource, deleting the LockNull - object from the container before putting the new object in. """ + """Create a new non-collection resource, deleting the LockNull object + from the container before putting the new object in.""" self.dav__init(REQUEST, RESPONSE) name = self.__name__ @@ -480,9 +480,12 @@ def PUT(self, REQUEST, RESPONSE): @security.protected(add_folders) def MKCOL(self, REQUEST, RESPONSE): - """ Create a new Collection (folder) resource. Since this is being - done on a LockNull resource, this also involves removing the LockNull - object and transferring its locks to the newly created Folder """ + """Create a new Collection (folder) resource. + + Since this is being done on a LockNull resource, this also + involves removing the LockNull object and transferring its locks + to the newly created Folder + """ self.dav__init(REQUEST, RESPONSE) if REQUEST.get('BODY', ''): raise UnsupportedMediaType('Unknown request body.') diff --git a/src/webdav/PropertySheets.py b/src/webdav/PropertySheets.py index 74e2141902..0b460563b2 100644 --- a/src/webdav/PropertySheets.py +++ b/src/webdav/PropertySheets.py @@ -36,7 +36,7 @@ def xml_escape(value): class DAVProperties(Virtual, PropertySheet, View): - """WebDAV properties""" + """WebDAV properties.""" id = 'webdav' _md = {'xmlns': 'DAV:'} diff --git a/src/webdav/Resource.py b/src/webdav/Resource.py index d0438e7bb8..1f405fc930 100644 --- a/src/webdav/Resource.py +++ b/src/webdav/Resource.py @@ -68,12 +68,13 @@ @implementer(IDAVResource) class Resource(Base, LockableItem): + """The Resource mixin class provides basic WebDAV support for non- + collection objects. - """The Resource mixin class provides basic WebDAV support for - non-collection objects. It provides default implementations - for most supported WebDAV HTTP methods, however certain methods - such as PUT should be overridden to ensure correct behavior in - the context of the object type.""" + It provides default implementations for most supported WebDAV HTTP + methods, however certain methods such as PUT should be overridden to + ensure correct behavior in the context of the object type. + """ __dav_resource__ = 1 @@ -232,10 +233,12 @@ def HEAD(self, REQUEST, RESPONSE): def PUT(self, REQUEST, RESPONSE): """Replace the GET response entity of an existing resource. - Because this is often object-dependent, objects which handle - PUT should override the default PUT implementation with an - object-specific implementation. By default, PUT requests - fail with a 405 (Method Not Allowed).""" + + Because this is often object-dependent, objects which handle PUT + should override the default PUT implementation with an object- + specific implementation. By default, PUT requests fail with a + 405 (Method Not Allowed). + """ self.dav__init(REQUEST, RESPONSE) raise MethodNotAllowed('Method not supported for this resource.') @@ -258,19 +261,24 @@ def OPTIONS(self, REQUEST, RESPONSE): @security.public def TRACE(self, REQUEST, RESPONSE): - """Return the HTTP message received back to the client as the - entity-body of a 200 (OK) response. This will often usually - be intercepted by the web server in use. If not, the TRACE - request will fail with a 405 (Method Not Allowed), since it - is not often possible to reproduce the HTTP request verbatim - from within the Zope environment.""" + """Return the HTTP message received back to the client as the entity- + body of a 200 (OK) response. + + This will often usually be intercepted by the web server in use. + If not, the TRACE request will fail with a 405 (Method Not + Allowed), since it is not often possible to reproduce the HTTP + request verbatim from within the Zope environment. + """ self.dav__init(REQUEST, RESPONSE) raise MethodNotAllowed('Method not supported for this resource.') @security.protected(delete_objects) def DELETE(self, REQUEST, RESPONSE): - """Delete a resource. For non-collection resources, DELETE may - return either 200 or 204 (No Content) to indicate success.""" + """Delete a resource. + + For non-collection resources, DELETE may return either 200 or + 204 (No Content) to indicate success. + """ self.dav__init(REQUEST, RESPONSE) ifhdr = REQUEST.get_header('If', '') url = urlfix(REQUEST['URL'], 'DELETE') @@ -346,18 +354,23 @@ def PROPPATCH(self, REQUEST, RESPONSE): return RESPONSE def MKCOL(self, REQUEST, RESPONSE): - """Create a new collection resource. If called on an existing - resource, MKCOL must fail with 405 (Method Not Allowed).""" + """Create a new collection resource. + + If called on an existing resource, MKCOL must fail with 405 + (Method Not Allowed). + """ self.dav__init(REQUEST, RESPONSE) raise MethodNotAllowed('The resource already exists.') @security.public def COPY(self, REQUEST, RESPONSE): - """Create a duplicate of the source resource whose state - and behavior match that of the source resource as closely - as possible. Though we may later try to make a copy appear - seamless across namespaces (e.g. from Zope to Apache), COPY - is currently only supported within the Zope namespace.""" + """Create a duplicate of the source resource whose state and behavior + match that of the source resource as closely as possible. + + Though we may later try to make a copy appear seamless across + namespaces (e.g. from Zope to Apache), COPY is currently only + supported within the Zope namespace. + """ self.dav__init(REQUEST, RESPONSE) if not hasattr(aq_base(self), 'cb_isCopyable') or \ not self.cb_isCopyable(): @@ -465,10 +478,12 @@ def COPY(self, REQUEST, RESPONSE): @security.public def MOVE(self, REQUEST, RESPONSE): - """Move a resource to a new location. Though we may later try to - make a move appear seamless across namespaces (e.g. from Zope - to Apache), MOVE is currently only supported within the Zope - namespace.""" + """Move a resource to a new location. + + Though we may later try to make a move appear seamless across + namespaces (e.g. from Zope to Apache), MOVE is currently only + supported within the Zope namespace. + """ self.dav__init(REQUEST, RESPONSE) self.dav__validate(self, 'DELETE', REQUEST) if not hasattr(aq_base(self), 'cb_isMoveable') or \ @@ -593,7 +608,7 @@ def MOVE(self, REQUEST, RESPONSE): @security.protected(webdav_lock_items) def LOCK(self, REQUEST, RESPONSE): - """Lock a resource""" + """Lock a resource.""" from webdav.davcmds import Lock self.dav__init(REQUEST, RESPONSE) security = getSecurityManager() @@ -677,11 +692,12 @@ def UNLOCK(self, REQUEST, RESPONSE): def manage_DAVget(self): """Gets the document source or file data. - This implementation is a last resort fallback. The subclass should - override this method to provide a more appropriate implementation. + This implementation is a last resort fallback. The subclass + should override this method to provide a more appropriate + implementation. - Using PrincipiaSearchSource, if it exists. It is one of the few shared - interfaces still around in common Zope content objects. + Using PrincipiaSearchSource, if it exists. It is one of the few + shared interfaces still around in common Zope content objects. """ if getattr(aq_base(self), 'PrincipiaSearchSource', None) is not None: return self.PrincipiaSearchSource() diff --git a/src/webdav/__init__.py b/src/webdav/__init__.py index 7da837bd51..a4997baa65 100644 --- a/src/webdav/__init__.py +++ b/src/webdav/__init__.py @@ -10,29 +10,29 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## - """The webdav package provides WebDAV capability for common Zope objects. - Current WebDAV support in Zope provides for the correct handling of HTTP - GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE, PROPFIND, PROPPATCH, MKCOL, - COPY and MOVE methods, as appropriate for the object that is the target - of the operation. Objects which do not support a given operation should - respond appropriately with a "405 Method Not Allowed" response. +Current WebDAV support in Zope provides for the correct handling of HTTP +GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE, PROPFIND, PROPPATCH, MKCOL, +COPY and MOVE methods, as appropriate for the object that is the target +of the operation. Objects which do not support a given operation should +respond appropriately with a "405 Method Not Allowed" response. - Note that the ability of a Zope installation to support WebDAV HTTP methods - depends on the willingness of the web server to defer handling of those - methods to the Zope process. In most cases, servers will allow the process - to handle any request, so the Zope portion of your url namespace may well - be able to handle WebDAV operations even though your web server software - is not WebDAV-aware itself. Zope installations which use bundled server - implementations such as ZopeHTTPServer or ZServer should fully support - WebDAV functions. +Note that the ability of a Zope installation to support WebDAV HTTP methods +depends on the willingness of the web server to defer handling of those +methods to the Zope process. In most cases, servers will allow the process +to handle any request, so the Zope portion of your url namespace may well +be able to handle WebDAV operations even though your web server software +is not WebDAV-aware itself. Zope installations which use bundled server +implementations such as ZopeHTTPServer or ZServer should fully support +WebDAV functions. - References: +References: - [WebDAV] Y. Y. Goland, E. J. Whitehead, Jr., A. Faizi, S. R. Carter, D. - Jensen, "HTTP Extensions for Distributed Authoring - WebDAV." RFC 2518. - Microsoft, U.C. Irvine, Netscape, Novell. February, 1999.""" +[WebDAV] Y. Y. Goland, E. J. Whitehead, Jr., A. Faizi, S. R. Carter, D. +Jensen, "HTTP Extensions for Distributed Authoring - WebDAV." RFC 2518. +Microsoft, U.C. Irvine, Netscape, Novell. February, 1999. +""" enable_ms_public_header = False diff --git a/src/webdav/common.py b/src/webdav/common.py index b9eb643808..161cf5f74a 100644 --- a/src/webdav/common.py +++ b/src/webdav/common.py @@ -125,7 +125,7 @@ def __init__(self): def IfParser(hdr): out = [] i = 0 - while 1: + while True: m = IfHdr.search(hdr[i:]) if not m: break @@ -146,7 +146,7 @@ def ListParser(listitem): out = [] NOTTED = 0 i = 0 - while 1: + while True: m = ListItem.search(listitem[i:]) if not m: break diff --git a/src/webdav/davcmds.py b/src/webdav/davcmds.py index bf33396ca2..744cb7dc16 100644 --- a/src/webdav/davcmds.py +++ b/src/webdav/davcmds.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""WebDAV xml request objects. -""" +"""WebDAV xml request objects.""" import sys from io import StringIO @@ -47,10 +46,12 @@ def safe_quote(url, mark=r'%'): class DAVProps(DAVProperties): - """Emulate required DAV properties for objects which do - not themselves support properties. This is mainly so - that non-PropertyManagers can appear to support DAV - PROPFIND requests.""" + """Emulate required DAV properties for objects which do not themselves + support properties. + + This is mainly so that non-PropertyManagers can appear to support + DAV PROPFIND requests. + """ def __init__(self, obj): self.__obj__ = obj @@ -350,8 +351,8 @@ def parse(self, data, dav='DAV:'): def apply(self, obj, creator=None, depth='infinity', token=None, result=None, url=None, top=1): - """ Apply, built for recursion (so that we may lock subitems - of a collection if requested """ + """Apply, built for recursion (so that we may lock subitems of a + collection if requested.""" if result is None: result = StringIO() @@ -434,7 +435,7 @@ def apply(self, obj, creator=None, depth='infinity', token=None, class Unlock: - """ Model an Unlock request """ + """Model an Unlock request.""" def apply(self, obj, token, url=None, result=None, top=1): if result is None: @@ -500,9 +501,9 @@ def apply(self, obj, token, url=None, result=None, top=1): class DeleteCollection: - """ With WriteLocks in the picture, deleting a collection involves - checking *all* descendents (deletes on collections are always of depth - infinite) for locks and if the locks match. """ + """With WriteLocks in the picture, deleting a collection involves checking + *all* descendents (deletes on collections are always of depth infinite) for + locks and if the locks match.""" def apply(self, obj, token, sm, url=None, result=None, top=1): if result is None: diff --git a/src/webdav/hookable_PUT.py b/src/webdav/hookable_PUT.py index 41f99edbf4..99f3aac67c 100644 --- a/src/webdav/hookable_PUT.py +++ b/src/webdav/hookable_PUT.py @@ -8,8 +8,7 @@ def PUT_factory(self, name, typ, body): - """ - """ + """""" if TEXT_PATTERN.match(typ): return OFS.DTMLMethod.DTMLMethod('', __name__=name) return None diff --git a/src/webdav/interfaces.py b/src/webdav/interfaces.py index 0a2a545f11..96517756be 100644 --- a/src/webdav/interfaces.py +++ b/src/webdav/interfaces.py @@ -10,8 +10,7 @@ # FOR A PARTICULAR PURPOSE. # ############################################################################## -"""webdav interfaces. -""" +"""Webdav interfaces.""" from OFS.interfaces import IWriteLock from zope.schema import Bool @@ -22,7 +21,6 @@ # not synced with ZopeBook API Reference; # based on webdav.Resource.Resource class IDAVResource(IWriteLock): - """Provide basic WebDAV support for non-collection objects.""" __dav_resource__ = Bool( @@ -33,47 +31,52 @@ class IDAVResource(IWriteLock): description="Sequence of valid HTTP methods") def dav__init(request, response): - """Init expected HTTP 1.1 / WebDAV headers which are not - currently set by the base response object automagically. + """Init expected HTTP 1.1 / WebDAV headers which are not currently set + by the base response object automagically. Also, we sniff for a ZServer response object, because we don't - want to write duplicate headers (since ZS writes Date - and Connection itself). + want to write duplicate headers (since ZS writes Date and + Connection itself). """ def dav__validate(object, methodname, REQUEST): - """ - """ + """""" def dav__simpleifhandler(request, response, method='PUT', col=0, url=None, refresh=0): - """ - """ + """""" def HEAD(REQUEST, RESPONSE): """Retrieve resource information without a response body.""" def PUT(REQUEST, RESPONSE): """Replace the GET response entity of an existing resource. - Because this is often object-dependent, objects which handle - PUT should override the default PUT implementation with an - object-specific implementation. By default, PUT requests - fail with a 405 (Method Not Allowed).""" + + Because this is often object-dependent, objects which handle PUT + should override the default PUT implementation with an object- + specific implementation. By default, PUT requests fail with a + 405 (Method Not Allowed). + """ def OPTIONS(REQUEST, RESPONSE): """Retrieve communication options.""" def TRACE(REQUEST, RESPONSE): - """Return the HTTP message received back to the client as the - entity-body of a 200 (OK) response. This will often usually - be intercepted by the web server in use. If not, the TRACE - request will fail with a 405 (Method Not Allowed), since it - is not often possible to reproduce the HTTP request verbatim - from within the Zope environment.""" + """Return the HTTP message received back to the client as the entity- + body of a 200 (OK) response. + + This will often usually be intercepted by the web server in use. + If not, the TRACE request will fail with a 405 (Method Not + Allowed), since it is not often possible to reproduce the HTTP + request verbatim from within the Zope environment. + """ def DELETE(REQUEST, RESPONSE): - """Delete a resource. For non-collection resources, DELETE may - return either 200 or 204 (No Content) to indicate success.""" + """Delete a resource. + + For non-collection resources, DELETE may return either 200 or + 204 (No Content) to indicate success. + """ def PROPFIND(REQUEST, RESPONSE): """Retrieve properties defined on the resource.""" @@ -82,59 +85,72 @@ def PROPPATCH(REQUEST, RESPONSE): """Set and/or remove properties defined on the resource.""" def MKCOL(REQUEST, RESPONSE): - """Create a new collection resource. If called on an existing - resource, MKCOL must fail with 405 (Method Not Allowed).""" + """Create a new collection resource. + + If called on an existing resource, MKCOL must fail with 405 + (Method Not Allowed). + """ def COPY(REQUEST, RESPONSE): - """Create a duplicate of the source resource whose state - and behavior match that of the source resource as closely - as possible. Though we may later try to make a copy appear - seamless across namespaces (e.g. from Zope to Apache), COPY - is currently only supported within the Zope namespace.""" + """Create a duplicate of the source resource whose state and behavior + match that of the source resource as closely as possible. + + Though we may later try to make a copy appear seamless across + namespaces (e.g. from Zope to Apache), COPY is currently only + supported within the Zope namespace. + """ def MOVE(REQUEST, RESPONSE): - """Move a resource to a new location. Though we may later try to - make a move appear seamless across namespaces (e.g. from Zope - to Apache), MOVE is currently only supported within the Zope - namespace.""" + """Move a resource to a new location. + + Though we may later try to make a move appear seamless across + namespaces (e.g. from Zope to Apache), MOVE is currently only + supported within the Zope namespace. + """ def LOCK(REQUEST, RESPONSE): - """Lock a resource""" + """Lock a resource.""" def UNLOCK(REQUEST, RESPONSE): """Remove an existing lock on a resource.""" def manage_DAVget(): - """Gets the document source""" + """Gets the document source.""" def listDAVObjects(): - """ - """ + """""" # XXX: might contain non-API methods and outdated comments; # not synced with ZopeBook API Reference; # based on webdav.Collection.Collection class IDAVCollection(IDAVResource): + """The Collection class provides basic WebDAV support for collection + objects. - """The Collection class provides basic WebDAV support for - collection objects. It provides default implementations - for all supported WebDAV HTTP methods. The behaviors of some - WebDAV HTTP methods for collections are slightly different - than those for non-collection resources.""" + It provides default implementations for all supported WebDAV HTTP + methods. The behaviors of some WebDAV HTTP methods for collections + are slightly different than those for non-collection resources. + """ __dav_collection__ = Bool( title="Is a DAV collection", description="Should be true") def PUT(REQUEST, RESPONSE): - """The PUT method has no inherent meaning for collection - resources, though collections are not specifically forbidden - to handle PUT requests. The default response to a PUT request - for collections is 405 (Method Not Allowed).""" + """The PUT method has no inherent meaning for collection resources, + though collections are not specifically forbidden to handle PUT + requests. + + The default response to a PUT request for collections is 405 + (Method Not Allowed). + """ def DELETE(REQUEST, RESPONSE): - """Delete a collection resource. For collection resources, DELETE - may return either 200 (OK) or 204 (No Content) to indicate total - success, or may return 207 (Multistatus) to indicate partial - success. Note that in Zope a DELETE currently never returns 207.""" + """Delete a collection resource. + + For collection resources, DELETE may return either 200 (OK) or + 204 (No Content) to indicate total success, or may return 207 + (Multistatus) to indicate partial success. Note that in Zope a + DELETE currently never returns 207. + """ diff --git a/src/webdav/tests/testCopySupportEvents.py b/src/webdav/tests/testCopySupportEvents.py index 470c17e462..f80bf79404 100644 --- a/src/webdav/tests/testCopySupportEvents.py +++ b/src/webdav/tests/testCopySupportEvents.py @@ -95,7 +95,7 @@ def tearDown(self): class TestCopySupport(EventTest): - '''Tests the order in which events are fired''' + """Tests the order in which events are fired.""" def setUp(self): EventTest.setUp(self) @@ -157,7 +157,7 @@ def test_7_DELETE(self): class TestCopySupportSublocation(EventTest): - '''Tests the order in which events are fired''' + """Tests the order in which events are fired.""" def setUp(self): EventTest.setUp(self) diff --git a/src/webdav/tests/testCopySupportHooks.py b/src/webdav/tests/testCopySupportHooks.py index 25f8d15bbd..6059aaadc3 100644 --- a/src/webdav/tests/testCopySupportHooks.py +++ b/src/webdav/tests/testCopySupportHooks.py @@ -102,7 +102,7 @@ def tearDown(self): class TestCopySupport(HookTest): - '''Tests the order in which add/clone/del hooks are called''' + """Tests the order in which add/clone/del hooks are called.""" def setUp(self): HookTest.setUp(self) @@ -157,7 +157,7 @@ def test_7_DELETE(self): class TestCopySupportSublocation(HookTest): - '''Tests the order in which add/clone/del hooks are called''' + """Tests the order in which add/clone/del hooks are called.""" def setUp(self): HookTest.setUp(self) diff --git a/src/webdav/tests/test_davcmds.py b/src/webdav/tests/test_davcmds.py index 1241936252..ba02658e7f 100644 --- a/src/webdav/tests/test_davcmds.py +++ b/src/webdav/tests/test_davcmds.py @@ -72,8 +72,8 @@ def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) def test_parse_xml_property_values_with_namespaces(self): - """ - Before Zope 2.11, litmus props tests 19: propvalnspace and 20: + """Before Zope 2.11, litmus props tests 19: propvalnspace and 20: + propwformed were failing because Zope did not strip off the xmlns: attribute attached to XML property values. We now strip off all attributes that look like xmlns declarations. diff --git a/src/webdav/xmltools.py b/src/webdav/xmltools.py index 3fc2a6f215..f2ecc47721 100644 --- a/src/webdav/xmltools.py +++ b/src/webdav/xmltools.py @@ -10,9 +10,8 @@ # FOR A PARTICULAR PURPOSE # ############################################################################## -""" -WebDAV XML request parsing tool using xml.minidom as xml parser. -Code contributed by Simon Eisenmann, struktur AG, Stuttgart, Germany +"""WebDAV XML request parsing tool using xml.minidom as xml parser. Code +contributed by Simon Eisenmann, struktur AG, Stuttgart, Germany. TODO: @@ -28,7 +27,6 @@ strings. While this is suboptimal, it does match the expected encoding from OFS.PropertySheet. We need to find a the encoding somehow, maybe use the same encoding as the ZMI is using? - """ from io import BytesIO @@ -72,8 +70,7 @@ def unescape(value, entities=None): class Node: - """ Our nodes no matter what type - """ + """Our nodes no matter what type.""" node = None @@ -189,6 +186,7 @@ def toxml(self): class ProtectedExpatParser(ExpatParser): """ See https://bugs.launchpad.net/zope2/+bug/1114688 """ + def __init__(self, forbid_dtd=True, forbid_entities=True, *args, **kwargs): # Python 2.x old style class @@ -217,9 +215,8 @@ def reset(self): class XmlParser: - """ Simple wrapper around minidom to support the required - interfaces for zope.webdav - """ + """Simple wrapper around minidom to support the required interfaces for + zope.webdav.""" dom = None diff --git a/src/zmi/styles/tests.py b/src/zmi/styles/tests.py index 256edfa74b..0b72fa4203 100644 --- a/src/zmi/styles/tests.py +++ b/src/zmi/styles/tests.py @@ -23,6 +23,7 @@ class SubscriberTests(Testing.ZopeTestCase.FunctionalTestCase): def call_manage_main(self): """Call /folder/manage_main and return the HTML text.""" + def _call_manage_main(self): self.setRoles(['Manager']) # temporaryPlacelessSetUp insists in creating an interaction diff --git a/util.py b/util.py index 3157c3faf7..d45c89be0a 100644 --- a/util.py +++ b/util.py @@ -1,7 +1,9 @@ import os -from typing import Optional, Tuple, List from configparser import NoSectionError from configparser import RawConfigParser +from typing import List +from typing import Optional +from typing import Tuple HERE = os.path.abspath(os.path.dirname(__file__)) From 19cc6c13521b5abe7b7042d5624eacde10b2bb9a Mon Sep 17 00:00:00 2001 From: Steffen Allner Date: Thu, 21 Sep 2023 15:30:54 +0200 Subject: [PATCH 03/12] Unfortunately a second run was needed. --- src/Testing/ZopeTestCase/testPortalTestCase.py | 3 +-- src/Testing/ZopeTestCase/testZopeTestCase.py | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Testing/ZopeTestCase/testPortalTestCase.py b/src/Testing/ZopeTestCase/testPortalTestCase.py index 661b9cd293..c844afc39f 100644 --- a/src/Testing/ZopeTestCase/testPortalTestCase.py +++ b/src/Testing/ZopeTestCase/testPortalTestCase.py @@ -395,8 +395,7 @@ def assertPermissionsOfRole(self, permissions, role, context=None): Fails if the lists are not found equal. """ lhs = sorted(list(permissions)[:]) - rhs = self.getPermissionsOfRole(role, context) - rhs.sort() + rhs = sorted(self.getPermissionsOfRole(role, context)) self.assertEqual(lhs, rhs) def assertRolesOfUser(self, roles, user): diff --git a/src/Testing/ZopeTestCase/testZopeTestCase.py b/src/Testing/ZopeTestCase/testZopeTestCase.py index 8e421e2ac4..9bac65da6e 100644 --- a/src/Testing/ZopeTestCase/testZopeTestCase.py +++ b/src/Testing/ZopeTestCase/testZopeTestCase.py @@ -326,8 +326,7 @@ def assertPermissionsOfRole(self, permissions, role, context=None): Fails if the lists are not found equal. """ lhs = sorted(list(permissions)[:]) - rhs = self.getPermissionsOfRole(role, context) - rhs.sort() + rhs = sorted(self.getPermissionsOfRole(role, context)) self.assertEqual(lhs, rhs) def assertRolesOfUser(self, roles, user): From 6f609ac8c507ca6f7f8cc4351f7a40e1dc5411e6 Mon Sep 17 00:00:00 2001 From: Steffen Allner Date: Thu, 21 Sep 2023 16:50:26 +0200 Subject: [PATCH 04/12] Some doc strings need to have a value to be traversable. This fixes some tests. --- CHANGES.rst | 2 ++ src/Products/Five/tests/testing/simplecontent.py | 4 ++-- src/ZPublisher/tests/testBaseRequest.py | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 54bf47ddae..2e307f6ba7 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -13,6 +13,8 @@ https://github.com/zopefoundation/Zope/blob/4.x/CHANGES.rst - Update to newest compatible versions of dependencies. +- Move all linters to pre-commit (hook). + 5.8.5 (2023-09-21) ------------------ diff --git a/src/Products/Five/tests/testing/simplecontent.py b/src/Products/Five/tests/testing/simplecontent.py index dba8de5414..80b0c1b0c8 100644 --- a/src/Products/Five/tests/testing/simplecontent.py +++ b/src/Products/Five/tests/testing/simplecontent.py @@ -62,7 +62,7 @@ class CallableSimpleContent(SimpleItem): meta_type = "Five CallableSimpleContent" def __call__(self, *args, **kw): - """""" + """.""" # We need some content to be traversable. return "Default __call__ called" @@ -76,7 +76,7 @@ class IndexSimpleContent(SimpleItem): meta_type = 'Five IndexSimpleContent' def index_html(self, *args, **kw): - """""" + """.""" # We need some content to be traversable. return "Default index_html called" diff --git a/src/ZPublisher/tests/testBaseRequest.py b/src/ZPublisher/tests/testBaseRequest.py index a7b52e0813..07e15749db 100644 --- a/src/ZPublisher/tests/testBaseRequest.py +++ b/src/ZPublisher/tests/testBaseRequest.py @@ -129,7 +129,7 @@ def _makeObjectWithBBT(self): from ZPublisher.interfaces import UseTraversalDefault class _DummyResult: - """""" + """.""" # We need some content to be traversable. def __init__(self, tag): self.tag = tag From decedb0676871d1fdb504f943bbee941b414089c Mon Sep 17 00:00:00 2001 From: Steffen Allner Date: Thu, 21 Sep 2023 16:58:29 +0200 Subject: [PATCH 05/12] Add new linter `teyit` for deprecated assert statements. --- .pre-commit-config.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2089cb479d..71760bedee 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -27,6 +27,11 @@ repos: additional_dependencies: - flake8-coding - flake8-debugger + - repo: https://github.com/isidentical/teyit + rev: 0.4.3 + hooks: + - id: teyit + exclude: src/App/tests/fixtures/error.py # invalid syntax - repo: https://github.com/mgedmin/check-manifest rev: "0.49" hooks: From 50efcb09f4faa1fb47059beaf8ab8c88b56f1f41 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci-lite[bot]" <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com> Date: Thu, 21 Sep 2023 15:12:00 +0000 Subject: [PATCH 06/12] [pre-commit.ci lite] apply automatic fixes --- src/App/tests/test_ApplicationManager.py | 24 ++-- src/OFS/tests/testAppInitializer.py | 8 +- src/OFS/tests/testCopySupport.py | 124 +++++++++--------- src/OFS/tests/testFileAndImage.py | 20 +-- src/OFS/tests/testHistory.py | 10 +- src/OFS/tests/testObjectManager.py | 52 ++++---- src/OFS/tests/testRanges.py | 8 +- src/OFS/tests/testSimpleItem.py | 4 +- src/OFS/tests/testTraverse.py | 31 +++-- src/OFS/tests/test_DTMLDocument.py | 4 +- src/OFS/tests/test_DTMLMethod.py | 4 +- src/OFS/tests/test_Uninstalled.py | 4 +- src/OFS/tests/test_userfolder.py | 4 +- .../Five/browser/tests/test_metaconfigure.py | 14 +- .../browser/tests/test_pagetemplatefile.py | 30 ++--- .../utilities/browser/tests/test_marker.py | 2 +- .../PageTemplates/tests/testExpressions.py | 8 +- .../PageTemplates/tests/testZRPythonExpr.py | 4 +- .../tests/testZopePageTemplate.py | 2 +- .../PageTemplates/tests/test_engine.py | 15 ++- .../PageTemplates/tests/test_pagetemplate.py | 18 +-- .../tests/test_viewpagetemplatefile.py | 20 +-- .../tests/testVirtualHostMonster.py | 4 +- .../ZopeTestCase/testPortalTestCase.py | 14 +- src/Testing/ZopeTestCase/testZODBCompat.py | 8 +- src/Testing/ZopeTestCase/testZopeTestCase.py | 12 +- src/Testing/tests/test_testbrowser.py | 8 +- src/ZPublisher/tests/testBaseRequest.py | 2 +- src/ZPublisher/tests/testHTTPRangeSupport.py | 18 ++- src/ZPublisher/tests/testHTTPRequest.py | 60 +++++---- src/ZPublisher/tests/testHTTPResponse.py | 69 ++++++---- src/ZPublisher/tests/test_WSGIPublisher.py | 46 +++---- src/ZPublisher/tests/test_cookie.py | 4 +- src/ZPublisher/tests/test_pubevents.py | 2 +- src/ZPublisher/tests/test_xmlrpc.py | 16 +-- src/ZTUtils/tests/testTree.py | 10 +- src/Zope2/App/tests/test_schema.py | 2 +- src/webdav/tests/testPUT_factory.py | 12 +- src/webdav/tests/testResource.py | 10 +- 39 files changed, 374 insertions(+), 333 deletions(-) diff --git a/src/App/tests/test_ApplicationManager.py b/src/App/tests/test_ApplicationManager.py index ec227e16ab..8690f157b1 100644 --- a/src/App/tests/test_ApplicationManager.py +++ b/src/App/tests/test_ApplicationManager.py @@ -131,7 +131,7 @@ def test_holds_db(self): db = object() parent_jar = object() fc = self._makeOne(db, parent_jar) - self.assertTrue(fc.db() is db) + self.assertIs(fc.db(), db) class ConfigurationViewerTests(ConfigTestBase, unittest.TestCase): @@ -204,10 +204,10 @@ def test___getitem___hit(self): found = dc['foo'] self.assertIsInstance(found, AltDatabaseManager) self.assertEqual(found.id, 'foo') - self.assertTrue(found.__parent__ is dc) + self.assertIs(found.__parent__, dc) conn = found._p_jar self.assertIsInstance(conn, FakeConnection) - self.assertTrue(conn.db() is foo) + self.assertIs(conn.db(), foo) def test___bobo_traverse___miss(self): self._makeConfig(foo=object(), bar=object(), qux=object()) @@ -227,10 +227,10 @@ def test___bobo_traverse___hit_db(self): found = dc.__bobo_traverse__(None, 'foo') self.assertIsInstance(found, AltDatabaseManager) self.assertEqual(found.id, 'foo') - self.assertTrue(found.__parent__ is dc) + self.assertIs(found.__parent__, dc) conn = found._p_jar self.assertIsInstance(conn, FakeConnection) - self.assertTrue(conn.db() is foo) + self.assertIs(conn.db(), foo) def test___bobo_traverse___miss_db_hit_attr(self): foo = object() @@ -241,7 +241,7 @@ def test___bobo_traverse___miss_db_hit_attr(self): dc = self._makeOne().__of__(root) dc.spam = spam = object() found = dc.__bobo_traverse__(None, 'spam') - self.assertTrue(found is spam) + self.assertIs(found, spam) class ApplicationManagerTests(ConfigTestBase, unittest.TestCase): @@ -493,11 +493,11 @@ def test_refcount_no_limit(self): pairs = dm.refcount() # XXX : Ugly empiricism here: I don't know why the count is up 1. foo_count = sys.getrefcount(Foo) - self.assertTrue((foo_count + 1, 'foo.Foo') in pairs) + self.assertIn((foo_count + 1, 'foo.Foo'), pairs) bar_count = sys.getrefcount(Bar) - self.assertTrue((bar_count + 1, 'foo.Bar') in pairs) + self.assertIn((bar_count + 1, 'foo.Bar'), pairs) baz_count = sys.getrefcount(Baz) - self.assertTrue((baz_count + 1, 'qux.Baz') in pairs) + self.assertIn((baz_count + 1, 'qux.Baz'), pairs) def test_refdict(self): import sys @@ -539,7 +539,7 @@ def test_rcdate(self): dm = self._makeOne('test') found = dm.rcdate() App.ApplicationManager._v_rst = None - self.assertTrue(found is dummy) + self.assertIs(found, dummy) def test_rcdeltas(self): dm = self._makeOne('test') @@ -548,8 +548,8 @@ def test_rcdeltas(self): mappings = dm.rcdeltas() self.assertTrue(len(mappings)) mapping = mappings[0] - self.assertTrue('rc' in mapping) - self.assertTrue('pc' in mapping) + self.assertIn('rc', mapping) + self.assertIn('pc', mapping) self.assertEqual(mapping['delta'], mapping['rc'] - mapping['pc']) # def test_dbconnections(self): XXX -- TOO UGLY TO TEST diff --git a/src/OFS/tests/testAppInitializer.py b/src/OFS/tests/testAppInitializer.py index 01c256fc02..a6278a293e 100644 --- a/src/OFS/tests/testAppInitializer.py +++ b/src/OFS/tests/testAppInitializer.py @@ -84,7 +84,7 @@ def test_install_virtual_hosting(self): i = self.getOne() i.install_virtual_hosting() app = i.getApp() - self.assertTrue('virtual_hosting' in app) + self.assertIn('virtual_hosting', app) self.assertEqual( app.virtual_hosting.meta_type, 'Virtual Host Monster') @@ -93,8 +93,8 @@ def test_install_required_roles(self): i = self.getOne() i.install_required_roles() app = i.getApp() - self.assertTrue('Owner' in app.__ac_roles__) - self.assertTrue('Authenticated' in app.__ac_roles__) + self.assertIn('Owner', app.__ac_roles__) + self.assertIn('Authenticated', app.__ac_roles__) def test_install_inituser(self): fname = os.path.join(self.TEMPNAME, 'inituser') @@ -122,7 +122,7 @@ def test_install_root_view(self): i = self.getOne() i.install_root_view() app = i.getApp() - self.assertTrue('index_html' in app) + self.assertIn('index_html', app) self.assertEqual(app.index_html.meta_type, 'Page Template') def test_install_products_which_need_the_application(self): diff --git a/src/OFS/tests/testCopySupport.py b/src/OFS/tests/testCopySupport.py index 1b644544bc..5929f53087 100644 --- a/src/OFS/tests/testCopySupport.py +++ b/src/OFS/tests/testCopySupport.py @@ -136,56 +136,56 @@ def test_interfaces(self): verifyClass(ICopySource, CopySource) def testRename(self): - self.assertTrue('file' in self.folder1.objectIds()) + self.assertIn('file', self.folder1.objectIds()) self.folder1.manage_renameObject(id='file', new_id='filex') - self.assertFalse('file' in self.folder1.objectIds()) - self.assertTrue('filex' in self.folder1.objectIds()) + self.assertNotIn('file', self.folder1.objectIds()) + self.assertIn('filex', self.folder1.objectIds()) def testCopy(self): - self.assertTrue('file' in self.folder1.objectIds()) - self.assertFalse('file' in self.folder2.objectIds()) + self.assertIn('file', self.folder1.objectIds()) + self.assertNotIn('file', self.folder2.objectIds()) cookie = self.folder1.manage_copyObjects(ids=('file',)) self.folder2.manage_pasteObjects(cookie) - self.assertTrue('file' in self.folder1.objectIds()) - self.assertTrue('file' in self.folder2.objectIds()) + self.assertIn('file', self.folder1.objectIds()) + self.assertIn('file', self.folder2.objectIds()) def testCut(self): - self.assertTrue('file' in self.folder1.objectIds()) - self.assertFalse('file' in self.folder2.objectIds()) + self.assertIn('file', self.folder1.objectIds()) + self.assertNotIn('file', self.folder2.objectIds()) cookie = self.folder1.manage_cutObjects(ids=('file',)) self.folder2.manage_pasteObjects(cookie) - self.assertFalse('file' in self.folder1.objectIds()) - self.assertTrue('file' in self.folder2.objectIds()) + self.assertNotIn('file', self.folder1.objectIds()) + self.assertIn('file', self.folder2.objectIds()) def testCopyNewObject(self): - self.assertFalse('newfile' in self.folder1.objectIds()) + self.assertNotIn('newfile', self.folder1.objectIds()) manage_addFile(self.folder1, 'newfile', file=b'', content_type='text/plain') cookie = self.folder1.manage_copyObjects(ids=('newfile',)) self.folder2.manage_pasteObjects(cookie) - self.assertTrue('newfile' in self.folder1.objectIds()) - self.assertTrue('newfile' in self.folder2.objectIds()) + self.assertIn('newfile', self.folder1.objectIds()) + self.assertIn('newfile', self.folder2.objectIds()) def testPasteSingleNotSameID(self): - self.assertTrue('file' in self.folder1.objectIds()) - self.assertFalse('file' in self.folder2.objectIds()) + self.assertIn('file', self.folder1.objectIds()) + self.assertNotIn('file', self.folder2.objectIds()) cookie = self.folder1.manage_copyObjects(ids=('file',)) result = self.folder2.manage_pasteObjects(cookie) - self.assertTrue('file' in self.folder1.objectIds()) - self.assertTrue('file' in self.folder2.objectIds()) - self.assertTrue(result == [{'id': 'file', 'new_id': 'file'}]) + self.assertIn('file', self.folder1.objectIds()) + self.assertIn('file', self.folder2.objectIds()) + self.assertEqual(result, [{'id': 'file', 'new_id': 'file'}]) def testPasteSingleSameID(self): - self.assertTrue('file' in self.folder1.objectIds()) - self.assertFalse('file' in self.folder2.objectIds()) + self.assertIn('file', self.folder1.objectIds()) + self.assertNotIn('file', self.folder2.objectIds()) manage_addFile(self.folder2, 'file', file=b'', content_type='text/plain') cookie = self.folder1.manage_copyObjects(ids=('file',)) result = self.folder2.manage_pasteObjects(cookie) - self.assertTrue('file' in self.folder1.objectIds()) - self.assertTrue('file' in self.folder2.objectIds()) - self.assertTrue('copy_of_file' in self.folder2.objectIds()) - self.assertTrue(result == [{'id': 'file', 'new_id': 'copy_of_file'}]) + self.assertIn('file', self.folder1.objectIds()) + self.assertIn('file', self.folder2.objectIds()) + self.assertIn('copy_of_file', self.folder2.objectIds()) + self.assertEqual(result, [{'id': 'file', 'new_id': 'copy_of_file'}]) def testPasteSingleSameIDMultipleTimes(self): cookie = self.folder1.manage_copyObjects(ids=('file',)) @@ -225,25 +225,25 @@ def testPasteSpecialName(self): self.assertEqual(result, [{'id': 'copy_of_', 'new_id': 'copy2_of_'}]) def testPasteMultiNotSameID(self): - self.assertTrue('file' in self.folder1.objectIds()) - self.assertFalse('file1' in self.folder1.objectIds()) + self.assertIn('file', self.folder1.objectIds()) + self.assertNotIn('file1', self.folder1.objectIds()) manage_addFile(self.folder1, 'file1', file=b'', content_type='text/plain') - self.assertFalse('file2' in self.folder1.objectIds()) + self.assertNotIn('file2', self.folder1.objectIds()) manage_addFile(self.folder1, 'file2', file=b'', content_type='text/plain') - self.assertFalse('file' in self.folder2.objectIds()) - self.assertFalse('file1' in self.folder2.objectIds()) - self.assertFalse('file2' in self.folder2.objectIds()) + self.assertNotIn('file', self.folder2.objectIds()) + self.assertNotIn('file1', self.folder2.objectIds()) + self.assertNotIn('file2', self.folder2.objectIds()) cookie = self.folder1.manage_copyObjects( ids=('file', 'file1', 'file2',)) result = self.folder2.manage_pasteObjects(cookie) - self.assertTrue('file' in self.folder1.objectIds()) - self.assertTrue('file1' in self.folder1.objectIds()) - self.assertTrue('file2' in self.folder1.objectIds()) - self.assertTrue('file' in self.folder2.objectIds()) - self.assertTrue('file1' in self.folder2.objectIds()) - self.assertTrue('file2' in self.folder2.objectIds()) + self.assertIn('file', self.folder1.objectIds()) + self.assertIn('file1', self.folder1.objectIds()) + self.assertIn('file2', self.folder1.objectIds()) + self.assertIn('file', self.folder2.objectIds()) + self.assertIn('file1', self.folder2.objectIds()) + self.assertIn('file2', self.folder2.objectIds()) self.assertEqual(result, [ {'id': 'file', 'new_id': 'file'}, {'id': 'file1', 'new_id': 'file1'}, @@ -251,34 +251,34 @@ def testPasteMultiNotSameID(self): ]) def testPasteMultiSameID(self): - self.assertTrue('file' in self.folder1.objectIds()) - self.assertFalse('file1' in self.folder1.objectIds()) + self.assertIn('file', self.folder1.objectIds()) + self.assertNotIn('file1', self.folder1.objectIds()) manage_addFile(self.folder1, 'file1', file=b'', content_type='text/plain') - self.assertFalse('file2' in self.folder1.objectIds()) + self.assertNotIn('file2', self.folder1.objectIds()) manage_addFile(self.folder1, 'file2', file=b'', content_type='text/plain') - self.assertFalse('file' in self.folder2.objectIds()) + self.assertNotIn('file', self.folder2.objectIds()) manage_addFile(self.folder2, 'file', file=b'', content_type='text/plain') - self.assertFalse('file1' in self.folder2.objectIds()) + self.assertNotIn('file1', self.folder2.objectIds()) manage_addFile(self.folder2, 'file1', file=b'', content_type='text/plain') - self.assertFalse('file2' in self.folder2.objectIds()) + self.assertNotIn('file2', self.folder2.objectIds()) manage_addFile(self.folder2, 'file2', file=b'', content_type='text/plain') cookie = self.folder1.manage_copyObjects( ids=('file', 'file1', 'file2',)) result = self.folder2.manage_pasteObjects(cookie) - self.assertTrue('file' in self.folder1.objectIds()) - self.assertTrue('file1' in self.folder1.objectIds()) - self.assertTrue('file2' in self.folder1.objectIds()) - self.assertTrue('file' in self.folder2.objectIds()) - self.assertTrue('file1' in self.folder2.objectIds()) - self.assertTrue('file2' in self.folder2.objectIds()) - self.assertTrue('copy_of_file' in self.folder2.objectIds()) - self.assertTrue('copy_of_file1' in self.folder2.objectIds()) - self.assertTrue('copy_of_file2' in self.folder2.objectIds()) + self.assertIn('file', self.folder1.objectIds()) + self.assertIn('file1', self.folder1.objectIds()) + self.assertIn('file2', self.folder1.objectIds()) + self.assertIn('file', self.folder2.objectIds()) + self.assertIn('file1', self.folder2.objectIds()) + self.assertIn('file2', self.folder2.objectIds()) + self.assertIn('copy_of_file', self.folder2.objectIds()) + self.assertIn('copy_of_file1', self.folder2.objectIds()) + self.assertIn('copy_of_file2', self.folder2.objectIds()) self.assertEqual(result, [ {'id': 'file', 'new_id': 'copy_of_file'}, {'id': 'file1', 'new_id': 'copy_of_file1'}, @@ -406,14 +406,14 @@ def test_copy_baseline(self): self._initPolicyAndUser() - self.assertTrue('file' in folder1.objectIds()) - self.assertFalse('file' in folder2.objectIds()) + self.assertIn('file', folder1.objectIds()) + self.assertNotIn('file', folder2.objectIds()) cookie = folder1.manage_copyObjects(ids=('file', )) folder2.manage_pasteObjects(cookie) - self.assertTrue('file' in folder1.objectIds()) - self.assertTrue('file' in folder2.objectIds()) + self.assertIn('file', folder1.objectIds()) + self.assertIn('file', folder2.objectIds()) def test_copy_cant_read_source(self): folder1, folder2 = self._initFolders() @@ -470,24 +470,24 @@ def test_copy_cant_copy_invisible_items(self): new_id = copy_info[0]['new_id'] new_folder = folder2[new_id] # The private item should not be in the copy. - self.assertTrue('private' not in new_folder.objectIds()) + self.assertNotIn('private', new_folder.objectIds()) # There is nothing wrong with copying the public item. - self.assertTrue('public' in new_folder.objectIds()) + self.assertIn('public', new_folder.objectIds()) def test_move_baseline(self): folder1, folder2 = self._initFolders() folder2.all_meta_types = FILE_META_TYPES - self.assertTrue('file' in folder1.objectIds()) - self.assertFalse('file' in folder2.objectIds()) + self.assertIn('file', folder1.objectIds()) + self.assertNotIn('file', folder2.objectIds()) self._initPolicyAndUser() cookie = folder1.manage_cutObjects(ids=('file', )) folder2.manage_pasteObjects(cookie) - self.assertFalse('file' in folder1.objectIds()) - self.assertTrue('file' in folder2.objectIds()) + self.assertNotIn('file', folder1.objectIds()) + self.assertIn('file', folder2.objectIds()) def test_move_cant_read_source(self): folder1, folder2 = self._initFolders() diff --git a/src/OFS/tests/testFileAndImage.py b/src/OFS/tests/testFileAndImage.py index 1e744f9dec..f596689798 100644 --- a/src/OFS/tests/testFileAndImage.py +++ b/src/OFS/tests/testFileAndImage.py @@ -152,12 +152,16 @@ def setUp(self): # Since we do the create here, let's test the events here too self.assertEqual(1, len(self.eventCatcher.created)) - self.assertTrue( - aq_base(self.eventCatcher.created[0].object) is aq_base(self.file)) + self.assertIs( + aq_base(self.eventCatcher.created[0].object), + aq_base(self.file) + ) self.assertEqual(1, len(self.eventCatcher.modified)) - self.assertTrue( - aq_base(self.eventCatcher.created[0].object) is aq_base(self.file)) + self.assertIs( + aq_base(self.eventCatcher.created[0].object), + aq_base(self.file) + ) self.eventCatcher.reset() @@ -207,7 +211,7 @@ def testManageEditWithFileData(self): self.assertTrue(ADummyCache.invalidated) self.assertTrue(ADummyCache.set) self.assertEqual(1, len(self.eventCatcher.modified)) - self.assertTrue(self.eventCatcher.modified[0].object is self.file) + self.assertIs(self.eventCatcher.modified[0].object, self.file) def testManageEditWithoutFileData(self): self.file.manage_edit('foobar', 'text/plain') @@ -215,7 +219,7 @@ def testManageEditWithoutFileData(self): self.assertEqual(self.file.content_type, 'text/plain') self.assertTrue(ADummyCache.invalidated) self.assertEqual(1, len(self.eventCatcher.modified)) - self.assertTrue(self.eventCatcher.modified[0].object is self.file) + self.assertIs(self.eventCatcher.modified[0].object, self.file) def testManageUpload(self): f = BytesIO(b'jammyjohnson') @@ -223,7 +227,7 @@ def testManageUpload(self): self.assertEqual(self.file.data, b'jammyjohnson') self.assertEqual(self.file.content_type, 'application/octet-stream') self.assertEqual(1, len(self.eventCatcher.modified)) - self.assertTrue(self.eventCatcher.modified[0].object is self.file) + self.assertIs(self.eventCatcher.modified[0].object, self.file) def testManageUploadWithoutFileData(self): self.file.manage_upload() @@ -297,7 +301,7 @@ def testPrincipiaSearchSource_text(self): self.file.manage_edit('foobar', 'text/plain', filedata=b'Now is the time for all good men to ' b'come to the aid of the Party.') - self.assertTrue(b'Party' in self.file.PrincipiaSearchSource()) + self.assertIn(b'Party', self.file.PrincipiaSearchSource()) def test_manage_DAVget_binary(self): self.assertEqual(self.file.manage_DAVget(), self.data) diff --git a/src/OFS/tests/testHistory.py b/src/OFS/tests/testHistory.py index 710d7c3fa1..2deb8ab282 100644 --- a/src/OFS/tests/testHistory.py +++ b/src/OFS/tests/testHistory.py @@ -77,14 +77,14 @@ def test_manage_change_history(self): self.assertEqual(len(entry.keys()), 6) # the transactions are in newest-first order self.assertEqual(entry['description'], 'Change %i' % (3 - i)) - self.assertTrue('key' in entry) + self.assertIn('key', entry) # lets not assume the size will stay the same forever - self.assertTrue('size' in entry) - self.assertTrue('tid' in entry) - self.assertTrue('time' in entry) + self.assertIn('size', entry) + self.assertIn('tid', entry) + self.assertIn('time', entry) if i: # check times are increasing - self.assertTrue(entry['time'] < r[i - 1]['time']) + self.assertLess(entry['time'], r[i - 1]['time']) self.assertEqual(entry['user_name'], '') def test_manage_historyCopy(self): diff --git a/src/OFS/tests/testObjectManager.py b/src/OFS/tests/testObjectManager.py index edb26b350d..d42c10292a 100644 --- a/src/OFS/tests/testObjectManager.py +++ b/src/OFS/tests/testObjectManager.py @@ -328,15 +328,15 @@ def test_manage_delObjects(self): ob = ItemForDeletion() om._setObject('stuff', ob) om.manage_delObjects('stuff') - self.assertFalse('stuff' in om) + self.assertNotIn('stuff', om) om._setObject('stuff', ob) om.manage_delObjects(['stuff']) - self.assertFalse('stuff' in om) + self.assertNotIn('stuff', om) om._setObject('stuff', ob) om.manage_delObjects('stuff') - self.assertFalse('stuff' in om) + self.assertNotIn('stuff', om) def test_hasObject(self): om = self._makeOne() @@ -401,13 +401,13 @@ def test_getsetitem(self): si1 = SimpleItem('1') si2 = SimpleItem('2') om['1'] = si1 - self.assertTrue('1' in om) - self.assertTrue(si1 in om.objectValues()) - self.assertTrue('1' in om.objectIds()) + self.assertIn('1', om) + self.assertIn(si1, om.objectValues()) + self.assertIn('1', om.objectIds()) om['2'] = si2 - self.assertTrue('2' in om) - self.assertTrue(si2 in om.objectValues()) - self.assertTrue('2' in om.objectIds()) + self.assertIn('2', om) + self.assertIn(si2, om.objectValues()) + self.assertIn('2', om.objectIds()) self.assertRaises(BadRequest, om._setObject, '1', si2) self.assertRaises(BadRequest, om.__setitem__, '1', si2) @@ -417,13 +417,13 @@ def test_delitem(self): si2 = SimpleItem('2') om['1'] = si1 om['2'] = si2 - self.assertTrue('1' in om) - self.assertTrue('2' in om) + self.assertIn('1', om) + self.assertIn('2', om) del om['1'] - self.assertFalse('1' in om) - self.assertTrue('2' in om) + self.assertNotIn('1', om) + self.assertIn('2', om) om._delObject('2') - self.assertFalse('2' in om) + self.assertNotIn('2', om) def test_iterator(self): om = self._makeOne() @@ -435,8 +435,8 @@ def test_iterator(self): self.assertTrue(hasattr(iterator, '__iter__')) self.assertTrue(hasattr(iterator, '__next__')) result = [i for i in iterator] - self.assertTrue('1' in result) - self.assertTrue('2' in result) + self.assertIn('1', result) + self.assertIn('2', result) def test_len(self): om = self._makeOne() @@ -444,7 +444,7 @@ def test_len(self): si2 = SimpleItem('2') om['1'] = si1 om['2'] = si2 - self.assertTrue(len(om) == 2) + self.assertEqual(len(om), 2) def test_nonzero(self): om = self._makeOne() @@ -463,8 +463,8 @@ def test___getitem___hit(self): si1 = SimpleItem('1') om['1'] = si1 got = om['1'] - self.assertTrue(aq_self(got) is si1) - self.assertTrue(got.__parent__ is om) + self.assertIs(aq_self(got), si1) + self.assertIs(got.__parent__, om) def test_get_miss_wo_default(self): om = self._makeOne() @@ -473,7 +473,7 @@ def test_get_miss_wo_default(self): def test_get_miss_w_default(self): om = self._makeOne() obj = object() - self.assertTrue(om.get('nonesuch', obj) is obj) + self.assertIs(om.get('nonesuch', obj), obj) def test_get_miss_w_non_instance_attr(self): om = self._makeOne() @@ -484,26 +484,26 @@ def test_get_hit(self): si1 = SimpleItem('1') om['1'] = si1 got = om.get('1') - self.assertTrue(aq_self(got) is si1) - self.assertTrue(got.__parent__ is om) + self.assertIs(aq_self(got), si1) + self.assertIs(got.__parent__, om) def test_items(self): om = self._makeOne() si1 = SimpleItem('1') om['1'] = si1 - self.assertTrue(('1', si1) in list(om.items())) + self.assertIn(('1', si1), list(om.items())) def test_keys(self): om = self._makeOne() si1 = SimpleItem('1') om['1'] = si1 - self.assertTrue('1' in list(om.keys())) + self.assertIn('1', list(om.keys())) def test_values(self): om = self._makeOne() si1 = SimpleItem('1') om['1'] = si1 - self.assertTrue(si1 in list(om.values())) + self.assertIn(si1, list(om.values())) def test_list_imports(self): om = self._makeOne() @@ -512,7 +512,7 @@ def test_list_imports(self): # in skel/import. Tolerate both cases. self.assertIsInstance(om.list_imports(), list) for filename in om.list_imports(): - self.assertTrue(os.path.splitext(filename)[1] in ('.zexp', '.xml')) + self.assertIn(os.path.splitext(filename)[1], ('.zexp', '.xml')) def test_manage_get_sortedObjects_quote_id(self): # manage_get_sortedObjects now returns a urlquoted version diff --git a/src/OFS/tests/testRanges.py b/src/OFS/tests/testRanges.py index b334f6f3bd..f110f377a3 100644 --- a/src/OFS/tests/testRanges.py +++ b/src/OFS/tests/testRanges.py @@ -128,11 +128,11 @@ def expectUnsatisfiable(self, range): body = self.doGET(req, rsp) - self.assertTrue(rsp.getStatus() == 416) + self.assertEqual(rsp.getStatus(), 416) expect_content_range = 'bytes */%d' % len(self.data) content_range = rsp.getHeader('content-range') - self.assertFalse(content_range is None) + self.assertIsNotNone(content_range) self.assertEqual(content_range, expect_content_range) self.assertEqual(body, b'') @@ -163,7 +163,7 @@ def expectSingleRange(self, range, start, end, if_range=None): expect_content_range = 'bytes %d-%d/%d' % ( start, end - 1, len(self.data)) content_range = rsp.getHeader('content-range') - self.assertFalse(content_range is None) + self.assertIsNotNone(content_range) self.assertEqual(content_range, expect_content_range) self.assertEqual(rsp.getHeader('content-length'), str(len(body))) self.assertEqual(body, self.data[start:end]) @@ -184,7 +184,7 @@ def expectMultipleRanges(self, range, sets, draft=0): body = self.doGET(req, rsp) - self.assertTrue(rsp.getStatus() == 206) + self.assertEqual(rsp.getStatus(), 206) self.assertFalse(rsp.getHeader('content-range')) ct = rsp.getHeader('content-type').split(';')[0] diff --git a/src/OFS/tests/testSimpleItem.py b/src/OFS/tests/testSimpleItem.py index 5ae1cb1f4b..4fb858bf3a 100644 --- a/src/OFS/tests/testSimpleItem.py +++ b/src/OFS/tests/testSimpleItem.py @@ -42,7 +42,7 @@ def _raise_during_standard_error_message(*args, **kw): self.assertEqual(sys.exc_info()[0], OverflowError) value = sys.exc_info()[1] self.assertTrue(value.message.startswith("'simple'")) - self.assertTrue('full details: testing' in value.message) + self.assertIn('full details: testing', value.message) def test_raise_StandardErrorMessage_TaintedString_errorValue(self): from AccessControl.tainted import TaintedString @@ -65,7 +65,7 @@ def _raise_during_standard_error_message(*args, **kw): import sys self.assertEqual(sys.exc_info()[0], OverflowError) value = sys.exc_info()[1] - self.assertFalse('<' in value.message) + self.assertNotIn('<', value.message) class TestItem_w__name__(unittest.TestCase): diff --git a/src/OFS/tests/testTraverse.py b/src/OFS/tests/testTraverse.py index 304cd3756c..c89f466ec1 100644 --- a/src/OFS/tests/testTraverse.py +++ b/src/OFS/tests/testTraverse.py @@ -220,18 +220,18 @@ def test_interfaces(self): verifyClass(ITraversable, Traversable) def testTraversePath(self): - self.assertTrue('file' in self.folder1.objectIds()) + self.assertIn('file', self.folder1.objectIds()) self.assertTrue( self.folder1.unrestrictedTraverse(('', 'folder1', 'file'))) self.assertTrue(self.folder1.unrestrictedTraverse(('', 'folder1'))) def testTraverseURLNoSlash(self): - self.assertTrue('file' in self.folder1.objectIds()) + self.assertIn('file', self.folder1.objectIds()) self.assertTrue(self.folder1.unrestrictedTraverse('/folder1/file')) self.assertTrue(self.folder1.unrestrictedTraverse('/folder1')) def testTraverseURLSlash(self): - self.assertTrue('file' in self.folder1.objectIds()) + self.assertIn('file', self.folder1.objectIds()) self.assertTrue(self.folder1.unrestrictedTraverse('/folder1/file/')) self.assertTrue(self.folder1.unrestrictedTraverse('/folder1/')) @@ -267,8 +267,10 @@ def testBoboTraverseToMethod(self): # Verify it's possible to use __bobo_traverse__ to a method. self._setupSecurity() bb = self._makeBoboTraversable() - self.assertTrue( - bb.restrictedTraverse('bb_method') is not bb.bb_method) + self.assertIsNot( + bb.restrictedTraverse('bb_method'), + bb.bb_method + ) def testBoboTraverseToSimpleAttrValue(self): # Verify it's possible to use __bobo_traverse__ to a simple @@ -284,8 +286,10 @@ def testBoboTraverseToNonAttrValue(self): # is fine, but to test the code branch we sub in the forgiving one self._setupSecurity(UnitTestSecurityPolicy()) bb = self._makeBoboTraversable() - self.assertTrue( - bb.restrictedTraverse('manufactured') == 42) + self.assertEqual( + bb.restrictedTraverse('manufactured'), + 42 + ) def testBoboTraverseToAcquiredObject(self): # Verify it's possible to use a __bobo_traverse__ which retrieves @@ -415,14 +419,17 @@ def testDefaultValueWhenNotFound(self): def testTraverseUp(self): # Test that we can traverse upwards from Acquisition import aq_base - self.assertTrue( - aq_base(self.root.folder1.file.restrictedTraverse('../..')) is - aq_base(self.root)) + self.assertIs( + aq_base(self.root.folder1.file.restrictedTraverse('../..')), + aq_base(self.root) + ) def testTraverseToNameStartingWithPlus(self): # Verify it's possible to traverse to a name such as +something - self.assertTrue( - self.folder1.unrestrictedTraverse('+something') == 'plus') + self.assertEqual( + self.folder1.unrestrictedTraverse('+something'), + 'plus' + ) def testTraverseWrongType(self): with self.assertRaises(TypeError): diff --git a/src/OFS/tests/test_DTMLDocument.py b/src/OFS/tests/test_DTMLDocument.py index 20984e65f7..65f50a9352 100644 --- a/src/OFS/tests/test_DTMLDocument.py +++ b/src/OFS/tests/test_DTMLDocument.py @@ -75,8 +75,8 @@ def test_defaults_no_standard_html_header(self): addDTMLDocument(dispatcher, 'id') method = dispatcher._set['id'] self.assertIsInstance(method, DTMLDocument) - self.assertFalse('standard_html_header' in method.read()) - self.assertFalse('standard_html_footer' in method.read()) + self.assertNotIn('standard_html_header', method.read()) + self.assertNotIn('standard_html_footer', method.read()) class DummyDispatcher: diff --git a/src/OFS/tests/test_DTMLMethod.py b/src/OFS/tests/test_DTMLMethod.py index fc9001b2c4..8d9aefbc13 100644 --- a/src/OFS/tests/test_DTMLMethod.py +++ b/src/OFS/tests/test_DTMLMethod.py @@ -268,8 +268,8 @@ def test_defaults_no_standard_html_header(self): addDTMLMethod(dispatcher, 'id') method = dispatcher._set['id'] self.assertIsInstance(method, DTMLMethod) - self.assertFalse('standard_html_header' in method.read()) - self.assertFalse('standard_html_footer' in method.read()) + self.assertNotIn('standard_html_header', method.read()) + self.assertNotIn('standard_html_footer', method.read()) class DummyDispatcher: diff --git a/src/OFS/tests/test_Uninstalled.py b/src/OFS/tests/test_Uninstalled.py index 6e2a9525bf..7d80f6980f 100644 --- a/src/OFS/tests/test_Uninstalled.py +++ b/src/OFS/tests/test_Uninstalled.py @@ -75,7 +75,7 @@ def test_Broken_product_with_oid_yields_instance_derived_from_Broken(self): inst = Broken(self, OID, ('Products.MyProduct.MyClass', 'MyClass')) self.assertIsInstance(inst, BrokenClass) - self.assertTrue(inst._p_jar is self) + self.assertIs(inst._p_jar, self) self.assertEqual(inst._p_oid, OID) klass = inst.__class__ @@ -136,7 +136,7 @@ def test_Broken_instance___getstate___gives_access_to_its_state(self): transaction.commit() # check that object is not left over app = base.app() - self.assertFalse('tr' in app.objectIds()) + self.assertNotIn('tr', app.objectIds()) def test_suite(): diff --git a/src/OFS/tests/test_userfolder.py b/src/OFS/tests/test_userfolder.py index 6749e143f8..96cae3cd7f 100644 --- a/src/OFS/tests/test_userfolder.py +++ b/src/OFS/tests/test_userfolder.py @@ -90,8 +90,8 @@ def testGetRolesInContext(self): user = uf.getUser('user1') app.manage_addLocalRoles('user1', ['Owner']) roles = user.getRolesInContext(app) - self.assertTrue('role1' in roles) - self.assertTrue('Owner' in roles) + self.assertIn('role1', roles) + self.assertIn('Owner', roles) def testHasRole(self): app = self._makeApp() diff --git a/src/Products/Five/browser/tests/test_metaconfigure.py b/src/Products/Five/browser/tests/test_metaconfigure.py index a8cbc94272..a503f8ecab 100644 --- a/src/Products/Five/browser/tests/test_metaconfigure.py +++ b/src/Products/Five/browser/tests/test_metaconfigure.py @@ -34,47 +34,47 @@ def test_publishTraverse_w_index_returns_index(self): request = DummyRequest() view = self._makeOne(request=request) index = view.index = DummyTemplate() - self.assertTrue(view.publishTraverse(request, 'index.html') is index) + self.assertIs(view.publishTraverse(request, 'index.html'), index) def test___getitem___uses_index_macros(self): view = self._makeOne() view.index = index = DummyTemplate() index.macros = {} index.macros['aaa'] = aaa = object() - self.assertTrue(view['aaa'] is aaa) + self.assertIs(view['aaa'], aaa) def test__getitem__gives_shortcut_to_index_macros(self): view = self._makeOne() view.index = index = DummyTemplate() index.macros = {} - self.assertTrue(view['macros'] is index.macros) + self.assertIs(view['macros'], index.macros) def test___call___no_args_no_kw(self): view = self._makeOne() view.index = index = DummyTemplate() result = view() - self.assertTrue(result is index) + self.assertIs(result, index) self.assertEqual(index._called_with, ((), {})) def test___call___w_args_no_kw(self): view = self._makeOne() view.index = index = DummyTemplate() result = view('abc') - self.assertTrue(result is index) + self.assertIs(result, index) self.assertEqual(index._called_with, (('abc',), {})) def test___call___no_args_w_kw(self): view = self._makeOne() view.index = index = DummyTemplate() result = view(foo='bar') - self.assertTrue(result is index) + self.assertIs(result, index) self.assertEqual(index._called_with, ((), {'foo': 'bar'})) def test___call___w_args_w_kw(self): view = self._makeOne() view.index = index = DummyTemplate() result = view('abc', foo='bar') - self.assertTrue(result is index) + self.assertIs(result, index) self.assertEqual(index._called_with, (('abc',), {'foo': 'bar'})) diff --git a/src/Products/Five/browser/tests/test_pagetemplatefile.py b/src/Products/Five/browser/tests/test_pagetemplatefile.py index 0d2ae0f209..651547e506 100644 --- a/src/Products/Five/browser/tests/test_pagetemplatefile.py +++ b/src/Products/Five/browser/tests/test_pagetemplatefile.py @@ -68,17 +68,17 @@ def test_pt_getContext_no_kw_no_physicalRoot(self): view = self._makeView(context, request) vptf = self._makeOne('seagull.pt') namespace = vptf.pt_getContext(view, request) - self.assertTrue(namespace['context'] is context) - self.assertTrue(namespace['request'] is request) + self.assertIs(namespace['context'], context) + self.assertIs(namespace['request'], request) views = namespace['views'] self.assertIsInstance(views, ViewMapper) self.assertEqual(views.ob, context) self.assertEqual(views.request, request) - self.assertTrue(namespace['here'] is context) - self.assertTrue(namespace['container'] is context) - self.assertTrue(namespace['root'] is None) + self.assertIs(namespace['here'], context) + self.assertIs(namespace['container'], context) + self.assertIsNone(namespace['root']) modules = namespace['modules'] - self.assertTrue(modules is SecureModuleImporter) + self.assertIs(modules, SecureModuleImporter) self.assertEqual(namespace['traverse_subpath'], []) self.assertEqual(namespace['user'].getId(), 'a_user') @@ -92,7 +92,7 @@ def test_pt_getContext_w_physicalRoot(self): view = self._makeView(context, request) vptf = self._makeOne('seagull.pt') namespace = vptf.pt_getContext(view, request) - self.assertTrue(namespace['root'] is root) + self.assertIs(namespace['root'], root) def test_pt_getContext_w_ignored_kw(self): from AccessControl.SecurityManagement import newSecurityManager @@ -102,8 +102,8 @@ def test_pt_getContext_w_ignored_kw(self): view = self._makeView(context, request) vptf = self._makeOne('seagull.pt') namespace = vptf.pt_getContext(view, request, foo='bar') - self.assertFalse('foo' in namespace) - self.assertFalse('foo' in namespace['options']) + self.assertNotIn('foo', namespace) + self.assertNotIn('foo', namespace['options']) def test_pt_getContext_w_args_kw(self): from AccessControl.SecurityManagement import newSecurityManager @@ -160,8 +160,8 @@ def __init__(self, context, request): foo = Foo(context, request) bound = foo.bar self.assertIsInstance(bound, BoundPageTemplate) - self.assertTrue(bound.__func__ is template) - self.assertTrue(bound.__self__ is foo) + self.assertIs(bound.__func__, template) + self.assertIs(bound.__self__, foo) class ViewMapperTests(unittest.TestCase): @@ -199,7 +199,7 @@ def _adapt(context, request): provideAdapter(_adapt, (None, None), Interface, name='test') mapper = self._makeOne() - self.assertTrue(mapper['test'] is self) + self.assertIs(mapper['test'], self) _marker = object() @@ -222,9 +222,9 @@ def test___init__(self): pt = DummyTemplate({'foo': 'bar'}) ob = DummyContext() bpt = self._makeOne(pt, ob) - self.assertTrue(bpt.__func__ is pt) - self.assertTrue(bpt.__self__ is ob) - self.assertTrue(bpt.__parent__ is ob) + self.assertIs(bpt.__func__, pt) + self.assertIs(bpt.__self__, ob) + self.assertIs(bpt.__parent__, ob) self.assertEqual(bpt.macros['foo'], 'bar') self.assertEqual(bpt.filename, 'dummy.pt') diff --git a/src/Products/Five/utilities/browser/tests/test_marker.py b/src/Products/Five/utilities/browser/tests/test_marker.py index e2ab725467..470fb9dbfe 100644 --- a/src/Products/Five/utilities/browser/tests/test_marker.py +++ b/src/Products/Five/utilities/browser/tests/test_marker.py @@ -52,7 +52,7 @@ def test_editview(self): view = EditView(obj, {}) # Test state before making any changes - self.assertTrue(view.context.aq_inner is obj) + self.assertIs(view.context.aq_inner, obj) self.assertEqual(view.request, {}) self.assertEqual(view.getAvailableInterfaceNames(), []) self.assertEqual(view.getDirectlyProvidedNames(), []) diff --git a/src/Products/PageTemplates/tests/testExpressions.py b/src/Products/PageTemplates/tests/testExpressions.py index 81c321e4ae..0b73be7419 100644 --- a/src/Products/PageTemplates/tests/testExpressions.py +++ b/src/Products/PageTemplates/tests/testExpressions.py @@ -105,7 +105,7 @@ def test_evaluate_with_render_DTML_template(self): def test_evaluate_alternative_first_missing(self): ec = self._makeContext() - self.assertTrue(ec.evaluate('x | nothing') is None) + self.assertIsNone(ec.evaluate('x | nothing')) def test_evaluate_dict_key_as_underscore(self): # Traversing to the name `_` will raise a DeprecationWarning @@ -204,8 +204,8 @@ def test_mixed(self): def test_builtin_in_path_expr(self): ec = self._makeContext() - self.assertIs(ec.evaluate('True'), True) - self.assertIs(ec.evaluate('False'), False) + self.assertTrue(ec.evaluate('True')) + self.assertFalse(ec.evaluate('False')) self.assertIs(ec.evaluate('nocall: test'), safe_builtins["test"]) @@ -343,5 +343,5 @@ def test_createErrorInfo_returns_unrestricted_object(self): # See: https://bugs.launchpad.net/zope2/+bug/174705 context = self._makeOne() info = context.createErrorInfo(AttributeError('nonesuch'), (12, 3)) - self.assertTrue(info.type is AttributeError) + self.assertIs(info.type, AttributeError) self.assertEqual(info.__allow_access_to_unprotected_subobjects__, 1) diff --git a/src/Products/PageTemplates/tests/testZRPythonExpr.py b/src/Products/PageTemplates/tests/testZRPythonExpr.py index c1f88c63af..1d16e0bb85 100644 --- a/src/Products/PageTemplates/tests/testZRPythonExpr.py +++ b/src/Products/PageTemplates/tests/testZRPythonExpr.py @@ -12,14 +12,14 @@ def test_call_with_ns_prefer_context_to_here(self): request = {'request': 1} names = {'context': context, 'here': here, 'request': request} result = call_with_ns(lambda td: td.this, names) - self.assertTrue(result is context, result) + self.assertIs(result, context, result) def test_call_with_ns_no_context_or_here(self): from Products.PageTemplates.ZRPythonExpr import call_with_ns request = {'request': 1} names = {'request': request} result = call_with_ns(lambda td: td.this, names) - self.assertTrue(result is None, result) + self.assertIsNone(result, result) def test_call_with_ns_no_request(self): from Products.PageTemplates.ZRPythonExpr import call_with_ns diff --git a/src/Products/PageTemplates/tests/testZopePageTemplate.py b/src/Products/PageTemplates/tests/testZopePageTemplate.py index 28c8019f5d..24f7a0479a 100644 --- a/src/Products/PageTemplates/tests/testZopePageTemplate.py +++ b/src/Products/PageTemplates/tests/testZopePageTemplate.py @@ -522,7 +522,7 @@ def test___before_publishing_traverse___wo__hacked_path(self): src = self._makeOne() request = DummyRequest() src.__before_publishing_traverse__(None, request) - self.assertFalse('_hacked_path' in request.__dict__) + self.assertNotIn('_hacked_path', request.__dict__) def test___before_publishing_traverse___w__hacked_path_false(self): src = self._makeOne() diff --git a/src/Products/PageTemplates/tests/test_engine.py b/src/Products/PageTemplates/tests/test_engine.py index 44d4d6b3a8..6af0ce91c1 100644 --- a/src/Products/PageTemplates/tests/test_engine.py +++ b/src/Products/PageTemplates/tests/test_engine.py @@ -23,13 +23,13 @@ def test_pagetemplate(self): with open(os.path.join(path, "simple.pt")) as fd: data = fd.read() template.write(data) - self.assertTrue('world' in template()) + self.assertIn('world', template()) # test arguments with open(os.path.join(path, "options.pt")) as fd: data = fd.read() template.write(data) - self.assertTrue('Hello world' in template(greeting='Hello world')) + self.assertIn('Hello world', template(greeting='Hello world')) def test_pagetemplatefile(self): from Products.PageTemplates.PageTemplateFile import PageTemplateFile @@ -37,7 +37,7 @@ def test_pagetemplatefile(self): # test rendering engine template = PageTemplateFile(os.path.join(path, "simple.pt")) template = template.__of__(self.folder) - self.assertTrue('world' in template()) + self.assertIn('world', template()) def test_pagetemplatefile_processing_instruction_skipped(self): from Products.PageTemplates.PageTemplateFile import PageTemplateFile @@ -59,14 +59,17 @@ def test_zopepagetemplate(self): with open(os.path.join(path, "simple.pt")) as fd: data = fd.read() template.write(data) - self.assertTrue('world' in template()) + self.assertIn('world', template()) # test arguments with open(os.path.join(path, "options.pt")) as fd: data = fd.read() template.write(data) - self.assertTrue('Hello world' in template( - greeting='Hello world')) + self.assertIn( + 'Hello world', + template( + greeting='Hello world') + ) # test commit import transaction diff --git a/src/Products/PageTemplates/tests/test_pagetemplate.py b/src/Products/PageTemplates/tests/test_pagetemplate.py index c834bb20e6..d709fdeedf 100644 --- a/src/Products/PageTemplates/tests/test_pagetemplate.py +++ b/src/Products/PageTemplates/tests/test_pagetemplate.py @@ -30,19 +30,19 @@ def __str__(self): template = self._makeOne('rr.pt') result = template(refs=[Prioritized(1), Prioritized(2)]) - self.assertTrue('P1' in result) - self.assertTrue(result.index('P1') < result.index('P2')) + self.assertIn('P1', result) + self.assertLess(result.index('P1'), result.index('P2')) def test_locals(self): template = self._makeOne('locals.pt') result = template() - self.assertTrue('function test' in result) - self.assertTrue('function same_type' in result) + self.assertIn('function test', result) + self.assertIn('function same_type', result) def test_locals_base(self): template = self._makeOne('locals_base.pt') result = template() - self.assertTrue('Application' in result) + self.assertIn('Application', result) def test_nocall(self): template = self._makeOne("nocall.pt") @@ -50,7 +50,7 @@ def test_nocall(self): def dont_call(): raise RuntimeError() result = template(callable=dont_call) - self.assertTrue(repr(dont_call) in result) + self.assertIn(repr(dont_call), result) def test_exists(self): template = self._makeOne("exists.pt") @@ -58,12 +58,12 @@ def test_exists(self): def dont_call(): raise RuntimeError() result = template(callable=dont_call) - self.assertTrue('ok' in result) + self.assertIn('ok', result) def test_simple(self): template = self._makeOne("simple.pt") result = template() - self.assertTrue('Hello world!' in result) + self.assertIn('Hello world!', result) def test_secure(self): soup = '' @@ -79,7 +79,7 @@ def test_secure(self): from AccessControl.SecurityInfo import allow_module allow_module('html') result = template(soup=soup) - self.assertTrue('<foo></bar>' in result) + self.assertIn('<foo></bar>', result) def test_suite(): diff --git a/src/Products/PageTemplates/tests/test_viewpagetemplatefile.py b/src/Products/PageTemplates/tests/test_viewpagetemplatefile.py index d2d450d50d..e359f0ae6e 100644 --- a/src/Products/PageTemplates/tests/test_viewpagetemplatefile.py +++ b/src/Products/PageTemplates/tests/test_viewpagetemplatefile.py @@ -47,7 +47,7 @@ def afterSetUp(self): def test_simple(self): view = SimpleView(self.folder, self.folder.REQUEST) result = view.index() - self.assertTrue('Hello world!' in result) + self.assertIn('Hello world!', result) def test_secure(self): view = SecureView(self.folder, self.folder.REQUEST) @@ -57,18 +57,18 @@ def test_secure(self): except Unauthorized: self.fail("Unexpected exception.") else: - self.assertTrue('<foo></bar>' in result) + self.assertIn('<foo></bar>', result) def test_locals(self): view = LocalsView(self.folder, self.folder.REQUEST) result = view.index() - self.assertTrue("view:yes" in result) - self.assertTrue('here==context:True' in result) - self.assertTrue('here==container:True' in result) - self.assertTrue("root:(\'\',)" in result) - self.assertTrue("nothing:" in result) + self.assertIn("view:yes", result) + self.assertIn('here==context:True', result) + self.assertIn('here==container:True', result) + self.assertIn("root:(\'\',)", result) + self.assertIn("nothing:", result) # test for the existence of the cgi.parse function - self.assertTrue("parse" in result) + self.assertIn("parse", result) def test_options(self): view = OptionsView(self.folder, self.folder.REQUEST) @@ -78,8 +78,8 @@ def test_options(self): c='abc', ) result = view.index(**options) - self.assertTrue("a : 1" in result) - self.assertTrue("c : abc" in result) + self.assertIn("a : 1", result) + self.assertIn("c : abc", result) def test_processing_instruction(self): view = ProcessingInstructionTestView(self.folder, self.folder.REQUEST) diff --git a/src/Products/SiteAccess/tests/testVirtualHostMonster.py b/src/Products/SiteAccess/tests/testVirtualHostMonster.py index 56529e6fb6..f7d025c2e0 100644 --- a/src/Products/SiteAccess/tests/testVirtualHostMonster.py +++ b/src/Products/SiteAccess/tests/testVirtualHostMonster.py @@ -267,7 +267,7 @@ def test_add_addToContainer(self): vhm1 = self._makeOne() vhm1.manage_addToContainer(self.root) - self.assertTrue(vhm1.getId() in self.root.objectIds()) + self.assertIn(vhm1.getId(), self.root.objectIds()) self.assertTrue(queryBeforeTraverse(self.root, vhm1.meta_type)) def test_add_manage_addVirtualHostMonster(self): @@ -277,6 +277,6 @@ def test_add_manage_addVirtualHostMonster(self): from ZPublisher.BeforeTraverse import queryBeforeTraverse manage_addVirtualHostMonster(self.root) - self.assertTrue(VirtualHostMonster.id in self.root.objectIds()) + self.assertIn(VirtualHostMonster.id, self.root.objectIds()) hook = queryBeforeTraverse(self.root, VirtualHostMonster.meta_type) self.assertTrue(hook) diff --git a/src/Testing/ZopeTestCase/testPortalTestCase.py b/src/Testing/ZopeTestCase/testPortalTestCase.py index c844afc39f..b2aadfaf44 100644 --- a/src/Testing/ZopeTestCase/testPortalTestCase.py +++ b/src/Testing/ZopeTestCase/testPortalTestCase.py @@ -119,7 +119,7 @@ def test_getPortal(self): self.assertTrue(hasattr_(self.app, portal_name)) self.assertTrue(hasattr_(self.portal, 'Members')) self.assertTrue(hasattr_(self.portal, 'portal_membership')) - self.assertTrue('Member' in self.portal.userdefined_roles()) + self.assertIn('Member', self.portal.userdefined_roles()) def test_setupUserFolder(self): # User folder should be set up. @@ -151,7 +151,7 @@ def test_setupHomeFolder(self): self.login() self._setupHomeFolder() self.assertTrue(hasattr_(self.portal.Members, user_name)) - self.assertFalse(self.folder is None) + self.assertIsNotNone(self.folder) # Shut up deprecation warnings try: owner_info = self.folder.getOwnerTuple() @@ -307,7 +307,7 @@ def test_clear(self): self._setupUser() self._setupHomeFolder() self._clear(1) - self.assertFalse(portal_name in self.app.__dict__) + self.assertNotIn(portal_name, self.app.__dict__) auth_name = getSecurityManager().getUser().getUserName() self.assertEqual(auth_name, 'Anonymous User') self.assertEqual(self._called, ['beforeClose', 'afterClear']) @@ -321,7 +321,7 @@ def test_setUp(self): self.assertTrue(hasattr_(self.portal, 'acl_users')) self.assertTrue(hasattr_(self.portal, 'Members')) self.assertTrue(hasattr_(self.portal, 'portal_membership')) - self.assertTrue('Member' in self.portal.userdefined_roles()) + self.assertIn('Member', self.portal.userdefined_roles()) self.assertTrue(hasattr_(self.portal.Members, user_name)) acl_user = self.portal.acl_users.getUserById(user_name) self.assertTrue(acl_user) @@ -336,7 +336,7 @@ def test_tearDown(self): self._setUp() self._called = [] self._tearDown() - self.assertFalse(portal_name in self.app.__dict__) + self.assertNotIn(portal_name, self.app.__dict__) auth_name = getSecurityManager().getUser().getUserName() self.assertEqual(auth_name, 'Anonymous User') self.assertEqual( @@ -427,7 +427,7 @@ def getPortal(self): def testGetUserDoesNotWrapUser(self): user = self.portal.acl_users.getUserById(user_name) self.assertFalse(hasattr(user, 'aq_base')) - self.assertTrue(user is aq_base(user)) + self.assertIs(user, aq_base(user)) def testLoggedInUserIsWrapped(self): user = getSecurityManager().getUser() @@ -452,7 +452,7 @@ def _setupUserFolder(self): def testGetUserWrapsUser(self): user = self.portal.acl_users.getUserById(user_name) self.assertTrue(hasattr(user, 'aq_base')) - self.assertFalse(user is aq_base(user)) + self.assertIsNot(user, aq_base(user)) self.assertTrue( user.__parent__.__class__.__name__, 'WrappingUserFolder') diff --git a/src/Testing/ZopeTestCase/testZODBCompat.py b/src/Testing/ZopeTestCase/testZODBCompat.py index e36510540e..7043798a33 100644 --- a/src/Testing/ZopeTestCase/testZODBCompat.py +++ b/src/Testing/ZopeTestCase/testZODBCompat.py @@ -330,14 +330,14 @@ def _getfolder(self): def testTransactionAbort(self): folder = self._getfolder() - self.assertTrue(folder is not None) - self.assertTrue(folder._p_jar is None) + self.assertIsNotNone(folder) + self.assertIsNone(folder._p_jar) transaction.savepoint() - self.assertTrue(folder._p_jar is not None) + self.assertIsNotNone(folder._p_jar) transaction.abort() del folder folder = self._getfolder() - self.assertTrue(folder is None) + self.assertIsNone(folder) def test_suite(): diff --git a/src/Testing/ZopeTestCase/testZopeTestCase.py b/src/Testing/ZopeTestCase/testZopeTestCase.py index 9bac65da6e..e7c315e29b 100644 --- a/src/Testing/ZopeTestCase/testZopeTestCase.py +++ b/src/Testing/ZopeTestCase/testZopeTestCase.py @@ -71,7 +71,7 @@ def test_setupFolder(self): self._setupFolder() self.assertTrue(hasattr_(self.app, folder_name)) self.assertTrue(hasattr_(self, 'folder')) - self.assertTrue(user_role in self.folder.userdefined_roles()) + self.assertIn(user_role, self.folder.userdefined_roles()) self.assertPermissionsOfRole(standard_permissions, user_role) def test_setupUserFolder(self): @@ -234,7 +234,7 @@ def test_clear(self): self._setupUser() self.login() self._clear(1) - self.assertFalse(folder_name in self.app.__dict__) + self.assertNotIn(folder_name, self.app.__dict__) auth_name = getSecurityManager().getUser().getUserName() self.assertEqual(auth_name, 'Anonymous User') self.assertEqual(self._called, ['beforeClose', 'afterClear']) @@ -246,7 +246,7 @@ def test_setUp(self): self._setUp() self.assertTrue(hasattr_(self.app, folder_name)) self.assertTrue(hasattr_(self, 'folder')) - self.assertTrue(user_role in self.folder.userdefined_roles()) + self.assertIn(user_role, self.folder.userdefined_roles()) self.assertPermissionsOfRole(standard_permissions, user_role) self.assertTrue(hasattr_(self.folder, 'acl_users')) acl_user = self.folder.acl_users.getUserById(user_name) @@ -262,7 +262,7 @@ def test_tearDown(self): self._setUp() self._called = [] self._tearDown() - self.assertFalse(folder_name in self.app.__dict__) + self.assertNotIn(folder_name, self.app.__dict__) auth_name = getSecurityManager().getUser().getUserName() self.assertEqual(auth_name, 'Anonymous User') self.assertEqual( @@ -354,7 +354,7 @@ class TestPlainUserFolder(ZopeTestCase.ZopeTestCase): def testGetUserDoesNotWrapUser(self): user = self.folder.acl_users.getUserById(user_name) self.assertFalse(hasattr(user, 'aq_base')) - self.assertTrue(user is aq_base(user)) + self.assertIs(user, aq_base(user)) def testLoggedInUserIsWrapped(self): user = getSecurityManager().getUser() @@ -375,7 +375,7 @@ def _setupUserFolder(self): def testGetUserWrapsUser(self): user = self.folder.acl_users.getUserById(user_name) self.assertTrue(hasattr(user, 'aq_base')) - self.assertFalse(user is aq_base(user)) + self.assertIsNot(user, aq_base(user)) self.assertTrue( user.__parent__.__class__.__name__, 'WrappingUserFolder') diff --git a/src/Testing/tests/test_testbrowser.py b/src/Testing/tests/test_testbrowser.py index 5fd0630bb0..65686b6d54 100644 --- a/src/Testing/tests/test_testbrowser.py +++ b/src/Testing/tests/test_testbrowser.py @@ -122,7 +122,7 @@ def test_handle_errors_false(self): # Even errors which can be handled by Zope go to the client: with self.assertRaises(NotFound): browser.open('http://localhost/nothing-is-here') - self.assertTrue(browser.contents is None) + self.assertIsNone(browser.contents) def test_handle_errors_false_redirect(self): self.folder._setObject('redirect', RedirectStub()) @@ -131,7 +131,7 @@ def test_handle_errors_false_redirect(self): with self.assertRaises(NotFound): browser.open('http://localhost/test_folder_1_/redirect') - self.assertTrue(browser.contents is None) + self.assertIsNone(browser.contents) def test_handle_errors_false_HTTPExceptionHandler_in_app(self): """HTTPExceptionHandler does not handle errors if requested via WSGI. @@ -188,8 +188,8 @@ def test_headers_camel_case(self): browser = Browser() browser.open('http://localhost/test_folder_1_/stub') header_text = str(browser.headers) - self.assertTrue('Content-Length: ' in header_text) - self.assertTrue('Content-Type: ' in header_text) + self.assertIn('Content-Length: ', header_text) + self.assertIn('Content-Type: ', header_text) def test_suite(): diff --git a/src/ZPublisher/tests/testBaseRequest.py b/src/ZPublisher/tests/testBaseRequest.py index 07e15749db..dbc02dea56 100644 --- a/src/ZPublisher/tests/testBaseRequest.py +++ b/src/ZPublisher/tests/testBaseRequest.py @@ -193,7 +193,7 @@ def _makeRootAndFolder(self): def test_no_docstring_on_instance(self): root, folder = self._makeRootAndFolder() r = self._makeOne(root) - self.assertTrue(r.__doc__ is None) + self.assertIsNone(r.__doc__) def test___bobo_traverse___raises(self): root, folder = self._makeRootAndFolder() diff --git a/src/ZPublisher/tests/testHTTPRangeSupport.py b/src/ZPublisher/tests/testHTTPRangeSupport.py index fe754bd0d8..9d58b7dd46 100644 --- a/src/ZPublisher/tests/testHTTPRangeSupport.py +++ b/src/ZPublisher/tests/testHTTPRangeSupport.py @@ -23,13 +23,15 @@ class TestRangeHeaderParse(unittest.TestCase): # Utility methods def expectNone(self, header): result = parseRange(header) - self.assertTrue(result is None, 'Expected None, got %r' % result) + self.assertIsNone(result, 'Expected None, got %r' % result) def expectSets(self, header, sets): result = parseRange(header) - self.assertTrue( - result == sets, - f'Expected {sets!r}, got {result!r}') + self.assertEqual( + result, + sets, + f'Expected {sets!r}, got {result!r}' + ) # Syntactically incorrect headers def testGarbage(self): @@ -85,9 +87,11 @@ class TestExpandRanges(unittest.TestCase): def expectSets(self, sets, size, expect): result = expandRanges(sets, size) - self.assertTrue( - result == expect, - f'Expected {expect!r}, got {result!r}') + self.assertEqual( + result, + expect, + f'Expected {expect!r}, got {result!r}' + ) def testExpandOpenEnd(self): self.expectSets([(1, 2), (5, None)], 50, [(1, 2), (5, 50)]) diff --git a/src/ZPublisher/tests/testHTTPRequest.py b/src/ZPublisher/tests/testHTTPRequest.py index 3e2db76480..c14cadbb35 100644 --- a/src/ZPublisher/tests/testHTTPRequest.py +++ b/src/ZPublisher/tests/testHTTPRequest.py @@ -56,8 +56,8 @@ def test_dict_methods(self): def test_dict_special_methods(self): rec = self._makeOne() rec.a = 1 - self.assertTrue('a' in rec) - self.assertFalse('b' in rec) + self.assertIn('a', rec) + self.assertNotIn('b', rec) self.assertEqual(len(rec), 1) self.assertEqual(list(iter(rec)), ['a']) @@ -206,14 +206,18 @@ def _valueIsOrHoldsTainted(self, val): def _noFormValuesInOther(self, req): for key in list(req.taintedform.keys()): - self.assertFalse( - key in req.other, - 'REQUEST.other should not hold tainted values at first!') + self.assertNotIn( + key, + req.other, + 'REQUEST.other should not hold tainted values at first!' + ) for key in list(req.form.keys()): - self.assertFalse( - key in req.other, - 'REQUEST.other should not hold form values at first!') + self.assertNotIn( + key, + req.other, + 'REQUEST.other should not hold form values at first!' + ) def _onlyTaintedformHoldsTaintedStrings(self, req): for key, val in list(req.taintedform.items()): @@ -232,9 +236,11 @@ def _onlyTaintedformHoldsTaintedStrings(self, req): def _taintedKeysAlsoInForm(self, req): for key in list(req.taintedform.keys()): - self.assertTrue( - key in req.form, - "Found tainted %s not in form" % key) + self.assertIn( + key, + req.form, + "Found tainted %s not in form" % key + ) self.assertEqual( req.form[key], req.taintedform[key], "Key %s not correctly reproduced in tainted; expected %r, " @@ -250,7 +256,7 @@ def test_webdav_source_port_available(self): def test_no_docstring_on_instance(self): env = {'SERVER_NAME': 'testingharnas', 'SERVER_PORT': '80'} req = self._makeOne(environ=env) - self.assertTrue(req.__doc__ is None) + self.assertIsNone(req.__doc__) def test___bobo_traverse___raises(self): env = {'SERVER_NAME': 'testingharnas', 'SERVER_PORT': '80'} @@ -726,13 +732,17 @@ def test_processInputs_w_tainted_values_cleans_exceptions(self): warnings.simplefilter('ignore') convert('') except Exception as e: - self.assertFalse( - '<' in e.args, - '%s converter does not quote unsafe value!' % type) + self.assertNotIn( + '<', + e.args, + '%s converter does not quote unsafe value!' % type + ) except SyntaxError as e: - self.assertFalse( - '<' in e, - '%s converter does not quote unsafe value!' % type) + self.assertNotIn( + '<', + e, + '%s converter does not quote unsafe value!' % type + ) def test_processInputs_w_dotted_name_as_tuple(self): # Collector #500 @@ -988,7 +998,7 @@ def test_debug_not_in_qs_still_gets_attr(self): request = self._makeOne() self.assertIsInstance(request.debug, DebugFlags) # It won't be available through dictonary lookup, though - self.assertTrue(request.get('debug') is None) + self.assertIsNone(request.get('debug')) def test_debug_in_qs_gets_form_var(self): env = {'QUERY_STRING': 'debug=1'} @@ -1022,16 +1032,16 @@ def test_locale_property_accessor(self): # before accessing request.locale for the first time, request._locale # is still a marker - self.assertTrue(request._locale is _marker) + self.assertIs(request._locale, _marker) # when accessing request.locale we will see an ILocale self.assertTrue(ILocale.providedBy(request.locale)) # and request._locale has been set - self.assertTrue(request._locale is request.locale) + self.assertIs(request._locale, request.locale) # It won't be available through dictonary lookup, though - self.assertTrue(request.get('locale') is None) + self.assertIsNone(request.get('locale')) def test_locale_in_qs(self): provideAdapter(BrowserLanguages, [IHTTPRequest], @@ -1098,9 +1108,9 @@ def test_locale_fallback(self): locale = request.locale self.assertTrue(ILocale.providedBy(locale)) - self.assertTrue(locale.id.language is None) - self.assertTrue(locale.id.territory is None) - self.assertTrue(locale.id.variant is None) + self.assertIsNone(locale.id.language) + self.assertIsNone(locale.id.territory) + self.assertIsNone(locale.id.variant) def test_method_GET(self): env = {'REQUEST_METHOD': 'GET'} diff --git a/src/ZPublisher/tests/testHTTPResponse.py b/src/ZPublisher/tests/testHTTPResponse.py index 71a6a7dcdb..9a4b5b19e4 100644 --- a/src/ZPublisher/tests/testHTTPResponse.py +++ b/src/ZPublisher/tests/testHTTPResponse.py @@ -127,8 +127,8 @@ def test_retry(self): response = self._makeOne(stdout=STDOUT, stderr=STDERR) cloned = response.retry() self.assertIsInstance(cloned, self._getTargetClass()) - self.assertTrue(cloned.stdout is STDOUT) - self.assertTrue(cloned.stderr is STDERR) + self.assertIs(cloned.stdout, STDOUT) + self.assertIs(cloned.stderr, STDERR) def test_setStatus_code(self): response = self._makeOne() @@ -261,7 +261,7 @@ def test_setCookie_w_secure_true_value(self): cookie = response.cookies.get('foo', None) self.assertEqual(len(cookie), 2) self.assertEqual(cookie.get('value'), 'bar') - self.assertIs(cookie.get('Secure'), True) + self.assertTrue(cookie.get('Secure')) cookies = response._cookie_list() self.assertEqual(len(cookies), 1) @@ -564,10 +564,10 @@ def test_setBody_with_is_error_converted_to_Site_Error(self): response.body = b'BEFORE' result = response.setBody(b'BODY', 'TITLE', is_error=True) self.assertTrue(result) - self.assertFalse(b'BEFORE' in response.body) - self.assertTrue(b'

Site Error

' in response.body) - self.assertTrue(b'TITLE' in response.body) - self.assertTrue(b'BODY' in response.body) + self.assertNotIn(b'BEFORE', response.body) + self.assertIn(b'

Site Error

', response.body) + self.assertIn(b'TITLE', response.body) + self.assertIn(b'BODY', response.body) self.assertEqual(response.getHeader('Content-Type'), 'text/html; charset=utf-8') @@ -713,7 +713,7 @@ def test_setBody_compression_no_prior_vary_header(self): response = self._makeOne() response.enableHTTPCompression({'HTTP_ACCEPT_ENCODING': 'gzip'}) response.setBody(b'foo' * 100) # body must get smaller on compression - self.assertTrue('Accept-Encoding' in response.getHeader('Vary')) + self.assertIn('Accept-Encoding', response.getHeader('Vary')) def test_setBody_compression_w_prior_vary_header_wo_encoding(self): # Vary header should be added here @@ -721,7 +721,7 @@ def test_setBody_compression_w_prior_vary_header_wo_encoding(self): response.setHeader('Vary', 'Cookie') response.enableHTTPCompression({'HTTP_ACCEPT_ENCODING': 'gzip'}) response.setBody(b'foo' * 100) # body must get smaller on compression - self.assertTrue('Accept-Encoding' in response.getHeader('Vary')) + self.assertIn('Accept-Encoding', response.getHeader('Vary')) def test_setBody_compression_w_prior_vary_header_incl_encoding(self): # Vary header already had Accept-Ecoding', do'nt munge @@ -854,7 +854,7 @@ def test_notFoundError(self): response.notFoundError() except NotFound as raised: self.assertEqual(response.status, 404) - self.assertTrue("

Resource: Unknown

" in str(raised)) + self.assertIn("

Resource: Unknown

", str(raised)) else: self.fail("Didn't raise NotFound") @@ -864,7 +864,7 @@ def test_notFoundError_w_entry(self): response.notFoundError('ENTRY') except NotFound as raised: self.assertEqual(response.status, 404) - self.assertTrue("

Resource: ENTRY

" in str(raised)) + self.assertIn("

Resource: ENTRY

", str(raised)) else: self.fail("Didn't raise NotFound") @@ -874,7 +874,7 @@ def test_forbiddenError(self): response.forbiddenError() except NotFound as raised: self.assertEqual(response.status, 404) - self.assertTrue("

Resource: Unknown

" in str(raised)) + self.assertIn("

Resource: Unknown

", str(raised)) else: self.fail("Didn't raise NotFound") @@ -884,7 +884,7 @@ def test_forbiddenError_w_entry(self): response.forbiddenError('ENTRY') except NotFound as raised: self.assertEqual(response.status, 404) - self.assertTrue("

Resource: ENTRY

" in str(raised)) + self.assertIn("

Resource: ENTRY

", str(raised)) else: self.fail("Didn't raise NotFound") @@ -927,8 +927,11 @@ def test_badRequestError_valid_parameter_name(self): response.badRequestError('some_parameter') except BadRequest as raised: self.assertEqual(response.status, 400) - self.assertTrue("The parameter, some_parameter, " - "was omitted from the request." in str(raised)) + self.assertIn( + "The parameter, some_parameter, " + "was omitted from the request.", + str(raised) + ) else: self.fail("Didn't raise BadRequest") @@ -938,8 +941,11 @@ def test_badRequestError_invalid_parameter_name(self): response.badRequestError('URL1') except InternalError as raised: self.assertEqual(response.status, 400) - self.assertTrue("Sorry, an internal error occurred in this " - "resource." in str(raised)) + self.assertIn( + "Sorry, an internal error occurred in this " + "resource.", + str(raised) + ) else: self.fail("Didn't raise InternalError") @@ -947,12 +953,12 @@ def test__unauthorized_no_realm(self): response = self._makeOne() response.realm = '' response._unauthorized() - self.assertFalse('WWW-Authenticate' in response.headers) + self.assertNotIn('WWW-Authenticate', response.headers) def test__unauthorized_w_default_realm(self): response = self._makeOne() response._unauthorized() - self.assertTrue('WWW-Authenticate' in response.headers) # literal + self.assertIn('WWW-Authenticate', response.headers) # literal self.assertEqual(response.headers['WWW-Authenticate'], 'basic realm="Zope", charset="UTF-8"') @@ -960,7 +966,7 @@ def test__unauthorized_w_realm(self): response = self._makeOne() response.realm = 'Folly' response._unauthorized() - self.assertTrue('WWW-Authenticate' in response.headers) # literal + self.assertIn('WWW-Authenticate', response.headers) # literal self.assertEqual(response.headers['WWW-Authenticate'], 'basic realm="Folly", charset="UTF-8"') @@ -970,8 +976,11 @@ def test_unauthorized_no_debug_mode(self): response.unauthorized() except Unauthorized as raised: self.assertEqual(response.status, 200) # publisher sets 401 later - self.assertTrue("You are not authorized " - "to access this resource." in str(raised)) + self.assertIn( + "You are not authorized " + "to access this resource.", + str(raised) + ) else: self.fail("Didn't raise Unauthorized") @@ -981,8 +990,10 @@ def test_unauthorized_w_debug_mode_no_credentials(self): try: response.unauthorized() except Unauthorized as raised: - self.assertTrue("\nNo Authorization header found." - in str(raised)) + self.assertIn( + "\nNo Authorization header found.", + str(raised) + ) else: self.fail("Didn't raise Unauthorized") @@ -993,8 +1004,10 @@ def test_unauthorized_w_debug_mode_w_credentials(self): try: response.unauthorized() except Unauthorized as raised: - self.assertTrue("\nUsername and password are not correct." - in str(raised)) + self.assertIn( + "\nUsername and password are not correct.", + str(raised) + ) else: self.fail("Didn't raise Unauthorized") @@ -1374,7 +1387,7 @@ def test_exception_Internal_Server_Error(self): raise AttributeError('ERROR VALUE') except AttributeError: body = response.exception() - self.assertTrue(b'ERROR VALUE' in bytes(body)) + self.assertIn(b'ERROR VALUE', bytes(body)) self.assertEqual(response.status, 500) self.assertEqual(response.errmsg, 'Internal Server Error') @@ -1388,7 +1401,7 @@ def test_exception_500_text(self): raise exc except AttributeError: body = response.exception() - self.assertTrue(expected in bytes(body)) + self.assertIn(expected, bytes(body)) self.assertEqual(response.status, 500) self.assertEqual(response.errmsg, 'Internal Server Error') diff --git a/src/ZPublisher/tests/test_WSGIPublisher.py b/src/ZPublisher/tests/test_WSGIPublisher.py index b624a3ac7f..55428d0088 100644 --- a/src/ZPublisher/tests/test_WSGIPublisher.py +++ b/src/ZPublisher/tests/test_WSGIPublisher.py @@ -84,7 +84,7 @@ def test_listHeaders_includes_Server_header_w_server_version_set(self): response.setBody('TESTING') headers = response.listHeaders() sv = [x for x in headers if x[0] == 'Server'] - self.assertTrue(('Server', 'TESTME') in sv) + self.assertIn(('Server', 'TESTME'), sv) def test_listHeaders_includes_Date_header(self): import time @@ -119,7 +119,7 @@ def __next__(self): body = TestStreamIterator() response.setBody(body) response.finalize() - self.assertTrue(body is response.body) + self.assertIs(body, response.body) self.assertEqual(response._streaming, 1) def test_setBody_IStreamIterator(self): @@ -147,7 +147,7 @@ def __len__(self): body = TestStreamIterator() response.setBody(body) response.finalize() - self.assertTrue(body is response.body) + self.assertIs(body, response.body) self.assertEqual(response._streaming, 0) self.assertEqual(response.getHeader('Content-Length'), '%d' % len(TestStreamIterator.data)) @@ -225,7 +225,7 @@ def test_wo_REMOTE_USER(self): _realm = 'TESTING' _debug_mode = True returned = self._callFUT(request, (_object, _realm, _debug_mode)) - self.assertTrue(returned is response) + self.assertIs(returned, response) self.assertTrue(request._processedInputs) self.assertTrue(response.debug_mode) self.assertEqual(response.realm, 'TESTING') @@ -399,7 +399,7 @@ def test_upgrades_ztk_not_found(self): except ZTK_NotFound: self.fail('ZTK exception raised, expected zExceptions.') except NotFound as exc: - self.assertTrue('name_not_found' in str(exc)) + self.assertIn('name_not_found', str(exc)) def test_response_body_is_file(self): from io import BytesIO @@ -420,7 +420,7 @@ def read(self, *args, **kw): _publish = DummyCallable() _publish._result = _response app_iter = self._callFUT(environ, start_response, _publish) - self.assertTrue(app_iter is body) + self.assertIs(app_iter, body) def test_response_is_stream(self): from zope.interface import implementer @@ -448,7 +448,7 @@ def __next__(self): _publish = DummyCallable() _publish._result = _response app_iter = self._callFUT(environ, start_response, _publish) - self.assertTrue(app_iter is body) + self.assertIs(app_iter, body) def test_response_is_unboundstream(self): from zope.interface import implementer @@ -475,7 +475,7 @@ def __next__(self): _publish = DummyCallable() _publish._result = _response app_iter = self._callFUT(environ, start_response, _publish) - self.assertTrue(app_iter is body) + self.assertIs(app_iter, body) def test_stream_file_wrapper(self): from zope.interface import implementer @@ -504,8 +504,8 @@ def __init__(self, file): _publish = DummyCallable() _publish._result = _response app_iter = self._callFUT(environ, start_response, _publish) - self.assertTrue(app_iter.file is body) - self.assertTrue(isinstance(app_iter, Wrapper)) + self.assertIs(app_iter.file, body) + self.assertIsInstance(app_iter, Wrapper) self.assertEqual( int(_response.headers['content-length']), len(body)) self.assertTrue( @@ -542,8 +542,8 @@ def __init__(self, file): _publish = DummyCallable() _publish._result = _response app_iter = self._callFUT(environ, start_response, _publish) - self.assertTrue(app_iter.file is body) - self.assertTrue(isinstance(app_iter, Wrapper)) + self.assertIs(app_iter.file, body) + self.assertIsInstance(app_iter, Wrapper) self.assertEqual( int(_response.headers['content-length']), len(body)) self.assertTrue( @@ -576,8 +576,8 @@ def __init__(self, file): app_iter = self._callFUT(environ, start_response, _publish) # The stream iterator has no ``read`` and will not be used # for ``wsgi.file_wrapper``. It is returned as-is. - self.assertTrue(app_iter is body) - self.assertTrue(isinstance(app_iter, TestStreamIterator)) + self.assertIs(app_iter, body) + self.assertIsInstance(app_iter, TestStreamIterator) self.assertEqual( int(_response.headers['content-length']), len(body)) self.assertTrue( @@ -684,7 +684,7 @@ def testCustomExceptionViewUnauthorized(self): app_iter = self._callFUT(environ, start_response, _publish) body = b''.join(app_iter) self.assertEqual(start_response._called_with[0][0], '401 Unauthorized') - self.assertTrue(b'Exception View: Unauthorized' in body) + self.assertIn(b'Exception View: Unauthorized', body) unregisterExceptionView(IUnauthorized) def testCustomExceptionViewForbidden(self): @@ -697,7 +697,7 @@ def testCustomExceptionViewForbidden(self): app_iter = self._callFUT(environ, start_response, _publish) body = b''.join(app_iter) self.assertEqual(start_response._called_with[0][0], '403 Forbidden') - self.assertTrue(b'Exception View: Forbidden' in body) + self.assertIn(b'Exception View: Forbidden', body) unregisterExceptionView(IForbidden) def testCustomExceptionViewNotFound(self): @@ -710,7 +710,7 @@ def testCustomExceptionViewNotFound(self): app_iter = self._callFUT(environ, start_response, _publish) body = b''.join(app_iter) self.assertEqual(start_response._called_with[0][0], '404 Not Found') - self.assertTrue(b'Exception View: NotFound' in body) + self.assertIn(b'Exception View: NotFound', body) unregisterExceptionView(INotFound) def testCustomExceptionViewZTKNotFound(self): @@ -723,7 +723,7 @@ def testCustomExceptionViewZTKNotFound(self): app_iter = self._callFUT(environ, start_response, _publish) body = b''.join(app_iter) self.assertEqual(start_response._called_with[0][0], '404 Not Found') - self.assertTrue(b'Exception View: NotFound' in body) + self.assertIn(b'Exception View: NotFound', body) unregisterExceptionView(INotFound) def testCustomExceptionViewBadRequest(self): @@ -736,7 +736,7 @@ def testCustomExceptionViewBadRequest(self): app_iter = self._callFUT(environ, start_response, _publish) body = b''.join(app_iter) self.assertEqual(start_response._called_with[0][0], '400 Bad Request') - self.assertTrue(b'Exception View: BadRequest' in body) + self.assertIn(b'Exception View: BadRequest', body) unregisterExceptionView(IException) def testCustomExceptionViewInternalError(self): @@ -750,7 +750,7 @@ def testCustomExceptionViewInternalError(self): body = b''.join(app_iter) self.assertEqual( start_response._called_with[0][0], '500 Internal Server Error') - self.assertTrue(b'Exception View: InternalError' in body) + self.assertIn(b'Exception View: InternalError', body) unregisterExceptionView(IException) def testRedirectExceptionView(self): @@ -764,7 +764,7 @@ def testRedirectExceptionView(self): body = b''.join(app_iter) status, headers = start_response._called_with[0] self.assertEqual(status, '302 Found') - self.assertTrue(b'Exception View: Redirect' in body) + self.assertIn(b'Exception View: Redirect', body) headers = dict(headers) self.assertEqual(headers['Location'], 'http://localhost:9/') unregisterExceptionView(IException) @@ -811,14 +811,14 @@ def test_set_REMOTE_USER_environ(self): _response = DummyResponse() _publish = DummyCallable() _publish._result = _response - self.assertFalse('REMOTE_USER' in environ) + self.assertNotIn('REMOTE_USER', environ) self._callFUT(environ, start_response, _publish) self.assertEqual(environ['REMOTE_USER'], user_name) # After logout there is no REMOTE_USER in environ environ = self._makeEnviron() self.logout() self._callFUT(environ, start_response, _publish) - self.assertFalse('REMOTE_USER' in environ) + self.assertNotIn('REMOTE_USER', environ) def test_set_REMOTE_USER_environ_error(self): environ = self._makeEnviron() diff --git a/src/ZPublisher/tests/test_cookie.py b/src/ZPublisher/tests/test_cookie.py index 460cc882ab..d286b3d83d 100644 --- a/src/ZPublisher/tests/test_cookie.py +++ b/src/ZPublisher/tests/test_cookie.py @@ -175,7 +175,7 @@ def test_http_only(self): # test true n, v = convertCookieParameter("Http_Only", True) self.assertEqual(n, "HttpOnly") - self.assertIs(v, True) + self.assertTrue(v) # test false _, v = convertCookieParameter("http_only", False) self.assertIsNone(v) @@ -183,7 +183,7 @@ def test_http_only(self): def test_secure(self): n, v = convertCookieParameter("secure", True) self.assertEqual(n, "Secure") - self.assertIs(v, True) + self.assertTrue(v) def test_samesite(self): for t in "None Lax Strict".split(): diff --git a/src/ZPublisher/tests/test_pubevents.py b/src/ZPublisher/tests/test_pubevents.py index fa86ed26bc..94cf65c2c0 100644 --- a/src/ZPublisher/tests/test_pubevents.py +++ b/src/ZPublisher/tests/test_pubevents.py @@ -168,7 +168,7 @@ def testStreaming(self): self.assertIsInstance(events[0], PubBeforeStreaming) self.assertEqual(events[0].response, response) - self.assertTrue(b'datachunk1datachunk2' in out.getvalue()) + self.assertIn(b'datachunk1datachunk2', out.getvalue()) class ExceptionView: diff --git a/src/ZPublisher/tests/test_xmlrpc.py b/src/ZPublisher/tests/test_xmlrpc.py index 5a73ef232e..025badfc43 100644 --- a/src/ZPublisher/tests/test_xmlrpc.py +++ b/src/ZPublisher/tests/test_xmlrpc.py @@ -58,7 +58,7 @@ def test_nil(self): response = self._makeOne(faux) response.setBody(body) data, method = xmlrpc.client.loads(faux._body) - self.assertIs(data[0]['public'], None) + self.assertIsNone(data[0]['public']) def test_instance(self): # Instances are turned into dicts with their private @@ -135,8 +135,8 @@ def test_instance_security(self): response.setBody(folder) data, method = xmlrpc.client.loads(faux._body) - self.assertFalse('file1' in data[0].keys()) - self.assertTrue('file2' in data[0].keys()) + self.assertNotIn('file1', data[0].keys()) + self.assertIn('file2', data[0].keys()) def test_zopedatetimeinstance(self): # DateTime instance at top-level @@ -146,7 +146,7 @@ def test_zopedatetimeinstance(self): response.setBody(body) data, method = xmlrpc.client.loads(faux._body) data = data[0] - self.assertTrue(isinstance(data, xmlrpc.client.DateTime)) + self.assertIsInstance(data, xmlrpc.client.DateTime) self.assertEqual(data.value, '2006-05-24T07:00:00+00:00') def test_zopedatetimeattribute(self): @@ -157,7 +157,7 @@ def test_zopedatetimeattribute(self): response.setBody(body) data, method = xmlrpc.client.loads(faux._body) data = data[0]['public'] - self.assertTrue(isinstance(data, xmlrpc.client.DateTime)) + self.assertIsInstance(data, xmlrpc.client.DateTime) self.assertEqual(data.value, '2006-05-24T07:00:00+00:00') def test_zopedatetimeattribute_recursive(self): @@ -169,7 +169,7 @@ def test_zopedatetimeattribute_recursive(self): response.setBody(body) data, method = xmlrpc.client.loads(faux._body) data = data[0]['public']['public'] - self.assertTrue(isinstance(data, xmlrpc.client.DateTime)) + self.assertIsInstance(data, xmlrpc.client.DateTime) self.assertEqual(data.value, '2006-05-24T07:00:00+00:00') def test_zopedatetimeinstance_in_list(self): @@ -180,7 +180,7 @@ def test_zopedatetimeinstance_in_list(self): response.setBody(body) data, method = xmlrpc.client.loads(faux._body) data = data[0][0] - self.assertTrue(isinstance(data, xmlrpc.client.DateTime)) + self.assertIsInstance(data, xmlrpc.client.DateTime) self.assertEqual(data.value, '2006-05-24T07:00:00+00:00') def test_zopedatetimeinstance_in_dict(self): @@ -191,7 +191,7 @@ def test_zopedatetimeinstance_in_dict(self): response.setBody(body) data, method = xmlrpc.client.loads(faux._body) data = data[0]['date'] - self.assertTrue(isinstance(data, xmlrpc.client.DateTime)) + self.assertIsInstance(data, xmlrpc.client.DateTime) self.assertEqual(data.value, '2006-05-24T07:00:00+00:00') def test_functionattribute(self): diff --git a/src/ZTUtils/tests/testTree.py b/src/ZTUtils/tests/testTree.py index b2d7c97aa1..8df4c07646 100644 --- a/src/ZTUtils/tests/testTree.py +++ b/src/ZTUtils/tests/testTree.py @@ -270,7 +270,7 @@ def testBaseTree(self): self.assertEqual(treeroot.height, 2) self.assertEqual(treeroot.depth, 0) self.assertEqual(treeroot.state, 1) - self.assertTrue(treeroot.object is self.root) + self.assertIs(treeroot.object, self.root) i = 'b' for subnode in treeroot: @@ -279,7 +279,7 @@ def testBaseTree(self): self.assertEqual(subnode.height, 1) self.assertEqual(subnode.depth, 1) self.assertEqual(subnode.state, -1) - self.assertTrue(subnode.object is self.items[i]) + self.assertIs(subnode.object, self.items[i]) i = chr(ord(i) + 1) expected_set = [self.items['a'], self.items['b'], self.items['c']] @@ -305,7 +305,7 @@ def testExpandedTree(self): self.assertEqual(treeroot.height, 4) self.assertEqual(treeroot.depth, 0) self.assertEqual(treeroot.state, 1) - self.assertTrue(treeroot.object is self.root) + self.assertIs(treeroot.object, self.root) items = self.items expected_set = [ @@ -420,7 +420,7 @@ def testEncodeDecode(self): treeroot1 = self.tm.tree(self.root, self.expansionmap) encoded = Tree.encodeExpansion(treeroot1.flat()) - self.assertFalse(encoded.find(b'\n') != -1) + self.assertEqual(encoded.find(b'\n'), -1) decodedmap = Tree.decodeExpansion(encoded) treeroot2 = self.tm.tree(self.root, decodedmap) @@ -451,6 +451,6 @@ def testDecodeDecompressedSizeLimit(self): from ZTUtils.Tree import b2a big = b2a(zlib.compress(b'x' * (1024 * 1100))) - self.assertTrue(len(big) < 8192) # Must be under the input size limit + self.assertLess(len(big), 8192) # Must be under the input size limit with self.assertRaises(ValueError): Tree.decodeExpansion(b':' + big) diff --git a/src/Zope2/App/tests/test_schema.py b/src/Zope2/App/tests/test_schema.py index 9c722afa4a..db3f468c5a 100644 --- a/src/Zope2/App/tests/test_schema.py +++ b/src/Zope2/App/tests/test_schema.py @@ -51,4 +51,4 @@ def _factory(context): registry = self._makeOne() context = object() found = registry.get(context, 'foundit') - self.assertTrue(found is _marker) + self.assertIs(found, _marker) diff --git a/src/webdav/tests/testPUT_factory.py b/src/webdav/tests/testPUT_factory.py index 0eb92d4501..af6cf42c5d 100644 --- a/src/webdav/tests/testPUT_factory.py +++ b/src/webdav/tests/testPUT_factory.py @@ -45,35 +45,35 @@ def testNoVirtualHosting(self): request = self.app.REQUEST put = request.traverse('/folder/doc') put(request, request.RESPONSE) - self.assertTrue('doc' in self.folder.objectIds()) + self.assertIn('doc', self.folder.objectIds()) def testSimpleVirtualHosting(self): request = self.app.REQUEST put = request.traverse('/VirtualHostBase/http/foo.com:80/' 'VirtualHostRoot/folder/doc') put(request, request.RESPONSE) - self.assertTrue('doc' in self.folder.objectIds()) + self.assertIn('doc', self.folder.objectIds()) def testSubfolderVirtualHosting(self): request = self.app.REQUEST put = request.traverse('/VirtualHostBase/http/foo.com:80/' 'folder/VirtualHostRoot/doc') put(request, request.RESPONSE) - self.assertTrue('doc' in self.folder.objectIds()) + self.assertIn('doc', self.folder.objectIds()) def testInsideOutVirtualHosting(self): request = self.app.REQUEST put = request.traverse('/VirtualHostBase/http/foo.com:80/' 'VirtualHostRoot/_vh_foo/folder/doc') put(request, request.RESPONSE) - self.assertTrue('doc' in self.folder.objectIds()) + self.assertIn('doc', self.folder.objectIds()) def testSubfolderInsideOutVirtualHosting(self): request = self.app.REQUEST put = request.traverse('/VirtualHostBase/http/foo.com:80/' 'folder/VirtualHostRoot/_vh_foo/doc') put(request, request.RESPONSE) - self.assertTrue('doc' in self.folder.objectIds()) + self.assertIn('doc', self.folder.objectIds()) def testCollector2261(self): from OFS.DTMLMethod import addDTMLMethod @@ -106,7 +106,7 @@ def custom_put_factory(name, typ, body): request = self.app.REQUEST put = request.traverse('/folder/doc') put(request, request.RESPONSE) - self.assertTrue('newname' in self.folder.objectIds()) + self.assertIn('newname', self.folder.objectIds()) def test_default_PUT_factory_type_guessing(self): # Check how the default PUT factory guesses the type of object to diff --git a/src/webdav/tests/testResource.py b/src/webdav/tests/testResource.py index 332a78d87c..1e9d6fbd70 100644 --- a/src/webdav/tests/testResource.py +++ b/src/webdav/tests/testResource.py @@ -115,21 +115,21 @@ def test_ms_public_header(self): req, resp = make_request_response() resource = self._makeOne() resource.OPTIONS(req, resp) - self.assertTrue('public' not in resp.headers) + self.assertNotIn('public', resp.headers) Resource.enable_ms_public_header = True req, resp = make_request_response() resource = self._makeOne() resource.OPTIONS(req, resp) - self.assertTrue('public' not in resp.headers) - self.assertTrue('allow' in resp.headers) + self.assertNotIn('public', resp.headers) + self.assertIn('allow', resp.headers) req, resp = make_request_response( environ={'USER_AGENT': MS_DAV_AGENT}) resource = self._makeOne() resource.OPTIONS(req, resp) - self.assertTrue('public' in resp.headers) - self.assertTrue('allow' in resp.headers) + self.assertIn('public', resp.headers) + self.assertIn('allow', resp.headers) self.assertEqual(resp.headers['public'], resp.headers['allow']) finally: From dcaf00b369f8eaba1d84ec904cc7132d2e3021d3 Mon Sep 17 00:00:00 2001 From: Steffen Allner Date: Thu, 21 Sep 2023 17:13:33 +0200 Subject: [PATCH 07/12] Update pre-commit hooks. --- .github/workflows/{pre-commit.yaml => pre-commit.yml} | 0 .pre-commit-config.yaml | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) rename .github/workflows/{pre-commit.yaml => pre-commit.yml} (100%) diff --git a/.github/workflows/pre-commit.yaml b/.github/workflows/pre-commit.yml similarity index 100% rename from .github/workflows/pre-commit.yaml rename to .github/workflows/pre-commit.yml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 71760bedee..8fe1349bf5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,10 +3,10 @@ ci: repos: - repo: https://github.com/asottile/pyupgrade - rev: "v2.6.2" + rev: "v3.11.1" hooks: - id: pyupgrade - args: [--py36-plus] + args: [--py37-plus] - repo: https://github.com/pycqa/isort rev: "5.12.0" hooks: @@ -16,7 +16,7 @@ repos: hooks: - id: docformatter - repo: https://github.com/pre-commit/mirrors-autopep8 - rev: "v2.0.2" + rev: "v2.0.4" hooks: - id: autopep8 args: [--in-place, --aggressive, --aggressive] From bfe6aa9a3ed2c37e821ad93ff368dcab01bbaecc Mon Sep 17 00:00:00 2001 From: "pre-commit-ci-lite[bot]" <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com> Date: Thu, 21 Sep 2023 15:28:39 +0000 Subject: [PATCH 08/12] [pre-commit.ci lite] apply automatic fixes --- src/App/Undo.py | 2 +- src/OFS/ObjectManager.py | 4 ++-- src/Products/PageTemplates/tests/test_engine.py | 2 +- src/Products/SiteAccess/VirtualHostMonster.py | 2 +- src/ZPublisher/tests/testHTTPResponse.py | 10 +++++----- src/ZPublisher/tests/test_xmlrpc.py | 2 +- src/ZTUtils/Tree.py | 2 +- src/ZTUtils/tests/testTree.py | 2 +- src/Zope2/utilities/mkwsgiinstance.py | 2 +- 9 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/App/Undo.py b/src/App/Undo.py index 9d9bf2521e..821cd9d53c 100644 --- a/src/App/Undo.py +++ b/src/App/Undo.py @@ -118,7 +118,7 @@ def manage_undo_transactions(self, transaction_info=(), REQUEST=None): raise ts.abort() - error = '{}: {}'.format(exc.__class__.__name__, str(exc)) + error = f'{exc.__class__.__name__}: {str(exc)}' return self.manage_UndoForm(self, REQUEST, manage_tabs_message=error, manage_tabs_type='danger') diff --git a/src/OFS/ObjectManager.py b/src/OFS/ObjectManager.py index 7c475e5f23..c6c75110bc 100644 --- a/src/OFS/ObjectManager.py +++ b/src/OFS/ObjectManager.py @@ -783,9 +783,9 @@ def compute_size(self, ob): if ob_size < 1024: return '1 KiB' elif ob_size > 1048576: - return "{:0.02f} MiB".format(ob_size / 1048576.0) + return f"{ob_size / 1048576.0:0.02f} MiB" else: - return "{:0.0f} KiB".format(ob_size / 1024.0) + return f"{ob_size / 1024.0:0.0f} KiB" @security.protected(access_contents_information) def last_modified(self, ob): diff --git a/src/Products/PageTemplates/tests/test_engine.py b/src/Products/PageTemplates/tests/test_engine.py index 6af0ce91c1..1f87848be5 100644 --- a/src/Products/PageTemplates/tests/test_engine.py +++ b/src/Products/PageTemplates/tests/test_engine.py @@ -68,7 +68,7 @@ def test_zopepagetemplate(self): self.assertIn( 'Hello world', template( - greeting='Hello world') + greeting='Hello world') ) # test commit diff --git a/src/Products/SiteAccess/VirtualHostMonster.py b/src/Products/SiteAccess/VirtualHostMonster.py index e57d2e8ba2..2d9e6134aa 100644 --- a/src/Products/SiteAccess/VirtualHostMonster.py +++ b/src/Products/SiteAccess/VirtualHostMonster.py @@ -60,7 +60,7 @@ def set_map(self, map_text, RESPONSE=None): # Drop the protocol, if any line = line.split('://')[-1] try: - host, path = [x.strip() for x in line.split('/', 1)] + host, path = (x.strip() for x in line.split('/', 1)) except Exception: raise ValueError( 'Line needs a slash between host and path: %s' % line) diff --git a/src/ZPublisher/tests/testHTTPResponse.py b/src/ZPublisher/tests/testHTTPResponse.py index 9a4b5b19e4..aad39f3b09 100644 --- a/src/ZPublisher/tests/testHTTPResponse.py +++ b/src/ZPublisher/tests/testHTTPResponse.py @@ -929,7 +929,7 @@ def test_badRequestError_valid_parameter_name(self): self.assertEqual(response.status, 400) self.assertIn( "The parameter, some_parameter, " - "was omitted from the request.", + "was omitted from the request.", str(raised) ) else: @@ -943,7 +943,7 @@ def test_badRequestError_invalid_parameter_name(self): self.assertEqual(response.status, 400) self.assertIn( "Sorry, an internal error occurred in this " - "resource.", + "resource.", str(raised) ) else: @@ -958,7 +958,7 @@ def test__unauthorized_no_realm(self): def test__unauthorized_w_default_realm(self): response = self._makeOne() response._unauthorized() - self.assertIn('WWW-Authenticate', response.headers) # literal + self.assertIn('WWW-Authenticate', response.headers) # literal self.assertEqual(response.headers['WWW-Authenticate'], 'basic realm="Zope", charset="UTF-8"') @@ -966,7 +966,7 @@ def test__unauthorized_w_realm(self): response = self._makeOne() response.realm = 'Folly' response._unauthorized() - self.assertIn('WWW-Authenticate', response.headers) # literal + self.assertIn('WWW-Authenticate', response.headers) # literal self.assertEqual(response.headers['WWW-Authenticate'], 'basic realm="Folly", charset="UTF-8"') @@ -978,7 +978,7 @@ def test_unauthorized_no_debug_mode(self): self.assertEqual(response.status, 200) # publisher sets 401 later self.assertIn( "You are not authorized " - "to access this resource.", + "to access this resource.", str(raised) ) else: diff --git a/src/ZPublisher/tests/test_xmlrpc.py b/src/ZPublisher/tests/test_xmlrpc.py index 025badfc43..f742354f4d 100644 --- a/src/ZPublisher/tests/test_xmlrpc.py +++ b/src/ZPublisher/tests/test_xmlrpc.py @@ -42,7 +42,7 @@ def test_setBody(self): response.setBody(body) body_str = faux._body - self.assertEqual(type(body_str), type('')) + self.assertEqual(type(body_str), str) as_set, method = xmlrpc.client.loads(body_str) as_set = as_set[0] diff --git a/src/ZTUtils/Tree.py b/src/ZTUtils/Tree.py index 62b926f628..b571ac7741 100644 --- a/src/ZTUtils/Tree.py +++ b/src/ZTUtils/Tree.py @@ -223,7 +223,7 @@ def tree(self, root, expanded=None, subtree=0): return node -_SIMPLE_TYPES = {type(''), type(b''), type(0), type(0.0), type(None)} +_SIMPLE_TYPES = {str, bytes, int, float, type(None)} def simple_type(ob): diff --git a/src/ZTUtils/tests/testTree.py b/src/ZTUtils/tests/testTree.py index 8df4c07646..603bde28d3 100644 --- a/src/ZTUtils/tests/testTree.py +++ b/src/ZTUtils/tests/testTree.py @@ -451,6 +451,6 @@ def testDecodeDecompressedSizeLimit(self): from ZTUtils.Tree import b2a big = b2a(zlib.compress(b'x' * (1024 * 1100))) - self.assertLess(len(big), 8192) # Must be under the input size limit + self.assertLess(len(big), 8192) # Must be under the input size limit with self.assertRaises(ValueError): Tree.decodeExpansion(b':' + big) diff --git a/src/Zope2/utilities/mkwsgiinstance.py b/src/Zope2/utilities/mkwsgiinstance.py index 107d48072d..f87d4ed854 100644 --- a/src/Zope2/utilities/mkwsgiinstance.py +++ b/src/Zope2/utilities/mkwsgiinstance.py @@ -224,7 +224,7 @@ def get_zope2path(python): try: output = subprocess.check_output( [python, '-c', 'import Zope2; print(Zope2.__file__)'], - universal_newlines=True, # makes Python 3 return text, not bytes + text=True, # makes Python 3 return text, not bytes stderr=subprocess.PIPE) zope2file = output.strip() except subprocess.CalledProcessError: From 3743bf1b0d7f3ea77919288fa1aac841c354789f Mon Sep 17 00:00:00 2001 From: Steffen Allner Date: Fri, 22 Sep 2023 09:32:25 +0200 Subject: [PATCH 09/12] Move slow linters back to `tox -e lint`. Those checkers are not able to work on single files present in a commit but need conecptionally work on the whole repository (check-manifest) and thus are not suited to be run before each commit, but only in the CI. --- .github/workflows/tests.yml | 3 +++ .pre-commit-config.yaml | 8 -------- tox.ini | 11 +++++++++++ 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 307c33fc23..dffa2b81f2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -22,6 +22,7 @@ jobs: - ["macos", "macos-11"] config: # [Python version, tox env] + - ["3.9", "lint"] - ["3.7", "py37"] - ["3.8", "py38"] - ["3.9", "py39"] @@ -31,8 +32,10 @@ jobs: - ["3.9", "docs"] - ["3.9", "coverage"] exclude: + - { os: ["windows", "windows-latest"], config: ["3.9", "lint"] } - { os: ["windows", "windows-latest"], config: ["3.9", "docs"] } - { os: ["windows", "windows-latest"], config: ["3.9", "coverage"] } + - { os: ["macos", "macos-11"], config: ["3.9", "lint"] } - { os: ["macos", "macos-11"], config: ["3.9", "docs"] } - { os: ["macos", "macos-11"], config: ["3.9", "coverage"] } # macOS/Python 3.11+ is set up for universal2 architecture diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8fe1349bf5..6c99aac659 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -32,11 +32,3 @@ repos: hooks: - id: teyit exclude: src/App/tests/fixtures/error.py # invalid syntax - - repo: https://github.com/mgedmin/check-manifest - rev: "0.49" - hooks: - - id: check-manifest - - repo: https://github.com/mgedmin/check-python-versions - rev: "0.21.3" - hooks: - - id: check-python-versions diff --git a/tox.ini b/tox.ini index 98eeac6bd1..6491464a88 100644 --- a/tox.ini +++ b/tox.ini @@ -3,6 +3,7 @@ [tox] minversion = 3.18 envlist = + lint py37 py38 py39 @@ -30,6 +31,16 @@ commands = {envdir}/bin/alltests --layer '!Products.PluginIndexes' {posargs:-vc} allowlist_externals = * +[testenv:lint] +basepython = python3 +commands_pre = +commands = + check-manifest + check-python-versions +deps = + check-manifest + check-python-versions + [testenv:pre-commit] basepython = python3 description = This env runs all linters configured in .pre-commit-config.yaml From e0f172c9dcdc56b689ff6251029ba518bbfed655 Mon Sep 17 00:00:00 2001 From: Steffen Allner Date: Fri, 22 Sep 2023 11:02:18 +0200 Subject: [PATCH 10/12] Apply suggestions from code review These are mostly documentation changes. Some of the docstrings might influence the public availability of the methods on an object. Co-authored-by: Michael Howitz --- .github/workflows/pre-commit.yml | 2 ++ src/OFS/DTMLDocument.py | 5 +---- src/OFS/EtagSupport.py | 4 ++-- src/OFS/Image.py | 4 +++- src/OFS/PropertySheets.py | 1 - src/OFS/SimpleItem.py | 2 +- src/OFS/interfaces.py | 2 +- src/OFS/tests/testFindSupport.py | 1 - src/OFS/userfolder.py | 4 ++-- src/Products/Five/browser/tests/test_defaultview.py | 2 +- src/Products/SiteAccess/VirtualHostMonster.py | 2 +- src/Shared/DC/Scripts/Signature.py | 8 ++------ src/Testing/ZopeTestCase/ZopeLite.py | 5 +++-- src/ZPublisher/tests/testHTTPResponse.py | 3 +-- src/ZPublisher/tests/test_pubevents.py | 1 - src/webdav/hookable_PUT.py | 2 +- 16 files changed, 21 insertions(+), 27 deletions(-) diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 48d2f6d19a..c716075bd0 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -1,3 +1,5 @@ +name: pre-commit + on: pull_request: diff --git a/src/OFS/DTMLDocument.py b/src/OFS/DTMLDocument.py index 2cd02d7d52..7f07824566 100644 --- a/src/OFS/DTMLDocument.py +++ b/src/OFS/DTMLDocument.py @@ -46,10 +46,7 @@ class DTMLDocument(PropertyManager, DTMLMethod): # Replace change_dtml_methods by change_dtml_documents __ac_permissions__ = tuple([ - # fmt: off - (perms[0] == change_dtml_methods) and # NOQA: W504 - (change_dtml_documents, perms[1]) or perms - # fmt: on + (change_dtml_documents, perms[1]) if (perms[0] == change_dtml_methods) else perms for perms in DTMLMethod.__ac_permissions__]) def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw): diff --git a/src/OFS/EtagSupport.py b/src/OFS/EtagSupport.py index ca4baa537a..c3e5968478 100644 --- a/src/OFS/EtagSupport.py +++ b/src/OFS/EtagSupport.py @@ -20,10 +20,10 @@ class EtagBaseInterface(Interface): - """\\ Basic Etag support interface, meaning the object supports generating + """Basic Etag support interface, meaning the object supports generating an Etag that can be used by certain HTTP and WebDAV Requests.""" def http__etag(): - """\\ Entity tags are used for comparing two or more entities from the + """Entity tags are used for comparing two or more entities from the same requested resource. Predominantly used for Caching, Etags can also be used to deal diff --git a/src/OFS/Image.py b/src/OFS/Image.py index 8a3c1c1084..3742867a8c 100644 --- a/src/OFS/Image.py +++ b/src/OFS/Image.py @@ -1083,7 +1083,9 @@ def tag( intelligently for 'height', 'width', and 'alt'. If specified, the 'scale', 'xscale', and 'yscale' keyword arguments will be used to automatically adjust the output height and width values - of the image tag. # Since 'class' is a Python reserved word, it + of the image tag. + + Since 'class' is a Python reserved word, it cannot be passed in directly in keyword arguments which is a problem if you are trying to use 'tag()' to include a CSS class. The tag() method will accept a 'css_class' argument that will be diff --git a/src/OFS/PropertySheets.py b/src/OFS/PropertySheets.py index 0e6acde2f2..28165c4e6d 100644 --- a/src/OFS/PropertySheets.py +++ b/src/OFS/PropertySheets.py @@ -470,7 +470,6 @@ def get(self, name, default=None): @security.protected(manage_properties) def manage_addPropertySheet(self, id, ns, REQUEST=None): - """""" md = {'xmlns': ns} ps = self.PropertySheetClass(id, md) self.addPropertySheet(ps) diff --git a/src/OFS/SimpleItem.py b/src/OFS/SimpleItem.py index f09c26cd6b..cd3dd01c5a 100644 --- a/src/OFS/SimpleItem.py +++ b/src/OFS/SimpleItem.py @@ -303,7 +303,7 @@ def raise_standardErrorMessage( tb = None def manage(self, URL1): - """""" + """Redirect to manage_main.""" raise Redirect("%s/manage_main" % URL1) # This keeps simple items from acquiring their parents diff --git a/src/OFS/interfaces.py b/src/OFS/interfaces.py index 2b0bc91fa4..474b4c7ce9 100644 --- a/src/OFS/interfaces.py +++ b/src/OFS/interfaces.py @@ -394,7 +394,7 @@ class ILockItem(Interface): # XXX: WAAAA! What is a ctor doing in the interface? def __init__(creator, owner, depth=0, timeout='Infinity', locktype='write', lockscope='exclusive', token=None): - """\\ If any of the following are untrue, a **ValueError** exception + """If any of the following are untrue, a **ValueError** exception will be raised. - **creator** MUST be a Zope user object or string to find a diff --git a/src/OFS/tests/testFindSupport.py b/src/OFS/tests/testFindSupport.py index b09b5796cd..94c3b03eaa 100644 --- a/src/OFS/tests/testFindSupport.py +++ b/src/OFS/tests/testFindSupport.py @@ -4,7 +4,6 @@ class DummyItem(FindSupport): - """""" def __init__(self, id, text=''): self.id = id diff --git a/src/OFS/userfolder.py b/src/OFS/userfolder.py index 3109fe1f0d..c2859c8a8f 100644 --- a/src/OFS/userfolder.py +++ b/src/OFS/userfolder.py @@ -112,7 +112,7 @@ def manage_userFolderProperties( REQUEST=None, manage_tabs_message=None ): - """""" + """Manage user folder properties.""" return self._userFolderProperties( self, REQUEST, @@ -321,7 +321,7 @@ def _createInitialUser(self): def manage_addUserFolder(self, dtself=None, REQUEST=None, **ignored): - """""" + """Add a user folder.""" f = UserFolder() self = self.this() try: diff --git a/src/Products/Five/browser/tests/test_defaultview.py b/src/Products/Five/browser/tests/test_defaultview.py index 49573309ed..d3e2617fdb 100644 --- a/src/Products/Five/browser/tests/test_defaultview.py +++ b/src/Products/Five/browser/tests/test_defaultview.py @@ -88,7 +88,7 @@ def test_default_view(): def test_default_method_args_marshalling(): - """\\ Test the default call method of a view, with respect to possible + """Test the default call method of a view, with respect to possible breakage of argument marshalling from other components. This is not directly a bug in Five, just a change that enables diff --git a/src/Products/SiteAccess/VirtualHostMonster.py b/src/Products/SiteAccess/VirtualHostMonster.py index 2d9e6134aa..30479ecd0b 100644 --- a/src/Products/SiteAccess/VirtualHostMonster.py +++ b/src/Products/SiteAccess/VirtualHostMonster.py @@ -254,7 +254,7 @@ def __bobo_traverse__(self, request, name): def manage_addVirtualHostMonster(self, id=None, REQUEST=None, **ignored): - """""" + """Add a virtual host monster.""" container = self.this() vhm = VirtualHostMonster() container._setObject(vhm.getId(), vhm) diff --git a/src/Shared/DC/Scripts/Signature.py b/src/Shared/DC/Scripts/Signature.py index 1cd718fe9f..2e64ff2c5c 100644 --- a/src/Shared/DC/Scripts/Signature.py +++ b/src/Shared/DC/Scripts/Signature.py @@ -32,18 +32,14 @@ def __init__(self, varnames=(), argcount=-1): def __eq__(self, other): if not isinstance(other, FuncCode): return False - # fmt: off - return ((self.co_argcount, self.co_varnames) == # NOQA: W504 + return ((self.co_argcount, self.co_varnames) == (other.co_argcount, other.co_varnames)) - # fmt: on def __lt__(self, other): if not isinstance(other, FuncCode): return False - # fmt: off - return ((self.co_argcount, self.co_varnames) < # NOQA: W504 + return ((self.co_argcount, self.co_varnames) < (other.co_argcount, other.co_varnames)) - # fmt: on def _setFuncSignature(self, defaults=None, varnames=(), argcount=-1): diff --git a/src/Testing/ZopeTestCase/ZopeLite.py b/src/Testing/ZopeTestCase/ZopeLite.py index 42652465b5..28fb254921 100644 --- a/src/Testing/ZopeTestCase/ZopeLite.py +++ b/src/Testing/ZopeTestCase/ZopeLite.py @@ -18,8 +18,9 @@ Typically used as in -import ZopeLite as Zope2 Zope2.installProduct('SomeProduct') app = -Zope2.app() + >>> import ZopeLite as Zope2 + >>> Zope2.installProduct('SomeProduct') + >>> app = Zope2.app() """ import os diff --git a/src/ZPublisher/tests/testHTTPResponse.py b/src/ZPublisher/tests/testHTTPResponse.py index aad39f3b09..624335b887 100644 --- a/src/ZPublisher/tests/testHTTPResponse.py +++ b/src/ZPublisher/tests/testHTTPResponse.py @@ -977,8 +977,7 @@ def test_unauthorized_no_debug_mode(self): except Unauthorized as raised: self.assertEqual(response.status, 200) # publisher sets 401 later self.assertIn( - "You are not authorized " - "to access this resource.", + "You are not authorized to access this resource.", str(raised) ) else: diff --git a/src/ZPublisher/tests/test_pubevents.py b/src/ZPublisher/tests/test_pubevents.py index 94cf65c2c0..4b8141accf 100644 --- a/src/ZPublisher/tests/test_pubevents.py +++ b/src/ZPublisher/tests/test_pubevents.py @@ -306,7 +306,6 @@ def cleanup(): def _succeed(): - """""" return 'success' diff --git a/src/webdav/hookable_PUT.py b/src/webdav/hookable_PUT.py index 99f3aac67c..2d0236f223 100644 --- a/src/webdav/hookable_PUT.py +++ b/src/webdav/hookable_PUT.py @@ -8,7 +8,7 @@ def PUT_factory(self, name, typ, body): - """""" + """PUT factory""" if TEXT_PATTERN.match(typ): return OFS.DTMLMethod.DTMLMethod('', __name__=name) return None From 7415c0065473ff6eaf72ceb59246da564e0a3ca4 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci-lite[bot]" <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com> Date: Fri, 22 Sep 2023 09:03:31 +0000 Subject: [PATCH 11/12] [pre-commit.ci lite] apply automatic fixes --- src/OFS/EtagSupport.py | 4 ++-- src/OFS/Image.py | 12 ++++++------ src/OFS/interfaces.py | 4 ++-- src/Shared/DC/Scripts/Signature.py | 8 ++++---- src/webdav/hookable_PUT.py | 2 +- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/OFS/EtagSupport.py b/src/OFS/EtagSupport.py index c3e5968478..b2facda348 100644 --- a/src/OFS/EtagSupport.py +++ b/src/OFS/EtagSupport.py @@ -20,8 +20,8 @@ class EtagBaseInterface(Interface): - """Basic Etag support interface, meaning the object supports generating - an Etag that can be used by certain HTTP and WebDAV Requests.""" + """Basic Etag support interface, meaning the object supports generating an + Etag that can be used by certain HTTP and WebDAV Requests.""" def http__etag(): """Entity tags are used for comparing two or more entities from the same requested resource. diff --git a/src/OFS/Image.py b/src/OFS/Image.py index 3742867a8c..59a10ee7f1 100644 --- a/src/OFS/Image.py +++ b/src/OFS/Image.py @@ -1084,12 +1084,12 @@ def tag( the 'scale', 'xscale', and 'yscale' keyword arguments will be used to automatically adjust the output height and width values of the image tag. - - Since 'class' is a Python reserved word, it - cannot be passed in directly in keyword arguments which is a - problem if you are trying to use 'tag()' to include a CSS class. - The tag() method will accept a 'css_class' argument that will be - converted to 'class' in the output tag to work around this. + + Since 'class' is a Python reserved word, it cannot be passed in + directly in keyword arguments which is a problem if you are + trying to use 'tag()' to include a CSS class. The tag() method + will accept a 'css_class' argument that will be converted to + 'class' in the output tag to work around this. """ if height is None: height = self.height diff --git a/src/OFS/interfaces.py b/src/OFS/interfaces.py index 474b4c7ce9..27214dba32 100644 --- a/src/OFS/interfaces.py +++ b/src/OFS/interfaces.py @@ -394,8 +394,8 @@ class ILockItem(Interface): # XXX: WAAAA! What is a ctor doing in the interface? def __init__(creator, owner, depth=0, timeout='Infinity', locktype='write', lockscope='exclusive', token=None): - """If any of the following are untrue, a **ValueError** exception - will be raised. + """If any of the following are untrue, a **ValueError** exception will + be raised. - **creator** MUST be a Zope user object or string to find a valid user object. diff --git a/src/Shared/DC/Scripts/Signature.py b/src/Shared/DC/Scripts/Signature.py index 2e64ff2c5c..ed035b875d 100644 --- a/src/Shared/DC/Scripts/Signature.py +++ b/src/Shared/DC/Scripts/Signature.py @@ -32,14 +32,14 @@ def __init__(self, varnames=(), argcount=-1): def __eq__(self, other): if not isinstance(other, FuncCode): return False - return ((self.co_argcount, self.co_varnames) == - (other.co_argcount, other.co_varnames)) + return ((self.co_argcount, self.co_varnames) + == (other.co_argcount, other.co_varnames)) def __lt__(self, other): if not isinstance(other, FuncCode): return False - return ((self.co_argcount, self.co_varnames) < - (other.co_argcount, other.co_varnames)) + return ((self.co_argcount, self.co_varnames) + < (other.co_argcount, other.co_varnames)) def _setFuncSignature(self, defaults=None, varnames=(), argcount=-1): diff --git a/src/webdav/hookable_PUT.py b/src/webdav/hookable_PUT.py index 2d0236f223..7bc1c02128 100644 --- a/src/webdav/hookable_PUT.py +++ b/src/webdav/hookable_PUT.py @@ -8,7 +8,7 @@ def PUT_factory(self, name, typ, body): - """PUT factory""" + """PUT factory.""" if TEXT_PATTERN.match(typ): return OFS.DTMLMethod.DTMLMethod('', __name__=name) return None From 3418f47daa122f122e0c51ab2aca09a1817a458b Mon Sep 17 00:00:00 2001 From: Steffen Allner Date: Fri, 22 Sep 2023 11:20:20 +0200 Subject: [PATCH 12/12] Format line which was not touched by autopep8. --- src/OFS/DTMLDocument.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/OFS/DTMLDocument.py b/src/OFS/DTMLDocument.py index 7f07824566..0fac552b52 100644 --- a/src/OFS/DTMLDocument.py +++ b/src/OFS/DTMLDocument.py @@ -46,7 +46,8 @@ class DTMLDocument(PropertyManager, DTMLMethod): # Replace change_dtml_methods by change_dtml_documents __ac_permissions__ = tuple([ - (change_dtml_documents, perms[1]) if (perms[0] == change_dtml_methods) else perms + (change_dtml_documents, perms[1]) + if (perms[0] == change_dtml_methods) else perms for perms in DTMLMethod.__ac_permissions__]) def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):