Commit 4a639656 authored by Jérome Perrin's avatar Jérome Perrin

use print_function future

This uses `from __future__ import print_function` from "unrestricted" python code.

For restricted python in python scripts, this expects SlapOS to have nexedi/slapos!1536 .
Running ERP5 with this patch on an old SlapOS software release should probably be OK,
especially because after all we don't have so much critical code using print.

To ease migration of custom project code, PythonCodeUtils was modified so that
when running CodingStyle python scripts are checked with print_function future enabled.

See merge request nexedi/erp5!1883
parents d63ec839 3b11c726
...@@ -26,9 +26,9 @@ informations = { 'processing': processing, ...@@ -26,9 +26,9 @@ informations = { 'processing': processing,
if informations['processing'] in ['converted', 'conversion_failed','empty']: if informations['processing'] in ['converted', 'conversion_failed','empty']:
informations['permanent_url'] = document.Document_getPermanentUrl() 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) portal.portal_sessions.manage_delObjects(reference)
else: else:
print dumps(informations) print(dumps(informations))
return printed return printed
...@@ -35,7 +35,7 @@ search_params = dict( ...@@ -35,7 +35,7 @@ search_params = dict(
for brain in portal.portal_simulation.getInventoryList(**search_params): for brain in portal.portal_simulation.getInventoryList(**search_params):
if round(brain.total_price, precision) == 0: 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: if fixit:
tr = brain.getObject().getParentValue() tr = brain.getObject().getParentValue()
grouped_line_list = tr.AccountingTransaction_guessGroupedLines() grouped_line_list = tr.AccountingTransaction_guessGroupedLines()
...@@ -51,9 +51,9 @@ for brain in portal.portal_simulation.getInventoryList(**search_params): ...@@ -51,9 +51,9 @@ for brain in portal.portal_simulation.getInventoryList(**search_params):
portal_type=portal.getPortalAccountingMovementTypeList(), portal_type=portal.getPortalAccountingMovementTypeList(),
grouping_reference=None,) if not line.getObject().getGroupingReference()]) grouping_reference=None,) if not line.getObject().getGroupingReference()])
if grouped_line_list: if grouped_line_list:
print 'FIXED', grouped_line_list print('FIXED %s' % grouped_line_list)
else: else:
print 'NOT FIXED' print('NOT FIXED')
active_result = ActiveResult( active_result = ActiveResult(
summary=context.getTitle(), summary=context.getTitle(),
......
...@@ -78,7 +78,7 @@ for property_dict in object_list: ...@@ -78,7 +78,7 @@ for property_dict in object_list:
gap = str(gap) gap = str(gap)
if gap: if gap:
gap = gap.replace('CLASSE ', '') 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 path = root
b = '' b = ''
for a in gap: for a in gap:
...@@ -96,7 +96,7 @@ for path in existing_path_list: ...@@ -96,7 +96,7 @@ for path in existing_path_list:
description = document.getDescription() or '' description = document.getDescription() or ''
gap = document.getId() or '' gap = document.getId() or ''
title = document.getTitle() 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()) document.getParentValue().deleteContent(document.getId())
return printed return printed
...@@ -7,7 +7,7 @@ for cat in category_list: ...@@ -7,7 +7,7 @@ for cat in category_list:
cat.getObject().setId(newid) cat.getObject().setId(newid)
except: except:
pass pass
print newid print(newid)
print 'Categories Renamed' print('Categories Renamed')
return printed return printed
...@@ -7,7 +7,7 @@ for cat in category_list: ...@@ -7,7 +7,7 @@ for cat in category_list:
cat.getObject().setId(newid) cat.getObject().setId(newid)
except: except:
pass pass
print newid print(newid)
print 'Categories Renamed' print('Categories Renamed')
return printed return printed
...@@ -48,7 +48,7 @@ dane.p59=dane.p55-dane.p56 ...@@ -48,7 +48,7 @@ dane.p59=dane.p55-dane.p56
if debug: if debug:
for f in range(20,60): for f in range(20,60):
n='p'+str(f) n='p'+str(f)
print n,getattr(dane,n) print(n,getattr(dane,n))
return printed return printed
return container[report].index_html(REQUEST=context.REQUEST, RESPONSE=context.REQUEST.RESPONSE,dane=dane) 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 ...@@ -5,7 +5,7 @@ Warning: Before using this script as zope, edit account_workflow and give Manage
#This script will REMOVE any existing accounts!!! #This script will REMOVE any existing accounts!!!
#comment following if you are sure #comment following if you are sure
print 'Nothing done!' print('Nothing done!')
return printed return printed
...@@ -22,7 +22,7 @@ for category in gap_root.getCategoryMemberValueList(): ...@@ -22,7 +22,7 @@ for category in gap_root.getCategoryMemberValueList():
acc = account_module.newContent(title='%s %s' % (category.getId(),category.getTitle()),\ acc = account_module.newContent(title='%s %s' % (category.getId(),category.getTitle()),\
gap_value = category) gap_value = category)
acc.validate() acc.validate()
print 'acc created' print('acc created')
return printed return printed
...@@ -251,7 +251,7 @@ for line in gap_text.splitlines(): ...@@ -251,7 +251,7 @@ for line in gap_text.splitlines():
cpath += n cpath += n
path.append(cpath) path.append(cpath)
parent = gap.restrictedTraverse('/'.join(path)) parent = gap.restrictedTraverse('/'.join(path))
print 'Added to ',parent print('Added to ',parent)
parent.newContent(id=num, title=descr) parent.newContent(id=num, title=descr)
......
container.REQUEST.RESPONSE.setHeader('content-type', 'text/html') container.REQUEST.RESPONSE.setHeader('content-type', 'text/html')
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': 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 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) 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): 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('<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('</tbody> </table> <br/>')
return printed return printed
...@@ -10,14 +10,14 @@ for security_uid_field in security_uid_field_list: ...@@ -10,14 +10,14 @@ for security_uid_field in security_uid_field_list:
print(">> useless uids in roles_and_users table <<\n") print(">> useless uids in roles_and_users table <<\n")
if len(referenced_uid_set) > 0: if len(referenced_uid_set) > 0:
for row in req("select * from roles_and_users where uid not in %s" + tuple(referenced_uid_set)): 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") 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")} 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 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))): 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 <<") print("\n>> END <<")
return printed return printed
...@@ -6,18 +6,18 @@ u = getSecurityManager().getUser() ...@@ -6,18 +6,18 @@ u = getSecurityManager().getUser()
user_value = u.getUserValue() user_value = u.getUserValue()
if user_value is None: if user_value is None:
print 'User ID:', u.getId() print('User ID:', u.getId())
else: else:
print 'User ID:', u.getId(), user_value.getPath() print('User ID:', u.getId(), user_value.getPath())
login_value = u.getLoginValue() login_value = u.getLoginValue()
if login_value is None: if login_value is None:
print 'Login:', u.getUserName() print('Login:', u.getUserName())
else: else:
print 'Login:', u.getUserName(), login_value.getPath() print('Login:', u.getUserName(), login_value.getPath())
print 'Is owner:', u.allowed(context,('Owner',)) print('Is owner:', u.allowed(context,('Owner',)))
print 'User roles:', u.getRoles() print('User roles:', u.getRoles())
print 'User roles in context:', u.getRolesInContext(context) print('User roles in context:', u.getRolesInContext(context))
print 'Permissions:' print('Permissions:')
for permission in [ for permission in [
'Access contents information', 'Access contents information',
'Add portal content', 'Add portal content',
...@@ -26,25 +26,25 @@ for permission in [ ...@@ -26,25 +26,25 @@ for permission in [
'View', 'View',
'Manage portal', 'Manage portal',
]: ]:
print " ", permission, u.has_permission(permission, context) print(" ", permission, u.has_permission(permission, context))
print print()
try: try:
print "User groups:\n", pformat(sorted(u.getGroups())) print("User groups:\n", pformat(sorted(u.getGroups())))
except AttributeError: except AttributeError:
print 'no getGroups' print('no getGroups')
print print()
print 'Local roles on document:\n', pformat(context.get_local_roles()) print('Local roles on document:\n', pformat(context.get_local_roles()))
print ''' print('''
---------------- ----------------
Security mapping Security mapping
----------------''' ----------------''')
if u.getId() is not None: if u.getId() is not None:
try: try:
print context.Base_viewSecurityMappingAsUser(u.getId()) print(context.Base_viewSecurityMappingAsUser(u.getId()))
except Unauthorized: except Unauthorized:
print "user doesn't have permission to security mapping in this context" print("user doesn't have permission to security mapping in this context")
return printed return printed
...@@ -16,12 +16,12 @@ for method_id, base_category_list in getSecurityCategoryMapping(): ...@@ -16,12 +16,12 @@ for method_id, base_category_list in getSecurityCategoryMapping():
security_category_dict.setdefault(tuple(base_category_list), []).extend( security_category_dict.setdefault(tuple(base_category_list), []).extend(
getattr(context, method_id)(base_category_list, login, context, '')) getattr(context, method_id)(base_category_list, login, context, ''))
except Exception: # XXX: it is not possible to log message with traceback from python script except Exception: # XXX: it is not possible to log message with traceback from python script
print 'It was not possible to invoke method %s with base_category_list %s'%(method_id, base_category_list) print('It was not possible to invoke method %s with base_category_list %s'%(method_id, base_category_list))
for base_category_list, category_value_list in security_category_dict.items(): for base_category_list, category_value_list in security_category_dict.items():
print 'base_category_list:', base_category_list print('base_category_list: %s' % (base_category_list,))
for category_dict in category_value_list: for category_dict in category_value_list:
print '-> category_dict:', category_dict print('-> category_dict: %s' % category_dict)
print '-->', group_id_list_generator(category_order=base_category_list, print('--> %s' % group_id_list_generator(category_order=base_category_list,
**category_dict) **category_dict))
return printed return printed
...@@ -20,7 +20,7 @@ if context.getPortalType() == 'Alarm': ...@@ -20,7 +20,7 @@ if context.getPortalType() == 'Alarm':
else: else:
active_process = context.portal_activities.newActiveProcess().getPath() active_process = context.portal_activities.newActiveProcess().getPath()
ERP5Site_checkDataWithScript = context.portal_activities.ERP5Site_checkDataWithScript 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() checkTopLevel()
ERP5Site_checkDataWithScript( ERP5Site_checkDataWithScript(
......
for builder in sorted(context.getPortalObject().portal_deliveries.contentValues(), for builder in sorted(context.getPortalObject().portal_deliveries.contentValues(),
key=lambda x:x.getTitle()): key=lambda x:x.getTitle()):
print builder.getId() print(builder.getId())
print " Title: %s" % (builder.getTitle()) print(" Title: %s" % (builder.getTitle()))
print " Simulation Select Method: %s" % (builder.getSimulationSelectMethodId()) print(" Simulation Select Method: %s" % (builder.getSimulationSelectMethodId()))
print " Delivery Select Method: %s" % (builder.getDeliverySelectMethodId()) print(" Delivery Select Method: %s" % (builder.getDeliverySelectMethodId()))
print " After Generation Script: %s" % (builder.getDeliveryAfterGenerationScriptId()) print(" After Generation Script: %s" % (builder.getDeliveryAfterGenerationScriptId()))
print print()
for mg in sorted(builder.contentValues(), key=lambda x:x.getTitle()): for mg in sorted(builder.contentValues(), key=lambda x:x.getTitle()):
print builder.getId() print(builder.getId())
print " ", "\n ".join([x for x in ( print(" ", "\n ".join([x for x in (
"Id: %s" % mg.getId(), "Id: %s" % mg.getId(),
"Title: %s" % mg.getTitle(), "Title: %s" % mg.getTitle(),
"Type: %s" % mg.getPortalType(), "Type: %s" % mg.getPortalType(),
...@@ -17,7 +17,7 @@ for builder in sorted(context.getPortalObject().portal_deliveries.contentValues( ...@@ -17,7 +17,7 @@ for builder in sorted(context.getPortalObject().portal_deliveries.contentValues(
"Tested Properties: %r" % mg.getTestedPropertyList(), "Tested Properties: %r" % mg.getTestedPropertyList(),
"Update Always: %r" % mg.isUpdateAlways(), "Update Always: %r" % mg.isUpdateAlways(),
)]) )]))
print print()
return printed return printed
...@@ -4,6 +4,6 @@ for business_template in sorted(context.getPortalObject().portal_templates.conte ...@@ -4,6 +4,6 @@ for business_template in sorted(context.getPortalObject().portal_templates.conte
key=lambda x:x.getTitle()): key=lambda x:x.getTitle()):
if business_template.getInstallationState() == 'installed' and \ if business_template.getInstallationState() == 'installed' and \
business_template.getTitle() not in ignore_business_template_list: business_template.getTitle() not in ignore_business_template_list:
print business_template.getTitle() print(business_template.getTitle())
return printed return printed
for builder in sorted(context.getPortalObject().portal_orders.contentValues(), for builder in sorted(context.getPortalObject().portal_orders.contentValues(),
key=lambda x:x.getTitle()): key=lambda x:x.getTitle()):
print builder.getId() print(builder.getId())
print " Title: %s" % (builder.getTitle()) print(" Title: %s" % (builder.getTitle()))
print " Simulation Select Method: %s" % (builder.getSimulationSelectMethodId()) print(" Simulation Select Method: %s" % (builder.getSimulationSelectMethodId()))
print " Delivery Select Method: %s" % (builder.getDeliverySelectMethodId()) print(" Delivery Select Method: %s" % (builder.getDeliverySelectMethodId()))
print " After Generation Script: %s" % (builder.getDeliveryAfterGenerationScriptId()) print(" After Generation Script: %s" % (builder.getDeliveryAfterGenerationScriptId()))
print " Delivery Module Before Building Script: %s" % (builder.getDeliveryModuleBeforeBuildingScriptId()) print(" Delivery Module Before Building Script: %s" % (builder.getDeliveryModuleBeforeBuildingScriptId()))
print print()
for mg in sorted(builder.contentValues(), key=lambda x:x.getTitle()): for mg in sorted(builder.contentValues(), key=lambda x:x.getTitle()):
print builder.getId() print(builder.getId())
print " ", "\n ".join([x for x in ( print(" ", "\n ".join([x for x in (
"Id: %s" % mg.getId(), "Id: %s" % mg.getId(),
"Title: %s" % mg.getTitle(), "Title: %s" % mg.getTitle(),
"Type: %s" % mg.getPortalType(), "Type: %s" % mg.getPortalType(),
...@@ -18,7 +18,7 @@ for builder in sorted(context.getPortalObject().portal_orders.contentValues(), ...@@ -18,7 +18,7 @@ for builder in sorted(context.getPortalObject().portal_orders.contentValues(),
"Tested Properties: %r" % mg.getTestedPropertyList(), "Tested Properties: %r" % mg.getTestedPropertyList(),
"Update Always: %r" % mg.isUpdateAlways(), "Update Always: %r" % mg.isUpdateAlways(),
)]) )]))
print print()
return printed return printed
...@@ -37,12 +37,12 @@ for skin_folder in portal.portal_skins.objectValues('Folder'): ...@@ -37,12 +37,12 @@ for skin_folder in portal.portal_skins.objectValues('Folder'):
for skin in skin_folder.objectValues(): for skin in skin_folder.objectValues():
if skin.getId() in ignore_skin_list: if skin.getId() in ignore_skin_list:
continue continue
print getSkinHash(skin, skin_folder) print(getSkinHash(skin, skin_folder))
if include_workflow_scripts: if include_workflow_scripts:
for workflow in portal.portal_workflow.objectValues(): for workflow in portal.portal_workflow.objectValues():
for skin in workflow.scripts.objectValues(): for skin in workflow.scripts.objectValues():
print getSkinHash(skin, workflow) print(getSkinHash(skin, workflow))
container.REQUEST.RESPONSE.setHeader('content-type', 'text/plain') container.REQUEST.RESPONSE.setHeader('content-type', 'text/plain')
return '\n'.join(sorted(printed.splitlines())) return '\n'.join(sorted(printed.splitlines()))
for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lambda x:x.getId()): for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lambda x:x.getId()):
for ai in sorted(ti.contentValues(portal_type='Action Information'), key=lambda x:x.getReference()): for ai in sorted(ti.contentValues(portal_type='Action Information'), key=lambda x:x.getReference()):
print ti.getId() print(ti.getId())
print " ", "\n ".join([x for x in ( print(" ", "\n ".join([x for x in (
"Reference: %s" % ai.getReference(), "Reference: %s" % ai.getReference(),
"Title: %s" % ai.getTitle(), "Title: %s" % ai.getTitle(),
"Action: %s" % ai.getActionText(), "Action: %s" % ai.getActionText(),
...@@ -9,7 +9,7 @@ for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lam ...@@ -9,7 +9,7 @@ for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lam
"Permission: %s" % ai.getActionPermission(), "Permission: %s" % ai.getActionPermission(),
"Action Type: %s" % ai.getActionType(), "Action Type: %s" % ai.getActionType(),
"Visible: %s" % ai.getVisible(), "Visible: %s" % ai.getVisible(),
"Index: %s" % ai.getFloatIndex())]) "Index: %s" % ai.getFloatIndex())]))
print print()
return printed return printed
for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lambda x:x.getId()): for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lambda x:x.getId()):
print ti.getId() print(ti.getId())
print " ", "\n ".join([x for x in ( print(" ", "\n ".join([x for x in (
"Short Title: %s" % ti.getShortTitle(), "Short Title: %s" % ti.getShortTitle(),
"Class: %s" % ti.getTypeClass(), "Class: %s" % ti.getTypeClass(),
"Init Script: %s" % ti.getTypeInitScriptId(), "Init Script: %s" % ti.getTypeInitScriptId(),
...@@ -12,7 +12,7 @@ for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lam ...@@ -12,7 +12,7 @@ for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lam
"Hidden Content Types: %r" % sorted(ti.getTypeHiddenContentTypeList()), "Hidden Content Types: %r" % sorted(ti.getTypeHiddenContentTypeList()),
"Searchable Property: %r" % sorted(ti.getSearchableTextPropertyIdList()), "Searchable Property: %r" % sorted(ti.getSearchableTextPropertyIdList()),
"Searchable Method: %r" % sorted(ti.getSearchableTextMethodIdList()), "Searchable Method: %r" % sorted(ti.getSearchableTextMethodIdList()),
)]) )]))
print print()
return printed return printed
for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lambda x:x.getId()): for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lambda x:x.getId()):
for ri in sorted(ti.contentValues(portal_type='Role Information'), key=lambda x:(x.getTitle(), x.getLocalRoleGroupId(), x.getRoleBaseCategoryScriptId(), x.getRoleBaseCategoryList())): for ri in sorted(ti.contentValues(portal_type='Role Information'), key=lambda x:(x.getTitle(), x.getLocalRoleGroupId(), x.getRoleBaseCategoryScriptId(), x.getRoleBaseCategoryList())):
print ti.getId() print(ti.getId())
print " ", "\n ".join([x for x in ( print(" ", "\n ".join([x for x in (
"Title: %s" % ri.getTitle(), "Title: %s" % ri.getTitle(),
"Roles: %r" % ri.getRoleNameList(), "Roles: %r" % ri.getRoleNameList(),
"Condition: %s" % ri.getConditionText(), "Condition: %s" % ri.getConditionText(),
"Local Roles Group Id: %s" % ri.getLocalRoleGroupId(), "Local Roles Group Id: %s" % ri.getLocalRoleGroupId(),
"Base Categories: %r" % ri.getRoleBaseCategoryList(), "Base Categories: %r" % ri.getRoleBaseCategoryList(),
"Base Category Script: %s" % ri.getRoleBaseCategoryScriptId(), "Base Category Script: %s" % ri.getRoleBaseCategoryScriptId(),
"Categories: %r" % ri.getRoleCategoryList() )]) "Categories: %r" % ri.getRoleCategoryList() )]))
print print()
return printed return printed
...@@ -6,7 +6,7 @@ for ps in sorted(context.getPortalObject().portal_property_sheets.contentValues( ...@@ -6,7 +6,7 @@ for ps in sorted(context.getPortalObject().portal_property_sheets.contentValues(
ps_id = ps.getId() ps_id = ps.getId()
if ps_id in ignore_property_sheet_list: if ps_id in ignore_property_sheet_list:
continue continue
print ps.getId() print(ps.getId())
info_list = ['id', 'portal_type', 'reference'] info_list = ['id', 'portal_type', 'reference']
std_prop_list = ['elementary_type', 'property_default', 'storage_id', 'multivaluated', 'range', 'preference', 'read_permission', 'write_permission', 'translatable', 'translation_domain'] std_prop_list = ['elementary_type', 'property_default', 'storage_id', 'multivaluated', 'range', 'preference', 'read_permission', 'write_permission', 'translatable', 'translation_domain']
if pd.getPortalType() == 'Standard Property': if pd.getPortalType() == 'Standard Property':
...@@ -29,10 +29,10 @@ for ps in sorted(context.getPortalObject().portal_property_sheets.contentValues( ...@@ -29,10 +29,10 @@ for ps in sorted(context.getPortalObject().portal_property_sheets.contentValues(
elif pd.getPortalType().endswith('Constraint'): elif pd.getPortalType().endswith('Constraint'):
info_list += [] + [p for p in pd.propertyIds() if p.startswith('message')] info_list += [] + [p for p in pd.propertyIds() if p.startswith('message')]
else: else:
print "(not supported)",pd.getRelativeUrl(), pd.getPortalType() print("(not supported)",pd.getRelativeUrl(), pd.getPortalType())
print " ", "\n ".join(['%s: %s' % (prop, pd.getProperty(prop)) for prop in sorted(info_list)]) print(" ", "\n ".join(['%s: %s' % (prop, pd.getProperty(prop)) for prop in sorted(info_list)]))
print print()
return printed return printed
...@@ -2,17 +2,17 @@ for rule in sorted(context.getPortalObject().portal_rules.contentValues(), ...@@ -2,17 +2,17 @@ for rule in sorted(context.getPortalObject().portal_rules.contentValues(),
key=lambda x:x.getTitle()): key=lambda x:x.getTitle()):
if rule.getValidationState() != 'validated': if rule.getValidationState() != 'validated':
continue continue
print rule.getId() print(rule.getId())
print " Title: %s" % (rule.getTitle()) print(" Title: %s" % (rule.getTitle()))
print " Trade Phases: %r" % (rule.getTradePhaseList()) print(" Trade Phases: %r" % (rule.getTradePhaseList()))
print " Test Method Id: %s" % (rule.getTestMethodId()) print(" Test Method Id: %s" % (rule.getTestMethodId()))
print " Membership Criteria: %r" % (rule.getMembershipCriterionBaseCategoryList()) print(" Membership Criteria: %r" % (rule.getMembershipCriterionBaseCategoryList()))
print " Membership Criterion Category: %r" % (rule.getMembershipCriterionCategoryList()) print(" Membership Criterion Category: %r" % (rule.getMembershipCriterionCategoryList()))
print print()
for tester in sorted(rule.contentValues(), key=lambda x:x.getTitle()): for tester in sorted(rule.contentValues(), key=lambda x:x.getTitle()):
print rule.getId() print(rule.getId())
print " ", "\n ".join([x for x in ( print(" ", "\n ".join([x for x in (
"Id: %s" % tester.getId(), "Id: %s" % tester.getId(),
"Title: %s" % tester.getTitle(), "Title: %s" % tester.getTitle(),
"Type: %s" % tester.getPortalType(), "Type: %s" % tester.getPortalType(),
...@@ -25,7 +25,7 @@ for rule in sorted(context.getPortalObject().portal_rules.contentValues(), ...@@ -25,7 +25,7 @@ for rule in sorted(context.getPortalObject().portal_rules.contentValues(),
(tester.getMembershipCriterionBaseCategoryList()), (tester.getMembershipCriterionBaseCategoryList()),
"Membership Criterion Category: %r" % "Membership Criterion Category: %r" %
(tester.getMembershipCriterionCategoryList()), (tester.getMembershipCriterionCategoryList()),
)]) )]))
print print()
return printed return printed
...@@ -13,5 +13,5 @@ for name, layers in skin_tool.getSkinPaths(): ...@@ -13,5 +13,5 @@ for name, layers in skin_tool.getSkinPaths():
if ignore_skin_folder_list is not None and\ if ignore_skin_folder_list is not None and\
layer in ignore_skin_folder_list: layer in ignore_skin_folder_list:
continue continue
print '%s,%s' % (name, layer) print('%s,%s' % (name, layer))
return printed return printed
...@@ -13,6 +13,6 @@ for field_path, field in context.ZopeFind( ...@@ -13,6 +13,6 @@ for field_path, field in context.ZopeFind(
relation_setter_id = field.get_value('relation_setter_id') relation_setter_id = field.get_value('relation_setter_id')
if relation_setter_id: if relation_setter_id:
print field_path, relation_setter_id print(field_path, relation_setter_id)
return printed return printed
...@@ -16,6 +16,6 @@ for bt in bt_list: ...@@ -16,6 +16,6 @@ for bt in bt_list:
delete_list.append(bt_id) delete_list.append(bt_id)
break break
print 'Deleted id list:%r' % delete_list print('Deleted id list:%r' % delete_list)
portal_templates.manage_delObjects(delete_list) portal_templates.manage_delObjects(delete_list)
return printed return printed
...@@ -8,5 +8,5 @@ context.ERP5Site_checkDataWithScript("Base_migrateToEmbeddedFile", ...@@ -8,5 +8,5 @@ context.ERP5Site_checkDataWithScript("Base_migrateToEmbeddedFile",
active_process=active_process.getPath(), active_process=active_process.getPath(),
method_kw=dict(force=1)) method_kw=dict(force=1))
print "Migration started with process id: %s" %active_process.getPath() print("Migration started with process id: %s" %active_process.getPath())
return printed return printed
from __future__ import print_function
from BTrees.LOBTree import LOBTree from BTrees.LOBTree import LOBTree
from persistent import Persistent from persistent import Persistent
import itertools import itertools
...@@ -314,7 +315,7 @@ class BTreeData(Persistent): ...@@ -314,7 +315,7 @@ class BTreeData(Persistent):
if __name__ == '__main__': if __name__ == '__main__':
def check(tree, length, read_offset, read_length, data_, keys=None): 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_length = len(tree)
tree_data = tree.read(read_offset, read_length) tree_data = tree.read(read_offset, read_length)
tree_iterator_data = ''.join(tree.iterate(read_offset, read_length)) tree_iterator_data = ''.join(tree.iterate(read_offset, read_length))
......
...@@ -68,11 +68,11 @@ for business_application_category_id, module_ids in module_business_application_ ...@@ -68,11 +68,11 @@ for business_application_category_id, module_ids in module_business_application_
if module is not None: if module is not None:
module.edit(business_application = business_application_category_id) module.edit(business_application = business_application_category_id)
print "Indexing translations" print("Indexing translations")
portal.ERP5Site_updateTranslationTable() portal.ERP5Site_updateTranslationTable()
# clear cache so user security is recalculated # clear cache so user security is recalculated
portal.portal_caches.clearAllCache() portal.portal_caches.clearAllCache()
print "Clear cache." print("Clear cache.")
log("%s" % printed) log("%s" % printed)
...@@ -12,7 +12,7 @@ if business_template is not None: ...@@ -12,7 +12,7 @@ if business_template is not None:
filter=dict(portal_type=portal_type)) filter=dict(portal_type=portal_type))
for module in module_list: for module in module_list:
module.updateLocalRolesOnSecurityGroups() module.updateLocalRolesOnSecurityGroups()
print "Updated Role Mappings for: %s(%s) " % (module.getTitle(), module.getPortalType()) print("Updated Role Mappings for: %s(%s) " % (module.getTitle(), module.getPortalType()))
# validate and open all objects # validate and open all objects
for path in business_template.getTemplatePathList(): for path in business_template.getTemplatePathList():
...@@ -22,16 +22,16 @@ if business_template is not None: ...@@ -22,16 +22,16 @@ if business_template is not None:
if obj.getPortalType() not in ('Category', 'Base Category',): if obj.getPortalType() not in ('Category', 'Base Category',):
obj.updateLocalRolesOnSecurityGroups() obj.updateLocalRolesOnSecurityGroups()
print "Updated Role Mappings for: ", path, obj.getPortalType() print("Updated Role Mappings for: ", path, obj.getPortalType())
if obj.getPortalType() in ('Person', 'Organisation'): if obj.getPortalType() in ('Person', 'Organisation'):
for period in obj.contentValues(filter={'portal_type':'Accounting Period'}): for period in obj.contentValues(filter={'portal_type':'Accounting Period'}):
period.updateLocalRolesOnSecurityGroups() period.updateLocalRolesOnSecurityGroups()
print "\tOpen (Accounting Period): ", period.getRelativeUrl() print("\tOpen (Accounting Period): ", period.getRelativeUrl())
for assignment in obj.contentValues(filter={'portal_type':'Assignment'}): for assignment in obj.contentValues(filter={'portal_type':'Assignment'}):
assignment.updateLocalRolesOnSecurityGroups() assignment.updateLocalRolesOnSecurityGroups()
print "\tOpen (assignment): ", assignment.getRelativeUrl() print("\tOpen (assignment): ", assignment.getRelativeUrl())
for solver_type in context.portal_solvers.objectValues(): for solver_type in context.portal_solvers.objectValues():
solver_type.updateLocalRolesOnSecurityGroups() solver_type.updateLocalRolesOnSecurityGroups()
...@@ -96,11 +96,11 @@ if osoe_runner_website is not None: ...@@ -96,11 +96,11 @@ if osoe_runner_website is not None:
available_language_list = list(portal.Localizer.get_supported_languages()) available_language_list = list(portal.Localizer.get_supported_languages())
osoe_runner_website.edit(available_language_set = available_language_list) osoe_runner_website.edit(available_language_set = available_language_list)
print "Indexing translations" print("Indexing translations")
portal.ERP5Site_updateTranslationTable() portal.ERP5Site_updateTranslationTable()
# clear cache so user security is recalculated # clear cache so user security is recalculated
portal.portal_caches.clearAllCache() portal.portal_caches.clearAllCache()
print "Clear cache." print("Clear cache.")
log("%s" % printed) log("%s" % printed)
...@@ -141,7 +141,7 @@ for message in message_list: ...@@ -141,7 +141,7 @@ for message in message_list:
comment_list = message_dict[message] comment_list = message_dict[message]
comment_list.sort() comment_list.sort()
comment = '\n'.join([('#: %s' % i) for i in comment_list]) 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') context.REQUEST.RESPONSE.setHeader('Content-Type', 'text/plain')
......
...@@ -8,10 +8,10 @@ message_list = ["Configuration is over. Enjoy your new ERP5 system!", ...@@ -8,10 +8,10 @@ message_list = ["Configuration is over. Enjoy your new ERP5 system!",
portal.REQUEST.RESPONSE.setHeader('content-type', 'text/plain') portal.REQUEST.RESPONSE.setHeader('content-type', 'text/plain')
for message in message_list: for message in message_list:
if not message in html_status_report: 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(): 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): if str(printed):
return printed return printed
......
...@@ -201,7 +201,7 @@ for serie in series_list: ...@@ -201,7 +201,7 @@ for serie in series_list:
# the last element must be saved # the last element must be saved
data_groups.append(new_group) data_groups.append(new_group)
print data_groups print(data_groups)
# [ # [
...@@ -236,24 +236,24 @@ def aggregate(big_list, item_to_add): ...@@ -236,24 +236,24 @@ def aggregate(big_list, item_to_add):
if big_list == []: if big_list == []:
return [] return []
if getListLevel(big_list) == getListLevel(item_to_add): if getListLevel(big_list) == getListLevel(item_to_add):
print "big_list " + big_list print("big_list " + big_list)
print "item_to_add " + item_to_add print("item_to_add " + item_to_add)
big_list.append(item_to_add) big_list.append(item_to_add)
return big_list return big_list
else: else:
new_big_list_sub_level = aggregate(getLastSubList(big_list), item_to_add) new_big_list_sub_level = aggregate(getLastSubList(big_list), item_to_add)
print "new_big_list_sub_level " + new_big_list_sub_level print("new_big_list_sub_level " + new_big_list_sub_level)
print "big_list " + big_list print("big_list " + big_list)
return None #setLastSubList(big_list, new_big_list_sub_level) return None #setLastSubList(big_list, new_big_list_sub_level)
for group in data_groups: for group in data_groups:
collapsed_group = group[0] collapsed_group = group[0]
for serie_group in group[1:]: for serie_group in group[1:]:
print serie_group print(serie_group)
collapsed_group = aggregate(collapsed_group, serie_group) collapsed_group = aggregate(collapsed_group, serie_group)
print collapsed_group print(collapsed_group)
# if # if
......
...@@ -27,6 +27,7 @@ ...@@ -27,6 +27,7 @@
# #
############################################################################## ##############################################################################
from __future__ import print_function
import random import random
import time import time
...@@ -69,7 +70,7 @@ class TestRamCache(ERP5TypeTestCase): ...@@ -69,7 +70,7 @@ class TestRamCache(ERP5TypeTestCase):
for cache_plugin in filtered_cache_plugins: for cache_plugin in filtered_cache_plugins:
if not self.quiet: if not self.quiet:
print "TESTING (scope): ", cache_plugin print("TESTING (scope): ", cache_plugin)
## clear cache for this plugin ## clear cache for this plugin
cache_plugin.clearCache() cache_plugin.clearCache()
...@@ -85,7 +86,7 @@ class TestRamCache(ERP5TypeTestCase): ...@@ -85,7 +86,7 @@ class TestRamCache(ERP5TypeTestCase):
## we set ONLY one value per scope -> check if we get the same cache_id ## we set ONLY one value per scope -> check if we get the same cache_id
self.assertEqual([cache_id], cache_plugin.getScopeKeyList(scope)) self.assertEqual([cache_id], cache_plugin.getScopeKeyList(scope))
if not self.quiet: if not self.quiet:
print "\t", cache_id, scope, "\t\tOK" print("\t", cache_id, scope, "\t\tOK")
## get list of scopes which must be the same as test_scopes since we clear cache initially ## get list of scopes which must be the same as test_scopes since we clear cache initially
scopes_from_cache = cache_plugin.getScopeList() scopes_from_cache = cache_plugin.getScopeList()
...@@ -118,7 +119,7 @@ class TestRamCache(ERP5TypeTestCase): ...@@ -118,7 +119,7 @@ class TestRamCache(ERP5TypeTestCase):
def generalExpire(self, cache_plugin, iterations): def generalExpire(self, cache_plugin, iterations):
if not self.quiet: if not self.quiet:
print "TESTING (expire): ", cache_plugin print("TESTING (expire): ", cache_plugin)
base_timeout = 1 base_timeout = 1
values = self.prepareValues(iterations) values = self.prepareValues(iterations)
scope = "peter" scope = "peter"
...@@ -128,7 +129,7 @@ class TestRamCache(ERP5TypeTestCase): ...@@ -128,7 +129,7 @@ class TestRamCache(ERP5TypeTestCase):
cache_timeout = base_timeout + random.random()*2 cache_timeout = base_timeout + random.random()*2
cache_id = "mycache_id_to_expire_%s" %(count) cache_id = "mycache_id_to_expire_%s" %(count)
if not self.quiet: if not self.quiet:
print "\t", cache_id, " ==> timeout (s) = ", cache_timeout, print("\t", cache_id, " ==> timeout (s) = ", cache_timeout, end=' ')
## set to cache ## set to cache
cache_plugin.set(cache_id, scope, value, cache_timeout) cache_plugin.set(cache_id, scope, value, cache_timeout)
...@@ -142,11 +143,11 @@ class TestRamCache(ERP5TypeTestCase): ...@@ -142,11 +143,11 @@ class TestRamCache(ERP5TypeTestCase):
## check it, we MUST NOT have this key any more in cache ## check it, we MUST NOT have this key any more in cache
self.assertEqual(False, cache_plugin.has_key(cache_id, scope)) self.assertEqual(False, cache_plugin.has_key(cache_id, scope))
if not self.quiet: if not self.quiet:
print "\t\tOK" print("\t\tOK")
def generaltestSetGet(self, cache_plugin, iterations): def generaltestSetGet(self, cache_plugin, iterations):
if not self.quiet: if not self.quiet:
print "TESTING (set/get/has/del): ", cache_plugin print("TESTING (set/get/has/del): ", cache_plugin)
values = self.prepareValues(iterations) values = self.prepareValues(iterations)
cache_duration = 30 cache_duration = 30
scope = "peter" scope = "peter"
...@@ -158,7 +159,7 @@ class TestRamCache(ERP5TypeTestCase): ...@@ -158,7 +159,7 @@ class TestRamCache(ERP5TypeTestCase):
## set to cache ## set to cache
cache_plugin.set(cache_id, scope, value, cache_duration) cache_plugin.set(cache_id, scope, value, cache_duration)
if not self.quiet: if not self.quiet:
print "\t", cache_id, print("\t", cache_id, end=' ')
## check has_key() ## check has_key()
self.assertEqual(True, cache_plugin.has_key(cache_id, scope)) self.assertEqual(True, cache_plugin.has_key(cache_id, scope))
...@@ -184,7 +185,7 @@ class TestRamCache(ERP5TypeTestCase): ...@@ -184,7 +185,7 @@ class TestRamCache(ERP5TypeTestCase):
self.assertEqual(False, cache_plugin.has_key(cache_id, scope)) self.assertEqual(False, cache_plugin.has_key(cache_id, scope))
if not self.quiet: if not self.quiet:
print "\t\tOK" print("\t\tOK")
def prepareValues(self, iterations): def prepareValues(self, iterations):
""" generate a big list of values """ """ generate a big list of values """
......
...@@ -27,6 +27,7 @@ ...@@ -27,6 +27,7 @@
# #
############################################################################## ##############################################################################
from __future__ import print_function
import time import time
import unittest import unittest
...@@ -227,9 +228,9 @@ return result ...@@ -227,9 +228,9 @@ return result
def _cacheFactoryInstanceTest(self, my_cache, cf_name, clear_allowed): def _cacheFactoryInstanceTest(self, my_cache, cf_name, clear_allowed):
portal = self.portal portal = self.portal
print print()
print "="*40 print("="*40)
print "TESTING:", cf_name print("TESTING:", cf_name)
result = 'a short value' result = 'a short value'
#portal.portal_caches.clearCacheFactory(cf_name) #portal.portal_caches.clearCacheFactory(cf_name)
...@@ -249,12 +250,12 @@ return result ...@@ -249,12 +250,12 @@ return result
result=result) result=result)
## 1st call ## 1st call
calculation_time = callCache(real_calculation=True) calculation_time = callCache(real_calculation=True)
print "\n\tCalculation time (1st call)", calculation_time print("\n\tCalculation time (1st call)", calculation_time)
self.commit() self.commit()
## 2nd call - should be cached now ## 2nd call - should be cached now
calculation_time = callCache(real_calculation=False) calculation_time = callCache(real_calculation=False)
print "\n\tCalculation time (2nd call)", calculation_time print("\n\tCalculation time (2nd call)", calculation_time)
self.commit() self.commit()
## OK so far let's clear cache ## OK so far let's clear cache
...@@ -263,10 +264,10 @@ return result ...@@ -263,10 +264,10 @@ return result
## 1st call ## 1st call
calculation_time = callCache(real_calculation=True) calculation_time = callCache(real_calculation=True)
print "\n\tCalculation time (after cache clear)", calculation_time print("\n\tCalculation time (after cache clear)", calculation_time)
# Test delete method on CachingMethod # Test delete method on CachingMethod
print "\n\tCalculation time (3rd call)", calculation_time print("\n\tCalculation time (3rd call)", calculation_time)
# make sure cache id filled # make sure cache id filled
calculation_time = callCache(real_calculation=False) calculation_time = callCache(real_calculation=False)
...@@ -275,7 +276,7 @@ return result ...@@ -275,7 +276,7 @@ return result
# Check that result is computed # Check that result is computed
calculation_time = callCache(real_calculation=True) calculation_time = callCache(real_calculation=True)
print "\n\tCalculation time (4th call)", calculation_time print("\n\tCalculation time (4th call)", calculation_time)
self.commit() self.commit()
def test_03_cachePersistentObjects(self): def test_03_cachePersistentObjects(self):
...@@ -296,9 +297,9 @@ return result ...@@ -296,9 +297,9 @@ return result
def test_04_CheckConcurrentRamCacheDict(self): def test_04_CheckConcurrentRamCacheDict(self):
"""Check that all RamCache doesn't clear the same cache_dict """Check that all RamCache doesn't clear the same cache_dict
""" """
print print()
print "="*40 print("="*40)
print "TESTING: Concurrent RamCache" print("TESTING: Concurrent RamCache")
portal = self.portal portal = self.portal
result = 'Something short' result = 'Something short'
...@@ -317,7 +318,7 @@ return result ...@@ -317,7 +318,7 @@ return result
result=result) result=result)
end = time.time() end = time.time()
calculation_time = end-start calculation_time = end-start
print "\n\tCalculation time (1st call)", calculation_time print("\n\tCalculation time (1st call)", calculation_time)
self.assertEqual(cached, result) self.assertEqual(cached, result)
self.commit() self.commit()
...@@ -328,7 +329,7 @@ return result ...@@ -328,7 +329,7 @@ return result
result=result) result=result)
end = time.time() end = time.time()
calculation_time = end-start calculation_time = end-start
print "\n\tCalculation time (2nd call)", calculation_time print("\n\tCalculation time (2nd call)", calculation_time)
self.assertTrue(1.0 > calculation_time, "1.0 <= %s" % calculation_time) self.assertTrue(1.0 > calculation_time, "1.0 <= %s" % calculation_time)
self.assertEqual(cached, result) self.assertEqual(cached, result)
self.commit() self.commit()
...@@ -342,7 +343,7 @@ return result ...@@ -342,7 +343,7 @@ return result
result=result) result=result)
end = time.time() end = time.time()
calculation_time = end-start calculation_time = end-start
print "\n\tCalculation time (3rd call)", calculation_time print("\n\tCalculation time (3rd call)", calculation_time)
self.assertTrue(1.0 > calculation_time, "1.0 <= %s" % calculation_time) self.assertTrue(1.0 > calculation_time, "1.0 <= %s" % calculation_time)
self.assertEqual(cached, result) self.assertEqual(cached, result)
self.commit() self.commit()
...@@ -351,9 +352,9 @@ return result ...@@ -351,9 +352,9 @@ return result
"""Check that persistent distributed Cache Plugin can handle keys """Check that persistent distributed Cache Plugin can handle keys
more than 250 bytes and values more than 1024 bytes. more than 250 bytes and values more than 1024 bytes.
""" """
print print()
print '=' * 40 print('=' * 40)
print 'TESTING: Long Keys and Large values' print('TESTING: Long Keys and Large values')
portal = self.portal portal = self.portal
# import the local and clear it # import the local and clear it
from Products.ERP5Type.CachePlugins.DistributedRamCache import\ from Products.ERP5Type.CachePlugins.DistributedRamCache import\
...@@ -410,7 +411,7 @@ return 'a' * 1024 * 1024 * 25 ...@@ -410,7 +411,7 @@ return 'a' * 1024 * 1024 * 25
long_parameter=long_parameter) long_parameter=long_parameter)
end = time.time() end = time.time()
calculation_time = end-start calculation_time = end-start
print "\n\tCalculation time (1st call)", calculation_time print("\n\tCalculation time (1st call)", calculation_time)
self.assertEqual(cached, result) self.assertEqual(cached, result)
self.commit() self.commit()
...@@ -423,7 +424,7 @@ return 'a' * 1024 * 1024 * 25 ...@@ -423,7 +424,7 @@ return 'a' * 1024 * 1024 * 25
long_parameter=long_parameter) long_parameter=long_parameter)
end = time.time() end = time.time()
calculation_time = end-start calculation_time = end-start
print "\n\tCalculation time (2nd call)", calculation_time print("\n\tCalculation time (2nd call)", calculation_time)
self.assertTrue(1.0 > calculation_time, "1.0 <= %s" % calculation_time) self.assertTrue(1.0 > calculation_time, "1.0 <= %s" % calculation_time)
self.assertEqual(cached, result) self.assertEqual(cached, result)
self.commit() self.commit()
...@@ -431,37 +432,37 @@ return 'a' * 1024 * 1024 * 25 ...@@ -431,37 +432,37 @@ return 'a' * 1024 * 1024 * 25
def test_06_CheckCacheExpiration(self): def test_06_CheckCacheExpiration(self):
"""Check that expiracy is well handle by Cache Plugins """Check that expiracy is well handle by Cache Plugins
""" """
print print()
print "="*40 print("="*40)
print "TESTING: Cache Expiration Time" print("TESTING: Cache Expiration Time")
py_script_obj = getattr(self.portal, self.python_script_id) py_script_obj = getattr(self.portal, self.python_script_id)
cache_factory_list = ('ram_cache_factory', 'distributed_ram_cache_factory', cache_factory_list = ('ram_cache_factory', 'distributed_ram_cache_factory',
'distributed_persistent_cache_factory') 'distributed_persistent_cache_factory')
for cache_factory in cache_factory_list: for cache_factory in cache_factory_list:
print '\n\t==> %s' % cache_factory print('\n\t==> %s' % cache_factory)
my_cache = CachingMethod(py_script_obj, my_cache = CachingMethod(py_script_obj,
'py_script_obj', 'py_script_obj',
cache_factory=cache_factory) cache_factory=cache_factory)
# First call, fill the cache # First call, fill the cache
calculation_time = self._callCache(my_cache, real_calculation=True) calculation_time = self._callCache(my_cache, real_calculation=True)
print "\n\tCalculation time (1st call)", calculation_time print("\n\tCalculation time (1st call)", calculation_time)
## 2nd call - should be cached now ## 2nd call - should be cached now
calculation_time = self._callCache(my_cache, real_calculation=False) calculation_time = self._callCache(my_cache, real_calculation=False)
print "\n\tCalculation time (2nd call)", calculation_time print("\n\tCalculation time (2nd call)", calculation_time)
# Wait expiration period then check that value is computed # Wait expiration period then check that value is computed
# .1 is an additional epsilon delay to work around time precision issues # .1 is an additional epsilon delay to work around time precision issues
time_left_to_wait = .1 + self.cache_duration time_left_to_wait = .1 + self.cache_duration
print "\n\tSleep %.2f seconds to wait expiration time" % time_left_to_wait print("\n\tSleep %.2f seconds to wait expiration time" % time_left_to_wait)
time.sleep(time_left_to_wait) time.sleep(time_left_to_wait)
# Call conversion for ram_cache_factory # Call conversion for ram_cache_factory
calculation_time = self._callCache(my_cache, real_calculation=True) calculation_time = self._callCache(my_cache, real_calculation=True)
print "\n\tCalculation time (3rd call)", calculation_time print("\n\tCalculation time (3rd call)", calculation_time)
def test_06_CheckCacheBag(self): def test_06_CheckCacheBag(self):
""" """
......
...@@ -289,7 +289,7 @@ class TestProxyField(ERP5TypeTestCase): ...@@ -289,7 +289,7 @@ class TestProxyField(ERP5TypeTestCase):
python_script_id = "ERP5Site_testAccessProxyFieldProperty" python_script_id = "ERP5Site_testAccessProxyFieldProperty"
python_script_parameter = "proxy_field" python_script_parameter = "proxy_field"
python_script_body = """ python_script_body = """
print proxy_field.getRecursiveTemplateField().meta_type print (proxy_field.getRecursiveTemplateField().meta_type)
return printed return printed
""" """
skin_folder.manage_addProduct['PythonScripts'].manage_addPythonScript( skin_folder.manage_addProduct['PythonScripts'].manage_addPythonScript(
......
...@@ -6,5 +6,5 @@ portal.event_module.recurseCallMethod( ...@@ -6,5 +6,5 @@ portal.event_module.recurseCallMethod(
group_method_cost=1), group_method_cost=1),
min_depth=1, min_depth=1,
max_depth=1) max_depth=1)
print "Migration started with process id: %s" %active_process.getPath() print("Migration started with process id: %s" %active_process.getPath())
return printed return printed
...@@ -6,6 +6,6 @@ object_list = list(context.portal_catalog(parent_uid=uids, portal_type = "Email ...@@ -6,6 +6,6 @@ object_list = list(context.portal_catalog(parent_uid=uids, portal_type = "Email
for o in object_list: for o in object_list:
o_value = o.getObject() o_value = o.getObject()
if o is not None: if o is not None:
print o_value.getUrlString() print(o_value.getUrlString())
return printed return printed
...@@ -29,6 +29,7 @@ ...@@ -29,6 +29,7 @@
# #
############################################################################## ##############################################################################
from __future__ import print_function
import unittest import unittest
from AccessControl.SecurityManagement import newSecurityManager from AccessControl.SecurityManagement import newSecurityManager
...@@ -131,12 +132,12 @@ class TestEditorField(ERP5TypeTestCase, ZopeTestCase.Functional): ...@@ -131,12 +132,12 @@ class TestEditorField(ERP5TypeTestCase, ZopeTestCase.Functional):
match_string1 = 'data-gadget-editable="field_%s"' % field_id match_string1 = 'data-gadget-editable="field_%s"' % field_id
match_string2 = 'data-gadget-value="%s"' % html_quote(text_content) match_string2 = 'data-gadget-value="%s"' % html_quote(text_content)
if html_text.find(match_string1) == -1: if html_text.find(match_string1) == -1:
print html_text print(html_text)
print match_string1 print(match_string1)
return False return False
if html_text.find(match_string2) == -1: if html_text.find(match_string2) == -1:
print html_text print(html_text)
print match_string2 print(match_string2)
return False return False
return True return True
...@@ -156,13 +157,13 @@ class TestEditorField(ERP5TypeTestCase, ZopeTestCase.Functional): ...@@ -156,13 +157,13 @@ class TestEditorField(ERP5TypeTestCase, ZopeTestCase.Functional):
match_string1 = 'data-gadget-editable="field_%s"' % field_id match_string1 = 'data-gadget-editable="field_%s"' % field_id
match_string2 = 'data-gadget-value="%s"' % html_quote(text_content) match_string2 = 'data-gadget-value="%s"' % html_quote(text_content)
if html_text.find(match_string1) == -1: if html_text.find(match_string1) == -1:
print html_text print(html_text)
print match_string1 print(match_string1)
import pdb; pdb.set_trace() import pdb; pdb.set_trace()
return False return False
if html_text.find(match_string2) == -1: if html_text.find(match_string2) == -1:
print html_text print(html_text)
print match_string2 print(match_string2)
import pdb; pdb.set_trace() import pdb; pdb.set_trace()
return False return False
return True return True
...@@ -182,12 +183,12 @@ class TestEditorField(ERP5TypeTestCase, ZopeTestCase.Functional): ...@@ -182,12 +183,12 @@ class TestEditorField(ERP5TypeTestCase, ZopeTestCase.Functional):
match_string1 = "data-gadget-editable=" match_string1 = "data-gadget-editable="
match_string2 = 'data-gadget-value="%s"' % html_quote(text_content) match_string2 = 'data-gadget-value="%s"' % html_quote(text_content)
if html_text.find(match_string1) != -1: if html_text.find(match_string1) != -1:
print html_text print(html_text)
print match_string1 print(match_string1)
return False return False
if html_text.find(match_string2) == -1: if html_text.find(match_string2) == -1:
print html_text print(html_text)
print match_string2 print(match_string2)
return False return False
return True return True
......
...@@ -872,12 +872,10 @@ class TestDocument(TestDocumentMixin): ...@@ -872,12 +872,10 @@ class TestDocument(TestDocumentMixin):
self.tic() self.tic()
test_document_set = {document_1, document_2, document_3, person, web_page, organisation} test_document_set = {document_1, document_2, document_3, person, web_page, organisation}
def getAdvancedSearchTextResultList(searchable_text, portal_type=None,src__=0): def getAdvancedSearchTextResultList(searchable_text, portal_type=None):
kw = {'full_text': searchable_text} kw = {'full_text': searchable_text}
if portal_type is not None: if portal_type is not None:
kw['portal_type'] = portal_type kw['portal_type'] = portal_type
if src__==1:
print portal.portal_catalog(src__=src__,**kw)
result_list = [x.getObject() for x in portal.portal_catalog(**kw)] result_list = [x.getObject() for x in portal.portal_catalog(**kw)]
return [x for x in result_list if x in test_document_set] return [x for x in result_list if x in test_document_set]
......
...@@ -8,5 +8,5 @@ context.ERP5Site_checkDataWithScript("Base_callPreConvert", ...@@ -8,5 +8,5 @@ context.ERP5Site_checkDataWithScript("Base_callPreConvert",
tag="pre_convert", tag="pre_convert",
packet=2, packet=2,
id_list=["document_module", "image_module", "web_page_module"]) id_list=["document_module", "image_module", "web_page_module"])
print "OK" print("OK")
return printed return printed
...@@ -42,5 +42,5 @@ tiolive_logo_image = context.portal_catalog.getResultValue( ...@@ -42,5 +42,5 @@ tiolive_logo_image = context.portal_catalog.getResultValue(
if tiolive_logo_image is not None and tiolive_logo_image.getValidationState() == 'published': if tiolive_logo_image is not None and tiolive_logo_image.getValidationState() == 'published':
tiolive_logo_image.reject() tiolive_logo_image.reject()
print "Done" print("Done")
return printed return printed
...@@ -2,5 +2,9 @@ ...@@ -2,5 +2,9 @@
#portal_preferences = context.portal_preferences #portal_preferences = context.portal_preferences
#portal_preferences.manage_delObjects(['dms_system_preference_ui_tests', 'dms_preference_ui_tests']) #portal_preferences.manage_delObjects(['dms_system_preference_ui_tests', 'dms_preference_ui_tests'])
#context.portal_caches.clearAllCache() #context.portal_caches.clearAllCache()
print "Done" # Delete System Preference
#portal_preferences = context.portal_preferences
#portal_preferences.manage_delObjects(['dms_system_preference_ui_tests', 'dms_preference_ui_tests'])
#context.portal_caches.clearAllCache()
print("Done")
return printed return printed
...@@ -2,10 +2,10 @@ result = context.GlossaryModule_getTermDictListFromPortalType(portal_type_list) ...@@ -2,10 +2,10 @@ result = context.GlossaryModule_getTermDictListFromPortalType(portal_type_list)
if export_tsv: if export_tsv:
for i in result: for i in result:
print '\t'.join(['"%s"' % x for x in (i['reference'], i['language'], print('\t'.join(['"%s"' % x for x in (i['reference'], i['language'],
i['business_field'], i['business_field'],
i['title'], i['description'], i['title'], i['description'],
i['field_path'])]) i['field_path'])]))
return printed return printed
else: else:
portal_catalog = context.portal_catalog portal_catalog = context.portal_catalog
......
...@@ -2,10 +2,10 @@ result = context.GlossaryModule_getTermDictListFromPropertySheet(property_sheet_ ...@@ -2,10 +2,10 @@ result = context.GlossaryModule_getTermDictListFromPropertySheet(property_sheet_
if export_tsv: if export_tsv:
for i in result: for i in result:
print '\t'.join(['"%s"' % x for x in (i['reference'], i['language'], print('\t'.join(['"%s"' % x for x in (i['reference'], i['language'],
i['business_field'], i['business_field'],
i['title'], i['description'], i['title'], i['description'],
i['field_path'])]) i['field_path'])]))
return printed return printed
else: else:
portal_catalog = context.portal_catalog portal_catalog = context.portal_catalog
......
...@@ -3,10 +3,10 @@ result = context.GlossaryModule_getTermDictListFromWorkflow(template_list) ...@@ -3,10 +3,10 @@ result = context.GlossaryModule_getTermDictListFromWorkflow(template_list)
if export_tsv: if export_tsv:
for i in result: for i in result:
print '\t'.join(['"%s"' % x for x in (i['reference'], i['language'], print('\t'.join(['"%s"' % x for x in (i['reference'], i['language'],
i['business_field'], i['business_field'],
i['title'], i['description'], i['title'], i['description'],
i['workflow_id'])]) i['workflow_id'])]))
return printed return printed
else: else:
portal_catalog = context.portal_catalog portal_catalog = context.portal_catalog
......
...@@ -24,7 +24,7 @@ def formatString(string): ...@@ -24,7 +24,7 @@ def formatString(string):
# po header # po header
now = DateTime().toZone('UTC').strftime("%Y-%m-%d %H:%M+0000") now = DateTime().toZone('UTC').strftime("%Y-%m-%d %H:%M+0000")
print MESSAGE_TEMPLATE % (dict(english='""', print(MESSAGE_TEMPLATE % (dict(english='""',
translation= translation=
r'''"Project-Id-Version: ERP5 Localized Interface\n" r'''"Project-Id-Version: ERP5 Localized Interface\n"
"POT-Creation-Date: %s\n" "POT-Creation-Date: %s\n"
...@@ -34,7 +34,7 @@ r'''"Project-Id-Version: ERP5 Localized Interface\n" ...@@ -34,7 +34,7 @@ r'''"Project-Id-Version: ERP5 Localized Interface\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n" "Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n" "Content-Transfer-Encoding: 8bit\n"
''' % (now, now, language))) ''' % (now, now, language))))
catalog = context.portal_catalog catalog = context.portal_catalog
for i in catalog(portal_type='Glossary Term', for i in catalog(portal_type='Glossary Term',
...@@ -63,18 +63,18 @@ for i in catalog(portal_type='Glossary Term', ...@@ -63,18 +63,18 @@ for i in catalog(portal_type='Glossary Term',
if not english_title: if not english_title:
raise ValueError('Title of corresponding English term(%s) to "%s" is empty.' % (english_relative_url, translated_title)) raise ValueError('Title of corresponding English term(%s) to "%s" is empty.' % (english_relative_url, translated_title))
if translated_title!=english_title: if translated_title!=english_title:
print formatMessage(english=formatString(english_title), print(formatMessage(english=formatString(english_title),
translation=formatString(translated_title), translation=formatString(translated_title),
term=term) term=term))
if translated_description: if translated_description:
if not english_description: if not english_description:
raise ValueError('Description of corresponding English term(%s) to "%s" is empty.' % (english_relative_url, translated_description)) raise ValueError('Description of corresponding English term(%s) to "%s" is empty.' % (english_relative_url, translated_description))
if translated_description!=english_description: if translated_description!=english_description:
print formatMessage(english=formatString(english_description), print(formatMessage(english=formatString(english_description),
translation=formatString(translated_description), translation=formatString(translated_description),
term=term) term=term))
RESPONSE = context.REQUEST.RESPONSE RESPONSE = context.REQUEST.RESPONSE
RESPONSE.setHeader('Content-disposition', 'attachment;filename=translation.po') RESPONSE.setHeader('Content-disposition', 'attachment;filename=translation.po')
......
...@@ -5,6 +5,6 @@ for i in context.getPortalObject().glossary_module.objectValues(): ...@@ -5,6 +5,6 @@ for i in context.getPortalObject().glossary_module.objectValues():
lang = lang_list[0] lang = lang_list[0]
i.setLanguage(lang) i.setLanguage(lang)
i.setCategoryList([x for x in i.categories if not x.startswith('language/')]) i.setCategoryList([x for x in i.categories if not x.startswith('language/')])
print i.getPath(), lang print(i.getPath(), lang)
print 'Migration finished.' print('Migration finished.')
return printed return printed
...@@ -22,28 +22,28 @@ for diff_object in sortDiffObjectList(diff_object_list): ...@@ -22,28 +22,28 @@ for diff_object in sortDiffObjectList(diff_object_list):
if getattr(diff_object, "error", None) is not None: if getattr(diff_object, "error", None) is not None:
print("<p>") print("<p>")
print("Error") print("Error")
print("(%s) -" % html_quote(diff_object.object_class)) print(("(%s) -" % html_quote(diff_object.object_class)))
if diff_object.object_class in link_configuration: if diff_object.object_class in link_configuration:
print(link_configuration[diff_object.object_class] % {"object_id": html_quote(diff_object.object_id)}) print((link_configuration[diff_object.object_class] % {"object_id": html_quote(diff_object.object_id)}))
else: else:
print(html_quote(diff_object.object_id)) print((html_quote(diff_object.object_id)))
print("</p>") print("</p>")
if detailed: if detailed:
print("<p>") print("<p>")
print(html_quote(diff_object.error)) print((html_quote(diff_object.error)))
print("</p>") print("</p>")
else: else:
print("<p>") print("<p>")
print(html_quote(diff_object.object_state)) print((html_quote(diff_object.object_state)))
print("(%s) -" % html_quote(diff_object.object_class)) print(("(%s) -" % html_quote(diff_object.object_class)))
if diff_object.object_class in link_configuration: if diff_object.object_class in link_configuration:
print(link_configuration[diff_object.object_class] % {"object_id": html_quote(diff_object.object_id)}) print((link_configuration[diff_object.object_class] % {"object_id": html_quote(diff_object.object_id)}))
else: else:
print(html_quote(diff_object.object_id)) print((html_quote(diff_object.object_id)))
print("</p>") print("</p>")
if detailed and getattr(diff_object, "data", None) is not None: if detailed and getattr(diff_object, "data", None) is not None:
print("<div>") print("<div>")
print(DiffFile(diff_object.data).toHTML()) print((DiffFile(diff_object.data).toHTML()))
print("</div>") print("</div>")
print("</div>") print("</div>")
return printed return printed
...@@ -2,14 +2,14 @@ def sortDiffObjectList(diff_object_list): ...@@ -2,14 +2,14 @@ def sortDiffObjectList(diff_object_list):
return sorted(diff_object_list, key=lambda x: (x.object_state, x.object_class, x.object_id)) return sorted(diff_object_list, key=lambda x: (x.object_state, x.object_class, x.object_id))
for diff_object in sortDiffObjectList(diff_object_list): for diff_object in sortDiffObjectList(diff_object_list):
print("%s (%s) - %s" % (diff_object.object_state, diff_object.object_class, diff_object.object_id)) print(("%s (%s) - %s" % (diff_object.object_state, diff_object.object_class, diff_object.object_id)))
if getattr(diff_object, "error", None) is not None: if getattr(diff_object, "error", None) is not None:
if detailed: if detailed:
print(" %s" % diff_object.error) print((" %s" % diff_object.error))
print("") print("")
else: else:
if detailed and getattr(diff_object, "data", None) is not None: if detailed and getattr(diff_object, "data", None) is not None:
print("%s" % diff_object.data.lstrip()) print(("%s" % diff_object.data.lstrip()))
print("") print("")
return printed return printed
# License: GPL # License: GPL
# Author: Lukasz Nowak <lukasz.nowak@ventis.com.pl> # Author: Lukasz Nowak <lukasz.nowak@ventis.com.pl>
# Copyright 2007 Ventis s. c. # Copyright 2007 Ventis s. c.
simulations_found = context.Base_getSimulationTree(start_path=start_path) simulations_found = context.Base_getSimulationTree(start_path=start_path)
if len(simulations_found) == 0: if len(simulations_found) == 0:
print 'No simulations related' print('No simulations related')
else: else:
for simulation_root in simulations_found.iterkeys(): for simulation_root in simulations_found:
print simulation_root print(simulation_root)
for simulation in simulations_found[simulation_root]: for simulation in simulations_found[simulation_root]:
print '\t',simulation.getPath(),simulation.getPortalType(), print('\t',simulation.getPath(),simulation.getPortalType(), end=' ')
if simulation.getPortalType() == 'Simulation Movement': if simulation.getPortalType() == 'Simulation Movement':
print simulation.getCausalityState(), print(simulation.getCausalityState(), end=' ')
else: else:
print 'nostate', print('nostate', end=' ')
print simulation.getCategoriesList() print(simulation.getCategoriesList())
return printed return printed
...@@ -172,10 +172,10 @@ def formatString(string): ...@@ -172,10 +172,10 @@ def formatString(string):
else: else:
return '\n'.join(['""']+[formatString(i) for i in line_list]) return '\n'.join(['""']+[formatString(i) for i in line_list])
print '''msgid "" print('''msgid ""
msgstr "Content-Type: text/plain; charset=UTF-8" msgstr "Content-Type: text/plain; charset=UTF-8"
''' ''')
MESSAGE_TEMPLATE = '''\ MESSAGE_TEMPLATE = '''\
%s %s
...@@ -188,7 +188,7 @@ for message in message_list: ...@@ -188,7 +188,7 @@ for message in message_list:
comment_list = message_dict[message] comment_list = message_dict[message]
comment_list.sort() comment_list.sort()
comment = '\n'.join([('#: %s' % i) for i in comment_list]) comment = '\n'.join([('#: %s' % i) for i in comment_list])
print MESSAGE_TEMPLATE % (comment, formatString(message)) print(MESSAGE_TEMPLATE % (comment, formatString(message)))
RESPONSE = context.REQUEST.RESPONSE RESPONSE = context.REQUEST.RESPONSE
RESPONSE.setHeader('Content-disposition', 'attachment;filename=translation.pot') RESPONSE.setHeader('Content-disposition', 'attachment;filename=translation.pot')
......
...@@ -48,7 +48,7 @@ recurse(o, callback, seldict) ...@@ -48,7 +48,7 @@ recurse(o, callback, seldict)
for selection_name in seldict.keys(): for selection_name in seldict.keys():
if len(seldict[selection_name]) != 1 or all_selections: if len(seldict[selection_name]) != 1 or all_selections:
print "'%s' [%s]"%(selection_name,len(seldict[selection_name])) print("'%s' [%s]"%(selection_name,len(seldict[selection_name])))
for form_name in seldict[selection_name]: for form_name in seldict[selection_name]:
print "\t%s"%(form_name,) print("\t%s"%(form_name,))
return printed return printed
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
from erp5.component.module.Log import log from erp5.component.module.Log import log
log("Obsolete script, please use BaseType_copyRoleList instead") log("Obsolete script, please use BaseType_copyRoleList instead")
print 'cloning role information from' print('cloning role information from')
print from_type print(from_type)
if to_type_list == (): if to_type_list == ():
to_type_list = (to_type,) to_type_list = (to_type,)
print "to", to_type_list print("to", to_type_list)
context.portal_types[from_type].BaseType_copyRoleList(remove_existing_roles=True, context.portal_types[from_type].BaseType_copyRoleList(remove_existing_roles=True,
portal_type_list=to_type_list) portal_type_list=to_type_list)
......
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
""" """
portal_skin = context.REQUEST.get('portal_skin', 'View') portal_skin = context.REQUEST.get('portal_skin', 'View')
print "<html>" print("<html>")
for field_path, field in context.ZopeFind( for field_path, field in context.ZopeFind(
context.portal_skins, obj_metatypes=['ProxyField'], search_sub=1): context.portal_skins, obj_metatypes=['ProxyField'], search_sub=1):
if field.getTemplateField() is None: if field.getTemplateField() is None:
print '<a href="%s/%s/manage_main?portal_skin=%s">%s</a><br />' % (context.absolute_url(), field_path, portal_skin, field_path) print('<a href="%s/%s/manage_main?portal_skin=%s">%s</a><br />' % (context.absolute_url(), field_path, portal_skin, field_path))
print "</html>" print("</html>")
return printed return printed
...@@ -7,9 +7,9 @@ for form_path, form in context.ZopeFind( ...@@ -7,9 +7,9 @@ for form_path, form in context.ZopeFind(
try: try:
groups = form.get_groups() groups = form.get_groups()
except AttributeError as e: except AttributeError as e:
print "%s is broken: %s" % (form_path, e) print("%s is broken: %s" % (form_path, e))
if 'not_assigned' in groups: if 'not_assigned' in groups:
print 'Not assigned fields in %s: %s' % (form_path, print('Not assigned fields in %s: %s' % (form_path,
[f.getId() for f in form.get_fields_in_group('not_assigned')]) [f.getId() for f in form.get_fields_in_group('not_assigned')]))
return printed return printed
...@@ -14,14 +14,14 @@ for field_path, field in context.ZopeFind( ...@@ -14,14 +14,14 @@ for field_path, field in context.ZopeFind(
continue continue
if not (field.get_value('proxy_listbox_ids') or field.get_value('columns')): if not (field.get_value('proxy_listbox_ids') or field.get_value('columns')):
print field_path print(field_path)
continue continue
for path, name in field.get_value('proxy_listbox_ids'): for path, name in field.get_value('proxy_listbox_ids'):
if context.restrictedTraverse(path, None) is None: if context.restrictedTraverse(path, None) is None:
print ' PROBLEM: field %s uses an invalid form for %s: %s' % (field_path, name, path) print(' PROBLEM: field %s uses an invalid form for %s: %s' % (field_path, name, path))
else: else:
proxy_listbox = context.restrictedTraverse(path) proxy_listbox = context.restrictedTraverse(path)
if proxy_listbox.meta_type not in ('ProxyField', 'ListBox'): if proxy_listbox.meta_type not in ('ProxyField', 'ListBox'):
print ' PROBLEM: field %s uses an invalid proxy with %s meta_type' % (field_path, proxy_listbox.meta_type) print(' PROBLEM: field %s uses an invalid proxy with %s meta_type' % (field_path, proxy_listbox.meta_type))
return printed return printed
...@@ -6,7 +6,7 @@ container.REQUEST.RESPONSE.setHeader('content-type', 'text/html') ...@@ -6,7 +6,7 @@ container.REQUEST.RESPONSE.setHeader('content-type', 'text/html')
# make sure context is the skins tool # make sure context is the skins tool
stool = context.portal_skins stool = context.portal_skins
print '<html><body>' print('<html><body>')
skins_by_name = {} skins_by_name = {}
for skin_key, skin_path_list in stool.getSkinPaths(): for skin_key, skin_path_list in stool.getSkinPaths():
...@@ -24,9 +24,9 @@ for skin_key, skin_path_list in stool.getSkinPaths(): ...@@ -24,9 +24,9 @@ for skin_key, skin_path_list in stool.getSkinPaths():
for skin_name, location_list in skins_by_name.items(): for skin_name, location_list in skins_by_name.items():
if len(location_list) > 1: if len(location_list) > 1:
print skin_name, '<br/>' print(skin_name, '<br/>')
for location in location_list: for location in location_list:
print "&nbsp;" * 3, '<a href="%s/%s/%s/manage_main">%s</a><br/>' % (stool.absolute_url(), location, skin_name, location) print("&nbsp;" * 3, '<a href="%s/%s/%s/manage_main">%s</a><br/>' % (stool.absolute_url(), location, skin_name, location))
print '</body></html>' print('</body></html>')
return printed return printed
...@@ -5,7 +5,7 @@ if template_tool.getDiffFilterScriptList(): ...@@ -5,7 +5,7 @@ if template_tool.getDiffFilterScriptList():
else: else:
from erp5.component.module.DiffUtils import DiffFile from erp5.component.module.DiffUtils import DiffFile
print '<div style="color: black">' print('<div style="color: black">')
# XXX: ERP5VCS_doCreateJavaScriptStatus should send lists # XXX: ERP5VCS_doCreateJavaScriptStatus should send lists
if isinstance(added, basestring): if isinstance(added, basestring):
...@@ -19,20 +19,20 @@ for f in modified: ...@@ -19,20 +19,20 @@ for f in modified:
diff = DiffFile(vcs_tool.diff(f)) diff = DiffFile(vcs_tool.diff(f))
if not diff: if not diff:
continue continue
print '<input name="modified" value="%s" type="checkbox" checked="checked" />'% f print('<input name="modified" value="%s" type="checkbox" checked="checked" />'% f)
print vcs_tool.getHeader(f) print(vcs_tool.getHeader(f))
print diff.toHTML() print(diff.toHTML())
print "<hr/><br/>" print("<hr/><br/>")
for f in added: for f in added:
print '<input name="added" value="%s" type="checkbox" checked="checked" />'% f print('<input name="added" value="%s" type="checkbox" checked="checked" />'% f)
print vcs_tool.getHeader(f) print(vcs_tool.getHeader(f))
print "<br/><span style='color: green;'>File Added</span><br/><br/><hr/><br/>" print("<br/><span style='color: green;'>File Added</span><br/><br/><hr/><br/>")
for f in removed: for f in removed:
print '<input name="removed" value="%s" type="checkbox" checked="checked" />'% f print('<input name="removed" value="%s" type="checkbox" checked="checked" />'% f)
print vcs_tool.getHeader(f) print(vcs_tool.getHeader(f))
print "<br/><span style='color: red;'>File Removed</span><br/><br/><hr/><br/>" print("<br/><span style='color: red;'>File Removed</span><br/><br/><hr/><br/>")
print '</div>' print('</div>')
return printed return printed
...@@ -9,10 +9,10 @@ from string import capitalize ...@@ -9,10 +9,10 @@ from string import capitalize
def addAction(portal_type, portal_type_type, country, amortisation_method): def addAction(portal_type, portal_type_type, country, amortisation_method):
print 'Adding UI tab "Amortisation Details" for method %s on portal_type %s... ' % (amortisation_method,portal_type), print('Adding UI tab "Amortisation Details" for method %s on portal_type %s... ' % (amortisation_method,portal_type), end=' ')
id = "%s_%s_amortisation_details_view" % (country, amortisation_method) id = "%s_%s_amortisation_details_view" % (country, amortisation_method)
if id in [x.id for x in portal_type.listActions()]: if id in [x.id for x in portal_type.listActions()]:
print "Already exists" print("Already exists")
else: else:
if portal_type_type == "Immobilisation": if portal_type_type == "Immobilisation":
action = "%s_Immobilisation_viewDetails" % amortisation_method action = "%s_Immobilisation_viewDetails" % amortisation_method
...@@ -27,7 +27,7 @@ def addAction(portal_type, portal_type_type, country, amortisation_method): ...@@ -27,7 +27,7 @@ def addAction(portal_type, portal_type_type, country, amortisation_method):
permission = ('View',), permission = ('View',),
category = "object_view", category = "object_view",
visible = 1) visible = 1)
print "OK" print("OK")
return printed return printed
...@@ -44,10 +44,10 @@ amortisation_method = "".join(tokens[1:]) ...@@ -44,10 +44,10 @@ amortisation_method = "".join(tokens[1:])
for portal_type in context.portal_types.objectValues(): for portal_type in context.portal_types.objectValues():
# Check if the portal_type is Immobilisation # Check if the portal_type is Immobilisation
if portal_type.id == "Immobilisation": if portal_type.id == "Immobilisation":
print addAction(portal_type, "Immobilisation", country, amortisation_method), print(addAction(portal_type, "Immobilisation", country, amortisation_method), end=' ')
else: else:
# Check if the portal_type is amortisable # Check if the portal_type is amortisable
if "immobilise" in [x.id for x in portal_type.listActions()]: if "immobilise" in [x.id for x in portal_type.listActions()]:
print addAction(portal_type, "Item", country, amortisation_method), print(addAction(portal_type, "Item", country, amortisation_method), end=' ')
return printed return printed
...@@ -10,18 +10,18 @@ actions_to_add = [ ...@@ -10,18 +10,18 @@ actions_to_add = [
] ]
print 'Adding Immobilisation Item Actions to Portal Type %s :' % context.getId() print('Adding Immobilisation Item Actions to Portal Type %s :' % context.getId())
action_list = context.listActions() action_list = context.listActions()
for action_to_add in actions_to_add: for action_to_add in actions_to_add:
print "- Adding Action '%s (%s)'... " % (action_to_add['id'],action_to_add['name']), print("- Adding Action '%s (%s)'... " % (action_to_add['id'],action_to_add['name']), end=' ')
found = 0 found = 0
for action in action_list: for action in action_list:
if getattr(action, 'id', None) == action_to_add['id']: if getattr(action, 'id', None) == action_to_add['id']:
print 'already exists' print('already exists')
found = 1 found = 1
if not found: if not found:
context.addAction(**action_to_add) context.addAction(**action_to_add)
print "OK" print("OK")
print print()
return printed return printed
...@@ -8,7 +8,7 @@ amortisation_method_view = 'amortisation_method_view' ...@@ -8,7 +8,7 @@ amortisation_method_view = 'amortisation_method_view'
action_list = context.listActions() action_list = context.listActions()
print "Making portal type '%s' an Immobilisation Movement :" % context.getId() print("Making portal type '%s' an Immobilisation Movement :" % context.getId())
# Add a view for each amortisation method # Add a view for each amortisation method
amortisation_method_list = context.Immobilisation_getAmortisationMethodList() amortisation_method_list = context.Immobilisation_getAmortisationMethodList()
for method in amortisation_method_list: for method in amortisation_method_list:
...@@ -17,13 +17,13 @@ for method in amortisation_method_list: ...@@ -17,13 +17,13 @@ for method in amortisation_method_list:
title = method[1].title or id title = method[1].title or id
action_id = view_id_basis % (region, id) action_id = view_id_basis % (region, id)
print "- Adding View for method '%s'... " % title, print("- Adding View for method '%s'... " % title, end=' ')
# Check if the action already exists # Check if the action already exists
exists = 0 exists = 0
for action in action_list: for action in action_list:
if getattr(action, "id", None) == action_id: if getattr(action, "id", None) == action_id:
print "already exists" print("already exists")
exists = 1 exists = 1
if not exists: if not exists:
...@@ -37,8 +37,8 @@ for method in amortisation_method_list: ...@@ -37,8 +37,8 @@ for method in amortisation_method_list:
permission = view_permissions_basis, permission = view_permissions_basis,
category = "object_view", category = "object_view",
visible=1) visible=1)
print "OK" print("OK")
print print()
return printed return printed
...@@ -18,18 +18,18 @@ actions_to_add = [ ...@@ -18,18 +18,18 @@ actions_to_add = [
] ]
print 'Adding Immobilisation Item Actions to Portal Type %s :' % context.getId() print('Adding Immobilisation Item Actions to Portal Type %s :' % context.getId())
action_list = context.listActions() action_list = context.listActions()
for action_to_add in actions_to_add: for action_to_add in actions_to_add:
print "- Adding Action '%s (%s)'... " % (action_to_add['id'],action_to_add['name']), print("- Adding Action '%s (%s)'... " % (action_to_add['id'],action_to_add['name']), end=' ')
found = 0 found = 0
for action in action_list: for action in action_list:
if getattr(action, 'id', None) == action_to_add['id']: if getattr(action, 'id', None) == action_to_add['id']:
print 'already exists' print('already exists')
found = 1 found = 1
if not found: if not found:
context.addAction(**action_to_add) context.addAction(**action_to_add)
print "OK" print("OK")
print print()
return printed return printed
user_preferences = context.KnowledgeBox_getDefaultPreferencesDict() user_preferences = context.KnowledgeBox_getDefaultPreferencesDict()
print user_preferences print(user_preferences)
return printed return printed
...@@ -17,5 +17,5 @@ if remove_existing_pads: ...@@ -17,5 +17,5 @@ if remove_existing_pads:
user_knowledge_pad_list = context.ERP5Site_getKnowledgePadListForUser(mode = mode) user_knowledge_pad_list = context.ERP5Site_getKnowledgePadListForUser(mode = mode)
context.knowledge_pad_module.manage_delObjects([x.getId() for x in user_knowledge_pad_list]) context.knowledge_pad_module.manage_delObjects([x.getId() for x in user_knowledge_pad_list])
print "Done" print("Done")
return printed return printed
...@@ -37,16 +37,16 @@ document_list = portal.portal_catalog( ...@@ -37,16 +37,16 @@ document_list = portal.portal_catalog(
path_list = [software_product_rurl] path_list = [software_product_rurl]
print " Processing File List \r===============================\r" print(" Processing File List \r===============================\r")
for document_brain in document_list: for document_brain in document_list:
document = document_brain.getObject() document = document_brain.getObject()
if document.getFollowUp(): if document.getFollowUp():
continue continue
print document.getId() print(document.getId())
new_document = document.Base_createCloneDocument(batch_mode=True) new_document = document.Base_createCloneDocument(batch_mode=True)
new_id = base_id + new_document.getReference().replace('.', '_') new_id = base_id + new_document.getReference().replace('.', '_')
if new_id in new_document.getParentValue(): if new_id in new_document.getParentValue():
print " deleting %s" % new_id print(" deleting %s" % new_id)
new_document.getParentValue().manage_delObjects([new_id]) new_document.getParentValue().manage_delObjects([new_id])
new_document.setId(new_id) new_document.setId(new_id)
path_list.append(new_document.getRelativeUrl()) path_list.append(new_document.getRelativeUrl())
...@@ -54,8 +54,8 @@ for document_brain in document_list: ...@@ -54,8 +54,8 @@ for document_brain in document_list:
# new_document.setVersion(base_id + "dev") # new_document.setVersion(base_id + "dev")
new_document.setFollowUp(software_product_rurl) new_document.setFollowUp(software_product_rurl)
print "\r\r Here is your path list\r===============================\r\r" print("\r\r Here is your path list\r===============================\r\r")
print '\r'.join(path_list) print('\r'.join(path_list))
print "\r\r===============================\r\r" print("\r\r===============================\r\r")
print " Done" print(" Done")
return printed return printed
container.REQUEST.RESPONSE.setHeader('Content-Type', 'text/html') container.REQUEST.RESPONSE.setHeader('Content-Type', 'text/html')
print "<html><body><h1 class='test-script-title'>Title is : " + parameter + "</h1></body></html>" print("<html><body><h1 class='test-script-title'>Title is : " + parameter + "</h1></body></html>")
return printed return printed
...@@ -8,8 +8,8 @@ line_dict_list = context.PaySheetTransaction_getLineListAsDict() ...@@ -8,8 +8,8 @@ line_dict_list = context.PaySheetTransaction_getLineListAsDict()
title_list = ['Designation\t\t', 'Base', 'Employer Rate', 'Employer Share', title_list = ['Designation\t\t', 'Base', 'Employer Rate', 'Employer Share',
'Employee Rate', 'Employee Share'] 'Employee Rate', 'Employee Share']
print '\t\t'.join(title_list) print('\t\t'.join(title_list))
print '' print('')
def rightPad(string, length): def rightPad(string, length):
string=str(string) string=str(string)
...@@ -36,6 +36,6 @@ for line in line_dict_list: ...@@ -36,6 +36,6 @@ for line in line_dict_list:
string_to_display.append(rightPad(' ', 24)) string_to_display.append(rightPad(' ', 24))
string_to_display.append(rightPad(' ', 24)) string_to_display.append(rightPad(' ', 24))
print ''.join(string_to_display) print(''.join(string_to_display))
return printed return printed
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
# #
############################################################################## ##############################################################################
from __future__ import print_function
from test import pystone from test import pystone
from time import time from time import time
pystone.clock = time pystone.clock = time
...@@ -72,10 +73,10 @@ class TestWorkflowPerformance(TestPerformanceMixin): ...@@ -72,10 +73,10 @@ class TestWorkflowPerformance(TestPerformanceMixin):
end = time() end = time()
print "\n%s pystones/second" % pystone.pystones()[1] print("\n%s pystones/second" % pystone.pystones()[1])
message = "\n%s took %.4gs (%s foo(s))" % (self._testMethodName, message = "\n%s took %.4gs (%s foo(s))" % (self._testMethodName,
end - start, foo_count) end - start, foo_count)
print message print(message)
ZopeTestCase._print(message) ZopeTestCase._print(message)
# some checking to make sure we tested something relevant # some checking to make sure we tested something relevant
......
...@@ -24,7 +24,7 @@ def foldContent(s): ...@@ -24,7 +24,7 @@ def foldContent(s):
return s return s
def printTask(task) : def printTask(task) :
print """BEGIN:VTODO print("""BEGIN:VTODO
DCREATED:%(creation_date)s DCREATED:%(creation_date)s
UID:%(uid)s UID:%(uid)s
SEQUENCE:1 SEQUENCE:1
...@@ -38,31 +38,31 @@ PRIORITY:%(priority)s""" % ( { ...@@ -38,31 +38,31 @@ PRIORITY:%(priority)s""" % ( {
'modification_date': formatDate(task.getModificationDate()), 'modification_date': formatDate(task.getModificationDate()),
'status': task.getSimulationState() == 'delivered' and 'COMPLETED' or 'NEEDS_ACTION', 'status': task.getSimulationState() == 'delivered' and 'COMPLETED' or 'NEEDS_ACTION',
'priority': task.getProperty('int_index', 3), 'priority': task.getProperty('int_index', 3),
} ) } ))
if task.hasComment(): if task.hasComment():
print "DESCRIPTION:" + foldContent(task.getComment()) print("DESCRIPTION:" + foldContent(task.getComment()))
if task.hasStartDate(): if task.hasStartDate():
print "DTSTART;VALUE=DATE:" + formatDate(task.getStartDate()) print("DTSTART;VALUE=DATE:" + formatDate(task.getStartDate()))
if task.hasStopDate(): if task.hasStopDate():
print "DUE;VALUE=DATE:" + formatDate(task.getStopDate()) print("DUE;VALUE=DATE:" + formatDate(task.getStopDate()))
organizer = task.getDestinationValue(portal_type='Person') organizer = task.getDestinationValue(portal_type='Person')
if organizer: if organizer:
print "ORGANIZER;CN=%s:MAILTO:%s" % (organizer.getTitle(), organizer.getDefaultEmailText()) print("ORGANIZER;CN=%s:MAILTO:%s" % (organizer.getTitle(), organizer.getDefaultEmailText()))
print "X-ORGANIZER:MAILTO:%s" % (organizer.getDefaultEmailText()) print("X-ORGANIZER:MAILTO:%s" % (organizer.getDefaultEmailText()))
for attendee in task.getSourceValueList( portal_type = 'Person') : for attendee in task.getSourceValueList( portal_type = 'Person') :
print "ATTENDEE;CN=%s:MAILTO:%s" % (attendee.getTitle(), attendee.getDefaultEmailText()) print("ATTENDEE;CN=%s:MAILTO:%s" % (attendee.getTitle(), attendee.getDefaultEmailText()))
print "ATTACH;FMTTYPE=text/html:%s/%s/view" % (context.ERP5Site_getAbsoluteUrl(), task.getRelativeUrl()) print("ATTACH;FMTTYPE=text/html:%s/%s/view" % (context.ERP5Site_getAbsoluteUrl(), task.getRelativeUrl()))
print "END:VTODO" print("END:VTODO")
return printed return printed
print """BEGIN:VCALENDAR print("""BEGIN:VCALENDAR
PRODID:-//ERP5//NONSGML Task Report Module//EN PRODID:-//ERP5//NONSGML Task Report Module//EN
VERSION:2.0""" VERSION:2.0""")
obj_list = context.getPortalObject().portal_selections.callSelectionFor("task_report_module_selection") obj_list = context.getPortalObject().portal_selections.callSelectionFor("task_report_module_selection")
for obj in obj_list : for obj in obj_list :
print printTask(obj.getObject()) print(printTask(obj.getObject()))
print "END:VCALENDAR" print("END:VCALENDAR")
context.REQUEST.RESPONSE.setHeader('Content-Type', 'text/calendar') context.REQUEST.RESPONSE.setHeader('Content-Type', 'text/calendar')
context.REQUEST.RESPONSE.setHeader('Content-disposition', 'attachment; filename=ERP5.ics') context.REQUEST.RESPONSE.setHeader('Content-disposition', 'attachment; filename=ERP5.ics')
......
...@@ -7,21 +7,21 @@ portal = context.getPortalObject() ...@@ -7,21 +7,21 @@ portal = context.getPortalObject()
test_pages = portal.test_page_module.searchFolder(validation_state= test_pages = portal.test_page_module.searchFolder(validation_state=
('published', 'published_alive','released', 'released_alive', ('published', 'published_alive','released', 'released_alive',
'shared', 'shared_alive',)) 'shared', 'shared_alive',))
print len(test_pages) print(len(test_pages))
new_page_list = [] new_page_list = []
for page in test_pages: for page in test_pages:
print "changing ID of %s to %s of document in state %s" %(page.getRelativeUrl(), page.getReference(), page.getValidationState()) print("changing ID of %s to %s of document in state %s" %(page.getRelativeUrl(), page.getReference(), page.getValidationState()))
if not dry_run: if not dry_run:
page.setId(page.getReference()) page.setId(page.getReference())
print "\tpage changed" print("\tpage changed")
new_page_list.append(page.getReference()) new_page_list.append(page.getReference())
print "finished" print("finished")
print "For business template Path" print("For business template Path")
for p in new_page_list: for p in new_page_list:
print "test_page_module/"+p print("test_page_module/"+p)
print "test_page_module/"+p+"/**" print("test_page_module/"+p+"/**")
return printed return printed
from __future__ import print_function
import PIL.Image as PIL_Image import PIL.Image as PIL_Image
import os import os
import transaction import transaction
...@@ -42,9 +43,9 @@ def uploadImage(self): ...@@ -42,9 +43,9 @@ def uploadImage(self):
def cleanUp(self): def cleanUp(self):
portal = self.getPortalObject() portal = self.getPortalObject()
print "exists path: %r" %os.path.exists("tmp/selenium_image_test.jpg") print("exists path: %r" %os.path.exists("tmp/selenium_image_test.jpg"))
if os.path.exists("tmp/selenium_image_test.jpg"): if os.path.exists("tmp/selenium_image_test.jpg"):
print "REMOVE IMAGE: %s" %(os.remove("tmp/selenium_image_test.jpg")) print("REMOVE IMAGE: %s" %(os.remove("tmp/selenium_image_test.jpg")))
portal.image_module.manage_delObjects(ids=['testTileTransformed']) portal.image_module.manage_delObjects(ids=['testTileTransformed'])
return True return True
else: else:
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
############################################################################## ##############################################################################
from __future__ import print_function
import os, sys, shutil, tempfile import os, sys, shutil, tempfile
from cStringIO import StringIO from cStringIO import StringIO
from zLOG import LOG,ERROR,INFO,WARNING from zLOG import LOG,ERROR,INFO,WARNING
...@@ -175,15 +176,15 @@ class ZoomifyBase: ...@@ -175,15 +176,15 @@ class ZoomifyBase:
lr_y = ul_y + self.tileSize lr_y = ul_y + self.tileSize
else: else:
lr_y = self.originalHeight lr_y = self.originalHeight
print "Going to open image" print("Going to open image")
imageRow = image.crop([0, ul_y, self.originalWidth, lr_y]) imageRow = image.crop([0, ul_y, self.originalWidth, lr_y])
saveFilename = root + str(tier) + '-' + str(row) + ext saveFilename = root + str(tier) + '-' + str(row) + ext
if imageRow.mode != 'RGB': if imageRow.mode != 'RGB':
imageRow = imageRow.convert('RGB') imageRow = imageRow.convert('RGB')
imageRow.save(os.path.join(tempfile.gettempdir(), saveFilename), imageRow.save(os.path.join(tempfile.gettempdir(), saveFilename),
'JPEG', quality=100) 'JPEG', quality=100)
print "os path exist : %r" % os.path.exists(os.path.join( print("os path exist : %r" % os.path.exists(os.path.join(
tempfile.gettempdir(), saveFilename)) tempfile.gettempdir(), saveFilename)))
if os.path.exists(os.path.join(tempfile.gettempdir(), saveFilename)): if os.path.exists(os.path.join(tempfile.gettempdir(), saveFilename)):
self.processRowImage(tier=tier, row=row) self.processRowImage(tier=tier, row=row)
row += 1 row += 1
...@@ -191,7 +192,7 @@ class ZoomifyBase: ...@@ -191,7 +192,7 @@ class ZoomifyBase:
def processRowImage(self, tier=0, row=0): def processRowImage(self, tier=0, row=0):
""" for an image, create and save tiles """ """ for an image, create and save tiles """
print '*** processing tier: ' + str(tier) + ' row: ' + str(row) print('*** processing tier: ' + str(tier) + ' row: ' + str(row))
tierWidth, tierHeight = self._v_scaleInfo[tier] tierWidth, tierHeight = self._v_scaleInfo[tier]
rowsForTier = tierHeight/self.tileSize rowsForTier = tierHeight/self.tileSize
if tierHeight % self.tileSize > 0: if tierHeight % self.tileSize > 0:
......
import json import json
portal = context.getPortalObject() portal = context.getPortalObject()
context.REQUEST.response.setHeader('Access-Control-Allow-Origin', '*') context.REQUEST.response.setHeader('Access-Control-Allow-Origin', '*')
print portal.portal_catalog(portal_type="Image Title", src__=1) print(portal.portal_catalog(portal_type="Image Title", src__=1))
#return printed #return printed
data = {} data = {}
data["image_list"] = [] data["image_list"] = []
......
...@@ -7,6 +7,6 @@ portal = context.getPortalObject() ...@@ -7,6 +7,6 @@ portal = context.getPortalObject()
data = portal.restrictedTraverse("portal_skins/erp5_safeimage/img/image_test.jpg") data = portal.restrictedTraverse("portal_skins/erp5_safeimage/img/image_test.jpg")
print data.data print(data.data)
return printed return printed
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
Tests invoice creation from simulation. Tests invoice creation from simulation.
""" """
from __future__ import print_function
import xml.dom.minidom import xml.dom.minidom
import zipfile import zipfile
...@@ -1273,7 +1274,7 @@ self.portal.getDefaultModule(self.packing_list_portal_type).newContent( ...@@ -1273,7 +1274,7 @@ self.portal.getDefaultModule(self.packing_list_portal_type).newContent(
def _acceptDivergenceOnInvoice(self, invoice, divergence_list): def _acceptDivergenceOnInvoice(self, invoice, divergence_list):
print invoice, divergence_list print(invoice, divergence_list)
self._solveDivergence(invoice, 'quantity', 'Accept Solver') self._solveDivergence(invoice, 'quantity', 'Accept Solver')
def test_accept_quantity_divergence_on_invoice_with_stopped_packing_list( def test_accept_quantity_divergence_on_invoice_with_stopped_packing_list(
...@@ -1326,7 +1327,7 @@ self.portal.getDefaultModule(self.packing_list_portal_type).newContent( ...@@ -1326,7 +1327,7 @@ self.portal.getDefaultModule(self.packing_list_portal_type).newContent(
self.assertEqual('solved', packing_list.getCausalityState()) self.assertEqual('solved', packing_list.getCausalityState())
def _adoptDivergenceOnInvoice(self, invoice, divergence_list): def _adoptDivergenceOnInvoice(self, invoice, divergence_list):
print invoice, divergence_list print(invoice, divergence_list)
self._solveDivergence(invoice, 'quantity', 'Adopt Solver') self._solveDivergence(invoice, 'quantity', 'Adopt Solver')
def test_adopt_quantity_divergence_on_invoice_line_with_stopped_packing_list( def test_adopt_quantity_divergence_on_invoice_line_with_stopped_packing_list(
......
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
# #
############################################################################## ##############################################################################
from __future__ import print_function
import subprocess import subprocess
import unittest import unittest
from test import pystone from test import pystone
...@@ -57,7 +58,7 @@ class TestSimulationPerformance(TestTradeModelLineSale): ...@@ -57,7 +58,7 @@ class TestSimulationPerformance(TestTradeModelLineSale):
self.test_01_OrderWithSimpleTaxedAndDiscountedLines() self.test_01_OrderWithSimpleTaxedAndDiscountedLines()
self.__class__._order = self['order'].getRelativeUrl() self.__class__._order = self['order'].getRelativeUrl()
self.runAlarms() self.runAlarms()
print "\n%s pystones/second" % pystone.pystones()[1] print("\n%s pystones/second" % pystone.pystones()[1])
def perf_01_invoiceSimpleOrder(self, order_count=1): def perf_01_invoiceSimpleOrder(self, order_count=1):
start = time() start = time()
...@@ -118,8 +119,8 @@ class TestSimulationPerformance(TestTradeModelLineSale): ...@@ -118,8 +119,8 @@ class TestSimulationPerformance(TestTradeModelLineSale):
self.runAlarms() self.runAlarms()
end = time() end = time()
print "\n%s took %.4gs (%s order(s))" % (self._testMethodName, print("\n%s took %.4gs (%s order(s))" % (self._testMethodName,
end - start, order_count) end - start, order_count))
def perf_02_invoiceManySimpleOrders(self): def perf_02_invoiceManySimpleOrders(self):
self.perf_01_invoiceSimpleOrder(10) self.perf_01_invoiceSimpleOrder(10)
......
...@@ -69,6 +69,7 @@ and that between Sale Packing List and Sale Invoice is M:N. ...@@ -69,6 +69,7 @@ and that between Sale Packing List and Sale Invoice is M:N.
""" """
from __future__ import print_function
import unittest import unittest
from time import time from time import time
import gc import gc
...@@ -304,8 +305,8 @@ class TestSimulationPerformance(ERP5TypeTestCase, LogInterceptor): ...@@ -304,8 +305,8 @@ class TestSimulationPerformance(ERP5TypeTestCase, LogInterceptor):
after_time = time() after_time = time()
amount_of_time = after_time - before_time amount_of_time = after_time - before_time
min_time, max_time = self._getMinMaxTime(target) min_time, max_time = self._getMinMaxTime(target)
print "\n%s took %.4f (%.4f < %.4f < %.4f)" \ print("\n%s took %.4f (%.4f < %.4f < %.4f)" \
% (target, amount_of_time, min_time, amount_of_time, max_time) % (target, amount_of_time, min_time, amount_of_time, max_time))
# Reset the target to make sure that the same target is not # Reset the target to make sure that the same target is not
# measured again. # measured again.
sequence.edit(measure_target=None) sequence.edit(measure_target=None)
...@@ -792,13 +793,13 @@ class TestSimulationPerformance(ERP5TypeTestCase, LogInterceptor): ...@@ -792,13 +793,13 @@ class TestSimulationPerformance(ERP5TypeTestCase, LogInterceptor):
if measurable: if measurable:
result = sequence.get('result') result = sequence.get('result')
if result: if result:
print '' print('')
failure_list = [] failure_list = []
for target, min_time, real_time, max_time in result: for target, min_time, real_time, max_time in result:
condition = (min_time < real_time < max_time) condition = (min_time < real_time < max_time)
print '%s%s: %.4f < %.4f < %.4f' \ print('%s%s: %.4f < %.4f < %.4f' \
% (condition and ' ' or '!', % (condition and ' ' or '!',
target, min_time, real_time, max_time) target, min_time, real_time, max_time))
if not condition: if not condition:
failure_list.append(target) failure_list.append(target)
self.assertTrue(not failure_list, self.assertTrue(not failure_list,
......
...@@ -15,6 +15,7 @@ if recipient_list: ...@@ -15,6 +15,7 @@ if recipient_list:
mail_from='nobody@svn.erp5.org', mail_from='nobody@svn.erp5.org',
include_link=include_link, include_link=include_link,
include_diff=True) include_diff=True)
print 'Successfully sent to: ', recipient_list
print 'OK' print('Successfully sent to: %s' % recipient_list)
print('OK')
return printed return printed
"""
Return for buildbot test summary info.
status, all tests, failures, errors
"""
seconds = 0.0
for obj in context.contentValues():
seconds += obj.getProperty('duration')
print '%s,%s,%s,%s,%s,%s' %( context.getProperty('status'), context.getProperty('all_tests'),
context.getProperty('failures'), context.getProperty('errors'),
context.getProperty('skips'), seconds)
return printed
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="PythonScript" module="Products.PythonScripts.PythonScript"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_bind_names</string> </key>
<value>
<object>
<klass>
<global name="_reconstructor" module="copy_reg"/>
</klass>
<tuple>
<global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
<global name="object" module="__builtin__"/>
<none/>
</tuple>
<state>
<dictionary>
<item>
<key> <string>_asgns</string> </key>
<value>
<dictionary>
<item>
<key> <string>name_container</string> </key>
<value> <string>container</string> </value>
</item>
<item>
<key> <string>name_context</string> </key>
<value> <string>context</string> </value>
</item>
<item>
<key> <string>name_m_self</string> </key>
<value> <string>script</string> </value>
</item>
<item>
<key> <string>name_subpath</string> </key>
<value> <string>traverse_subpath</string> </value>
</item>
</dictionary>
</value>
</item>
</dictionary>
</state>
</object>
</value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>_proxy_roles</string> </key>
<value>
<tuple>
<string>Manager</string>
</tuple>
</value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>TestResult_getSummary</string> </value>
</item>
<item>
<key> <string>title</string> </key>
<value> <string>Return short test summary</string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
...@@ -5,5 +5,5 @@ Multiline stdout values behaviour is undefined. ...@@ -5,5 +5,5 @@ Multiline stdout values behaviour is undefined.
""" """
for test_result_node in context.objectValues(portal_type='Test Result Node'): for test_result_node in context.objectValues(portal_type='Test Result Node'):
if test_result_node.getCmdline() == 'LOG url': if test_result_node.getCmdline() == 'LOG url':
print test_result_node.getStdout() print(test_result_node.getStdout().decode('ascii', 'replace'))
return printed return printed
...@@ -5,12 +5,12 @@ ps = context.getPortalObject().portal_property_sheets[property_sheet_id] ...@@ -5,12 +5,12 @@ ps = context.getPortalObject().portal_property_sheets[property_sheet_id]
for prop in ps.objectValues(portal_type="Standard Property"): for prop in ps.objectValues(portal_type="Standard Property"):
field_id = "my_%s" %prop.getReference() field_id = "my_%s" %prop.getReference()
if getattr(context, field_id, None) is None: if getattr(context, field_id, None) is None:
print "will add %s" %(field_id) print("will add %s" %(field_id))
if prop.getElementaryType() == "string": if prop.getElementaryType() == "string":
context.manage_addField(field_id, prop.getReference(), "StringField") context.manage_addField(field_id, prop.getReference(), "StringField")
elif prop.getElementaryType() == "boolean": elif prop.getElementaryType() == "boolean":
context.manage_addField(field_id, prop.getReference(), "CheckBoxField") context.manage_addField(field_id, prop.getReference(), "CheckBoxField")
else: else:
print "unkown type", prop.getElementaryType() print("unkown type", prop.getElementaryType())
return printed return printed
...@@ -19,9 +19,9 @@ for record in portal.expense_record_module.objectValues(portal_type="Expense Rec ...@@ -19,9 +19,9 @@ for record in portal.expense_record_module.objectValues(portal_type="Expense Rec
) )
image.share() image.share()
else: else:
print ticket.getRelativeUrl() print(ticket.getRelativeUrl())
print DateTime() print(DateTime())
#return printed #return printed
...@@ -31,6 +31,6 @@ for i in context.portal_catalog(portal_type='Expense Validation Request'): ...@@ -31,6 +31,6 @@ for i in context.portal_catalog(portal_type='Expense Validation Request'):
if i.getReference() != sourceReference: if i.getReference() != sourceReference:
if migrate: if migrate:
i.setReference(sourceReference) i.setReference(sourceReference)
print i.getRelativeUrl() print(i.getRelativeUrl())
return printed return printed
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
from __future__ import print_function
from time import time from time import time
import gc import gc
import subprocess import subprocess
...@@ -219,8 +220,8 @@ class TestPerformance(TestPerformanceMixin): ...@@ -219,8 +220,8 @@ class TestPerformance(TestPerformanceMixin):
bar.Bar_viewPerformance() bar.Bar_viewPerformance()
after_view = time() after_view = time()
req_time = (after_view - before_view)/100. req_time = (after_view - before_view)/100.
print "%s time to view object form %.4f < %.4f < %.4f\n" % \ print("%s time to view object form %.4f < %.4f < %.4f\n" % \
(prefix, min_, req_time, max_) (prefix, min_, req_time, max_))
if PROFILE: if PROFILE:
self.profile(bar.Bar_viewPerformance) self.profile(bar.Bar_viewPerformance)
if DO_TEST: if DO_TEST:
...@@ -291,10 +292,10 @@ class TestPerformance(TestPerformanceMixin): ...@@ -291,10 +292,10 @@ class TestPerformance(TestPerformanceMixin):
add_value = add_result[key] add_value = add_result[key]
min_view = MIN_MODULE_VIEW + LISTBOX_COEF * i min_view = MIN_MODULE_VIEW + LISTBOX_COEF * i
max_view = MAX_MODULE_VIEW + LISTBOX_COEF * i max_view = MAX_MODULE_VIEW + LISTBOX_COEF * i
print "nb objects = %s\n\tadd = %.4f < %.4f < %.4f" %(key, MIN_OBJECT_CREATION, add_value, MAX_OBJECT_CREATION) print("nb objects = %s\n\tadd = %.4f < %.4f < %.4f" %(key, MIN_OBJECT_CREATION, add_value, MAX_OBJECT_CREATION))
print "\ttic = %.4f < %.4f < %.4f" %(MIN_TIC, tic_value, MAX_TIC) print("\ttic = %.4f < %.4f < %.4f" %(MIN_TIC, tic_value, MAX_TIC))
print "\tview = %.4f < %.4f < %.4f" %(min_view, module_value, max_view) print("\tview = %.4f < %.4f < %.4f" %(min_view, module_value, max_view))
print print()
i += 1 i += 1
# then check results # then check results
if DO_TEST: if DO_TEST:
...@@ -337,10 +338,10 @@ class TestPerformance(TestPerformanceMixin): ...@@ -337,10 +338,10 @@ class TestPerformance(TestPerformanceMixin):
after_view = time() after_view = time()
req_time = (after_view - before_view)/100. req_time = (after_view - before_view)/100.
print "time to view proxyfield form %.4f < %.4f < %.4f\n" % \ print("time to view proxyfield form %.4f < %.4f < %.4f\n" % \
( MIN_OBJECT_PROXYFIELD_VIEW, ( MIN_OBJECT_PROXYFIELD_VIEW,
req_time, req_time,
MAX_OBJECT_PROXYFIELD_VIEW ) MAX_OBJECT_PROXYFIELD_VIEW ))
if PROFILE: if PROFILE:
self.profile(foo.Foo_viewProxyField) self.profile(foo.Foo_viewProxyField)
if DO_TEST: if DO_TEST:
...@@ -368,10 +369,10 @@ class TestPerformance(TestPerformanceMixin): ...@@ -368,10 +369,10 @@ class TestPerformance(TestPerformanceMixin):
after_view = time() after_view = time()
req_time = (after_view - before_view)/100. req_time = (after_view - before_view)/100.
print "time to view object form with many lines %.4f < %.4f < %.4f\n" % \ print("time to view object form with many lines %.4f < %.4f < %.4f\n" % \
( MIN_OBJECT_MANY_LINES_VIEW, ( MIN_OBJECT_MANY_LINES_VIEW,
req_time, req_time,
MAX_OBJECT_MANY_LINES_VIEW ) MAX_OBJECT_MANY_LINES_VIEW ))
if PROFILE: if PROFILE:
self.profile(foo.Foo_viewPerformance) self.profile(foo.Foo_viewPerformance)
if DO_TEST: if DO_TEST:
...@@ -407,12 +408,12 @@ class TestPropertyPerformance(TestPerformanceMixin): ...@@ -407,12 +408,12 @@ class TestPropertyPerformance(TestPerformanceMixin):
after = time() after = time()
total_time = (after - before) / 100. total_time = (after - before) / 100.
print ("time %s.%s %.4f < %.4f < %.4f\n" % \ print(("time %s.%s %.4f < %.4f < %.4f\n" % \
( self.id(), ( self.id(),
f.__doc__ or f.__name__, f.__doc__ or f.__name__,
min_time, min_time,
total_time, total_time,
max_time )) max_time )))
if PROFILE: if PROFILE:
self.profile(f, args=(i, )) self.profile(f, args=(i, ))
if DO_TEST: if DO_TEST:
......
...@@ -12,11 +12,11 @@ if getattr(context.MailHost, "getMessageList", None) is None: ...@@ -12,11 +12,11 @@ if getattr(context.MailHost, "getMessageList", None) is None:
message_list = context.MailHost.getMessageList() message_list = context.MailHost.getMessageList()
for mail in message_list: for mail in message_list:
for part in mail: for part in mail:
print part print(part)
print "="*79 print("="*79)
print "" print("")
print "Total messages: %s" %len(message_list) print("Total messages: %s" %len(message_list))
# If messages "looks like html", zope will set content type to text/html, # If messages "looks like html", zope will set content type to text/html,
# and the assertTextPresent from selenium will be applied after the emails # and the assertTextPresent from selenium will be applied after the emails
......
...@@ -10,5 +10,4 @@ try: ...@@ -10,5 +10,4 @@ try:
for x in portal_tests.objectValues('Zuite Results')]) for x in portal_tests.objectValues('Zuite Results')])
except BadRequest: except BadRequest:
pass pass
print "OK" return "OK"
return printed
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# #
############################################################################## ##############################################################################
from __future__ import print_function
import unittest import unittest
from Products.ERP5Type.tests.ERP5TypeFunctionalTestCase import ERP5TypeFunctionalTestCase from Products.ERP5Type.tests.ERP5TypeFunctionalTestCase import ERP5TypeFunctionalTestCase
...@@ -86,7 +87,7 @@ class TestZeleniumCore(ERP5TypeFunctionalTestCase): ...@@ -86,7 +87,7 @@ class TestZeleniumCore(ERP5TypeFunctionalTestCase):
ERP5TypeFunctionalTestCase.afterSetUp(self) ERP5TypeFunctionalTestCase.afterSetUp(self)
self.http_root_dir = tempfile.mkdtemp() self.http_root_dir = tempfile.mkdtemp()
print "Serving files on http from %r" % self.http_root_dir print("Serving files on http from %r" % self.http_root_dir)
self.generateMonitoringInstanceTree() self.generateMonitoringInstanceTree()
self.httpd_is_alive = True self.httpd_is_alive = True
......
...@@ -227,5 +227,5 @@ if create_project_documents: ...@@ -227,5 +227,5 @@ if create_project_documents:
portal_type = 'Project', portal_type = 'Project',
reference = draft_project) reference = draft_project)
print "Project Created" print("Project Created")
return printed return printed
...@@ -419,9 +419,9 @@ class TestConvertedWorkflow(TestERP5WorkflowMixin): ...@@ -419,9 +419,9 @@ class TestConvertedWorkflow(TestERP5WorkflowMixin):
text_document3 = self.getTestObject() text_document3 = self.getTestObject()
text_document3_permission = getattr(text_document3, permission_key, None) text_document3_permission = getattr(text_document3, permission_key, None)
print 'text_document1_permission: %r' % (text_document1_permission, ) print('text_document1_permission: %r' % (text_document1_permission, ))
print 'text_document2_permission: %r' % (text_document2_permission, ) print('text_document2_permission: %r' % (text_document2_permission, ))
print 'text_document3_permission: %r' % (text_document3_permission, ) print('text_document3_permission: %r' % (text_document3_permission, ))
self.assertEqual(tuple(getattr(text_document3, permission_key)), self.assertEqual(tuple(getattr(text_document3, permission_key)),
('Assignee', 'Assignor', 'Auditor', 'Author')) ('Assignee', 'Assignor', 'Auditor', 'Author'))
......
...@@ -22,7 +22,7 @@ result = connection.getresponse() ...@@ -22,7 +22,7 @@ result = connection.getresponse()
path = result.getheader("X-Document-Location") path = result.getheader("X-Document-Location")
result.close() result.close()
path = '/%s' % '/'.join(path.split('/')[3:]) path = '/%s' % '/'.join(path.split('/')[3:])
print path print(path)
###################################### ######################################
# Upload chunks # Upload chunks
......
from six import string_types as basestring from six import string_types as basestring
import re
import json import json
from Products.ERP5Type.Utils import checkPythonSourceCode from Products.ERP5Type.Utils import checkPythonSourceCode
match_PEP263 = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)').match
def checkPythonSourceCodeAsJSON(self, data, REQUEST=None): def checkPythonSourceCodeAsJSON(self, data, REQUEST=None):
""" """
Check Python source suitable for Source Code Editor and return a JSON object Check Python source suitable for Source Code Editor and return a JSON object
...@@ -24,8 +29,19 @@ def checkPythonSourceCodeAsJSON(self, data, REQUEST=None): ...@@ -24,8 +29,19 @@ def checkPythonSourceCodeAsJSON(self, data, REQUEST=None):
signature_parts += [data['params']] signature_parts += [data['params']]
signature = ", ".join(signature_parts) signature = ", ".join(signature_parts)
function_name = "function_name" # keep the PEP263 magic comment
body = "def %s(%s):\n%s" % (function_name, pep263_comment = '#'
lines = data['code'].splitlines() + ['', '']
for line in lines[0], lines[1]:
m = match_PEP263(line)
if m:
pep263_comment = '# coding=' + m.groups()[0]
break
body = "%s\n"\
"from __future__ import print_function\n"\
"def function_name(%s):\n%s" % (
pep263_comment,
signature, signature,
indent(data['code']) or " pass") indent(data['code']) or " pass")
else: else:
...@@ -34,7 +50,7 @@ def checkPythonSourceCodeAsJSON(self, data, REQUEST=None): ...@@ -34,7 +50,7 @@ def checkPythonSourceCodeAsJSON(self, data, REQUEST=None):
message_list = checkPythonSourceCode(body.encode('utf8'), data.get('portal_type')) message_list = checkPythonSourceCode(body.encode('utf8'), data.get('portal_type'))
for message_dict in message_list: for message_dict in message_list:
if is_script: if is_script:
message_dict['row'] = message_dict['row'] - 2 message_dict['row'] = message_dict['row'] - 4
else: else:
message_dict['row'] = message_dict['row'] - 1 message_dict['row'] = message_dict['row'] - 1
......
...@@ -14,7 +14,7 @@ if from_cat is not None and to_cat is not None: ...@@ -14,7 +14,7 @@ if from_cat is not None and to_cat is not None:
new_category_list += (cat,) new_category_list += (cat,)
if has_changed == 1: if has_changed == 1:
o.setCategoryList(new_category_list) o.setCategoryList(new_category_list)
print("changed category %s with %s on %s" % (str(from_cat),str(to_cat),str(o.getPath()))) print(("changed category %s with %s on %s" % (str(from_cat),str(to_cat),str(o.getPath()))))
print(" ") print(" ")
......
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
# user: user1 password: user1 # user: user1 password: user1
# user: user2 password: user2 # user: user2 password: user2
from __future__ import print_function
from threading import Thread from threading import Thread
from time import sleep from time import sleep
from urllib import addinfourl from urllib import addinfourl
...@@ -47,13 +48,11 @@ def main(): ...@@ -47,13 +48,11 @@ def main():
# We must provide an authentication parameter such as __ac_name # We must provide an authentication parameter such as __ac_name
url = '//user%i:user%i@localhost:9673%s?__ac_name=user%s&__ac_password=user%s' % \ url = '//user%i:user%i@localhost:9673%s?__ac_name=user%s&__ac_password=user%s' % \
(i,i,list_url[i][:-1],i,i) (i,i,list_url[i][:-1],i,i)
#print "cur thread : %i" % (len(threads))
threads += [Thread(target=checker[len(threads)].CheckUrl,kwargs={'url':url})] threads += [Thread(target=checker[len(threads)].CheckUrl,kwargs={'url':url})]
#print "cur thread : %i" % (len(threads)-1)
threads[len(threads)-1].start() threads[len(threads)-1].start()
request_number += 1 request_number += 1
i+=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: else:
for t in range(0,max_thread): for t in range(0,max_thread):
if threads[t].isAlive() == 0: if threads[t].isAlive() == 0:
...@@ -63,7 +62,7 @@ def main(): ...@@ -63,7 +62,7 @@ def main():
threads[t].start() threads[t].start()
i+=1 i+=1
request_number += 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 break
...@@ -97,7 +96,6 @@ class URLOpener(FancyURLopener): ...@@ -97,7 +96,6 @@ class URLOpener(FancyURLopener):
user_passwd, realhost = splituser(realhost) user_passwd, realhost = splituser(realhost)
if user_passwd: if user_passwd:
selector = "%s://%s%s" % (urltype, realhost, rest) selector = "%s://%s%s" % (urltype, realhost, rest)
#print "proxy via http:", host, selector
if not host: raise IOError('http error', 'no host given') if not host: raise IOError('http error', 'no host given')
if user_passwd: if user_passwd:
import base64 import base64
...@@ -146,17 +144,17 @@ class Checker(URLOpener): ...@@ -146,17 +144,17 @@ class Checker(URLOpener):
thread.start() thread.start()
while thread.isAlive(): while thread.isAlive():
sleep(0.5) sleep(0.5)
print "Connection to %s went fine" % url print("Connection to %s went fine" % url)
except IOError as err: except IOError as err:
(errno, strerror) = err.args (errno, strerror) = err.args
print "Can't connect to %s because of I/O error(%s): %s" % (url, errno, strerror) print("Can't connect to %s because of I/O error(%s): %s" % (url, errno, strerror))
def SearchUrl(self, url=None): def SearchUrl(self, url=None):
try: try:
conn = self.open_http(url) conn = self.open_http(url)
except IOError as err: except IOError as err:
(errno, strerror) = err.args (errno, strerror) = err.args
print "Can't connect to %s because of I/O error(%s): %s" % (url, errno, strerror) print("Can't connect to %s because of I/O error(%s): %s" % (url, errno, strerror))
def raise_error(self, error_key, field): def raise_error(self, error_key, field):
......
...@@ -188,8 +188,8 @@ class TestInvalidationBug(ERP5TypeTestCase): ...@@ -188,8 +188,8 @@ class TestInvalidationBug(ERP5TypeTestCase):
module.setIdGenerator('_generatePerDayId') module.setIdGenerator('_generatePerDayId')
#module.migrateToHBTree() #module.migrateToHBTree()
self.tic() self.tic()
print 'OID(%s) = %r' % (module.getRelativeUrl(), module._p_oid) print('OID(%s) = %r' % (module.getRelativeUrl(), module._p_oid))
print ' OID(_tree) = %r' % module._tree._p_oid print(' OID(_tree) = %r' % module._tree._p_oid)
previous = DateTime() previous = DateTime()
skin_folder = self.getPortal().portal_skins.custom skin_folder = self.getPortal().portal_skins.custom
if 'create_script' in skin_folder.objectIds(): if 'create_script' in skin_folder.objectIds():
......
...@@ -103,7 +103,7 @@ class TestSecurityMixin(ERP5TypeTestCase): ...@@ -103,7 +103,7 @@ class TestSecurityMixin(ERP5TypeTestCase):
if os.environ.get('erp5_debug_mode') or '/erp5/' in filename or '<portal_components' in filename: if os.environ.get('erp5_debug_mode') or '/erp5/' in filename or '<portal_components' in filename:
error_list.append('%s:%s %s' % (filename, lineno, method_id)) error_list.append('%s:%s %s' % (filename, lineno, method_id))
else: else:
print('Ignoring missing security definition for %s in %s:%s ' % (method_id, filename, lineno)) print(('Ignoring missing security definition for %s in %s:%s ' % (method_id, filename, lineno)))
if error_list: if error_list:
message = '\nThe following %s methods have a docstring but have no security assertions.\n\t%s' \ message = '\nThe following %s methods have a docstring but have no security assertions.\n\t%s' \
% (len(error_list), '\n\t'.join(error_list)) % (len(error_list), '\n\t'.join(error_list))
......
...@@ -690,7 +690,7 @@ if validator_to_use == 'tidy': ...@@ -690,7 +690,7 @@ if validator_to_use == 'tidy':
warning = False warning = False
validator_path = '/usr/bin/tidy' validator_path = '/usr/bin/tidy'
if not os.path.exists(validator_path): 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: else:
validator = TidyValidator(validator_path, show_warnings) validator = TidyValidator(validator_path, show_warnings)
......
...@@ -27,5 +27,5 @@ ...@@ -27,5 +27,5 @@
############################################################################## ##############################################################################
def say_hello(): def say_hello():
print 'hello' print('hello')
...@@ -454,10 +454,10 @@ class ERP5TypeFunctionalTestCase(ERP5TypeTestCase): ...@@ -454,10 +454,10 @@ class ERP5TypeFunctionalTestCase(ERP5TypeTestCase):
def _verboseErrorLog(self, size=10): def _verboseErrorLog(self, size=10):
for entry in self.portal.error_log.getLogEntries()[:size]: for entry in self.portal.error_log.getLogEntries()[:size]:
print "="*20 print("="*20)
print "ERROR ID : %s" % entry["id"] print("ERROR ID : %s" % entry["id"])
print "TRACEBACK :" print("TRACEBACK :")
print entry["tb_text"] print(entry["tb_text"])
def testFunctionalTestRunner(self): def testFunctionalTestRunner(self):
# Check the zuite page templates can be rendered, because selenium test # Check the zuite page templates can be rendered, because selenium test
......
...@@ -33,4 +33,4 @@ class TestPystone(unittest.TestCase): ...@@ -33,4 +33,4 @@ class TestPystone(unittest.TestCase):
"""Tests to get pystone value """Tests to get pystone value
""" """
def test_pystone(self): def test_pystone(self):
print "PYSTONE RESULT (time,score) : %r" % (pystone.pystones(),) print("PYSTONE RESULT (time,score) : %r" % (pystone.pystones(),))
...@@ -55,11 +55,11 @@ class TestSQLBench(unittest.TestCase): ...@@ -55,11 +55,11 @@ class TestSQLBench(unittest.TestCase):
sqlbench_path + '/test-alter-table', sqlbench_path + '/test-alter-table',
'--database', database, '--database', database,
'--host', host, '--user', user, '--password', password] '--host', host, '--user', user, '--password', password]
print command_list print(command_list)
process = subprocess.Popen(command_list, process = subprocess.Popen(command_list,
cwd = sqlbench_path, cwd = sqlbench_path,
stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate() output, error = process.communicate()
self.assertEqual(0, len(error), error) self.assertEqual(0, len(error), error)
print output print(output)
self.assertTrue(output.find("Total time: ")>=0) self.assertTrue(output.find("Total time: ")>=0)
#!/usr/bin/env python2.7 #!/usr/bin/env python2.7
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import print_function
import argparse, sys, os, textwrap import argparse, sys, os, textwrap
from erp5.util import taskdistribution from erp5.util import taskdistribution
...@@ -8,7 +9,7 @@ from erp5.util import taskdistribution ...@@ -8,7 +9,7 @@ from erp5.util import taskdistribution
from . import ERP5TypeTestSuite from . import ERP5TypeTestSuite
def _parsingErrorHandler(data, _): def _parsingErrorHandler(data, _):
print >> sys.stderr, 'Error parsing data:', repr(data) print('Error parsing data:', repr(data), file=sys.stderr)
taskdistribution.patchRPCParser(_parsingErrorHandler) taskdistribution.patchRPCParser(_parsingErrorHandler)
def makeSuite( def makeSuite(
...@@ -119,8 +120,8 @@ def main(): ...@@ -119,8 +120,8 @@ def main():
args.zserver_frontend_url_list.split(',') if args.zserver_frontend_url_list else ()) 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: 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)' % ( print('Not enough zserver address/frontends for node quantity %s (%r)' % (
args.node_quantity, args.zserver_address_list) args.node_quantity, args.zserver_address_list), file=sys.stderr)
sys.exit(1) sys.exit(1)
# sanity check # sanity check
......
#!/usr/bin/env python2.7 #!/usr/bin/env python2.7
from __future__ import print_function
import os import os
import sys import sys
import pdb import pdb
...@@ -698,7 +699,7 @@ def runUnitTestList(test_list, verbosity=1, debug=0, run_only=None): ...@@ -698,7 +699,7 @@ def runUnitTestList(test_list, verbosity=1, debug=0, run_only=None):
transaction.commit() transaction.commit()
except: except:
import traceback 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 # finally does not expect opened transaction, even in the
# case of a Ctrl-C. # case of a Ctrl-C.
transaction.abort() transaction.abort()
...@@ -733,10 +734,10 @@ def runUnitTestList(test_list, verbosity=1, debug=0, run_only=None): ...@@ -733,10 +734,10 @@ def runUnitTestList(test_list, verbosity=1, debug=0, run_only=None):
def usage(stream, msg=None): def usage(stream, msg=None):
if msg: if msg:
print >>stream, msg print(msg, file=stream)
print >>stream print(file=stream)
program = os.path.basename(sys.argv[0]) program = os.path.basename(sys.argv[0])
print >>stream, __doc__ % {"program": program} print(__doc__ % {"program": program}, file=stream)
log_directory = None log_directory = None
def main(argument_list=None): def main(argument_list=None):
......
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import print_function
import os import os
import logging import logging
from Products.Archetypes.tests.atsitetestcase import ATSiteTestCase from Products.Archetypes.tests.atsitetestcase import ATSiteTestCase
...@@ -44,8 +45,8 @@ class TransformTest(ATSiteTestCase): ...@@ -44,8 +45,8 @@ class TransformTest(ATSiteTestCase):
output = open(output) output = open(output)
except IOError: except IOError:
import sys import sys
print >>sys.stderr, 'No output file found.' print('No output file found.', file=sys.stderr)
print >>sys.stderr, 'File %s created, check it !' % self.output print('File %s created, check it !' % self.output, file=sys.stderr)
output = open(output, 'w') output = open(output, 'w')
output.write(got) output.write(got)
output.close() output.close()
...@@ -238,7 +239,7 @@ def make_tests(test_descr=TRANSFORMS_TESTINFO): ...@@ -238,7 +239,7 @@ def make_tests(test_descr=TRANSFORMS_TESTINFO):
continue continue
if TR_NAMES is not None and not _transform.name() in TR_NAMES: if TR_NAMES is not None and not _transform.name() in TR_NAMES:
print 'skip test for', _transform.name() print('skip test for', _transform.name())
continue continue
class TransformTestSubclass(TransformTest): class TransformTestSubclass(TransformTest):
......
...@@ -2,7 +2,7 @@ import sys ...@@ -2,7 +2,7 @@ import sys
import httplib import httplib
if ( len(sys.argv) != 5 ): if ( len(sys.argv) != 5 ):
print "usage tinyWebClient.py host port method path" print("usage tinyWebClient.py host port method path")
else: else:
host = sys.argv[1] host = sys.argv[1]
port = sys.argv[2] port = sys.argv[2]
...@@ -10,7 +10,7 @@ else: ...@@ -10,7 +10,7 @@ else:
path = sys.argv[4] path = sys.argv[4]
info = (host, port) info = (host, port)
print "%s:%s" % info print("%s:%s" % info)
conn = httplib.HTTPConnection("%s:%s" % info) conn = httplib.HTTPConnection("%s:%s" % info)
conn.request(method, path) conn.request(method, path)
print conn.getresponse().msg print(conn.getresponse().msg)
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
# serves files relative to the current directory. # serves files relative to the current directory.
# cgi-bin directory serves Python CGIs. # cgi-bin directory serves Python CGIs.
from __future__ import print_function
import BaseHTTPServer import BaseHTTPServer
import CGIHTTPServer import CGIHTTPServer
import time import time
...@@ -62,12 +63,12 @@ if __name__ == '__main__': ...@@ -62,12 +63,12 @@ if __name__ == '__main__':
server_address = ('', port) server_address = ('', port)
httpd = BaseHTTPServer.HTTPServer(server_address, HTTPHandler) httpd = BaseHTTPServer.HTTPServer(server_address, HTTPHandler)
print "serving at port", port print("serving at port", port)
print "To run the entire JsUnit test suite, open" print("To run the entire JsUnit test suite, open")
print (" http://localhost:8000/jsunit/testRunner.html?testPage=" print(" http://localhost:8000/jsunit/testRunner.html?testPage="
"http://localhost:8000/tests/JsUnitSuite.html&autoRun=true") "http://localhost:8000/tests/JsUnitSuite.html&autoRun=true")
print "To run the acceptance test suite, open" print("To run the acceptance test suite, open")
print " http://localhost:8000/TestRunner.html" print(" http://localhost:8000/TestRunner.html")
while not HTTPHandler.quitRequestReceived : while not HTTPHandler.quitRequestReceived :
httpd.handle_request() httpd.handle_request()
......
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