Commit 3f9d9434 authored by Hanno Schlichting's avatar Hanno Schlichting

flake8

parent b5d92f77
......@@ -15,6 +15,7 @@
from logging import getLogger
import os
import sys
from AccessControl.Permission import registerPermissions
from AccessControl.PermissionRole import PermissionRole
......@@ -32,6 +33,9 @@ if not hasattr(Products, 'meta_classes'):
Products.meta_classes = {}
Products.meta_class_info = {}
if sys.version_info >= (3, ):
basestring = str
_marker = [] # Create a new marker object
LOG = getLogger('ProductContext')
......
......@@ -17,8 +17,13 @@ This module provides a wrapper that causes a database connection to be created
and used when bobo publishes a bobo_application object.
"""
import sys
import transaction
if sys.version_info >= (3, ):
basestring = str
connection_open_hooks = []
......
......@@ -21,7 +21,6 @@ from AccessControl.SecurityInfo import ClassSecurityInfo
from Acquisition import Implicit
from App.special_dtml import DTMLFile
from App.special_dtml import HTML
from DateTime.DateTime import DateTime
from AccessControl import getSecurityManager
from AccessControl.Permissions import view_management_screens
from AccessControl.Permissions import change_proxy_roles
......
......@@ -289,13 +289,15 @@ class Item(Base,
if nobody.allowed(
self.manage_FTPget,
getRoles(self, 'manage_FTPget', self.manage_FTPget, ())):
getRoles(self, 'manage_FTPget',
self.manage_FTPget, ())):
mode = mode | 0o0004
# check write permissions
if hasattr(aq_base(self), 'PUT'):
try:
if getSecurityManager().validate(None, self, 'PUT', self.PUT):
if getSecurityManager().validate(None, self,
'PUT', self.PUT):
mode = mode | 0o0220
except Unauthorized:
pass
......@@ -338,7 +340,8 @@ class Item(Base,
ob = self
while 1:
if is_acquired(ob):
raise ValueError('FTP List not supported on acquired objects')
raise ValueError(
'FTP List not supported on acquired objects')
if not hasattr(ob, '__parent__'):
break
ob = aq_parent(ob)
......@@ -410,8 +413,8 @@ class Item_w__name__(Item):
def getPhysicalPath(self):
# 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
# 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.
......
......@@ -15,11 +15,15 @@
encoding.
"""
import sys
from warnings import warn
from ZPublisher.HTTPRequest import isCGI_NAMEs
from zope.i18n.interfaces import IUserPreferredCharsets
if sys.version_info >= (3, ):
unicode = str
def _decode(text, charsets):
"""Try to decode the text using one of the available charsets.
......
......@@ -25,7 +25,8 @@ def test_absoluteurl():
>>> from Zope2.App import zcml
>>> zcml.load_config("configure.zcml", Products.Five)
>>> from Products.Five.tests.testing import manage_addFiveTraversableFolder
>>> from Products.Five.tests.testing import (
... manage_addFiveTraversableFolder)
>>> manage_addFiveTraversableFolder(self.folder, 'testoid', 'Testoid')
A simple traversal will yield us the @@absolute_url view:
......
......@@ -83,7 +83,8 @@ def test_processInputs():
Mixed dicts work:
>>> request.form['foo'] = {'foo': u'f\xf6\xf6'.encode('iso-8859-1'), 'bar': 2}
>>> request.form['foo'] = {
... 'foo': u'f\xf6\xf6'.encode('iso-8859-1'), 'bar': 2}
>>> with warnings.catch_warnings():
... warnings.simplefilter('ignore')
... processInputs(request, charsets)
......@@ -92,11 +93,14 @@ def test_processInputs():
Deep recursion works:
>>> request.form['foo'] = [{'foo': u'f\xf6\xf6'.encode('iso-8859-1'), 'bar': 2}, {'foo': u"one", 'bar': 3}]
>>> request.form['foo'] = [
... {'foo': u'f\xf6\xf6'.encode('iso-8859-1'), 'bar': 2},
... {'foo': u"one", 'bar': 3}]
>>> with warnings.catch_warnings():
... warnings.simplefilter('ignore')
... processInputs(request, charsets)
>>> request.form['foo'] == [{'foo': u'f\xf6\xf6', 'bar': 2}, {'foo': u"one", 'bar': 3}]
>>> request.form['foo'] == [
... {'foo': u'f\xf6\xf6', 'bar': 2}, {'foo': u"one", 'bar': 3}]
True
"""
......
......@@ -29,9 +29,11 @@ def test_default_view():
Now let's add a couple of stub objects:
>>> from Products.Five.tests.testing.simplecontent import manage_addSimpleContent
>>> from Products.Five.tests.testing.simplecontent import manage_addCallableSimpleContent
>>> from Products.Five.tests.testing.simplecontent import manage_addIndexSimpleContent
>>> from Products.Five.tests.testing.simplecontent import (
... manage_addSimpleContent,
... manage_addCallableSimpleContent,
... manage_addIndexSimpleContent,
... )
>>> manage_addSimpleContent(self.folder, 'testoid', 'Testoid')
>>> manage_addCallableSimpleContent(self.folder, 'testcall', 'TestCall')
......@@ -60,7 +62,7 @@ def test_default_view():
In Five 1.5 ``index_html`` you can no longer set default views to anything
else than views:
>>> print http(r'''
... GET /test_folder_1_/testindex HTTP/1.1
... ''')
......
......@@ -46,7 +46,8 @@ def test_zpt_i18n():
In order to be able to traverse to the PageTemplate view, we need
a traversable object:
>>> from Products.Five.tests.testing import manage_addFiveTraversableFolder
>>> from Products.Five.tests.testing import (
... manage_addFiveTraversableFolder)
>>> manage_addFiveTraversableFolder(self.folder, 'testoid', 'Testoid')
We tell Zope to translate the messages by passing the
......
......@@ -43,7 +43,8 @@ def test_recursion():
>>> from zope.component import provideAdapter
>>> from zope.publisher.interfaces.browser import IBrowserRequest
>>> from zope.publisher.interfaces import IDefaultViewName
>>> provideAdapter(u'view', (IRecurse, IBrowserRequest), IDefaultViewName)
>>> provideAdapter(
... u'view', (IRecurse, IBrowserRequest), IDefaultViewName)
Here comes the actual test:
......
......@@ -41,9 +41,11 @@ def test_resource_restricted_code():
>>> import Products.Five.browser.tests
>>> from Zope2.App import zcml
>>> zcml.load_config("configure.zcml", Products.Five)
>>> zcml.load_config('resource.zcml', package=Products.Five.browser.tests)
>>> zcml.load_config('resource.zcml',
... package=Products.Five.browser.tests)
>>> from Products.Five.tests.testing import manage_addFiveTraversableFolder
>>> from Products.Five.tests.testing import (
... manage_addFiveTraversableFolder)
>>> manage_addFiveTraversableFolder(self.folder, 'testoid', 'Testoid')
>>> import os, glob
......@@ -54,8 +56,10 @@ def test_resource_restricted_code():
... glob.glob('%s/[a-z]*.py' % _prefix) +
... glob.glob('%s/*.css' % _prefix))]
>>> from Products.Five.browser.tests.test_scriptsecurity import checkRestricted
>>> from Products.Five.browser.tests.test_scriptsecurity import checkUnauthorized
>>> from Products.Five.browser.tests.test_scriptsecurity import (
... checkRestricted,
... checkUnauthorized,
... )
>>> resource_names = ['cockatiel.html', 'style.css', 'pattern.png']
......@@ -64,12 +68,14 @@ def test_resource_restricted_code():
>>> for resource in resource_names:
... checkUnauthorized(
... self.folder,
... 'context.restrictedTraverse("testoid/++resource++%s")()' % resource)
... 'context.restrictedTraverse("testoid/++resource++%s")()' %
... resource)
>>> base = 'testoid/++resource++fivetest_resources/%s'
>>> for resource in dir_resource_names:
... path = base % resource
... checkUnauthorized(self.folder, 'context.restrictedTraverse("%s")' % path)
... checkUnauthorized(
... self.folder, 'context.restrictedTraverse("%s")' % path)
Now let's create a manager user account and log in:
......@@ -82,20 +88,25 @@ def test_resource_restricted_code():
>>> for resource in resource_names:
... checkRestricted(
... self.folder,
... 'context.restrictedTraverse("testoid/++resource++%s")()' % resource)
... 'context.restrictedTraverse("testoid/++resource++%s")()' %
... resource)
>>> base = 'testoid/++resource++fivetest_resources/%s'
>>> for resource in dir_resource_names:
... path = base % resource
... checkRestricted(self.folder, 'context.restrictedTraverse("%s")' % path)
... checkRestricted(
... self.folder, 'context.restrictedTraverse("%s")' %path)
Let's make sure restrictedTraverse() works directly, too. It used to get
tripped up on subdirectories due to missing security declarations.
>>> self.folder.restrictedTraverse('++resource++fivetest_resources/resource.txt') is not None
>>> self.folder.restrictedTraverse(
... '++resource++fivetest_resources/resource.txt') is not None
True
>>> self.folder.restrictedTraverse('++resource++fivetest_resources/resource_subdir/resource.txt') is not None
>>> self.folder.restrictedTraverse(
... '++resource++fivetest_resources/resource_subdir/resource.txt'
... ) is not None
True
Clean up
......@@ -116,7 +127,8 @@ def test_view_restricted_code():
Let's add a test object that we view most of the pages off of:
>>> from Products.Five.tests.testing.simplecontent import manage_addSimpleContent
>>> from Products.Five.tests.testing.simplecontent import (
... manage_addSimpleContent)
>>> manage_addSimpleContent(self.folder, 'testoid', 'Testoid')
We also need to create a stub user account and login; otherwise we
......@@ -137,8 +149,10 @@ def test_view_restricted_code():
... 'nodoc-method', 'nodoc-function', 'nodoc-object',
... 'dirpage1', 'dirpage2']
>>> from Products.Five.browser.tests.test_scriptsecurity import checkRestricted
>>> from Products.Five.browser.tests.test_scriptsecurity import checkUnauthorized
>>> from Products.Five.browser.tests.test_scriptsecurity import (
... checkRestricted,
... checkUnauthorized,
... )
As long as we're not authenticated, we should get Unauthorized for
protected views, but we should be able to view the public ones:
......@@ -169,8 +183,9 @@ def test_view_restricted_code():
Even when logged in though the private methods should not be accessible:
>>> checkUnauthorized( self.folder,
... 'context.restrictedTraverse("testoid/eagle.method").mouse()')
>>> checkUnauthorized(
... self.folder,
... 'context.restrictedTraverse("testoid/eagle.method").mouse()')
Cleanup:
......
......@@ -33,7 +33,8 @@ def test_traversable():
the wrong reason: None doesn't have a docstring so BaseRequest
raises NotFoundError.)
>>> from Products.Five.tests.testing.simplecontent import manage_addSimpleContent
>>> from Products.Five.tests.testing.simplecontent import (
... manage_addSimpleContent)
>>> manage_addSimpleContent(self.folder, 'testoid', 'Testoid')
>>> print http(r'''
... GET /test_folder_1_/testoid/doesntexist HTTP/1.1
......@@ -79,7 +80,8 @@ def test_traversable():
... </configure>'''
>>> zcml.load_string(configure_zcml)
>>> from Products.Five.tests.testing.fancycontent import manage_addFancyContent
>>> from Products.Five.tests.testing.fancycontent import (
... manage_addFancyContent)
>>> info = manage_addFancyContent(self.folder, 'fancy', '')
In the following test we let the original __bobo_traverse__ method
......@@ -135,8 +137,10 @@ def test_traversable():
__bobo_traverse__ method itself does it (i.e. the __bobo_traverse__ is the
only element used for traversal lookup). Let's demonstrate:
>>> from Products.Five.tests.testing.fancycontent import manage_addNonTraversableFancyContent
>>> info = manage_addNonTraversableFancyContent(self.folder, 'fancy_zope2', '')
>>> from Products.Five.tests.testing.fancycontent import (
... manage_addNonTraversableFancyContent)
>>> info = manage_addNonTraversableFancyContent(
... self.folder, 'fancy_zope2', '')
>>> self.folder.fancy_zope2.an_attribute = 'This is an attribute'
>>> print http(r'''
... GET /test_folder_1_/fancy_zope2/an_attribute HTTP/1.1
......@@ -217,12 +221,14 @@ def test_view_doesnt_shadow_attribute():
Then we create a traversable folder...
>>> from Products.Five.tests.testing.folder import manage_addFiveTraversableFolder
>>> from Products.Five.tests.testing.folder import (
... manage_addFiveTraversableFolder)
>>> manage_addFiveTraversableFolder(self.folder, 'ftf')
and add an object called ``eagle`` to it:
>>> from Products.Five.tests.testing.simplecontent import manage_addIndexSimpleContent
>>> from Products.Five.tests.testing.simplecontent import (
... manage_addIndexSimpleContent)
>>> manage_addIndexSimpleContent(self.folder.ftf, 'eagle', 'Eagle')
When we publish the ``ftf/eagle`` now, we expect the attribute to
......
......@@ -30,7 +30,8 @@ def test_check_permission():
In order to be able to traverse to the PageTemplate view, we need
a traversable object:
>>> from Products.Five.tests.testing import manage_addFiveTraversableFolder
>>> from Products.Five.tests.testing import (
... manage_addFiveTraversableFolder)
>>> manage_addFiveTraversableFolder(self.folder, 'testoid', 'Testoid')
Now we access a page that uses
......@@ -39,10 +40,14 @@ def test_check_permission():
>>> from Testing.testbrowser import Browser
>>> browser = Browser()
>>> browser.open('http://localhost/test_folder_1_/testoid/@@zope3security.html?permission=zope2.View')
>>> browser.open(
... 'http://localhost/test_folder_1_/testoid/'
... '@@zope3security.html?permission=zope2.View')
>>> print browser.contents
Yes, you have the 'zope2.View' permission.
>>> browser.open('http://localhost/test_folder_1_/testoid/@@zope3security.html?permission=zope2.DeleteObjects')
>>> browser.open(
... 'http://localhost/test_folder_1_/testoid/'
... '@@zope3security.html?permission=zope2.DeleteObjects')
>>> print browser.contents
No, you don't have the 'zope2.DeleteObjects' permission.
......@@ -55,8 +60,8 @@ def test_check_permission():
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()
......@@ -125,8 +130,8 @@ def test_allowed_interface():
>>> getRoles(view, 'wot', view.wot, ('Def',)) is ACCESS_PRIVATE
True
But 'superMethod' is defined on IDummy by inheritance from ISuperDummy, and
so should have the 'Manager' role setup.
But 'superMethod' is defined on IDummy by inheritance from ISuperDummy,
and so should have the 'Manager' role setup.
>>> getRoles(view, 'superMethod', view.superMethod, ('Def',))
('Manager',)
......
......@@ -22,7 +22,8 @@ def test_standard_macros():
>>> _ignored = uf._doAddUser('manager', 'r00t', ['Manager'], [])
>>> self.login('manager')
>>> from Products.Five.tests.testing import manage_addFiveTraversableFolder
>>> from Products.Five.tests.testing import (
... manage_addFiveTraversableFolder)
>>> manage_addFiveTraversableFolder(self.folder, 'testoid', 'Testoid')
>>> import Products.Five.skin.tests
......
......@@ -58,8 +58,10 @@ def test_size():
>>> configure_zcml = '''
... <configure xmlns="http://namespaces.zope.org/zope"
... xmlns:five="http://namespaces.zope.org/five">
... <five:sizable class="Products.Five.tests.testing.simplecontent.SimpleContent" />
... <five:sizable class="Products.Five.tests.testing.fancycontent.FancyContent" />
... <five:sizable
... class="Products.Five.tests.testing.simplecontent.SimpleContent" />
... <five:sizable
... class="Products.Five.tests.testing.fancycontent.FancyContent" />
... <adapter
... for="Products.Five.tests.testing.simplecontent.ISimpleContent"
... provides="zope.size.interfaces.ISized"
......@@ -77,8 +79,10 @@ def test_size():
>>> zcml.load_config('meta.zcml', Products.Five)
>>> zcml.load_string(configure_zcml)
>>> from Products.Five.tests.testing.simplecontent import manage_addSimpleContent
>>> from Products.Five.tests.testing.fancycontent import manage_addFancyContent
>>> from Products.Five.tests.testing.simplecontent import (
... manage_addSimpleContent)
>>> from Products.Five.tests.testing.fancycontent import (
... manage_addFancyContent)
We have registered an ``ISized`` adapter for SimpleContent:
......
......@@ -27,7 +27,6 @@ from Acquisition import Acquired
from Acquisition import Explicit
from Acquisition import aq_get
from App.Common import package_home
from DateTime.DateTime import DateTime
from OFS.Cache import Cacheable
from OFS.SimpleItem import SimpleItem
from OFS.PropertyManager import PropertyManager
......
......@@ -35,10 +35,11 @@ from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
from Acquisition import aq_base
portal_name = 'portal'
from ZopeTestCase import user_name
from ZopeTestCase import user_password
portal_name = 'portal'
class PortalTestCase(base.TestCase):
'''Base test case for testing CMF-style portals'''
......@@ -96,7 +97,7 @@ class PortalTestCase(base.TestCase):
'''Refreshes the skin cache.'''
if hasattr(aq_base(self.portal), 'clearCurrentSkin'):
self.portal.clearCurrentSkin()
else: # CMF 1.4
else: # CMF 1.4
self.portal._v_skindata = None
try:
self.portal.setupCurrentSkin(self.app.REQUEST)
......@@ -122,7 +123,7 @@ class PortalTestCase(base.TestCase):
pm = self.portal.portal_membership
if hasattr(aq_base(pm), 'createMemberArea'):
pm.createMemberArea(name)
else: # CMF 1.4
else: # CMF 1.4
pm.createMemberarea(name)
# Security interface
......@@ -149,4 +150,3 @@ class PortalTestCase(base.TestCase):
def logout(self):
'''Logs out.'''
noSecurityManager()
......@@ -23,8 +23,10 @@ Typically used as in
app = Zope2.app()
"""
import os, sys, time
import layer
import os
import sys
import time
from Testing.ZopeTestCase import layer
# Allow code to tell it is run by the test framework
os.environ['ZOPETESTCASE'] = '1'
......@@ -32,22 +34,22 @@ os.environ['ZOPETESTCASE'] = '1'
# Increase performance on MP hardware
sys.setcheckinterval(2500)
# Shut up if we are not in control of the import process
#_quiet = sys.modules.has_key('Zope2')
# Always shut up
_quiet = True
def _print(msg):
'''Writes 'msg' to stderr and flushes the stream.'''
sys.stderr.write(msg)
sys.stderr.flush()
def _write(msg):
'''Writes 'msg' to stderr if not _quiet.'''
if not _quiet:
_print(msg)
def _exec(cmd):
'''Prints the time it takes to execute 'cmd'.'''
if os.environ.get('X', None):
......@@ -58,16 +60,20 @@ def _exec(cmd):
_write('Loading Zope, please stand by ')
_start = time.time()
def _configure_logging():
# Initialize the logging module
import logging
root = logging.getLogger()
if not root.handlers:
class NullHandler(logging.Handler):
def emit(self, record): pass
def emit(self, record):
pass
root.addHandler(NullHandler())
logging.basicConfig()
def _configure_debug_mode():
# Switch off debug mode
import App.config
......@@ -75,6 +81,7 @@ def _configure_debug_mode():
config.debug_mode = 0
App.config.setConfiguration(config)
def _configure_client_cache():
# Make sure we use a temporary client cache
import App.config
......@@ -87,25 +94,26 @@ _configure_debug_mode()
_configure_client_cache()
_exec('import Zope2')
import Zope2
import Zope2.Startup.run
import Zope2 # NOQA
import Zope2.Startup.run # NOQA
_exec('import ZODB')
import ZODB
import ZODB # NOQA
_write('.')
_exec('import OFS.SimpleItem')
import OFS.SimpleItem
import OFS.SimpleItem # NOQA
_exec('import OFS.ObjectManager')
import OFS.ObjectManager
import OFS.ObjectManager # NOQA
_write('.')
_exec('import OFS.Application')
import OFS.Application
import App.ProductContext
import OFS.Application # NOQA
import App.ProductContext # NOQA
_write('.')
_patched = False
@layer.onsetup
def _apply_patches():
# Do not patch a running Zope
......@@ -113,16 +121,20 @@ def _apply_patches():
return
# Avoid expensive product import
def null_import_products(): pass
def null_import_products():
pass
OFS.Application.import_products = null_import_products
# Avoid expensive product installation
def null_initialize(app): pass
def null_initialize(app):
pass
OFS.Application.initialize = null_initialize
# Avoid loading any ZCML
from Zope2.App import startup as zopeapp_startup
def null_load_zcml(): pass
def null_load_zcml():
pass
zopeapp_startup.load_zcml = null_load_zcml
# Note that we applied the monkey patches
......@@ -133,6 +145,7 @@ _apply_patches()
_theApp = None
@layer.onsetup
def _startup():
global _theApp
......@@ -143,30 +156,33 @@ _startup()
# Allow test authors to install Zope products into the test environment. Note
# that installProduct() must be called at module level -- never from tests.
from OFS.Application import get_folder_permissions, get_products
from OFS.Application import install_product, install_package
from OFS.Folder import Folder
import Products
from OFS.Application import get_folder_permissions, get_products # NOQA
from OFS.Application import install_product, install_package # NOQA
from OFS.Folder import Folder # NOQA
import Products # NOQA
_installedProducts = {}
_installedPackages = {}
def hasProduct(name):
'''Checks if a product can be found along Products.__path__'''
return name in [n[1] for n in get_products()]
@layer.onsetup
def installProduct(name, quiet=0):
'''Installs a Zope product at layer setup time.'''
quiet = 1 # Ignore argument
quiet = 1 # Ignore argument
_installProduct(name, quiet)
def _installProduct(name, quiet=0):
'''Installs a Zope product.'''
from AccessControl.class_init import InitializeClass
start = time.time()
meta_types = []
if _patched and not _installedProducts.has_key(name):
if _patched and name not in _installedProducts:
for priority, product_name, index, product_dir in get_products():
if product_name == name:
if not quiet:
......@@ -176,27 +192,32 @@ def _installProduct(name, quiet=0):
_installedProducts[product_name] = 1
Products.meta_types = Products.meta_types + tuple(meta_types)
InitializeClass(Folder)
if not quiet: _print('done (%.3fs)\n' % (time.time() - start))
if not quiet:
_print('done (%.3fs)\n' % (time.time() - start))
break
else:
if name != 'SomeProduct': # Ignore the skeleton tests :-P
if not quiet: _print('Installing %s ... NOT FOUND\n' % name)
if not quiet:
_print('Installing %s ... NOT FOUND\n' % name)
def hasPackage(name):
'''Checks if a package has been registered with five:registerPackage.'''
from OFS.metaconfigure import has_package
return has_package(name)
def installPackage(name, quiet=0):
'''Installs a registered Python package.'''
quiet = 1 # Ignore argument
quiet = 1 # Ignore argument
_installPackage(name, quiet)
def _installPackage(name, quiet=0):
'''Installs a registered Python package.'''
from OFS.metaconfigure import get_packages_to_initialize
start = time.time()
if _patched and not _installedPackages.has_key(name):
if _patched and name not in _installedPackages:
for module, init_func in get_packages_to_initialize():
if module.__name__ == name:
if not quiet:
......@@ -207,7 +228,8 @@ def _installPackage(name, quiet=0):
_print('done (%.3fs)\n' % (time.time() - start))
break
else:
if not quiet: _print('Installing %s ... NOT FOUND\n' % name)
if not quiet:
_print('Installing %s ... NOT FOUND\n' % name)
installProduct('OFSP', 1)
......@@ -216,16 +238,22 @@ app = Zope2.app
debug = Zope2.debug
DB = Zope2.DB
configure = Zope2.Startup.run.configure_wsgi
def startup(): pass
def startup():
pass
Zope = Zope2
active = _patched
# ZODB sandbox factory
from ZODB.DemoStorage import DemoStorage
from ZODB.DemoStorage import DemoStorage # NOQA
def sandbox(base=None):
'''Returns a sandbox copy of the base ZODB.'''
if base is None: base = Zope2.DB
if base is None:
base = Zope2.DB
storage = DemoStorage(base=base._storage)
return ZODB.DB(storage)
......
......@@ -22,12 +22,6 @@ The default user is logged in and has the 'Access contents information'
and 'View' permissions given to his role.
"""
import base
import functional
import interfaces
import utils
import connections
from zope.interface import implements
from AccessControl import getSecurityManager
from AccessControl.SecurityManagement import newSecurityManager
......@@ -35,6 +29,14 @@ from AccessControl.SecurityManagement import noSecurityManager
from AccessControl.Permissions import access_contents_information
from AccessControl.Permissions import view
from Testing.ZopeTestCase import base
from Testing.ZopeTestCase.base import app # NOQA
from Testing.ZopeTestCase.base import close # NOQA
from Testing.ZopeTestCase import functional
from Testing.ZopeTestCase import interfaces
from Testing.ZopeTestCase import utils
from Testing.ZopeTestCase import connections
folder_name = 'test_folder_1_'
user_name = 'test_user_1_'
user_password = 'secret'
......@@ -119,8 +121,3 @@ class FunctionalTestCase(functional.Functional, ZopeTestCase):
You can mix-in Functional with every xTestCase
to turn it into a functional test case.
'''
from base import app
from base import close
......@@ -14,44 +14,43 @@
"""
import ZopeLite as Zope2
import utils
import layer
import utils # NOQA
import layer # NOQA
from ZopeLite import hasProduct
from ZopeLite import installProduct
from ZopeLite import hasPackage
from ZopeLite import installPackage
from ZopeLite import _print
from ZopeLite import hasProduct # NOQA
from ZopeLite import installProduct # NOQA
from ZopeLite import hasPackage # NOQA
from ZopeLite import installPackage # NOQA
from ZopeLite import _print # NOQA
from ZopeTestCase import folder_name
from ZopeTestCase import user_name
from ZopeTestCase import user_password
from ZopeTestCase import user_role
from ZopeTestCase import standard_permissions
from ZopeTestCase import ZopeTestCase
from ZopeTestCase import FunctionalTestCase
from ZopeTestCase import folder_name # NOQA
from ZopeTestCase import user_name # NOQA
from ZopeTestCase import user_password # NOQA
from ZopeTestCase import user_role # NOQA
from ZopeTestCase import standard_permissions # NOQA
from ZopeTestCase import ZopeTestCase # NOQA
from ZopeTestCase import FunctionalTestCase # NOQA
from PortalTestCase import portal_name
from PortalTestCase import PortalTestCase
from PortalTestCase import portal_name # NOQA
from PortalTestCase import PortalTestCase # NOQA
from sandbox import Sandboxed
from functional import Functional
from sandbox import Sandboxed # NOQA
from functional import Functional # NOQA
from base import TestCase
from base import app
from base import close
from base import TestCase # NOQA
from base import app # NOQA
from base import close # NOQA
from warnhook import WarningsHook
from unittest import main
from warnhook import WarningsHook # NOQA
from unittest import main # NOQA
from zopedoctest import ZopeDocTestSuite
from zopedoctest import ZopeDocFileSuite
from zopedoctest import FunctionalDocTestSuite
from zopedoctest import FunctionalDocFileSuite
from zopedoctest import ZopeDocTestSuite # NOQA
from zopedoctest import ZopeDocFileSuite # NOQA
from zopedoctest import FunctionalDocTestSuite # NOQA
from zopedoctest import FunctionalDocFileSuite # NOQA
import zopedoctest as doctest
import transaction
import placeless
import zopedoctest as doctest # NOQA
import transaction # NOQA
import placeless # NOQA
Zope = Zope2
......@@ -131,4 +131,3 @@ class TestCase(unittest.TestCase, object):
def logout(self):
'''Logs out.'''
noSecurityManager()
......@@ -13,7 +13,8 @@
"""ZODB connection registry
"""
class ConnectionRegistry:
class ConnectionRegistry(object):
'''ZODB connection registry
This registry can hold either ZODB.Connection objects or OFS.Application
......@@ -60,4 +61,3 @@ contains = registry.contains
count = registry.count
close = registry.close
closeAll = registry.closeAll
......@@ -95,10 +95,9 @@ class IPortalSecurity(IZopeSecurity):
class IFunctional(Interface):
def publish(path, basic=None, env=None, extra=None, request_method='GET', stdin=None):
def publish(path, basic=None, env=None, extra=None,
request_method='GET', stdin=None):
'''Publishes the object at 'path' returning an
extended response object. The path may contain
extended response object. The path may contain
a query string.
'''
......@@ -20,6 +20,9 @@ from zope.i18n.testing import PlacelessSetup as I18nPlacelessSetup
from zope.security.testing import addCheckerPublic
from AccessControl.security import newInteraction
# For convenience
from Zope2.App import zcml # NOQA
class PlacelessSetup(CAPlacelessSetup,
EventPlacelessSetup,
......@@ -39,8 +42,11 @@ class PlacelessSetup(CAPlacelessSetup,
ps = PlacelessSetup()
setUp = ps.setUp
def tearDown():
global ps
tearDown_ = ps.tearDown
def tearDown(doctesttest=None):
tearDown_()
return tearDown
......@@ -49,9 +55,6 @@ tearDown = tearDown()
del ps
# For convenience
from Zope2.App import zcml
def callZCML(zcml_callback):
if callable(zcml_callback):
......@@ -61,7 +64,8 @@ def callZCML(zcml_callback):
func()
def temporaryPlacelessSetUp(orig_func, placeless_available=True, required_zcml=[]):
def temporaryPlacelessSetUp(orig_func, placeless_available=True,
required_zcml=[]):
'''A wrapper for test functions that require CA to be available and/or
some ZCML to be run during test fixture creation.
'''
......@@ -81,9 +85,9 @@ def temporaryPlacelessSetUp(orig_func, placeless_available=True, required_zcml=[
# Call any necessary callbacks for setting up ZCML
callZCML(required_zcml)
if kw.has_key('required_zcml'):
zcml = kw.pop('required_zcml')
callZCML(zcml)
if 'required_zcml' in kw:
req_zcml = kw.pop('required_zcml')
callZCML(req_zcml)
value = orig_func(*args, **kw)
......@@ -92,4 +96,3 @@ def temporaryPlacelessSetUp(orig_func, placeless_available=True, required_zcml=[
return value
return wrapper
......@@ -15,6 +15,7 @@
import transaction
from App.ZApplication import ZApplicationWrapper
from Testing.makerequest import makerequest
from Testing.ZopeTestCase import connections
from Testing.ZopeTestCase import ZopeLite as Zope2
......@@ -69,9 +70,7 @@ def __bobo_traverse__(self, REQUEST=None, name=None):
return self.__old_bobo_traverse__(REQUEST, name)
from App.ZApplication import ZApplicationWrapper
if not hasattr(ZApplicationWrapper, '__old_bobo_traverse__'):
ZApplicationWrapper.__old_bobo_traverse__ = (
ZApplicationWrapper.__bobo_traverse__)
ZApplicationWrapper.__bobo_traverse__ = __bobo_traverse__
......@@ -19,6 +19,7 @@ See testPythonScript.py and testShoppingCart.py for
example test cases. See testSkeleton.py for a quick
way of getting started.
"""
import gc
import transaction
......@@ -113,9 +114,11 @@ class TestTestCase(HookTest):
uf = self.app.acl_users
uf.userFolderAddUser('user_1', '', [], [])
newSecurityManager(None, uf.getUserById('user_1').__of__(uf))
self.assertEqual(getSecurityManager().getUser().getUserName(), 'user_1')
self.assertEqual(
getSecurityManager().getUser().getUserName(), 'user_1')
self._clear()
self.assertEqual(getSecurityManager().getUser().getUserName(), 'Anonymous User')
self.assertEqual(
getSecurityManager().getUser().getUserName(), 'Anonymous User')
def testClearSurvivesDoubleCall(self):
self._called = []
......@@ -169,9 +172,11 @@ class TestTestCase(HookTest):
uf = self.app.acl_users
uf.userFolderAddUser('user_1', '', [], [])
newSecurityManager(None, uf.getUserById('user_1').__of__(uf))
self.assertEqual(getSecurityManager().getUser().getUserName(), 'user_1')
self.assertEqual(
getSecurityManager().getUser().getUserName(), 'user_1')
self.logout()
self.assertEqual(getSecurityManager().getUser().getUserName(), 'Anonymous User')
self.assertEqual(
getSecurityManager().getUser().getUserName(), 'Anonymous User')
def getObjectsInTransaction(self):
# Lets us spy into the transaction
......@@ -181,7 +186,7 @@ class TestTestCase(HookTest):
elif hasattr(t, '_resources'): # Zope >= 2.8
return t._resources
else:
raise Exception, 'Unknown version'
raise Exception('Unknown version')
class TestSetUpRaises(HookTest):
......@@ -230,10 +235,12 @@ class TestTearDownRaises(HookTest):
class TestConnectionRegistry(base.TestCase):
'''Test the registry with Connection-like objects'''
class Conn:
class Conn(object):
_closed = 0
def close(self):
self._closed = 1
def closed(self):
return self._closed
......@@ -309,11 +316,13 @@ class TestConnectionRegistry(base.TestCase):
class TestApplicationRegistry(TestConnectionRegistry):
'''Test the registry with Application-like objects'''
class App:
class Conn:
class App(object):
class Conn(object):
_closed = 0
def close(self):
self._closed = 1
def closed(self):
return self._closed
......@@ -363,8 +372,9 @@ class TestListConverter(base.TestCase):
self.assertRaises(ValueError, utils.makelist, 0)
def testObject(self):
class dummy: pass
self.assertRaises(ValueError, utils.makelist, dummy())
class Dummy(object):
pass
self.assertRaises(ValueError, utils.makelist, Dummy())
class TestRequestVariables(base.TestCase):
......@@ -385,7 +395,6 @@ class TestRequestVariables(base.TestCase):
self.assertNotEqual(request.get('ACTUAL_URL', ''), '')
import gc
_sentinel1 = []
_sentinel2 = []
_sentinel3 = []
......@@ -457,4 +466,3 @@ def test_suite():
suite.addTest(makeSuite(TestRequestGarbage2))
suite.addTest(makeSuite(TestRequestGarbage3))
return suite
......@@ -24,8 +24,6 @@ from Testing.ZopeTestCase import user_password
from AccessControl import getSecurityManager
from AccessControl.Permissions import view
from AccessControl.Permissions import manage_properties
from AccessControl.Permissions import add_documents_images_and_files
from DocumentTemplate.permissions import change_dtml_documents
from StringIO import StringIO
from urllib import urlencode
......
......@@ -13,8 +13,20 @@
"""Interface tests
"""
from Testing.ZopeTestCase import *
from Testing.ZopeTestCase.interfaces import *
from Testing.ZopeTestCase import (
Functional,
FunctionalTestCase,
PortalTestCase,
TestCase,
ZopeTestCase,
)
from Testing.ZopeTestCase.interfaces import (
IFunctional,
IPortalSecurity,
IPortalTestCase,
IZopeSecurity,
IZopeTestCase,
)
from zope.interface.verify import verifyClass
from zope.interface.verify import verifyObject
......@@ -92,4 +104,3 @@ def test_suite():
suite.addTest(makeSuite(TestFunctionalTestCase))
suite.addTest(makeSuite(TestPortalTestCase))
return suite
......@@ -38,6 +38,7 @@ class IAdaptable(Interface):
"""This method will be adapted
"""
class IAdapted(Interface):
"""The interface we adapt to.
"""
......@@ -46,6 +47,7 @@ class IAdapted(Interface):
"""A method to adapt.
"""
class Adaptable:
implements(IAdaptable)
......@@ -81,7 +83,7 @@ class TestPlacelessSetUp(ZopeTestCase.ZopeTestCase):
self.assertEqual(adapted.adaptedMethod(), 'Adapted: The method')
def func(self, *args):
adapted = IAdapted(Adaptable())
IAdapted(Adaptable())
return True
def testNoCA(self):
......@@ -101,7 +103,8 @@ class TestPlacelessSetUp(ZopeTestCase.ZopeTestCase):
self.assertEqual(f(), True)
def testPlacelessFlagDisablesDecoration(self):
f = temporaryPlacelessSetUp(self.func, placeless_available=False, required_zcml=setupZCML)
f = temporaryPlacelessSetUp(
self.func, placeless_available=False, required_zcml=setupZCML)
self.assertRaises(TypeError, f)
def testDecoratedFuncLoadsZCMLCallable(self):
......@@ -118,4 +121,3 @@ def test_suite():
suite = TestSuite()
suite.addTest(makeSuite(TestPlacelessSetUp))
return suite
......@@ -24,7 +24,9 @@ from Testing import ZopeTestCase
from Acquisition import aq_base
from AccessControl import getSecurityManager
from types import ListType
from OFS.SimpleItem import SimpleItem
from OFS.Folder import Folder
from OFS.userfolder import UserFolder
import transaction
......@@ -36,11 +38,6 @@ def hasattr_(ob, attr):
return hasattr(aq_base(ob), attr)
# A dummy portal
from OFS.SimpleItem import SimpleItem
from OFS.Folder import Folder
class DummyPortal(Folder):
def __init__(self, id):
self.id = id
......@@ -48,24 +45,32 @@ class DummyPortal(Folder):
self._setObject('portal_membership', DummyMembershipTool())
self.manage_addFolder('Members')
self._called = []
def clearCurrentSkin(self):
self._called.append('clearCurrentSkin')
def setupCurrentSkin(self):
self._called.append('setupCurrentSkin')
class DummyMembershipTool(SimpleItem):
id = 'portal_membership'
def __init__(self):
self._called = []
def createMemberarea(self, member_id):
self._called.append('createMemberarea')
portal = self.aq_inner.aq_parent
portal.Members.manage_addFolder(member_id)
def getHomeFolder(self, member_id):
portal = self.aq_inner.aq_parent
return getattr(portal.Members, member_id)
class NewMembershipTool(DummyMembershipTool):
def createMemberArea(self, member_id):
self._called.append('createMemberArea')
portal = self.aq_inner.aq_parent
......@@ -133,7 +138,7 @@ class TestPortalTestCase(ZopeTestCase.PortalTestCase):
acl_user = self.portal.acl_users.getUserById(user_name)
self.assertTrue(acl_user)
self.assertEqual(acl_user.getRoles(), ('Member', 'Authenticated'))
self.assertEqual(type(acl_user.roles), ListType)
self.assertTrue(isinstance(acl_user.roles, list))
def test_setupHomeFolder(self):
# User's home folder should be set up
......@@ -146,7 +151,8 @@ class TestPortalTestCase(ZopeTestCase.PortalTestCase):
self.assertTrue(hasattr_(self.portal.Members, user_name))
self.assertFalse(self.folder is None)
# Shut up deprecation warnings
try: owner_info = self.folder.getOwnerTuple()
try:
owner_info = self.folder.getOwnerTuple()
except AttributeError:
owner_info = self.folder.getOwner(info=1)
self.assertEqual(owner_info, ([portal_name, 'acl_users'], user_name))
......@@ -156,7 +162,8 @@ class TestPortalTestCase(ZopeTestCase.PortalTestCase):
self.app = self._app()
self.portal = self._portal()
self._refreshSkinData()
self.assertEqual(self.portal._called, ['clearCurrentSkin', 'setupCurrentSkin'])
self.assertEqual(
self.portal._called, ['clearCurrentSkin', 'setupCurrentSkin'])
def test_setRoles(self):
# Roles should be set for user
......@@ -298,7 +305,7 @@ class TestPortalTestCase(ZopeTestCase.PortalTestCase):
self._setupUser()
self._setupHomeFolder()
self._clear(1)
self.assertFalse(self.app.__dict__.has_key(portal_name))
self.assertFalse(portal_name in self.app.__dict__)
auth_name = getSecurityManager().getUser().getUserName()
self.assertEqual(auth_name, 'Anonymous User')
self.assertEqual(self._called, ['beforeClose', 'afterClear'])
......@@ -317,11 +324,9 @@ class TestPortalTestCase(ZopeTestCase.PortalTestCase):
acl_user = self.portal.acl_users.getUserById(user_name)
self.assertTrue(acl_user)
self.assertEqual(acl_user.getRoles(), ('Member', 'Authenticated'))
self.assertEqual(type(acl_user.roles), ListType)
self.assertTrue(isinstance(acl_user.roles, list))
auth_name = getSecurityManager().getUser().getId()
self.assertEqual(auth_name, user_name)
# XXX: Changed in 0.9.0
#self.assertEqual(self._called, ['afterClear', 'beforeSetUp', 'afterSetUp'])
self.assertEqual(self._called, ['beforeSetUp', 'afterSetUp'])
def test_tearDown(self):
......@@ -329,10 +334,11 @@ class TestPortalTestCase(ZopeTestCase.PortalTestCase):
self._setUp()
self._called = []
self._tearDown()
self.assertFalse(self.app.__dict__.has_key(portal_name))
self.assertFalse(portal_name in self.app.__dict__)
auth_name = getSecurityManager().getUser().getUserName()
self.assertEqual(auth_name, 'Anonymous User')
self.assertEqual(self._called, ['beforeTearDown', 'beforeClose', 'afterClear'])
self.assertEqual(
self._called, ['beforeTearDown', 'beforeClose', 'afterClear'])
def test_configureFlag(self):
# Nothing should be configured
......@@ -342,8 +348,6 @@ class TestPortalTestCase(ZopeTestCase.PortalTestCase):
self.assertFalse(hasattr_(self.portal.Members, user_name))
auth_name = getSecurityManager().getUser().getUserName()
self.assertEqual(auth_name, 'Anonymous User')
# XXX: Changed in 0.9.0
#self.assertEqual(self._called, ['afterClear', 'beforeSetUp', 'afterSetUp'])
self.assertEqual(self._called, ['beforeSetUp', 'afterSetUp'])
def test_createMemberarea(self):
......@@ -354,7 +358,8 @@ class TestPortalTestCase(ZopeTestCase.PortalTestCase):
self._setupUser()
self.login()
self.createMemberarea(user_name)
self.assertEqual(self.portal.portal_membership._called, ['createMemberarea'])
self.assertEqual(
self.portal.portal_membership._called, ['createMemberarea'])
self.assertTrue(hasattr_(self.portal.Members, user_name))
def test_createMemberarea_NewTool(self):
......@@ -367,7 +372,8 @@ class TestPortalTestCase(ZopeTestCase.PortalTestCase):
self.portal._setObject('portal_membership', NewMembershipTool())
self.login()
self.createMemberarea(user_name)
self.assertEqual(self.portal.portal_membership._called, ['createMemberArea'])
self.assertEqual(
self.portal.portal_membership._called, ['createMemberArea'])
self.assertTrue(hasattr_(self.portal.Members, user_name))
# Helpers
......@@ -404,8 +410,6 @@ class TestPortalTestCase(ZopeTestCase.PortalTestCase):
self.assertEqual(lhs, rhs)
from OFS.userfolder import UserFolder
class WrappingUserFolder(UserFolder):
'''User folder returning wrapped user objects'''
......@@ -448,14 +452,16 @@ class TestWrappingUserFolder(ZopeTestCase.PortalTestCase):
user = self.portal.acl_users.getUserById(user_name)
self.assertTrue(hasattr(user, 'aq_base'))
self.assertFalse(user is aq_base(user))
self.assertTrue(user.aq_parent.__class__.__name__, 'WrappingUserFolder')
self.assertTrue(
user.aq_parent.__class__.__name__, 'WrappingUserFolder')
def testLoggedInUserIsWrapped(self):
user = getSecurityManager().getUser()
self.assertEqual(user.getId(), user_name)
self.assertTrue(hasattr(user, 'aq_base'))
self.assertTrue(user.__class__.__name__, 'User')
self.assertTrue(user.aq_parent.__class__.__name__, 'WrappingUserFolder')
self.assertTrue(
user.aq_parent.__class__.__name__, 'WrappingUserFolder')
self.assertTrue(user.aq_parent.aq_parent.__class__.__name__, 'Folder')
......@@ -517,4 +523,3 @@ def test_suite():
suite.addTest(makeSuite(TestWrappingUserFolder))
suite.addTest(makeSuite(TestSetUpRaises))
return suite
......@@ -25,7 +25,7 @@ class TestSomeProduct(ZopeTestCase.ZopeTestCase):
def testSomething(self):
# Test something
self.assertEqual(1+1, 2)
self.assertEqual(1 + 1, 2)
def test_suite():
......@@ -33,4 +33,3 @@ def test_suite():
suite = TestSuite()
suite.addTest(makeSuite(TestSomeProduct))
return suite
......@@ -20,19 +20,19 @@ example test cases. See testSkeleton.py for a quick
way of getting started.
"""
from Testing import ZopeTestCase
import transaction
from AccessControl import getSecurityManager
from Acquisition import aq_base
from OFS.userfolder import UserFolder
from types import ListType
from Testing import ZopeTestCase
from Testing.ZopeTestCase import folder_name
from Testing.ZopeTestCase import user_name
from Testing.ZopeTestCase import user_role
from Testing.ZopeTestCase import standard_permissions
from Acquisition import aq_base
from AccessControl import getSecurityManager
from types import ListType
import transaction
def hasattr_(ob, attr):
return hasattr(aq_base(ob), attr)
......@@ -235,7 +235,7 @@ class TestZopeTestCase(ZopeTestCase.ZopeTestCase):
self._setupUser()
self.login()
self._clear(1)
self.assertFalse(self.app.__dict__.has_key(folder_name))
self.assertFalse(folder_name in self.app.__dict__)
auth_name = getSecurityManager().getUser().getUserName()
self.assertEqual(auth_name, 'Anonymous User')
self.assertEqual(self._called, ['beforeClose', 'afterClear'])
......@@ -256,8 +256,6 @@ class TestZopeTestCase(ZopeTestCase.ZopeTestCase):
self.assertEqual(type(acl_user.roles), ListType)
auth_name = getSecurityManager().getUser().getId()
self.assertEqual(auth_name, user_name)
# XXX: Changed in 0.9.0
#self.assertEqual(self._called, ['afterClear', 'beforeSetUp', 'afterSetUp'])
self.assertEqual(self._called, ['beforeSetUp', 'afterSetUp'])
def test_tearDown(self):
......@@ -265,10 +263,11 @@ class TestZopeTestCase(ZopeTestCase.ZopeTestCase):
self._setUp()
self._called = []
self._tearDown()
self.assertFalse(self.app.__dict__.has_key(folder_name))
self.assertFalse(folder_name in self.app.__dict__)
auth_name = getSecurityManager().getUser().getUserName()
self.assertEqual(auth_name, 'Anonymous User')
self.assertEqual(self._called, ['beforeTearDown', 'beforeClose', 'afterClear'])
self.assertEqual(
self._called, ['beforeTearDown', 'beforeClose', 'afterClear'])
def test_setupFlag(self):
# Nothing should be set up
......@@ -277,8 +276,6 @@ class TestZopeTestCase(ZopeTestCase.ZopeTestCase):
self.assertFalse(hasattr_(self.app, folder_name))
auth_name = getSecurityManager().getUser().getUserName()
self.assertEqual(auth_name, 'Anonymous User')
# XXX: Changed in 0.9.0
#self.assertEqual(self._called, ['afterClear', 'beforeSetUp', 'afterSetUp'])
self.assertEqual(self._called, ['beforeSetUp', 'afterSetUp'])
# Bug tests
......@@ -347,9 +344,6 @@ class TestZopeTestCase(ZopeTestCase.ZopeTestCase):
self.assertEqual(lhs, rhs)
from OFS.userfolder import UserFolder
from Acquisition import aq_inner, aq_parent, aq_chain
class WrappingUserFolder(UserFolder):
'''User folder returning wrapped user objects'''
......@@ -384,14 +378,16 @@ class TestWrappingUserFolder(ZopeTestCase.ZopeTestCase):
user = self.folder.acl_users.getUserById(user_name)
self.assertTrue(hasattr(user, 'aq_base'))
self.assertFalse(user is aq_base(user))
self.assertTrue(user.aq_parent.__class__.__name__, 'WrappingUserFolder')
self.assertTrue(
user.aq_parent.__class__.__name__, 'WrappingUserFolder')
def testLoggedInUserIsWrapped(self):
user = getSecurityManager().getUser()
self.assertEqual(user.getId(), user_name)
self.assertTrue(hasattr(user, 'aq_base'))
self.assertTrue(user.__class__.__name__, 'User')
self.assertTrue(user.aq_parent.__class__.__name__, 'WrappingUserFolder')
self.assertTrue(
user.aq_parent.__class__.__name__, 'WrappingUserFolder')
self.assertTrue(user.aq_parent.aq_parent.__class__.__name__, 'Folder')
......@@ -402,4 +398,3 @@ def test_suite():
suite.addTest(makeSuite(TestPlainUserFolder))
suite.addTest(makeSuite(TestWrappingUserFolder))
return suite
def initialize(context):
print 'testpackage.initialize called'
print('testpackage.initialize called')
......@@ -21,10 +21,8 @@ suite = unittest.TestSuite()
names = os.listdir(os.path.dirname(__file__))
tests = [x[:-3] for x in names
if x.startswith('test') and x.endswith('.py')
and x != 'tests.py'
# Don't run this module as part of the Zope2 suite
and x != 'testWebserver.py']
if x.startswith('test') and x.endswith('.py') and
x != 'tests.py']
for test in tests:
m = __import__('Testing.ZopeTestCase.%s' % test)
......@@ -32,5 +30,6 @@ for test in tests:
if hasattr(m, 'test_suite'):
suite.addTest(m.test_suite())
def test_suite():
return suite
......@@ -13,6 +13,7 @@
##############################################################################
import warnings
class WarningsHook:
"""Hook to capture warnings generated by Python.
......@@ -50,7 +51,8 @@ class WarningsHook:
warnings.showwarning = self.original
self.original = None
def showwarning(self, message, category, filename, lineno, file=None, line=None):
def showwarning(self, message, category, filename, lineno,
file=None, line=None):
self.warnings.append((str(message), category, filename, lineno))
def clear(self):
......
......@@ -13,5 +13,5 @@
"""ZopeTestCase doctest support
"""
from doctest import *
from functional import *
from doctest import * # NOQA
from Testing.ZopeTestCase.zopedoctest.functional import * # NOQA
......@@ -33,6 +33,9 @@ from Testing.ZopeTestCase.sandbox import AppZapper
from Testing.ZopeTestCase.functional import ResponseWrapper
from Testing.ZopeTestCase.functional import savestate
if sys.version_info >= (3, ):
basestring = str
class HTTPHeaderOutput:
......
......@@ -49,4 +49,3 @@ def test_suite():
return TestSuite((
makeSuite(AuthHeaderTestCase),
))
......@@ -85,14 +85,14 @@ class HTTPHeaderOutputTests(unittest.TestCase):
self.assertEqual(str(hho),
'HTTP/1.0 200 OK\n'
'Content-Length: 23\n'
'Content-Type: text/html'
)
'Content-Type: text/html')
SHOW_COOKIES_DTML = '''\
<dtml-in "REQUEST.cookies.keys()">
<dtml-var sequence-item>: <dtml-var "REQUEST.cookies[_['sequence-item']]">
</dtml-in>'''
def setUp(self):
'''This method will run after the test_class' setUp.
......@@ -112,13 +112,9 @@ def setUp(self):
from Testing.ZopeTestCase.testFunctional import SET_COOKIE_DTML
self.folder.addDTMLDocument('index_html', file='index')
self.folder.addDTMLMethod('change_title', file=CHANGE_TITLE_DTML)
self.folder.addDTMLMethod('set_cookie', file=SET_COOKIE_DTML)
self.folder.addDTMLMethod('show_cookies', file=SHOW_COOKIES_DTML)
self.globs['foo'] = 1
......@@ -128,4 +124,3 @@ def test_suite():
FunctionalDocTestSuite(setUp=setUp),
FunctionalDocFileSuite('FunctionalDocTest.txt', setUp=setUp),
))
......@@ -54,4 +54,3 @@ def test_suite():
ZopeDocTestSuite(test_class=TestCase),
ZopeDocFileSuite('layerextraction.txt', test_class=TestCase),
))
......@@ -21,4 +21,3 @@ def test_suite():
return TestSuite((
ZopeDocFileSuite('WarningsTest.txt'),
))
......@@ -36,4 +36,3 @@ def test_suite():
ZopeDocTestSuite(setUp=setUp),
ZopeDocFileSuite('ZopeDocTest.txt', setUp=setUp),
))
......@@ -21,8 +21,7 @@ suite = unittest.TestSuite()
names = os.listdir(os.path.dirname(__file__))
tests = [x[:-3] for x in names
if x.startswith('test') and x.endswith('.py')
and x != 'tests.py']
if x.startswith('test') and x.endswith('.py') and x != 'tests.py']
for test in tests:
m = __import__('Testing.ZopeTestCase.zopedoctest.%s' % test)
......@@ -30,5 +29,6 @@ for test in tests:
if hasattr(m, 'test_suite'):
suite.addTest(m.test_suite())
def test_suite():
return suite
......@@ -12,10 +12,14 @@
##############################################################################
import re
import sys
from DateTime import DateTime
from DateTime.interfaces import SyntaxError
from cgi import escape
if sys.version_info >= (3, ):
unicode = str
# This may get overwritten during configuration
default_encoding = 'utf-8'
......
......@@ -36,6 +36,9 @@ from ZPublisher import NotFound
from ZPublisher.BaseResponse import BaseResponse
from ZPublisher.pubevents import PubBeforeStreaming
if sys.version_info >= (3, ):
unicode = str
nl2sp = maketrans('\n', ' ')
# This may get overwritten during configuration
......
......@@ -38,6 +38,11 @@ MONTHNAME = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
WEEKDAYNAME = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
if sys.version_info >= (3, ):
from io import IOBase
else:
IOBase = file # NOQA
def _now():
if _NOW is not None:
......@@ -114,7 +119,7 @@ class WSGIResponse(HTTPResponse):
self.stdout.write(data)
def setBody(self, body, title='', is_error=0):
if isinstance(body, file):
if isinstance(body, IOBase):
body.seek(0, 2)
length = body.tell()
body.seek(0)
......@@ -287,7 +292,7 @@ def publish_module(environ, start_response,
body = response.body
if isinstance(body, file) or IUnboundStreamIterator.providedBy(body):
if isinstance(body, IOBase) or IUnboundStreamIterator.providedBy(body):
result = body
else:
# If somebody used response.write, that data will be in the
......
import sys
import unittest
from ZPublisher.tests.testBaseRequest import TestRequestViewsBase
from zope.testing.cleanup import cleanUp
from ZPublisher.tests.testBaseRequest import TestRequestViewsBase
if sys.version_info >= (3, ):
unicode = str
class RecordTests(unittest.TestCase):
......
......@@ -11,8 +11,12 @@
#
##############################################################################
import sys
import unittest
if sys.version_info >= (3, ):
unicode = str
class ConvertersTests(unittest.TestCase):
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment