From 151405a3352b0f7f4b97a1c1ade2dfe4d54a6c0a Mon Sep 17 00:00:00 2001 From: Johannes Raggam Date: Thu, 10 Dec 2015 23:35:02 +0100 Subject: [PATCH] autopep8 --- CHANGES.rst | 3 + setup.py | 158 +++++++++-------- src/plone/__init__.py | 1 + src/plone/testing/__init__.py | 8 +- src/plone/testing/_z2_testbrowser.py | 62 +++++-- src/plone/testing/layer.py | 34 ++-- src/plone/testing/publisher.py | 9 +- src/plone/testing/security.py | 5 +- src/plone/testing/testing_zca.zcml | 17 +- .../testing/testing_zca_more_specific.zcml | 14 +- src/plone/testing/tests.py | 17 +- src/plone/testing/z2.py | 166 ++++++++++++------ src/plone/testing/zca.py | 27 +-- src/plone/testing/zodb.py | 8 +- 14 files changed, 327 insertions(+), 202 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 58a6af1..6f107d8 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -10,6 +10,9 @@ New: Fixes: +- PEP 8. + [thet] + - Depend on zope.testrunner, which was moved out from zope.testing.testrunner. [thet] diff --git a/setup.py b/setup.py index 6fb36ff..90ed341 100644 --- a/setup.py +++ b/setup.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- import os import os.path import sys @@ -5,87 +6,88 @@ version = '4.1.0.dev0' -install_requires = ['setuptools', - 'zope.testing', - ] +install_requires = [ + 'setuptools', + 'zope.testing', +] if sys.version_info < (2, 7): install_requires.append('unittest2') -tests_require = ['zope.component', - 'zope.interface', - 'zope.publisher', - 'zope.security', - 'zope.event', - 'zope.configuration', - 'zope.testbrowser', - 'zope.testrunner', - 'zope.app.publisher', # XXX: Can probably go away in Zope 2.13 - 'ZODB3', - 'Zope2', - ] +tests_require = [ + 'zope.component', + 'zope.interface', + 'zope.publisher', + 'zope.security', + 'zope.event', + 'zope.configuration', + 'zope.testbrowser', + 'zope.testrunner', + 'zope.app.publisher', # XXX: Can probably go away in Zope 2.13 + 'ZODB3', + 'Zope2', +] -setup(name='plone.testing', - version=version, - description="Testing infrastructure for Zope and Plone projects.", - long_description=(open(os.path.join("src", "plone", "testing", "README.rst")).read() + "\n\n" + - open("CHANGES.rst").read() + "\n\n" + - "Detailed documentation\n" + - "======================\n\n" + - open(os.path.join("src", "plone", "testing", "layer.txt")).read() + "\n\n" + - open(os.path.join("src", "plone", "testing", "zca.txt")).read() + "\n\n" + - open(os.path.join("src", "plone", "testing", "security.txt")).read() + "\n\n" + - open(os.path.join("src", "plone", "testing", "publisher.txt")).read() + "\n\n" + - open(os.path.join("src", "plone", "testing", "zodb.txt")).read()), - classifiers=[ - "Environment :: Web Environment", - "Framework :: Plone", - "Framework :: Plone :: 4.2", - "Framework :: Plone :: 4.3", - "Framework :: Plone :: 5.0", - "Operating System :: OS Independent", - "Programming Language :: Python", - "Programming Language :: Python :: 2.6", - "Programming Language :: Python :: 2.7", - "Topic :: Internet :: WWW/HTTP :: Dynamic Content", - "License :: OSI Approved :: BSD License", - ], - keywords='plone zope testing', - author='Plone Foundation', - author_email='plone-developers@lists.sourceforge.net', - url='https://github.com/plone/plone.testing', - license='BSD', - packages=find_packages('src'), - package_dir={'': 'src'}, - namespace_packages=['plone'], - include_package_data=True, - zip_safe=False, - install_requires=install_requires, - tests_require=tests_require, - extras_require={ - 'test': tests_require, - 'zodb': [ - 'ZODB3', - ], - 'zca': [ - 'zope.component', - 'zope.event', - 'zope.configuration', - ], - 'security': [ - 'zope.security', - ], - 'publisher': [ - 'zope.configuration', - 'zope.security', - 'zope.app.publisher', # XXX: Can probably go away in Zope 2.13 - ], - 'z2': [ - 'Zope2', - 'zope.site', - 'zope.testbrowser', - 'zope.publisher', - ], - }, - ) +setup( + name='plone.testing', + version=version, + description="Testing infrastructure for Zope and Plone projects.", + long_description=(open(os.path.join("src", "plone", "testing", "README.rst")).read() + "\n\n" + + open("CHANGES.rst").read() + "\n\n" + + "Detailed documentation\n" + + "======================\n\n" + + open(os.path.join("src", "plone", "testing", "layer.txt")).read() + "\n\n" + + open(os.path.join("src", "plone", "testing", "zca.txt")).read() + "\n\n" + + open(os.path.join("src", "plone", "testing", "security.txt")).read() + "\n\n" + + open(os.path.join("src", "plone", "testing", "publisher.txt")).read() + "\n\n" + + open(os.path.join("src", "plone", "testing", "zodb.txt")).read()), + classifiers=[ + "Environment :: Web Environment", + "Framework :: Plone", + "Framework :: Plone :: 4.2", + "Framework :: Plone :: 4.3", + "Framework :: Plone :: 5.0", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 2.6", + "Programming Language :: Python :: 2.7", + "Topic :: Internet :: WWW/HTTP :: Dynamic Content", + "License :: OSI Approved :: BSD License", + ], + keywords='plone zope testing', + author='Plone Foundation', + author_email='plone-developers@lists.sourceforge.net', + url='https://github.com/plone/plone.testing', + license='BSD', + packages=find_packages('src'), + package_dir={'': 'src'}, + namespace_packages=['plone'], + include_package_data=True, + zip_safe=False, + install_requires=install_requires, + tests_require=tests_require, + extras_require={ + 'test': tests_require, + 'zodb': ['ZODB3'], + 'zca': [ + 'zope.component', + 'zope.event', + 'zope.configuration', + ], + 'security': [ + 'zope.security', + ], + 'publisher': [ + 'zope.configuration', + 'zope.security', + 'zope.app.publisher', # XXX: Can probably go away in Zope 2.13 + ], + 'z2': [ + 'Zope2', + 'zope.site', + 'zope.testbrowser', + 'zope.publisher', + ], + }, +) diff --git a/src/plone/__init__.py b/src/plone/__init__.py index de40ea7..68c04af 100644 --- a/src/plone/__init__.py +++ b/src/plone/__init__.py @@ -1 +1,2 @@ +# -*- coding: utf-8 -*- __import__('pkg_resources').declare_namespace(__name__) diff --git a/src/plone/testing/__init__.py b/src/plone/testing/__init__.py index c879a5d..a39d736 100644 --- a/src/plone/testing/__init__.py +++ b/src/plone/testing/__init__.py @@ -1,6 +1,4 @@ +# -*- coding: utf-8 -*- # Convenience imports - -from plone.testing.layer import ( - Layer, - layered - ) +from plone.testing.layer import Layer # noqa +from plone.testing.layer import layered # noqa diff --git a/src/plone/testing/_z2_testbrowser.py b/src/plone/testing/_z2_testbrowser.py index 14cce2c..8a230ee 100644 --- a/src/plone/testing/_z2_testbrowser.py +++ b/src/plone/testing/_z2_testbrowser.py @@ -1,15 +1,14 @@ -import sys -import re +# -*- coding: utf-8 -*- +from cStringIO import StringIO import base64 +import mechanize +import pkg_resources +import re import rfc822 +import sys import urllib import urllib2 -from cStringIO import StringIO - -import mechanize -import pkg_resources - # Using a from-import here to avoid an AttributeError below when using # zope.testbrowser 4.x without zope.app.testing: from zope.testbrowser.testing import PublisherConnection, PublisherResponse @@ -18,6 +17,7 @@ try: pkg_resources.get_distribution('Zope2>=2.13') + def get_cookies(request): return request.response._cookie_list() except (pkg_resources.VersionConflict, pkg_resources.DistributionNotFound): @@ -31,15 +31,30 @@ class Browser(zope.testbrowser.browser.Browser): """ def __init__(self, app, url=None): - super(Browser, self).__init__(url=url, mech_browser=Zope2MechanizeBrowser(app)) + super( + Browser, + self).__init__( + url=url, + mech_browser=Zope2MechanizeBrowser(app)) + class Zope2MechanizeBrowser(mechanize.Browser): """A mechanize browser class that uses the Zope 2 publisher to talk HTTP """ - default_schemes = ['http'] - default_others = ['_http_error', '_http_request_upgrade', '_http_default_error'] - default_features = ['_redirect', '_cookies', '_referer', '_refresh','_equiv', '_basicauth', '_digestauth' ] + default_schemes = ['http'] + default_others = [ + '_http_error', + '_http_request_upgrade', + '_http_default_error'] + default_features = [ + '_redirect', + '_cookies', + '_referer', + '_refresh', + '_equiv', + '_basicauth', + '_digestauth'] def __init__(self, app, *args, **kws): @@ -52,6 +67,7 @@ def httpHandlerFactory(): if cls in mechanize.Browser.handler_classes] mechanize.Browser.__init__(self, *args, **kws) + class Zope2HTTPHandler(urllib2.HTTPHandler): """A protocol handler that uses the Zope 2 publisher to talk HTTP """ @@ -65,6 +81,7 @@ def connectionFactory(host, timeout=None): return Zope2Connection(self.app, host, timeout=timeout) return self.do_open(connectionFactory, req) + class Zope2Connection(PublisherConnection): """A urllib2-compatible connection that can talk to the Zope 2 publisher. """ @@ -92,9 +109,11 @@ def getresponse(self): # only change non-literal header names key = "%s%s" % (key[:1].upper(), key[1:]) start = 0 - l = key.find('-',start) + l = key.find('-', start) while l >= start: - key = "%s-%s%s" % (key[:l],key[l+1:l+2].upper(),key[l+2:]) + key = "%s-%s%s" % (key[:l], + key[l + 1:l + 2].upper(), + key[l + 2:]) start = l + 1 l = key.find('-', start) headers.append((key, val)) @@ -109,6 +128,7 @@ def getresponse(self): return PublisherResponse(content, headers, status, reason) + def saveState(func): """Save threadlocal state (security manager, local component site) before exectuting a decorated function, and restore it after. @@ -128,10 +148,14 @@ def wrapped_func(*args, **kw): return wrapped_func HEADER_RE = re.compile('(\S+): (.+)$') + + def splitHeader(header): return HEADER_RE.match(header).group(1, 2) BASIC_RE = re.compile('Basic (.+)?:(.+)?$') + + def authHeader(header): match = BASIC_RE.match(header) if match: @@ -144,6 +168,7 @@ def authHeader(header): return 'Basic %s' % auth[:-1] return header + class Zope2Caller(object): """Functional testing caller that can execute HTTP requests via the Zope 2 publisher. @@ -172,7 +197,7 @@ def setBody(self, body, title='', is_error=0, **kw): # Split off and parse the command line l = requestString.find('\n') commandLine = requestString[:l].rstrip() - requestString = requestString[l+1:] + requestString = requestString[l + 1:] method, url, protocol = commandLine.split() instream = StringIO(requestString) @@ -189,14 +214,15 @@ def setBody(self, body, title='', is_error=0, **kw): elif len(p) == 2: [env['PATH_INFO'], env['QUERY_STRING']] = p else: - raise TypeError, '' + raise TypeError('') # If you followed closely, you notice that one part of the url # gets unquoted (PATH_INFO) while the other (QUERY_STRING) # doesn't That complies with what the ZSERVER does. env['PATH_INFO'] = urllib.unquote(env['PATH_INFO']) - headers = [splitHeader(header) for header in rfc822.Message(instream).headers] + headers = [splitHeader(header) + for header in rfc822.Message(instream).headers] # Store request body without headers instream = StringIO(instream.read()) @@ -207,7 +233,7 @@ def setBody(self, body, title='', is_error=0, **kw): name = 'HTTP_' + name env[name] = value.rstrip() - if env.has_key('HTTP_AUTHORIZATION'): + if 'HTTP_AUTHORIZATION' in env: env['HTTP_AUTHORIZATION'] = authHeader(env['HTTP_AUTHORIZATION']) outstream = StringIO() @@ -218,7 +244,7 @@ def setBody(self, body, title='', is_error=0, **kw): stdin=instream, environ=env, debug=not handle_errors, - ) + ) self.app._p_jar.sync() diff --git a/src/plone/testing/layer.py b/src/plone/testing/layer.py index a14592a..8d8d76d 100644 --- a/src/plone/testing/layer.py +++ b/src/plone/testing/layer.py @@ -1,11 +1,13 @@ +# -*- coding: utf-8 -*- import sys _marker = object() + class ResourceManager(object): """Mixin class for resource managers. """ - __bases__ = () # must be set as an instance variable by subclass + __bases__ = () # must be set as an instance variable by subclass def __init__(self): self._resources = {} @@ -38,7 +40,7 @@ def __setitem__(self, key, value): foundStack = True foundStackItem = False - for idx in range(len(stack)-1, -1, -1): + for idx in range(len(stack) - 1, -1, -1): if stack[idx][1] is self: # This layer instance has already added an item to @@ -52,7 +54,7 @@ def __setitem__(self, key, value): # This layer instance does not have a stack item yet. Create # a new one. if not foundStackItem: - stack.append([value, self,]) + stack.append([value, self, ]) # Note: We do not break here on purpose: it's possible # that there is resource stack in another branch of the base @@ -67,7 +69,7 @@ def __delitem__(self, key): for resourceManager in self.baseResolutionOrder: if key in getattr(resourceManager, '_resources', {}): stack = resourceManager._resources[key] - for idx in range(len(stack)-1, -1, -1): + for idx in range(len(stack) - 1, -1, -1): if stack[idx][1] is self: del stack[idx] @@ -101,11 +103,11 @@ def _mergeResourceManagers(self, seqs): i += 1 - for seq in nonemptyseqs: # find merge candidates among seq heads + for seq in nonemptyseqs: # find merge candidates among seq heads cand = seq[0] - nothead=[s for s in nonemptyseqs if cand in s[1:]] + nothead = [s for s in nonemptyseqs if cand in s[1:]] if nothead: - cand=None #reject candidate + cand = None # reject candidate else: break @@ -113,16 +115,17 @@ def _mergeResourceManagers(self, seqs): raise TypeError(u"Inconsistent layer hierarchy!") res.append(cand) - for seq in nonemptyseqs: # remove cand + for seq in nonemptyseqs: # remove cand if seq[0] == cand: del seq[0] def _resourceResolutionOrder(self, instance): return self._mergeResourceManagers( - [ [instance] ] + - map(self._resourceResolutionOrder, instance.__bases__) + - [ list(instance.__bases__) ] - ) + [[instance]] + + map(self._resourceResolutionOrder, instance.__bases__) + + [list(instance.__bases__)] + ) + class Layer(ResourceManager): """A base class for layers. @@ -151,10 +154,10 @@ def __init__(self, bases=None, name=None, module=None): """ if self.__class__ is Layer and name is None: - raise ValueError('The `name` argument is required when instantiating `Layer` directly') + raise ValueError('The `name` argument is required when instantiating `Layer` directly') # noqa if name is None and bases is not None: - raise ValueError('The `name`` argument is required when overriding bases with the `bases` argument') + raise ValueError('The `name`` argument is required when overriding bases with the `bases` argument') # noqa super(Layer, self).__init__() @@ -201,6 +204,7 @@ def testSetUp(self): def testTearDown(self): pass + def layered(suite, layer, addLayerToDoctestGlobs=True): """Add the given layer to the given suite and return the suite. @@ -214,7 +218,7 @@ def layered(suite, layer, addLayerToDoctestGlobs=True): for test in suite: if hasattr(test, '_dt_test'): globs = test._dt_test.globs - if not 'layer' in globs: + if 'layer' not in globs: globs['layer'] = layer return suite diff --git a/src/plone/testing/publisher.py b/src/plone/testing/publisher.py index 26de1df..555e035 100644 --- a/src/plone/testing/publisher.py +++ b/src/plone/testing/publisher.py @@ -1,8 +1,10 @@ +# -*- coding: utf-8 -*- """Helpers for working with common Zope publisher operations """ - from plone.testing import Layer -from plone.testing import zca, security +from plone.testing import security +from plone.testing import zca + class PublisherDirectives(Layer): """Enables the use of the ZCML directives from ``zope.app.publisher`` @@ -19,7 +21,8 @@ def setUp(self): from zope.configuration import xmlconfig # Stack a new configuration context - self['configurationContext'] = context = zca.stackConfigurationContext(self.get('configurationContext')) + self['configurationContext'] = context = zca.stackConfigurationContext( + self.get('configurationContext')) import zope.security xmlconfig.file('meta.zcml', zope.security, context=context) diff --git a/src/plone/testing/security.py b/src/plone/testing/security.py index 2cfbb72..28516e7 100644 --- a/src/plone/testing/security.py +++ b/src/plone/testing/security.py @@ -1,10 +1,11 @@ +# -*- coding: utf-8 -*- """Security helpers and layers """ - from plone.testing import Layer _checkersStack = [] + def pushCheckers(): """Push the current set of security checkers onto a stack. You should normally do this during layer set-up, before loading any ZCML files that @@ -17,6 +18,7 @@ def pushCheckers(): _checkersStack.append(checker._checkers.copy()) + def popCheckers(): """Pop the most recently pushed set of security checkers from the stack. You should normally do this during layer tear-down. You *must* keep calls @@ -29,6 +31,7 @@ def popCheckers(): checker._checkers = _checkersStack.pop() + class Checkers(Layer): """Ensures correct isolation of security checkers in zope.security. """ diff --git a/src/plone/testing/testing_zca.zcml b/src/plone/testing/testing_zca.zcml index b5c5170..417804c 100644 --- a/src/plone/testing/testing_zca.zcml +++ b/src/plone/testing/testing_zca.zcml @@ -1,6 +1,13 @@ - - - + + + + + + diff --git a/src/plone/testing/testing_zca_more_specific.zcml b/src/plone/testing/testing_zca_more_specific.zcml index 43ec7d5..a6f0692 100644 --- a/src/plone/testing/testing_zca_more_specific.zcml +++ b/src/plone/testing/testing_zca_more_specific.zcml @@ -1,5 +1,11 @@ - - + + + + diff --git a/src/plone/testing/tests.py b/src/plone/testing/tests.py index 47f1876..a768614 100644 --- a/src/plone/testing/tests.py +++ b/src/plone/testing/tests.py @@ -1,6 +1,7 @@ +# -*- coding: utf-8 -*- try: import unittest2 as unittest -except ImportError: # Python 2.7 +except ImportError: # Python 2.7 import unittest import doctest @@ -20,20 +21,29 @@ # # To get around this, we define a fake method and stick it into the globs for # the doctest. + + def _canOutrunKlingons(warpDrive): return warpDrive.maxSpeed > 8.0 + class DummyUtility(object): + def __repr__(self): return "" + class DummyView(object): + def __init__(self, context, request): pass + def __call__(self): return u"" + class DummyFile(SimpleItem): + def __call__(self): path = get_distribution('plone.testing').location path = os.path.join(path, 'plone', 'testing', 'z2.txt') @@ -44,12 +54,15 @@ def __call__(self): response.setHeader('Content-Length', os.path.getsize(path)) return filestream_iterator(path) + def setUp(self): zope.component.testing.setUp() + def tearDown(self): zope.component.testing.tearDown() + def test_suite(): suite = unittest.TestSuite() suite.addTests([ @@ -66,7 +79,7 @@ def test_suite(): ), doctest.DocFileSuite( 'README.rst', - globs={'canOutrunKlingons': _canOutrunKlingons,}, + globs={'canOutrunKlingons': _canOutrunKlingons, }, setUp=setUp, tearDown=tearDown, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE, diff --git a/src/plone/testing/z2.py b/src/plone/testing/z2.py index 316f236..bb9e11c 100644 --- a/src/plone/testing/z2.py +++ b/src/plone/testing/z2.py @@ -1,12 +1,14 @@ +# -*- coding: utf-8 -*- """Zope2-specific helpers and layers """ - -import contextlib -import os - from plone.testing import Layer -from plone.testing import zodb from plone.testing import zca +from plone.testing import zodb +from zope.schema.vocabulary import getVocabularyRegistry +from zope.schema.vocabulary import setVocabularyRegistry +from Zope2.App.schema import Zope2VocabularyRegistry +import contextlib +import os try: from plone.testing._z2_testbrowser import Browser @@ -14,10 +16,6 @@ # Just in case zope.testbrowser causes an import error, don't break pass -from zope.schema.vocabulary import getVocabularyRegistry -from zope.schema.vocabulary import setVocabularyRegistry -from Zope2.App.schema import Zope2VocabularyRegistry - try: from OFS.metaconfigure import get_packages_to_initialize HAS_ZOPE213 = True @@ -26,6 +24,7 @@ _INSTALLED_PRODUCTS = {} + def installProduct(app, productName, quiet=False, multiinit=False): """Install the Zope 2 product with the given name, so that it will show up in the Zope 2 control panel and have its ``initialize()`` hook called. @@ -38,17 +37,14 @@ def installProduct(app, productName, quiet=False, multiinit=False): Note that products' ZCML is *not* loaded automatically, even if the product is in the Products namespace. """ - - import sys - - - from OFS.Folder import Folder - from OFS.Application import get_folder_permissions, get_products - from OFS.Application import install_product, install_package - from App.class_init import InitializeClass - + from OFS.Application import get_folder_permissions + from OFS.Application import get_products + from OFS.Application import install_package + from OFS.Application import install_product + from OFS.Folder import Folder import Products + import sys found = False @@ -59,10 +55,21 @@ def installProduct(app, productName, quiet=False, multiinit=False): for priority, name, index, productDir in get_products(): if ('Products.' + name) == productName: - install_product(app, productDir, name, [], get_folder_permissions(), raise_exc=1) + install_product( + app, + productDir, + name, + [], + get_folder_permissions(), + raise_exc=1) InitializeClass(Folder) - _INSTALLED_PRODUCTS[productName] = (priority, name, index, productDir,) + _INSTALLED_PRODUCTS[productName] = ( + priority, + name, + index, + productDir, + ) found = True break @@ -76,7 +83,8 @@ def installProduct(app, productName, quiet=False, multiinit=False): if module.__name__ == productName: install_package(app, module, init_func, raise_exc=1) if not HAS_ZOPE213: - Products._packages_to_initialize.remove((module, init_func)) + Products._packages_to_initialize.remove( + (module, init_func)) _INSTALLED_PRODUCTS[productName] = (module, init_func,) @@ -88,6 +96,7 @@ def installProduct(app, productName, quiet=False, multiinit=False): sys.stderr.write("Could not install product %s\n" % productName) sys.stderr.flush() + def uninstallProduct(app, productName, quiet=False): """Uninstall the given Zope 2 product. This is the inverse of ``installProduct()`` above. @@ -130,12 +139,13 @@ def uninstallProduct(app, productName, quiet=False): del cp[name] # TODO: Also remove permissions from get_folder_permissions? - # Difficult to know if this would stomp on any other permissions + # Difficult to know if this would stomp on any other + # permissions # InitializeClass(Folder) found = True break - elif productName in _INSTALLED_PRODUCTS: # must be a package + elif productName in _INSTALLED_PRODUCTS: # must be a package module, init_func = _INSTALLED_PRODUCTS[productName] name = module.__name__ @@ -168,6 +178,7 @@ def uninstallProduct(app, productName, quiet=False): sys.stderr.write("Could not install product %s\n" % productName) sys.stderr.flush() + def login(userFolder, userName): """Log in as the given user in the given user folder. """ @@ -181,6 +192,7 @@ def login(userFolder, userName): user = user.__of__(userFolder) newSecurityManager(None, user) + def logout(): """Log out, i.e. become anonymous """ @@ -188,6 +200,7 @@ def logout(): from AccessControl.SecurityManagement import noSecurityManager noSecurityManager() + def setRoles(userFolder, userId, roles): """Set the given user's roles to a tuple of roles. """ @@ -203,9 +216,9 @@ def setRoles(userFolder, userId, roles): def makeTestRequest(environ=None): """Return an HTTPRequest object suitable for testing views.""" from sys import stdin, stdout + from zope.publisher.browser import setDefaultSkin from ZPublisher.HTTPRequest import HTTPRequest from ZPublisher.HTTPResponse import HTTPResponse - from zope.publisher.browser import setDefaultSkin if environ is None: environ = {} @@ -272,18 +285,18 @@ def zopeApp(db=None, connection=None, environ=None): inner_exception = None try: yield app - except Exception, e: + except Exception as e: inner_exception = e try: transaction.abort() - except Exception, e: + except Exception as e: inner_exception = e raise raise else: try: transaction.commit() - except Exception, e: + except Exception as e: inner_exception = e finally: try: @@ -297,6 +310,7 @@ def zopeApp(db=None, connection=None, environ=None): else: raise + # Startup layer - you probably don't want to use this one directly class Startup(Layer): @@ -414,36 +428,48 @@ def setUpPatches(self): import Zope2.App.startup # Avoid expensive product import - def null_import_products(): pass + def null_import_products(): + pass self._OFS_Application_import_products = OFS.Application.import_products OFS.Application.import_products = null_import_products # Avoid expensive product installation - def null_initialize(app): pass + def null_initialize(app): + pass self._OFS_Application_initialize = OFS.Application.initialize OFS.Application.initialize = null_initialize # Avoid expensive help registration try: - self._App_ProductContext_ProductContext_registerHelpTopic = App.ProductContext.ProductContext.registerHelpTopic + self._App_ProductContext_ProductContext_registerHelpTopic = App.ProductContext.ProductContext.registerHelpTopic # noqa except AttributeError: # Zope 4 pass else: - def null_register_topic(self,id,topic): pass - App.ProductContext.ProductContext.registerHelpTopic = null_register_topic + def null_register_topic(self, id, topic): + pass + App.ProductContext.ProductContext.registerHelpTopic = null_register_topic # noqa + + self._App_ProductContext_ProductContext_registerHelpTitle = App.ProductContext.ProductContext.registerHelpTitle # noqa - self._App_ProductContext_ProductContext_registerHelpTitle = App.ProductContext.ProductContext.registerHelpTitle - def null_register_title(self,title): pass - App.ProductContext.ProductContext.registerHelpTitle = null_register_title + def null_register_title(self, title): + pass + App.ProductContext.ProductContext.registerHelpTitle = null_register_title # noqa - self._App_ProductContext_ProductContext_registerHelp = App.ProductContext.ProductContext.registerHelp - def null_register_help(self,directory='',clear=1,title_re=None): pass + self._App_ProductContext_ProductContext_registerHelp = App.ProductContext.ProductContext.registerHelp # noqa + + def null_register_help( + self, + directory='', + clear=1, + title_re=None): + pass App.ProductContext.ProductContext.registerHelp = null_register_help # in Zope 2.13, prevent ZCML from loading during App startup if hasattr(Zope2.App.startup, 'load_zcml'): - def null_load_zcml(): pass + def null_load_zcml(): + pass self._Zope2_App_startup_load_zcml = Zope2.App.startup.load_zcml Zope2.App.startup.load_zcml = null_load_zcml @@ -461,17 +487,17 @@ def tearDownPatches(self): del self._OFS_Application_initialize try: - App.ProductContext.ProductContext.registerHelpTopic = self._App_ProductContext_ProductContext_registerHelpTopic + App.ProductContext.ProductContext.registerHelpTopic = self._App_ProductContext_ProductContext_registerHelpTopic # noqa except AttributeError: # Zope 4 pass else: del self._App_ProductContext_ProductContext_registerHelpTopic - App.ProductContext.ProductContext.registerHelpTitle = self._App_ProductContext_ProductContext_registerHelpTitle + App.ProductContext.ProductContext.registerHelpTitle = self._App_ProductContext_ProductContext_registerHelpTitle # noqa del self._App_ProductContext_ProductContext_registerHelpTitle - App.ProductContext.ProductContext.registerHelp = self._App_ProductContext_ProductContext_registerHelp + App.ProductContext.ProductContext.registerHelp = self._App_ProductContext_ProductContext_registerHelp # noqa del self._App_ProductContext_ProductContext_registerHelp def setUpThreads(self): @@ -524,7 +550,9 @@ def setUpDatabase(self): # Layer a new storage for Zope 2 on top of the one from the base # layer, if there is one. - self['zodbDB'] = zodb.stackDemoStorage(self.get('zodbDB'), name='Startup') + self['zodbDB'] = zodb.stackDemoStorage( + self.get('zodbDB'), + name='Startup') # Create a facade for the database object that will delegate to the # correct underlying database. This allows resource shadowing to work @@ -551,7 +579,8 @@ class DBTab(Zope2.Startup.datatypes.DBTab): """ def __init__(self, db): - self.db_factories = {'testing': None} # value is never used when we have an open db + # value is never used when we have an open db + self.db_factories = {'testing': None} self.mount_paths = {'/': 'testing'} self.databases = {'testing': db} @@ -658,8 +687,10 @@ def tearDownBasicProducts(self): except ImportError: # Zope <= 2.12 from Products.Five import fiveconfigure as metaconfigure - metaconfigure._register_monkies = list(set(metaconfigure._register_monkies)) - metaconfigure._meta_type_regs = list(set(metaconfigure._meta_type_regs)) + metaconfigure._register_monkies = list( + set(metaconfigure._register_monkies)) + metaconfigure._meta_type_regs = list( + set(metaconfigure._meta_type_regs)) def setUpZCML(self): """Load the basic ZCML configuration from Five. Exposes a resource @@ -673,7 +704,8 @@ def setUpZCML(self): # Load something akin to the default site.zcml without actually auto- # loading products - self['configurationContext'] = context = zca.stackConfigurationContext(self.get('configurationContext')) + self['configurationContext'] = context = zca.stackConfigurationContext( + self.get('configurationContext')) from zope.configuration import xmlconfig xmlconfig.string("""\ @@ -720,6 +752,7 @@ def tearDownFive(self): STARTUP = Startup() + # Basic integration and functional test and layers. These are the simplest # Zope 2 layers that are generally useful @@ -744,7 +777,7 @@ class MyFixture(Layer): ... MY_FIXTURE = MyFixture(bases=(z2.STARTUP,), name='MyFixture') - MY_INTEGRATION_TESTING = z2.IntegrationTesting(bases=(MY_FIXTURE,), name='MyFixture:Integration') + MY_INTEGRATION_TESTING = z2.IntegrationTesting(bases=(MY_FIXTURE,), name='MyFixture:Integration') # noqa """ defaultBases = (STARTUP,) @@ -804,6 +837,7 @@ def testTearDown(self): INTEGRATION_TESTING = IntegrationTesting() + class FunctionalTesting(Layer): """An alternative to ``INTEGRATION_TESTING`` suitable for functional testing. This one pushes and pops a ``DemoStorage`` layer for each test. The @@ -825,7 +859,7 @@ class MyFixture(Layer): ... MY_FIXTURE = MyFixture(bases=(z2.STARTUP,), name='MyFixture') - MY_FUNCTIONAL_TESTING = z2.FunctionalTesting(bases=(MY_FIXTURE,), name='MyFixture:Functional') + MY_FUNCTIONAL_TESTING = z2.FunctionalTesting(bases=(MY_FIXTURE,), name='MyFixture:Functional') # noqa """ defaultBases = (STARTUP,) @@ -840,7 +874,9 @@ def testSetUp(self): # this layer, we can't just assign a new shadow. We therefore keep # track of the original so that we can restore it on tear-down. - self['zodbDB'] = zodb.stackDemoStorage(self.get('zodbDB'), name='FunctionalTest') + self['zodbDB'] = zodb.stackDemoStorage( + self.get('zodbDB'), + name='FunctionalTest') # Save the app @@ -894,6 +930,7 @@ def testTearDown(self): FUNCTIONAL_TESTING = FunctionalTesting() + # More advanced functional testing - running ZServer and FTP server class ZServer(Layer): @@ -931,9 +968,9 @@ def setUp(self): self.setUpServer() self.thread = Thread( - name="%s server" % self.__name__, - target=self.runner, - ) + name="%s server" % self.__name__, + target=self.runner, + ) self.thread.start() time.sleep(0.5) @@ -963,7 +1000,11 @@ def setUpServer(self): zopeLog = logger.file_logger(log) - server = zhttp_server(ip=self.host, port=self.port, resolver=None, logger_object=zopeLog) + server = zhttp_server( + ip=self.host, + port=self.port, + resolver=None, + logger_object=zopeLog) zhttpHandler = zhttp_handler(module='Zope2', uri_base='') server.install_handler(zhttpHandler) @@ -993,7 +1034,12 @@ def runner(self): ZSERVER_FIXTURE = ZServer() # Functional testing layer that uses the ZSERVER_FIXTURE -ZSERVER = FunctionalTesting(bases=(ZSERVER_FIXTURE,), name="ZServer:Functional") +ZSERVER = FunctionalTesting( + bases=( + ZSERVER_FIXTURE, + ), + name="ZServer:Functional") + class FTPServer(ZServer): """FTP variant of the ZServer layer. @@ -1031,7 +1077,11 @@ def setUpServer(self): zopeLog = logger.file_logger(log) - self.ftpServer = FTPServer('Zope2', ip=self.host, port=self.port, logger_object=zopeLog) + self.ftpServer = FTPServer( + 'Zope2', + ip=self.host, + port=self.port, + logger_object=zopeLog) def tearDownServer(self): """Close the FTPServer socket @@ -1043,4 +1093,8 @@ def tearDownServer(self): FTP_SERVER_FIXTURE = FTPServer() # Functional testing layer that uses the FTP_SERVER_FIXTURE -FTP_SERVER = FunctionalTesting(bases=(FTP_SERVER_FIXTURE,), name="FTPServer:Functional") +FTP_SERVER = FunctionalTesting( + bases=( + FTP_SERVER_FIXTURE, + ), + name="FTPServer:Functional") diff --git a/src/plone/testing/zca.py b/src/plone/testing/zca.py index 9ef7731..fb4f598 100644 --- a/src/plone/testing/zca.py +++ b/src/plone/testing/zca.py @@ -1,11 +1,12 @@ +# -*- coding: utf-8 -*- """Core Zope Component Architecture helpers and layers """ +from plone.testing import Layer +from zope.configuration.config import ConfigurationMachine import logging -logger = logging.getLogger('plone.testing.zca') -from zope.configuration.config import ConfigurationMachine -from plone.testing import Layer +logger = logging.getLogger('plone.testing.zca') # Contains a stack of installed global registries (but not the default one) _REGISTRIES = [] @@ -48,8 +49,8 @@ def _hookRegistry(reg): else: localsitemanager.base = reg -# Helper functions +# Helper functions def pushGlobalRegistry(new=None): """Set a new global component registry that uses the current registry as @@ -83,11 +84,13 @@ def pushGlobalRegistry(new=None): if new is None: name = 'test-stack-%d' % len(_REGISTRIES) new = globalregistry.BaseGlobalComponents(name=name, bases=(current,)) - logger.debug("New component registry: %s based on %s", name, current.__name__) + logger.debug( + "New component registry: %s based on %s", + name, + current.__name__) else: logger.debug("Push component registry: %s", new.__name__) - _REGISTRIES.append(new) # Monkey patch this into the three (!) places where zope.component @@ -119,7 +122,7 @@ def popGlobalRegistry(): if not _REGISTRIES or not _REGISTRIES[-1] is globalregistry.base: msg = ("popGlobalRegistry() called out of sync with " - "pushGlobalRegistry()") + "pushGlobalRegistry()") raise ValueError(msg) current = _REGISTRIES.pop() @@ -159,7 +162,7 @@ def __init__(self, name): def __str__(self): return ('' - % self.__name__) + % self.__name__) def __repr__(self): return self.__str__() @@ -217,13 +220,13 @@ def stackConfigurationContext(context=None, name="not named"): if Interface in info: factory = info[Interface][u''] newRegistry.register([interface], Interface, '', - factory) + factory) logger.debug('Configuration context %s cloned from %s', clone, context) return clone -# Layers +# Layers class UnitTesting(Layer): """Zope Component Architecture unit testing sandbox: The ZCA is cleared @@ -308,7 +311,7 @@ class ZCMLSandbox(Layer): defaultBases = (LAYER_CLEANUP,) def __init__(self, bases=None, name=None, module=None, filename=None, - package=None): + package=None): super(ZCMLSandbox, self).__init__(bases, name, module) self.filename = filename self.package = package @@ -327,7 +330,7 @@ def setUpZCMLFiles(self): raise ValueError("ZCML file name has not been provided.") if self.package is None: raise ValueError("The package that contains the ZCML file " - "has not been provided.") + "has not been provided.") self.loadZCMLFile(self.filename, self.package) def loadZCMLFile(self, filename, package): diff --git a/src/plone/testing/zodb.py b/src/plone/testing/zodb.py index fd98cf3..6c041ce 100644 --- a/src/plone/testing/zodb.py +++ b/src/plone/testing/zodb.py @@ -1,8 +1,9 @@ +# -*- coding: utf-8 -*- """ZODB-specific helpers and layers """ - from plone.testing import Layer + def stackDemoStorage(db=None, name=None): """Create a new DemoStorage that has the given database as a base. ``db`` may be none, in which case a base demo storage will be created. @@ -11,7 +12,7 @@ def stackDemoStorage(db=None, name=None): The usual pattern in a layer is:: def setUp(self): - self['zodbDB'] = stackDemoStorage(self.get('zodbDB'), name='mylayer') + self['zodbDB'] = stackDemoStorage(self.get('zodbDB'), name='mylayer') # noqa def tearDown(self): self['zodbDB'].close() @@ -28,6 +29,7 @@ def tearDown(self): return DB(storage) + class EmptyZODB(Layer): """Set up a new ZODB database using ``DemoStorage``. The database object is available as the resource ``zodbDB``. @@ -55,7 +57,7 @@ def tearDown(self): def testSetUp(self): self['zodbConnection'] = connection = self['zodbDB'].open() - self['zodbRoot'] = connection.root() + self['zodbRoot'] = connection.root() import transaction transaction.begin()