Commit a7d4459c authored by Kazuhiko Shiozaki's avatar Kazuhiko Shiozaki

fixup! py2/py3: Make Products code compatible with both python2 and python3.

parent 489b50e3
......@@ -121,7 +121,7 @@ class URLOpener(FancyURLopener):
if data is not None:
h.send(data + '\r\n')
errcode, errmsg, headers = h.getreply()
if headers and headers.has_key('set-cookie'):
if headers and 'set-cookie' in headers:
cookies = headers.getallmatchingheaders('set-cookie')
for cookie in cookies: self.cookies.load(cookie)
......@@ -147,13 +147,15 @@ class Checker(URLOpener):
while thread.isAlive():
sleep(0.5)
print "Connection to %s went fine" % url
except IOError, (errno, strerror):
except IOError as err:
(errno, strerror) = err.args
print "Can't connect to %s because of I/O error(%s): %s" % (url, errno, strerror)
def SearchUrl(self, url=None):
try:
conn = self.open_http(url)
except IOError, (errno, strerror):
except IOError as err:
(errno, strerror) = err.args
print "Can't connect to %s because of I/O error(%s): %s" % (url, errno, strerror)
......
......@@ -128,7 +128,7 @@ class TestXHTMLMixin(ERP5TypeTestCase):
yield field
except Exception:
yield field
except AttributeError, e:
except AttributeError as e:
ZopeTestCase._print("%s is broken: %s" % (form_path, e))
def test_deadProxyFields(self):
......@@ -245,7 +245,7 @@ class TestXHTMLMixin(ERP5TypeTestCase):
try:
stdout, stderr = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE,
close_fds=True).communicate(body)
except OSError, e:
except OSError as e:
e.strerror += '\n%r' % os.environ
raise
if stdout:
......
......@@ -484,7 +484,7 @@ class TestFormPrintoutAsODT(TestFormPrintoutMixin):
last_row = odf_table_rows[-1]
last_row_columns = last_row.getchildren()
span_attribute = "{%s}number-columns-spanned" % content.nsmap['table']
self.assertFalse(first_row_columns[0].attrib.has_key(span_attribute))
self.assertFalse(span_attribute in first_row_columns[0].attrib)
self.assertEqual(int(last_row_columns[0].attrib[span_attribute]), 2)
self._validate(odf_document)
......@@ -637,7 +637,7 @@ class TestFormPrintoutAsODT(TestFormPrintoutMixin):
first_row_columns = first_row.getchildren()
date_column = first_row_columns[3]
date_value_attrib = "{%s}date-value" % content.nsmap['office']
self.assertTrue(date_column.attrib.has_key(date_value_attrib))
self.assertTrue(date_value_attrib in date_column.attrib)
self.assertEqual(date_column.attrib[date_value_attrib], '2009-04-20')
self._validate(odf_document)
......
......@@ -29,7 +29,7 @@
import os
import unittest
from cStringIO import StringIO
from six.moves import cStringIO as StringIO
from zipfile import ZipFile
from Products.ERP5Type.tests.utils import FileUpload
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
......
......@@ -65,17 +65,17 @@ class TestOOoImportMixin(ERP5TypeTestCase):
gender_bc = self.gender_base_cat_id
if gender_bc not in portal_categories.objectIds():
portal_categories.newContent(portal_type='Base Category', id=gender_bc)
if not portal_categories[gender_bc].has_key('male'):
if 'male' not in portal_categories[gender_bc]:
portal_categories[gender_bc].newContent(id='male', portal_type='Category', title='Male')
if not portal_categories[gender_bc].has_key('female'):
if 'female' not in portal_categories[gender_bc]:
portal_categories[gender_bc].newContent(id='female', portal_type='Category', title='Female')
function_bc = self.function_base_cat_id
if function_bc not in portal_categories.objectIds():
portal_categories.newContent(portal_type='Base Category', id=function_bc)
if not portal_categories[function_bc].has_key('director'):
if 'director' not in portal_categories[function_bc]:
portal_categories[function_bc].newContent(id='director', portal_type='Category', title='Director')
if not portal_categories[function_bc].has_key('manager'):
if 'manager' not in portal_categories[function_bc]:
portal_categories[function_bc].newContent(id='manager', portal_type='Category', title='Manager')
self.portal.portal_caches.clearCache()
......@@ -821,7 +821,7 @@ class TestOOoImport(TestOOoImportMixin):
try:
self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping(
import_file=import_file)
except ValueError, error:
except ValueError as error:
# 'france' is the duplicate ID in this spreadsheet
self.assertTrue('france' in str(error), str(error))
else:
......@@ -850,7 +850,7 @@ class TestOOoImport(TestOOoImportMixin):
try:
self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping(
import_file=import_file)
except ValueError, error:
except ValueError as error:
# 'wrong_hierarchy' is the ID of the category where the problem happens
self.assertTrue('wrong_hierarchy' in str(error), str(error))
else:
......@@ -864,7 +864,7 @@ class TestOOoImport(TestOOoImportMixin):
try:
self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping(
import_file=import_file)
except ValueError, error:
except ValueError as error:
self.assertTrue('More that one path is defined' in str(error), str(error))
else:
self.fail('ValueError not raised')
......
......@@ -141,7 +141,7 @@ def DCWorkflowDefinition_listGlobalActions(self, info):
# Patch to automatically filter workflists per portal type
# so that the same state can be used for different
# worklists and they are not merged
if not dict.has_key('portal_type'):
if 'portal_type' not in dict:
dict['portal_type'] = portal_type_list
# Patch for ERP5 by JP Smets in order
# to implement worklists and search of local roles
......@@ -255,11 +255,11 @@ def DCWorkflowDefinition_executeTransition(self, ob, tdef=None, kwargs=None):
try:
#LOG('_executeTransition', 0, "script = %s, sci = %s" % (repr(script), repr(sci)))
script(sci) # May throw an exception.
except ValidationFailed, validation_exc:
except ValidationFailed as validation_exc:
before_script_success = 0
before_script_error_message = deepcopy(validation_exc.msg)
validation_exc_traceback = sys.exc_traceback
except ObjectMoved, moved_exc:
except ObjectMoved as moved_exc:
ob = moved_exc.getNewObject()
# Re-raise after transition
......@@ -274,11 +274,11 @@ def DCWorkflowDefinition_executeTransition(self, ob, tdef=None, kwargs=None):
if not vdef.for_status:
continue
expr = None
if state_values.has_key(id):
if id in state_values:
value = state_values[id]
elif tdef_exprs.has_key(id):
elif id in tdef_exprs:
expr = tdef_exprs[id]
elif not vdef.update_always and former_status.has_key(id):
elif not vdef.update_always and id in former_status:
# Preserve former value
value = former_status[id]
else:
......@@ -387,11 +387,11 @@ def _executeMetaTransition(self, ob, new_state_id):
if not vdef.for_status:
continue
expr = None
if state_values.has_key(id):
if id in state_values:
value = state_values[id]
elif tdef_exprs.has_key(id):
elif id in tdef_exprs:
expr = tdef_exprs[id]
elif not vdef.update_always and former_status.has_key(id):
elif not vdef.update_always and id in former_status:
# Preserve former value
value = former_status[id]
else:
......
......@@ -141,7 +141,7 @@ class WorkflowMethod( Method ):
# No workflow tool found.
try:
res = self._m(instance, *args, **kw)
except ObjectDeleted, ex:
except ObjectDeleted as ex:
res = ex.getResult()
else:
if hasattr(aq_base(instance), 'reindexObject'):
......
......@@ -29,7 +29,7 @@ if 1: # For easy diff with original
else:
v=expr(md)
except (KeyError, NameError):
if args.has_key('optional') and args['optional']:
if 'optional' in args and args['optional']:
return ''
raise ValueError('Missing input variable, <em>%s</em>' % name)
......@@ -80,7 +80,7 @@ if 1: # For easy diff with original
vs.append(v)
if not vs and t=='nb':
if args.has_key('optional') and args['optional']:
if 'optional' in args and args['optional']:
return ''
else:
raise ValueError(
......
......@@ -474,7 +474,7 @@ class ERP5TypeFunctionalTestCase(ERP5TypeTestCase):
error = []
try:
iframe = self.runner.test(debug=debug)
except TimeoutError, e:
except TimeoutError as e:
error.append(repr(e))
try:
self.tic()
......
......@@ -21,7 +21,7 @@ import traceback
import urllib
import ConfigParser
from contextlib import contextmanager
from cStringIO import StringIO
from six.moves import cStringIO as StringIO
from cPickle import dumps
from glob import glob
from hashlib import md5
......@@ -1558,7 +1558,7 @@ class ZEOServerTestCase(ERP5TypeTestCase):
try:
self.zeo_server = StorageServer(host_port, storage)
break
except socket.error, e:
except socket.error as e:
if e[0] != errno.EADDRINUSE:
raise
if zeo_client:
......
......@@ -32,7 +32,7 @@ class ERP5TypeTestSuite(TestSuite):
if self.log_directory:
args = ('--log_directory', self.getLogDirectoryPath(*args, **kw), ) + args
if self.__dict__.has_key("bt5_path"):
if "bt5_path" in self.__dict__:
args = ("--bt5_path=%s" % self.bt5_path,) + args
instance_number = self.instance or 1
if self.zserver_address_list:
......@@ -71,7 +71,7 @@ class ERP5TypeTestSuite(TestSuite):
+ ('--verbose', '--erp5_sql_connection_string=' + mysql_db_list[0]) \
+ args
status_dict = self.spawn(*args, **kw)
except SubprocessError, e:
except SubprocessError as e:
status_dict = e.status_dict
test_log = status_dict['stderr']
search = self.RUN_RE.search(test_log)
......@@ -157,7 +157,7 @@ class SavedTestSuite(ERP5TypeTestSuite):
return super(SavedTestSuite, self).getLogDirectoryPath(*args, **kw)
def __runUnitTest(self, *args, **kw):
if self.__dict__.has_key("bt5_path"):
if "bt5_path" in self.__dict__:
args = ("--bt5_path=%s" % self.bt5_path,) + args
return super(SavedTestSuite, self).runUnitTest(
'--portal_id=' + self._portal_id,
......
......@@ -319,7 +319,7 @@ class ProcessingNodeTestCase(ZopeTestCase.TestCase):
error_message = 'tic is looping forever. '
try:
self.assertNoPendingMessage()
except AssertionError, e:
except AssertionError as e:
error_message += str(e)
raise RuntimeError(error_message)
# This give some time between messages
......
......@@ -30,7 +30,7 @@
import os, sys
import unittest
from subprocess import check_output, CalledProcessError
from cStringIO import StringIO
from six.moves import cStringIO as StringIO
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from lib2to3.main import main
......
......@@ -787,7 +787,7 @@ def main(argument_list=None):
"log_directory=",
"with_wendelin_core"
])
except getopt.GetoptError, msg:
except getopt.GetoptError as msg:
usage(sys.stderr, msg)
sys.exit(2)
......
......@@ -2782,7 +2782,7 @@ class TestGC(XMLObject):
import gc
initial_gc_debug_flags = gc.get_debug()
initial_stderr = sys.stderr
from cStringIO import StringIO
from six.moves import cStringIO as StringIO
stderr = StringIO()
try:
gc.disable()
......
......@@ -399,7 +399,7 @@ def createZServer(log=os.devnull, zserver_type='http'):
hs.__init__(ip, port, resolver=None, logger_object=lg)
hs.install_handler(zhandler_class(module='Zope2', uri_base=''))
return hs
except socket.error, e:
except socket.error as e:
if e[0] != errno.EADDRINUSE:
raise
hs.close()
......
......@@ -22,13 +22,13 @@ class TestField:
return "utf-8"
def has_value(self, id):
return self.kw.has_key(id)
return id in self.kw
class ValidatorTestCase(unittest.TestCase):
def assertValidatorRaises(self, exception, error_key, f, *args, **kw):
try:
apply(f, args, kw)
except exception, e:
except exception as e:
if hasattr(e, 'error_key') and e.error_key != error_key:
self.fail('Got wrong error. Expected %s received %s' %
(error_key, e))
......
......@@ -211,14 +211,14 @@ class SerializeTestCase(unittest.TestCase):
try:
form.validate_all(request)
self.fail('form should fail in validation')
except FormValidationError, e:
except FormValidationError as e:
self.assertEqual(1, len(e.errors))
text1 = e.errors[0].error_text
try:
form2.validate_all(request)
self.fail('form2 should fail in validation')
except FormValidationError, e:
except FormValidationError as e:
self.assertEqual(1, len(e.errors))
text2 = e.errors[0].error_text
......@@ -344,7 +344,7 @@ class SerializeTestCase(unittest.TestCase):
})
empty_field.manage_edit(REQUEST=request)
except ValidationError, e:
except ValidationError as e:
self.fail('error when editing field %s; error message: %s' %
(e.field_id, e.error_text) )
......@@ -400,14 +400,14 @@ class SerializeTestCase(unittest.TestCase):
request['field_empty_field'] = ''
try:
result1 = form.validate_all(request)
except FormValidationError, e:
except FormValidationError as e:
# XXX only render first error ...
self.fail('error when editing form1, field %s; error message: %s' %
(e.errors[0].field_id, e.errors[0].error_text) )
try:
result2 = form2.validate_all(request)
except FormValidationError, e:
except FormValidationError as e:
# XXX only render first error ...
self.fail('error when editing form1, field %s; error message: %s' %
(e.errors[0].field_id, e.errors[0].error_text) )
......
......@@ -99,7 +99,7 @@ class HBTreeFolder2Tests(ERP5TypeTestCase):
def testHasKey(self):
self.assert_(self.f.hasObject('item')) # Old spelling
self.assert_(self.f.has_key('item')) # New spelling
self.assert_('item' in self.f) # New spelling
def testDelete(self):
self.f._delOb('item')
......@@ -117,7 +117,7 @@ class HBTreeFolder2Tests(ERP5TypeTestCase):
def testSetObject(self):
f2 = HBTreeFolder2('item2')
self.f._setObject(f2.id, f2)
self.assert_(self.f.has_key('item2'))
self.assert_('item2' in self.f)
self.assertEqual(self.f.objectCount(), 2)
def testWrapped(self):
......@@ -153,7 +153,7 @@ class HBTreeFolder2Tests(ERP5TypeTestCase):
old_f._setObject(inner_f.id, inner_f)
self.ff._populateFromFolder(old_f)
self.assertEqual(self.ff.objectCount(), 1)
self.assert_(self.ff.has_key('inner'))
self.assert_('inner' in self.ff)
self.assertEqual(self.getBase(self.ff._getOb('inner')), inner_f)
def testObjectListing(self):
......
......@@ -127,7 +127,7 @@ else:
from zExceptions import Redirect
try:
self.assertRaises(self.ob.fake_skin.test.manage_workspace(self.r))
except Redirect,r:
except Redirect as r:
# this may appear to be incorrect, but http://foo/test_mt
# is what we set as REQUEST['URL1']
self.assertEqual(r.args,('http://foo/test_mt/manage_main',))
......
......@@ -14,7 +14,7 @@ except ImportError:
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.SecurityManagement import noSecurityManager
from AccessControl.User import system as SystemUser, SimpleUser
from cStringIO import StringIO
from six.moves import cStringIO as StringIO
from difflib import unified_diff
from Products.MailHost.MailHost import MailHost
from Testing.makerequest import makerequest
......@@ -325,7 +325,7 @@ class TestMailTemplate(TestCase):
from zExceptions import Redirect
try:
self.assertRaises(self.mt.manage_workspace(self.r))
except Redirect,r:
except Redirect as r:
# this may appear to be incorrect, but http://foo/test_mt
# is what we set as REQUEST['URL1']
self.assertEqual(r.args,('http://foo/test_mt/pt_editForm',))
......@@ -378,7 +378,7 @@ class TestMailTemplate(TestCase):
self.test_add('Test Body')
try:
self.mt.send(**params)
except TypeError,e:
except TypeError as e:
self.assertEqual(e.args[0],error)
else:
self.fail('Mail sent even though params missing')
......
......@@ -163,7 +163,7 @@ class StrippingParser( SGMLParser ):
def handle_entityref(self, name):
if self.entitydefs.has_key(name):
if name in self.entitydefs:
x = ';'
else:
# this breaks unstandard entities that end with ';'
......@@ -175,7 +175,7 @@ class StrippingParser( SGMLParser ):
""" Delete all tags except for legal ones.
"""
if VALID_TAGS.has_key(tag):
if tag in VALID_TAGS:
self.result = self.result + '<' + tag
......
......@@ -64,13 +64,11 @@ class Parser:
msg, self.raw[self.lines[line]:]))
self.out.write('\n</pre>\n')
def __call__(self, toktype, toktext, (srow,scol), (erow,ecol), line):
def __call__(self, toktype, toktext, sx, ex, line):
""" Token handler.
"""
#print "type", toktype, token.tok_name[toktype], "text", toktext,
#print "start", srow,scol, "end", erow,ecol, "<br>"
## calculate new positions
(srow, scol) = sx
(erow, ecol) = ex
oldpos = self.pos
newpos = self.lines[srow] + scol
self.pos = newpos + len(toktext)
......
......@@ -136,7 +136,7 @@ class TestDeferredConnection(ERP5TypeTestCase):
try:
try:
self.commit()
except OperationalError, m:
except OperationalError as m:
if m[0] not in hosed_connection:
raise
else:
......
......@@ -10,7 +10,7 @@ import re
import getopt
import glob
import cgi
import six.moves import .urllib
from six.moves import urllib
import multifile
if six.PY2:
from email import message_from_file as message_from_bytes
......
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