Commit 740eb601 authored by Hanno Schlichting's avatar Hanno Schlichting

Port some code to Python 3 via 2to3 suggestions.

parent 7214980c
......@@ -13,11 +13,11 @@
import os
import sys
import urllib
from AccessControl.class_init import InitializeClass
from AccessControl.requestmethod import requestmethod
from Acquisition import Implicit
from six.moves.urllib import parse
from zExceptions import Redirect
from App.config import getConfiguration
......@@ -61,7 +61,7 @@ class DatabaseChooser(Tabs, Traversable, Implicit):
names = configuration.dbtab.listDatabaseNames()
names.sort()
if quote:
return [(name, urllib.quote(name)) for name in names]
return [(name, parse.quote(name)) for name in names]
return names
def __getitem__(self, name):
......
......@@ -20,6 +20,7 @@ from Acquisition import aq_base, aq_parent
# BBB
from os.path import realpath # NOQA
import collections
attrget = getattr
# These are needed because the various date formats below must
......@@ -71,7 +72,7 @@ def rfc1123_date(ts=None):
def absattr(attr, callable=callable):
# Return the absolute value of an attribute,
# calling the attr if it is callable.
if callable(attr):
if isinstance(attr, collections.Callable):
return attr()
return attr
......
......@@ -28,8 +28,8 @@ from zExceptions import NotFound
class FuncCode(object):
def __init__(self, f, im=0):
self.co_varnames = f.func_code.co_varnames[im:]
self.co_argcount = f.func_code.co_argcount - im
self.co_varnames = f.__code__.co_varnames[im:]
self.co_argcount = f.__code__.co_argcount - im
def __eq__(self, other):
if not isinstance(other, FuncCode):
......
......@@ -14,9 +14,7 @@
"""
from cgi import escape
import urllib
from zope.interface import implementer
from AccessControl import Unauthorized
from AccessControl import ClassSecurityInfo
from AccessControl.class_init import InitializeClass
......@@ -24,7 +22,9 @@ from AccessControl.Permissions import view_management_screens
from App.interfaces import INavigation
from App.special_dtml import DTMLFile
from ExtensionClass import Base
from six.moves.urllib.parse import quote, unquote
from zExceptions import Redirect
from zope.interface import implementer
class Tabs(Base):
......@@ -46,8 +46,8 @@ class Tabs(Base):
options = tuple(self.manage_options())
for d in options:
filter = d.get('filter', None)
if filter is not None and not filter(self):
filter_ = d.get('filter', None)
if filter_ is not None and not filter_(self):
continue
path = d.get('path', None)
......@@ -81,10 +81,7 @@ class Tabs(Base):
return getattr(self, m)(self, REQUEST)
def tabs_path_default(self, REQUEST,
# Static var
unquote=urllib.unquote,
):
def tabs_path_default(self, REQUEST):
steps = REQUEST._steps[:-1]
script = REQUEST['BASEPATH1']
linkpat = '<a href="%s/manage_workspace">%s</a>'
......@@ -102,10 +99,7 @@ class Tabs(Base):
(escape(script, 1), escape(unquote(last))))
return '%s%s' % (url, '/'.join(out))
def tabs_path_info(self, script, path,
# Static vars
quote=urllib.quote,
):
def tabs_path_info(self, script, path):
out = []
while path[:1] == '/':
path = path[1:]
......
......@@ -37,6 +37,10 @@ PREFIX = os.path.realpath(
)
class Code(object):
pass
class HTML(DocumentTemplate.HTML, Persistence.Persistent):
"Persistent HTML Document Templates"
......@@ -44,12 +48,11 @@ class HTML(DocumentTemplate.HTML, Persistence.Persistent):
class ClassicHTMLFile(DocumentTemplate.HTMLFile, MethodObject.Method):
"Persistent HTML Document Templates read from files"
class func_code:
pass
__code__ = func_code = Code()
__code__.co_varnames = 'trueself', 'self', 'REQUEST'
__code__.co_argcount = 3
__defaults__ = func_defaults = None
func_code = __code__ = func_code()
func_code.co_varnames = 'trueself', 'self', 'REQUEST'
func_code.co_argcount = 3
_need__name__ = 1
_v_last_read = 0
......@@ -101,8 +104,8 @@ defaultBindings = {'name_context': 'context',
class DTMLFile(Bindings, Explicit, ClassicHTMLFile):
"HTMLFile with bindings and support for __render_with_namespace__"
func_code = __code__ = None
func_defaults = __defaults__ = None
__code__ = func_code = None
__defaults__ = func_defaults = None
_need__name__ = 1
_Bindings_ns_class = TemplateDict
......@@ -202,7 +205,7 @@ class DTMLFile(Bindings, Explicit, ClassicHTMLFile):
except DTReturn as v:
result = v.v
except AttributeError:
if (type(sys.exc_value) == InstanceType and
if (type(sys.exc_info()[1]) == InstanceType and
sys.exc_value.args[0] == "_v_blocks"):
LOG.warn("DTML file '%s' could not be read" % self.raw)
raise ValueError(
......
import io
import os.path
from StringIO import StringIO
from io import BytesIO
import unittest
import App
......@@ -25,8 +25,8 @@ class TestImageFile(unittest.TestCase):
def test_warn_on_software_home_default(self):
App.ImageFile.ImageFile('App/www/zopelogo.png')
self.assertEquals(self.warningshook.warnings.pop()[0],
App.ImageFile.NON_PREFIX_WARNING)
self.assertEqual(self.warningshook.warnings.pop()[0],
App.ImageFile.NON_PREFIX_WARNING)
def test_no_warn_on_absolute_path(self):
path = os.path.join(os.path.dirname(App.__file__),
......@@ -55,8 +55,8 @@ class TestImageFileFunctional(unittest.TestCase):
'SERVER_PROTOCOL': 'HTTP/1.1',
'REQUEST_METHOD': 'GET',
}
stdin = StringIO()
stdout = StringIO()
stdin = BytesIO()
stdout = BytesIO()
response = WSGIResponse(stdout)
request = WSGIRequest(stdin, env, response)
path = os.path.join(os.path.dirname(App.__file__),
......
......@@ -19,7 +19,7 @@ class DummyDBTab(object):
self._databases = databases or {}
def listDatabaseNames(self):
return self._databases.keys()
return list(self._databases.keys())
def hasDatabase(self, name):
return name in self._databases
......
......@@ -37,10 +37,10 @@ from zExceptions import (
)
from zope.interface import implementer
import Folder
import misc_
from interfaces import IApplication
from misc_ import Misc_
from . import Folder
from . import misc_
from .interfaces import IApplication
from .misc_ import Misc_
if bbb.HAS_ZSERVER:
from webdav.NullResource import NullResource
......@@ -221,7 +221,7 @@ class AppInitializer:
app = self.getApp()
app._p_activate()
if 'Control_Panel' in app.__dict__.keys():
if 'Control_Panel' in list(app.__dict__.keys()):
del app.__dict__['Control_Panel']
app._objects = tuple(i for i in app._objects
if i['id'] != 'Control_Panel')
......@@ -344,7 +344,7 @@ def import_products():
continue
done[product_name] = product_dir
import_product(product_dir, product_name)
return done.keys()
return list(done.keys())
def import_product(product_dir, product_name, raise_exc=None):
......
......@@ -17,8 +17,6 @@ from json import dumps
from json import loads
import re
import tempfile
from urllib import quote
from urllib import unquote
import warnings
from zlib import compress
from zlib import decompressobj
......@@ -34,6 +32,7 @@ from Acquisition import aq_base
from Acquisition import aq_inner
from Acquisition import aq_parent
from ExtensionClass import Base
from six.moves.urllib.parse import quote, unquote
from zExceptions import Unauthorized, BadRequest, ResourceLockedError
from ZODB.POSException import ConflictError
from zope.interface import implementer
......@@ -49,6 +48,7 @@ from OFS.interfaces import ICopySource
from OFS.Moniker import loadMoniker
from OFS.Moniker import Moniker
from OFS.subscribers import compatibilityCall
import collections
class CopyError(Exception):
......@@ -549,7 +549,7 @@ def sanity_check(c, ob):
def absattr(attr):
if callable(attr):
if isinstance(attr, collections.Callable):
return attr()
return attr
......
......@@ -12,12 +12,12 @@
##############################################################################
"""DTML Document objects.
"""
from urllib import quote
from AccessControl import getSecurityManager
from AccessControl.class_init import InitializeClass
from DocumentTemplate.permissions import change_dtml_methods
from DocumentTemplate.permissions import change_dtml_documents
from six.moves.urllib.parse import quote
from zExceptions import Redirect
from zExceptions import ResourceLockedError
from zExceptions.TracebackSupplement import PathTracebackSupplement
......
......@@ -14,7 +14,6 @@
"""
import re
import sys
from urllib import quote
from AccessControl.class_init import InitializeClass
from AccessControl.SecurityInfo import ClassSecurityInfo
......@@ -26,6 +25,7 @@ from AccessControl.tainted import TaintedString
from Acquisition import Implicit
from DocumentTemplate.permissions import change_dtml_methods
from DocumentTemplate.security import RestrictedDTML
from six.moves.urllib.parse import quote
from zExceptions import Redirect
from zExceptions import ResourceLockedError
from zExceptions.TracebackSupplement import PathTracebackSupplement
......@@ -44,6 +44,11 @@ if sys.version_info >= (3, ):
_marker = [] # Create a new marker object.
class Code(object):
# Documents masquerade as functions:
pass
class DTMLMethod(RestrictedDTML,
HTML,
Implicit,
......@@ -58,13 +63,10 @@ class DTMLMethod(RestrictedDTML,
security = ClassSecurityInfo()
security.declareObjectProtected(View)
class func_code(object):
# Documents masquerade as functions:
pass
func_code = __code__ = func_code()
func_code.co_varnames = 'self', 'REQUEST', 'RESPONSE'
func_code.co_argcount = 3
__code__ = func_code = Code()
__code__.co_varnames = 'self', 'REQUEST', 'RESPONSE'
__code__.co_argcount = 3
__defaults__ = func_defaults = None
manage_options = ((
{'label': 'Edit', 'action': 'manage_main'},
......
......@@ -29,6 +29,7 @@ from ExtensionClass import Base
from zope.interface import implementer
from OFS.interfaces import IFindSupport
import collections
@implementer(IFindSupport)
......@@ -172,16 +173,16 @@ def role_match(ob, permission, roles, lt=type([]), tt=type(())):
if hasattr(ob, permission):
p = getattr(ob, permission)
if type(p) is lt:
map(fn, p)
list(map(fn, p))
if hasattr(ob, '__parent__'):
ob = aq_parent(ob)
continue
break
if type(p) is tt:
map(fn, p)
list(map(fn, p))
break
if p is None:
map(fn, ('Manager', 'Anonymous'))
list(map(fn, ('Manager', 'Anonymous')))
break
if hasattr(ob, '__parent__'):
......@@ -196,7 +197,7 @@ def role_match(ob, permission, roles, lt=type([]), tt=type(())):
def absattr(attr):
if callable(attr):
if isinstance(attr, collections.Callable):
return attr()
return attr
......
......@@ -14,7 +14,7 @@
"""
from cgi import escape
from cStringIO import StringIO
from io import BytesIO
from mimetools import choose_boundary
import struct
import sys
......@@ -500,7 +500,7 @@ class File(Persistent, Implicit, PropertyManager,
if size < n:
return (file, size)
# Big string: cut it into smaller chunks
file = StringIO(file)
file = BytesIO(file)
if isinstance(file, FileUpload) and not file:
raise ValueError('File not specified')
......@@ -534,7 +534,7 @@ class File(Persistent, Implicit, PropertyManager,
# to front to minimize the number of database updates
# and to allow us to get things out of memory as soon as
# possible.
next = None
_next = None
while end > 0:
pos = end - n
if pos < n:
......@@ -546,7 +546,7 @@ class File(Persistent, Implicit, PropertyManager,
# a single database update for it.
data = Pdata(read(end - pos))
self._p_jar.add(data)
data.next = next
data.next = _next
# Save the object so that we can release its memory.
transaction.savepoint(optimistic=True)
......@@ -555,10 +555,10 @@ class File(Persistent, Implicit, PropertyManager,
assert data._p_oid is not None
assert data._p_state == -1
next = data
_next = data
end = pos
return next, size
return (_next, size)
security.declareProtected(View, 'get_size')
def get_size(self):
......@@ -703,7 +703,7 @@ def getImageInfo(data):
# handle JPEGs
elif (size >= 2) and (data[:2] == '\377\330'):
content_type = 'image/jpeg'
jpeg = StringIO(data)
jpeg = BytesIO(data)
jpeg.read(2)
b = jpeg.read(1)
try:
......@@ -857,7 +857,7 @@ class Image(File):
if css_class is not None:
result = '%s class="%s"' % (result, css_class)
for key in args.keys():
for key in list(args.keys()):
value = args.get(key)
if value:
result = '%s %s="%s"' % (result, key, value)
......@@ -894,14 +894,14 @@ class Pdata(Persistent, Implicit):
return len(data)
def __str__(self):
next = self.next
if next is None:
_next = self.next
if _next is None:
return self.data
r = [self.data]
while next is not None:
self = next
while _next is not None:
self = _next
r.append(self.data)
next = self.next
_next = self.next
return ''.join(r)
......@@ -58,7 +58,7 @@ class LockableItem(EtagSupport):
return locks
elif killinvalids:
# Delete invalid locks
for token, lock in locks.items():
for token, lock in list(locks.items()):
if not lock.isValid():
del locks[token]
if (not locks) and hasattr(aq_base(self),
......@@ -69,18 +69,18 @@ class LockableItem(EtagSupport):
return locks
def wl_lockItems(self, killinvalids=0):
return self.wl_lockmapping(killinvalids).items()
return list(self.wl_lockmapping(killinvalids).items())
def wl_lockValues(self, killinvalids=0):
return self.wl_lockmapping(killinvalids).values()
return list(self.wl_lockmapping(killinvalids).values())
def wl_lockTokens(self, killinvalids=0):
return self.wl_lockmapping(killinvalids).keys()
return list(self.wl_lockmapping(killinvalids).keys())
def wl_hasLock(self, token, killinvalids=0):
if not token:
return 0
return token in self.wl_lockmapping(killinvalids).keys()
return token in list(self.wl_lockmapping(killinvalids).keys())
def wl_isLocked(self):
# returns true if 'self' is locked at all
......@@ -88,7 +88,7 @@ class LockableItem(EtagSupport):
# valid (timeout has been exceeded)
locks = self.wl_lockmapping(killinvalids=1)
if locks.keys():
if list(locks.keys()):
return 1
else:
return 0
......
......@@ -17,6 +17,7 @@
a real object that retains its correct version context
and aquisition relationships via a simple interface.
"""
import collections
class Moniker(object):
......@@ -51,6 +52,6 @@ def loadMoniker(data):
def absattr(attr):
if callable(attr):
if isinstance(attr, collections.Callable):
return attr()
return attr
......@@ -59,6 +59,7 @@ from OFS.event import ObjectWillBeAddedEvent
from OFS.event import ObjectWillBeRemovedEvent
from OFS.Lockable import LockableItem
from OFS.subscribers import compatibilityCall
import collections
if bbb.HAS_ZSERVER:
from webdav.Collection import Collection
......@@ -265,7 +266,7 @@ class ObjectManager(CopyContainer,
# adequate permission to add that type of object.
sm = getSecurityManager()
meta_types = []
if callable(self.all_meta_types):
if isinstance(self.all_meta_types, collections.Callable):
all = self.all_meta_types()
else:
all = self.all_meta_types
......@@ -451,7 +452,7 @@ class ObjectManager(CopyContainer,
security.declareProtected(access_contents_information, 'objectValues_d')
def objectValues_d(self, t=None):
return map(self._getOb, self.objectIds_d(t))
return list(map(self._getOb, self.objectIds_d(t)))
security.declareProtected(access_contents_information, 'objectItems_d')
def objectItems_d(self, t=None):
......@@ -722,6 +723,9 @@ class ObjectManager(CopyContainer,
def __nonzero__(self):
return True
def __bool__(self):
return True
security.declareProtected(access_contents_information, 'get')
def get(self, key, default=None):
if key in self:
......
......@@ -61,6 +61,7 @@ from OFS.CopySupport import CopySource
from OFS.Lockable import LockableItem
from OFS.role import RoleManager
from OFS.Traversable import Traversable
import collections
if bbb.HAS_ZSERVER:
from webdav.Resource import Resource
......@@ -134,7 +135,7 @@ class Item(Base,
"""Return the title if it is not blank and the id otherwise.
"""
title = self.title
if callable(title):
if isinstance(title, collections.Callable):
title = title()
if title:
return title
......@@ -146,7 +147,7 @@ class Item(Base,
If the title is not blank, then the id is included in parens.
"""
title = self.title
if callable(title):
if isinstance(title, collections.Callable):
title = title()
id = self.getId()
return title and ("%s (%s)" % (title, id)) or id
......@@ -231,7 +232,7 @@ class Item(Base,
if getattr(aq_base(s), 'isDocTemp', 0):
v = s(client, REQUEST, **kwargs)
elif callable(s):
elif isinstance(s, collections.Callable):
v = s(**kwargs)
else:
v = HTML.__call__(s, client, REQUEST, **kwargs)
......
......@@ -13,8 +13,6 @@
"""This module implements a mix-in for traversable objects.
"""
from urllib import quote
from AccessControl.class_init import InitializeClass
from AccessControl.SecurityInfo import ClassSecurityInfo
from AccessControl.SecurityManagement import getSecurityManager
......@@ -28,6 +26,7 @@ from Acquisition import aq_parent
from Acquisition.interfaces import IAcquirer
from OFS import bbb
from OFS.interfaces import ITraversable, IApplication
from six.moves.urllib.parse import quote
from zExceptions import NotFound
from ZPublisher.interfaces import UseTraversalDefault
from ZODB.POSException import ConflictError
......@@ -128,9 +127,9 @@ class Traversable:
if p is None:
return path
func = self.getPhysicalPath.im_func
func = self.getPhysicalPath.__func__
while p is not None:
if func is p.getPhysicalPath.im_func:
if func is p.getPhysicalPath.__func__:
try:
pid = p.id or p.getId()
except AttributeError:
......@@ -251,7 +250,7 @@ class Traversable:
next, 'im_self', None) is not None:
# Bound method, the bound instance
# is the container
container = next.im_self
container = next.__self__
elif getattr(
aq_base(obj),
name, _marker) is next:
......
......@@ -15,7 +15,6 @@ Objects for packages that have been uninstalled.
"""
from cgi import escape
from logging import getLogger
from thread import allocate_lock
from Acquisition import Acquired
from Acquisition import Explicit
......@@ -23,6 +22,7 @@ from App.special_dtml import DTMLFile
from OFS.SimpleItem import Item
from Persistence import Overridable
from six import exec_
from six.moves._thread import allocate_lock
from ZODB.broken import Broken as ZODB_Broken
from ZODB.broken import persistentBroken
......
......@@ -12,10 +12,9 @@
#
##############################################################################
import urllib
from Acquisition import aq_parent
from OFS.interfaces import ITraversable
from six.moves.urllib.parse import quote, unquote
from zope.component import getMultiAdapter
from zope.interface import implementer
from zope.traversing.browser.interfaces import IAbsoluteURL
......@@ -34,7 +33,7 @@ class AbsoluteURL(BrowserView):
"""
def __unicode__(self):
return urllib.unquote(self.__str__()).decode('utf-8')
return unquote(self.__str__()).decode('utf-8')
def __str__(self):
context = self.context
......@@ -50,7 +49,7 @@ class AbsoluteURL(BrowserView):
raise TypeError(_insufficientContext)
if name:
url += '/' + urllib.quote(name.encode('utf-8'), _safe)
url += '/' + quote(name.encode('utf-8'), _safe)
return url
......@@ -80,8 +79,7 @@ class AbsoluteURL(BrowserView):
if name:
base += ({'name': name,
'url': ("%s/%s" % (base[-1]['url'],
urllib.quote(name.encode('utf-8'),
_safe)))
quote(name.encode('utf-8'), _safe)))
}, )
return base
......@@ -93,7 +91,7 @@ class OFSTraversableAbsoluteURL(BrowserView):
"""
def __unicode__(self):
return urllib.unquote(self.__str__()).decode('utf-8')
return unquote(self.__str__()).decode('utf-8')
def __str__(self):
return self.context.absolute_url()
......
......@@ -13,8 +13,6 @@
"""Support for owned objects
"""
import urlparse
from AccessControl.class_init import InitializeClass
from AccessControl.owner import Owned as BaseOwned
from AccessControl.owner import ownableFilter
......@@ -27,6 +25,7 @@ from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.unauthorized import Unauthorized
from Acquisition import aq_get
from Acquisition import aq_parent
from six.moves.urllib import parse
from zExceptions import Redirect
from App.special_dtml import DTMLFile
......@@ -55,7 +54,7 @@ class Owned(BaseOwned):
security = getSecurityManager()
want_referer = REQUEST['URL1'] + '/manage_owner'
got_referer = ("%s://%s%s" %
urlparse.urlparse(REQUEST['HTTP_REFERER'])[:3])
parse.urlparse(REQUEST['HTTP_REFERER'])[:3])
__traceback_info__ = want_referer, got_referer
if (want_referer != got_referer or security.calledByExecutable()):
raise Unauthorized(
......
......@@ -12,7 +12,7 @@
#
##############################################################################
import cStringIO
import io
import os
import tempfile
import unittest
......@@ -77,7 +77,7 @@ class TestInitialization(unittest.TestCase):
# of the directory is checked. This handles this in a
# platform-independent way.
schema = self.schema
sio = cStringIO.StringIO(text.replace("<<INSTANCE_HOME>>", TEMPNAME))
sio = io.BytesIO(text.replace("<<INSTANCE_HOME>>", TEMPNAME))
conf, handler = ZConfig.loadConfigFile(schema, sio)
self.assertEqual(conf.instancehome, TEMPNAME)
setConfiguration(conf)
......
import unittest
import cStringIO
import io
import transaction
from AccessControl import SecurityManager
......@@ -63,7 +63,7 @@ class CopySupportTestBase(unittest.TestCase):
a = Application()
r['Application'] = a
self.root = a
responseOut = self.responseOut = cStringIO.StringIO()
responseOut = self.responseOut = io.BytesIO()
self.app = makerequest(self.root, stdout=responseOut)
manage_addFolder(self.app, 'folder1')
manage_addFolder(self.app, 'folder2')
......
......@@ -5,7 +5,7 @@ import Zope2
import os
import sys
import time
from cStringIO import StringIO
from io import BytesIO
from Acquisition import aq_base
......@@ -95,7 +95,7 @@ class FileTests(unittest.TestCase):
a = Application()
r['Application'] = a
self.root = a
responseOut = self.responseOut = StringIO()
responseOut = self.responseOut = BytesIO()
self.app = makerequest(self.root, stdout=responseOut)
factory = getattr(self.app, self.factory)
factory('file',
......@@ -110,11 +110,11 @@ class FileTests(unittest.TestCase):
self.file = getattr(self.app, 'file')
# Since we do the create here, let's test the events here too
self.assertEquals(1, len(self.eventCatcher.created))
self.assertEqual(1, len(self.eventCatcher.created))
self.assertTrue(
aq_base(self.eventCatcher.created[0].object) is aq_base(self.file))
self.assertEquals(1, len(self.eventCatcher.modified))
self.assertEqual(1, len(self.eventCatcher.modified))
self.assertTrue(
aq_base(self.eventCatcher.created[0].object) is aq_base(self.file))
......@@ -140,7 +140,7 @@ class FileTests(unittest.TestCase):
def testReadData(self):
s = "a" * (2 << 16)
f = StringIO(s)
f = BytesIO(s)
data, size = self.file._read_data(f)
self.assertTrue(isinstance(data, Pdata))
self.assertEqual(str(data), s)
......@@ -151,7 +151,7 @@ class FileTests(unittest.TestCase):
# Test that a big enough string is split into several Pdata
# From a file
s = "a" * (1 << 16) * 3
data, size = self.file._read_data(StringIO(s))
data, size = self.file._read_data(BytesIO(s))
self.assertNotEqual(data.next, None)
# From a string
data, size = self.file._read_data(s)
......@@ -161,22 +161,22 @@ class FileTests(unittest.TestCase):
self.file.manage_edit('foobar', 'text/plain', filedata='ASD')
self.assertEqual(self.file.title, 'foobar')
self.assertEqual(self.file.content_type, 'text/plain')
self.assertEquals(1, len(self.eventCatcher.modified))
self.assertEqual(1, len(self.eventCatcher.modified))
self.assertTrue(self.eventCatcher.modified[0].object is self.file)
def testManageEditWithoutFileData(self):
self.file.manage_edit('foobar', 'text/plain')
self.assertEqual(self.file.title, 'foobar')
self.assertEqual(self.file.content_type, 'text/plain')
self.assertEquals(1, len(self.eventCatcher.modified))
self.assertEqual(1, len(self.eventCatcher.modified))
self.assertTrue(self.eventCatcher.modified[0].object is self.file)
def testManageUpload(self):
f = StringIO('jammyjohnson')
f = BytesIO('jammyjohnson')
self.file.manage_upload(f)
self.assertEqual(self.file.data, 'jammyjohnson')
self.assertEqual(self.file.content_type, 'application/octet-stream')
self.assertEquals(1, len(self.eventCatcher.modified))
self.assertEqual(1, len(self.eventCatcher.modified))
self.assertTrue(self.eventCatcher.modified[0].object is self.file)
def testIfModSince(self):
......@@ -188,7 +188,7 @@ class FileTests(unittest.TestCase):
# not modified since
t_notmod = rfc1123_date(now)
e['HTTP_IF_MODIFIED_SINCE'] = t_notmod
out = StringIO()
out = BytesIO()
resp = HTTPResponse(stdout=out)
req = HTTPRequest(sys.stdin, e, resp)
data = self.file.index_html(req, resp)
......@@ -198,7 +198,7 @@ class FileTests(unittest.TestCase):
# modified since
t_mod = rfc1123_date(now - 100)
e['HTTP_IF_MODIFIED_SINCE'] = t_mod
out = StringIO()
out = BytesIO()
resp = HTTPResponse(stdout=out)
req = HTTPRequest(sys.stdin, e, resp)
data = self.file.index_html(req, resp)
......@@ -208,12 +208,12 @@ class FileTests(unittest.TestCase):
def testIndexHtmlWithPdata(self):
self.file.manage_upload('a' * (2 << 16)) # 128K
self.file.index_html(self.app.REQUEST, self.app.REQUEST.RESPONSE)
self.assert_(self.app.REQUEST.RESPONSE._wrote)
self.assertTrue(self.app.REQUEST.RESPONSE._wrote)
def testIndexHtmlWithString(self):
self.file.manage_upload('a' * 100) # 100 bytes
self.file.index_html(self.app.REQUEST, self.app.REQUEST.RESPONSE)
self.assert_(not self.app.REQUEST.RESPONSE._wrote)
self.assertTrue(not self.app.REQUEST.RESPONSE._wrote)
def testStr(self):
self.assertEqual(str(self.file), self.data)
......
......@@ -15,7 +15,7 @@ class DummyItem(FindSupport):
class DummyFolder(DummyItem, dict):
def objectItems(self):
return self.items()
return list(self.items())
class TestFindSupport(unittest.TestCase):
......
......@@ -335,7 +335,7 @@ class ObjectManagerTests(PlacelessSetup, unittest.TestCase):
self.assertFalse(om.hasObject('foo'))
si = SimpleItem('foo')
om._setObject('foo', si)
self.assert_(om.hasObject('foo'))
self.assertTrue(om.hasObject('foo'))
om._delObject('foo')
self.assertFalse(om.hasObject('foo'))
......@@ -472,19 +472,19 @@ class ObjectManagerTests(PlacelessSetup, unittest.TestCase):
om = self._makeOne()
si1 = SimpleItem('1')
om['1'] = si1
self.assertTrue(('1', si1) in om.items())
self.assertTrue(('1', si1) in list(om.items()))
def test_keys(self):
om = self._makeOne()
si1 = SimpleItem('1')
om['1'] = si1
self.assertTrue('1' in om.keys())
self.assertTrue('1' in list(om.keys()))
def test_values(self):
om = self._makeOne()
si1 = SimpleItem('1')
om['1'] = si1
self.assertTrue(si1 in om.values())
self.assertTrue(si1 in list(om.values()))
def test_list_imports(self):
om = self._makeOne()
......
......@@ -26,15 +26,15 @@ def createBigFile():
# Create a file that is several 1<<16 blocks of data big, to force the
# use of chained Pdata objects.
# Make sure we create a file that isn't of x * 1<<16 length! Coll #671
import cStringIO
import io
import random
import string
size = (1 << 16) * 5 + 12345
file = cStringIO.StringIO()
file = io.BytesIO()
def addLetter(x, add=file.write, l=string.letters, c=random.choice):
add(c(l))
filter(addLetter, range(size))
filter(addLetter, list(range(size)))
return file
......@@ -45,14 +45,14 @@ BIGFILE = createBigFile()
class TestRequestRange(unittest.TestCase):
# Test case setup and teardown
def setUp(self):
import cStringIO
import io
import string
import transaction
from OFS.Application import Application
from OFS.Folder import manage_addFolder
from OFS.Image import manage_addFile
from Testing.makerequest import makerequest
self.responseOut = cStringIO.StringIO()
self.responseOut = io.BytesIO()
self.connection = makeConnection()
try:
r = self.connection.root()
......@@ -166,7 +166,7 @@ class TestRequestRange(unittest.TestCase):
self.assertEqual(body, self.data[start:end])
def expectMultipleRanges(self, range, sets, draft=0):
import cStringIO
import io
import re
import email
rangeParse = re.compile('bytes\s*(\d+)-(\d+)/(\d+)')
......@@ -191,7 +191,7 @@ class TestRequestRange(unittest.TestCase):
self.assertFalse(rsp.getHeader('content-length') != str(len(body)))
# Decode the multipart message
bodyfile = cStringIO.StringIO('Content-Type: %s\n\n%s' % (
bodyfile = io.BytesIO('Content-Type: %s\n\n%s' % (
rsp.getHeader('content-type'), body))
partmessages = [part
for part in email.message_from_file(bodyfile).walk()]
......
......@@ -115,4 +115,4 @@ class TestSimpleItem(unittest.TestCase):
item.raise_standardErrorMessage(client=item,
REQUEST=REQUEST())
self.assertEquals(sem.kw.get('error_type'), 'BadRequest')
self.assertEqual(sem.kw.get('error_type'), 'BadRequest')
......@@ -53,7 +53,7 @@ class ProtectedMethodSecurityPolicy:
# Bound method
if name is None:
raise Unauthorized
klass = value.im_self.__class__
klass = value.__self__.__class__
roles = getattr(klass, name + '__roles__', object())
if roles is None: # ACCESS_PUBLIC
return 1
......@@ -64,7 +64,7 @@ class ProtectedMethodSecurityPolicy:
class TestTraverse(unittest.TestCase):
def setUp(self):
import cStringIO
import io
import transaction
from AccessControl import SecurityManager
from AccessControl.SecurityManagement import newSecurityManager
......@@ -83,7 +83,7 @@ class TestTraverse(unittest.TestCase):
a = Application()
r['Application'] = a
self.root = a
responseOut = self.responseOut = cStringIO.StringIO()
responseOut = self.responseOut = io.BytesIO()
self.app = makerequest(self.root, stdout=responseOut)
manage_addFolder(self.app, 'folder1')
folder1 = getattr(self.app, 'folder1')
......@@ -251,7 +251,7 @@ class TestTraverse(unittest.TestCase):
my.id = 'my'
self._setupSecurity(ProtectedMethodSecurityPolicy())
r = my.restrictedTraverse('getId')
self.assertEquals(r(), 'my')
self.assertEqual(r(), 'my')
self.assertRaises(Unauthorized, my.restrictedTraverse, 'private')
self.assertRaises(Unauthorized, my.restrictedTraverse, 'ohno')
......
......@@ -18,11 +18,11 @@ class DTMLMethodTests(unittest.TestCase):
def test_edit_taintedstring(self):
from AccessControl.tainted import TaintedString
doc = self._makeOne()
self.assertEquals(doc.read(), '')
self.assertEqual(doc.read(), '')
data = TaintedString('hello<br/>')
doc.manage_edit(data, 'title')
self.assertEquals(doc.read(), 'hello&lt;br/&gt;')
self.assertEqual(doc.read(), 'hello&lt;br/&gt;')
class FactoryTests(unittest.TestCase):
......
......@@ -13,7 +13,7 @@
##############################################################################
import StringIO
import io
import logging
import unittest
......@@ -31,7 +31,7 @@ class TestMaybeWarnDeprecated(unittest.TestCase):
# deprecatedManageAddDeleteClasses list is special cased
self.deprecatedManageAddDeleteClasses.append(int)
# Pick up log messages
self.logfile = StringIO.StringIO()
self.logfile = io.BytesIO()
self.log_handler = logging.StreamHandler(self.logfile)
logging.root.addHandler(self.log_handler)
self.old_log_level = logging.root.level
......@@ -46,7 +46,7 @@ class TestMaybeWarnDeprecated(unittest.TestCase):
def assertLog(self, class_, expected):
from OFS.subscribers import maybeWarnDeprecated
maybeWarnDeprecated(class_(), 'manage_afterAdd')
self.assertEquals(expected, self.logfile.getvalue())
self.assertEqual(expected, self.logfile.getvalue())
def test_method_deprecated(self):
class Deprecated(object):
......
......@@ -51,7 +51,7 @@ def processInputValue(value, charsets):
elif isinstance(value, tuple):
return tuple([processInputValue(v, charsets) for v in value])
elif isinstance(value, dict):
for k, v in value.items():
for k, v in list(value.items()):
value[k] = processInputValue(v, charsets)
return value
elif isinstance(value, str):
......@@ -77,7 +77,7 @@ def processInputs(request, charsets=None):
else:
charsets = envadapter.getPreferredCharsets() or ['utf-8']
for name, value in request.form.items():
for name, value in list(request.form.items()):
if not (name in isCGI_NAMEs or name.startswith('HTTP_')):
request.form[name] = processInputValue(value, charsets)
......
......@@ -62,7 +62,7 @@ def _configure_z2security(_context, new_class, required):
callable=protectClass,
args=(new_class, required.pop(''))
)
for attr, permission in required.iteritems():
for attr, permission in required.items():
_context.action(
discriminator=('five:protectName', new_class, attr),
callable=protectName,
......@@ -146,10 +146,10 @@ def page(_context, name, permission, for_=Interface,
if not func.__doc__:
# cannot test for MethodType/UnboundMethod here
# because of ExtensionClass
if hasattr(func, 'im_func'):
if hasattr(func, '__func__'):
# you can only set a docstring on functions, not
# on method objects
func = func.im_func
func = func.__func__
func.__doc__ = "Stub docstring to make ZPublisher work"
if hasattr(class_, '__implements__'):
......@@ -395,7 +395,7 @@ def resourceDirectory(_context, name, directory, layer=IDefaultBrowserLayer,
f_resource = type(class_name, (factory.resource,), {})
f_cache[factory] = type(factory_name, (factory,),
{'resource': f_resource})
for ext, factory in resource_factories.items():
for ext, factory in list(resource_factories.items()):
resource_factories[ext] = f_cache[factory]
default_factory = resource_factories['default']
del resource_factories['default']
......@@ -410,8 +410,7 @@ def resourceDirectory(_context, name, directory, layer=IDefaultBrowserLayer,
factory = DirectoryResourceFactory(name, directory,
resource_factory=dir_factory)
new_classes = [dir_factory,
] + [f.resource for f in f_cache.values()]
new_classes = [dir_factory] + [f.resource for f in f_cache.values()]
_context.action(
discriminator=('resource', name, IBrowserRequest, layer),
......
......@@ -110,25 +110,25 @@ class ViewMapper(object):
class BoundPageTemplate(object):
def __init__(self, pt, ob):
object.__setattr__(self, 'im_func', pt)
object.__setattr__(self, 'im_self', ob)
object.__setattr__(self, '__func__', pt)
object.__setattr__(self, '__self__', ob)
macros = property(lambda self: self.im_func.macros)
filename = property(lambda self: self.im_func.filename)
__parent__ = property(lambda self: self.im_self)
macros = property(lambda self: self.__func__.macros)
filename = property(lambda self: self.__func__.filename)
__parent__ = property(lambda self: self.__self__)
def __call__(self, *args, **kw):
if self.im_self is None:
if self.__self__ is None:
im_self, args = args[0], args[1:]
else:
im_self = self.im_self
return self.im_func(im_self, *args, **kw)
im_self = self.__self__
return self.__func__(im_self, *args, **kw)
def __setattr__(self, name, v):
raise AttributeError("Can't set attribute", name)
def __repr__(self):
return "<BoundPageTemplateFile of %r>" % self.im_self
return "<BoundPageTemplateFile of %r>" % self.__self__
# BBB
......
......@@ -15,8 +15,8 @@
"""
import os
import urllib
from six.moves.urllib.parse import unquote
import zope.browserresource.directory
import zope.browserresource.file
from zope.browserresource.file import File
......@@ -48,7 +48,7 @@ class Resource(object):
name = self.__name__
container = self.__parent__
url = urllib.unquote(absoluteURL(container, self.request))
url = unquote(absoluteURL(container, self.request))
if not isinstance(container, DirectoryResource):
name = '++resource++%s' % name
return "%s/%s" % (url, name)
......
......@@ -32,4 +32,4 @@ class ViewOne(BrowserView):
'Yet another class'
def my_method(self, arg1, arg2, kw1=None, kw2='D'):
print("CALLED %s %s %s %s" % (arg1, arg2, kw1, kw2))
print('CALLED %s %s %s %s' % (arg1, arg2, kw1, kw2))
......@@ -156,9 +156,9 @@ def test_default_method_args_marshalling():
method's signature. They both should yield the four parameters.
>>> def args(method):
... f = method.im_func
... c = f.func_code
... defaults = f.func_defaults
... f = method.__func__
... c = f.__code__
... defaults = f.__defaults__
... names = c.co_varnames[1:c.co_argcount]
... return names
>>> args(view.my_method)
......
......@@ -160,8 +160,8 @@ class ViewPageTemplateFileTests(unittest.TestCase):
foo = Foo(context, request)
bound = foo.bar
self.assertTrue(isinstance(bound, BoundPageTemplate))
self.assertTrue(bound.im_func is template)
self.assertTrue(bound.im_self is foo)
self.assertTrue(bound.__func__ is template)
self.assertTrue(bound.__self__ is foo)
class ViewMapperTests(unittest.TestCase):
......@@ -221,8 +221,8 @@ class BoundPageTemplateTests(unittest.TestCase):
pt = DummyTemplate({'foo': 'bar'})
ob = DummyContext()
bpt = self._makeOne(pt, ob)
self.assertTrue(bpt.im_func is pt)
self.assertTrue(bpt.im_self is ob)
self.assertTrue(bpt.__func__ is pt)
self.assertTrue(bpt.__self__ is ob)
self.assertTrue(bpt.__parent__ is ob)
self.assertEqual(bpt.macros['foo'], 'bar')
self.assertEqual(bpt.filename, 'dummy.pt')
......
......@@ -14,6 +14,8 @@
"""Test the basic ZCML directives
"""
from __future__ import absolute_import
def test_directives():
"""
......
......@@ -13,6 +13,7 @@
##############################################################################
"""Size adapters for testing
"""
from __future__ import absolute_import
from zope.interface import implementer
from zope.size.interfaces import ISized
......
......@@ -24,7 +24,7 @@ from zope.interface.interfaces import IInterface
from zope.component.interface import getInterface, interfaceToName
from zope.component.interface import searchInterface
from interfaces import IMarkerInterfaces
from .interfaces import IMarkerInterfaces
def interfaceStringCheck(f):
......
......@@ -29,7 +29,7 @@ class SimpleAttributeViewlet(zope.viewlet.viewlet.SimpleAttributeViewlet):
class simple(zope.viewlet.viewlet.simple):
# We need to ensure that the proper __init__ is called.
__init__ = ViewletBase.__init__.im_func
__init__ = ViewletBase.__init__.__func__
def SimpleViewletClass(template, bases=(), attributes=None, name=u''):
......
......@@ -46,6 +46,7 @@ from zExceptions import Unauthorized
from zope.contentprovider.tales import TALESProviderExpression
from Products.PageTemplates import ZRPythonExpr
from Products.PageTemplates.interfaces import IUnicodeEncodingConflictResolver
import collections
if sys.version_info >= (3, ):
basestring = str
......@@ -117,7 +118,7 @@ def render(ob, ns):
# item might be proxied (e.g. modules might have a deprecation
# proxy)
base = removeAllProxies(base)
if callable(base):
if isinstance(base, collections.Callable):
try:
if getattr(base, 'isDocTemp', 0):
ob = ZRPythonExpr.call_with_ns(ob, ns, 2)
......@@ -347,6 +348,11 @@ class ZopeIterator(Iterator):
return getattr(ob1, name, no) == getattr(ob2, name, no) is not no
# 'first' needs to have access to the last item in the loop
def __next__(self):
if self._nextIndex > 0:
self._last_item = self.item
return next(super(ZopeIterator, self))
def next(self):
if self._nextIndex > 0:
self._last_item = self.item
......
......@@ -55,8 +55,8 @@ class PageTemplateFile(SimpleItem, Script, PageTemplate, Traversable):
meta_type = 'Page Template (File)'
func_defaults = __defaults__ = None
func_code = __code__ = FuncCode((), 0)
__code__ = func_code = FuncCode((), 0)
__defaults__ = func_defaults = None
_v_last_read = 0
# needed by AccessControl.class_init.InitializeClass
......
......@@ -47,7 +47,7 @@ class PythonExpr(PythonExpr):
raise engine.getCompilerError()(
'Python expression error:\n%s' % '\n'.join(err))
self._varnames = use.keys()
self._varnames = list(use.keys())
self._code = code
def __call__(self, econtext):
......
......@@ -79,8 +79,8 @@ class ZopePageTemplate(Script, PageTemplate, Cacheable,
meta_type = 'Page Template'
output_encoding = 'utf-8' # provide default for old instances
func_defaults = __defaults__ = None
func_code = __code__ = FuncCode((), 0)
__code__ = func_code = FuncCode((), 0)
__defaults__ = func_defaults = None
_default_bindings = {'name_subpath': 'traverse_subpath'}
_default_content_fn = os.path.join(package_home(globals()),
......
......@@ -27,5 +27,5 @@ import ZTUtils # NOQA
def initialize(context):
# Import lazily, and defer initialization to the module
import ZopePageTemplate
from . import ZopePageTemplate
ZopePageTemplate.initialize(context)
......@@ -26,6 +26,7 @@ from chameleon.codegen import template
from sourcecodegen import generate_code
from z3c.pt import expressions
import collections
_marker = object()
......@@ -81,7 +82,8 @@ class BoboAwareZopeTraverse(object):
if call is False:
return base
if getattr(base, '__call__', _marker) is not _marker or callable(base):
if (getattr(base, '__call__', _marker) is not _marker or
isinstance(base, collections.Callable)):
base = render(base, econtext)
return base
......
......@@ -14,7 +14,7 @@
######################################################################
# Sequence batching support
import util
from . import util
__allow_access_to_unprotected_subobjects__ = {'batch': 1}
__roles__ = None
......
......@@ -90,14 +90,14 @@ class EngineTestsBase(PlacelessSetup):
def test_evaluate_with_render_simple_callable(self):
ec = self._makeContext()
self.assertEquals(ec.evaluate('dummy'), 'dummy')
self.assertEqual(ec.evaluate('dummy'), 'dummy')
def test_evaluate_with_render_DTML_template(self):
# http://www.zope.org/Collectors/Zope/2232
# DTML templates could not be called from a Page Template
# due to an ImportError
ec = self._makeContext()
self.assertEquals(ec.evaluate('dummy2'), 'dummy')
self.assertEqual(ec.evaluate('dummy2'), 'dummy')
def test_evaluate_alternative_first_missing(self):
ec = self._makeContext()
......@@ -152,19 +152,19 @@ class EngineTestsBase(PlacelessSetup):
def test_empty_path_expression_explicit(self):
ec = self._makeContext()
self.assertEquals(ec.evaluate('path:'), None)
self.assertEqual(ec.evaluate('path:'), None)
def test_empty_path_expression_explicit_with_trailing_whitespace(self):
ec = self._makeContext()
self.assertEquals(ec.evaluate('path: '), None)
self.assertEqual(ec.evaluate('path: '), None)
def test_empty_path_expression_implicit(self):
ec = self._makeContext()
self.assertEquals(ec.evaluate(''), None)
self.assertEqual(ec.evaluate(''), None)
def test_empty_path_expression_implicit_with_trailing_whitespace(self):
ec = self._makeContext()
self.assertEquals(ec.evaluate(' \n'), None)
self.assertEqual(ec.evaluate(' \n'), None)
def test_unicode(self):
# All our string expressions are unicode now
......
......@@ -195,12 +195,12 @@ class ZPTUnicodeEncodingConflictResolution(ZopeTestCase):
def test_bug_198274(self):
# See https://bugs.launchpad.net/bugs/198274
# ZPT w/ '_text' not assigned can't be unpickled.
import cPickle
import pickle
empty = ZopePageTemplate(id='empty', text=' ',
content_type='text/html',
output_encoding='ascii')
state = cPickle.dumps(empty, protocol=1)
cPickle.loads(state)
state = pickle.dumps(empty, protocol=1)
pickle.loads(state)
def testBug246983(self):
# See https://bugs.launchpad.net/bugs/246983
......@@ -213,14 +213,14 @@ class ZPTUnicodeEncodingConflictResolution(ZopeTestCase):
""".strip()
manage_addPageTemplate(self.app, 'test', text=textDirect)
zpt = self.app['test']
self.assertEquals(zpt.pt_render(), u'')
self.assertEqual(zpt.pt_render(), u'')
# Indirect inclusion of encoded strings through String Expressions
# should be resolved as well.
textIndirect = """
<tal:block content="string:x ${request/data}" />
""".strip()
zpt.pt_edit(textIndirect, zpt.content_type)
self.assertEquals(zpt.pt_render(), u'x ')
self.assertEqual(zpt.pt_render(), u'x ')
def testDebugFlags(self):
# Test for bug 229549
......
......@@ -150,7 +150,7 @@ class TestPersistent(ZopeTestCase):
extra_context['capture'] = capture
template.pt_render(extra_context=extra_context)
del extra_context['capture']
self.assertEquals(extra_context, capture)
self.assertEqual(extra_context, capture)
# pt_render is also used to retrieve the unrendered source for
# TTW editing purposes.
self.assertEqual(template.pt_render(source=True), source)
......@@ -168,9 +168,9 @@ class TestPersistent(ZopeTestCase):
def test_repeat_object_security(self):
template = self._makeOne('foo', repeat_object)
# this should not raise an Unauthorized error
self.assertEquals(template().strip(), u'012')
# XXX-leorochael: the rest of this test is not actually
# testing the security access, but I couldn't find a simpler
self.assertEqual(template().strip(), u'012')
# The rest of this test is not actually testing
# the security access, but I couldn't find a simpler
# way to test if the RepeatItem instance itself allows public
# access, and there are convoluted situations in production
# that need RepeatItem to be declared public.
......@@ -191,7 +191,7 @@ class TestPersistent(ZopeTestCase):
# check that the "path" function inside a python expression works
self.folder.method = 'post'
template = self._makeOne('foo', python_path_source)
self.assertEquals(template(), u'<form method="post" />')
self.assertEqual(template(), u'<form method="post" />')
def test_filename_attribute(self):
# check that a persistent page template that happens to have
......
......@@ -76,7 +76,7 @@ class argv(Base):
args.append(arg(len(args) + 1, aa))
def items(self):
return map(lambda a: ('spam%d' % a.num, a), self.args)
return [('spam%d' % a.num, a) for a in self.args]
def values(self):
return self.args
......
......@@ -329,7 +329,7 @@ class Bindings:
# Try to find unbound parameters in the namespace, if the
# namespace is bound.
if self.getBindingAssignments().isNameAssigned('name_ns'):
code = self.func_code
code = self.__code__
for name in code.co_varnames[:code.co_argcount]:
try:
namevals[name] = namespace[name]
......
......@@ -33,10 +33,10 @@ class Script(SimpleItem, BindingsUI):
security = ClassSecurityInfo()
index_html = None
func_defaults = __defaults__ = ()
func_code = __code__ = None
__code__ = func_code = None
__defaults__ = func_defaults = ()
_Bindings_ns_class = TemplateDict
from Signature import _setFuncSignature
from .Signature import _setFuncSignature
InitializeClass(Script)
......@@ -44,8 +44,8 @@ def _setFuncSignature(self, defaults=None, varnames=(), argcount=-1):
if argcount < 0 and varnames:
argcount = len(varnames)
# Generate a change only if we have to.
if self.func_defaults != defaults:
self.func_defaults = self.__defaults__ = defaults
if self.__defaults__ != defaults:
self.__defaults__ = self.__defaults__ = defaults
code = FuncCode(varnames, argcount)
if self.func_code != code:
self.func_code = self.__code__ = code
if self.__code__ != code:
self.__code__ = self.__code__ = code
......@@ -25,9 +25,9 @@ by the PortalTestCase class! Subclasses must make sure
getPortal() returns a usable portal object to the setup code.
"""
import base
import interfaces
import utils
from . import base
from . import interfaces
from . import utils
from zope.interface import implementer
from AccessControl import getSecurityManager
......@@ -35,8 +35,8 @@ from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
from Acquisition import aq_base
from ZopeTestCase import user_name
from ZopeTestCase import user_password
from .ZopeTestCase import user_name
from .ZopeTestCase import user_password
portal_name = 'portal'
......
......@@ -13,44 +13,44 @@
"""Names exported by the ZopeTestCase package
"""
import ZopeLite as Zope2
import utils # NOQA
import layer # NOQA
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 # 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 # NOQA
from PortalTestCase import PortalTestCase # NOQA
from sandbox import Sandboxed # NOQA
from functional import Functional # NOQA
from base import TestCase # NOQA
from base import app # NOQA
from base import close # NOQA
from warnhook import WarningsHook # NOQA
from . import ZopeLite as Zope2
from . import utils # NOQA
from . import layer # NOQA
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 # 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 # NOQA
from .PortalTestCase import PortalTestCase # NOQA
from .sandbox import Sandboxed # NOQA
from .functional import Functional # NOQA
from .base import TestCase # NOQA
from .base import app # NOQA
from .base import close # NOQA
from .warnhook import WarningsHook # NOQA
from unittest import main # NOQA
from zopedoctest import ZopeDocTestSuite # NOQA
from zopedoctest import ZopeDocFileSuite # NOQA
from zopedoctest import FunctionalDocTestSuite # NOQA
from zopedoctest import FunctionalDocFileSuite # NOQA
from .zopedoctest import ZopeDocTestSuite # NOQA
from .zopedoctest import ZopeDocFileSuite # NOQA
from .zopedoctest import FunctionalDocTestSuite # NOQA
from .zopedoctest import FunctionalDocFileSuite # NOQA
import zopedoctest as doctest # NOQA
from . import zopedoctest as doctest # NOQA
import transaction # NOQA
import placeless # NOQA
from . import placeless # NOQA
Zope = Zope2
......@@ -60,7 +60,7 @@ class Functional(sandbox.Sandboxed):
request_method='GET', stdin=None, handle_errors=True):
'''Publishes the object at 'path' returning a response object.'''
from StringIO import StringIO
from io import BytesIO
from ZPublisher.HTTPRequest import WSGIRequest as Request
from ZPublisher.HTTPResponse import WSGIResponse
from ZPublisher.WSGIPublisher import publish_module
......@@ -92,16 +92,15 @@ class Functional(sandbox.Sandboxed):
env['HTTP_AUTHORIZATION'] = "Basic %s" % base64.encodestring(basic)
if stdin is None:
stdin = StringIO()
stdin = BytesIO()
outstream = StringIO()
outstream = BytesIO()
response = WSGIResponse(stdout=outstream, stderr=sys.stderr)
request = Request(stdin, env, response)
request.retry_max_count = 0
for k, v in extra.items():
request[k] = v
wsgi_headers = StringIO()
wsgi_headers = BytesIO()
def start_response(status, headers):
wsgi_headers.write('HTTP/1.1 %s\r\n' % status)
......
......@@ -22,6 +22,7 @@ from AccessControl.security import newInteraction
# For convenience
from Zope2.App import zcml # NOQA
import collections
class PlacelessSetup(CAPlacelessSetup,
......@@ -57,7 +58,7 @@ del ps
def callZCML(zcml_callback):
if callable(zcml_callback):
if isinstance(zcml_callback, collections.Callable):
zcml_callback()
else:
for func in zcml_callback:
......
......@@ -16,17 +16,16 @@ Demonstrates how to use the publish() API to execute GET, POST, PUT, etc.
requests against the ZPublisher and how to examine the response.
"""
from Testing import ZopeTestCase
from Testing.ZopeTestCase import user_name
from Testing.ZopeTestCase import user_password
from io import BytesIO
from AccessControl import getSecurityManager
from AccessControl.Permissions import view
from AccessControl.Permissions import manage_properties
from six.moves.urllib.parse import urlencode
from StringIO import StringIO
from urllib import urlencode
from Testing import ZopeTestCase
from Testing.ZopeTestCase import user_name
from Testing.ZopeTestCase import user_password
REDIRECT_DTML = '''\
<dtml-call "RESPONSE.redirect('%s')">'''
......@@ -109,7 +108,7 @@ class TestFunctional(ZopeTestCase.FunctionalTestCase):
self.setPermissions([manage_properties])
form = {'title': 'Foo'}
post_data = StringIO(urlencode(form))
post_data = BytesIO(urlencode(form))
response = self.publish(self.folder_path + '/index_html/change_title',
request_method='POST', stdin=post_data,
......
......@@ -228,14 +228,14 @@ class TestTransactionAbort(ZopeTestCase.ZopeTestCase):
def testTransactionAbort(self):
folder = self._getfolder()
self.assert_(folder is not None)
self.assert_(folder._p_jar is None)
self.assertTrue(folder is not None)
self.assertTrue(folder._p_jar is None)
transaction.savepoint()
self.assert_(folder._p_jar is not None)
self.assertTrue(folder._p_jar is not None)
transaction.abort()
del folder
folder = self._getfolder()
self.assert_(folder is None)
self.assertTrue(folder is None)
def test_suite():
......
......@@ -31,7 +31,7 @@ deprecated(
def appcall(func, *args, **kw):
'''Calls a function passing 'app' as first argument.'''
from base import app, close
from .base import app, close
app = app()
args = (app,) + args
try:
......@@ -50,5 +50,5 @@ def makelist(arg):
if isinstance(arg, tuple):
return list(arg)
if isinstance(arg, str):
return filter(None, [arg])
return [a for a in [arg] if a]
raise ValueError('Argument must be list, tuple, or string')
......@@ -125,9 +125,9 @@ def http(request_string, handle_errors=True):
This is used for HTTP doc tests.
"""
import urllib
import rfc822
from cStringIO import StringIO
from io import BytesIO
from six.moves.urllib.parse import unquote
from ZPublisher.HTTPRequest import WSGIRequest as Request
from ZPublisher.HTTPResponse import WSGIResponse
from ZPublisher.WSGIPublisher import publish_module
......@@ -143,9 +143,9 @@ def http(request_string, handle_errors=True):
command_line = request_string[:l].rstrip()
request_string = request_string[l + 1:]
method, path, protocol = command_line.split()
path = urllib.unquote(path)
path = unquote(path)
instream = StringIO(request_string)
instream = BytesIO(request_string)
env = {
'HTTP_HOST': 'localhost',
......@@ -171,7 +171,7 @@ def http(request_string, handle_errors=True):
for header in rfc822.Message(instream).headers]
# Store request body without headers
instream = StringIO(instream.read())
instream = BytesIO(instream.read())
for name, value in headers:
name = ('_'.join(name.upper().split('-')))
......@@ -182,13 +182,12 @@ def http(request_string, handle_errors=True):
if 'HTTP_AUTHORIZATION' in env:
env['HTTP_AUTHORIZATION'] = auth_header(env['HTTP_AUTHORIZATION'])
outstream = StringIO()
outstream = BytesIO()
response = WSGIResponse(stdout=outstream, stderr=sys.stderr)
request = Request(instream, env, response)
request.retry_max_count = 0
env['wsgi.input'] = instream
wsgi_headers = StringIO()
wsgi_headers = BytesIO()
def start_response(status, headers):
wsgi_headers.write('HTTP/1.1 %s\r\n' % status)
......
......@@ -24,25 +24,25 @@ class AuthHeaderTestCase(TestCase):
def test_auth_encoded(self):
header = 'Basic Z2xvYmFsbWdyOmdsb2JhbG1ncnB3'
self.assertEquals(auth_header(header), header)
self.assertEqual(auth_header(header), header)
def test_auth_non_encoded(self):
header = 'Basic globalmgr:globalmgrpw'
expected = 'Basic Z2xvYmFsbWdyOmdsb2JhbG1ncnB3'
self.assertEquals(auth_header(header), expected)
self.assertEqual(auth_header(header), expected)
def test_auth_non_encoded_empty(self):
header = 'Basic globalmgr:'
expected = 'Basic Z2xvYmFsbWdyOg=='
self.assertEquals(auth_header(header), expected)
self.assertEqual(auth_header(header), expected)
header = 'Basic :pass'
expected = 'Basic OnBhc3M='
self.assertEquals(auth_header(header), expected)
self.assertEqual(auth_header(header), expected)
def test_auth_non_encoded_colon(self):
header = 'Basic globalmgr:pass:pass'
expected = 'Basic Z2xvYmFsbWdyOnBhc3M6cGFzcw=='
self.assertEquals(auth_header(header), expected)
self.assertEqual(auth_header(header), expected)
def test_suite():
......
......@@ -16,16 +16,22 @@
Mostly just copy and paste from zope.testbrowser.testing.
"""
import cStringIO
import httplib
import urllib2
import io
import mechanize
from six.moves.urllib.request import HTTPHandler
from zExceptions import status_reasons
from zope.testbrowser import browser
from Testing.ZopeTestCase.zopedoctest import functional
try:
from http.client import HTTPMessage
from urllib.request import AbstractHTTPHandler
except ImportError:
from httplib import HTTPMessage
from urllib2 import AbstractHTTPHandler
class PublisherConnection(object):
......@@ -78,10 +84,10 @@ class PublisherConnection(object):
self.response = self.caller(request_string, handle_errors)
def getresponse(self):
"""Return a ``urllib2`` compatible response.
"""Return a ``urllib`` compatible response.
The goal of ths method is to convert the Zope Publisher's response to
a ``urllib2`` compatible response, which is also understood by
a ``urllib`` compatible response, which is also understood by
mechanize.
"""
real_response = self.response._response
......@@ -104,8 +110,8 @@ class PublisherResponse(object):
self.content = content
self.status = status
self.reason = reason
self.msg = httplib.HTTPMessage(cStringIO.StringIO(headers), 0)
self.content_as_file = cStringIO.StringIO(self.content)
self.msg = HTTPMessage(io.BytesIO(headers), 0)
self.content_as_file = io.BytesIO(self.content)
def read(self, amt=None):
return self.content_as_file.read(amt)
......@@ -115,13 +121,13 @@ class PublisherResponse(object):
pass
class PublisherHTTPHandler(urllib2.HTTPHandler):
class PublisherHTTPHandler(HTTPHandler):
"""Special HTTP handler to use the Zope Publisher."""
http_request = urllib2.AbstractHTTPHandler.do_request_
http_request = AbstractHTTPHandler.do_request_
def http_open(self, req):
"""Open an HTTP connection having a ``urllib2`` request."""
"""Open an HTTP connection having a ``urllib`` request."""
# Here we connect to the publisher.
return self.do_open(PublisherConnection, req)
......
......@@ -44,8 +44,8 @@ class MakerequestTests(unittest.TestCase):
def test_stdout(self):
# You can pass a stdout arg and it's used by the response.
import cStringIO
out = cStringIO.StringIO()
import io
out = io.BytesIO()
item = makerequest(SimpleItem(), stdout=out)
item.REQUEST.RESPONSE.write('aaa')
out.seek(0)
......
......@@ -13,7 +13,6 @@
""" Basic ZPublisher request management.
"""
from urllib import quote as urllib_quote
import types
from AccessControl.ZopeSecurityPolicy import getRoles
......@@ -21,6 +20,7 @@ from Acquisition import aq_base, aq_inner
from Acquisition.interfaces import IAcquirer
from ExtensionClass import Base
import pkg_resources
from six.moves.urllib.parse import quote as urllib_quote
from zExceptions import Forbidden
from zExceptions import NotFound
from zope.component import queryMultiAdapter
......@@ -67,7 +67,7 @@ class RequestContainer(Base):
self.__dict__[k] = v
def manage_property_types(self):
return type_converters.keys()
return list(type_converters.keys())
@implementer(IBrowserPublisher)
......@@ -307,7 +307,7 @@ class BaseRequest(object):
keys = {}
keys.update(self.common)
keys.update(self.other)
return keys.keys()
return list(keys.keys())
def items(self):
result = []
......@@ -322,7 +322,7 @@ class BaseRequest(object):
return result
def __str__(self):
L1 = self.items()
L1 = list(self.items())
L1.sort()
return '\n'.join("%s:\t%s" % item for item in L1)
......@@ -434,7 +434,7 @@ class BaseRequest(object):
parents.append(object)
steps = self.steps
self._steps = _steps = map(quote, steps)
self._steps = _steps = list(map(quote, steps))
path.reverse()
request['TraversalRequestNameStack'] = request.path = path
......@@ -610,14 +610,14 @@ class BaseRequest(object):
# No roles, so if we have a named group, get roles from
# group keys
if hasattr(groups, 'keys'):
self.roles = groups.keys()
self.roles = list(groups.keys())
else:
try:
groups = groups()
except Exception:
pass
try:
self.roles = groups.keys()
self.roles = list(groups.keys())
except Exception:
pass
......
......@@ -42,7 +42,7 @@ def unregisterBeforeTraverse(container, app_handle):
Returns a list of unregistered objects."""
btr = getattr(container, '__before_traverse__', {})
objects = []
for k in btr.keys():
for k in list(btr.keys()):
if k[1] == app_handle:
objects.append(btr[k])
del btr[k]
......@@ -74,7 +74,7 @@ def rewriteBeforeTraverse(container, btr):
bpth = MultiHook(hookname, bpth, dic)
setattr(container, hookname, bpth)
keys = btr.keys()
keys = list(btr.keys())
keys.sort()
for key in keys:
bpth.add(btr[key])
......@@ -129,12 +129,12 @@ class NameCaller:
except AttributeError:
return
# The code below can acquire "func_code" from an unrelated object
# The code below can acquire "__code__" from an unrelated object
# on the acquisition chain.
# This happens especially, if "meth" is a "CookieCrumber" instance,
# i.e. in a CMF Portal, if a DTMLMethod (or a similar object
# with a fake "func_code" is in the acquisition context
args = getattr(getattr(aq_base(meth), 'func_code', None),
# with a fake "__code__" is in the acquisition context
args = getattr(getattr(aq_base(meth), '__code__', None),
'co_argcount', 2)
try:
......
......@@ -64,7 +64,7 @@ def field2required(v):
def field2int(v):
if isinstance(v, (list, tuple)):
return map(field2int, v)
return list(map(field2int, v))
v = field2string(v)
if v:
try:
......@@ -78,7 +78,7 @@ def field2int(v):
def field2float(v):
if isinstance(v, (list, tuple)):
return map(field2float, v)
return list(map(field2float, v))
v = field2string(v)
if v:
try:
......@@ -94,7 +94,7 @@ def field2float(v):
def field2long(v):
if isinstance(v, (list, tuple)):
return map(field2long, v)
return list(map(field2long, v))
v = field2string(v)
# handle trailing 'L' if present.
if v[-1:] in ('L', 'l'):
......
......@@ -55,7 +55,7 @@ def parseRange(header):
# The sets are delimited by commas.
sets = sets.split(',')
# Filter out empty values, things like ',,' are allowed in the spec
sets = filter(None, sets)
sets = [_set for _set in sets if _set]
# We need at least one set
if not sets:
return None
......@@ -87,12 +87,12 @@ def parseRange(header):
# Special case: No start means the suffix format was used, which
# means the end value is actually a negative start value.
# Convert this by making it absolute.
# A -0 range is converted to sys.maxint, which will result in a
# A -0 range is converted to sys.maxsize, which will result in a
# Unsatisfiable response if no other ranges can by satisfied either.
if start is None:
start, end = -end, None
if not start:
start = sys.maxint
start = sys.maxsize
elif end is not None:
end = end + 1 # Make the end of the range exclusive
......
......@@ -30,12 +30,10 @@ from tempfile import (
_TemporaryFileWrapper,
)
import time
from urllib import unquote
from urllib import splittype
from urllib import splitport
from AccessControl.tainted import TaintedString
import pkg_resources
from six.moves.urllib.parse import unquote
from zope.i18n.interfaces import IUserPreferredLanguages
from zope.i18n.locales import locales, LoadLocaleError
from zope.interface import directlyProvidedBy
......@@ -47,9 +45,15 @@ from zope.publisher.interfaces.browser import IBrowserRequest
from ZPublisher.BaseRequest import BaseRequest
from ZPublisher.BaseRequest import quote
from ZPublisher.Converters import get_converter
import collections
if sys.version_info >= (3, ):
unicode = str
from urllib.parse import splitport
from urllib.parse import splittype
else:
from urllib import splitport
from urllib import splittype
xmlrpc = None
try:
......@@ -177,7 +181,7 @@ class HTTPRequest(BaseRequest):
_file = None
_urls = ()
retry_max_count = 3
retry_max_count = 0
def supports_retry(self):
if self.retry_count < self.retry_max_count:
......@@ -233,7 +237,7 @@ class HTTPRequest(BaseRequest):
other = self.other
if isinstance(path, str) or isinstance(path, unicode):
path = path.split('/')
self._script[:] = map(quote, filter(None, path))
self._script[:] = list(map(quote, [_p for _p in path if _p]))
del self._steps[:]
parents = other['PARENTS']
if hard:
......@@ -263,7 +267,8 @@ class HTTPRequest(BaseRequest):
def physicalPathToURL(self, path, relative=0):
""" Convert a physical path into a URL in the current context """
path = self._script + map(quote, self.physicalPathToVirtualPath(path))
path = self._script + list(
map(quote, self.physicalPathToVirtualPath(path)))
if relative:
path.insert(0, '')
else:
......@@ -275,7 +280,7 @@ class HTTPRequest(BaseRequest):
If the URL makes no sense in light of the current virtual
hosting context, a ValueError is raised."""
other = self.other
path = filter(None, URL.split('/'))
path = [_p for _p in URL.split('/') if _p]
if URL.find('://') >= 0:
path = path[2:]
......@@ -288,7 +293,7 @@ class HTTPRequest(BaseRequest):
else:
raise ValueError('Url does not match virtual hosting context')
vrpp = other.get('VirtualRootPhysicalPath', ('',))
return list(vrpp) + map(unquote, path)
return list(vrpp) + list(map(unquote, path))
def _resetURLS(self):
other = self.other
......@@ -377,7 +382,7 @@ class HTTPRequest(BaseRequest):
b = script = get_env('SCRIPT_NAME', '').strip()
# _script and the other _names are meant for URL construction
self._script = map(quote, filter(None, script.split('/')))
self._script = list(map(quote, [_s for _s in script.split('/') if _s]))
while b and b[-1] == '/':
b = b[:-1]
......@@ -1159,7 +1164,7 @@ class HTTPRequest(BaseRequest):
def postProcessInputs(self):
"""Process the values in request.form to decode strings to unicode.
"""
for name, value in self.form.iteritems():
for name, value in self.form.items():
self.form[name] = _decode(value, default_encoding)
def resolve_url(self, url):
......@@ -1203,7 +1208,7 @@ class HTTPRequest(BaseRequest):
# to ensure we are getting the actual object named by
# the given url, and not some kind of default object.
if hasattr(object, 'id'):
if callable(object.id):
if isinstance(object.id, collections.Callable):
name = object.id()
else:
name = object.id
......@@ -1342,7 +1347,7 @@ class HTTPRequest(BaseRequest):
if self._lazies:
v = self._lazies.get(key, _marker)
if v is not _marker:
if callable(v):
if isinstance(v, collections.Callable):
v = v()
self[key] = v # Promote lazy value
del self._lazies[key]
......@@ -1445,7 +1450,7 @@ class HTTPRequest(BaseRequest):
if returnTaints:
keys.update(self.taintedform)
keys = keys.keys()
keys = list(keys.keys())
keys.sort()
return keys
......@@ -1679,6 +1684,12 @@ class FileUpload:
except Exception:
pass
def __bool__(self):
"""FileUpload objects are considered false if their
filename is empty.
"""
return not not self.filename
def __nonzero__(self):
"""FileUpload objects are considered false if their
filename is empty.
......@@ -1774,7 +1785,7 @@ class record(object):
def __eq__(self, other):
if not isinstance(other, record):
return False
return self.__dict__.items() == other.__dict__.items()
return list(self.__dict__.items()) == list(other.__dict__.items())
def _filterPasswordFields(items):
......@@ -1800,7 +1811,7 @@ def _decode(value, charset):
elif isinstance(value, tuple):
return tuple(_decode(v, charset) for v in value)
elif isinstance(value, dict):
return dict((k, _decode(v, charset)) for k, v in value.iteritems())
return dict((k, _decode(v, charset)) for k, v in value.items())
elif isinstance(value, str):
return unicode(value, charset, 'replace')
return value
......@@ -20,11 +20,10 @@ from string import translate
import struct
import sys
import time
import types
from urllib import quote
import zlib
from six import reraise
from six import class_types, reraise
from six.moves.urllib.parse import quote
from zope.event import notify
from zExceptions import (
BadRequest,
......@@ -63,7 +62,7 @@ for key, val in status_reasons.items():
status_codes[val.lower()] = key
status_codes[key] = key
status_codes[str(key)] = key
en = filter(lambda n: n[-5:] == 'Error', dir(__builtins__))
en = [n for n in dir(__builtins__) if n[-5:] == 'Error']
for name in en:
status_codes[name.lower()] = 500
status_codes['nameerror'] = 503
......@@ -195,7 +194,7 @@ class HTTPBaseResponse(BaseResponse):
# It has already been determined.
return
if (isinstance(status, (type, types.ClassType)) and
if (isinstance(status, class_types) and
issubclass(status, Exception)):
status = status.__name__
......
......@@ -9,7 +9,7 @@ class IUnboundStreamIterator(Interface):
An iterator with unknown length that can be published.
"""
def next():
def __next__():
"""
Return a sequence of bytes out of the bytestream, or raise
StopIeration if we've reached the end of the bytestream.
......@@ -49,12 +49,14 @@ class filestream_iterator(io.FileIO):
super(filestream_iterator, self).__init__(name, mode)
self.streamsize = streamsize
def next(self):
def __next__(self):
data = self.read(self.streamsize)
if not data:
raise StopIteration
return data
next = __next__
def __len__(self):
cur_pos = self.tell()
self.seek(0, io.SEEK_END)
......
......@@ -13,13 +13,13 @@
""" Python Object Publisher -- Publish Python objects on web servers
"""
from contextlib import contextmanager, closing
from cStringIO import StringIO
from io import BytesIO
from io import IOBase
import sys
from thread import allocate_lock
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
from six.moves._thread import allocate_lock
import transaction
from transaction.interfaces import TransientError
from zExceptions import (
......@@ -201,7 +201,7 @@ def publish_module(environ, start_response,
module_info = get_module_info(_module_name)
result = ()
with closing(StringIO()) as stdout, closing(StringIO()) as stderr:
with closing(BytesIO()) as stdout, closing(BytesIO()) as stderr:
response = (_response if _response is not None else
_response_factory(stdout=stdout, stderr=stderr))
response._http_version = environ['SERVER_PROTOCOL'].split('/')[1]
......@@ -235,7 +235,7 @@ def publish_module(environ, start_response,
result = response.body
else:
# If somebody used response.write, that data will be in the
# stdout StringIO, so we put that before the body.
# stdout BytesIO, so we put that before the body.
result = (stdout.getvalue(), response.body)
for func in response.after_list:
......
......@@ -26,10 +26,10 @@ def default_missing_name(name, context):
def default_handle_class(klass, context):
if hasattr(klass, '__init__'):
f = klass.__init__.im_func
c = f.func_code
f = klass.__init__.__func__
c = f.__code__
names = c.co_varnames[1:c.co_argcount]
return klass, names, f.func_defaults
return klass, names, f.__defaults__
else:
return klass, (), ()
......@@ -50,8 +50,8 @@ def mapply(object, positional=(), keyword={},
if maybe:
return object
raise
code = f.func_code
defaults = f.func_defaults
code = f.__code__
defaults = f.__defaults__
names = code.co_varnames[count:code.co_argcount]
nargs = len(names)
......
......@@ -11,4 +11,4 @@
#
##############################################################################
from thread import allocate_lock # NOQA
from six.moves._thread import allocate_lock # NOQA
......@@ -77,7 +77,7 @@ class TestRangeHeaderParse(unittest.TestCase):
self.expectSets('bytes=0-0', [(0, 1)])
def testNegativeZero(self):
self.expectSets('bytes=-0', [(sys.maxint, None)])
self.expectSets('bytes=-0', [(sys.maxsize, None)])
class TestExpandRanges(unittest.TestCase):
......@@ -127,4 +127,4 @@ class TestExpandRanges(unittest.TestCase):
self.expectSets([(-5, None), (40, 100)], 50, [(45, 50), (40, 50)])
def testRemoveUnsatisfiable(self):
self.expectSets([(sys.maxint, None), (10, 20)], 50, [(10, 20)])
self.expectSets([(sys.maxsize, None), (10, 20)], 50, [(10, 20)])
import base64
from StringIO import StringIO
from io import BytesIO
import sys
import unittest
......@@ -41,7 +41,7 @@ class HTTPRequestFactoryMixin(object):
def _makeOne(self, stdin=None, environ=None, response=None, clean=1):
from ZPublisher.HTTPResponse import HTTPResponse
if stdin is None:
stdin = StringIO()
stdin = BytesIO()
if environ is None:
environ = {}
......@@ -56,7 +56,7 @@ class HTTPRequestFactoryMixin(object):
environ['SERVER_PORT'] = '8080'
if response is None:
response = HTTPResponse(stdout=StringIO())
response = HTTPResponse(stdout=BytesIO())
return self._getTargetClass()(stdin, environ, response, clean)
......@@ -64,7 +64,7 @@ class HTTPRequestFactoryMixin(object):
class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
def _processInputs(self, inputs):
from urllib import quote_plus
from six.moves.urllib.parse import quote_plus
# Have the inputs processed, and return a HTTPRequest object
# holding the result.
# inputs is expected to be a list of (key, value) tuples, no CGI
......@@ -84,7 +84,7 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
return req
def _noTaintedValues(self, req):
self.assertFalse(req.taintedform.keys())
self.assertFalse(list(req.taintedform.keys()))
def _valueIsOrHoldsTainted(self, val):
# Recursively searches a structure for a TaintedString and returns 1
......@@ -103,7 +103,7 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
retval = 1
elif isinstance(val, record):
for attr, value in val.__dict__.items():
for attr, value in list(val.__dict__.items()):
rval = self._valueIsOrHoldsTainted(attr)
if rval:
retval = 1
......@@ -125,24 +125,24 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
return retval
def _noFormValuesInOther(self, req):
for key in req.taintedform.keys():
for key in list(req.taintedform.keys()):
self.assertFalse(
key in req.other,
'REQUEST.other should not hold tainted values at first!')
for key in req.form.keys():
for key in list(req.form.keys()):
self.assertFalse(
key in req.other,
'REQUEST.other should not hold form values at first!')
def _onlyTaintedformHoldsTaintedStrings(self, req):
for key, val in req.taintedform.items():
self.assert_(
for key, val in list(req.taintedform.items()):
self.assertTrue(
self._valueIsOrHoldsTainted(key) or
self._valueIsOrHoldsTainted(val),
'Tainted form holds item %s that is not tainted' % key)
for key, val in req.form.items():
for key, val in list(req.form.items()):
if key in req.taintedform:
continue
self.assertFalse(
......@@ -151,8 +151,8 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
'Normal form holds item %s that is tainted' % key)
def _taintedKeysAlsoInForm(self, req):
for key in req.taintedform.keys():
self.assert_(
for key in list(req.taintedform.keys()):
self.assertTrue(
key in req.form,
"Found tainted %s not in form" % key)
self.assertEqual(
......@@ -630,7 +630,7 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
# returned should be HTML safe
from DateTime.interfaces import SyntaxError
from ZPublisher.Converters import type_converters
for type, convert in type_converters.items():
for type, convert in list(type_converters.items()):
try:
convert('<html garbage>')
except Exception as e:
......@@ -722,7 +722,7 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
def test_close_removes_stdin_references(self):
# Verifies that all references to the input stream go away on
# request.close(). Otherwise a tempfile may stick around.
s = StringIO(TEST_FILE_DATA)
s = BytesIO(TEST_FILE_DATA)
start_count = sys.getrefcount(s)
req = self._makeOne(stdin=s, environ=TEST_ENVIRON.copy())
......@@ -733,26 +733,24 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
def test_processInputs_w_large_input_gets_tempfile(self):
# checks fileupload object supports the filename
s = StringIO(TEST_LARGEFILE_DATA)
s = BytesIO(TEST_LARGEFILE_DATA)
req = self._makeOne(stdin=s, environ=TEST_ENVIRON.copy())
req.processInputs()
f = req.form.get('file')
self.assert_(f.name)
self.assertTrue(f.name)
def test_processInputs_with_file_upload_gets_iterator(self):
# checks fileupload object supports the iterator protocol
# collector entry 1837
s = StringIO(TEST_FILE_DATA)
s = BytesIO(TEST_FILE_DATA)
req = self._makeOne(stdin=s, environ=TEST_ENVIRON.copy())
req.processInputs()
f = req.form.get('file')
self.assertEqual(list(f), ['test\n'])
f.seek(0)
self.assertEqual(f.next(), 'test\n')
f.seek(0)
self.assertEqual(f.xreadlines(), f)
self.assertEqual(next(f), 'test\n')
def test__authUserPW_simple(self):
user_id = 'user'
......@@ -787,9 +785,9 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
from zope.publisher.base import DebugFlags
# when accessing request.debug we will see the DebugFlags instance
request = self._makeOne()
self.assert_(isinstance(request.debug, DebugFlags))
self.assertTrue(isinstance(request.debug, DebugFlags))
# It won't be available through dictonary lookup, though
self.assert_(request.get('debug') is None)
self.assertTrue(request.get('debug') is None)
def test_debug_in_qs_gets_form_var(self):
env = {'QUERY_STRING': 'debug=1'}
......@@ -823,16 +821,16 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
# before accessing request.locale for the first time, request._locale
# is still a marker
self.assert_(request._locale is _marker)
self.assertTrue(request._locale is _marker)
# when accessing request.locale we will see an ILocale
self.assert_(ILocale.providedBy(request.locale))
self.assertTrue(ILocale.providedBy(request.locale))
# and request._locale has been set
self.assert_(request._locale is request.locale)
self.assertTrue(request._locale is request.locale)
# It won't be available through dictonary lookup, though
self.assert_(request.get('locale') is None)
self.assertTrue(request.get('locale') is None)
def test_locale_in_qs(self):
provideAdapter(BrowserLanguages, [IHTTPRequest],
......@@ -857,7 +855,7 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
request = self._makeOne(environ=env)
request.processInputs()
self.assert_(ILocale.providedBy(request.locale))
self.assertTrue(ILocale.providedBy(request.locale))
request.form['locale'] = '1'
self.assertEqual(request.locale, '1')
......@@ -876,7 +874,7 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
env['HTTP_ACCEPT_LANGUAGE'] = httplang
request = self._makeOne(environ=env)
locale = request.locale
self.assert_(ILocale.providedBy(locale))
self.assertTrue(ILocale.providedBy(locale))
parts = httplang.split('-')
lang = parts.pop(0).lower()
territory = variant = None
......@@ -898,10 +896,10 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
request = self._makeOne(environ=env)
locale = request.locale
self.assert_(ILocale.providedBy(locale))
self.assert_(locale.id.language is None)
self.assert_(locale.id.territory is None)
self.assert_(locale.id.variant is None)
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)
def test_method_GET(self):
env = {'REQUEST_METHOD': 'GET'}
......
# -*- coding: utf-8 -*-
from StringIO import StringIO
from io import BytesIO
import sys
import unittest
......@@ -1235,7 +1235,7 @@ class HTTPResponseTests(unittest.TestCase):
self.assertEqual(lines[5], 'BLAH')
def test_write_already_wrote(self):
stdout = StringIO()
stdout = BytesIO()
response = self._makeOne(stdout=stdout)
response.write('Kilroy was here!')
self.assertTrue(response._wrote)
......@@ -1249,7 +1249,7 @@ class HTTPResponseTests(unittest.TestCase):
self.assertEqual(lines[4], 'Kilroy was here!')
def test_write_not_already_wrote(self):
stdout = StringIO()
stdout = BytesIO()
response = self._makeOne(stdout=stdout)
response._wrote = True
response.write('Kilroy was here!')
......
......@@ -99,12 +99,14 @@ class WSGIResponseTests(unittest.TestCase):
data = "hello"
done = 0
def next(self):
def __next__(self):
if not self.done:
self.done = 1
return self.data
raise StopIteration
next = __next__
response = self._makeOne()
response.setStatus(200)
body = TestStreamIterator()
......@@ -122,12 +124,14 @@ class WSGIResponseTests(unittest.TestCase):
data = "hello"
done = 0
def next(self):
def __next__(self):
if not self.done:
self.done = 1
return self.data
raise StopIteration
next = __next__
def __len__(self):
return len(self.data)
......@@ -226,7 +230,7 @@ class TestPublishModule(unittest.TestCase, PlacelessSetup):
provideAdapter(factory, requires, provides, name)
def _makeEnviron(self, **kw):
from StringIO import StringIO
from io import BytesIO
environ = {
'SCRIPT_NAME': '',
'REQUEST_METHOD': 'GET',
......@@ -237,7 +241,7 @@ class TestPublishModule(unittest.TestCase, PlacelessSetup):
'SERVER_PORT': '8080',
'HTTP_HOST': '127.0.0.1:8080',
'SERVER_PROTOCOL': 'HTTP/1.1',
'wsgi.input': StringIO(''),
'wsgi.input': BytesIO(''),
'CONTENT_LENGTH': '0',
'HTTP_CONNECTION': 'keep-alive',
'CONTENT_TYPE': ''
......@@ -349,12 +353,14 @@ class TestPublishModule(unittest.TestCase, PlacelessSetup):
data = "hello"
done = 0
def next(self):
def __next__(self):
if not self.done:
self.done = 1
return self.data
raise StopIteration
next = __next__
_response = DummyResponse()
_response._status = '200 OK'
_response._headers = [('Content-Length', '4')]
......@@ -375,12 +381,14 @@ class TestPublishModule(unittest.TestCase, PlacelessSetup):
data = "hello"
done = 0
def next(self):
def __next__(self):
if not self.done:
self.done = 1
return self.data
raise StopIteration
next = __next__
_response = DummyResponse()
_response._status = '200 OK'
body = _response.body = TestUnboundStreamIterator()
......
from StringIO import StringIO
from io import BytesIO
from sys import modules, exc_info
from unittest import TestCase
......@@ -88,13 +88,13 @@ class TestPubEvents(TestCase):
r.action = 'succeed'
self._publish(r, PUBMODULE)
events = self.reporter.events
self.assert_(isinstance(events[0], PubStart))
self.assertTrue(isinstance(events[0], PubStart))
self.assertEqual(events[0].request, r)
self.assert_(isinstance(events[1], PubAfterTraversal))
self.assertTrue(isinstance(events[1], PubAfterTraversal))
self.assertEqual(events[1].request, r)
self.assert_(isinstance(events[2], PubBeforeCommit))
self.assertTrue(isinstance(events[2], PubBeforeCommit))
self.assertEqual(events[2].request, r)
self.assert_(isinstance(events[3], PubSuccess))
self.assertTrue(isinstance(events[3], PubSuccess))
self.assertEqual(events[3].request, r)
def testFailureReturn(self):
......@@ -102,11 +102,11 @@ class TestPubEvents(TestCase):
r.action = 'fail_return'
self.assertRaises(Exception, self._publish, r, PUBMODULE)
events = self.reporter.events
self.assert_(isinstance(events[0], PubStart))
self.assertTrue(isinstance(events[0], PubStart))
self.assertEqual(events[0].request, r)
self.assert_(isinstance(events[1], PubBeforeAbort))
self.assertTrue(isinstance(events[1], PubBeforeAbort))
self.assertEqual(events[1].request, r)
self.assert_(isinstance(events[2], PubFailure))
self.assertTrue(isinstance(events[2], PubFailure))
self.assertEqual(events[2].request, r)
self.assertEqual(len(events[2].exc_info), 3)
......@@ -115,12 +115,12 @@ class TestPubEvents(TestCase):
r.action = 'fail_exception'
self.assertRaises(Exception, self._publish, r, PUBMODULE)
events = self.reporter.events
self.assert_(isinstance(events[0], PubStart))
self.assertTrue(isinstance(events[0], PubStart))
self.assertEqual(events[0].request, r)
self.assert_(isinstance(events[1], PubBeforeAbort))
self.assertTrue(isinstance(events[1], PubBeforeAbort))
self.assertEqual(events[1].request, r)
self.assertEqual(len(events[1].exc_info), 3)
self.assert_(isinstance(events[2], PubFailure))
self.assertTrue(isinstance(events[2], PubFailure))
self.assertEqual(events[2].request, r)
self.assertEqual(len(events[2].exc_info), 3)
......@@ -129,26 +129,26 @@ class TestPubEvents(TestCase):
r.action = 'conflict'
self.assertRaises(ConflictError, self._publish, r, PUBMODULE)
events = self.reporter.events
self.assert_(isinstance(events[0], PubStart))
self.assertTrue(isinstance(events[0], PubStart))
self.assertEqual(events[0].request, r)
self.assert_(isinstance(events[1], PubBeforeAbort))
self.assertTrue(isinstance(events[1], PubBeforeAbort))
self.assertEqual(events[1].request, r)
self.assertEqual(len(events[1].exc_info), 3)
self.assert_(isinstance(events[1].exc_info[1], ConflictError))
self.assert_(isinstance(events[2], PubFailure))
self.assertTrue(isinstance(events[1].exc_info[1], ConflictError))
self.assertTrue(isinstance(events[2], PubFailure))
self.assertEqual(events[2].request, r)
self.assertEqual(len(events[2].exc_info), 3)
self.assert_(isinstance(events[2].exc_info[1], ConflictError))
self.assertTrue(isinstance(events[2].exc_info[1], ConflictError))
def testStreaming(self):
out = StringIO()
out = BytesIO()
response = WSGIResponse(stdout=out)
response.write('datachunk1')
response.write('datachunk2')
events = self.reporter.events
self.assertEqual(len(events), 1)
self.assert_(isinstance(events[0], PubBeforeStreaming))
self.assertTrue(isinstance(events[0], PubBeforeStreaming))
self.assertEqual(events[0].response, response)
self.assertTrue('datachunk1datachunk2' in out.getvalue())
......
......@@ -30,7 +30,7 @@ def recordMetaData(object, request):
if hasattr(object, 'im_self') and hasattr(object, '__name__'):
# object is a Python method.
to_append = (object.__name__,)
object = object.im_self
object = object.__self__
while (object is not None and
not hasattr(object, 'getPhysicalPath')):
......
......@@ -14,7 +14,7 @@
"""
from Acquisition import aq_acquire
from Tree import TreeMaker, TreeNode, b2a
from .Tree import TreeMaker, TreeNode, b2a
class SimpleTreeNode(TreeNode):
......
......@@ -14,12 +14,12 @@
"""
import cgi
import urllib
from AccessControl import getSecurityManager
from AccessControl.unauthorized import Unauthorized
from AccessControl.ZopeGuards import guarded_getitem
from DateTime.DateTime import DateTime
from six.moves.urllib.parse import quote, unquote
from ZTUtils.Batch import Batch
from ZTUtils.Lazy import Lazy
......@@ -185,11 +185,10 @@ def make_query(*args, **kwargs):
d.update(arg)
d.update(kwargs)
uq = urllib.quote
qlist = complex_marshal(d.items())
qlist = complex_marshal(list(d.items()))
for i in range(len(qlist)):
k, m, v = qlist[i]
qlist[i] = '%s%s=%s' % (uq(k), m, uq(str(v)))
qlist[i] = '%s%s=%s' % (quote(k), m, quote(str(v)))
return '&'.join(qlist)
......@@ -215,7 +214,7 @@ def make_hidden_input(*args, **kwargs):
def hq(x):
return cgi.escape(x, quote=True)
qlist = complex_marshal(d.items())
qlist = complex_marshal(list(d.items()))
for i in range(len(qlist)):
k, m, v = qlist[i]
qlist[i] = ('<input type="hidden" name="%s%s" value="%s">'
......@@ -310,9 +309,8 @@ def url_query(request, req_name="URL", omit=None):
for name in omit:
omits[name] = None
unq = urllib.unquote
for i in range(len(qsparts)):
name = unq(qsparts[i].split('=', 1)[0])
name = unquote(qsparts[i].split('=', 1)[0])
if name in omits:
qsparts[i] = ''
name = name.split(':', 1)[0]
......@@ -322,7 +320,7 @@ def url_query(request, req_name="URL", omit=None):
if name in omits:
qsparts[i] = ''
qs = '&'.join(filter(None, qsparts))
qs = '&'.join([part for part in qsparts if part])
# We alway append '?' since arguments will be appended to the URL
return '%s?%s' % (base, qs)
......@@ -16,7 +16,7 @@ from AccessControl.SecurityInfo import ModuleSecurityInfo
security = ModuleSecurityInfo('ZTUtils')
security.declarePublic('encodeExpansion', 'decodeExpansion', 'a2b', 'b2a')
from Tree import encodeExpansion, decodeExpansion, a2b, b2a # NOQA
from .Tree import encodeExpansion, decodeExpansion, a2b, b2a # NOQA
security.declarePublic('Batch', 'TreeMaker', 'SimpleTreeMaker', 'LazyFilter')
from ZTUtils.Zope import Batch, TreeMaker, SimpleTreeMaker, LazyFilter # NOQA
......
......@@ -15,7 +15,7 @@ class BatchTests(unittest.TestCase):
def testSingle(self):
'''Test single Batch'''
for bsize in range(1, 6):
seq = range(bsize)
seq = list(range(bsize))
b = Batch(seq, 5)
assert b.previous is None
assert b.next is None
......@@ -30,12 +30,12 @@ class BatchTests(unittest.TestCase):
def testOrphan(self):
'''Test orphan collection'''
for bsize in (6, 7):
b = Batch(range(bsize), 5, orphan=3)
b = Batch(list(range(bsize)), 5, orphan=3)
assert b.next is None
assert len(b) == bsize
assert b[bsize - 1] == bsize - 1
assert b.sequence_length == bsize
b = Batch(range(8), 5)
b = Batch(list(range(8)), 5)
assert len(b) == 5
assert b.sequence_length == 8
assert len(b.next) == 3
......@@ -43,6 +43,6 @@ class BatchTests(unittest.TestCase):
def testLengthEqualsSizePlusOrphans(self):
'''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(range(bsize),
b = Batch(list(range(bsize)),
size=10, start=1, end=0, orphan=3, overlap=0)
assert length == b.length
......@@ -21,7 +21,7 @@ class BaseSequenceTest(object):
self.assertEqual(list(lseq), seq)
def test_actual_result_count(self):
lcat = self._createLSeq(range(10))
lcat = self._createLSeq(list(range(10)))
self.assertEqual(len(lcat), 10)
self.assertEqual(lcat.actual_result_count, 10)
......@@ -47,37 +47,37 @@ class TestLazyCat(unittest.TestCase, BaseSequenceTest):
def test_repr(self):
lcat = self._createLSeq([0, 1])
self.assertEquals(repr(lcat), repr([0, 1]))
self.assertEqual(repr(lcat), repr([0, 1]))
def test_init_single(self):
seq = range(10)
seq = list(range(10))
lcat = self._createLSeq(seq)
self._compare(lcat, seq)
self.assertEqual(lcat.actual_result_count, 10)
def test_add(self):
seq1 = range(10)
seq2 = range(10, 20)
seq1 = list(range(10))
seq2 = list(range(10, 20))
lcat1 = self._createLSeq(seq1)
lcat2 = self._createLSeq(seq2)
lcat = lcat1 + lcat2
self._compare(lcat, range(20))
self._compare(lcat, list(range(20)))
self.assertEqual(lcat.actual_result_count, 20)
def test_add_after_getitem(self):
seq1 = range(10)
seq2 = range(10, 20)
seq1 = list(range(10))
seq2 = list(range(10, 20))
lcat1 = self._createLSeq(seq1)
lcat2 = self._createLSeq(seq2)
# turning lcat1 into a list will flatten it into _data and remove _seq
list(lcat1)
lcat = lcat1 + lcat2
self._compare(lcat, range(20))
self._compare(lcat, list(range(20)))
self.assertEqual(lcat.actual_result_count, 20)
def test_init_multiple(self):
from string import hexdigits, letters
seq1 = range(10)
seq1 = list(range(10))
seq2 = list(hexdigits)
seq3 = list(letters)
lcat = self._createLSeq(seq1, seq2, seq3)
......@@ -85,7 +85,7 @@ class TestLazyCat(unittest.TestCase, BaseSequenceTest):
def test_init_nested(self):
from string import hexdigits, letters
seq1 = range(10)
seq1 = list(range(10))
seq2 = list(hexdigits)
seq3 = list(letters)
lcat = self._createLSeq(
......@@ -94,7 +94,7 @@ class TestLazyCat(unittest.TestCase, BaseSequenceTest):
def test_slicing(self):
from string import hexdigits, letters
seq1 = range(10)
seq1 = list(range(10))
seq2 = list(hexdigits)
seq3 = list(letters)
lcat = self._createLSeq(
......@@ -103,25 +103,25 @@ class TestLazyCat(unittest.TestCase, BaseSequenceTest):
def test_length(self):
# Unaccessed length
lcat = self._createLSeq(range(10))
lcat = self._createLSeq(list(range(10)))
self.assertEqual(len(lcat), 10)
self.assertEqual(lcat.actual_result_count, 10)
# Accessed in the middle
lcat = self._createLSeq(range(10))
lcat = self._createLSeq(list(range(10)))
lcat[4]
self.assertEqual(len(lcat), 10)
self.assertEqual(lcat.actual_result_count, 10)
# Accessed after the lcat is accessed over the whole range
lcat = self._createLSeq(range(10))
lcat = self._createLSeq(list(range(10)))
lcat[:]
self.assertEqual(len(lcat), 10)
self.assertEqual(lcat.actual_result_count, 10)
def test_actual_result_count(self):
# specify up-front
lcat = self._createLSeq(range(10))
lcat = self._createLSeq(list(range(10)))
lcat.actual_result_count = 100
self.assertEqual(len(lcat), 10)
......@@ -153,7 +153,7 @@ class TestLazyMap(TestLazyCat):
def test_map(self):
from string import hexdigits, letters
seq1 = range(10)
seq1 = list(range(10))
seq2 = list(hexdigits)
seq3 = list(letters)
......@@ -164,7 +164,7 @@ class TestLazyMap(TestLazyCat):
self._compare(lmap, [str(x).lower() for x in (seq1 + seq2 + seq3)])
def testMapFuncIsOnlyCalledAsNecessary(self):
seq = range(10)
seq = list(range(10))
count = [0] # closure only works with list, and `nonlocal` in py3
def func(x):
......@@ -190,7 +190,7 @@ class TestLazyFilter(TestLazyCat):
def test_filter(self):
from string import hexdigits, letters
seq1 = range(10)
seq1 = list(range(10))
seq2 = list(hexdigits)
seq3 = list(letters)
......@@ -233,7 +233,7 @@ class TestLazyMop(TestLazyCat):
def test_mop(self):
from string import hexdigits, letters
seq1 = range(10)
seq1 = list(range(10))
seq2 = list(hexdigits)
seq3 = list(letters)
......@@ -248,7 +248,7 @@ class TestLazyMop(TestLazyCat):
def test_length_with_filter(self):
from string import letters
letter_length = len(letters)
seq = range(10) + list(letters)
seq = list(range(10)) + list(letters)
def filter(x):
if isinstance(x, int):
......@@ -282,12 +282,12 @@ class TestLazyValues(unittest.TestCase, BaseSequenceTest):
def test_values(self):
from string import letters
seq = zip(letters, range(10))
seq = list(zip(letters, list(range(10))))
lvals = self._createLSeq(seq)
self._compare(lvals, range(10))
self._compare(lvals, list(range(10)))
def test_slicing(self):
from string import letters
seq = zip(letters, range(10))
seq = list(zip(letters, list(range(10))))
lvals = self._createLSeq(seq)
self._compare(lvals[2:-2], range(2, 8))
self._compare(lvals[2:-2], list(range(2, 8)))
......@@ -51,7 +51,7 @@ class TreeTests(unittest.TestCase):
self.assertEqual(treeroot.height, 2)
self.assertEqual(treeroot.depth, 0)
self.assertEqual(treeroot.state, 1)
self.assert_(treeroot.object is self.root)
self.assertTrue(treeroot.object is self.root)
i = 'b'
for subnode in treeroot:
......@@ -60,7 +60,7 @@ class TreeTests(unittest.TestCase):
self.assertEqual(subnode.height, 1)
self.assertEqual(subnode.depth, 1)
self.assertEqual(subnode.state, -1)
self.assert_(subnode.object is self.items[i])
self.assertTrue(subnode.object is self.items[i])
i = chr(ord(i) + 1)
expected_set = [self.items['a'], self.items['b'], self.items['c']]
......@@ -86,7 +86,7 @@ class TreeTests(unittest.TestCase):
self.assertEqual(treeroot.height, 4)
self.assertEqual(treeroot.depth, 0)
self.assertEqual(treeroot.state, 1)
self.assert_(treeroot.object is self.root)
self.assertTrue(treeroot.object is self.root)
items = self.items
expected_set = [
......@@ -230,5 +230,5 @@ class TreeTests(unittest.TestCase):
import zlib
from ZTUtils.Tree import b2a
big = b2a(zlib.compress('x' * (1024 * 1100)))
self.assert_(len(big) < 8192) # Must be under the input size limit
self.assertTrue(len(big) < 8192) # Must be under the input size limit
self.assertRaises(ValueError, Tree.decodeExpansion, ':' + big)
import unittest
import urllib
from ZTUtils.Zope import make_query, complex_marshal
from ZTUtils.Zope import make_hidden_input
from DateTime import DateTime
from six.moves.urllib.parse import quote
from ZTUtils.Zope import (
complex_marshal,
make_hidden_input,
make_query,
)
class QueryTests(unittest.TestCase):
......@@ -39,7 +43,7 @@ class QueryTests(unittest.TestCase):
def testMakeComplexQuery(self):
'''Test that make_query returns sane results'''
test_date = DateTime()
quote_date = urllib.quote(str(test_date))
quote_date = quote(str(test_date))
record = {'arg1': [1, test_date, 'str'], 'arg2': 1}
list_ = [1, test_date, 'str']
int_ = 1
......
......@@ -123,7 +123,7 @@ def startup():
Zope2.DB = DB
Zope2.opened.append(DB)
import ClassFactory
from . import ClassFactory
DB.classFactory = ClassFactory.ClassFactory
# "Log on" as system user
......
......@@ -13,7 +13,7 @@
##############################################################################
"""Datatypes for the Zope schema for use with ZConfig."""
import cStringIO
import io
import os
from UserDict import UserDict
import traceback
......@@ -84,7 +84,7 @@ def importable_name(name):
package = __import__(n, g, g, component)
return package
except ImportError:
IO = cStringIO.StringIO()
IO = io.StringIO()
traceback.print_exc(file=IO)
raise ValueError(
'The object named by "%s" could not be imported\n%s' % (
......@@ -222,12 +222,12 @@ class DBTab:
def listMountPaths(self):
"""Returns a sequence of (virtual_mount_path, database_name).
"""
return self.mount_paths.items()
return list(self.mount_paths.items())
def listDatabaseNames(self):
"""Returns a sequence of names.
"""
return self.db_factories.keys()
return list(self.db_factories.keys())
def hasDatabase(self, name):
"""Returns true if name is the name of a configured database."""
......
......@@ -87,9 +87,11 @@ def root_wsgi_handler(cfg):
HTTPRequest.trusted_proxies = tuple(mapped)
# set the maximum number of ConflictError retries
from ZPublisher import HTTPRequest
if cfg.max_conflict_retries:
from ZPublisher import HTTPRequest
HTTPRequest.retry_max_count = cfg.max_conflict_retries
else:
HTTPRequest.retry_max_count = 3
def _name_to_ips(host, _is_ip=re.compile(r'(\d+\.){3}').match):
......
......@@ -13,7 +13,7 @@
##############################################################################
import os
import cStringIO
import io
import tempfile
import unittest
......@@ -41,7 +41,7 @@ class WSGIStartupTestCase(unittest.TestCase):
# We have to create a directory of our own since the existence
# of the directory is checked. This handles this in a
# platform-independent way.
sio = cStringIO.StringIO(
sio = io.BytesIO(
text.replace("<<INSTANCE_HOME>>", TEMPNAME))
os.mkdir(TEMPNAME)
os.mkdir(TEMPVAR)
......@@ -71,7 +71,7 @@ class WSGIStartupTestCase(unittest.TestCase):
NSYNC doesnt
</environment>
""")
items = conf.environment.items()
items = list(conf.environment.items())
items.sort()
self.assertEqual(
items, [("FEARFACTORY", "rocks"), ("NSYNC", "doesnt")])
......
......@@ -12,7 +12,7 @@
#
##############################################################################
import cStringIO
import io
import os
import shutil
import sys
......@@ -53,7 +53,7 @@ class WSGIStarterTestCase(unittest.TestCase):
# We have to create a directory of our own since the existence
# of the directory is checked. This handles this in a
# platform-independent way.
sio = cStringIO.StringIO(
sio = io.BytesIO(
text.replace("<<INSTANCE_HOME>>", self.TEMPNAME))
try:
os.mkdir(self.TEMPNAME)
......
......@@ -185,7 +185,7 @@ def copyskel(sourcedir, targetdir, uid, gid, **replacements):
finally:
os.chdir(pwd)
except (IOError, OSError) as msg:
print >>sys.stderr, msg
print(msg, file=sys.stderr)
sys.exit(1)
......
......@@ -29,10 +29,13 @@ necessary to create a Zope WSGI instance home.
import getopt
import os
import sys
import copyzopeskel
from . import copyzopeskel
if sys.version_info > (3, ):
raw_input = input
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
def main():
......@@ -153,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.')
print
print()
while 1:
skeltarget = raw_input("Directory: ").strip()
if skeltarget == '':
......@@ -169,7 +172,7 @@ def get_inituser():
print('Please choose a username and password for the initial user.')
print('These will be the credentials you use to initially manage')
print('your new Zope instance.')
print
print()
user = raw_input("Username: ").strip()
if user == '':
return None, None
......@@ -199,7 +202,6 @@ def check_buildout(script_path):
"""
buildout_cfg = os.path.join(os.path.dirname(script_path), 'buildout.cfg')
if os.path.exists(buildout_cfg):
from ConfigParser import RawConfigParser
parser = RawConfigParser()
parser.read(buildout_cfg)
return 'zopepy' in parser.sections()
......
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