Commit aec66a49 authored by Arnaud Fontaine's avatar Arnaud Fontaine

WIP: 2to3.

parent 33f41220
......@@ -26,9 +26,9 @@ informations = { 'processing': processing,
if informations['processing'] in ['converted', 'conversion_failed','empty']:
informations['permanent_url'] = document.Document_getPermanentUrl()
print dumps(informations) #print info before del object
print(dumps(informations)) #print info before del object
portal.portal_sessions.manage_delObjects(reference)
else:
print dumps(informations)
print(dumps(informations))
return printed
......@@ -6,7 +6,7 @@
website = context.getWebSiteValue()
REQUEST = context.REQUEST
if REQUEST.has_key('portal_skin'):
if 'portal_skin' in REQUEST:
context.portal_skins.clearSkinCookie()
#XXX get cookie name from key authentication plugin
......
......@@ -31,10 +31,10 @@ from ZPublisher.HTTPRequest import HTTPRequest
from ZPublisher.HTTPResponse import HTTPResponse
from Products.PluggableAuthService.interfaces.plugins import IAuthenticationPlugin
from DateTime import DateTime
import urllib
import httplib
import urllib.request, urllib.parse, urllib.error
import http.client
import base64
import StringIO
import io
import mock
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Security.ERP5DumbHTTPExtractionPlugin import ERP5DumbHTTPExtractionPlugin
......@@ -140,10 +140,10 @@ class TestERP5AccessTokenSkins(AccessTokenTestCase):
response = self.publish('/%s/Base_getUserCaption?%s' % (
self.portal.getId(),
urllib.urlencode({
urllib.parse.urlencode({
'access_token': access_token.getId(),
'access_token_secret': access_token.getReference()})))
self.assertEqual(response.getStatus(), httplib.OK)
self.assertEqual(response.getStatus(), http.client.OK)
# XXX caption currently shows plugin id and relative URL of the token,
# that's not ideal.
self.assertEqual(
......@@ -438,7 +438,7 @@ class TestERP5DumbHTTPExtractionPlugin(AccessTokenTestCase):
env['GATEWAY_INTERFACE']='CGI/1.1 '
env['SCRIPT_NAME']='Main'
env.update(headers)
return HTTPRequest(StringIO.StringIO(), env, HTTPResponse())
return HTTPRequest(io.StringIO(), env, HTTPResponse())
def test_working_authentication(self):
request = self.do_fake_request("GET", {"HTTP_AUTHORIZATION": "Basic " + base64.b64encode("login:password")})
......
......@@ -26,7 +26,8 @@
#
##############################################################################
from UserDict import UserDict
from collections import UserDict
from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet
......
......@@ -20,7 +20,7 @@ def getSubFieldDict():
item_key = '/'.join(item_split[:split_depth])
# Create a new subfield if necessary
if not sub_field_dict.has_key(item_key):
if item_key not in sub_field_dict:
# Create property dict (key are field parameters)
sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key
......@@ -45,7 +45,7 @@ def getSubFieldDict():
# Those cached dictionnaries are later modified, we just reset the 'value'
# key to return clean dictionnaries.
sub_field_dict = getSubFieldDictCache()
for k in sub_field_dict.keys():
for k in list(sub_field_dict.keys()):
sub_field_dict[k]['value'] = None
return sub_field_dict
......@@ -57,7 +57,7 @@ for item_value in value_list:
item_split = item_value.split('/')
item_key = '/'.join(item_split[:split_depth])
if not sub_field_dict.has_key(item_key):
if item_key not in sub_field_dict:
# This can only happens if an accounting plan have been uninstalled
sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key
......@@ -72,4 +72,4 @@ for item_value in value_list:
sub_field_dict[item_key]['value'] = item_value
# Return the list of subfield configuration.
return sub_field_dict.values()
return list(sub_field_dict.values())
......@@ -4,6 +4,7 @@ The id of the line is used to filter the list, unless `omit_filter` is true.
If `mirror` is set to a true value, the list will be filtered for the mirror
node.
"""
from past.builtins import cmp
from Products.ERP5Type.Cache import CachingMethod
from AccessControl import getSecurityManager
......
......@@ -118,7 +118,7 @@ for brain in portal.portal_simulation.getMovementHistoryList(
if by_mirror_section_list_dict:
for row in portal_catalog(
select_list=['title'],
uid=by_mirror_section_list_dict.keys(),
uid=list(by_mirror_section_list_dict.keys()),
):
title = row.title
for line in by_mirror_section_list_dict[row.uid]:
......
......@@ -15,4 +15,4 @@ for accounting_transaction in [context] + context.getCausalityValueList(
if related_causality.getSimulationState() not in ('cancelled', 'deleted'):
accounting_transaction_set[related_causality] = 1
return accounting_transaction_set.keys()
return list(accounting_transaction_set.keys())
......@@ -35,7 +35,7 @@ search_params = dict(
for brain in portal.portal_simulation.getInventoryList(**search_params):
if round(brain.total_price, precision) == 0:
print '%s has a 0 balance but some not grouped transactions.' % brain.mirror_section_relative_url
print('%s has a 0 balance but some not grouped transactions.' % brain.mirror_section_relative_url)
if fixit:
tr = brain.getObject().getParentValue()
grouped_line_list = tr.AccountingTransaction_guessGroupedLines()
......@@ -51,9 +51,9 @@ for brain in portal.portal_simulation.getInventoryList(**search_params):
portal_type=portal.getPortalAccountingMovementTypeList(),
grouping_reference=None,) if not line.getObject().getGroupingReference()])
if grouped_line_list:
print 'FIXED', grouped_line_list
print('FIXED', grouped_line_list)
else:
print 'NOT FIXED'
print('NOT FIXED')
active_result = ActiveResult(
summary=context.getTitle(),
......
......@@ -78,7 +78,7 @@ for property_dict in object_list:
gap = str(gap)
if gap:
gap = gap.replace('CLASSE ', '')
print '+ %s - %s - %s' % (gap or '', title or '', description or '')
print('+ %s - %s - %s' % (gap or '', title or '', description or ''))
path = root
b = ''
for a in gap:
......@@ -96,7 +96,7 @@ for path in existing_path_list:
description = document.getDescription() or ''
gap = document.getId() or ''
title = document.getTitle() or ''
print '- %s - %s - %s' % (gap or '', title or '', description or '')
print('- %s - %s - %s' % (gap or '', title or '', description or ''))
document.getParentValue().deleteContent(document.getId())
return printed
......@@ -30,7 +30,7 @@
"""
from StringIO import StringIO
from io import StringIO
import lxml
from DateTime import DateTime
......
......@@ -7,7 +7,7 @@ for cat in category_list:
cat.getObject().setId(newid)
except:
pass
print newid
print(newid)
print 'Categories Renamed'
print('Categories Renamed')
return printed
......@@ -7,7 +7,7 @@ for cat in category_list:
cat.getObject().setId(newid)
except:
pass
print newid
print(newid)
print 'Categories Renamed'
print('Categories Renamed')
return printed
from cStringIO import StringIO
from io import StringIO
import zipfile
from Products.ERP5Type.Message import translateString
......
......@@ -8,7 +8,7 @@ if same_type(cell_value, 0) or same_type(cell_value, 0.0) :
negative = number < 0
amount = str(abs(number))
indexes = range(len(amount))
indexes = list(range(len(amount)))
indexes.reverse()
string = ''
count = 0
......
......@@ -34,7 +34,7 @@ import unittest
import zipfile
import email
import os.path
from cStringIO import StringIO
from io import StringIO
from DateTime import DateTime
from lxml import etree
......
......@@ -17,7 +17,7 @@ def getAccountsForGap(gap_id):
return GAP.restrictedTraverse(gap_id).getGapRelatedValueList(portal_type='Account')
def getUniqueGapList(accounts_list):
return dict([ (x.getGap(),True) for x in accounts_list]).keys()
return list(dict([ (x.getGap(),True) for x in accounts_list]).keys())
def getCell(row_number=1):
return '%s%d'%(ooo_struct['rows'][row_number-1], ooo_struct['line'])
......
......@@ -19,6 +19,7 @@ return a list of dictionnaries like that :
}
"""
from past.builtins import cmp
request = context.REQUEST
at_date = request['at_date']
transaction_section_category = request['transaction_section_category']
......
......@@ -48,7 +48,7 @@ dane.p59=dane.p55-dane.p56
if debug:
for f in range(20,60):
n='p'+str(f)
print n,getattr(dane,n)
print(n,getattr(dane,n))
return printed
return container[report].index_html(REQUEST=context.REQUEST, RESPONSE=context.REQUEST.RESPONSE,dane=dane)
......@@ -5,7 +5,7 @@ Warning: Before using this script as zope, edit account_workflow and give Manage
#This script will REMOVE any existing accounts!!!
#comment following if you are sure
print 'Nothing done!'
print('Nothing done!')
return printed
......@@ -22,7 +22,7 @@ for category in gap_root.getCategoryMemberValueList():
acc = account_module.newContent(title='%s %s' % (category.getId(),category.getTitle()),\
gap_value = category)
acc.validate()
print 'acc created'
print('acc created')
return printed
......@@ -251,7 +251,7 @@ for line in gap_text.splitlines():
cpath += n
path.append(cpath)
parent = gap.restrictedTraverse('/'.join(path))
print 'Added to ',parent
print('Added to ',parent)
parent.newContent(id=num, title=descr)
......
......@@ -6,7 +6,7 @@ section_title = 'My Organisation'
portal = context.getPortalObject()
accounting_module = portal.accounting_module
year = 2005
default_date = DateTime(year, 01, 01)
default_date = DateTime(year, 0o1, 0o1)
business_process = portal.portal_catalog.getResultValue(
reference=('default_erp5_business_process', # erp5_configurator
......
......@@ -98,8 +98,8 @@ for month in range(1, month_count + 1):
source_payment=getBankAccountByTitle('My default bank account'),
destination_section=getOrganisationByTitle(client_title),
created_by_builder=1,
start_date=DateTime(year, month, day, 01, 01) + 10,
stop_date=DateTime(year, month, day, 01, 01) + 10,
start_date=DateTime(year, month, day, 0o1, 0o1) + 10,
stop_date=DateTime(year, month, day, 0o1, 0o1) + 10,
causality_value=tr,
resource=euro_resource,
)
......
print '<html><head><meta http-equiv="refresh" content="%s"></head><body>' % refresh_interval
print('<html><head><meta http-equiv="refresh" content="%s"></head><body>' % refresh_interval)
for table in 'message', 'message_queue':
q = """SELECT count(*) AS %(table)s, method_id, processing_node AS node, min(priority) AS min_pri, max(priority) AS max_pri
FROM %(table)s GROUP BY method_id, processing_node ORDER BY node""" % dict(table=table)
print "<table border=\"\" style=\"font-size:XX-small;\"><tbody> <tr><th>%s</th> <th>method_id</th> <th>node</th> <th>min_pri</th> <th>max_pri</th> </tr>" % table
print("<table border=\"\" style=\"font-size:XX-small;\"><tbody> <tr><th>%s</th> <th>method_id</th> <th>node</th> <th>min_pri</th> <th>max_pri</th> </tr>" % table)
for row in context.cmf_activity_sql_connection.manage_test(q):
print '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td</tr>' % (row[table], row['method_id'], row['node'], row['min_pri'], row['max_pri'])
print '</tbody> </table> <br/>'
print('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td</tr>' % (row[table], row['method_id'], row['node'], row['min_pri'], row['max_pri']))
print('</tbody> </table> <br/>')
return printed
......@@ -10,14 +10,14 @@ for security_uid_field in security_uid_field_list:
print(">> useless uids in roles_and_users table <<\n")
if len(referenced_uid_set) > 0:
for row in req("select * from roles_and_users where uid not in %s" + tuple(referenced_uid_set)):
print row.uid, row.local_roles_group_id, row.allowedRolesAndUsers
print(row.uid, row.local_roles_group_id, row.allowedRolesAndUsers)
print("\n>> uids that should be in roles_and_users table <<\n")
all_uid_set = {row.uid for row in req("select uid from roles_and_users")}
for security_uid_field in security_uid_field_list:
for row in req("select %s, relative_url from catalog where %s not in %s" % (security_uid_field, security_uid_field, tuple(all_uid_set))):
print security_uid_field, getattr(row, security_uid_field, None), row.relative_url
print(security_uid_field, getattr(row, security_uid_field, None), row.relative_url)
print("\n>> END <<")
return printed
......@@ -20,7 +20,7 @@ if context.getPortalType() == 'Alarm':
else:
active_process = context.portal_activities.newActiveProcess().getPath()
ERP5Site_checkDataWithScript = context.portal_activities.ERP5Site_checkDataWithScript
print 'Results will be saved to %s' % active_process
print('Results will be saved to %s' % active_process)
checkTopLevel()
ERP5Site_checkDataWithScript(
......
......@@ -4,6 +4,6 @@ for business_template in sorted(context.getPortalObject().portal_templates.conte
key=lambda x:x.getTitle()):
if business_template.getInstallationState() == 'installed' and \
business_template.getTitle() not in ignore_business_template_list:
print business_template.getTitle()
print(business_template.getTitle())
return printed
......@@ -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'
......@@ -37,12 +37,12 @@ for skin_folder in portal.portal_skins.objectValues('Folder'):
for skin in skin_folder.objectValues():
if skin.getId() in ignore_skin_list:
continue
print getSkinHash(skin, skin_folder)
print(getSkinHash(skin, skin_folder))
if include_workflow_scripts:
for workflow in portal.portal_workflow.objectValues():
for skin in workflow.scripts.objectValues():
print getSkinHash(skin, workflow)
print(getSkinHash(skin, workflow))
container.REQUEST.RESPONSE.setHeader('content-type', 'text/plain')
return '\n'.join(sorted(printed.splitlines()))
......@@ -16,6 +16,6 @@ for bt in bt_list:
delete_list.append(bt_id)
break
print 'Deleted id list:%r' % delete_list
print('Deleted id list:%r' % delete_list)
portal_templates.manage_delObjects(delete_list)
return printed
......@@ -22,14 +22,14 @@ 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)
# Make sure editors are pushed back as values into the REQUEST object
for f in form.get_fields():
field_id = f.id
if request.has_key(field_id):
if field_id in request:
value = request.get(field_id)
if callable(value):
value(request)
......
from urlparse import urlparse
from urlparse import parse_qsl
from urllib.parse import urlparse
from urllib.parse import parse_qsl
context.REQUEST.RESPONSE.setCookie("loyalty_reward", "disable", path='/')
......
from urlparse import urlparse
from urlparse import parse_qsl
from urllib.parse import urlparse
from urllib.parse import parse_qsl
context.REQUEST.RESPONSE.setCookie("loyalty_reward", "enable", path='/')
......
......@@ -3,7 +3,7 @@
"""
website = context.getWebSiteValue()
REQUEST = context.REQUEST
if REQUEST.has_key('portal_skin'):
if 'portal_skin' in REQUEST:
context.portal_skins.clearSkinCookie()
REQUEST.RESPONSE.expireCookie('__ac', path='/')
REQUEST.RESPONSE.expireCookie('__ac_facebook_hash', path='/')
......
......@@ -10,7 +10,7 @@ for item in item_list:
item_key = '/'.join(item_split[:split_depth])
base_category = item_split[0]
# Create a new subfield if necessary
if not sub_field_dict.has_key(item_key):
if item_key not in sub_field_dict:
# Create property dict (key are field parameters)
sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key
......
......@@ -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:
......
......@@ -86,7 +86,7 @@ try:
bath = ''
for item in created_item_list:
bath = str(item.grouping_reference)
if bath_dict.has_key(bath):
if bath in bath_dict:
bath_dict[str(bath)].extend([item])
else:
bath_dict[str(bath)] = [item]
......@@ -142,7 +142,7 @@ try:
new_movement = context.portal_simulation.solveMovement(movement, None, 'SplitQuantity', additional_parameters={'aggregate_list':apparel_bath_list}, start_date=start_date, stop_date=stop_date, quantity=quantity)
movement_list.append(new_movement[0].getRelativeUrl())
# update root movement if require
if bath_dict.has_key(movement_bath):
if movement_bath in bath_dict:
items = bath_dict[movement_bath]
quantity = 0
for item in items:
......@@ -181,7 +181,7 @@ try:
if cell.getVariationText() == variation_text:
# update aggregate list with items
cell_aggregate_list = cell.getAggregateValueList()
if bath_dict.has_key(line_bath):
if line_bath in bath_dict:
# new items on cell
cell_item = bath_dict[line_bath]
cell_aggregate_list.extend(cell_item)
......@@ -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.")
)
......
......@@ -159,10 +159,10 @@ class TestApparelModel(ERP5TypeTestCase):
self.assertEqual(elasthane.getProperty('quantity'), 0.12)
# check indexes are present
self.assertTrue(apparel_model.index.has_key('composition'))
self.assertTrue('composition' in apparel_model.index)
index = apparel_model.index['composition'][0]
self.assertTrue(index.has_key('composition/elasthane'))
self.assertTrue(index.has_key('composition/acrylique'))
self.assertTrue('composition/elasthane' in index)
self.assertTrue('composition/acrylique' in index)
def test_checkCopyColourRangeVariation(self):
'''
......
......@@ -26,7 +26,7 @@ node_inventory_dict = {}
activate_kw = {"tag": tag}
for inventory in node_inventory_list:
# Do only one inventory per node
if not node_inventory_dict.has_key(inventory.node_relative_url):
if inventory.node_relative_url not in node_inventory_dict:
inv = inventory_module.newContent(portal_type="Archive Inventory",
destination=inventory.node_relative_url,
......@@ -99,7 +99,7 @@ for inv in node_inventory_dict.values():
payment_inventory_dict = {}
for inventory in payment_inventory_list:
# Do only one inventory per payment
if not payment_inventory_dict.has_key(inventory.payment_uid):
if inventory.payment_uid not in payment_inventory_dict:
inv = inventory_module.newContent(portal_type="Archive Inventory",
destination=inventory.node_relative_url,
......
......@@ -30,11 +30,11 @@
from functools import partial
import unittest
import urllib
import urlparse
from StringIO import StringIO
import urllib.request, urllib.parse, urllib.error
import urllib.parse
from io import StringIO
import time
import httplib
import http.client
import mock
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.Document import newTempBase
......@@ -712,9 +712,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
basic='test-05:used_ALREADY_1234',
)
response = publish()
redirect_url = urlparse.urlparse(response.getHeader("Location"))
redirect_url = urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, '{}/login_form'.format(portal.absolute_url_path()))
redirect_url_params = urlparse.parse_qsl(redirect_url.query)
redirect_url_params = urllib.parse.parse_qsl(redirect_url.query)
self.assertEqual(redirect_url_params, [('portal_status_message', 'Account is blocked.')] )
# test expire password message, first unblock it
......@@ -723,9 +723,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
self.tic()
self._clearCache()
response = publish()
redirect_url = urlparse.urlparse(response.getHeader("Location"))
redirect_url = urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, '{}/login_form'.format(portal.absolute_url_path()))
redirect_url_params = urlparse.parse_qsl(redirect_url.query)
redirect_url_params = urllib.parse.parse_qsl(redirect_url.query)
self.assertEqual(redirect_url_params, [('portal_status_message', 'Password is expired.')] )
self.assertTrue(login.isPasswordExpired())
......@@ -735,9 +735,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
self.tic()
self._clearCache()
response = publish()
redirect_url = urlparse.urlparse(response.getHeader("Location"))
redirect_url = urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, '{}/ERP5Site_viewNewPersonCredentialUpdateDialog'.format(portal.absolute_url_path()))
redirect_url_params = urlparse.parse_qs(redirect_url.query)
redirect_url_params = urllib.parse.parse_qs(redirect_url.query)
# status message contain the password expiration date
self.assertIn('Your password will expire at 20', redirect_url_params['portal_status_message'][0])
self.assertIn('You are advised to change it as soon as possible', redirect_url_params['portal_status_message'][0])
......@@ -756,12 +756,12 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
response = self.publish(
portal.absolute_url_path() + '/logged_in',
basic='test-05:used_ALREADY_1234',
stdin=StringIO(urllib.urlencode({'came_from': 'https://www.erp5.com'})),
stdin=StringIO(urllib.parse.urlencode({'came_from': 'https://www.erp5.com'})),
request_method='POST',
)
redirect_url = urlparse.urlparse(response.getHeader("Location"))
redirect_url = urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, portal.absolute_url_path())
redirect_url_params = urlparse.parse_qsl(redirect_url.query)
redirect_url_params = urllib.parse.parse_qsl(redirect_url.query)
self.assertEqual(redirect_url_params, [('portal_status_message', 'Redirection to an external site prevented.')] )
def test_ExpireOldAuthenticationEventList(self):
......@@ -819,7 +819,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
def submit_reset_password_dialog(new_password):
return self.publish(
'%s/portal_password' % self.portal.getPath(),
stdin=StringIO(urllib.urlencode({
stdin=StringIO(urllib.parse.urlencode({
'Base_callDialogMethod:method': '',
'dialog_id': 'PasswordTool_viewResetPassword',
'dialog_method': 'PasswordTool_changeUserPassword',
......@@ -832,7 +832,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
handle_errors=False)
ret = submit_reset_password_dialog('alice')
self.assertEqual(httplib.OK, ret.getStatus())
self.assertEqual(http.client.OK, ret.getStatus())
self.assertIn(
'<span class="error">You can not use any parts of your '
'first and last name in password.</span>',
......@@ -848,14 +848,14 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
with mock.patch.object(self.portal.Localizer.erp5_ui.__class__, 'gettext', side_effect=gettext):
ret = submit_reset_password_dialog('alice')
self.assertEqual(httplib.OK, ret.getStatus())
self.assertEqual(http.client.OK, ret.getStatus())
self.assertIn(
'<span class="error">Yöü can not ... translated</span>',
ret.getBody())
# now with a password complying to the policy
ret = submit_reset_password_dialog('ok')
self.assertEqual(httplib.FOUND, ret.getStatus())
self.assertEqual(http.client.FOUND, ret.getStatus())
self.assertTrue(ret.getHeader('Location').endswith(
'/login_form?portal_status_message=Password+changed.'))
......@@ -874,7 +874,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
return self.publish(
'%s/portal_preferences' % self.portal.getPath(),
basic='%s:current' % self.id(),
stdin=StringIO(urllib.urlencode({
stdin=StringIO(urllib.parse.urlencode({
'Base_callDialogMethod:method': '',
'dialog_id': 'PreferenceTool_viewChangePasswordDialog',
'dialog_method': 'PreferenceTool_setNewPassword',
......@@ -887,7 +887,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
# too short password is refused
ret = submit_change_password_dialog('short')
self.assertEqual(httplib.OK, ret.getStatus())
self.assertEqual(http.client.OK, ret.getStatus())
self.assertIn(
'<span class="error">Too short.</span>',
ret.getBody())
......@@ -902,7 +902,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
with mock.patch.object(self.portal.Localizer.erp5_ui.__class__, 'gettext', side_effect=gettext):
ret = submit_change_password_dialog('short')
self.assertEqual(httplib.OK, ret.getStatus())
self.assertEqual(http.client.OK, ret.getStatus())
self.assertIn(
'<span class="error">Töü short ... translated</span>',
ret.getBody())
......@@ -919,7 +919,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
# long enough password is accepted
ret = submit_change_password_dialog('long_enough_password')
# When password reset is succesful, user is logged out
self.assertEqual(httplib.FOUND, ret.getStatus())
self.assertEqual(http.client.FOUND, ret.getStatus())
self.assertEqual(self.portal.portal_preferences.absolute_url(),
ret.getHeader("Location"))
......
......@@ -26,7 +26,7 @@
#
##############################################################################
import urllib2
import urllib.request, urllib.error, urllib.parse
from lxml import etree
from erp5.component.document.Document import ConversionError
......@@ -34,8 +34,8 @@ SVG_DEFAULT_NAMESPACE = "http://www.w3.org/2000/svg"
def getDataURI(url):
try:
data = urllib2.urlopen(url)
except Exception, e:
data = urllib.request.urlopen(url)
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', ""))
......
......@@ -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,
......
......@@ -314,7 +314,7 @@ class BTreeData(Persistent):
if __name__ == '__main__':
def check(tree, length, read_offset, read_length, data_, keys=None):
print list(tree._tree.items())
print(list(tree._tree.items()))
tree_length = len(tree)
tree_data = tree.read(read_offset, read_length)
tree_iterator_data = ''.join(tree.iterate(read_offset, read_length))
......
......@@ -208,7 +208,7 @@ class CertificateAuthorityTool(BaseTool):
cert = os.path.join(self.certificate_authority_path, 'certs',
new_id + '.crt')
try:
os.close(os.open(key, os.O_CREAT | os.O_EXCL, 0600))
os.close(os.open(key, os.O_CREAT | os.O_EXCL, 0o600))
popenCommunicate([self.openssl_binary, 'req', '-utf8', '-nodes', '-config',
self.openssl_config, '-new', '-keyout', key, '-out', csr, '-days',
'3650'], '%s\n' % common_name, stdin=subprocess.PIPE)
......
from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
import urllib
import urllib.request, urllib.parse, urllib.error
import mechanize
def getProductPrice(product):
......@@ -9,7 +9,7 @@ def getProductPrice(product):
def submitPaypalNVPRequest(parameter_dict, nvp_url):
request = mechanize.Request(nvp_url)
params = urllib.urlencode(parameter_dict)
params = urllib.parse.urlencode(parameter_dict)
try:
response = mechanize.urlopen(request, data=params)
except:
......
......@@ -14,14 +14,14 @@ 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)
# Make sure editors are pushed back as values into the REQUEST object
for f in form.get_fields():
field_id = f.id
if request.has_key(field_id):
if field_id in request:
value = request.get(field_id)
if callable(value):
value(request)
......
......@@ -9,4 +9,4 @@ shopping_cart_order_lines = shopping_cart.contentValues()
if include_shipping:
return shopping_cart_order_lines
else:
return filter(lambda x: x.getId()!='shipping_method', shopping_cart_order_lines)
return [x for x in shopping_cart_order_lines if x.getId()!='shipping_method']
......@@ -3,16 +3,16 @@
current_web_section = context.REQUEST.get('current_web_section', context)
product_list = []
if not kw.has_key('portal_type'):
if 'portal_type' not in kw:
kw['portal_type'] = 'Product'
if not kw.has_key('limit'):
if 'limit' not in kw:
kw['limit'] = limit
if not kw.has_key('all_versions'):
if 'all_versions' not in kw:
kw['all_versions'] = 1
if not kw.has_key('all_languages'):
if 'all_languages' not in kw:
kw['all_languages'] = 1
for key in ['limit','all_versions','all_languages']:
......
......@@ -5,7 +5,7 @@ from random import choice
web_site = context.getWebSiteValue() or context.REQUEST.get('current_web_site')
if not kw.has_key('portal_type'):
if 'portal_type' not in kw:
kw['portal_type'] = 'Product'
# Getting all the products from all the visible Web Section.
......
......@@ -30,7 +30,7 @@
import os
import string
import unittest
import urllib
import urllib.request, urllib.parse, urllib.error
from unittest import skip
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
......@@ -567,14 +567,14 @@ class TestCommerce(ERP5TypeTestCase):
self.logout()
self.assertEqual(1, len(self.website.SaleOrder_getShoppingCartItemList()))
self.website.SaleOrder_paymentRedirect()
self.assertTrue(urllib.quote("You need to create an account to " \
self.assertTrue(urllib.parse.quote("You need to create an account to " \
"continue. If you already have please login.") in
self.app.REQUEST.RESPONSE.getHeader('location'))
# but it should work if the user is authenticated
self.loginByUserName('customer')
self.portal.SaleOrder_paymentRedirect()
self.assertTrue(urllib.quote("SaleOrder_viewAsWeb") in
self.assertTrue(urllib.parse.quote("SaleOrder_viewAsWeb") in
self.app.REQUEST.RESPONSE.getHeader('location'))
def test_10_deleteShoppingCartItem(self):
......@@ -587,7 +587,7 @@ class TestCommerce(ERP5TypeTestCase):
# Trying to remove
self.portal.SaleOrder_deleteShoppingCartItem()
self.assertTrue(urllib.quote("Please select an item.") in
self.assertTrue(urllib.parse.quote("Please select an item.") in
self.app.REQUEST.RESPONSE.getHeader('location'))
# Check if the item still into the Shopping Cart
......@@ -600,7 +600,7 @@ class TestCommerce(ERP5TypeTestCase):
# Check if the Product have been removed sucessfully
self.assertTrue(
urllib.quote("Successfully removed from shopping cart.") in
urllib.parse.quote("Successfully removed from shopping cart.") in
self.app.REQUEST.RESPONSE.getHeader('location'))
# Check if the Shopping Cart is empty
......@@ -861,7 +861,7 @@ class TestCommerce(ERP5TypeTestCase):
self.loginByUserName('toto')
self.portal.SaleOrder_paymentRedirect()
self.assertTrue(urllib.quote("SaleOrder_viewAsWeb") in
self.assertTrue(urllib.parse.quote("SaleOrder_viewAsWeb") in
self.app.REQUEST.RESPONSE.getHeader('location'))
def test_23_getShoppingCartCustomer(self):
......
......@@ -1054,8 +1054,8 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase):
def stepAccountingTransaction(self, sequence=None, sequence_list=None, **kw):
transaction = self.portal.accounting_module.newContent(
portal_type='Accounting Transaction',
start_date=DateTime(2001, 01, 01),
stop_date=DateTime(2001, 01, 01))
start_date=DateTime(2001, 0o1, 0o1),
stop_date=DateTime(2001, 0o1, 0o1))
self.assertEqual('draft', transaction.getSimulationState())
for user_id in self._getUserIdList(self.all_username_list):
self.assertUserCanViewDocument(user_id, transaction)
......@@ -1186,8 +1186,8 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase):
def stepSaleInvoiceTransaction(self, sequence=None, sequence_list=None, **kw):
transaction = self.portal.accounting_module.newContent(
portal_type='Sale Invoice Transaction',
start_date=DateTime(2001, 01, 01),
stop_date=DateTime(2001, 01, 01))
start_date=DateTime(2001, 0o1, 0o1),
stop_date=DateTime(2001, 0o1, 0o1))
self.assertEqual('draft', transaction.getSimulationState())
for user_id in self._getUserIdList(self.all_username_list):
self.assertUserCanViewDocument(user_id, transaction)
......@@ -1329,8 +1329,8 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase):
def stepPurchaseInvoiceTransaction(self, sequence=None, sequence_list=None, **kw):
transaction = self.portal.accounting_module.newContent(
portal_type='Purchase Invoice Transaction',
start_date=DateTime(2001, 01, 01),
stop_date=DateTime(2001, 01, 01))
start_date=DateTime(2001, 0o1, 0o1),
stop_date=DateTime(2001, 0o1, 0o1))
self.assertEqual('draft', transaction.getSimulationState())
for user_id in self._getUserIdList(self.all_username_list):
self.assertUserCanViewDocument(user_id, transaction)
......@@ -1476,8 +1476,8 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase):
def stepPaymentTransaction(self, sequence=None, sequence_list=None, **kw):
transaction = self.portal.accounting_module.newContent(
portal_type='Payment Transaction',
start_date=DateTime(2001, 01, 01),
stop_date=DateTime(2001, 01, 01))
start_date=DateTime(2001, 0o1, 0o1),
stop_date=DateTime(2001, 0o1, 0o1))
self.assertEqual('draft', transaction.getSimulationState())
for user_id in self._getUserIdList(self.all_username_list):
self.assertUserCanViewDocument(user_id, transaction)
......@@ -1621,29 +1621,29 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase):
accounting_transaction_x_related_to_a = self.portal.\
accounting_module.newContent(
portal_type='Accounting Transaction',
start_date=DateTime(2010, 06, 01),
stop_date=DateTime(2010, 06, 01))
start_date=DateTime(2010, 0o6, 0o1),
stop_date=DateTime(2010, 0o6, 0o1))
accounting_transaction_y_related_to_a = self.portal.\
accounting_module.newContent(
portal_type='Accounting Transaction',
start_date=DateTime(2010, 06, 01),
stop_date=DateTime(2010, 06, 01))
start_date=DateTime(2010, 0o6, 0o1),
stop_date=DateTime(2010, 0o6, 0o1))
accounting_transaction_a = self.portal.accounting_module.newContent(
portal_type='Accounting Transaction',
start_date=DateTime(2010, 06, 01),
stop_date=DateTime(2010, 06, 01))
start_date=DateTime(2010, 0o6, 0o1),
stop_date=DateTime(2010, 0o6, 0o1))
accounting_transaction_b = self.portal.accounting_module.newContent(
portal_type='Accounting Transaction',
start_date=DateTime(2010, 06, 01),
stop_date=DateTime(2010, 06, 01))
start_date=DateTime(2010, 0o6, 0o1),
stop_date=DateTime(2010, 0o6, 0o1))
accounting_transaction_c = self.portal.accounting_module.newContent(
portal_type='Accounting Transaction',
start_date=DateTime(2010, 06, 01),
stop_date=DateTime(2010, 06, 01))
start_date=DateTime(2010, 0o6, 0o1),
stop_date=DateTime(2010, 0o6, 0o1))
accounting_transaction_x_related_to_a.setCausalityValue(\
accounting_transaction_a)
......
......@@ -68,11 +68,11 @@ for business_application_category_id, module_ids in module_business_application_
if module is not None:
module.edit(business_application = business_application_category_id)
print "Indexing translations"
print("Indexing translations")
portal.ERP5Site_updateTranslationTable()
# clear cache so user security is recalculated
portal.portal_caches.clearAllCache()
print "Clear cache."
print("Clear cache.")
log("%s" % printed)
......@@ -141,7 +141,7 @@ for message in message_list:
comment_list = message_dict[message]
comment_list.sort()
comment = '\n'.join([('#: %s' % i) for i in comment_list])
print MESSAGE_TEMPLATE % (comment, formatText(message))
print(MESSAGE_TEMPLATE % (comment, formatText(message)))
context.REQUEST.RESPONSE.setHeader('Content-Type', 'text/plain')
......
......@@ -8,10 +8,10 @@ message_list = ["Configuration is over. Enjoy your new ERP5 system!",
portal.REQUEST.RESPONSE.setHeader('content-type', 'text/plain')
for message in message_list:
if not message in html_status_report:
print "Error: {message} not found in status report".format(message=message)
print("Error: {message} not found in status report".format(message=message))
for log in portal.error_log.getLogEntries():
print "Error: {type} {value} {tb_text}".format(**log)
print("Error: {type} {value} {tb_text}".format(**log))
if str(printed):
return printed
......
......@@ -201,7 +201,7 @@ for serie in series_list:
# the last element must be saved
data_groups.append(new_group)
print data_groups
print(data_groups)
# [
......@@ -236,24 +236,24 @@ def aggregate(big_list, item_to_add):
if big_list == []:
return []
if getListLevel(big_list) == getListLevel(item_to_add):
print "big_list " + big_list
print "item_to_add " + item_to_add
print("big_list " + big_list)
print("item_to_add " + item_to_add)
big_list.append(item_to_add)
return big_list
else:
new_big_list_sub_level = aggregate(getLastSubList(big_list), item_to_add)
print "new_big_list_sub_level " + new_big_list_sub_level
print "big_list " + big_list
print("new_big_list_sub_level " + new_big_list_sub_level)
print("big_list " + big_list)
return None #setLastSubList(big_list, new_big_list_sub_level)
for group in data_groups:
collapsed_group = group[0]
for serie_group in group[1:]:
print serie_group
print(serie_group)
collapsed_group = aggregate(collapsed_group, serie_group)
print collapsed_group
print(collapsed_group)
# if
......
......@@ -34,7 +34,7 @@ fast_input_lines = []
# get the fast input form datas
for inputline in listbox:
if inputline.has_key('listbox_key'):
if 'listbox_key' in inputline:
line = {}
line['id'] = int(inputline['listbox_key'])
for data_name in input_data_names:
......@@ -75,7 +75,7 @@ for line in fast_input_lines:
new_1st_level_sub_items.append(new_2nd_level_item)
if has_1st_level == True:
if structured_input_data.has_key(new_1st_level_key):
if new_1st_level_key in structured_input_data:
new_1st_level_sub_items = structured_input_data[new_1st_level_key][1] + new_1st_level_sub_items
else:
structured_input_data[new_1st_level_key] = [None, None]
......
......@@ -14,7 +14,7 @@ except: #XXX
# get the user information
for line in listbox:
if line.has_key('listbox_key') and line['title'] not in ('', None):
if 'listbox_key' in line and line['title'] not in ('', None):
line_id = int(line['listbox_key'])
item = {}
item['id'] = line_id
......
......@@ -14,7 +14,7 @@ except:
# get the user information
for line in listbox:
if line.has_key('listbox_key') and line['title'] not in ('', None):
if 'listbox_key' in line and line['title'] not in ('', None):
line_id = int(line['listbox_key'])
item = {}
item['id'] = line_id
......
......@@ -144,7 +144,7 @@ class TestAlarm(ERP5TypeTestCase):
right_first_date = DateTime(self.date_format % (2006,10,6,15,00,00))
now = DateTime(self.date_format % (2006,10,6,15,00,00))
right_second_date = DateTime(self.date_format % (2006,10,6,21,00,00))
right_third_date = DateTime(self.date_format % (2006,10,7,06,00,00))
right_third_date = DateTime(self.date_format % (2006,10,7,0o6,00,00))
right_fourth_date = DateTime(self.date_format % (2006,10,7,10,00,00))
alarm = self.newAlarm(enabled=True)
hour_list = (6,10,15,21)
......@@ -240,8 +240,8 @@ class TestAlarm(ERP5TypeTestCase):
def test_09_SomeMonthDaysSomeHours(self):
"""- every 1st and 15th every month, at 12 and 14"""
right_first_date = DateTime(self.date_format % (2006,10,01,12,00,00))
right_second_date = DateTime(self.date_format % (2006,10,01,14,00,00))
right_first_date = DateTime(self.date_format % (2006,10,0o1,12,00,00))
right_second_date = DateTime(self.date_format % (2006,10,0o1,14,00,00))
right_third_date = DateTime(self.date_format % (2006,10,15,12,00,00))
right_fourth_date = DateTime(self.date_format % (2006,10,15,14,00,00))
alarm = self.newAlarm(enabled=True)
......@@ -253,9 +253,9 @@ class TestAlarm(ERP5TypeTestCase):
def test_10_OnceEvery2Month(self):
"""- every 1st day of every 2 month, at 6"""
right_first_date = DateTime(self.date_format % (2006,10,01,6,00,00))
right_second_date = DateTime(self.date_format % (2006,12,01,6,00,00))
right_third_date = DateTime(self.date_format % (2007,2,01,6,00,00))
right_first_date = DateTime(self.date_format % (2006,10,0o1,6,00,00))
right_second_date = DateTime(self.date_format % (2006,12,0o1,6,00,00))
right_third_date = DateTime(self.date_format % (2007,2,0o1,6,00,00))
alarm = self.newAlarm(enabled=True)
alarm.setPeriodicityStartDate(right_first_date)
alarm.setPeriodicityMonthDayList((1,))
......
......@@ -29,9 +29,9 @@
##############################################################################
from functools import partial
from StringIO import StringIO
from io import StringIO
import unittest
import urllib
import urllib.request, urllib.parse, urllib.error
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from DateTime import DateTime
......@@ -71,7 +71,7 @@ class TestAuoLogout(ERP5TypeTestCase):
"""
portal = self.getPortal()
stdin = urllib.urlencode({
stdin = urllib.parse.urlencode({
'__ac_name': self.manager_username,
'__ac_password': self.manager_password,
})
......
......@@ -35,7 +35,7 @@ from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Acquisition import aq_base
from App.config import getConfiguration
from Products.ERP5Type.tests.Sequence import SequenceList, Sequence
from urllib import pathname2url
from urllib.request import pathname2url
from Products.ERP5Type.Globals import PersistentMapping
from Products.ERP5Type.dynamic.lazy_class import ERP5BaseBroken
from Products.ERP5Type.tests.utils import LogInterceptor
......@@ -606,7 +606,7 @@ class BusinessTemplateMixin(ERP5TypeTestCase, LogInterceptor):
module.manage_permission('Copy or Move', ['Assignor'], False)
sequence.edit(module_id=module.getId())
module_object_list = []
for _ in xrange(10):
for _ in range(10):
obj = module.newContent(portal_type = 'Geek Object')
self.assertIsNotNone(obj)
module_object_list.append(obj)
......@@ -630,7 +630,7 @@ class BusinessTemplateMixin(ERP5TypeTestCase, LogInterceptor):
module = portal._getOb(module_id, None)
self.assertIsNotNone(module)
module_object_list = []
for _ in xrange(10):
for _ in range(10):
obj = module.newContent(portal_type = 'Geek Object')
self.assertIsNotNone(obj)
module_object_list.append(obj.getId())
......@@ -1178,7 +1178,7 @@ class BusinessTemplateMixin(ERP5TypeTestCase, LogInterceptor):
base_category = pc._getOb(bc_id, None)
self.assertTrue(base_category is not None)
category_list = []
for _ in xrange(10):
for _ in range(10):
category = base_category.newContent(portal_type='Category')
category_list.append(category.getId())
sequence.edit(category_id_list=category_list)
......@@ -1245,7 +1245,7 @@ class BusinessTemplateMixin(ERP5TypeTestCase, LogInterceptor):
self.assertTrue(category is not None)
subcategory_list = []
subcategory_uid_dict = {}
for _ in xrange(10):
for _ in range(10):
subcategory = category.newContent(portal_type='Category', title='toto')
subcategory_list.append(subcategory.getId())
subcategory_uid_dict[subcategory.getId()] = subcategory.getUid()
......@@ -3040,7 +3040,7 @@ class BusinessTemplateMixin(ERP5TypeTestCase, LogInterceptor):
def stepCreateFakeZODBScript(self, sequence=None, **kw):
"""Create a Script inside portal_skins
"""
grain_of_sand = ''.join([random.choice(string.ascii_letters) for _ in xrange(10)])
grain_of_sand = ''.join([random.choice(string.ascii_letters) for _ in range(10)])
python_script_id = 'ERP5Site_dummyScriptWhichRandomId%s' % grain_of_sand
skin_folder_id = 'custom'
if getattr(self.portal.portal_skins, skin_folder_id, None) is None:
......
......@@ -142,11 +142,11 @@ class TestRamCache(ERP5TypeTestCase):
## check it, we MUST NOT have this key any more in cache
self.assertEqual(False, cache_plugin.has_key(cache_id, scope))
if not self.quiet:
print "\t\tOK"
print("\t\tOK")
def generaltestSetGet(self, cache_plugin, iterations):
if not self.quiet:
print "TESTING (set/get/has/del): ", cache_plugin
print("TESTING (set/get/has/del): ", cache_plugin)
values = self.prepareValues(iterations)
cache_duration = 30
scope = "peter"
......
......@@ -27,6 +27,7 @@
#
##############################################################################
from __future__ import print_function
import time
import unittest
......
......@@ -1020,7 +1020,7 @@ class TestCMFActivity(ERP5TypeTestCase, LogInterceptor):
"""
activity_tool = self.getActivityTool()
def delete_volatiles():
for property_id in activity_tool.__dict__.keys():
for property_id in list(activity_tool.__dict__.keys()):
if property_id.startswith('_v_'):
delattr(activity_tool, property_id)
organisation_module = self.getOrganisationModule()
......@@ -1540,7 +1540,7 @@ class TestCMFActivity(ERP5TypeTestCase, LogInterceptor):
# on REQUEST information when the method was activated.
request = self.portal.REQUEST
request.setServerURL('http', 'test.erp5.org', '9080')
request.setServerURL('http', 'test.erp5.org', 9080)
request.other['PARENTS'] = [self.portal.organisation_module]
request.setVirtualRoot('virtual_root')
......@@ -1559,7 +1559,7 @@ class TestCMFActivity(ERP5TypeTestCase, LogInterceptor):
# Reset server URL and virtual root before executing messages.
# This simulates the case of activities beeing executed with different
# REQUEST, such as TimerServer.
request.setServerURL('https', 'anotherhost.erp5.org', '443')
request.setServerURL('https', 'anotherhost.erp5.org', 443)
request.other['PARENTS'] = [self.app]
request.setVirtualRoot('')
# obviously, the object url is different
......@@ -2464,7 +2464,7 @@ class TestCMFActivity(ERP5TypeTestCase, LogInterceptor):
check(1, tag="foo")
check(0, tag="foo", method_id="getUid")
check(1, processing_node=-1)
check(3, processing_node=range(-5,5))
check(3, processing_node=list(range(-5,5)))
test()
self.commit()
test(check)
......
......@@ -26,6 +26,7 @@
#
##############################################################################
from past.builtins import cmp
from collections import deque
import unittest
......@@ -102,7 +103,7 @@ class TestCMFCategory(ERP5TypeTestCase):
self.validateRules()
portal_categories = self.getCategoriesTool()
for name, kw in self.category_dict.iteritems():
for name, kw in self.category_dict.items():
try:
bc = portal_categories[name]
except KeyError:
......@@ -168,7 +169,7 @@ class TestCMFCategory(ERP5TypeTestCase):
def beforeTearDown(self):
"""Clean up."""
# type informations
for portal_type, categories in self._original_categories.iteritems():
for portal_type, categories in self._original_categories.items():
ti = self.getTypesTool().getTypeInfo(portal_type)
ti.filter_content_types = 1
ti._setTypeBaseCategoryList(categories)
......@@ -1306,9 +1307,9 @@ class TestCMFCategory(ERP5TypeTestCase):
self.assertEqual(get(bc.id), list('aa'))
_set(bc.id, list('baa'))
self.assertEqual(get(bc.id), list('aba'))
_set(bc.id, map(base, 'bb'), 1)
_set(bc.id, list(map(base, 'bb')), 1)
self.assertEqual(get(bc.id), list('bb'))
_set(bc.id, map(base, 'abb'), 1)
_set(bc.id, list(map(base, 'abb')), 1)
self.assertEqual(get(bc.id), list('bab'))
_set(bc.id, ())
......
from __future__ import print_function
input_file = open('big_file.log', 'r')
import httplib
connection = httplib.HTTPConnection('192.168.242.68:12001')
import http.client
connection = http.client.HTTPConnection('192.168.242.68:12001')
import base64
base64string = base64.encodestring('zope:insecure')[:-1]
......@@ -22,7 +23,7 @@ result = connection.getresponse()
path = result.getheader("X-Document-Location")
result.close()
path = '/%s' % '/'.join(path.split('/')[3:])
print path
print(path)
######################################
# Upload chunks
......
......@@ -12,17 +12,18 @@
# user: user1 password: user1
# user: user2 password: user2
from __future__ import print_function
from threading import Thread
from time import sleep
from urllib import addinfourl
from urllib import splithost
from urllib import splituser
from urllib import unquote
from urllib import splittype
from urllib.parse import splithost
from urllib.parse import splituser
from urllib.parse import unquote
from urllib.parse import splittype
import string
from urllib import FancyURLopener
from Cookie import SimpleCookie
from urllib.request import FancyURLopener
from http.cookies import SimpleCookie
def main():
max_thread = 7 # The number of thread we want by the same time
......@@ -53,7 +54,7 @@ def main():
threads[len(threads)-1].start()
request_number += 1
i+=1
print "thread: %i request: %i url: %s" % (i,request_number,url)
print("thread: %i request: %i url: %s" % (i,request_number,url))
else:
for t in range(0,max_thread):
if threads[t].isAlive() == 0:
......@@ -63,7 +64,7 @@ def main():
threads[t].start()
i+=1
request_number += 1
print "thread: %i request: %i url: %s" % (i,request_number,url)
print("thread: %i request: %i url: %s" % (i,request_number,url))
break
......@@ -76,7 +77,7 @@ class URLOpener(FancyURLopener):
def open_http(self, url, data=None):
"""Use HTTP protocol."""
import httplib
import http.client
user_passwd = None
if type(url) is type(""):
host, selector = splithost(url)
......@@ -104,24 +105,24 @@ class URLOpener(FancyURLopener):
auth = string.strip(base64.encodestring(user_passwd))
else:
auth = None
h = httplib.HTTP(host)
h = http.client.HTTP(host)
if data is not None:
h.putrequest('POST', selector)
h.putheader('Content-type', 'application/x-www-form-urlencoded')
h.putheader('Content-length', '%d' % len(data))
else:
h.putrequest('GET', selector)
for cookie in self.cookies.items():
for cookie in list(self.cookies.items()):
h.putheader('Cookie', '%s=%s;' % cookie)
if auth: h.putheader('Authorization', 'Basic %s' % auth)
if realhost: h.putheader('Host', realhost)
for args in self.addheaders: apply(h.putheader, args)
for args in self.addheaders: h.putheader(*args)
h.endheaders()
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)
......@@ -146,15 +147,15 @@ class Checker(URLOpener):
thread.start()
while thread.isAlive():
sleep(0.5)
print "Connection to %s went fine" % url
except IOError, (errno, strerror):
print "Can't connect to %s because of I/O error(%s): %s" % (url, errno, strerror)
print("Connection to %s went fine" % url)
except IOError as e:
print("Can't connect to %s because of I/O error(%s): %s" % (url, e.errno, e.strerror))
def SearchUrl(self, url=None):
try:
conn = self.open_http(url)
except IOError, (errno, strerror):
print "Can't connect to %s because of I/O error(%s): %s" % (url, errno, strerror)
except IOError as e:
print("Can't connect to %s because of I/O error(%s): %s" % (url, e.errno, e.strerror))
def raise_error(self, error_key, field):
......
......@@ -119,7 +119,7 @@ class TestBusinessTemplateTwoFileExport(ERP5TypeTestCase):
pass
file_document_path = document_path + extension
self.assertEqual([os.path.basename(file_document_path)],
map(os.path.basename, exported))
list(map(os.path.basename, exported)))
with open(file_document_path, 'rb') as test_file:
self.assertEqual(test_file.read(), data)
else:
......
......@@ -28,9 +28,10 @@
#
##############################################################################
from __future__ import print_function
import threading
import unittest
import urllib
import urllib.request, urllib.parse, urllib.error
import transaction
import pkg_resources
from DateTime import DateTime
......@@ -67,13 +68,13 @@ class TestInvalidationBug(ERP5TypeTestCase):
query = connection.factory()('-' + connection.connection_string).query
sql = "rollback\0select * from %s where path='%s'" % (table, path)
test_list.append(lambda query=query, sql=sql: len(query(sql)[1]))
result_list = [map(apply, test_list)]
result_list = [t() for t in test_list]
Transaction_commitResources = transaction.Transaction._commitResources
connection = module._p_jar
def _commitResources(self):
def tpc_finish(rm, txn):
rm.__class__.tpc_finish(rm, txn)
result_list.append(None if rm is connection else map(apply, test_list))
result_list.append(None if rm is connection else [t() for t in test_list])
try:
for rm in self._resources:
rm.tpc_finish = lambda txn, rm=rm: tpc_finish(rm, txn)
......@@ -160,7 +161,7 @@ class TestInvalidationBug(ERP5TypeTestCase):
storage._server = None
# ... monkey-patch done
## create object
urllib.urlopen(new_content_url).read()
urllib.request.urlopen(new_content_url).read()
## validate reindex activity
activity_tool.distribute()
self.assertEqual(1, len(activity_tool.getMessageList()))
......@@ -188,8 +189,8 @@ class TestInvalidationBug(ERP5TypeTestCase):
module.setIdGenerator('_generatePerDayId')
#module.migrateToHBTree()
self.tic()
print 'OID(%s) = %r' % (module.getRelativeUrl(), module._p_oid)
print ' OID(_tree) = %r' % module._tree._p_oid
print('OID(%s) = %r' % (module.getRelativeUrl(), module._p_oid))
print(' OID(_tree) = %r' % module._tree._p_oid)
previous = DateTime()
skin_folder = self.getPortal().portal_skins.custom
if 'create_script' in skin_folder.objectIds():
......@@ -215,7 +216,7 @@ if (count % 500) < 5:
log('creation speed: %s obj/s' % ((count - start[0]) /
(86400 * (DateTime() - start[1]))))
""")
for x in xrange(0,200):
for x in range(0,200):
module.activate(activity='SQLQueue', priority=2).create_script()
self.tic()
......
......@@ -32,6 +32,7 @@ TODO: test variation
test selection_report
"""
from six.moves import xrange
import os
import random
import unittest
......@@ -1959,94 +1960,94 @@ class TestMovementHistoryList(InventoryAPITestCase):
def test_FromDate(self):
getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
for date in [DateTime(2006, 01, day) for day in range(1, 4)]:
for date in [DateTime(2006, 0o1, day) for day in range(1, 4)]:
self._makeMovement(quantity=100,
start_date=date,
stop_date=date+1)
# from_date takes all movements >=
self.assertEqual(len(getMovementHistoryList(
from_date=DateTime(2006, 01, 03),
from_date=DateTime(2006, 0o1, 0o3),
section_uid=self.section.getUid())), 2)
self.assertEqual(len(getMovementHistoryList(
from_date=DateTime(2006, 01, 02),
from_date=DateTime(2006, 0o1, 0o2),
section_uid=self.mirror_section.getUid())), 2)
def test_AtDate(self):
getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
for date in [DateTime(2006, 01, day) for day in range(1, 4)]:
for date in [DateTime(2006, 0o1, day) for day in range(1, 4)]:
self._makeMovement(quantity=100,
start_date=date,
stop_date=date+1)
# at_date takes all movements <=
self.assertEqual(len(getMovementHistoryList(
at_date=DateTime(2006, 01, 03),
at_date=DateTime(2006, 0o1, 0o3),
section_uid=self.section.getUid())), 2)
self.assertEqual(len(getMovementHistoryList(
at_date=DateTime(2006, 01, 02),
at_date=DateTime(2006, 0o1, 0o2),
section_uid=self.mirror_section.getUid())), 2)
def test_ToDate(self):
getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
for date in [DateTime(2006, 01, day) for day in range(1, 4)]:
for date in [DateTime(2006, 0o1, day) for day in range(1, 4)]:
self._makeMovement(quantity=100,
start_date=date,
stop_date=date+1)
# to_date takes all movements <
self.assertEqual(len(getMovementHistoryList(
to_date=DateTime(2006, 01, 03),
to_date=DateTime(2006, 0o1, 0o3),
section_uid=self.section.getUid())), 1)
self.assertEqual(len(getMovementHistoryList(
to_date=DateTime(2006, 01, 02),
to_date=DateTime(2006, 0o1, 0o2),
section_uid=self.mirror_section.getUid())), 1)
def test_FromDateAtDate(self):
getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
for date in [DateTime(2006, 01, day) for day in range(1, 4)]:
for date in [DateTime(2006, 0o1, day) for day in range(1, 4)]:
self._makeMovement(quantity=100,
start_date=date,
stop_date=date+1)
# both from_date and at_date
self.assertEqual(len(getMovementHistoryList(
from_date=DateTime(2006, 01, 03),
at_date=DateTime(2006, 01, 03),
from_date=DateTime(2006, 0o1, 0o3),
at_date=DateTime(2006, 0o1, 0o3),
section_uid=self.section.getUid())), 1)
self.assertEqual(len(getMovementHistoryList(
from_date=DateTime(2006, 01, 02),
at_date=DateTime(2006, 01, 03),
from_date=DateTime(2006, 0o1, 0o2),
at_date=DateTime(2006, 0o1, 0o3),
section_uid=self.section.getUid())), 2)
self.assertEqual(len(getMovementHistoryList(
from_date=DateTime(2005, 01, 02),
at_date=DateTime(2006, 01, 03),
from_date=DateTime(2005, 0o1, 0o2),
at_date=DateTime(2006, 0o1, 0o3),
section_uid=self.section.getUid())), 2)
# from other side
self.assertEqual(len(getMovementHistoryList(
from_date=DateTime(2006, 01, 02),
at_date=DateTime(2006, 01, 03),
from_date=DateTime(2006, 0o1, 0o2),
at_date=DateTime(2006, 0o1, 0o3),
section_uid=self.mirror_section.getUid())), 2)
def test_FromDateToDate(self):
getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
for date in [DateTime(2006, 01, day) for day in range(1, 4)]:
for date in [DateTime(2006, 0o1, day) for day in range(1, 4)]:
self._makeMovement(quantity=100,
start_date=date,
stop_date=date+1)
# both from_date and to_date
self.assertEqual(len(getMovementHistoryList(
from_date=DateTime(2006, 01, 03),
to_date=DateTime(2006, 01, 03),
from_date=DateTime(2006, 0o1, 0o3),
to_date=DateTime(2006, 0o1, 0o3),
section_uid=self.section.getUid())), 0)
self.assertEqual(len(getMovementHistoryList(
from_date=DateTime(2006, 01, 02),
to_date=DateTime(2006, 01, 03),
from_date=DateTime(2006, 0o1, 0o2),
to_date=DateTime(2006, 0o1, 0o3),
section_uid=self.section.getUid())), 1)
self.assertEqual(len(getMovementHistoryList(
from_date=DateTime(2005, 01, 02),
to_date=DateTime(2007, 01, 02),
from_date=DateTime(2005, 0o1, 0o2),
to_date=DateTime(2007, 0o1, 0o2),
section_uid=self.section.getUid())), 3)
# from other side
self.assertEqual(len(getMovementHistoryList(
from_date=DateTime(2006, 01, 02),
to_date=DateTime(2006, 01, 03),
from_date=DateTime(2006, 0o1, 0o2),
to_date=DateTime(2006, 0o1, 0o3),
section_uid=self.mirror_section.getUid())), 1)
......@@ -2084,7 +2085,7 @@ class TestMovementHistoryList(InventoryAPITestCase):
def test_SortOnDate(self):
getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
date_list = [DateTime(2006, 01, day) for day in range(1, 10)]
date_list = [DateTime(2006, 0o1, day) for day in range(1, 10)]
reverse_date_list = date_list[:]
reverse_date_list.reverse()
......@@ -2193,7 +2194,7 @@ class TestMovementHistoryList(InventoryAPITestCase):
"""Test that a running_total_quantity attribute is set on brains
"""
getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
date_and_qty_list = [(DateTime(2006, 01, day), day) for day in range(1, 10)]
date_and_qty_list = [(DateTime(2006, 0o1, day), day) for day in range(1, 10)]
for date, quantity in date_and_qty_list:
self._makeMovement(stop_date=date, quantity=quantity)
movement_history_list = getMovementHistoryList(
......@@ -2212,7 +2213,7 @@ class TestMovementHistoryList(InventoryAPITestCase):
"""Test that a running_total_price attribute is set on brains
"""
getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
date_and_price_list = [(DateTime(2006, 01, day), day) for day in range(1, 10)]
date_and_price_list = [(DateTime(2006, 0o1, day), day) for day in range(1, 10)]
for date, price in date_and_price_list:
self._makeMovement(stop_date=date, quantity=1, price=price)
movement_history_list = getMovementHistoryList(
......@@ -2232,7 +2233,7 @@ class TestMovementHistoryList(InventoryAPITestCase):
value.
"""
getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
date_and_qty_list = [(DateTime(2006, 01, day), day) for day in range(1, 10)]
date_and_qty_list = [(DateTime(2006, 0o1, day), day) for day in range(1, 10)]
for date, quantity in date_and_qty_list:
self._makeMovement(stop_date=date, price=quantity, quantity=quantity)
initial_running_total_price=100
......@@ -2904,7 +2905,7 @@ class TestInventoryCacheTable(InventoryAPITestCase):
def afterSetUp(self):
InventoryAPITestCase.afterSetUp(self)
self.CACHE_LAG = cache_lag = self.getSimulationTool().getInventoryCacheLag()
min_lag = cache_lag / 2
min_lag = cache_lag // 2
self.NOW = now = DateTime(DateTime().strftime("%Y-%m-%d %H:%M:%S UTC"))
self.CACHE_DATE = cache_date = now - min_lag
from erp5.component.tool.SimulationTool import MYSQL_MIN_DATETIME_RESOLUTION
......@@ -2977,7 +2978,7 @@ class TestInventoryCacheTable(InventoryAPITestCase):
inventory_list = inventory_list[:] # That list is modified in this method
for criterion_dict in criterion_dict_list:
success = False
for inventory_position in xrange(len(inventory_list)):
for inventory_position in range(len(inventory_list)):
if self._doesInventoryLineMatch(criterion_dict,
inventory_list[inventory_position]):
del inventory_list[inventory_position]
......
......@@ -94,15 +94,15 @@ class TestSecurityMixin(ERP5TypeTestCase):
method.__doc__ and \
not hasattr(obj, '%s__roles__' % method_id) and \
method.__module__:
if method.__module__ == 'Products.ERP5Type.Accessor.WorkflowState' and method.func_code.co_name == 'serialize':
if method.__module__ == 'Products.ERP5Type.Accessor.WorkflowState' and method.__code__.co_name == 'serialize':
continue
func_code = method.func_code
func_code = method.__code__
error_dict[(func_code.co_filename, func_code.co_firstlineno, method_id)] = True
error_list = error_dict.keys()
if os.environ.get('erp5_debug_mode', None):
pass
else:
error_list = filter(lambda x:'/erp5/' in x[0], error_list)
error_list = [x for x in error_list if '/erp5/' in x[0]]
if error_list:
message = '\nThe following %s methods have a docstring but have no security assertions.\n\t%s' \
% (len(error_list), '\n\t'.join(['%s:%s %s' % x for x in sorted(error_list)]))
......
......@@ -114,7 +114,7 @@ class TestSpellChecking(ERP5TypeTestCase):
message = '"%s" is misspelled, suggestion are : "%s"'
result_dict = {}
for word, result_list in self.spellChecker(sentence).iteritems():
filtered_result_list = filter(lambda x: x not in ('*', ''), result_list)
filtered_result_list = [x for x in result_list if x not in ('*', '')]
if filtered_result_list:
result_dict[word] = message % (word, \
filtered_result_list[0].split(':')[-1].strip())
......
......@@ -27,6 +27,7 @@
#
##############################################################################
from __future__ import print_function
import cgi
import unittest
import os
......@@ -128,7 +129,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 +246,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:
......@@ -748,7 +749,7 @@ if validator_to_use == 'tidy':
warning = False
validator_path = '/usr/bin/tidy'
if not os.path.exists(validator_path):
print 'tidy is not installed at %s' % validator_path
print('tidy is not installed at %s' % validator_path)
else:
validator = TidyValidator(validator_path, show_warnings)
......
......@@ -29,7 +29,7 @@ import os
import tarfile
import xml.parsers.expat
import xml.dom.minidom
from urllib import url2pathname
from six.moves.urllib.request import url2pathname
from ZODB.DemoStorage import DemoStorage
from ZODB import DB
from Products.ERP5Type.XMLExportImport import importXML
......
......@@ -36,7 +36,7 @@ from AccessControl.SecurityManagement import newSecurityManager
from Acquisition import aq_base
from Products.ERP5OOo.tests.utils import Validator
from lxml import html
import email, urlparse, httplib
import email, urllib.parse, http.client
from Products.Formulator.MethodField import Method
......@@ -158,9 +158,9 @@ class TestDeferredStyleBase(DeferredStyleTestCase):
self.assertTrue("History%s" % extension or self.attachment_file_extension in content)
tree = html.fromstring(content)
link, = [href for href in tree.xpath('//a/@href') if href]
relative_url =urlparse.urlparse(link)
relative_url =urllib.parse.urlparse(link)
report = self.publish(relative_url.path+"?"+relative_url.query, '%s:%s' % (self.username, self.password))
self.assertEqual(httplib.OK, report.getStatus())
self.assertEqual(http.client.OK, report.getStatus())
self.assertEqual(report.getHeader('content-type'), content_type or self.content_type)
def _checkDocument(self):
......
......@@ -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)
......@@ -688,7 +688,7 @@ class TestFormPrintoutAsODT(TestFormPrintoutMixin):
request = self.app.REQUEST
request['here'] = test1
for i in xrange(3, 7):
for i in range(3, 7):
foo_id = "foo_%s" % i
if test1._getOb(foo_id, None) is None:
test1.newContent(foo_id, portal_type='Foo Line')
......
......@@ -31,7 +31,7 @@
import unittest
import os
import StringIO
import io
from cgi import FieldStorage
from lxml import etree
from AccessControl.SecurityManagement import newSecurityManager
......@@ -47,10 +47,10 @@ from Products.CMFCore.utils import getToolByName
from zExceptions import BadRequest
import ZPublisher.HTTPRequest
from unittest import expectedFailure
import urllib
import urllib2
import httplib
import urlparse
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import http.client
import urllib.parse
import base64
# test files' home
......@@ -2001,13 +2001,13 @@ return result
reference = 'ITISAREFERENCE'
portal_url = self.portal.absolute_url()
url_split = urlparse.urlsplit(portal_url)
url_split = urllib.parse.urlsplit(portal_url)
url_dict = dict(protocol=url_split[0],
hostname=url_split[1])
uri = '%(protocol)s://%(hostname)s' % url_dict
push_url = '%s%s/newContent' % (uri, self.portal.portal_contributions.getPath(),)
request = urllib2.Request(push_url, urllib.urlencode(
request = urllib.request.Request(push_url, urllib.parse.urlencode(
{'data': data,
'filename': filename,
'reference': reference,
......@@ -2018,8 +2018,8 @@ return result
})
# disable_cookie_login__ is required to force zope to raise Unauthorized (401)
# then HTTPDigestAuthHandler can perform HTTP Authentication
response = urllib2.urlopen(request)
self.assertEqual(response.getcode(), httplib.OK)
response = urllib.request.urlopen(request)
self.assertEqual(response.getcode(), http.client.OK)
self.tic()
document = self.portal.portal_catalog.getResultValue(portal_type='Spreadsheet',
reference=reference)
......@@ -2108,7 +2108,7 @@ class Base_contributeMixin:
"""
person = self.portal.person_module.newContent(portal_type='Person')
empty_file_upload = ZPublisher.HTTPRequest.FileUpload(FieldStorage(
fp=StringIO.StringIO(),
fp=io.StringIO(),
environ=dict(REQUEST_METHOD='PUT'),
headers={"content-disposition":
"attachment; filename=empty;"}))
......
......@@ -29,7 +29,7 @@
import os
import unittest
from cStringIO import StringIO
from io import StringIO
from zipfile import ZipFile
from Products.ERP5Type.tests.utils import FileUpload
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
......@@ -240,8 +240,7 @@ return getattr(context, "%s_%s" % (parameter, current_language))
cs = StringIO()
cs.write(body)
zip_document = ZipFile(cs)
picture_list = filter(lambda x: "Pictures" in x.filename,
zip_document.infolist())
picture_list = [x for x in zip_document.infolist() if "Pictures" in x.filename]
self.assertNotEquals([], picture_list)
manifest = zip_document.read('META-INF/manifest.xml')
content = zip_document.read('content.xml')
......
......@@ -64,17 +64,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()
......@@ -820,7 +820,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:
......@@ -849,7 +849,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:
......@@ -863,7 +863,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')
......
......@@ -42,7 +42,7 @@ class TestOOoParser(unittest.TestCase):
parser = OOoParser()
parser.openFile(open(makeFilePath('import_data_list.ods'), 'rb'))
mapping = parser.getSpreadsheetsMapping()
self.assertEqual(['Person'], mapping.keys())
self.assertEqual(['Person'], list(mapping.keys()))
person_mapping = mapping['Person']
self.assertTrue(isinstance(person_mapping, list))
self.assertTrue(102, len(person_mapping))
......@@ -56,13 +56,13 @@ class TestOOoParser(unittest.TestCase):
parser.openFromString(
open(makeFilePath('import_data_list.ods'), 'rb').read())
mapping = parser.getSpreadsheetsMapping()
self.assertEqual(['Person'], mapping.keys())
self.assertEqual(['Person'], list(mapping.keys()))
def test_getSpreadSheetMappingStyle(self):
parser = OOoParser()
parser.openFile(open(makeFilePath('import_data_list_with_style.ods'), 'rb'))
mapping = parser.getSpreadsheetsMapping()
self.assertEqual(['Feuille1'], mapping.keys())
self.assertEqual(['Feuille1'], list(mapping.keys()))
self.assertEqual(mapping['Feuille1'][1],
['a line with style'])
self.assertEqual(mapping['Feuille1'][2],
......@@ -76,7 +76,7 @@ class TestOOoParser(unittest.TestCase):
parser = OOoParser()
parser.openFile(open(makeFilePath('import_data_list_data_type.ods'), 'rb'))
mapping = parser.getSpreadsheetsMapping()
self.assertEqual(['Feuille1'], mapping.keys())
self.assertEqual(['Feuille1'], list(mapping.keys()))
self.assertEqual(mapping['Feuille1'][0],
['1234.5678'])
self.assertEqual(mapping['Feuille1'][1],
......@@ -109,7 +109,7 @@ class TestOOoParser(unittest.TestCase):
parser = OOoParser()
parser.openFile(open(makeFilePath('complex_text.ods'), 'rb'))
mapping = parser.getSpreadsheetsMapping()
self.assertEqual(['Feuille1'], mapping.keys())
self.assertEqual(['Feuille1'], list(mapping.keys()))
self.assertEqual(mapping['Feuille1'][0], [' leading space'])
self.assertEqual(mapping['Feuille1'][1], [' leading space'])
self.assertEqual(mapping['Feuille1'][2], ['tab\t'])
......@@ -119,7 +119,7 @@ class TestOOoParser(unittest.TestCase):
parser = OOoParser()
parser.openFile(open(makeFilePath('empty_cells.ods'), 'rb'))
mapping = parser.getSpreadsheetsMapping()
self.assertEqual(['Feuille1'], mapping.keys())
self.assertEqual(['Feuille1'], list(mapping.keys()))
self.assertEqual(mapping['Feuille1'],
[
['A1', None, 'C1'],
......
......@@ -34,11 +34,11 @@ from Products.ERP5Type.tests.utils import DummyLocalizer
from Products.ERP5Form.Selection import Selection
from Testing import ZopeTestCase
from Products.ERP5OOo.tests.utils import Validator
import httplib
import http.client
import lxml.html
import PyPDF2
HTTP_OK = httplib.OK
HTTP_OK = http.client.OK
# setting this to True allows the .publish() calls to provide tracebacks
debug = False
......
from __future__ import print_function
##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
......@@ -27,5 +28,5 @@
##############################################################################
def say_hello():
print 'hello'
print('hello')
......@@ -34,7 +34,7 @@ import mock
import itertools
import transaction
import unittest
import urlparse
import urllib.parse
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.utils import createZODBPythonScript
from AccessControl.SecurityManagement import newSecurityManager
......@@ -55,7 +55,7 @@ class UserManagementTestCase(ERP5TypeTestCase):
"""TestCase for user manement, with utilities to create users and helpers
assertion methods.
"""
_login_generator = itertools.count().next
_login_generator = itertools.count().__next__
def getBusinessTemplateList(self):
......@@ -648,12 +648,12 @@ class TestPreferences(UserManagementTestCase):
current_password='bad' + password,
new_password=new_password,
)
parsed_url = urlparse.urlparse(result)
parsed_url = urllib.parse.urlparse(result)
self.assertEqual(
parsed_url.path.split('/')[-2:],
['portal_preferences', 'PreferenceTool_viewChangePasswordDialog'])
self.assertEqual(
urlparse.parse_qs(parsed_url.query),
urllib.parse.parse_qs(parsed_url.query),
{'portal_status_message': ['Current password is wrong.'], 'portal_status_level': ['error']})
self.login()
......
from __future__ import print_function
##############################################################################
#
# Copyright (c) 2011 Nexedi SARL and Contributors. All Rights Reserved.
......@@ -435,10 +436,10 @@ class ERP5TypeFunctionalTestCase(ERP5TypeTestCase):
def _verboseErrorLog(self, size=10):
for entry in self.portal.error_log.getLogEntries()[:size]:
print "="*20
print "ERROR ID : %s" % entry["id"]
print "TRACEBACK :"
print entry["tb_text"]
print("="*20)
print("ERROR ID : %s" % entry["id"])
print("TRACEBACK :")
print(entry["tb_text"])
def testFunctionalTestRunner(self):
# Check the zuite page templates can be rendered, because selenium test
......@@ -474,7 +475,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()
......
......@@ -237,7 +237,7 @@ class ERP5TypeTestReLoader(ERP5TypeTestLoader):
def runLiveTest(test_list, verbosity=1, stream=None, request_server_url=None, **kw):
from Products.ERP5Type.tests.runUnitTest import DebugTestResult
from StringIO import StringIO
from io import StringIO
# Add path of the TestTemplateItem folder of the instance
path = kw.get('path', None)
if path is not None and path not in sys.path:
......
......@@ -9,7 +9,7 @@ __version__ = '0.3.0'
import base64
import errno
import httplib
import http.client
import os
import random
import re
......@@ -18,11 +18,11 @@ import string
import sys
import time
import traceback
import urllib
import ConfigParser
import urllib.request, urllib.parse, urllib.error
from contextlib import contextmanager
from cStringIO import StringIO
from cPickle import dumps
from io import StringIO
from six.moves import configparser
from six.moves.cPickle import dumps
from glob import glob
from hashlib import md5
from warnings import warn
......@@ -168,7 +168,7 @@ def _createTestPromiseConfigurationFile(promise_path, bt5_repository_path_list=N
_getVolatileMemcachedServerDict()
cloudooo_url_list = _getConversionServerUrlList()
promise_config = ConfigParser.RawConfigParser()
promise_config = configparser.RawConfigParser()
promise_config.add_section('external_service')
promise_config.set('external_service', 'cloudooo_url_list', cloudooo_url_list)
promise_config.set('external_service', 'memcached_url',memcached_url)
......@@ -607,12 +607,12 @@ 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)
urltype, url = urllib.parse.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)
host, selector = urllib.parse.splithost(url)
user_passwd, host = urllib.parse.splituser(host)
host = urllib.parse.unquote(host)
h = http.client.HTTP(host)
h.putrequest('HEAD', selector)
h.putheader('Host', host)
if user_passwd:
......@@ -815,7 +815,7 @@ class ERP5TypeTestCaseMixin(ProcessingNodeTestCase, PortalTestCase):
elif user:
PAS = self.portal.acl_users.__class__
orig_extractUserIds = PAS._extractUserIds
from thread import get_ident
from _thread import get_ident
me = get_ident()
def _extractUserIds(pas, request, plugins):
if me == get_ident():
......@@ -1575,7 +1575,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:
......@@ -1652,7 +1652,7 @@ def optimize():
PythonScript._compile = _compile
PythonScript_exec = PythonScript._exec
def _exec(self, *args):
self.func_code # trigger compilation if needed
self.__code__ # trigger compilation if needed
return PythonScript_exec(self, *args)
PythonScript._exec = _exec
from Acquisition import aq_parent
......
......@@ -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)
......@@ -148,7 +148,7 @@ class SavedTestSuite(ERP5TypeTestSuite):
def __init__(self, *args, **kw):
# Use same portal id for all tests run by current instance
# but keep it (per-run) random.
self._portal_id = 'portal_%i' % (random.randint(0, sys.maxint), )
self._portal_id = 'portal_%i' % (random.randint(0, sys.maxsize), )
super(SavedTestSuite, self).__init__(*args, **kw)
def getLogDirectoryPath(self, *args, **kw):
......@@ -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,
......
......@@ -2,7 +2,7 @@
import errno, logging, os, socket, time
import itertools
from threading import Thread
from UserDict import IterableUserDict
from collections import UserDict
import Lifetime
import transaction
from Testing import ZopeTestCase
......@@ -14,7 +14,7 @@ from Products.ERP5Type.tests.utils import \
from Products.CMFActivity.ActivityTool import getCurrentNode
class DictPersistentWrapper(IterableUserDict, object):
class DictPersistentWrapper(UserDict, object):
def __metaclass__(name, base, d):
def wrap(attr):
......@@ -74,7 +74,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):
......@@ -112,7 +112,7 @@ def Application_resolveConflict(self, old_state, saved_state, new_state):
new_state['test_distributing_node'] = test_distributing_node_set.pop()
old, saved, new = [set(state.pop('test_processing_nodes', {}).items())
for state in old_state, saved_state, new_state]
for state in (old_state, saved_state, new_state)]
# The value of these attributes don't have proper __eq__ implementation.
for attr in '__before_traverse__', '__before_publishing_traverse__':
del old_state[attr], saved_state[attr]
......@@ -318,7 +318,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 io import StringIO
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from lib2to3.main import main
......
......@@ -56,7 +56,7 @@ def special_extract_tb(tb, limit = None):
else: line = None
# display where we failed in the sequence
if co == Sequence.play.func_code:
if co == Sequence.play.__code__:
if line is None:
line = ''
sequence = f.f_locals['self']
......
from __future__ import print_function
##############################################################################
#
# Copyright (c) 2013 Nexedi SA and Contributors. All Rights Reserved.
......@@ -33,4 +34,4 @@ class TestPystone(unittest.TestCase):
"""Tests to get pystone value
"""
def test_pystone(self):
print "PYSTONE RESULT (time,score) : %r" % (pystone.pystones(),)
print("PYSTONE RESULT (time,score) : %r" % (pystone.pystones(),))
from __future__ import print_function
##############################################################################
#
# Copyright (c) 2013 Nexedi SA and Contributors. All Rights Reserved.
......@@ -55,11 +56,11 @@ class TestSQLBench(unittest.TestCase):
sqlbench_path + '/test-alter-table',
'--database', database,
'--host', host, '--user', user, '--password', password]
print command_list
print(command_list)
process = subprocess.Popen(command_list,
cwd = sqlbench_path,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
self.assertEqual(0, len(error), error)
print output
print(output)
self.assertTrue(output.find("Total time: ")>=0)
......@@ -35,7 +35,7 @@ def patch():
self.stream.writeln()
# 'None' correspond to redundant errors due to site creation errors,
# and we do not display them here.
self.printErrorList('ERROR', filter(None, self.errors))
self.printErrorList('ERROR', [_f for _f in self.errors if _f])
self.printErrorList('FAIL', self.failures)
if self.unexpectedSuccesses:
self.stream.writeln(self.separator1)
......
......@@ -7,6 +7,7 @@ from asyncore import socket_map
from ZODB.DemoStorage import DemoStorage
from ZODB.FileStorage import FileStorage
from Products.ERP5Type.tests.utils import getMySQLArguments, instance_random
from six.moves import xrange
def _print(message):
sys.stderr.write(message + "\n")
......
#!/usr/bin/env python2.7
from __future__ import print_function
from __future__ import absolute_import
import argparse, sys, os, textwrap
from erp5.util import taskdistribution
......@@ -8,7 +9,7 @@ from erp5.util import taskdistribution
from . import ERP5TypeTestSuite
def _parsingErrorHandler(data, _):
print >> sys.stderr, 'Error parsing data:', repr(data)
print('Error parsing data:', repr(data), file=sys.stderr)
taskdistribution.patchRPCParser(_parsingErrorHandler)
def makeSuite(
......@@ -20,7 +21,7 @@ def makeSuite(
zserver_frontend_url_list=None,
**kwargs):
# BBB tests (plural form) is only checked for backward compatibility
for k in sys.modules.keys():
for k in list(sys.modules.keys()):
if k in ('tests', 'test',) or k.startswith('tests.') or k.startswith('test.'):
del sys.modules[k]
singular_succeed = True
......@@ -119,8 +120,8 @@ def main():
args.zserver_frontend_url_list.split(',') if args.zserver_frontend_url_list else ())
if args.zserver_address_list and len(args.zserver_address_list) < args.node_quantity:
print >> sys.stderr, 'Not enough zserver address/frontends for node quantity %s (%r)' % (
args.node_quantity, args.zserver_address_list)
print('Not enough zserver address/frontends for node quantity %s (%r)' % (
args.node_quantity, args.zserver_address_list), file=sys.stderr)
sys.exit(1)
# sanity check
......@@ -142,7 +143,7 @@ def main():
if test_result is not None:
assert revision == test_result.revision, (revision, test_result.revision)
while suite.acquire():
test = test_result.start(suite.running.keys())
test = test_result.start(list(suite.running.keys()))
if test is not None:
suite.start(test.name, lambda status_dict, __test=test:
__test.stop(**status_dict))
......
#!/usr/bin/env python2.7
from __future__ import print_function
import os
import sys
import pdb
......@@ -677,7 +678,7 @@ def runUnitTestList(test_list, verbosity=1, debug=0, run_only=None):
transaction.commit()
except:
import traceback
print "runUnitTestList Exception : %r" % (traceback.print_exc(),)
print("runUnitTestList Exception : %r" % (traceback.print_exc(),))
# finally does not expect opened transaction, even in the
# case of a Ctrl-C.
transaction.abort()
......@@ -716,10 +717,10 @@ def runUnitTestList(test_list, verbosity=1, debug=0, run_only=None):
def usage(stream, msg=None):
if msg:
print >>stream, msg
print >>stream
print(msg, file=stream)
print(file=stream)
program = os.path.basename(sys.argv[0])
print >>stream, __doc__ % {"program": program}
print(__doc__ % {"program": program}, file=stream)
log_directory = None
def main(argument_list=None):
......@@ -772,7 +773,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)
......@@ -895,10 +896,9 @@ def main(argument_list=None):
elif opt == "--with_wendelin_core":
os.environ["with_wendelin_core"] = "1"
bt5_path_list += filter(None,
os.environ.get("erp5_tests_bt5_path", "").split(','))
bt5_path_list += [_f for _f in os.environ.get("erp5_tests_bt5_path", "").split(',') if _f]
valid_path_list = []
for path in map(os.path.expanduser, bt5_path_list) if bt5_path_list else (
for path in [os.path.expanduser(x) for x in bt5_path_list] if bt5_path_list else (
os.path.join(real_instance_home if WIN else instance_home, 'bt5'),):
if os.path.exists(path):
valid_path_list.append(path)
......
......@@ -2781,7 +2781,7 @@ class TestGC(XMLObject):
import gc
initial_gc_debug_flags = gc.get_debug()
initial_stderr = sys.stderr
from cStringIO import StringIO
from io import StringIO
stderr = StringIO()
try:
gc.disable()
......
......@@ -26,9 +26,9 @@
#
##############################################################################
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
import StringIO
import urllib
import httplib
import io
import urllib.request, urllib.parse, urllib.error
import http.client
class TestUpgradeInstanceWithOldDataFs(ERP5TypeTestCase):
......@@ -118,7 +118,7 @@ class TestUpgradeInstanceWithOldDataFs(ERP5TypeTestCase):
ret = self.publish(
'%s/portal_alarms/promise_check_upgrade' % self.portal.getPath(),
basic='%s:current' % self.id(),
stdin=StringIO.StringIO(urllib.urlencode({
stdin=io.StringIO(urllib.parse.urlencode({
'Base_callDialogMethod:method': '',
'dialog_id': 'Alarm_viewSolveDialog',
'dialog_method': 'Alarm_solve',
......@@ -128,7 +128,7 @@ class TestUpgradeInstanceWithOldDataFs(ERP5TypeTestCase):
request_method="POST",
handle_errors=False
)
self.assertEqual(httplib.FOUND, ret.getStatus())
self.assertEqual(http.client.FOUND, ret.getStatus())
alarm.Alarm_solve()
......
......@@ -49,6 +49,7 @@ from email import message_from_string
from Products.ERP5Type.Globals import PersistentMapping
from Products.ERP5Type.Utils import simple_decorator
from Products.ZSQLCatalog.SQLCatalog import Catalog
from six.moves import xrange
class FileUpload(file):
"""Act as an uploaded file.
......@@ -397,7 +398,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()
......@@ -589,8 +590,7 @@ def updateCellList(portal, line, cell_type, cell_range_method, cell_dict_list):
def getSortedCategoryList(line, base_id, category_list):
result = []
index_list = line.index[base_id].keys()
index_list.sort()
index_list = sorted(line.index[base_id].keys())
for category in category_list:
for index in index_list:
if line.index[base_id][index]:
......@@ -666,7 +666,7 @@ def updateCellList(portal, line, cell_type, cell_range_method, cell_dict_list):
*category_list)
cell.edit(**mapped_value_dict)
cell.setMappedValuePropertyList(mapped_value_dict.keys())
cell.setMappedValuePropertyList(list(mapped_value_dict.keys()))
base_category_list = [category_path
for category_path in category_list
......
......@@ -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:
f(*args, **kw)
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))
......
......@@ -35,8 +35,9 @@ class FakeRequest:
def clear(self):
self.dict.clear()
def __nonzero__(self):
def __bool__(self):
return 0
__nonzero__ = __bool__ # six.PY2
class SerializeTestCase(unittest.TestCase):
def test_simpleSerialize(self):
......@@ -210,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
......@@ -343,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) )
......@@ -399,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) )
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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