Commit fc0a6eb0 authored by Jérome Perrin's avatar Jérome Perrin

Merge remote-tracking branch 'upstream/master' into zope4py2

parents 3202fcb0 e0fcd76d
Pipeline #23876 failed with stage
in 0 seconds
......@@ -6,4 +6,4 @@ import string
import random
return str(DateTime().millis()) + '-' + ''.join(random.sample(string.letters+string.digits, random.randint(min_len,max_len)))
return str(DateTime().millis()) + '-' + ''.join(random.sample(string.ascii_letters+string.digits, random.randint(min_len,max_len)))
......@@ -21,7 +21,7 @@ def getSkinHash(skin, skin_container):
content = skin.formXML()
if isinstance(content, unicode):
content = content.encode('utf8', 'repr')
except AttributeError, e:
except AttributeError as e:
# This can happen with dead proxy fields.
content = "broken form %s" % e
content = 'ignore'
......
......@@ -22,7 +22,7 @@ if form_id is not None:
# button itself
try:
form.validate_all_to_request(request)
except FormValidationError, validation_errors:
except FormValidationError as validation_errors:
# Pack errors into the request
field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors)
......
......@@ -112,7 +112,7 @@ for erp5_action_key in erp5_action_dict.keys():
if mode != "allDocs":
return result
result_list += result
except ValueError, e:
except ValueError as e:
try:
error_dict.update(json.loads(str(e)))
except ValueError:
......
......@@ -196,7 +196,7 @@ try:
cell.edit(quantity=total_quantity)
except FormValidationError, validation_errors:
except FormValidationError as validation_errors:
redirect_url = '%s/view?%s' % ( context.absolute_url()
, 'portal_status_message=%s' % localizer.erp5_ui.gettext("input failed.")
)
......
......@@ -27,11 +27,13 @@
#
##############################################################################
import binascii
import zope.interface
from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet, interfaces
from Products.ERP5.Document.Node import Node
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
from Products.ERP5Type.Utils import bytes2str, str2bytes
from erp5.component.mixin.EncryptedPasswordMixin import EncryptedPasswordMixin
from erp5.component.mixin.LoginAccountProviderMixin import LoginAccountProviderMixin
from erp5.component.mixin.ERP5UserMixin import ERP5UserMixin
......@@ -143,9 +145,9 @@ class Person(EncryptedPasswordMixin, Node, LoginAccountProviderMixin, ERP5UserMi
# Encode reference to hex to prevent uppercase/lowercase conflict in
# activity table (when calling countMessageWithTag)
if user_id:
tag = 'set_userid_' + user_id.encode('hex')
tag = 'set_userid_' + bytes2str(binascii.hexlify(str2bytes(user_id)))
else:
tag = 'set_login_' + login.encode('hex')
tag = 'set_userid_' + bytes2str(binascii.hexlify(str2bytes(login)))
# Check that there no existing user
acl_users = getattr(self, 'acl_users', None)
if PluggableAuthService is not None and isinstance(acl_users,
......
......@@ -35,7 +35,7 @@ SVG_DEFAULT_NAMESPACE = "http://www.w3.org/2000/svg"
def getDataURI(url):
try:
data = urllib2.urlopen(url)
except Exception, e:
except Exception as e:
raise ConversionError("Error to transform url (%s) into data uri. ERROR = %s" % (url, Exception(e)))
return 'data:%s;base64,%s' % (data.info()["content-type"],
data.read().encode("base64").replace('\n', ""))
......
return ''.join(random.SystemRandom().sample(string.letters + string.digits, length))
return ''.join(random.SystemRandom().sample(string.ascii_letters + string.digits, length))
......@@ -23,7 +23,7 @@ else:
new_id = person.generateNewId()
try:
default_career.setId(new_id)
except ActivityPendingError, error:
except ActivityPendingError as error:
message = Base_translateString("%s" % error)
return context.Base_redirect(form_id=form_id,
selection_name=selection_name,
......
......@@ -296,7 +296,7 @@ class TestBigFile(ERP5TypeTestCase):
# NOTE this change is automatically reverted back in calling helper
self.assertIsInstance(f._baseGetData._default, str)
self.assertEqual(f._baseGetData._default, '')
f._baseGetData.im_func._default = None # NOTE not possible to do on just f._baseGetData
f._baseGetData.__func__._default = None # NOTE not possible to do on just f._baseGetData
self.assertIs(f._baseGetData._default, None)
self.assertIs(f._baseGetData(), None) # <- oops
......@@ -330,7 +330,7 @@ class TestBigFile(ERP5TypeTestCase):
self.assertEqual(_, '')
# NOTE obtaining getter is not possible via BigFile._baseGetData
g = f._baseGetData.im_func
g = f._baseGetData.__func__
self.assertIsInstance(g._default, str)
self.assertEqual(g._default, '')
......
......@@ -3,4 +3,4 @@
"""
from random import choice
import string
return ''.join([choice(string.letters) for i in range(max_long)])
return ''.join([choice(string.ascii_letters) for i in range(max_long)])
......@@ -14,7 +14,7 @@ if form_id is not None:
# button itself
try:
params = form.validate_all_to_request(request)
except FormValidationError, validation_errors:
except FormValidationError as validation_errors:
# Pack errors into the request
field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors)
......
......@@ -536,7 +536,7 @@ class TestCommerce(ERP5TypeTestCase):
id_string = self.getPortal().Base_generateSessionID()
self.assertEqual(10, len(id_string))
for caracter in id_string:
self.assertTrue(caracter in string.letters)
self.assertTrue(caracter in string.ascii_letters)
id_string = self.getPortal().Base_generateSessionID(max_long=20)
self.assertEqual(20, len(id_string))
......
......@@ -29,7 +29,7 @@ form = getattr(context,form_id)
try:
# Validate
form.validate_all_to_request(request)
except FormValidationError, validation_errors:
except FormValidationError as validation_errors:
# Pack errors into the request
field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors)
......
......@@ -2494,7 +2494,7 @@ class BusinessTemplateMixin(ERP5TypeTestCase, LogInterceptor):
while import_id in template_tool.objectIds():
n = n + 1
import_id = "%s_%s" %(import_id, n)
template_tool.download(url='file:'+template_path, id=import_id)
template_tool.download(url='file://'+template_path, id=import_id)
import_bt = template_tool._getOb(id=import_id)
self.assertFalse(import_bt is None)
self.assertEqual(import_bt.getPortalType(), 'Business Template')
......@@ -5052,7 +5052,7 @@ class TestBusinessTemplate(BusinessTemplateMixin):
bt.export(path=export_dir, local=True)
self.tic()
self.portal.portal_templates.updateBusinessTemplateFromUrl(
download_url='file:/%s' % export_dir)
download_url='file://%s' % export_dir)
finally:
shutil.rmtree(export_dir)
......@@ -5072,7 +5072,7 @@ class TestBusinessTemplate(BusinessTemplateMixin):
bt.export(path=export_dir, local=True)
self.tic()
new_bt = self.portal.portal_templates.updateBusinessTemplateFromUrl(
download_url='file:/%s' % export_dir)
download_url='file://%s' % export_dir)
finally:
shutil.rmtree(export_dir)
......@@ -6379,7 +6379,7 @@ class TestBusinessTemplate(BusinessTemplateMixin):
[os.path.basename(f) for f in
glob.glob('%s/%s/*' % (export_dir, template_item))])
new_bt = self.portal.portal_templates.download(
url='file:/%s' % export_dir)
url='file://%s' % export_dir)
finally:
shutil.rmtree(export_dir)
......@@ -6457,7 +6457,7 @@ class TestBusinessTemplate(BusinessTemplateMixin):
bt.export(path=export_dir, local=True)
self.tic()
new_bt = self.portal.portal_templates.download(
url='file:/%s' % export_dir)
url='file://%s' % export_dir)
finally:
shutil.rmtree(export_dir)
......@@ -6489,7 +6489,7 @@ class TestBusinessTemplate(BusinessTemplateMixin):
bt.export(path=export_dir, local=True)
self.tic()
new_bt = self.portal.portal_templates.download(
url='file:/%s' % export_dir)
url='file://%s' % export_dir)
finally:
shutil.rmtree(export_dir)
......@@ -6526,7 +6526,7 @@ class TestBusinessTemplate(BusinessTemplateMixin):
[os.path.basename(f) for f in
glob.glob('%s/ActionTemplateItem/portal_types/*' % (export_dir, ))])
new_bt = self.portal.portal_templates.download(
url='file:/%s' % export_dir)
url='file://%s' % export_dir)
finally:
shutil.rmtree(export_dir)
......@@ -6568,7 +6568,7 @@ class TestBusinessTemplate(BusinessTemplateMixin):
bt.export(path=export_dir, local=True)
self.tic()
new_bt = self.portal.portal_templates.download(
url='file:/%s' % export_dir)
url='file://%s' % export_dir)
finally:
shutil.rmtree(export_dir)
......
......@@ -100,7 +100,8 @@ class TransactionThread(threading.Thread):
# Login
newSecurityManager(None, portal_value.acl_users.getUser('ERP5TypeTestCase'))
self.payload(portal_value=portal_value)
except Exception as self.exception: # pylint: disable=redefine-in-handler
except Exception as e: # pylint: disable=redefine-in-handler
self.exception = e # pylint: disable=redefine-in-handler
if six.PY2:
self.exception.__traceback__ = sys.exc_info()[2]
......
......@@ -66,10 +66,10 @@ class TestRenderViewAPI(ERP5TypeTestCase):
def test_signature(self):
for field in FieldRegistry.get_field_classes().itervalues(): # pylint: disable=no-value-for-parameter
self.assertEqual(('self', 'value', 'REQUEST', 'render_prefix'),
field.render_view.im_func.func_code.co_varnames)
field.render_view.__func__.func_code.co_varnames)
if field is not ProxyField:
self.assertEqual(('self', 'field', 'value', 'REQUEST'),
field.widget.render_view.im_func.func_code.co_varnames[:4], '%s %s' % (field.widget, field.widget.render_view.im_func.func_code.co_varnames[:4]))
field.widget.render_view.__func__.func_code.co_varnames[:4], '%s %s' % (field.widget, field.widget.render_view.__func__.func_code.co_varnames[:4]))
class TestFloatField(ERP5TypeTestCase):
......
......@@ -2,14 +2,16 @@
Parameters:
value -- field value (string)
REQUEST -- standard REQUEST variable"""
import binascii
from Products.ERP5Type.Utils import bytes2str, str2bytes
portal = context.getPortalObject()
if value:
# Same tag is used as in ERP5 Login _setReference, in order to protect against
# concurrency between Credential Request and ERP5 Login object too
#
# XXX: value.encode('hex') may exceed 'tag' column length (255)...
if context.getPortalObject().portal_activities.countMessageWithTag('set_login_' + value.encode('hex')):
# XXX: hex encoded value may exceed 'tag' column length (255)...
if context.getPortalObject().portal_activities.countMessageWithTag('set_login_' + bytes2str(binascii.hexlify(str2bytes(value)))):
return False
def getRealContext():
......
......@@ -3,6 +3,8 @@ Paramameter list :
reference -- User login is mandatory (String)
default_email_text -- Email is mandatory (String)"""
# create the credential request
import binascii
from Products.ERP5Type.Utils import bytes2str, str2bytes
portal = context.getPortalObject()
module = portal.getDefaultModule(portal_type='Credential Request')
portal_preferences = portal.portal_preferences
......@@ -39,7 +41,7 @@ credential_request = module.newContent(
credential_request.setCategoryList(category_list)
# Same tag is used as in ERP5 Login._setReference, in order to protect against
# concurrency between Credential Request and Person object too
tag = 'set_login_%s' % reference.encode('hex')
tag = 'set_login_%s' % bytes2str(binascii.hexlify(str2bytes(reference)))
credential_request.reindexObject(activate_kw={'tag': tag})
#We attach the current user to the credential request if not anonymous
......
......@@ -280,7 +280,7 @@ class PDFDocument(Image):
'-noframes', '-i', tmp.name]
try:
command_result = Popen(command, stdout=PIPE).communicate()[0]
except OSError, e:
except OSError as e:
if e.errno == errno.ENOENT:
raise ConversionError('pdftohtml was not found')
raise
......@@ -309,7 +309,7 @@ class PDFDocument(Image):
command = ['pdf2djvu', tmp.name]
try:
command_result = Popen(command, stdout=PIPE).communicate()[0]
except OSError, e:
except OSError as e:
if e.errno == errno.ENOENT:
raise ConversionError('pdf2djvu was not found')
raise
......@@ -338,7 +338,7 @@ class PDFDocument(Image):
command = ['pdfinfo', '-meta', '-box', tmp.name]
try:
command_result = Popen(command, stdout=PIPE).communicate()[0]
except OSError, e:
except OSError as e:
if e.errno == errno.ENOENT:
raise ConversionError('pdfinfo was not found')
raise
......
......@@ -8,7 +8,7 @@ try:
return result
if not context.hasBaseData():
error_message = context.Base_translateString("This document is not converted yet.")
except Exception, e:
except Exception as e:
from erp5.component.module.Log import log
log("asStrippedHTML", str(e))
error_message = "%s %s" % (context.Base_translateString("Preview Error:"),
......
......@@ -11,13 +11,13 @@ if context.getExternalProcessingState() not in ('converted', 'empty'):
return context.convertToBaseFormat()
except ConflictError:
raise
except ConversionError, e:
except ConversionError as e:
message = 'Conversion Error: %s' % (str(e) or 'undefined.')
except Fault, e:
except Fault as e:
message = 'XMLFault: %s' % (repr(e) or 'undefined.')
except SocketError, e:
except SocketError as e:
message = 'Socket Error: %s' % (repr(e) or 'undefined.')
except Exception, e:
except Exception as e:
message = 'Problem: %s' % (repr(e) or 'undefined.')
# reach here, then exception was raised, message must be logged in workflow
# do not simply raise but rather change external processing state
......
......@@ -7,9 +7,9 @@ try:
return context.updateBaseMetadata(**kw)
except ConflictError:
raise
except ConversionError, e:
except ConversionError as e:
message = 'Conversion Error: %s' % (str(e) or 'undefined.')
except Exception, e:
except Exception as e:
message = 'Problem: %s' % (repr(e) or 'undefined.')
# reach here, then exception was raised, message must be logged in workflow
......
......@@ -44,7 +44,7 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment
cdict = category_dict.copy()
cdict[base_category] = '/'.join(grouplist[:-i])
category_list.append(cdict)
except RuntimeError,e:
except RuntimeError as e:
log(str(e))
return category_list
......@@ -72,7 +72,7 @@ class DummyMovement(Movement):
parent = self.getParentValue()
if isinstance(parent, DummyDelivery):
self = parent
return DummyDelivery.getSimulationState.im_func(self)
return DummyDelivery.getSimulationState.__func__(self)
def getDeliveryValue(self):
"""
......
......@@ -330,7 +330,7 @@ class EmailReader(ExternalSource):
# This is very sequential and could be improved probably
try:
message_uid_list = self._getMailServer().getMessageUIDList(message_folder=message_folder)
except ValueError, error_message: # Use a better exception here XXX
except ValueError as error_message: # Use a better exception here XXX
message_uid_list = []
# Reduce list size based on asumption of growing sequence of uids
latest_uid = self._latest_uid.get(message_folder, 0)
......
......@@ -67,7 +67,7 @@ class Git(WorkingCopy):
argv = ['git']
try:
return subprocess.Popen(argv + list(args), **kw)
except OSError, e:
except OSError as e:
from zLOG import LOG, WARNING
LOG('Git', WARNING,
'will not work as the executable cannot be executed, perhaps not '
......@@ -117,7 +117,7 @@ class Git(WorkingCopy):
env.update(ERP5_GIT_USERNAME=userpwd[0], ERP5_GIT_PASSWORD=userpwd[1])
try:
return self.git(*args, **kw)
except GitError, e:
except GitError as e:
message = 'Authentication failed'
if message in str(e):
raise GitLoginError(userpwd and message or
......@@ -148,7 +148,7 @@ class Git(WorkingCopy):
local, remote = self.git('rev-parse', '--symbolic-full-name',
'HEAD', '@{u}').splitlines()
remote = remote[:13] == 'refs/remotes/' and remote[13:] or None
except GitError, e:
except GitError as e:
local = e.stdout.splitlines()[0]
remote = None
if local != 'HEAD':
......@@ -293,7 +293,7 @@ class Git(WorkingCopy):
try:
return self.git('show', 'HEAD:' + self.prefix + path,
strip=False, cwd=self.toplevel)
except GitError, e:
except GitError as e:
err = e.args[0]
if ' does not exist in ' in err or ' exists on disk, but not in ' in err:
raise NotVersionedError(path)
......@@ -350,7 +350,7 @@ class Git(WorkingCopy):
push_args = 'push', '--porcelain', remote, '%s:%s' % (src, dst)
try:
self.remote_git(*push_args)
except GitError, e:
except GitError as e:
# first check why we could not push
status = [x for x in e.stdout.splitlines() if x[:1] == '!']
if (len(status) != 1 or
......@@ -365,7 +365,7 @@ class Git(WorkingCopy):
# TODO: solve conflicts on */bt/revision automatically
try:
self.git(merge, '@{u}', env=env)
except GitError, e:
except GitError as e:
# XXX: how to know how it failed ?
try:
self.git(merge, '--abort')
......@@ -377,7 +377,7 @@ class Git(WorkingCopy):
reset += 1
# retry to push everything
self.remote_git(*push_args)
except (GitError, GitLoginError), e:
except (GitError, GitLoginError) as e:
self.git('reset', '--soft', '@{%u}' % reset)
if isinstance(e, GitLoginError):
raise
......
......@@ -145,7 +145,7 @@ class Subversion(WorkingCopy):
try:
return self._getClient().cat(os.path.join(self.working_copy, path),
Revision(opt_revision_kind.base))
except ClientError, e:
except ClientError as e:
if e.args[1][-1][1] in (errno.ENOENT, svn_err.entry_not_found):
raise NotVersionedError(path)
raise
......
......@@ -271,7 +271,7 @@ try:
return Revision(self.client.checkin(path,
log_message=log_message or 'none',
recurse=recurse))
except pysvn.ClientError, error:
except pysvn.ClientError as error:
excep = self.getException()
if excep:
raise excep # pylint: disable=raising-bad-type
......@@ -281,7 +281,7 @@ try:
def update(self, path):
try:
return [Revision(x) for x in self.client.update(path)]
except pysvn.ClientError, error:
except pysvn.ClientError as error:
excep = self.getException()
if excep:
raise excep # pylint: disable=raising-bad-type
......@@ -293,7 +293,7 @@ try:
# Zope, convert the objects.
try:
status_list = [Status(x) for x in self.client.status(path=path, **kw)]
except pysvn.ClientError, error:
except pysvn.ClientError as error:
excep = self.getException()
if excep:
raise excep # pylint: disable=raising-bad-type
......@@ -328,7 +328,7 @@ try:
def log(self, path):
try:
log_list = self.client.log(path)
except pysvn.ClientError, error:
except pysvn.ClientError as error:
if 'path not found' in error.args[0]:
return
excep = self.getException()
......@@ -361,7 +361,7 @@ try:
path = os.path.realpath(path)
try:
entry = self.client.info(path=path)
except pysvn.ClientError, error:
except pysvn.ClientError as error:
excep = self.getException()
if excep:
raise excep # pylint: disable=raising-bad-type
......@@ -381,7 +381,7 @@ try:
def ls(self, path):
try:
dict_list = self.client.ls(url_or_path=path, recurse=False)
except pysvn.ClientError, error:
except pysvn.ClientError as error:
if 'non-existent' in error.args[0]:
return
excep = self.getException()
......
......@@ -269,7 +269,7 @@ class WorkingCopy(Implicit):
try:
with open(os.path.join(self.working_copy, path), 'rU') as f:
text = f.read()
except IOError, e:
except IOError as e:
if e.errno == errno.EISDIR:
return '%s<hr/>%r is a folder!' % (head, path)
if e.errno != errno.ENOENT:
......@@ -369,7 +369,7 @@ class BusinessTemplateWorkingCopy(BusinessTemplateFolder):
try:
try:
file_obj = open(path, 'r+b')
except IOError, e:
except IOError as e:
if e.errno == errno.EISDIR:
shutil.rmtree(path, ignore_errors=True)
elif e.errno != errno.ENOENT:
......
......@@ -3,10 +3,10 @@ from erp5.component.module.SubversionClient import SubversionSSLTrustError, Subv
vcs_tool = context.getVcsTool()
try:
entry_dict = vcs_tool.checkout(context, url)
except SubversionSSLTrustError, error:
except SubversionSSLTrustError as error:
context.REQUEST.set('portal_status_message', 'SSL Certificate was not recognized')
return context.asContext(trust_dict = error.getTrustDict(), caller='info').BusinessTemplate_viewSvnSSLTrustDialog()
except SubversionLoginError, error1 :
except SubversionLoginError as error1 :
context.REQUEST.set('portal_status_message', 'Server needs authentication, no cookie found')
return context.asContext(caller='info', realm = error1.getRealm(), username = vcs_tool.getPreferredUsername()).BusinessTemplate_viewSvnLoginDialog()
return entry_dict
......@@ -52,5 +52,5 @@ try:
modified=commit_dict['modified'],
removed=commit_dict['removed']
)
except Exception, error:
except Exception as error:
return context.BusinessTemplate_handleException(error, script.id, commit_dict)
......@@ -8,7 +8,7 @@ if keep:
try:
new_bt = context.getVcsTool().update(commit_dict['keep'])
except Exception, error:
except Exception as error:
return context.BusinessTemplate_handleException(
error, script.id, commit_dict)
......
......@@ -4,15 +4,15 @@ import json
try:
raise exception
except SubversionSSLTrustError, e:
except SubversionSSLTrustError as e:
message = 'SSL Certificate was not recognized'
kw = dict(trust_dict=e.getTrustDict())
method = 'BusinessTemplate_viewSvnSSLTrustDialog'
except SubversionLoginError, e:
except SubversionLoginError as e:
message = 'Server needs authentication, no cookie found'
kw = dict(realm=e.getRealm(), username=context.getVcsTool().getPreferredUsername())
method = 'BusinessTemplate_viewSvnLoginDialog'
except GitLoginError, e:
except GitLoginError as e:
message = str(e)
kw = dict(remote_url=context.getVcsTool().getRemoteUrl())
method = 'BusinessTemplate_viewGitLoginDialog'
......
......@@ -26,7 +26,7 @@ for path in path_list:
raise
except Unauthorized: # should happen in tricky testERP5Catalog tests only
continue
except Exception, e:
except Exception as e:
exception = e
failed_path_list.append(path)
else:
......
......@@ -26,7 +26,7 @@ for path in path_list:
raise
except Unauthorized: # should happen in tricky testERP5Catalog tests only
continue
except Exception, e:
except Exception as e:
exception = e
failed_path_list.append(path)
else:
......
......@@ -6,7 +6,7 @@ form = getattr(context, form_id)
try:
# Validate
form.validate_all_to_request(request, key_prefix='my_')
except FormValidationError, validation_errors:
except FormValidationError as validation_errors:
# Pack errors into the request
result = {}
result['field_errors'] = {}
......
......@@ -18,7 +18,7 @@ try:
request.set('editable_mode', 1)
form.validate_all_to_request(request)
request.set('editable_mode', editable_mode)
except FormValidationError, validation_errors:
except FormValidationError as validation_errors:
# Pack errors into the request
field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors)
......@@ -69,7 +69,7 @@ try:
context,
doaction_param_list['workflow_action'],
**doaction_param_list)
except ValidationFailed, error_message:
except ValidationFailed as error_message:
if getattr(error_message, 'msg', None):
# use of Message class to store message+mapping+domain
message = error_message.msg
......
......@@ -86,7 +86,7 @@ class InotifyTool(TimerServiceMixin, BaseTool):
p = os.path.join(inode_path, name)
try:
s = os.lstat(p)
except OSError, e:
except OSError as e:
if e.errno != errno.ENOENT:
raise
else:
......
......@@ -985,7 +985,7 @@ class TestInvoiceMixin(TestPackingListMixin):
"""
try:
self.tic()
except RuntimeError, exc:
except RuntimeError as exc:
invoice = sequence.get('invoice')
# check which activities are failing
self.assertTrue(str(exc).startswith('tic is looping forever.'),
......
......@@ -153,7 +153,7 @@ return json.dumps({
try:
getattr(self.portal, method)(json_data, list_error=True)
raise ValueError("No error raised during processing")
except ValueError, e:
except ValueError as e:
self.assertEqual(error, json.loads(str(e)))
def test_call_valid_datetime_format(self):
......@@ -211,6 +211,6 @@ return json.dumps({
try:
getattr(self.portal, method)(json_data, list_error=True)
raise ValueError("No error raised during processing")
except ValueError, e:
except ValueError as e:
self.assertEqual(error, json.loads(str(e)))
......@@ -16,7 +16,7 @@ form = getattr(box, form_id)
try:
# Validate
form.validate_all_to_request(request, key_prefix=form_fields_main_prefix)
except FormValidationError, validation_errors:
except FormValidationError as validation_errors:
# Pack errors into the request
field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors)
......
......@@ -70,11 +70,11 @@ class MailevaSOAPConnector(XMLObject):
try:
response = suds.client.Client(url = self.getProperty('submit_url_string'), transport=authenticated).service.submit(__inject={'msg': maileva_exchange.getRequest()})
maileva_exchange.activate().MailevaExchange_processResponse(response)
except socket.error, e:
except socket.error as e:
if e.errno == socket.errno.ECONNREFUSED:
if runtime_environment:
runtime_environment.edit(max_retry=None)
except Exception, e:
except Exception as e:
maileva_exchange.activate().MailevaExchange_processResponse(str(e), failed = True)
......
......@@ -57,7 +57,7 @@ else:
**imported_line_property_dict)
except ConflictError:
raise
except Exception, error:
except Exception as error:
translated_msg = Message('erp5_ui',
'An error Occurred while creating object: ${error}',
mapping=dict(error=Message('erp5_ui',
......@@ -75,7 +75,7 @@ else:
new_object.edit(**category_dict)
except ConflictError:
raise
except Exception, error:
except Exception as error:
#context.log('category: %s' %category)
translated_msg = Message(
'erp5_ui',
......
......@@ -18,7 +18,7 @@ try:
message_list = template_tool.upgradeSite(bt5_list, dry_run=True,
update_catalog=CATALOG_UPDATABLE)
severity = len(message_list)
except BusinessTemplateUnknownError, error:
except BusinessTemplateUnknownError as error:
severity = -1
detail = str(error)
......
......@@ -54,7 +54,7 @@ class TestRealTimeInventoryAccountingMixin:
self.portal.portal_workflow.doActionFor(document, workflow_method_id)
else:
getattr(document, workflow_method_id)()
except ValidationFailed, error:
except ValidationFailed as error:
self.fail("Transition '%s' on %r should have succeeded (%s)" % \
(workflow_method_id, document,
sorted([m.message for m in error.msg])))
......
......@@ -18,7 +18,7 @@ if user_quantity is None:
"error_message": "Parameter 'user_quantity' is required.",
"password" : None })
password = ''.join(random.choice(string.digits + string.letters) for i in xrange(10))
password = ''.join(random.choice(string.digits + string.ascii_letters) for i in xrange(10))
# check erp5_scalability_test business template is present
configurator = portal.business_configuration_module.default_standard_configuration
......
......@@ -3,4 +3,4 @@
"""
from random import choice
import string
return ''.join([choice(string.letters) for i in range(max_long)])
return ''.join([choice(string.ascii_letters) for i in range(max_long)])
......@@ -33,7 +33,7 @@ try:
# Update basic attributes
context.updateConfiguration(**kw)
context.reindexObject()
except FormValidationError, validation_errors:
except FormValidationError as validation_errors:
# Pack errors into the request
field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors)
......
......@@ -8,7 +8,7 @@ response = container.REQUEST.RESPONSE
start = time.time()
try:
results = context.manage_test(query)
except Exception, e:
except Exception as e:
response.setStatus(500)
try:
response.write(str(e[1]))
......
......@@ -271,7 +271,7 @@ class ERP5ProjectUnitTestDistributor(XMLObject):
if test_node.getValidationState() != 'validated':
try:
test_node.validate()
except Exception, e:
except Exception as e:
LOG('Test Node Validate',ERROR,'%s' %e)
if test_node is None:
test_node = test_node_module.newContent(portal_type="Test Node", title=title, computer_guid=computer_guid,
......
......@@ -128,7 +128,7 @@ class ERP5ScalabilityDistributor(ERP5ProjectUnitTestDistributor, object):
if test_node.getValidationState() != 'validated':
try:
test_node.validate()
except Exception, e:
except Exception as e:
LOG('Test Node Validate',ERROR,'%s' %e)
return test_node
return None
......
......@@ -87,7 +87,7 @@ class IntegrationModule(XMLObject):
return self.getObjectList(id=item)
else:
return self.getObjectList[item]
except ValueError, msg:
except ValueError as msg:
raise KeyError(msg)
security.declareProtected(Permissions.AccessContentsInformation,
......
......@@ -184,7 +184,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate):
# Call the method
try:
url, xml = callRequest(self, method_name, *args, **kw)
except ConnectionError, msg:
except ConnectionError as msg:
if test_mode:
error = msg
url = connection.url
......
......@@ -20,7 +20,7 @@ if context.getLastRequestError() is None:
for obj in object_list:
try:
xml = obj.asXML(debug=True)
except (ValueError, NotImplementedError), msg:
except (ValueError, NotImplementedError) as msg:
error = msg
continue
if not xml:
......
......@@ -47,7 +47,7 @@ from Products.ERP5Type.Core.Workflow import ValidationFailed
from zExceptions import Redirect
try:
transaction.Base_checkConsistency()
except ValidationFailed, error_message:
except ValidationFailed as error_message:
if getattr(error_message, 'msg', None):
# use of Message class to store message+mapping+domain
message = error_message.msg
......
......@@ -240,7 +240,7 @@ class TestListBox(ERP5TypeTestCase):
request['here'] = portal.foo_module
try:
listbox.get_value('default', render_format='list', REQUEST=request)
except UnicodeError, e:
except UnicodeError as e:
self.fail('Rendering failed: %s' % e)
self.assertIn(u"\xe9lisa", listbox.render(REQUEST=request))
......@@ -270,7 +270,7 @@ class TestListBox(ERP5TypeTestCase):
request['here'] = portal.foo_module
try:
listbox.get_value('default', render_format='list', REQUEST=request)
except UnicodeError, e:
except UnicodeError as e:
self.fail('Rendering failed: %s' % e)
self.assertIn(u"\xe9lisa", listbox.render(REQUEST=request))
......@@ -304,7 +304,7 @@ class TestListBox(ERP5TypeTestCase):
request['here'] = portal.foo_module
try:
listbox.get_value('default', render_format='list', REQUEST=request)
except UnicodeError, e:
except UnicodeError as e:
self.fail('Rendering failed: %s' % e)
self.assertIn(u"http://example.com/?\xe9lisa", listbox.render(REQUEST=request))
......@@ -338,7 +338,7 @@ class TestListBox(ERP5TypeTestCase):
request['here'] = portal.foo_module
try:
listbox.get_value('default', render_format='list', REQUEST=request)
except UnicodeError, e:
except UnicodeError as e:
self.fail('Rendering failed: %s' % e)
self.assertIn(u"http://example.com/?\xe9lisa", listbox.render(REQUEST=request))
......@@ -360,7 +360,7 @@ class TestListBox(ERP5TypeTestCase):
listbox.get_value('default', render_format='list', REQUEST=request)
try:
self.commit()
except TypeError, e:
except TypeError as e:
self.fail('Unable to commit transaction: %s' % e)
def test_06_LineFields(self, quiet=0, run=run_all_test):
......
......@@ -36,7 +36,7 @@ def urlread(url, safe_return=0):
import urllib
try:
return urllib.urlopen(url).read()
except IOError, e:
except IOError as e:
if safe_return:
# Return an Selenium test code that will obviously fail. This
# prevent zelenium test run get Stalled.
......
......@@ -36,7 +36,7 @@ try:
user = context.WebSite_createUser(**kwargs)
log(user)
msg = 'Thank you for registering. Your password will be sent to the email address that you provided once your account has been validated by the appropriate department.'
except Exception, e:
except Exception as e:
msg = str(e)
return req.RESPONSE.redirect(context.absolute_url() + '?portal_status_message='+msg)
......@@ -94,14 +94,14 @@ class SFTPConnection:
raise SFTPError("No password or private_key defined")
# Connect
self.conn = SFTPClient.from_transport(self.transport)
except (gaierror, error), msg:
except (gaierror, error) as msg:
raise SFTPError(str(msg) + ' while establishing connection to %s' % (self.url,))
# Go to specified directory
try:
schema.path.rstrip('/')
if len(schema.path):
self.conn.chdir(schema.path)
except IOError, msg:
except IOError as msg:
raise SFTPError(str(msg) + ' while changing to dir -%r-' % (schema.path,))
return self
......@@ -113,7 +113,7 @@ class SFTPConnection:
serialized_data = Binary(str(data))
try:
self.conn.putfo(StringIO(str(serialized_data)), filepath, confirm=confirm)
except error, msg:
except error as msg:
raise SFTPError(str(msg) + ' while writing file %s on %s' % (filepath, path))
def _getFile(self, filepath):
......@@ -125,7 +125,7 @@ class SFTPConnection:
tmp_file = self.conn.file(filepath, 'rb')
tmp_file.seek(0)
return tmp_file.read()
except error, msg:
except error as msg:
raise SFTPError(str(msg) + ' while retrieving file %s from %s' % (filepath, self.url))
def readBinaryFile(self, filepath):
......@@ -149,7 +149,7 @@ class SFTPConnection:
if sort_on:
return [x.filename for x in sorted(self.conn.listdir_attr(path), key=operator.attrgetter(sort_on))]
return self.conn.listdir(path)
except (EOFError, error), msg:
except (EOFError, error) as msg:
raise SFTPError(str(msg) + ' while trying to list %s on %s' % (path, self.url))
def getDirectoryFileList(self, path):
......@@ -160,14 +160,14 @@ class SFTPConnection:
"""Delete the file"""
try:
self.conn.unlink(filepath)
except error, msg:
except error as msg:
raise SFTPError(str(msg) + 'while trying to delete %s on %s' % (filepath, self.url))
def renameFile(self, old_path, new_path):
"""Rename a file"""
try:
self.conn.rename(old_path, new_path)
except error, msg:
except error as msg:
raise SFTPError('%s while trying to rename "%s" to "%s" on %s.' % \
(str(msg), old_path, new_path, self.url))
......
......@@ -156,7 +156,7 @@ class MethodWrapper(object):
def __call__(self, *args, **kw):
try:
return self._method(*args, **kw)
except SOAPpy.Types.faultType, exception:
except SOAPpy.Types.faultType as exception:
raise SOAPWSDLException(*exception())
# SOAPpy says nothing about thread-safeness of parsed WSDL.
......
......@@ -76,4 +76,4 @@ class ActivityBuffer(TM):
def sortKey(self, *ignored):
"""Activities must be finished before databases commit transactions."""
return -1
return chr(0)
......@@ -34,7 +34,7 @@ from Acquisition import aq_parent
# If the sort order below doesn't work, we cannot guarantee the sort key
# used below will actually result in the activity connection being committed
# after the ZODB and Catalog data.
assert None < 0 < '' < (), "Cannot guarantee commit of activities comes after the appropriate data"
assert '' < chr(0) < chr(1) < 'xxx' < chr(255), "Cannot guarantee commit of activities comes after the appropriate data"
manage_addActivityConnectionForm = HTMLFile('dtml/connectionAdd', globals())
......@@ -66,4 +66,4 @@ InitializeClass(ActivityConnection)
class ActivityDB(DB):
_sort_key = (0,)
_sort_key = chr(255)
......@@ -55,10 +55,7 @@ from Products.ERP5 import _dtmldir
from six.moves import xrange
from six.moves import cStringIO as StringIO
from six.moves.urllib.request import pathname2url, urlopen, urlretrieve
try:
from urllib import splittype
except ImportError: # six.PY3
from urllib.parse import splittype
from six.moves.urllib.parse import urlparse
from six.moves import urllib
import re
from xml.dom.minidom import parse
......@@ -385,7 +382,9 @@ class TemplateTool (BaseTool):
if id is None:
id = self.generateNewId()
urltype, path = splittype(url)
parsed_url = urlparse(url)
urltype = parsed_url.scheme
path = parsed_url.path
if WIN and urltype and '\\' in path:
urltype = None
path = url
......@@ -625,7 +624,9 @@ class TemplateTool (BaseTool):
#LOG('updateRepositoryBusiessTemplateList', 0,
# 'repository_list = %r' % (repository_list,))
for repository in repository_list:
urltype, url = splittype(repository)
parsed_url = urlparse(repository)
urltype = parsed_url.scheme
url = parsed_url.path
if WIN and urltype and '\\' in url:
urltype = None
url = repository
......
......@@ -70,7 +70,7 @@ class TransactionalVariable(dict):
_unregistered = True
def sortKey(self):
return None
return ''
commit = tpc_vote = tpc_begin = tpc_abort = lambda self, transaction: None
......@@ -127,7 +127,7 @@ class TransactionalResource(object):
return not (args in tv or tv.add(args))
def sortKey(self):
return 1
return chr(1)
abort = commit = tpc_vote = tpc_begin = tpc_finish = tpc_abort = \
lambda self, transaction: None
......@@ -198,10 +198,10 @@ DCWorkflowDefinition.listObjectActions = ERP5Workflow.__dict__['listObjectAction
from Products.DCWorkflow.Expression import Expression
DCWorkflowDefinition.security.declarePrivate('getWorklistVariableMatchDict')
DCWorkflowDefinition.getWorklistVariableMatchDict = ERP5Workflow.getWorklistVariableMatchDict.im_func
DCWorkflowDefinition.getWorklistVariableMatchDict = ERP5Workflow.getWorklistVariableMatchDict.__func__
DCWorkflowDefinition.security.declarePrivate('isWorkflowMethodSupported')
DCWorkflowDefinition.isWorkflowMethodSupported = ERP5Workflow.isWorkflowMethodSupported.im_func
DCWorkflowDefinition.isWorkflowMethodSupported = ERP5Workflow.isWorkflowMethodSupported.__func__
TransitionDefinition__init__orig = TransitionDefinition.__init__
def TransitionDefinition__init__(self, *args, **kw):
......@@ -421,7 +421,7 @@ def _executeMetaTransition(self, ob, new_state_id):
DCWorkflowDefinition._executeMetaTransition = _executeMetaTransition
DCWorkflowDefinition.wrapWorkflowMethod = ERP5Workflow.wrapWorkflowMethod.im_func
DCWorkflowDefinition.wrapWorkflowMethod = ERP5Workflow.wrapWorkflowMethod.__func__
def StateDefinition_getStatePermissionRoleListDict(self):
if self.permission_roles is None:
......@@ -878,7 +878,7 @@ def method_getGuardExpressionInstance(self):
return self.guard.expr
def method_checkGuard(self, *args, **kwargs):
return ERP5Guardable.checkGuard.im_func(self, *args, **kwargs)
return ERP5Guardable.checkGuard.__func__(self, *args, **kwargs)
def method_getAction(self):
return self.actbox_url
......@@ -1207,9 +1207,9 @@ DCWorkflowDefinition.getTitle = method_getTitle
DCWorkflowDefinition.getDescription = method_getDescription
DCWorkflowDefinition.isManagerBypass = lambda self: self.manager_bypass
DCWorkflowDefinition.getSourceValue = DCWorkflowDefinition_getSourceValue
DCWorkflowDefinition.notifyWorkflowMethod = ERP5Workflow.notifyWorkflowMethod.im_func
DCWorkflowDefinition.notifyBefore = ERP5Workflow.notifyBefore.im_func
DCWorkflowDefinition.notifySuccess = ERP5Workflow.notifySuccess.im_func
DCWorkflowDefinition.notifyWorkflowMethod = ERP5Workflow.notifyWorkflowMethod.__func__
DCWorkflowDefinition.notifyBefore = ERP5Workflow.notifyBefore.__func__
DCWorkflowDefinition.notifySuccess = ERP5Workflow.notifySuccess.__func__
DCWorkflowDefinition.getVariableValueDict = DCWorkflowDefinition_getVariableValueDict
DCWorkflowDefinition.getVariableValueByReference = DCWorkflowDefinition_getVariableValueByReference
DCWorkflowDefinition.getStateValueByReference = DCWorkflowDefinition_getStateValueByReference
......
......@@ -29,3 +29,6 @@ def TM__register(self):
#except: pass
TM._register = TM__register
# sortKey should return str in transaction 1.4.1 or later.
TM._sort_key = '1'
......@@ -64,7 +64,7 @@ from Products.PythonScripts.PythonScript import PythonScript
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
from Products.ERP5Form.PreferenceTool import Priority
from zLOG import LOG, DEBUG
from Products.ERP5Type.Utils import convertToUpperCase
from Products.ERP5Type.Utils import convertToUpperCase, str2bytes
from Products.ERP5Type.tests.backportUnittest import SetupSiteError
from Products.ERP5Type.tests.utils import addUserToDeveloperRole
from Products.ERP5Type.tests.utils import parseListeningAddress
......@@ -251,7 +251,7 @@ class ERP5TypeTestCaseMixin(ProcessingNodeTestCase, PortalTestCase):
def newPassword(self):
""" Generate a password """
return ''.join(random.SystemRandom().sample(string.letters + string.digits, 20))
return ''.join(random.SystemRandom().sample(string.ascii_letters + string.digits, 20))
def login(self, user_name='ERP5TypeTestCase', quiet=0):
"""
......@@ -596,17 +596,18 @@ class ERP5TypeTestCaseMixin(ProcessingNodeTestCase, PortalTestCase):
bt5_path_list += [os.path.join(path, "*") for path in bt5_path_list]
def search(path, template):
urltype, url = urllib.splittype(path + '/' + template)
if urltype == 'http':
host, selector = urllib.splithost(url)
user_passwd, host = urllib.splituser(host)
host = urllib.unquote(host)
h = httplib.HTTP(host)
parsed_url = six.moves.urllib.parse.urlparse(path + '/' + template)
if parsed_url.scheme == 'http':
user = parsed_url.username
password = parsed_url.password
host = parsed_url.hostname
selector = parsed_url.path
h = http_client.HTTP(host)
h.putrequest('HEAD', selector)
h.putheader('Host', host)
if user_passwd:
if user and passwd:
h.putheader('Authorization',
'Basic %s' % base64.b64encode(user_passwd).strip())
'Basic %s' % base64.b64encode(str2bytes('%s:%s' % (user, passwd))).strip())
h.endheaders()
errcode, errmsg, headers = h.getreply()
if errcode == 200:
......@@ -1354,7 +1355,7 @@ class ERP5TypeCommandLineTestCase(ERP5TypeTestCaseMixin):
sql = kw.get('erp5_sql_connection_string')
if sql:
app[portal_name]._setProperty('erp5_site_global_id',
base64.standard_b64encode(sql))
base64.standard_b64encode(str2bytes(sql)))
if not quiet:
ZopeTestCase._print('done (%.3fs)\n' % (time.time() - _start))
# Release locks
......
......@@ -75,7 +75,7 @@ def patchActivityTool():
def __init__(self, ob):
self._ob = ob
def __getattr__(self, attr):
m = getattr(self._ob, attr).im_func
m = getattr(self._ob, attr).__func__
return lambda *args, **kw: m(self, *args, **kw)
@patch
def manage_setDistributingNode(self, distributingNode, REQUEST=None):
......
......@@ -78,12 +78,18 @@ class Python3StyleTest(ERP5TypeTestCase):
def test_applyFixApplied(self):
self._testFixer('apply')
def test_exceptFixApplied(self):
self._testFixer('except')
def test_hasKeyFixApplied(self):
self._testFixer('has_key')
def test_importFixApplied(self):
self._testFixer('import')
def test_methodattrsFixApplied(self):
self._testFixer('methodattrs')
def test_numliteralsFixApplied(self):
self._testFixer('numliterals')
......
......@@ -285,8 +285,8 @@ class TestERP5Type(ERP5TypeTestCase, LogInterceptor):
def test_objectValues(self):
person = self.portal.person_module.newContent(portal_type='Person')
createZODBPythonScript(person, 'script', '', '')
script = person['script']
createZODBPythonScript(person, 'test_script', '', '')
script = person['test_script']
self.assertIn(script, person.objectValues())
self.assertNotIn(script, person.objectValues(portal_type='Person'))
......
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