Commit f01065f8 authored by Arnaud Fontaine's avatar Arnaud Fontaine

WIP: futurize --both-stages --write --nobackups .

parent eef397c1

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

......@@ -13,10 +13,10 @@ information = context.getContentInformation()
result = {}
property_id_list = context.propertyIds()
for k, v in information.items():
for k, v in list(information.items()):
key = k.lower()
if v:
if isinstance(v, unicode): v = v.encode('utf-8')
if isinstance(v, str): v = v.encode('utf-8')
if key in property_id_list:
if key == 'reference':
pass # XXX - We can not trust reference on getContentInformation
......
from __future__ import print_function
#try: //Implement try catch instead of if else
#from Products.ERP5Type.JSON import dumps
from Products.ERP5Type.JSONEncoder import encodeInJson as dumps
......@@ -26,9 +27,9 @@ informations = { 'processing': processing,
if informations['processing'] in ['converted', 'conversion_failed','empty']:
informations['permanent_url'] = document.Document_getPermanentUrl()
print dumps(informations) #print info before del object
print(dumps(informations)) #print info before del object
portal.portal_sessions.manage_delObjects(reference)
else:
print dumps(informations)
print(dumps(informations))
return printed
......@@ -2,6 +2,7 @@
Keyword argument:
min_len -- min length of password (default=6, int)
max_len -- min length of password (default=10, int)"""
from builtins import str
import string
import random
......
......@@ -6,7 +6,7 @@
website = context.getWebSiteValue()
REQUEST = context.REQUEST
if REQUEST.has_key('portal_skin'):
if 'portal_skin' in REQUEST:
context.portal_skins.clearSkinCookie()
#XXX get cookie name from key authentication plugin
......
......@@ -27,14 +27,17 @@
#
##############################################################################
from future import standard_library
standard_library.install_aliases()
from builtins import str
from ZPublisher.HTTPRequest import HTTPRequest
from ZPublisher.HTTPResponse import HTTPResponse
from Products.PluggableAuthService.interfaces.plugins import IAuthenticationPlugin
from DateTime import DateTime
import urllib
import httplib
import urllib.request, urllib.parse, urllib.error
import http.client
import base64
import StringIO
import io
import mock
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Security.ERP5DumbHTTPExtractionPlugin import ERP5DumbHTTPExtractionPlugin
......@@ -140,10 +143,10 @@ class TestERP5AccessTokenSkins(AccessTokenTestCase):
response = self.publish('/%s/Base_getUserCaption?%s' % (
self.portal.getId(),
urllib.urlencode({
urllib.parse.urlencode({
'access_token': access_token.getId(),
'access_token_secret': access_token.getReference()})))
self.assertEqual(response.getStatus(), httplib.OK)
self.assertEqual(response.getStatus(), http.client.OK)
# XXX caption currently shows plugin id and relative URL of the token,
# that's not ideal.
self.assertEqual(
......@@ -438,7 +441,7 @@ class TestERP5DumbHTTPExtractionPlugin(AccessTokenTestCase):
env['GATEWAY_INTERFACE']='CGI/1.1 '
env['SCRIPT_NAME']='Main'
env.update(headers)
return HTTPRequest(StringIO.StringIO(), env, HTTPResponse())
return HTTPRequest(io.StringIO(), env, HTTPResponse())
def test_working_authentication(self):
request = self.do_fake_request("GET", {"HTTP_AUTHORIZATION": "Basic " + base64.b64encode("login:password")})
......
......@@ -62,7 +62,7 @@ class AccountingTransactionBalanceConstraint(ConstraintMixin):
section = line.getDestinationSectionValue()
destination_sum[section].append(line.getDestinationInventoriatedTotalAssetPrice() or 0)
for section, amount_list in source_sum.items():
for section, amount_list in list(source_sum.items()):
precision = 2
if amount_list and section is not None and\
section.getPortalType() == 'Organisation':
......@@ -75,7 +75,7 @@ class AccountingTransactionBalanceConstraint(ConstraintMixin):
mapping=dict(section_title=section.getTranslatedTitle())))
break
for section, amount_list in destination_sum.items():
for section, amount_list in list(destination_sum.items()):
precision = 2
if amount_list and section is not None and\
section.getPortalType() == 'Organisation':
......
......@@ -346,7 +346,7 @@ class BalanceTransaction(AccountingTransaction, Inventory):
for new_stock in new_stock_list:
matching_diff = None
for diff in stock_diff_list:
for prop in [k for k in diff.keys() if k not in ('quantity',
for prop in [k for k in list(diff.keys()) if k not in ('quantity',
'total_price', 'id', 'uid', 'relative_url')]:
if diff[prop] != new_stock.get(prop):
break
......@@ -377,7 +377,7 @@ class BalanceTransaction(AccountingTransaction, Inventory):
delta_list = []
for current_stock_key, current_stock_value_list in \
current_stock_dict.items():
list(current_stock_dict.items()):
if current_stock_key in new_stock_dict:
delta_list.extend(computeStockDifference(
current_stock_value_list,
......@@ -388,7 +388,7 @@ class BalanceTransaction(AccountingTransaction, Inventory):
# now add every thing in new stock which was not in current stock
for new_stock_key, new_stock_value_list in \
new_stock_dict.items():
list(new_stock_dict.items()):
if new_stock_key not in current_stock_dict:
delta_list.extend(new_stock_value_list)
......
from builtins import zip
from Products.ZSQLCatalog.SQLCatalog import SimpleQuery
from Products.PythonScripts.standard import Object
from ZTUtils import LazyFilter
......@@ -42,7 +43,7 @@ src_list = []
def getInventoryList(node_uid=None, **kw):
if not node_uid and node_uid is not None:
return []
for key, value in inventory_params.iteritems():
for key, value in inventory_params.items():
assert key not in kw, key
kw[key] = value
result = getInventoryList_(
......@@ -632,7 +633,7 @@ def getPaymentTitleFromUid(uid):
return title
line_list = []
for key, data in line_per_account.iteritems():
for key, data in line_per_account.items():
node_relative_url = key[0]
mirror_section_uid = key[1]
payment_uid = key[2]
......
from builtins import str
from ZTUtils import make_query
from Products.PythonScripts.standard import html_quote
......
......@@ -20,7 +20,7 @@ def getSubFieldDict():
item_key = '/'.join(item_split[:split_depth])
# Create a new subfield if necessary
if not sub_field_dict.has_key(item_key):
if item_key not in sub_field_dict:
# Create property dict (key are field parameters)
sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key
......@@ -45,7 +45,7 @@ def getSubFieldDict():
# Those cached dictionnaries are later modified, we just reset the 'value'
# key to return clean dictionnaries.
sub_field_dict = getSubFieldDictCache()
for k in sub_field_dict.keys():
for k in list(sub_field_dict.keys()):
sub_field_dict[k]['value'] = None
return sub_field_dict
......@@ -57,7 +57,7 @@ for item_value in value_list:
item_split = item_value.split('/')
item_key = '/'.join(item_split[:split_depth])
if not sub_field_dict.has_key(item_key):
if item_key not in sub_field_dict:
# This can only happens if an accounting plan have been uninstalled
sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key
......@@ -72,4 +72,4 @@ for item_value in value_list:
sub_field_dict[item_key]['value'] = item_value
# Return the list of subfield configuration.
return sub_field_dict.values()
return list(sub_field_dict.values())
from builtins import str
from DateTime import DateTime
from erp5.component.module.DateUtils import addToDate
from Products.ERP5Type.Message import translateString
......
......@@ -4,6 +4,7 @@ The id of the line is used to filter the list, unless `omit_filter` is true.
If `mirror` is set to a true value, the list will be filtered for the mirror
node.
"""
from past.builtins import cmp
from Products.ERP5Type.Cache import CachingMethod
from AccessControl import getSecurityManager
......
......@@ -3,6 +3,7 @@
This script is indented to be used on custom listfields for accounting lines, and on reports.
If this script returns an empty list, it means that reports by project are disabled.
"""
from builtins import str
from Products.ERP5Type.Message import translateString
portal = context.getPortalObject()
......
......@@ -118,7 +118,7 @@ for brain in portal.portal_simulation.getMovementHistoryList(
if by_mirror_section_list_dict:
for row in portal_catalog(
select_list=['title'],
uid=by_mirror_section_list_dict.keys(),
uid=list(by_mirror_section_list_dict.keys()),
):
title = row.title
for line in by_mirror_section_list_dict[row.uid]:
......
from builtins import str
from Products.ERP5Type.Message import translateString
from Products.ERP5Form.Report import ReportSection
......@@ -30,7 +31,7 @@ previous_period = 0
for idx, period in enumerate(period_list):
if idx != 0:
previous_period = period_list[idx - 1]
selection_columns.append(('period_%s' % idx, unicode(translateString(
selection_columns.append(('period_%s' % idx, str(translateString(
'Period ${period_number} (from ${from} to ${to} days)',
mapping={'period_number': 1 + idx,
'from': previous_period,
......@@ -38,7 +39,7 @@ for idx, period in enumerate(period_list):
editable_columns.append(('period_%s' % idx, ''))
selection_columns.append(('period_%s' % (idx + 1),
unicode(translateString('Older (more than ${day_count} days)',
str(translateString('Older (more than ${day_count} days)',
mapping={'day_count': period_list[-1]}))))
editable_columns.append(('period_%s' % (idx + 1), ''))
......
......@@ -65,7 +65,7 @@ if grouping == 'grouping':
for line in grouped_line_list:
transaction_list[portal.restrictedTraverse(line).getParentValue()] = 1
for transaction in transaction_list.keys():
for transaction in list(transaction_list.keys()):
if transaction.getPortalType() == 'Balance Transfer Transaction':
transaction = transaction.getCausalityValue()
# Check if this document has a payment_state
......
......@@ -2,6 +2,7 @@
and redirects to the accounting transaction view which is easier to
use.
'''
from builtins import range
from Products.ERP5Type.Message import translateString
for _ in range(line_count):
......
......@@ -15,4 +15,4 @@ for accounting_transaction in [context] + context.getCausalityValueList(
if related_causality.getSimulationState() not in ('cancelled', 'deleted'):
accounting_transaction_set[related_causality] = 1
return accounting_transaction_set.keys()
return list(accounting_transaction_set.keys())
......@@ -72,7 +72,7 @@ for line in accounting_transaction_line_value_list:
path=line.getRelativeUrl()))
changed_line_list = []
for (node, section, mirror_section, _), line_info_list in lines_per_node.items():
for (node, section, mirror_section, _), line_info_list in list(lines_per_node.items()):
if node is None:
continue
total_price = sum([l['total_price'] for l in line_info_list])
......
......@@ -55,7 +55,7 @@ payable_type = account_type.liability.payable
line_to_adjust = None
asset_line = None
for line, account_type_list in account_type_dict.iteritems():
for line, account_type_list in account_type_dict.items():
if receivable_type in account_type_list or payable_type in account_type_list:
if line.getSourceSection() == context.getSourceSection() and \
line.getDestinationSection() == context.getDestinationSection():
......
# Get sections.
from builtins import str
source_section = None
source_section_value = context.getSourceSectionValue()
if source_section_value is not None \
......
......@@ -3,6 +3,8 @@ that a 0 balance are grouped.
In other words, check that all transactions that can be grouped are grouped.
"""
from __future__ import print_function
from builtins import str
from Products.CMFActivity.ActiveResult import ActiveResult
active_process = context.newActiveProcess()
......@@ -35,7 +37,7 @@ search_params = dict(
for brain in portal.portal_simulation.getInventoryList(**search_params):
if round(brain.total_price, precision) == 0:
print '%s has a 0 balance but some not grouped transactions.' % brain.mirror_section_relative_url
print('%s has a 0 balance but some not grouped transactions.' % brain.mirror_section_relative_url)
if fixit:
tr = brain.getObject().getParentValue()
grouped_line_list = tr.AccountingTransaction_guessGroupedLines()
......@@ -51,9 +53,9 @@ for brain in portal.portal_simulation.getInventoryList(**search_params):
portal_type=portal.getPortalAccountingMovementTypeList(),
grouping_reference=None,) if not line.getObject().getGroupingReference()])
if grouped_line_list:
print 'FIXED', grouped_line_list
print('FIXED', grouped_line_list)
else:
print 'NOT FIXED'
print('NOT FIXED')
active_result = ActiveResult(
summary=context.getTitle(),
......
from __future__ import print_function
from builtins import str
def recursiveDocumentList(obj):
ret = []
ret.append(obj.getPath())
......@@ -78,7 +80,7 @@ for property_dict in object_list:
gap = str(gap)
if gap:
gap = gap.replace('CLASSE ', '')
print '+ %s - %s - %s' % (gap or '', title or '', description or '')
print('+ %s - %s - %s' % (gap or '', title or '', description or ''))
path = root
b = ''
for a in gap:
......@@ -96,7 +98,7 @@ for path in existing_path_list:
description = document.getDescription() or ''
gap = document.getId() or ''
title = document.getTitle() or ''
print '- %s - %s - %s' % (gap or '', title or '', description or '')
print('- %s - %s - %s' % (gap or '', title or '', description or ''))
document.getParentValue().deleteContent(document.getId())
return printed
......@@ -77,7 +77,7 @@ bank = related_payment.newContent(
bank_quantity = 0
for (line_node, line_mirror_section), quantity in\
total_payable_price_details.items():
list(total_payable_price_details.items()):
if line_mirror_section == mirror_section:
bank_quantity += quantity
if is_source:
......
......@@ -181,7 +181,7 @@ if detailed:
else:
if mirror_section_relative_url:
total_amount = 0
for (node, mirror_section), amount in total_payable_price_per_node_section.items(): # pylint: disable=unused-variable
for (node, mirror_section), amount in list(total_payable_price_per_node_section.items()): # pylint: disable=unused-variable
if mirror_section == mirror_section_relative_url:
total_amount += amount
return total_amount
......
......@@ -30,7 +30,11 @@
"""
from StringIO import StringIO
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from io import StringIO
import lxml
from DateTime import DateTime
......
from builtins import next
from Products.ERP5Type.Core.Workflow import ValidationFailed
from Products.ERP5Type.Message import translateString
......
from __future__ import print_function
category_list = context.portal_catalog(path="%portal_categories/gap2/br%")
for cat in category_list:
......@@ -7,7 +8,7 @@ for cat in category_list:
cat.getObject().setId(newid)
except:
pass
print newid
print(newid)
print 'Categories Renamed'
print('Categories Renamed')
return printed
from __future__ import print_function
category_list = context.portal_catalog(path="%portal_categories/gap2/br%")
for cat in category_list:
......@@ -7,7 +8,7 @@ for cat in category_list:
cat.getObject().setId(newid)
except:
pass
print newid
print(newid)
print 'Categories Renamed'
print('Categories Renamed')
return printed
from cStringIO import StringIO
from future import standard_library
standard_library.install_aliases()
from builtins import str
from io import StringIO
import zipfile
from Products.ERP5Type.Message import translateString
......@@ -25,7 +28,7 @@ attachment_list = (
portal.ERP5Site_notifyReportComplete(
user_name=user_name,
subject=unicode(translateString('French Accounting Transaction File')),
subject=str(translateString('French Accounting Transaction File')),
message='',
attachment_list=attachment_list)
......
""" display value in the cell according to (french) fiscality rules """
from builtins import str
from builtins import range
context.log(cell_name, cell_value)
if same_type(cell_value, 0) or same_type(cell_value, 0.0) :
......@@ -8,7 +10,7 @@ if same_type(cell_value, 0) or same_type(cell_value, 0.0) :
negative = number < 0
amount = str(abs(number))
indexes = range(len(amount))
indexes = list(range(len(amount)))
indexes.reverse()
string = ''
count = 0
......
......@@ -2,6 +2,7 @@
Translates a short account number (eg 280) to a full gap category url (eg gap/2/28/280).
"""
from builtins import range
number = gap_id.strip()
gap_url = gap_base
......
......@@ -30,11 +30,13 @@
"""Test suite for erp5_accounting_l10n_fr
"""
from future import standard_library
standard_library.install_aliases()
import unittest
import zipfile
import email
import os.path
from cStringIO import StringIO
from io import StringIO
from DateTime import DateTime
from lxml import etree
......
#context = self
# vim: ts=2 sw=2 et
from builtins import chr
STRIP_IF_EMPTY = True
request = context.REQUEST
result = []
......@@ -17,7 +18,7 @@ def getAccountsForGap(gap_id):
return GAP.restrictedTraverse(gap_id).getGapRelatedValueList(portal_type='Account')
def getUniqueGapList(accounts_list):
return dict([ (x.getGap(),True) for x in accounts_list]).keys()
return list(dict([ (x.getGap(),True) for x in accounts_list]).keys())
def getCell(row_number=1):
return '%s%d'%(ooo_struct['rows'][row_number-1], ooo_struct['line'])
......
......@@ -16,6 +16,7 @@
"""
from builtins import str
def shortAccountNameToFullGapCategory(accountName) :
""" translates a short account name (eg asset/current_assets) to a full gap category url
(eg gap/in/sme1/asset/current_assets) """
......
......@@ -27,7 +27,8 @@
#
##############################################################################
class PolishAddressDetails:
from builtins import object
class PolishAddressDetails(object):
"""
Detailed address information needed to proper fill of tax reports
"""
......
......@@ -19,6 +19,8 @@ return a list of dictionnaries like that :
}
"""
from past.builtins import cmp
from builtins import str
request = context.REQUEST
at_date = request['at_date']
transaction_section_category = request['transaction_section_category']
......
from builtins import object
getInventory=context.FiscalReportCell_doGetInventory
# pobiera stan kont po stronie credit
......@@ -9,7 +10,7 @@ getDebit=context.getDebit
# pobiera różnicę dla kont po obu stronach
getBalance=context.getBalance
class Bil:pass
class Bil(object):pass
bil=Bil()
bil.AI1=getBalance(('022',))+getBalance(('072',))
......
from __future__ import print_function
from builtins import str
from builtins import range
from builtins import object
debug=True
request=context.REQUEST
from Products.ERP5Type.Message import Message
# empty class for report data
class Dane:pass
class Dane(object):pass
# only one report implemented at this time - monthly VAT
mess=Message(domain='ui',message='VAT-7 is a monthly report')
......@@ -48,7 +52,7 @@ dane.p59=dane.p55-dane.p56
if debug:
for f in range(20,60):
n='p'+str(f)
print n,getattr(dane,n)
print(n,getattr(dane,n))
return printed
return container[report].index_html(REQUEST=context.REQUEST, RESPONSE=context.REQUEST.RESPONSE,dane=dane)
from builtins import object
getInventory=context.FiscalReportCell_doGetInventory
# pobiera stan kont po stronie credit
......@@ -9,7 +10,7 @@ getDebit=context.getDebit
# pobiera różnicę dla kont po obu stronach
getBalance=context.getBalance
class PL:pass
class PL(object):pass
pl=PL()
pl.AI=-getBalance(('70',))
......
from builtins import range
gap_root = kw.get('gap_root', context.getPortalObject().portal_preferences.getPreferredAccountingTransactionGap())
parts=[]
......
......@@ -2,10 +2,11 @@
Deployment script for crating initial accounts upon gap/pl/default structure
Warning: Before using this script as zope, edit account_workflow and give Manager permission to validate_action
"""
from __future__ import print_function
#This script will REMOVE any existing accounts!!!
#comment following if you are sure
print 'Nothing done!'
print('Nothing done!')
return printed
......@@ -22,7 +23,7 @@ for category in gap_root.getCategoryMemberValueList():
acc = account_module.newContent(title='%s %s' % (category.getId(),category.getTitle()),\
gap_value = category)
acc.validate()
print 'acc created'
print('acc created')
return printed
......@@ -4,6 +4,7 @@ Creates gap structure under gap/pl/default.
The definition text is a raw text representation of a wiki page
with accountants-approved gap structure
"""
from __future__ import print_function
gap_text = \
"""* [0] Aktywa trwałe
......@@ -251,7 +252,7 @@ for line in gap_text.splitlines():
cpath += n
path.append(cpath)
parent = gap.restrictedTraverse('/'.join(path))
print 'Added to ',parent
print('Added to ',parent)
parent.newContent(id=num, title=descr)
......
from builtins import range
from DateTime import DateTime
from Products.ZSQLCatalog.SQLCatalog import SimpleQuery
......@@ -6,7 +7,7 @@ section_title = 'My Organisation'
portal = context.getPortalObject()
accounting_module = portal.accounting_module
year = 2005
default_date = DateTime(year, 01, 01)
default_date = DateTime(year, 0o1, 0o1)
business_process = portal.portal_catalog.getResultValue(
reference=('default_erp5_business_process', # erp5_configurator
......
from builtins import range
from DateTime import DateTime
from Products.ZSQLCatalog.SQLCatalog import SimpleQuery
......@@ -98,8 +99,8 @@ for month in range(1, month_count + 1):
source_payment=getBankAccountByTitle('My default bank account'),
destination_section=getOrganisationByTitle(client_title),
created_by_builder=1,
start_date=DateTime(year, month, day, 01, 01) + 10,
stop_date=DateTime(year, month, day, 01, 01) + 10,
start_date=DateTime(year, month, day, 0o1, 0o1) + 10,
stop_date=DateTime(year, month, day, 0o1, 0o1) + 10,
causality_value=tr,
resource=euro_resource,
)
......
# params
from builtins import range
section_title = 'My Organisation'
business_process = 'business_process_module/erp5_default_business_process'
portal = context.getPortalObject()
......
from builtins import str
preference = context.portal_preferences.accounting_zuite_preference
preference.setPreferredAccountingTransactionSectionCategory(None)
preference.setPreferredSectionCategory(None)
......
from builtins import str
preference = context.portal_preferences.accounting_zuite_preference
preference.setPreferredAccountingTransactionSectionCategory('group/demo_group')
preference.setPreferredSectionCategory('group/demo_group')
......
......@@ -26,6 +26,7 @@
#
##############################################################################
from builtins import str
import unittest
from DateTime import DateTime
......
......@@ -89,7 +89,7 @@ def MessageCatalog_getMessageDict(self):
Get Localizer's MessageCatalog instance messages.
"""
d = {}
for k,v in self._messages.iteritems():
for k,v in self._messages.items():
d[k] = v
return d
......@@ -99,8 +99,8 @@ def MessageCatalog_getNotTranslatedMessageDict(self):
"""
not_translated_message_dict = {}
messages = MessageCatalog_getMessageDict(self)
for k, v in messages.iteritems():
if not [x for x in v.values() if x]:
for k, v in messages.items():
if not [x for x in list(v.values()) if x]:
not_translated_message_dict[k] = v
return not_translated_message_dict
......@@ -109,10 +109,10 @@ def MessageCatalog_deleteNotTranslatedMessageDict(self):
Delete from Localizer's MessageCatalog instance messages that are NOT translated.
"""
not_translated_message_dict = MessageCatalog_getNotTranslatedMessageDict(self)
for k,_ in not_translated_message_dict.iteritems():
for k,_ in not_translated_message_dict.items():
# delete message from dict
del(self._messages[k])
return len(not_translated_message_dict.keys())
return len(list(not_translated_message_dict.keys()))
def MessageCatalog_cleanUpMessageDict(self):
"""
......@@ -121,8 +121,8 @@ def MessageCatalog_cleanUpMessageDict(self):
MessageCatalog instance messages.
"""
count = 0
for k,v in self._messages.items():
for lang, translation in v.items():
for k,v in list(self._messages.items()):
for lang, translation in list(v.items()):
if len(translation) == 0 or translation == k:
del self._messages[k][lang]
if len(v) == 0:
......
print '<html><head><meta http-equiv="refresh" content="%s"></head><body>' % refresh_interval
from __future__ import print_function
print('<html><head><meta http-equiv="refresh" content="%s"></head><body>' % refresh_interval)
for table in 'message', 'message_queue':
q = """SELECT count(*) AS %(table)s, method_id, processing_node AS node, min(priority) AS min_pri, max(priority) AS max_pri
FROM %(table)s GROUP BY method_id, processing_node ORDER BY node""" % dict(table=table)
print "<table border=\"\" style=\"font-size:XX-small;\"><tbody> <tr><th>%s</th> <th>method_id</th> <th>node</th> <th>min_pri</th> <th>max_pri</th> </tr>" % table
print("<table border=\"\" style=\"font-size:XX-small;\"><tbody> <tr><th>%s</th> <th>method_id</th> <th>node</th> <th>min_pri</th> <th>max_pri</th> </tr>" % table)
for row in context.cmf_activity_sql_connection.manage_test(q):
print '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td</tr>' % (row[table], row['method_id'], row['node'], row['min_pri'], row['max_pri'])
print '</tbody> </table> <br/>'
print('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td</tr>' % (row[table], row['method_id'], row['node'], row['min_pri'], row['max_pri']))
print('</tbody> </table> <br/>')
return printed
......@@ -6,8 +6,8 @@ alarm_warn_ratio = 0.25
localizer = context.Localizer
for message_catalog in localizer.objectValues('MessageCatalog'):
all_messages = len(message_catalog.MessageCatalog_getMessageDict().keys())
not_translated = len(message_catalog.MessageCatalog_getNotTranslatedMessageDict().keys())
all_messages = len(list(message_catalog.MessageCatalog_getMessageDict().keys()))
not_translated = len(list(message_catalog.MessageCatalog_getNotTranslatedMessageDict().keys()))
enable_warning = not_translated > all_messages * alarm_warn_ratio
if enable_warning:
# we have more than allowed number of untranslated messages,
......
from functools import reduce
portal = context.getPortalObject()
security_uid_field_list = [x + ("_" if x != "" else "") + "security_uid" for x in portal.portal_catalog.getSQLCatalog().getSQLCatalogSecurityUidGroupsColumnsDict().keys()]
security_uid_field_list = [x + ("_" if x != "" else "") + "security_uid" for x in list(portal.portal_catalog.getSQLCatalog().getSQLCatalogSecurityUidGroupsColumnsDict().keys())]
security_uid_set_list = []
for security_uid_field in security_uid_field_list:
security_uid_set_list.append({getattr(x, security_uid_field) for x in context.z_get_referenced_security_uid_set_for(security_uid_field=security_uid_field)})
......
from __future__ import print_function
portal = context.getPortalObject()
req = portal.erp5_sql_connection.manage_test
security_uid_field_list = [x + ("_" if x != "" else "") + "security_uid" for x in portal.portal_catalog.getSQLCatalog().getSQLCatalogSecurityUidGroupsColumnsDict().keys()]
security_uid_field_list = [x + ("_" if x != "" else "") + "security_uid" for x in list(portal.portal_catalog.getSQLCatalog().getSQLCatalogSecurityUidGroupsColumnsDict().keys())]
referenced_uid_set = set()
all_uid_set = set()
for security_uid_field in security_uid_field_list:
......@@ -10,14 +11,14 @@ for security_uid_field in security_uid_field_list:
print(">> useless uids in roles_and_users table <<\n")
if len(referenced_uid_set) > 0:
for row in req("select * from roles_and_users where uid not in %s" + tuple(referenced_uid_set)):
print row.uid, row.local_roles_group_id, row.allowedRolesAndUsers
print(row.uid, row.local_roles_group_id, row.allowedRolesAndUsers)
print("\n>> uids that should be in roles_and_users table <<\n")
all_uid_set = {row.uid for row in req("select uid from roles_and_users")}
for security_uid_field in security_uid_field_list:
for row in req("select %s, relative_url from catalog where %s not in %s" % (security_uid_field, security_uid_field, tuple(all_uid_set))):
print security_uid_field, getattr(row, security_uid_field, None), row.relative_url
print(security_uid_field, getattr(row, security_uid_field, None), row.relative_url)
print("\n>> END <<")
return printed
from __future__ import print_function
from AccessControl import getSecurityManager
from zExceptions import Unauthorized
from pprint import pformat
......@@ -6,18 +7,18 @@ u = getSecurityManager().getUser()
user_value = u.getUserValue()
if user_value is None:
print 'User ID:', u.getId()
print('User ID:', u.getId())
else:
print 'User ID:', u.getId(), user_value.getPath()
print('User ID:', u.getId(), user_value.getPath())
login_value = u.getLoginValue()
if login_value is None:
print 'Login:', u.getUserName()
print('Login:', u.getUserName())
else:
print 'Login:', u.getUserName(), login_value.getPath()
print 'Is owner:', u.allowed(context,('Owner',))
print 'User roles:', u.getRoles()
print 'User roles in context:', u.getRolesInContext(context)
print 'Permissions:'
print('Login:', u.getUserName(), login_value.getPath())
print('Is owner:', u.allowed(context,('Owner',)))
print('User roles:', u.getRoles())
print('User roles in context:', u.getRolesInContext(context))
print('Permissions:')
for permission in [
'Access contents information',
'Add portal content',
......@@ -26,25 +27,25 @@ for permission in [
'View',
'Manage portal',
]:
print " ", permission, u.has_permission(permission, context)
print(" ", permission, u.has_permission(permission, context))
print
print()
try:
print "User groups:\n", pformat(u.getGroups())
print("User groups:\n", pformat(u.getGroups()))
except AttributeError:
print 'no getGroups'
print('no getGroups')
print
print 'Local roles on document:\n', pformat(context.get_local_roles())
print()
print('Local roles on document:\n', pformat(context.get_local_roles()))
print '''
print('''
----------------
Security mapping
----------------'''
----------------''')
if u.getId() is not None:
try:
print context.Base_viewSecurityMappingAsUser(u.getId())
print(context.Base_viewSecurityMappingAsUser(u.getId()))
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
from __future__ import print_function
group_id_list_generator = getattr(context, 'ERP5Type_asSecurityGroupId')
security_category_dict = {}
......@@ -16,12 +17,12 @@ for method_id, base_category_list in getSecurityCategoryMapping():
security_category_dict.setdefault(tuple(base_category_list), []).extend(
getattr(context, method_id)(base_category_list, login, context, ''))
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():
print 'base_category_list:', base_category_list
for base_category_list, category_value_list in list(security_category_dict.items()):
print('base_category_list:', base_category_list)
for category_dict in category_value_list:
print '-> category_dict:', category_dict
print '-->', group_id_list_generator(category_order=base_category_list,
**category_dict)
print('-> category_dict:', category_dict)
print('-->', group_id_list_generator(category_order=base_category_list,
**category_dict))
return printed
......@@ -14,6 +14,9 @@
Extra parameters passed to catalog
retry
"""
from builtins import map
from builtins import str
from builtins import range
from DateTime import DateTime
from Products.CMFActivity.ActiveResult import ActiveResult
active_result = ActiveResult()
......@@ -54,7 +57,7 @@ if catalog_uid_list is None:
'tag': tag,
'fixit': fixit,
}
for _ in xrange(activity_count):
for _ in range(activity_count):
if len(catalog_uid_list) == 0:
result_list.append('No more uids to check, stop spawning activities.')
break
......@@ -142,7 +145,7 @@ else:
reference_dict = getattr(context, property_override_method_id)(instance=actual_object)
do_reindex = False
for attribute_id in attribute_id_list:
if not reference_dict.has_key(attribute_id):
if attribute_id not in reference_dict:
reference_value = actual_object.getProperty(attribute_id)
else:
reference_value = reference_dict[attribute_id]
......@@ -152,8 +155,8 @@ else:
# stocks (1 line with a positive value and another with a negative one).
is_reference_value_list = same_type(reference_value, ()) \
or same_type(reference_value, [])
if (catalog_value not in map(normalize, not is_reference_value_list
and (reference_value,) or reference_value)):
if (catalog_value not in list(map(normalize, not is_reference_value_list
and (reference_value,) or reference_value))):
if error('%s.%s %s %r, but catalog contains %r'
% (actual_object.getRelativeUrl(), attribute_id,
is_reference_value_list and 'has candidate list' or '=',
......
from __future__ import print_function
def checkTopLevel():
portal = context.getPortalObject()
for o in portal.objectValues():
......@@ -20,7 +21,7 @@ if context.getPortalType() == 'Alarm':
else:
active_process = context.portal_activities.newActiveProcess().getPath()
ERP5Site_checkDataWithScript = context.portal_activities.ERP5Site_checkDataWithScript
print 'Results will be saved to %s' % active_process
print('Results will be saved to %s' % active_process)
checkTopLevel()
ERP5Site_checkDataWithScript(
......
from builtins import str
alarm_tool = context.getPortalObject().portal_alarms
periodicity_list = [
'periodicity_day_frequency',
......
from __future__ import print_function
for builder in sorted(context.getPortalObject().portal_deliveries.contentValues(),
key=lambda x:x.getTitle()):
print builder.getId()
print " Title: %s" % (builder.getTitle())
print " Simulation Select Method: %s" % (builder.getSimulationSelectMethodId())
print " Delivery Select Method: %s" % (builder.getDeliverySelectMethodId())
print " After Generation Script: %s" % (builder.getDeliveryAfterGenerationScriptId())
print
print(builder.getId())
print(" Title: %s" % (builder.getTitle()))
print(" Simulation Select Method: %s" % (builder.getSimulationSelectMethodId()))
print(" Delivery Select Method: %s" % (builder.getDeliverySelectMethodId()))
print(" After Generation Script: %s" % (builder.getDeliveryAfterGenerationScriptId()))
print()
for mg in sorted(builder.contentValues(), key=lambda x:x.getTitle()):
print builder.getId()
print " ", "\n ".join([x for x in (
print(builder.getId())
print(" ", "\n ".join([x for x in (
"Id: %s" % mg.getId(),
"Title: %s" % mg.getTitle(),
"Type: %s" % mg.getPortalType(),
......@@ -17,7 +18,7 @@ for builder in sorted(context.getPortalObject().portal_deliveries.contentValues(
"Tested Properties: %r" % mg.getTestedPropertyList(),
"Update Always: %r" % mg.isUpdateAlways(),
)])
print
)]))
print()
return printed
from __future__ import print_function
if ignore_business_template_list is None:
ignore_business_template_list = []
for business_template in sorted(context.getPortalObject().portal_templates.contentValues(portal_type='Business Template'),
key=lambda x:x.getTitle()):
if business_template.getInstallationState() == 'installed' and \
business_template.getTitle() not in ignore_business_template_list:
print business_template.getTitle()
print(business_template.getTitle())
return printed
from __future__ import print_function
for builder in sorted(context.getPortalObject().portal_orders.contentValues(),
key=lambda x:x.getTitle()):
print builder.getId()
print " Title: %s" % (builder.getTitle())
print " Simulation Select Method: %s" % (builder.getSimulationSelectMethodId())
print " Delivery Select Method: %s" % (builder.getDeliverySelectMethodId())
print " After Generation Script: %s" % (builder.getDeliveryAfterGenerationScriptId())
print " Delivery Module Before Building Script: %s" % (builder.getDeliveryModuleBeforeBuildingScriptId())
print
print(builder.getId())
print(" Title: %s" % (builder.getTitle()))
print(" Simulation Select Method: %s" % (builder.getSimulationSelectMethodId()))
print(" Delivery Select Method: %s" % (builder.getDeliverySelectMethodId()))
print(" After Generation Script: %s" % (builder.getDeliveryAfterGenerationScriptId()))
print(" Delivery Module Before Building Script: %s" % (builder.getDeliveryModuleBeforeBuildingScriptId()))
print()
for mg in sorted(builder.contentValues(), key=lambda x:x.getTitle()):
print builder.getId()
print " ", "\n ".join([x for x in (
print(builder.getId())
print(" ", "\n ".join([x for x in (
"Id: %s" % mg.getId(),
"Title: %s" % mg.getTitle(),
"Type: %s" % mg.getPortalType(),
......@@ -18,7 +19,7 @@ for builder in sorted(context.getPortalObject().portal_orders.contentValues(),
"Tested Properties: %r" % mg.getTestedPropertyList(),
"Update Always: %r" % mg.isUpdateAlways(),
)])
print
)]))
print()
return printed
from __future__ import print_function
from builtins import str
import hashlib
portal = context.getPortalObject()
......@@ -19,9 +21,9 @@ def getSkinHash(skin, skin_container):
elif skin.meta_type in ('ERP5 Form', ):
try:
content = skin.formXML()
if isinstance(content, unicode):
if isinstance(content, str):
content = content.encode('utf8', 'repr')
except AttributeError, e:
except AttributeError as e:
# This can happen with dead proxy fields.
content = "broken form %s" % e
content = 'ignore'
......@@ -37,12 +39,12 @@ for skin_folder in portal.portal_skins.objectValues('Folder'):
for skin in skin_folder.objectValues():
if skin.getId() in ignore_skin_list:
continue
print getSkinHash(skin, skin_folder)
print(getSkinHash(skin, skin_folder))
if include_workflow_scripts:
for workflow in portal.portal_workflow.objectValues():
for skin in workflow.scripts.objectValues():
print getSkinHash(skin, workflow)
print(getSkinHash(skin, workflow))
container.REQUEST.RESPONSE.setHeader('content-type', 'text/plain')
return '\n'.join(sorted(printed.splitlines()))
from __future__ import print_function
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()):
print ti.getId()
print " ", "\n ".join([x for x in (
print(ti.getId())
print(" ", "\n ".join([x for x in (
"Reference: %s" % ai.getReference(),
"Title: %s" % ai.getTitle(),
"Action: %s" % ai.getActionText(),
......@@ -9,7 +10,7 @@ for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lam
"Permission: %s" % ai.getActionPermission(),
"Action Type: %s" % ai.getActionType(),
"Visible: %s" % ai.getVisible(),
"Index: %s" % ai.getFloatIndex())])
print
"Index: %s" % ai.getFloatIndex())]))
print()
return printed
from __future__ import print_function
for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lambda x:x.getId()):
print ti.getId()
print " ", "\n ".join([x for x in (
print(ti.getId())
print(" ", "\n ".join([x for x in (
"Short Title: %s" % ti.getShortTitle(),
"Class: %s" % ti.getTypeClass(),
"Init Script: %s" % ti.getTypeInitScriptId(),
......@@ -12,7 +13,7 @@ for ti in sorted(context.getPortalObject().portal_types.contentValues(), key=lam
"Hidden Content Types: %r" % sorted(ti.getTypeHiddenContentTypeList()),
"Searchable Property: %r" % sorted(ti.getSearchableTextPropertyIdList()),
"Searchable Method: %r" % sorted(ti.getSearchableTextMethodIdList()),
)])
print
)]))
print()
return printed
from __future__ import print_function
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())):
print ti.getId()
print " ", "\n ".join([x for x in (
print(ti.getId())
print(" ", "\n ".join([x for x in (
"Title: %s" % ri.getTitle(),
"Roles: %r" % ri.getRoleNameList(),
"Condition: %s" % ri.getConditionText(),
"Local Roles Group Id: %s" % ri.getLocalRoleGroupId(),
"Base Categories: %r" % ri.getRoleBaseCategoryList(),
"Base Category Script: %s" % ri.getRoleBaseCategoryScriptId(),
"Categories: %r" % ri.getRoleCategoryList() )])
print
"Categories: %r" % ri.getRoleCategoryList() )]))
print()
return printed
from __future__ import print_function
if ignore_property_sheet_list is None:
ignore_property_sheet_list = []
......@@ -6,7 +7,7 @@ for ps in sorted(context.getPortalObject().portal_property_sheets.contentValues(
ps_id = ps.getId()
if ps_id in ignore_property_sheet_list:
continue
print ps.getId()
print(ps.getId())
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']
if pd.getPortalType() == 'Standard Property':
......@@ -29,10 +30,10 @@ for ps in sorted(context.getPortalObject().portal_property_sheets.contentValues(
elif pd.getPortalType().endswith('Constraint'):
info_list += [] + [p for p in pd.propertyIds() if p.startswith('message')]
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
print(" ", "\n ".join(['%s: %s' % (prop, pd.getProperty(prop)) for prop in sorted(info_list)]))
print()
return printed
from __future__ import print_function
for rule in sorted(context.getPortalObject().portal_rules.contentValues(),
key=lambda x:x.getTitle()):
if rule.getValidationState() != 'validated':
continue
print rule.getId()
print " Title: %s" % (rule.getTitle())
print " Trade Phases: %r" % (rule.getTradePhaseList())
print " Test Method Id: %s" % (rule.getTestMethodId())
print " Membership Criteria: %r" % (rule.getMembershipCriterionBaseCategoryList())
print " Membership Criterion Category: %r" % (rule.getMembershipCriterionCategoryList())
print
print(rule.getId())
print(" Title: %s" % (rule.getTitle()))
print(" Trade Phases: %r" % (rule.getTradePhaseList()))
print(" Test Method Id: %s" % (rule.getTestMethodId()))
print(" Membership Criteria: %r" % (rule.getMembershipCriterionBaseCategoryList()))
print(" Membership Criterion Category: %r" % (rule.getMembershipCriterionCategoryList()))
print()
for tester in sorted(rule.contentValues(), key=lambda x:x.getTitle()):
print rule.getId()
print " ", "\n ".join([x for x in (
print(rule.getId())
print(" ", "\n ".join([x for x in (
"Id: %s" % tester.getId(),
"Title: %s" % tester.getTitle(),
"Type: %s" % tester.getPortalType(),
......@@ -25,7 +26,7 @@ for rule in sorted(context.getPortalObject().portal_rules.contentValues(),
(tester.getMembershipCriterionBaseCategoryList()),
"Membership Criterion Category: %r" %
(tester.getMembershipCriterionCategoryList()),
)])
print
)]))
print()
return printed
from __future__ import print_function
# This method outputs the skin properties in the format that you can
# easily get diff like the following:
# ---
......@@ -13,5 +14,5 @@ for name, layers in skin_tool.getSkinPaths():
if ignore_skin_folder_list is not None and\
layer in ignore_skin_folder_list:
continue
print '%s,%s' % (name, layer)
print('%s,%s' % (name, layer))
return printed
......@@ -20,7 +20,9 @@ zipfile (bool)
When true, the result is a zip file containing profiling result along with the python code (and, when not possible, the disassembled bytecode) of all files which appear in the profiling result.
When false, the result is a bare profiling result (cachegrind file format).
"""
from StringIO import StringIO
from future import standard_library
standard_library.install_aliases()
from io import StringIO
portal = context.getPortalObject()
if statistic:
profiler, retriever = portal.ERP5Site_getStatisticalProfilerAndThread(single=True)
......
......@@ -17,8 +17,10 @@ zipfile (bool)
When true, the result is a zip file containing profiling result along with the python code (and, when not possible, the disassembled bytecode) of all files which appear in the profiling result.
When false, the result is a bare profiling result (cachegrind file format).
"""
from future import standard_library
standard_library.install_aliases()
from time import sleep
from StringIO import StringIO
from io import StringIO
profiler, thread = context.ERP5Site_getStatisticalProfilerAndThread(single=False)
with thread:
sleep(duration)
......
from builtins import zip
from Products.CMFActivity.ActiveResult import ActiveResult
portal = context.getPortalObject()
......
"""Utility script listing all relation fields that are using relation_setter_id feature.
This helps migrating them after r33837
"""
from __future__ import print_function
multi_relation_field_meta_type_list = ['RelationStringField',
'MultiRelationStringField']
for field_path, field in context.ZopeFind(
......@@ -13,6 +14,6 @@ for field_path, field in context.ZopeFind(
relation_setter_id = field.get_value('relation_setter_id')
if relation_setter_id:
print field_path, relation_setter_id
print(field_path, relation_setter_id)
return printed
from __future__ import print_function
portal_templates = context.getPortalObject().portal_templates
delete_list = []
bt_list = portal_templates.objectValues()
......@@ -16,6 +17,6 @@ for bt in bt_list:
delete_list.append(bt_id)
break
print 'Deleted id list:%r' % delete_list
print('Deleted id list:%r' % delete_list)
portal_templates.manage_delObjects(delete_list)
return printed
......@@ -27,6 +27,7 @@
#
##############################################################################
from builtins import str
import unittest
import time
from Products.ERP5.tests.testInventoryAPI import InventoryAPITestCase
......
......@@ -22,14 +22,14 @@ if form_id is not None:
# button itself
try:
form.validate_all_to_request(request)
except FormValidationError, validation_errors:
except FormValidationError as validation_errors:
# Pack errors into the request
field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors)
# Make sure editors are pushed back as values into the REQUEST object
for f in form.get_fields():
field_id = f.id
if request.has_key(field_id):
if field_id in request:
value = request.get(field_id)
if callable(value):
value(request)
......
......@@ -26,7 +26,7 @@ session = portal_sessions[session_id]
# some cleanup could be required if the shopping cart
# comes from a previous user with same session
if shopping_cart_id in session.keys():
if shopping_cart_id in list(session.keys()):
shopping_cart = session[shopping_cart_id]
if shopping_cart.getStartDate() is None:
shopping_cart.edit(start_date=DateTime())
......@@ -35,7 +35,7 @@ if shopping_cart_id in session.keys():
# session = portal_sessions[session_id]
# create shopping cart
if not shopping_cart_id in session.keys():
if not shopping_cart_id in list(session.keys()):
shopping_cart = context.sale_order_module.newContent(portal_type="Sale Order",
temp_object=True,
id=shopping_cart_id,
......
......@@ -8,6 +8,7 @@
Script can optionally include currency.
"""
from builtins import str
web_site = context.getWebSiteValue()
total = 0.0
sale_order = context.SaleOrder_getShoppingCart()
......
from urlparse import urlparse
from urlparse import parse_qsl
from future import standard_library
standard_library.install_aliases()
from urllib.parse import urlparse
from urllib.parse import parse_qsl
context.REQUEST.RESPONSE.setCookie("loyalty_reward", "disable", path='/')
......
from urlparse import urlparse
from urlparse import parse_qsl
from future import standard_library
standard_library.install_aliases()
from urllib.parse import urlparse
from urllib.parse import parse_qsl
context.REQUEST.RESPONSE.setCookie("loyalty_reward", "enable", path='/')
......
......@@ -3,7 +3,7 @@
"""
website = context.getWebSiteValue()
REQUEST = context.REQUEST
if REQUEST.has_key('portal_skin'):
if 'portal_skin' in REQUEST:
context.portal_skins.clearSkinCookie()
REQUEST.RESPONSE.expireCookie('__ac', path='/')
REQUEST.RESPONSE.expireCookie('__ac_facebook_hash', path='/')
......
......@@ -10,7 +10,7 @@ for item in item_list:
item_key = '/'.join(item_split[:split_depth])
base_category = item_split[0]
# Create a new subfield if necessary
if not sub_field_dict.has_key(item_key):
if item_key not in sub_field_dict:
# Create property dict (key are field parameters)
sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key
......@@ -28,4 +28,4 @@ for item in item_list:
# Return the list of subfield configuration.
return sub_field_dict.values()
return list(sub_field_dict.values())
# an external script is need to extract content from body: REQUEST.get('BODY')
from builtins import str
mode = mode or context.REQUEST.form.get("mode", "get")
text_content = text_content or context.REQUEST.form.get("text_content", "")
document_id = document_id or context.REQUEST.form.get("document_id", "")
......@@ -34,7 +35,7 @@ def _byteify(data, ignore_dicts = False):
if isinstance(data, dict) and not ignore_dicts:
return {
_byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)
for key, value in data.items() # changed to .items() for python 2.7/3
for key, value in list(data.items()) # changed to .items() for python 2.7/3
}
# python 3 compatible duck-typing
......@@ -60,7 +61,7 @@ mode_dict = {
}
if mode not in mode_dict:
return "Used Mode is not defined in the mode list %s" % mode_dict.keys()
return "Used Mode is not defined in the mode list %s" % list(mode_dict.keys())
# Check JSON Form
try:
......@@ -96,7 +97,7 @@ erp5_action_dict = portal.Base_filterDuplicateActions(
portal.portal_actions.listFilteredActionsFor(document))
# Try to find an action matching the text_content
for erp5_action_key in erp5_action_dict.keys():
for erp5_action_key in list(erp5_action_dict.keys()):
for view_action in erp5_action_dict[erp5_action_key]:
if (action_type == view_action['category']):
try:
......@@ -112,7 +113,7 @@ for erp5_action_key in erp5_action_dict.keys():
if mode != "allDocs":
return result
result_list += result
except ValueError, e:
except ValueError as e:
try:
error_dict.update(json.loads(str(e)))
except ValueError:
......
from builtins import str
import json
context.log(error_message)
if not text_content:
......
......@@ -77,7 +77,7 @@ class TestjIOApiStyle(ERP5TypeTestCase):
"alldocs": "object_json_api_all_docs",
"get": "object_json_api_get",
}
for key, action_type in self.action_type_dict.iteritems():
for key, action_type in self.action_type_dict.items():
self.updateCreateActionType(action_type)
self.api_web_section.setProperty(
"configuration_%s_action_type" % key,
......
......@@ -8,11 +8,10 @@ for base_category in selected_base_category_list:
if matrixbox==1:
# XXX matrixbox is right_display (not as listfield)
# => invert display and value in item
cell_range.append(map(lambda x: (x[1], x[0]),
context.getVariationCategoryItemList(
cell_range.append([(x[1], x[0]) for x in context.getVariationCategoryItemList(
base_category_list=[base_category,],
display_base_category=display_base_category,
sort_id='id')))
sort_id='id')])
else:
cell_range.append(
context.getVariationCategoryList(
......
# erp5_apparel/ApparelFabricItem_fastInput
from builtins import filter
from builtins import str
from Products.Formulator.Errors import ValidationError, FormValidationError
request=context.REQUEST
......@@ -31,7 +33,7 @@ try:
else : # we create a master_item
my_container = context.getPortalObject().apparel_fabric_item_module
# get only lines with a piece_number and a quantity
input_list = filter( (lambda x: (x[new_quantity_name] != '') and (x[new_quantity_name] > 0) ) ,listbox )
input_list = list(filter( (lambda x: (x[new_quantity_name] != '') and (x[new_quantity_name] > 0) ) ,listbox ))
error_message = ''
for input in input_list:
title = input[new_source_reference_name]
......@@ -86,7 +88,7 @@ try:
bath = ''
for item in created_item_list:
bath = str(item.grouping_reference)
if bath_dict.has_key(bath):
if bath in bath_dict:
bath_dict[str(bath)].extend([item])
else:
bath_dict[str(bath)] = [item]
......@@ -98,7 +100,7 @@ try:
resource = context.getResource()
variation_category_list = context.getVariationCategoryList()
bath_object_list = {}
for bath_title in bath_dict.keys():
for bath_title in list(bath_dict.keys()):
if bath_title != "None":
bath_list = context.portal_catalog(portal_type=apparel_bath_portal_type, resource_uid=resource_uid, title=bath_title)
if len(bath_list) > 0:
......@@ -126,7 +128,7 @@ try:
# must call splitQuantity to create new movement foreach new bath
context.updateAppliedRule()
movement_list = []
for bath in bath_dict.keys():
for bath in list(bath_dict.keys()):
if bath != movement_bath:
quantity = 0
context.log('bath', bath)
......@@ -142,7 +144,7 @@ try:
new_movement = context.portal_simulation.solveMovement(movement, None, 'SplitQuantity', additional_parameters={'aggregate_list':apparel_bath_list}, start_date=start_date, stop_date=stop_date, quantity=quantity)
movement_list.append(new_movement[0].getRelativeUrl())
# update root movement if require
if bath_dict.has_key(movement_bath):
if movement_bath in bath_dict:
items = bath_dict[movement_bath]
quantity = 0
for item in items:
......@@ -181,7 +183,7 @@ try:
if cell.getVariationText() == variation_text:
# update aggregate list with items
cell_aggregate_list = cell.getAggregateValueList()
if bath_dict.has_key(line_bath):
if line_bath in bath_dict:
# new items on cell
cell_item = bath_dict[line_bath]
cell_aggregate_list.extend(cell_item)
......@@ -196,7 +198,7 @@ try:
cell.edit(quantity=total_quantity)
except FormValidationError, validation_errors:
except FormValidationError as validation_errors:
redirect_url = '%s/view?%s' % ( context.absolute_url()
, 'portal_status_message=%s' % localizer.erp5_ui.gettext("input failed.")
)
......
# erp5_apparel/ApparelFabricItem_getFastInputList
from builtins import str
from builtins import range
from Products.ERP5Type.Document import newTempBase
object_list = []
......
......@@ -10,11 +10,10 @@ for c in base_category_list:
# try to display line first, then column, and finally others
if matrixbox==1:
# XXX matrixbox is right_display (not as listfield) => invert display and value in item
cell_range.append(map(lambda x: (x[1], x[0]),
resource.getVariationCategoryItemList(
cell_range.append([(x[1], x[0]) for x in resource.getVariationCategoryItemList(
base_category_list=(c,),
display_base_category=display_base_category,
omit_individual_variation=0, sort_id='id')))
omit_individual_variation=0, sort_id='id')])
else:
cell_range.append(
resource.getVariationCategoryList(base_category_list=(c,),
......@@ -26,15 +25,14 @@ predicate_list = context.contentValues(
pred_ids = []
if predicate_list != []:
if matrixbox == 1:
pred_ids = list(map(lambda x: (x.getRelativeUrl(), x.getTitle()),
predicate_list))
pred_ids = list([(x.getRelativeUrl(), x.getTitle()) for x in predicate_list])
else:
pred_ids = list(map(lambda x: x.getRelativeUrl(), predicate_list))
pred_ids = list([x.getRelativeUrl() for x in predicate_list])
# Insert predicat list for display in columns
cell_range.insert(1, pred_ids)
# Remove empty range
cell_range = filter(lambda x: x!=[], cell_range)
cell_range = [x for x in cell_range if x!=[]]
return cell_range
......@@ -5,10 +5,10 @@ msg = context.Base_translateString('No Apparel Model Colour Variation found.')
if apparel_colour_range is None:
msg = context.Base_translateString('Apparel Colour Range must be defined.')
else:
apparel_colour_range_variation_list = map( lambda x: x.getObject(), apparel_colour_range.searchFolder(portal_type=('Apparel Colour Range Variation',)))
apparel_colour_range_variation_list = [x.getObject() for x in apparel_colour_range.searchFolder(portal_type=('Apparel Colour Range Variation',))]
apparel_model_colour_variation_list = context.searchFolder(portal_type=('Apparel Model Colour Variation',))
apparel_model_colour_variation_title_list = map( lambda x: x.getObject().getTitle(), apparel_model_colour_variation_list)
apparel_model_colour_variation_title_list = [x.getObject().getTitle() for x in apparel_model_colour_variation_list]
count = 0
for apparel_colour_range_variation in apparel_colour_range_variation_list:
......
from builtins import str
translateString = context.Base_translateString
portal = context.getPortalObject()
portal_preferences = portal.portal_preferences
......@@ -61,9 +62,9 @@ def getPrototype():
return None
def unicodeDict(d):
for k, v in d.items():
for k, v in list(d.items()):
if isinstance(v, str):
d.update({k:unicode(v, 'utf8')})
d.update({k:str(v, 'utf8')})
return d
data_dict = {
......
......@@ -159,10 +159,10 @@ class TestApparelModel(ERP5TypeTestCase):
self.assertEqual(elasthane.getProperty('quantity'), 0.12)
# check indexes are present
self.assertTrue(apparel_model.index.has_key('composition'))
self.assertTrue('composition' in apparel_model.index)
index = apparel_model.index['composition'][0]
self.assertTrue(index.has_key('composition/elasthane'))
self.assertTrue(index.has_key('composition/acrylique'))
self.assertTrue('composition/elasthane' in index)
self.assertTrue('composition/acrylique' in index)
def test_checkCopyColourRangeVariation(self):
'''
......
......@@ -27,6 +27,8 @@
#
##############################################################################
from builtins import zip
from builtins import range
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from zLOG import LOG
from Products.ERP5Type.tests.Sequence import SequenceList
......
......@@ -26,7 +26,7 @@ node_inventory_dict = {}
activate_kw = {"tag": tag}
for inventory in node_inventory_list:
# Do only one inventory per node
if not node_inventory_dict.has_key(inventory.node_relative_url):
if inventory.node_relative_url not in node_inventory_dict:
inv = inventory_module.newContent(portal_type="Archive Inventory",
destination=inventory.node_relative_url,
......@@ -69,9 +69,9 @@ for inventory in node_inventory_list:
inv_line.updateCellRange(script_id='CashDetail_asCellRange', base_id=base_id)
# create cell
cell_range_key_list = inv_line.getCellRangeKeyList(base_id=base_id)
if cell_range_key_list <> [[None, None]] :
if cell_range_key_list != [[None, None]] :
for k in cell_range_key_list:
category_list = filter(lambda k_item: k_item is not None, k)
category_list = [k_item for k_item in k if k_item is not None]
cell = inv_line.newCell(*k, **line_kwd)
cell.setDefaultActivateParameterDict(activate_kw)
cell.setDefaultReindexParameterDict(dict(sql_catalog_id=destination_sql_catalog_id))
......@@ -87,7 +87,7 @@ for inventory in node_inventory_list:
# deliver all inventory
for inv in node_inventory_dict.values():
for inv in list(node_inventory_dict.values()):
inv.setDefaultActivateParameterDict(activate_kw)
inv.setDefaultReindexParameterDict(dict(sql_catalog_id=destination_sql_catalog_id))
inv.deliver()
......@@ -99,7 +99,7 @@ for inv in node_inventory_dict.values():
payment_inventory_dict = {}
for inventory in payment_inventory_list:
# Do only one inventory per payment
if not payment_inventory_dict.has_key(inventory.payment_uid):
if inventory.payment_uid not in payment_inventory_dict:
inv = inventory_module.newContent(portal_type="Archive Inventory",
destination=inventory.node_relative_url,
......@@ -127,7 +127,7 @@ for inventory in payment_inventory_list:
# deliver all inventory
for inv in payment_inventory_dict.values():
for inv in list(payment_inventory_dict.values()):
inv.setDefaultActivateParameterDict(activate_kw)
inv.setDefaultReindexParameterDict(dict(sql_catalog_id=destination_sql_catalog_id))
inv.deliver()
......@@ -27,6 +27,7 @@
#
##############################################################################
from builtins import str
import time
import unittest
......
from past.builtins import cmp
from builtins import range
from Products.ERP5Type.Core.Workflow import ValidationFailed
from Products.ERP5Type.Message import Message
......@@ -25,7 +27,7 @@ if archive.getStopDateRangeMax() is not None:
if len(previous_archive_list) > 0:
# Check the date
for x in xrange(len(previous_archive_list)):
for x in range(len(previous_archive_list)):
previous_archive = previous_archive_list[x]
# find a previous archive which was not for current catalog
if previous_archive.getStopDateRangeMax() is not None:
......@@ -40,7 +42,7 @@ else:
if len(previous_archive_list) > 0:
# Check the date
for x in xrange(len(previous_archive_list)):
for x in range(len(previous_archive_list)):
previous_archive = previous_archive_list[x]
# find a previous archive which was not for current catalog
if previous_archive.getStopDateRangeMax() is not None:
......
......@@ -24,12 +24,12 @@ kw = {'portal_type': 'Authentication Event',
failure_list = portal.portal_catalog(**kw)
for failure in failure_list:
login = failure.getDestinationValue()
if login not in all_blocked_user_login_dict.keys():
if login not in list(all_blocked_user_login_dict.keys()):
all_blocked_user_login_dict[login] = []
all_blocked_user_login_dict[login].append(failure)
# leave only ones that are blocked:
for login, failure_list in all_blocked_user_login_dict.items():
for login, failure_list in list(all_blocked_user_login_dict.items()):
if len(failure_list) >= max_authentication_failures:
person = login.getParentValue()
blocked_user_login_list.append(newTempBase(portal,
......
......@@ -28,13 +28,17 @@
#
##############################################################################
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from functools import partial
import unittest
import urllib
import urlparse
from StringIO import StringIO
import urllib.request, urllib.parse, urllib.error
import urllib.parse
from io import StringIO
import time
import httplib
import http.client
import mock
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.Document import newTempBase
......@@ -712,9 +716,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
basic='test-05:used_ALREADY_1234',
)
response = publish()
redirect_url = urlparse.urlparse(response.getHeader("Location"))
redirect_url = urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, '{}/login_form'.format(portal.absolute_url_path()))
redirect_url_params = urlparse.parse_qsl(redirect_url.query)
redirect_url_params = urllib.parse.parse_qsl(redirect_url.query)
self.assertEqual(redirect_url_params, [('portal_status_message', 'Account is blocked.')] )
# test expire password message, first unblock it
......@@ -723,9 +727,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
self.tic()
self._clearCache()
response = publish()
redirect_url = urlparse.urlparse(response.getHeader("Location"))
redirect_url = urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, '{}/login_form'.format(portal.absolute_url_path()))
redirect_url_params = urlparse.parse_qsl(redirect_url.query)
redirect_url_params = urllib.parse.parse_qsl(redirect_url.query)
self.assertEqual(redirect_url_params, [('portal_status_message', 'Password is expired.')] )
self.assertTrue(login.isPasswordExpired())
......@@ -735,9 +739,9 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
self.tic()
self._clearCache()
response = publish()
redirect_url = urlparse.urlparse(response.getHeader("Location"))
redirect_url = urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, '{}/ERP5Site_viewNewPersonCredentialUpdateDialog'.format(portal.absolute_url_path()))
redirect_url_params = urlparse.parse_qs(redirect_url.query)
redirect_url_params = urllib.parse.parse_qs(redirect_url.query)
# status message contain the password expiration date
self.assertIn('Your password will expire at 20', redirect_url_params['portal_status_message'][0])
self.assertIn('You are advised to change it as soon as possible', redirect_url_params['portal_status_message'][0])
......@@ -756,12 +760,12 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
response = self.publish(
portal.absolute_url_path() + '/logged_in',
basic='test-05:used_ALREADY_1234',
stdin=StringIO(urllib.urlencode({'came_from': 'https://www.erp5.com'})),
stdin=StringIO(urllib.parse.urlencode({'came_from': 'https://www.erp5.com'})),
request_method='POST',
)
redirect_url = urlparse.urlparse(response.getHeader("Location"))
redirect_url = urllib.parse.urlparse(response.getHeader("Location"))
self.assertEqual(redirect_url.path, portal.absolute_url_path())
redirect_url_params = urlparse.parse_qsl(redirect_url.query)
redirect_url_params = urllib.parse.parse_qsl(redirect_url.query)
self.assertEqual(redirect_url_params, [('portal_status_message', 'Redirection to an external site prevented.')] )
def test_ExpireOldAuthenticationEventList(self):
......@@ -819,7 +823,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
def submit_reset_password_dialog(new_password):
return self.publish(
'%s/portal_password' % self.portal.getPath(),
stdin=StringIO(urllib.urlencode({
stdin=StringIO(urllib.parse.urlencode({
'Base_callDialogMethod:method': '',
'dialog_id': 'PasswordTool_viewResetPassword',
'dialog_method': 'PasswordTool_changeUserPassword',
......@@ -832,7 +836,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
handle_errors=False)
ret = submit_reset_password_dialog('alice')
self.assertEqual(httplib.OK, ret.getStatus())
self.assertEqual(http.client.OK, ret.getStatus())
self.assertIn(
'<span class="error">You can not use any parts of your '
'first and last name in password.</span>',
......@@ -848,14 +852,14 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
with mock.patch.object(self.portal.Localizer.erp5_ui.__class__, 'gettext', side_effect=gettext):
ret = submit_reset_password_dialog('alice')
self.assertEqual(httplib.OK, ret.getStatus())
self.assertEqual(http.client.OK, ret.getStatus())
self.assertIn(
'<span class="error">Yöü can not ... translated</span>',
ret.getBody())
# now with a password complying to the policy
ret = submit_reset_password_dialog('ok')
self.assertEqual(httplib.FOUND, ret.getStatus())
self.assertEqual(http.client.FOUND, ret.getStatus())
self.assertTrue(ret.getHeader('Location').endswith(
'/login_form?portal_status_message=Password+changed.'))
......@@ -874,7 +878,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
return self.publish(
'%s/portal_preferences' % self.portal.getPath(),
basic='%s:current' % self.id(),
stdin=StringIO(urllib.urlencode({
stdin=StringIO(urllib.parse.urlencode({
'Base_callDialogMethod:method': '',
'dialog_id': 'PreferenceTool_viewChangePasswordDialog',
'dialog_method': 'PreferenceTool_setNewPassword',
......@@ -887,7 +891,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
# too short password is refused
ret = submit_change_password_dialog('short')
self.assertEqual(httplib.OK, ret.getStatus())
self.assertEqual(http.client.OK, ret.getStatus())
self.assertIn(
'<span class="error">Too short.</span>',
ret.getBody())
......@@ -902,7 +906,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
with mock.patch.object(self.portal.Localizer.erp5_ui.__class__, 'gettext', side_effect=gettext):
ret = submit_change_password_dialog('short')
self.assertEqual(httplib.OK, ret.getStatus())
self.assertEqual(http.client.OK, ret.getStatus())
self.assertIn(
'<span class="error">Töü short ... translated</span>',
ret.getBody())
......@@ -919,7 +923,7 @@ class TestAuthenticationPolicy(ERP5TypeTestCase):
# long enough password is accepted
ret = submit_change_password_dialog('long_enough_password')
# When password reset is succesful, user is logged out
self.assertEqual(httplib.FOUND, ret.getStatus())
self.assertEqual(http.client.FOUND, ret.getStatus())
self.assertEqual(self.portal.portal_preferences.absolute_url(),
ret.getHeader("Location"))
......
......@@ -28,6 +28,7 @@
"""Tests Bank Reconciliation
"""
from builtins import str
import unittest
from DateTime import DateTime
......
......@@ -25,9 +25,14 @@
#
##############################################################################
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import map
from builtins import range
import os
from string import zfill
from urllib import urlencode
from urllib.parse import urlencode
import tempfile
from DateTime import DateTime
from zLOG import LOG
......@@ -37,7 +42,7 @@ lp = 'lp'
def escapeString(string):
#Barcode can accept only ASCII
string = str(unicode(str(string), 'utf-8'))
string = str(str(str(string), 'utf-8'))
#Escape
string = string.replace('"', '\\"')
return string
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment