Commit 08be2f8c authored by Aurel's avatar Aurel

apply raiser fixer & absolute import fixer

parent 86985db3
...@@ -44,24 +44,24 @@ class InventoryKey(UserDict): ...@@ -44,24 +44,24 @@ class InventoryKey(UserDict):
self.data.update(kw) self.data.update(kw)
def clear(self): def clear(self):
raise TypeError, 'InventoryKey are immutable' raise TypeError('InventoryKey are immutable')
def pop(self, keys, *args): def pop(self, keys, *args):
raise TypeError, 'InventoryKey are immutable' raise TypeError('InventoryKey are immutable')
def update(self, dict=None, **kwargs): # pylint: disable=redefined-builtin def update(self, dict=None, **kwargs): # pylint: disable=redefined-builtin
raise TypeError, 'InventoryKey are immutable' raise TypeError('InventoryKey are immutable')
def __delitem__(self, key): def __delitem__(self, key):
raise TypeError, 'InventoryKey are immutable' raise TypeError('InventoryKey are immutable')
def __setitem__(self, key, item): def __setitem__(self, key, item):
raise TypeError, 'InventoryKey are immutable' raise TypeError('InventoryKey are immutable')
def setdefault(self, key, failobj=None): def setdefault(self, key, failobj=None):
if key in self.data: if key in self.data:
return self.data[key] return self.data[key]
raise TypeError, 'InventoryKey are immutable' raise TypeError('InventoryKey are immutable')
def __hash__(self): def __hash__(self):
return hash(tuple(self.items())) return hash(tuple(self.items()))
...@@ -162,7 +162,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): ...@@ -162,7 +162,7 @@ class BalanceTransaction(AccountingTransaction, Inventory):
for movement in self._getGroupByNodeMovementList(): for movement in self._getGroupByNodeMovementList():
node_uid = movement.getDestinationUid() node_uid = movement.getDestinationUid()
if not node_uid: if not node_uid:
raise ValueError, "No destination uid for %s" % movement raise ValueError("No destination uid for %s" % movement)
resource_uid = movement.getResourceUid() resource_uid = movement.getResourceUid()
stock_list = current_stock.setdefault( stock_list = current_stock.setdefault(
...@@ -188,7 +188,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): ...@@ -188,7 +188,7 @@ class BalanceTransaction(AccountingTransaction, Inventory):
for movement in self._getGroupByMirrorSectionMovementList(): for movement in self._getGroupByMirrorSectionMovementList():
node_uid = movement.getDestinationUid() node_uid = movement.getDestinationUid()
if not node_uid: if not node_uid:
raise ValueError, "No destination uid for %s" % movement raise ValueError("No destination uid for %s" % movement)
mirror_section_uid = movement.getSourceSectionUid() mirror_section_uid = movement.getSourceSectionUid()
resource_uid = movement.getResourceUid() resource_uid = movement.getResourceUid()
...@@ -219,7 +219,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): ...@@ -219,7 +219,7 @@ class BalanceTransaction(AccountingTransaction, Inventory):
for movement in self._getGroupByPaymentMovementList(): for movement in self._getGroupByPaymentMovementList():
node_uid = movement.getDestinationUid() node_uid = movement.getDestinationUid()
if not node_uid: if not node_uid:
raise ValueError, "No destination uid for %s" % movement raise ValueError("No destination uid for %s" % movement)
payment_uid = movement.getDestinationPaymentUid() payment_uid = movement.getDestinationPaymentUid()
resource_uid = movement.getResourceUid() resource_uid = movement.getResourceUid()
...@@ -258,7 +258,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): ...@@ -258,7 +258,7 @@ class BalanceTransaction(AccountingTransaction, Inventory):
for movement in self._getGroupByNodeMovementList(): for movement in self._getGroupByNodeMovementList():
node_uid = movement.getDestinationUid() node_uid = movement.getDestinationUid()
if not node_uid: if not node_uid:
raise ValueError, "No destination uid for %s" % movement raise ValueError("No destination uid for %s" % movement)
section_uid = movement.getDestinationSectionUid() section_uid = movement.getDestinationSectionUid()
stock_list = new_stock.setdefault( stock_list = new_stock.setdefault(
...@@ -280,7 +280,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): ...@@ -280,7 +280,7 @@ class BalanceTransaction(AccountingTransaction, Inventory):
for movement in self._getGroupByMirrorSectionMovementList(): for movement in self._getGroupByMirrorSectionMovementList():
node_uid = movement.getDestinationUid() node_uid = movement.getDestinationUid()
if not node_uid: if not node_uid:
raise ValueError, "No destination uid for %s" % movement raise ValueError("No destination uid for %s" % movement)
section_uid = movement.getDestinationSectionUid() section_uid = movement.getDestinationSectionUid()
mirror_section_uid = movement.getSourceSectionUid() mirror_section_uid = movement.getSourceSectionUid()
...@@ -305,7 +305,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): ...@@ -305,7 +305,7 @@ class BalanceTransaction(AccountingTransaction, Inventory):
for movement in self._getGroupByPaymentMovementList(): for movement in self._getGroupByPaymentMovementList():
node_uid = movement.getDestinationUid() node_uid = movement.getDestinationUid()
if not node_uid: if not node_uid:
raise ValueError, "No destination uid for %s" % movement raise ValueError("No destination uid for %s" % movement)
section_uid = movement.getDestinationSectionUid() section_uid = movement.getDestinationSectionUid()
payment_uid = movement.getDestinationPaymentUid() payment_uid = movement.getDestinationPaymentUid()
......
...@@ -10,7 +10,7 @@ start_date = closing_period.getStartDate() ...@@ -10,7 +10,7 @@ start_date = closing_period.getStartDate()
stop_date = closing_period.getStopDate() stop_date = closing_period.getStopDate()
if start_date > stop_date: if start_date > stop_date:
raise ValidationFailed, translateString("Start date is after stop date.") raise ValidationFailed(translateString("Start date is after stop date."))
period_list = [ period_list = [
x x
...@@ -23,9 +23,9 @@ period_list = [ ...@@ -23,9 +23,9 @@ period_list = [
for period in period_list: for period in period_list:
if start_date <= period.getStopDate() and not stop_date <= period.getStartDate(): if start_date <= period.getStopDate() and not stop_date <= period.getStartDate():
raise ValidationFailed, translateString( raise ValidationFailed(translateString(
"${date} is already in an open accounting period.", "${date} is already in an open accounting period.",
mapping={'date': start_date}) mapping={'date': start_date}))
previous_period = next( previous_period = next(
iter( iter(
...@@ -39,9 +39,9 @@ previous_period = next( ...@@ -39,9 +39,9 @@ previous_period = next(
) )
if previous_period is not None: if previous_period is not None:
if (start_date - previous_period.getStopDate()) > 1.9: if (start_date - previous_period.getStopDate()) > 1.9:
raise ValidationFailed, translateString( raise ValidationFailed(translateString(
"Last opened period ends on ${last_openned_date},"+ "Last opened period ends on ${last_openned_date},"+
" this period starts on ${this_period_start_date}."+ " this period starts on ${this_period_start_date}."+
" Accounting Periods must be consecutive.", " Accounting Periods must be consecutive.",
mapping = { 'last_openned_date': previous_period.getStopDate(), mapping = { 'last_openned_date': previous_period.getStopDate(),
'this_period_start_date': start_date } ) 'this_period_start_date': start_date } ))
...@@ -34,7 +34,7 @@ while section.getPortalType() == period.getPortalType(): ...@@ -34,7 +34,7 @@ while section.getPortalType() == period.getPortalType():
section_category = section.getGroup(base=True) section_category = section.getGroup(base=True)
if not section_category: if not section_category:
raise ValidationFailed, translateString("This Organisation must be member of a Group") raise ValidationFailed(translateString("This Organisation must be member of a Group"))
# XXX copy and paste from AccountingPeriod_createBalanceTransaction ! # XXX copy and paste from AccountingPeriod_createBalanceTransaction !
...@@ -81,5 +81,5 @@ movement_list = portal.portal_simulation.getMovementHistoryList( ...@@ -81,5 +81,5 @@ movement_list = portal.portal_simulation.getMovementHistoryList(
limit=1) limit=1)
if movement_list: if movement_list:
raise ValidationFailed, translateString( raise ValidationFailed(translateString(
"All Accounting Transactions for this organisation during the period have to be closed first.") "All Accounting Transactions for this organisation during the period have to be closed first."))
...@@ -32,21 +32,21 @@ for line in transaction_lines: ...@@ -32,21 +32,21 @@ for line in transaction_lines:
): ):
if account is not None and account.getValidationState() != 'validated': if account is not None and account.getValidationState() != 'validated':
raise ValidationFailed, translateString( raise ValidationFailed(translateString(
"Account ${account_title} is not validated.", "Account ${account_title} is not validated.",
mapping=dict(account_title=account.Account_getFormattedTitle())) mapping=dict(account_title=account.Account_getFormattedTitle())))
if third_party is not None and\ if third_party is not None and\
third_party.getValidationState() in invalid_state_list: third_party.getValidationState() in invalid_state_list:
raise ValidationFailed, translateString( raise ValidationFailed(translateString(
"Third party ${third_party_name} is invalid.", "Third party ${third_party_name} is invalid.",
mapping=dict(third_party_name=third_party.getTitle())) mapping=dict(third_party_name=third_party.getTitle())))
if bank_account is not None: if bank_account is not None:
if bank_account.getValidationState() in invalid_state_list: if bank_account.getValidationState() in invalid_state_list:
raise ValidationFailed, translateString( raise ValidationFailed(translateString(
"Bank Account ${bank_account_reference} is invalid.", "Bank Account ${bank_account_reference} is invalid.",
mapping=dict(bank_account_reference=bank_account.getReference())) mapping=dict(bank_account_reference=bank_account.getReference())))
if account is not None and account.isMemberOf('account_type/asset/cash/bank'): if account is not None and account.isMemberOf('account_type/asset/cash/bank'):
# also check that currencies are consistent if we use this quantity for # also check that currencies are consistent if we use this quantity for
...@@ -54,11 +54,11 @@ for line in transaction_lines: ...@@ -54,11 +54,11 @@ for line in transaction_lines:
bank_account_currency = bank_account.getProperty('price_currency') bank_account_currency = bank_account.getProperty('price_currency')
if bank_account_currency is not None and \ if bank_account_currency is not None and \
bank_account_currency != line.getResource(): bank_account_currency != line.getResource():
raise ValidationFailed, translateString( raise ValidationFailed(translateString(
"Bank Account ${bank_account_reference} " "Bank Account ${bank_account_reference} "
"uses ${bank_account_currency} as default currency.", "uses ${bank_account_currency} as default currency.",
mapping=dict(bank_account_reference=bank_account.getReference(), mapping=dict(bank_account_reference=bank_account.getReference(),
bank_account_currency=bank_account.getPriceCurrencyReference())) bank_account_currency=bank_account.getPriceCurrencyReference())))
source_currency = None source_currency = None
source_section = line.getSourceSectionValue() source_section = line.getSourceSectionValue()
......
...@@ -18,7 +18,7 @@ show_parent_accounts = request.get('show_parent_accounts', False) ...@@ -18,7 +18,7 @@ show_parent_accounts = request.get('show_parent_accounts', False)
# flat_mode is a boolean that indicate wether we should use a report tree # flat_mode is a boolean that indicate wether we should use a report tree
# or a flat list of all accounts. # or a flat list of all accounts.
if request.get('tree_mode', False): if request.get('tree_mode', False):
raise 'Tree mode no longer supported' raise ValueError('Tree mode no longer supported')
result = [] result = []
params = { params = {
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
the new Invoice. the new Invoice.
""" """
if related_simulation_movement_path_list is None: if related_simulation_movement_path_list is None:
raise RuntimeError, 'related_simulation_movement_path_list is missing. Update ERP5 Product.' raise RuntimeError('related_simulation_movement_path_list is missing. Update ERP5 Product.')
invoice = context invoice = context
......
...@@ -327,8 +327,8 @@ class TestProductionOrderApparelMixin(TestOrderMixin): ...@@ -327,8 +327,8 @@ class TestProductionOrderApparelMixin(TestOrderMixin):
LOG('object.getQuantity()',0,object.getQuantity()) LOG('object.getQuantity()',0,object.getQuantity())
LOG('object.__dict__',0,object.__dict__) LOG('object.__dict__',0,object.__dict__)
LOG('object.getDeliveryValue().getQuantity()',0,object.getDeliveryValue().getQuantity()) LOG('object.getDeliveryValue().getQuantity()',0,object.getDeliveryValue().getQuantity())
raise AssertionError, "Attribute: %s, Value: %s, Result: %s" %\ raise AssertionError("Attribute: %s, Value: %s, Result: %s"
(attribute, value, getattr(object, attribute)()) % (attribute, value, getattr(object, attribute)()))
def stepCheckProductionSimulation(self, sequence=None, sequence_list=None, def stepCheckProductionSimulation(self, sequence=None, sequence_list=None,
**kw): **kw):
......
...@@ -116,7 +116,7 @@ class ArchiveTool(BaseTool): ...@@ -116,7 +116,7 @@ class ArchiveTool(BaseTool):
""" """
# First check parameter for destination catalog # First check parameter for destination catalog
if destination_archive_id == archive_id: if destination_archive_id == archive_id:
raise ValueError, "Archive and destination archive can't be the same" raise ValueError("Archive and destination archive can't be the same")
portal_catalog =self.portal_catalog portal_catalog =self.portal_catalog
# Guess connection id from current catalog # Guess connection id from current catalog
source_catalog = portal_catalog.getSQLCatalog() source_catalog = portal_catalog.getSQLCatalog()
...@@ -126,7 +126,7 @@ class ArchiveTool(BaseTool): ...@@ -126,7 +126,7 @@ class ArchiveTool(BaseTool):
source_deferred_connection_id = source_catalog.getConnectionId(deferred=True) source_deferred_connection_id = source_catalog.getConnectionId(deferred=True)
if source_connection_id is None or source_deferred_connection_id is None: if source_connection_id is None or source_deferred_connection_id is None:
raise ValueError, "Unable to determine connection id for the current catalog" raise ValueError("Unable to determine connection id for the current catalog")
# Get destination property from archive # Get destination property from archive
destination_archive_id = destination_archive_id.split(' - ')[0] destination_archive_id = destination_archive_id.split(' - ')[0]
...@@ -144,25 +144,25 @@ class ArchiveTool(BaseTool): ...@@ -144,25 +144,25 @@ class ArchiveTool(BaseTool):
# Check we don't use same connection id for source and destination # Check we don't use same connection id for source and destination
if destination_sql_catalog_id == source_catalog_id: if destination_sql_catalog_id == source_catalog_id:
raise ValueError, "Destination and source catalog can't be the same" raise ValueError("Destination and source catalog can't be the same")
if destination_connection_id == source_connection_id: if destination_connection_id == source_connection_id:
raise ValueError, "Destination and source connection can't be the same" raise ValueError("Destination and source connection can't be the same")
if destination_deferred_connection_id == source_deferred_connection_id: if destination_deferred_connection_id == source_deferred_connection_id:
raise ValueError, "Destination and source deferred connection can't be the same" raise ValueError("Destination and source deferred connection can't be the same")
# Same for source and archive # Same for source and archive
if archive_sql_catalog_id == source_catalog_id: if archive_sql_catalog_id == source_catalog_id:
raise ValueError, "Archive and source catalog can't be the same" raise ValueError("Archive and source catalog can't be the same")
if archive_connection_id == source_connection_id: if archive_connection_id == source_connection_id:
raise ValueError, "Archive and source connection can't be the same" raise ValueError("Archive and source connection can't be the same")
if archive_deferred_connection_id == source_deferred_connection_id: if archive_deferred_connection_id == source_deferred_connection_id:
raise ValueError, "Archive and source deferred connection can't be the same" raise ValueError("Archive and source deferred connection can't be the same")
# Same for destination and archive # Same for destination and archive
if archive_sql_catalog_id == destination_sql_catalog_id: if archive_sql_catalog_id == destination_sql_catalog_id:
raise ValueError, "Archive and destination catalog can't be the same" raise ValueError("Archive and destination catalog can't be the same")
if archive_connection_id == destination_connection_id: if archive_connection_id == destination_connection_id:
raise ValueError, "Archive and destination connection can't be the same" raise ValueError("Archive and destination connection can't be the same")
if archive_deferred_connection_id == destination_deferred_connection_id: if archive_deferred_connection_id == destination_deferred_connection_id:
raise ValueError, "Archive and destination deferred connection can't be the same" raise ValueError("Archive and destination deferred connection can't be the same")
# Update connection id in destination and archive catalog if asked # Update connection id in destination and archive catalog if asked
destination_sql_catalog = getattr(portal_catalog, destination_sql_catalog_id) destination_sql_catalog = getattr(portal_catalog, destination_sql_catalog_id)
......
...@@ -8,17 +8,17 @@ start_date = inventory.getStartDate() ...@@ -8,17 +8,17 @@ start_date = inventory.getStartDate()
if start_date is None: if start_date is None:
text = "Sorry, you must define the inventory date" text = "Sorry, you must define the inventory date"
message = Message(domain='ui', message=text) message = Message(domain='ui', message=text)
raise ValidationFailed, message raise ValidationFailed(message)
# Make sure the node is defined # Make sure the node is defined
node = inventory.getDestination() node = inventory.getDestination()
if node is None: if node is None:
text = "Sorry, you must define the inventory warehouse" text = "Sorry, you must define the inventory warehouse"
message = Message(domain='ui', message=text) message = Message(domain='ui', message=text)
raise ValidationFailed, message raise ValidationFailed(message)
# use of the constraint # use of the constraint
error_list = inventory.checkConsistency() error_list = inventory.checkConsistency()
if len(error_list) > 0: if len(error_list) > 0:
raise ValidationFailed, (error_list[0].getTranslatedMessage(),) raise ValidationFailed(error_list[0].getTranslatedMessage())
...@@ -11,7 +11,7 @@ catalog_id = archive.getCatalogId() ...@@ -11,7 +11,7 @@ catalog_id = archive.getCatalogId()
if "deferred" not in archive.getDeferredConnectionId(): if "deferred" not in archive.getDeferredConnectionId():
msg = Message(domain='ui', message='Deferred connection ID choose is not a deferred connection.') msg = Message(domain='ui', message='Deferred connection ID choose is not a deferred connection.')
raise ValidationFailed, (msg,) raise ValidationFailed(msg)
def sort_max_date(a, b): def sort_max_date(a, b):
return cmp(a.getStopDateRangeMax(), b.getStopDateRangeMax()) return cmp(a.getStopDateRangeMax(), b.getStopDateRangeMax())
...@@ -32,7 +32,7 @@ if archive.getStopDateRangeMax() is not None: ...@@ -32,7 +32,7 @@ if archive.getStopDateRangeMax() is not None:
break break
if previous_archive.getStopDateRangeMax().Date() != min_stop_date: if previous_archive.getStopDateRangeMax().Date() != min_stop_date:
msg = Message(domain='ui', message='Archive are not contiguous.') msg = Message(domain='ui', message='Archive are not contiguous.')
raise ValidationFailed, (msg,) raise ValidationFailed(msg)
else: else:
previous_archive_list = [x.getObject() for x in archive.portal_catalog(portal_type="Archive", previous_archive_list = [x.getObject() for x in archive.portal_catalog(portal_type="Archive",
validation_state='ready')] validation_state='ready')]
...@@ -47,7 +47,7 @@ else: ...@@ -47,7 +47,7 @@ else:
break break
if previous_archive.getStopDateRangeMax().Date() != min_stop_date: if previous_archive.getStopDateRangeMax().Date() != min_stop_date:
msg = Message(domain='ui', message='Archive are not contiguous.') msg = Message(domain='ui', message='Archive are not contiguous.')
raise ValidationFailed, (msg,) raise ValidationFailed(msg)
# Check the catalog # Check the catalog
...@@ -57,4 +57,4 @@ previous_archive_list = [x.getObject() for x in archive.portal_catalog(portal_ty ...@@ -57,4 +57,4 @@ previous_archive_list = [x.getObject() for x in archive.portal_catalog(portal_ty
for arch in previous_archive_list: for arch in previous_archive_list:
if arch.getCatalogId() == catalog_id and arch is not previous_archive: if arch.getCatalogId() == catalog_id and arch is not previous_archive:
msg = Message(domain='ui', message='Use of a former catalog is prohibited.') msg = Message(domain='ui', message='Use of a former catalog is prohibited.')
raise ValidationFailed, (msg,) raise ValidationFailed(msg)
...@@ -66,7 +66,7 @@ def printBarcodeSheet(self, sheet_number=1, input_list=[], test=False): ...@@ -66,7 +66,7 @@ def printBarcodeSheet(self, sheet_number=1, input_list=[], test=False):
ps2pdf_command = '%s %s %s' % (ps2pdf, ps_file_path, new_pdf_file_path) ps2pdf_command = '%s %s %s' % (ps2pdf, ps_file_path, new_pdf_file_path)
ret = os.system(ps2pdf_command) ret = os.system(ps2pdf_command)
if ret != 0: if ret != 0:
raise RuntimeError, 'PS Conversion Failed' raise RuntimeError('PS Conversion Failed')
file = open(new_pdf_file_path, 'rb') file = open(new_pdf_file_path, 'rb')
result = file.read() result = file.read()
file_size = len(result) file_size = len(result)
...@@ -93,7 +93,7 @@ def printBarcodeSheet(self, sheet_number=1, input_list=[], test=False): ...@@ -93,7 +93,7 @@ def printBarcodeSheet(self, sheet_number=1, input_list=[], test=False):
text_command = 'echo "%s" > %s' % (input_list, new_txt_file_path) text_command = 'echo "%s" > %s' % (input_list, new_txt_file_path)
ret = os.system(text_command) ret = os.system(text_command)
if ret != 0: if ret != 0:
raise RuntimeError, 'File Creation Failed' raise RuntimeError('File Creation Failed')
if horizontal_padding not in ('', None) and vertical_padding not in ('', None): if horizontal_padding not in ('', None) and vertical_padding not in ('', None):
margin = '%sx%s' % (horizontal_padding, vertical_padding) margin = '%sx%s' % (horizontal_padding, vertical_padding)
...@@ -139,7 +139,7 @@ def printBarcodeSheet(self, sheet_number=1, input_list=[], test=False): ...@@ -139,7 +139,7 @@ def printBarcodeSheet(self, sheet_number=1, input_list=[], test=False):
barcode_command += ' -o %s ' %(new_ps_file_path) barcode_command += ' -o %s ' %(new_ps_file_path)
ret = os.system(barcode_command) ret = os.system(barcode_command)
if ret != 0: if ret != 0:
raise RuntimeError, 'Barcode PS File Creation Failed' raise RuntimeError('Barcode PS File Creation Failed')
if test: if test:
return getPdfOutput(self, new_ps_file_path, file_name='TestReferenceSheet.pdf') return getPdfOutput(self, new_ps_file_path, file_name='TestReferenceSheet.pdf')
......
...@@ -80,7 +80,7 @@ class Agent(Folder, Image): ...@@ -80,7 +80,7 @@ class Agent(Folder, Image):
% self.absolute_url()) % self.absolute_url())
return return
else : else :
raise RuntimeError, 'No file or an empty file was specified' raise RuntimeError('No file or an empty file was specified')
import_file.seek(0) import_file.seek(0)
self.manage_upload(file=import_file) self.manage_upload(file=import_file)
......
...@@ -58,7 +58,7 @@ class CausalityMovementGroup(MovementGroup): ...@@ -58,7 +58,7 @@ class CausalityMovementGroup(MovementGroup):
movement = movement.getParentValue().getParentValue() movement = movement.getParentValue().getParentValue()
explanation_value = movement.getExplanationValue() explanation_value = movement.getExplanationValue()
if explanation_value is None: if explanation_value is None:
raise ValueError, 'No explanation for movement %s' % movement.getPath() raise ValueError('No explanation for movement %s' % movement.getPath())
else: else:
# This is a temp movement # This is a temp movement
explanation_value = None explanation_value = None
......
...@@ -135,7 +135,7 @@ class Url(Coordinate, UrlMixin): ...@@ -135,7 +135,7 @@ class Url(Coordinate, UrlMixin):
if to_url is None: if to_url is None:
to_url = self.getUrlString(None) to_url = self.getUrlString(None)
if from_url is None or to_url is None: if from_url is None or to_url is None:
raise AttributeError, "No mail defined" raise AttributeError("No mail defined")
portal_notifications = getToolByName(self, 'portal_notifications') portal_notifications = getToolByName(self, 'portal_notifications')
......
...@@ -29,7 +29,7 @@ def generateBarcodeImage(self, barcode_type, data, REQUEST=None): ...@@ -29,7 +29,7 @@ def generateBarcodeImage(self, barcode_type, data, REQUEST=None):
fp.seek(0) fp.seek(0)
output = fp.read() output = fp.read()
else: else:
raise NotImplementedError, 'barcode_type=%s is not supported' % barcode_type raise NotImplementedError('barcode_type=%s is not supported' % barcode_type)
if REQUEST is not None: if REQUEST is not None:
REQUEST.RESPONSE.setHeader('Content-Type', 'image/png') REQUEST.RESPONSE.setHeader('Content-Type', 'image/png')
return output return output
...@@ -290,8 +290,8 @@ class BuilderMixin(XMLObject, Amount, Predicate): ...@@ -290,8 +290,8 @@ class BuilderMixin(XMLObject, Amount, Predicate):
for movement in select_method(**kw): for movement in select_method(**kw):
movement = movement.getObject() movement = movement.getObject()
if movement in movement_set: if movement in movement_set:
raise SelectMethodError('%s returned %s twice or more' % \ raise SelectMethodError('%s returned %s twice or more'
(method_id, movement.getRelativeUrl())) % (method_id, movement.getRelativeUrl()))
movement_set.add(movement) movement_set.add(movement)
movement_list.append(movement) movement_list.append(movement)
...@@ -493,7 +493,7 @@ class BuilderMixin(XMLObject, Amount, Predicate): ...@@ -493,7 +493,7 @@ class BuilderMixin(XMLObject, Amount, Predicate):
if delivery is None: if delivery is None:
if not self.isDeliveryCreatable(): if not self.isDeliveryCreatable():
raise SelectMethodError('No updatable delivery found with %s for %s' \ raise SelectMethodError('No updatable delivery found with %s for %s'
% (self.getPath(), movement_group_node_list)) % (self.getPath(), movement_group_node_list))
delivery = self._createDelivery(delivery_module, delivery = self._createDelivery(delivery_module,
...@@ -661,8 +661,9 @@ class BuilderMixin(XMLObject, Amount, Predicate): ...@@ -661,8 +661,9 @@ class BuilderMixin(XMLObject, Amount, Predicate):
else: else:
movement_list = movement_group_node.getMovementList() movement_list = movement_group_node.getMovementList()
if len(movement_list) != 1: if len(movement_list) != 1:
raise CollectError, "DeliveryBuilder: %s unable to distinct those\ raise CollectError(
movements: %s" % (self.getId(), str(movement_list)) "DeliveryBuilder: %s unable to distinct those movements: %s"
% (self.getId(), movement_list))
else: else:
# XXX Hardcoded value # XXX Hardcoded value
base_id = 'movement' base_id = 'movement'
...@@ -720,8 +721,8 @@ class BuilderMixin(XMLObject, Amount, Predicate): ...@@ -720,8 +721,8 @@ class BuilderMixin(XMLObject, Amount, Predicate):
membership_criterion_base_category_list=movement.\ membership_criterion_base_category_list=movement.\
getVariationBaseCategoryList()) getVariationBaseCategoryList())
else: else:
raise MatrixError, 'Cell: %s already exists on %s' % \ raise MatrixError('Cell: %s already exists on %s'
(str(cell_key), str(delivery_line)) % (cell_key, delivery_line))
object_to_update = cell object_to_update = cell
self._setUpdated(object_to_update, 'cell') self._setUpdated(object_to_update, 'cell')
self._setDeliveryMovementProperties( self._setDeliveryMovementProperties(
......
...@@ -17,4 +17,4 @@ for career_step in career_step_list : ...@@ -17,4 +17,4 @@ for career_step in career_step_list :
# for now, we only return the first one. # for now, we only return the first one.
return career_step.getStartDate() return career_step.getStartDate()
raise ValueError, 'No Career Step Defined.' raise ValueError('No Career Step Defined.')
...@@ -21,7 +21,7 @@ user_name = context.getId() ...@@ -21,7 +21,7 @@ user_name = context.getId()
# XXX Note : sometimes, you don't want to update security for users who don't belong to your organisation. # XXX Note : sometimes, you don't want to update security for users who don't belong to your organisation.
# You can then add code in the assignment_workflow script to skip those (if role != internal for instance) # You can then add code in the assignment_workflow script to skip those (if role != internal for instance)
if user_name not in user_folder.getUserNames(): if user_name not in user_folder.getUserNames():
raise RuntimeError, "Error: Zope user '%s' doesn't exist in the acl_users folder" % (user_name) raise RuntimeError("Error: Zope user %r doesn't exist in the acl_users folder" % user_name)
category_list = [] category_list = []
security_group_list = [] security_group_list = []
......
...@@ -23,4 +23,4 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment ...@@ -23,4 +23,4 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment
# The only case when several assignments can be started at the same time is when they share the same 'site' value. # The only case when several assignments can be started at the same time is when they share the same 'site' value.
if len(assignment_site_list) != 1: if len(assignment_site_list) != 1:
raise ValidationFailed, "Error: started assignments must have the same site value." raise ValidationFailed("Error: started assignments must have the same site value.")
...@@ -116,7 +116,7 @@ class BigFile(File): ...@@ -116,7 +116,7 @@ class BigFile(File):
file = StringIO(file) file = StringIO(file)
if isinstance(file, FileUpload) and not file: if isinstance(file, FileUpload) and not file:
raise ValueError, 'File not specified' raise ValueError('File not specified')
seek=file.seek seek=file.seek
read=file.read read=file.read
......
...@@ -42,8 +42,8 @@ for person in person_value_list: ...@@ -42,8 +42,8 @@ for person in person_value_list:
resource = inventory.resource_relative_url resource = inventory.resource_relative_url
if inventory.resource_uid in presence_resource_uid_list: if inventory.resource_uid in presence_resource_uid_list:
raise ValueError, "This report does not work when same resource are"\ raise ValueError("This report does not work when same resource are"
" used in presence and leave." " used in presence and leave.")
person_time = (person_planned_time - person.getAvailableTime( person_time = (person_planned_time - person.getAvailableTime(
from_date=from_date, from_date=from_date,
......
...@@ -36,6 +36,7 @@ from Products.ERP5Type.Tool.BaseTool import BaseTool ...@@ -36,6 +36,7 @@ from Products.ERP5Type.Tool.BaseTool import BaseTool
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from Products.PageTemplates.PageTemplateFile import PageTemplateFile from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from zLOG import LOG, INFO from zLOG import LOG, INFO
from six import reraise
def popenCommunicate(command_list, input_=None, **kwargs): def popenCommunicate(command_list, input_=None, **kwargs):
kwargs.update(stdout=subprocess.PIPE, stderr=subprocess.STDOUT) kwargs.update(stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
...@@ -220,7 +221,7 @@ class CertificateAuthorityTool(BaseTool): ...@@ -220,7 +221,7 @@ class CertificateAuthorityTool(BaseTool):
certificate=open(cert).read(), certificate=open(cert).read(),
id=new_id, id=new_id,
common_name=common_name) common_name=common_name)
except: except Exception:
e = sys.exc_info() e = sys.exc_info()
try: try:
for p in key, csr, cert: for p in key, csr, cert:
...@@ -229,7 +230,7 @@ class CertificateAuthorityTool(BaseTool): ...@@ -229,7 +230,7 @@ class CertificateAuthorityTool(BaseTool):
except Exception: except Exception:
# do not raise during cleanup # do not raise during cleanup
pass pass
raise e[0], e[1], e[2] reraise(*e)
finally: finally:
self._unlockCertificateAuthority() self._unlockCertificateAuthority()
...@@ -260,7 +261,7 @@ class CertificateAuthorityTool(BaseTool): ...@@ -260,7 +261,7 @@ class CertificateAuthorityTool(BaseTool):
created.append(alias) created.append(alias)
os.symlink(os.path.basename(crl), alias) os.symlink(os.path.basename(crl), alias)
return dict(crl=open(crl).read()) return dict(crl=open(crl).read())
except: except Exception:
e = sys.exc_info() e = sys.exc_info()
try: try:
for p in 'index.txt', 'crlnumber': for p in 'index.txt', 'crlnumber':
...@@ -272,7 +273,7 @@ class CertificateAuthorityTool(BaseTool): ...@@ -272,7 +273,7 @@ class CertificateAuthorityTool(BaseTool):
except Exception: except Exception:
# do not raise during cleanup # do not raise during cleanup
pass pass
raise e[0], e[1], e[2] reraise(*e)
finally: finally:
self._unlockCertificateAuthority() self._unlockCertificateAuthority()
......
...@@ -21,7 +21,7 @@ if isAnon: ...@@ -21,7 +21,7 @@ if isAnon:
#Check if payment is sucessfull #Check if payment is sucessfull
if buyer is None: if buyer is None:
raise ValueError, "Impossible to finalize and order not payed" raise ValueError("Impossible to finalize and order not payed")
portal_type = "Sale %s" % shopping_cart.getPortalType() portal_type = "Sale %s" % shopping_cart.getPortalType()
module = context.getDefaultModule(portal_type) module = context.getDefaultModule(portal_type)
......
"""Set connected user as shopping cart customer""" """Set connected user as shopping cart customer"""
if REQUEST is not None: if REQUEST is not None:
raise RuntimeError, "You can not call this script from the URL" raise RuntimeError("You can not call this script from the URL")
shopping_cart = context.SaleOrder_getShoppingCart() shopping_cart = context.SaleOrder_getShoppingCart()
......
...@@ -338,7 +338,7 @@ class TestAlarm(ERP5TypeTestCase): ...@@ -338,7 +338,7 @@ class TestAlarm(ERP5TypeTestCase):
finally: finally:
self.portal.portal_activities.manageClearActivities(keep=0) self.portal.portal_activities.manageClearActivities(keep=0)
else: else:
raise Exception, 'Tic did not raise though activity was supposed to fail' raise Exception('Tic did not raise though activity was supposed to fail')
# Make the sense method succeed and leave a trace # Make the sense method succeed and leave a trace
self.getPortal().portal_skins[skin_folder_id][sense_method_id].ZPythonScript_edit('*args,**kw', 'context.newActiveProcess()') self.getPortal().portal_skins[skin_folder_id][sense_method_id].ZPythonScript_edit('*args,**kw', 'context.newActiveProcess()')
alarm.activeSense() alarm.activeSense()
......
...@@ -165,7 +165,7 @@ class IndexableDocument(ObjectManager): ...@@ -165,7 +165,7 @@ class IndexableDocument(ObjectManager):
if name.startswith('is') or \ if name.startswith('is') or \
name.startswith('provides'): name.startswith('provides'):
return lambda: 0 return lambda: 0
raise AttributeError, name raise AttributeError(name)
def getProperty(self, prop, default=None): def getProperty(self, prop, default=None):
return getattr(aq_base(self), prop, default) return getattr(aq_base(self), prop, default)
...@@ -2155,7 +2155,7 @@ class TestERP5Catalog(ERP5TypeTestCase, LogInterceptor): ...@@ -2155,7 +2155,7 @@ class TestERP5Catalog(ERP5TypeTestCase, LogInterceptor):
result = query('SELECT * FROM roles_and_users WHERE allowedRolesAndUsers LIKE "%s:%%" AND uid = %i' % (line['allowedRolesAndUsers'], uid) ) result = query('SELECT * FROM roles_and_users WHERE allowedRolesAndUsers LIKE "%s:%%" AND uid = %i' % (line['allowedRolesAndUsers'], uid) )
self.assertNotEqual(len(result), 0, 'No line found for allowedRolesAndUsers=%r and uid=%i' % (line['allowedRolesAndUsers'], uid)) self.assertNotEqual(len(result), 0, 'No line found for allowedRolesAndUsers=%r and uid=%i' % (line['allowedRolesAndUsers'], uid))
else: else:
raise Exception, 'Malformed allowedRolesAndUsers value: %r' % (line['allowedRolesAndUsers'], ) raise Exception('Malformed allowedRolesAndUsers value: %(allowedRolesAndUsers)r' % line)
# Check that object that 'bar' can view because of 'Author' role can *not* # Check that object that 'bar' can view because of 'Author' role can *not*
# be found when searching for his other 'Whatever' role. # be found when searching for his other 'Whatever' role.
......
...@@ -9,7 +9,7 @@ if context.hasDocumentReference(): ...@@ -9,7 +9,7 @@ if context.hasDocumentReference():
else: else:
message_reference = portal.portal_preferences.getPreferredCredentialPasswordRecoveryMessageReference() message_reference = portal.portal_preferences.getPreferredCredentialPasswordRecoveryMessageReference()
if message_reference is None: if message_reference is None:
raise ValueError, "Preference not configured" raise ValueError("Preference not configured")
notification_message = portal.NotificationTool_getDocumentValue(message_reference, notification_message = portal.NotificationTool_getDocumentValue(message_reference,
context.getLanguage()) context.getLanguage())
......
...@@ -17,7 +17,7 @@ if context.hasDocumentReference(): ...@@ -17,7 +17,7 @@ if context.hasDocumentReference():
else: else:
message_reference = portal.portal_preferences.getPreferredCredentialUsernameRecoveryMessageReference() message_reference = portal.portal_preferences.getPreferredCredentialUsernameRecoveryMessageReference()
if message_reference is None: if message_reference is None:
raise ValueError, "Preference not configured" raise ValueError("Preference not configured")
notification_message = portal.NotificationTool_getDocumentValue(message_reference, notification_message = portal.NotificationTool_getDocumentValue(message_reference,
context.getLanguage()) context.getLanguage())
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
#Don't allow to call from url #Don't allow to call from url
if REQUEST: if REQUEST:
raise ValueError, "You can not call this script from the url" raise ValueError("You can not call this script from the url")
portal = context.getPortalObject() portal = context.getPortalObject()
portal_preferences = context.portal_preferences portal_preferences = context.portal_preferences
...@@ -27,7 +27,7 @@ if user_id and login.hasPassword(): ...@@ -27,7 +27,7 @@ if user_id and login.hasPassword():
reference = context.getReference() reference = context.getReference()
if not login.hasReference(): if not login.hasReference():
if not reference: if not reference:
raise ValueError, "Impossible to create an account without login" raise ValueError("Impossible to create an account without login")
login.setReference(reference) login.setReference(reference)
if not user_id: if not user_id:
person.setUserId(reference) person.setUserId(reference)
......
...@@ -16,7 +16,7 @@ notification_reference = 'credential_request-confirmation-%s' % notification_typ ...@@ -16,7 +16,7 @@ notification_reference = 'credential_request-confirmation-%s' % notification_typ
notification_message = portal.portal_notifications.getDocumentValue(reference=notification_reference, notification_message = portal.portal_notifications.getDocumentValue(reference=notification_reference,
language=recipient.getLanguage()) language=recipient.getLanguage())
if notification_message is None: if notification_message is None:
raise ValueError, 'Unable to found Notification Message with reference "%s".' % notification_reference raise ValueError('Unable to found Notification Message with reference "%s".' % notification_reference)
#Set notification mapping #Set notification mapping
notification_mapping_dict = {'login_name': login} notification_mapping_dict = {'login_name': login}
......
...@@ -3,7 +3,7 @@ Proxy ...@@ -3,7 +3,7 @@ Proxy
Manager -- allow to update all image property""" Manager -- allow to update all image property"""
if REQUEST is not None: if REQUEST is not None:
raise ValueError, "This script can not be call from url" raise ValueError("This script can not be call from url")
def getAccessor(prop): def getAccessor(prop):
return "".join([x.capitalize() for x in prop.split('_')]) return "".join([x.capitalize() for x in prop.split('_')])
......
...@@ -8,4 +8,4 @@ Assignee -- allow to check credential informations""" ...@@ -8,4 +8,4 @@ Assignee -- allow to check credential informations"""
for portal_type in destination_decision_type: for portal_type in destination_decision_type:
destination = context.getDestinationDecisionValue(portal_type=portal_type) destination = context.getDestinationDecisionValue(portal_type=portal_type)
if destination is None: if destination is None:
raise ValueError, '%s request must be in relation with a %s' % (context.getPortalType(),portal_type) raise ValueError('%s request must be in relation with a %s' % (context.getPortalType(),portal_type))
...@@ -14,16 +14,16 @@ if context.getPassword(): ...@@ -14,16 +14,16 @@ if context.getPassword():
if login.getReference() == reference: if login.getReference() == reference:
break break
else: else:
raise RuntimeError, 'Person %s does not have a validated Login with reference %r' % \ raise RuntimeError('Person %s does not have a validated Login with reference %r'
(person.getRelativeUrl(), reference) % (person.getRelativeUrl(), reference))
else: # BBB when login reference is not set in Credential Update document. else: # BBB when login reference is not set in Credential Update document.
if login_list: if login_list:
user_id = person.Person_getUserId() user_id = person.Person_getUserId()
login = sorted(login_list, login = sorted(login_list,
key=lambda x:x.getReference() == user_id, reverse=True)[0] key=lambda x:x.getReference() == user_id, reverse=True)[0]
else: else:
raise RuntimeError, 'Person %s does not have a validated Login with reference %r' % \ raise RuntimeError('Person %s does not have a validated Login with reference %r'
(person.getRelativeUrl(), reference) % (person.getRelativeUrl(), reference))
else: else:
# BBB # BBB
login = person login = person
......
...@@ -47,7 +47,7 @@ elif direction == 'incoming': ...@@ -47,7 +47,7 @@ elif direction == 'incoming':
destination_url = destination or person destination_url = destination or person
destination_section_url = organisation destination_section_url = organisation
else: else:
raise NotImplementedError, 'The specified direction is not handled: %r' % (direction,) raise NotImplementedError('The specified direction is not handled: %r' % (direction,))
event_kw = { event_kw = {
'portal_type' : portal_type, 'portal_type' : portal_type,
......
...@@ -110,7 +110,7 @@ class CrmTestCase(ERP5ReportTestCase): ...@@ -110,7 +110,7 @@ class CrmTestCase(ERP5ReportTestCase):
ev = self.event_module.newContent(portal_type=portal_type,**kw) ev = self.event_module.newContent(portal_type=portal_type,**kw)
if simulation_state == 'assigned': if simulation_state == 'assigned':
raise NotImplementedError, '%r state only exists in the old event workflow.' % simulation_state raise NotImplementedError('%r state only exists in the old event workflow.' % simulation_state)
""" """
ticket=self.portal.restrictedTraverse(ev.getFollowUp()) ticket=self.portal.restrictedTraverse(ev.getFollowUp())
self._doWorkflowAction(ev,'assign_action', self._doWorkflowAction(ev,'assign_action',
...@@ -120,7 +120,7 @@ class CrmTestCase(ERP5ReportTestCase): ...@@ -120,7 +120,7 @@ class CrmTestCase(ERP5ReportTestCase):
elif simulation_state == 'planned': elif simulation_state == 'planned':
ev.plan() ev.plan()
elif simulation_state == 'posted': elif simulation_state == 'posted':
raise NotImplementedError, '%r state only exists in the old event workflow.' % simulation_state raise NotImplementedError('%r state only exists in the old event workflow.' % simulation_state)
""" """
ev.start() ev.start()
""" """
...@@ -128,12 +128,12 @@ class CrmTestCase(ERP5ReportTestCase): ...@@ -128,12 +128,12 @@ class CrmTestCase(ERP5ReportTestCase):
ev.start() ev.start()
ev.deliver() ev.deliver()
elif simulation_state == 'new': elif simulation_state == 'new':
raise NotImplementedError, '%r state only exists in the old event workflow.' % simulation_state raise NotImplementedError('%r state only exists in the old event workflow.' % simulation_state)
""" """
ev.receive() ev.receive()
""" """
elif simulation_state == 'acknowledged': elif simulation_state == 'acknowledged':
raise NotImplementedError, '%r state only exists in the old event workflow.' % simulation_state raise NotImplementedError('%r state only exists in the old event workflow.' % simulation_state)
""" """
ticket=self.portal.restrictedTraverse(ev.getFollowUp()) ticket=self.portal.restrictedTraverse(ev.getFollowUp())
self._doWorkflowAction(ev,'assign_action', self._doWorkflowAction(ev,'assign_action',
...@@ -147,13 +147,13 @@ class CrmTestCase(ERP5ReportTestCase): ...@@ -147,13 +147,13 @@ class CrmTestCase(ERP5ReportTestCase):
elif simulation_state == 'deleted': elif simulation_state == 'deleted':
ev.delete() ev.delete()
elif simulation_state == 'expired': elif simulation_state == 'expired':
raise NotImplementedError, '%r state only exists in the old event workflow.' % simulation_state raise NotImplementedError('%r state only exists in the old event workflow.' % simulation_state)
""" """
ev.receive() ev.receive()
ev.expire() ev.expire()
""" """
elif simulation_state == 'responded': elif simulation_state == 'responded':
raise NotImplementedError, '%r state only exists in the old event workflow.' % simulation_state raise NotImplementedError('%r state only exists in the old event workflow.' % simulation_state)
""" """
ev.receive() ev.receive()
ev.respond() ev.respond()
...@@ -161,7 +161,7 @@ class CrmTestCase(ERP5ReportTestCase): ...@@ -161,7 +161,7 @@ class CrmTestCase(ERP5ReportTestCase):
elif simulation_state == 'started': elif simulation_state == 'started':
ev.start() ev.start()
elif simulation_state == 'ordered': elif simulation_state == 'ordered':
raise NotImplementedError, '%r state only exists in the old event workflow.' % simulation_state raise NotImplementedError('%r state only exists in the old event workflow.' % simulation_state)
""" """
ev.plan() ev.plan()
ev.order() ev.order()
......
...@@ -24,7 +24,7 @@ follow_up = event.getFollowUp() ...@@ -24,7 +24,7 @@ follow_up = event.getFollowUp()
if follow_up is None: if follow_up is None:
if not (follow_up_ticket_type and follow_up_ticket_title): if not (follow_up_ticket_type and follow_up_ticket_title):
raise ValueError, 'Follow up must not empty when assign or acknowledge.' raise ValueError('Follow up must not empty when assign or acknowledge.')
if follow_up is None and follow_up_ticket_type and follow_up_ticket_title: if follow_up is None and follow_up_ticket_type and follow_up_ticket_title:
event.Event_createFollowUpTicket(follow_up_ticket_title, event.Event_createFollowUpTicket(follow_up_ticket_title,
......
...@@ -17,7 +17,7 @@ with portal.Localizer.translationContext(localizer_language): ...@@ -17,7 +17,7 @@ with portal.Localizer.translationContext(localizer_language):
if field.getRecursiveTemplateField().meta_type == 'ReportBox': if field.getRecursiveTemplateField().meta_type == 'ReportBox':
report_section_list.extend(field.render()) report_section_list.extend(field.render())
else: else:
raise ValueError, 'form meta_type (%r) unknown' %(form.meta_type,) raise ValueError('form meta_type (%r) unknown' %(form.meta_type,))
report_title = portal.Base_translateString((form.getProperty('title'))) report_title = portal.Base_translateString((form.getProperty('title')))
......
...@@ -36,7 +36,7 @@ def Base_runPythonScript(self, code): ...@@ -36,7 +36,7 @@ def Base_runPythonScript(self, code):
code = '\n'.join(code_line_list) code = '\n'.join(code_line_list)
script.write(code) script.write(code)
if script._code is None: if script._code is None:
raise ValueError, repr(script.errors) raise ValueError(repr(script.errors))
return script() return script()
......
...@@ -119,7 +119,7 @@ if send_notification_text not in ('', None): ...@@ -119,7 +119,7 @@ if send_notification_text not in ('', None):
notification_reference = 'forum-new-thread' notification_reference = 'forum-new-thread'
notification_message = context.NotificationTool_getDocumentValue(notification_reference, 'en') notification_message = context.NotificationTool_getDocumentValue(notification_reference, 'en')
if notification_message is None: if notification_message is None:
raise ValueError, 'Unable to found Notification Message with reference "%s".' % notification_reference raise ValueError('Unable to found Notification Message with reference "%s".' % notification_reference)
notification_mapping_dict = {'subject': discussion_thread.getTitle(), notification_mapping_dict = {'subject': discussion_thread.getTitle(),
'url': discussion_thread.absolute_url(), 'url': discussion_thread.absolute_url(),
......
...@@ -27,7 +27,7 @@ if searchabletext is None: ...@@ -27,7 +27,7 @@ if searchabletext is None:
searchabletext = selection_object.get('searchabletext') searchabletext = selection_object.get('searchabletext')
if searchabletext is None: if searchabletext is None:
raise ValueError, "No search string specified." raise ValueError("No search string specified.")
parsed_search_string = context.Base_parseSearchString(searchabletext) parsed_search_string = context.Base_parseSearchString(searchabletext)
......
...@@ -34,7 +34,7 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment ...@@ -34,7 +34,7 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment
if root: category_value=category_value.split('/')[0] if root: category_value=category_value.split('/')[0]
category_dict[base_category] = category_value category_dict[base_category] = category_value
else: else:
raise RuntimeError, "Error: '%s' property is required in order to update person security group" % (base_category) raise RuntimeError("Error: '%s' property is required in order to update person security group" % base_category)
category_list.append(category_dict) category_list.append(category_dict)
# if not strict, we go up the hierarchy (because if you work in group/a/b/c, chances are you # if not strict, we go up the hierarchy (because if you work in group/a/b/c, chances are you
# are working in group/a/b, too :) # are working in group/a/b, too :)
......
...@@ -15,7 +15,7 @@ for ob in obj.getDestinationValueList(): ...@@ -15,7 +15,7 @@ for ob in obj.getDestinationValueList():
if category_value not in (None, ''): if category_value not in (None, ''):
category_dict[base_category] = category_value category_dict[base_category] = category_value
else: else:
raise RuntimeError, "Error: '%s' property is required in order to update person security group" % (base_category) raise RuntimeError("Error: '%s' property is required in order to update person security group" % base_category)
category_list.append(category_dict) category_list.append(category_dict)
log(category_list) log(category_list)
......
...@@ -18,7 +18,7 @@ for base_category in base_category_list: ...@@ -18,7 +18,7 @@ for base_category in base_category_list:
if category_value not in (None, ''): if category_value not in (None, ''):
category_dict[base_category] = category_value category_dict[base_category] = category_value
else: else:
raise RuntimeError, "Error: '%s' property is required in order to update person security group" % (base_category) raise RuntimeError("Error: '%s' property is required in order to update person security group" % base_category)
category_list.append(category_dict) category_list.append(category_dict)
return category_list return category_list
...@@ -153,4 +153,4 @@ def setGuard(self, guard): ...@@ -153,4 +153,4 @@ def setGuard(self, guard):
if isinstance(self, TransitionDefinition): if isinstance(self, TransitionDefinition):
self.guard = guard self.guard = guard
else: else:
raise ValueError, "not a TransitionDefinition" raise ValueError("not a TransitionDefinition")
...@@ -122,7 +122,7 @@ try: ...@@ -122,7 +122,7 @@ try:
def __call__(self): def __call__(self):
current_time = time.time() current_time = time.time()
if current_time - self.client.creation_time > self.client.getTimeout(): if current_time - self.client.creation_time > self.client.getTimeout():
raise SubversionTimeoutError, 'too long transaction' raise SubversionTimeoutError('too long transaction')
#return True #return True
return False return False
...@@ -355,7 +355,7 @@ try: ...@@ -355,7 +355,7 @@ try:
def info(self, path): def info(self, path):
if not os.path.exists(path): if not os.path.exists(path):
raise ValueError, "Repository %s does not exist" % path raise ValueError("Repository %s does not exist" % path)
# symlinks are not well supported by pysvn # symlinks are not well supported by pysvn
if os.path.islink(path): if os.path.islink(path):
path = os.path.realpath(path) path = os.path.realpath(path)
...@@ -368,7 +368,7 @@ try: ...@@ -368,7 +368,7 @@ try:
else: else:
raise error raise error
if entry is None: if entry is None:
raise ValueError, "Could not open SVN repository %s" % path raise ValueError("Could not open SVN repository %s" % path)
# transform entry to dict to make it more usable in zope # transform entry to dict to make it more usable in zope
members_tuple = ('url', 'uuid', 'revision', 'kind', \ members_tuple = ('url', 'uuid', 'revision', 'kind', \
'commit_author', 'commit_revision', 'commit_time',) 'commit_author', 'commit_revision', 'commit_time',)
...@@ -413,4 +413,4 @@ except ImportError: ...@@ -413,4 +413,4 @@ except ImportError:
'could not import pysvn; until pysvn is installed properly,' 'could not import pysvn; until pysvn is installed properly,'
' this tool will not work.', error=True) ' this tool will not work.', error=True)
def newSubversionClient(container, **kw): def newSubversionClient(container, **kw):
raise SubversionInstallationError, 'pysvn library is not installed' raise SubversionInstallationError('pysvn library is not installed')
...@@ -37,7 +37,7 @@ if to_url is None: ...@@ -37,7 +37,7 @@ if to_url is None:
else: else:
to_url_list.append(email) to_url_list.append(email)
else: else:
raise ValueError, 'Recipient %s has no defined email' % recipient raise ValueError('Recipient %s has no defined email' % recipient)
elif same_type(to_url, ''): elif same_type(to_url, ''):
to_url_list.append(to_url) to_url_list.append(to_url)
......
...@@ -11,7 +11,7 @@ request = container.REQUEST ...@@ -11,7 +11,7 @@ request = container.REQUEST
response = request.RESPONSE response = request.RESPONSE
if import_filename=='': if import_filename=='':
raise ValueError, "You must upload a file" raise ValueError("You must upload a file")
def addReportLine(error, category, message): def addReportLine(error, category, message):
report_line = newTempBase(context, 'item') report_line = newTempBase(context, 'item')
...@@ -22,9 +22,8 @@ def invalid_category_spreadsheet_handler(message): ...@@ -22,9 +22,8 @@ def invalid_category_spreadsheet_handler(message):
# action taken when an invalid spreadsheet is provided. # action taken when an invalid spreadsheet is provided.
# we *raise* a Redirect, because we don't want the transaction to succeed # we *raise* a Redirect, because we don't want the transaction to succeed
# note, we could make a dialog parameter to allow import invalid spreadsheet: # note, we could make a dialog parameter to allow import invalid spreadsheet:
raise 'Redirect', '%s/view?portal_status_message=%s' % ( context.Base_redirect('view', keep_items={'portal_status_message':message},
context.portal_categories.absolute_url(), abort_transaction=True)
message)
category_list_mapping = context.Base_getCategoriesSpreadSheetMapping(import_file, category_list_mapping = context.Base_getCategoriesSpreadSheetMapping(import_file,
invalid_spreadsheet_error_handler=invalid_category_spreadsheet_handler) invalid_spreadsheet_error_handler=invalid_category_spreadsheet_handler)
......
...@@ -61,7 +61,7 @@ for i in catalog(portal_type='Glossary Term', ...@@ -61,7 +61,7 @@ for i in catalog(portal_type='Glossary Term',
if translated_title: if translated_title:
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),
...@@ -69,7 +69,7 @@ for i in catalog(portal_type='Glossary Term', ...@@ -69,7 +69,7 @@ for i in catalog(portal_type='Glossary 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),
......
...@@ -8,7 +8,7 @@ for listbox_line in listbox_line_list: ...@@ -8,7 +8,7 @@ for listbox_line in listbox_line_list:
if not choice: if not choice:
continue continue
elif len(choice) > 1: elif len(choice) > 1:
raise ValueError, 'Unknown choice %s' % choice raise ValueError('Unknown choice %s' % choice)
else: else:
choice = choice[0] choice = choice[0]
if choice.startswith('0_'): if choice.startswith('0_'):
...@@ -29,6 +29,6 @@ for listbox_line in listbox_line_list: ...@@ -29,6 +29,6 @@ for listbox_line in listbox_line_list:
# skin_folder.manage_addProduct['ERP5Form'].addERP5Form(id=form_id, title='') # skin_folder.manage_addProduct['ERP5Form'].addERP5Form(id=form_id, title='')
# raise NotImplementedError # raise NotImplementedError
else: else:
raise ValueError, 'Unknown choice %s' % choice raise ValueError('Unknown choice %s' % choice)
context.Base_redirect() context.Base_redirect()
...@@ -39,7 +39,7 @@ if len(failed_path_list): ...@@ -39,7 +39,7 @@ if len(failed_path_list):
context.activate(activity='SQLQueue', priority=5).SQLCatalog_deferFullTextIndexActivity(path_list=failed_path_list) context.activate(activity='SQLQueue', priority=5).SQLCatalog_deferFullTextIndexActivity(path_list=failed_path_list)
else: else:
# if all objects are failed one, just raise an exception to avoid infinite loop. # if all objects are failed one, just raise an exception to avoid infinite loop.
raise AttributeError, 'exception %r raised in indexing %r' % (exception, failed_path_list) raise AttributeError('exception %r raised in indexing %r' % (exception, failed_path_list))
if parameter_dict: if parameter_dict:
return method(**parameter_dict) return method(**parameter_dict)
...@@ -39,7 +39,7 @@ if len(failed_path_list): ...@@ -39,7 +39,7 @@ if len(failed_path_list):
context.activate(activity='SQLQueue', priority=5, serialization_tag='sphinxse_indexing').SQLCatalog_deferFullTextIndexActivity(path_list=failed_path_list) context.activate(activity='SQLQueue', priority=5, serialization_tag='sphinxse_indexing').SQLCatalog_deferFullTextIndexActivity(path_list=failed_path_list)
else: else:
# if all objects are failed one, just raise an exception to avoid infinite loop. # if all objects are failed one, just raise an exception to avoid infinite loop.
raise AttributeError, 'exception %r raised in indexing %r' % (exception, failed_path_list) raise AttributeError('exception %r raised in indexing %r' % (exception, failed_path_list))
if parameter_dict: if parameter_dict:
method(**parameter_dict) method(**parameter_dict)
......
...@@ -3,7 +3,7 @@ the new Invoice. ...@@ -3,7 +3,7 @@ the new Invoice.
""" """
if related_simulation_movement_path_list is None: if related_simulation_movement_path_list is None:
raise RuntimeError, 'related_simulation_movement_path_list is missing. Update ERP5 Product.' raise RuntimeError('related_simulation_movement_path_list is missing. Update ERP5 Product.')
invoice = context invoice = context
......
...@@ -696,8 +696,8 @@ class TestProductionOrderMixin(TestOrderMixin): ...@@ -696,8 +696,8 @@ class TestProductionOrderMixin(TestOrderMixin):
LOG('object.getDeliveryValue()', 0, delivery_value) LOG('object.getDeliveryValue()', 0, delivery_value)
if delivery_value is not None: if delivery_value is not None:
LOG('object.getDeliveryValue().getQuantity()',0,delivery_value.getQuantity()) LOG('object.getDeliveryValue().getQuantity()',0,delivery_value.getQuantity())
raise AssertionError, "Attribute: %s, Value: %s, Result: %s" %\ raise AssertionError("Attribute: %s, Value: %s, Result: %s"
(attribute, value, getattr(object, attribute)()) % (attribute, value, getattr(object, attribute)()))
def stepCheckProductionSimulation(self, sequence=None, sequence_list=None, def stepCheckProductionSimulation(self, sequence=None, sequence_list=None,
**kw): **kw):
......
...@@ -25,7 +25,7 @@ def order_line_list(line_list, current_structure, depth=0, index=0, last_dict=No ...@@ -25,7 +25,7 @@ def order_line_list(line_list, current_structure, depth=0, index=0, last_dict=No
index += 1 index += 1
index = order_line_list(line_list, new_structure, depth=new_depth, index=index, last_dict=last_dict) index = order_line_list(line_list, new_structure, depth=new_depth, index=index, last_dict=last_dict)
elif section_depth > (depth +2): elif section_depth > (depth +2):
raise ValueError, "A depth is missing" raise ValueError("A depth is missing")
else: else:
return index return index
if index < len(line_list): if index < len(line_list):
......
...@@ -10,4 +10,4 @@ if active_process_path is not None: ...@@ -10,4 +10,4 @@ if active_process_path is not None:
return '%s lines imported sucessfully' % \ return '%s lines imported sucessfully' % \
len(context.Base_getReportResultList(active_process_path=active_process_path)) len(context.Base_getReportResultList(active_process_path=active_process_path))
raise AttributeError, 'Unable to get the active process' raise AttributeError('Unable to get the active process')
...@@ -114,7 +114,7 @@ else: ...@@ -114,7 +114,7 @@ else:
# portal_type should be the same for all columns # portal_type should be the same for all columns
if portal_type != mapping[spreadsheet_name][0]: if portal_type != mapping[spreadsheet_name][0]:
raise AttributeError, "Portal type is not the same for all columns" raise AttributeError("Portal type is not the same for all columns")
# If no mapping is given # If no mapping is given
if not mapping: if not mapping:
...@@ -165,7 +165,7 @@ else: ...@@ -165,7 +165,7 @@ else:
active_process=active_process_path) active_process=active_process_path)
if getattr(context, import_file_line_script, None) is None: if getattr(context, import_file_line_script, None) is None:
raise AttributeError, 'specified script "%s" does not exists' % import_file_line_script raise AttributeError('specified script "%s" does not exists' % import_file_line_script)
getattr(active_object, import_file_line_script)(context.getRelativeUrl(), getattr(active_object, import_file_line_script)(context.getRelativeUrl(),
portal_type, portal_type,
......
...@@ -30,7 +30,7 @@ for allowed_portal_type in container.allowedContentTypes(): ...@@ -30,7 +30,7 @@ for allowed_portal_type in container.allowedContentTypes():
break break
if portal_type_object is None: if portal_type_object is None:
raise ValueError, 'Disallowed subobject type: %s' % portal_type raise ValueError('Disallowed subobject type: %s' % portal_type)
else: else:
# Default result # Default result
success = 1 success = 1
......
...@@ -21,4 +21,4 @@ for sale_trade_condition in sale_trade_condition_list: ...@@ -21,4 +21,4 @@ for sale_trade_condition in sale_trade_condition_list:
if periodicity_line.getResourceUid()==resource_uid: if periodicity_line.getResourceUid()==resource_uid:
return [periodicity_line] return [periodicity_line]
raise RuntimeError, 'Cannot find an appropriate Periodicity Line for the movement: %s' % context.getRelativeUrl() raise RuntimeError('Cannot find an appropriate Periodicity Line for the movement: %s' % context.getRelativeUrl())
if related_simulation_movement_path_list is None: if related_simulation_movement_path_list is None:
raise RuntimeError, 'related_simulation_movement_path_list is missing. Update ERP5 Product.' raise RuntimeError('related_simulation_movement_path_list is missing. Update ERP5 Product.')
open_sale_order = context.getCausalityValue() open_sale_order = context.getCausalityValue()
......
...@@ -54,7 +54,7 @@ class PeriodicityLineMixin(PeriodicityMixin): ...@@ -54,7 +54,7 @@ class PeriodicityLineMixin(PeriodicityMixin):
if scope_type: if scope_type:
method = self._getTypeBasedMethod('calculateScopeTypeStopDate') method = self._getTypeBasedMethod('calculateScopeTypeStopDate')
if method is None: if method is None:
raise RuntimeError, 'Type based method calculateScopeTypeStopDate does not exist.' raise RuntimeError('Type based method calculateScopeTypeStopDate does not exist.')
else: else:
return method(scope_type, start_date) return method(scope_type, start_date)
elif time_scale: elif time_scale:
...@@ -62,7 +62,7 @@ class PeriodicityLineMixin(PeriodicityMixin): ...@@ -62,7 +62,7 @@ class PeriodicityLineMixin(PeriodicityMixin):
day = length_number day = length_number
return start_date+day return start_date+day
else: else:
raise RuntimeError, 'Unknown time scale: %s' % time_scale raise RuntimeError('Unknown time scale: %s' % time_scale)
else: else:
return None return None
......
...@@ -28,4 +28,4 @@ elif scope_type=='until_the_end_of_month': ...@@ -28,4 +28,4 @@ elif scope_type=='until_the_end_of_month':
return DateTime(year, month, day) return DateTime(year, month, day)
return getEndOfMonth(start_date) return getEndOfMonth(start_date)
raise ValueError, 'Unknown scope type: %s' % scope_type raise ValueError('Unknown scope type: %s' % scope_type)
...@@ -45,8 +45,9 @@ if matrixbox : ...@@ -45,8 +45,9 @@ if matrixbox :
translateString('${contribution_share_title} (Amount or Percent)', translateString('${contribution_share_title} (Amount or Percent)',
mapping=dict(contribution_share_title=category_item[0])))) mapping=dict(contribution_share_title=category_item[0]))))
else: else:
raise ValueError, "PaySheetModelLine_asCellRange: the two categories "\ raise ValueError(
"must could be only contribution_share and salary_range" "%s: base category must be either contribution_share or salary_range"
% script.id)
cell_range.append(category_cell_range) cell_range.append(category_cell_range)
cell_range = filter(lambda x: x != [], cell_range) cell_range = filter(lambda x: x != [], cell_range)
......
...@@ -9,7 +9,7 @@ category_list = [] ...@@ -9,7 +9,7 @@ category_list = []
for category in context.getVariationSettingsCategoryList(): for category in context.getVariationSettingsCategoryList():
category_name = category.replace('salary_range/','',1) category_name = category.replace('salary_range/','',1)
if context.portal_categories.getCategoryValue(category) is None: if context.portal_categories.getCategoryValue(category) is None:
raise ValueError, 'no category %s' % category raise ValueError('no category %s' % category)
else: else:
if matrixbox: if matrixbox:
category_list.extend(context.portal_categories.getCategoryValue(category).getCategoryChildLogicalPathItemList(checked_permission='View', is_right_display=1, base=1)[1:]) category_list.extend(context.portal_categories.getCategoryValue(category).getCategoryChildLogicalPathItemList(checked_permission='View', is_right_display=1, base=1)[1:])
......
...@@ -105,9 +105,9 @@ def getSocialOrganisationValue(): ...@@ -105,9 +105,9 @@ def getSocialOrganisationValue():
business_path_list = business_process.getTradeModelPathValueList(trade_phase=\ business_path_list = business_process.getTradeModelPathValueList(trade_phase=\
'payroll/invoicing/social_security', context=context) 'payroll/invoicing/social_security', context=context)
if len(business_path_list) > 1: if len(business_path_list) > 1:
raise NotImplementedError, 'For now, it can not support more '\ raise NotImplementedError('For now, it can not support more'
'than one business_path with same trade_phase. '\ ' than one business_path with same trade_phase.'
'%s have same trade_phase' % repr(business_path_list) ' %r have same trade_phase' % business_path_list)
if len(business_path_list) == 1: if len(business_path_list) == 1:
business_path = business_path_list[0] business_path = business_path_list[0]
return business_path.getSourceSectionValue() return business_path.getSourceSectionValue()
......
...@@ -26,7 +26,7 @@ base_contribution_uid_list = [] ...@@ -26,7 +26,7 @@ base_contribution_uid_list = []
for category in base_contribution_list: for category in base_contribution_list:
category_value = base_amount.restrictedTraverse(category) category_value = base_amount.restrictedTraverse(category)
if category_value is None: if category_value is None:
raise ValueError, 'Category "%s/%s" not found.' % (base_amount.getPath(), category) raise ValueError('Category "%s/%s" not found.' % (base_amount.getPath(), category))
base_contribution_uid_list.append(category_value.getUid()) base_contribution_uid_list.append(category_value.getUid())
params = { params = {
......
...@@ -22,8 +22,8 @@ for paysheet in paysheet_list: ...@@ -22,8 +22,8 @@ for paysheet in paysheet_list:
if annotation_line is None: if annotation_line is None:
annotation_line = getattr(paysheet, 'work_time_annotation_line', None) annotation_line = getattr(paysheet, 'work_time_annotation_line', None)
if annotation_line is None: if annotation_line is None:
raise ValueError, "Paysheet %s has no Annotation Line with reference work_time_annotation_line"\ raise ValueError("Paysheet %s has no Annotation Line with reference work_time_annotation_line"
% paysheet.getRelativeUrl() % paysheet.getRelativeUrl())
nb_heures = annotation_line.getQuantity() nb_heures = annotation_line.getQuantity()
yearly_work_time += nb_heures yearly_work_time += nb_heures
......
...@@ -172,7 +172,7 @@ class PayzenService(XMLObject, PayzenREST): ...@@ -172,7 +172,7 @@ class PayzenService(XMLObject, PayzenREST):
# backward compatibility: # backward compatibility:
message_list.append(err[3]) message_list.append(err[3])
if message_list: if message_list:
raise ValidationFailed, message_list raise ValidationFailed(message_list)
temp_document = self.newContent(temp_object=True, portal_type='Document', id='id') temp_document = self.newContent(temp_object=True, portal_type='Document', id='id')
temp_document.edit( temp_document.edit(
......
...@@ -97,9 +97,9 @@ for task_line in result_list: ...@@ -97,9 +97,9 @@ for task_line in result_list:
source_uid = task_line.node_uid source_uid = task_line.node_uid
if source_uid is None: if source_uid is None:
# This should not happens, so display an error message # This should not happens, so display an error message
raise ValueError, context.Base_translateString(\ raise ValueError(context.Base_translateString(
"This task should have a source : ${task_relative_url}", "This task should have a source : ${task_relative_url}",
mapping = {'task_relative_url': task_line.getRelativeUrl()}) mapping = {'task_relative_url': task_line.getRelativeUrl()}))
source_dict = source_uid_dict.get(source_uid, None) source_dict = source_uid_dict.get(source_uid, None)
if source_dict is None: if source_dict is None:
source_value = task_line.getSourceValue() source_value = task_line.getSourceValue()
......
...@@ -19,7 +19,7 @@ if selection is not None: ...@@ -19,7 +19,7 @@ if selection is not None:
elif selection.report_path == 'parent': elif selection.report_path == 'parent':
return context.searchFolder(**kw) return context.searchFolder(**kw)
else: else:
raise NotImplementedError, "Unknow domain %s" % selection.report_path raise NotImplementedError("Unknow domain %s" % selection.report_path)
return context.portal_catalog(**kw) return context.portal_catalog(**kw)
......
...@@ -33,7 +33,7 @@ for task in task_list: ...@@ -33,7 +33,7 @@ for task in task_list:
update_kw['real_start_date'] = task_line.getStartDate() update_kw['real_start_date'] = task_line.getStartDate()
update_kw['real_stop_date'] = task_line.getStopDate() update_kw['real_stop_date'] = task_line.getStopDate()
else: else:
raise ValueError, "This script more than one causality yet" raise ValueError("This script more than one causality yet")
elif task_line.getPortalType() == 'Task Line': elif task_line.getPortalType() == 'Task Line':
update_kw['initial_quantity'] = task_line.getQuantity() update_kw['initial_quantity'] = task_line.getQuantity()
update_kw['initial_start_date'] = task_line.getStartDate() update_kw['initial_start_date'] = task_line.getStartDate()
......
"""Export the current selection in task report module in iCalendar format. """Export the current selection in task report module in iCalendar format.
""" """
from zExceptions import Unauthorized
# XXX bypass CookieCrumbler # XXX bypass CookieCrumbler
if context.REQUEST.AUTHENTICATED_USER.getUserName() == 'Anonymous User': if context.REQUEST.AUTHENTICATED_USER.getUserName() == 'Anonymous User':
if context.REQUEST.get('disable_cookie_login__', 0) \ if context.REQUEST.get('disable_cookie_login__', 0) \
or context.REQUEST.get('no_infinite_loop', 0) : or context.REQUEST.get('no_infinite_loop', 0) :
raise 'Unauthorized', context raise Unauthorized(context)
return context.REQUEST.RESPONSE.redirect(script.id + "?disable_cookie_login__=1&no_infinite_loop=1") return context.REQUEST.RESPONSE.redirect(script.id + "?disable_cookie_login__=1&no_infinite_loop=1")
def formatDate(date): def formatDate(date):
......
if related_simulation_movement_path_list is None: if related_simulation_movement_path_list is None:
raise RuntimeError, 'related_simulation_movement_path_list is missing. Update ERP5 Product.' raise RuntimeError('related_simulation_movement_path_list is missing. Update ERP5 Product.')
if REQUEST is not None: if REQUEST is not None:
from zExceptions import Unauthorized from zExceptions import Unauthorized
......
...@@ -50,7 +50,7 @@ class SecurePaymentTool(BaseTool): ...@@ -50,7 +50,7 @@ class SecurePaymentTool(BaseTool):
if len(result) > 0: if len(result) > 0:
return result[0].getObject().__of__(self) return result[0].getObject().__of__(self)
raise ValueError, "Impossible to find a payment service with '%s' reference" % service_reference raise ValueError("Impossible to find a payment service with '%s' reference" % service_reference)
def _loginAsSuperUser(self): def _loginAsSuperUser(self):
user = getSecurityManager().getUser() user = getSecurityManager().getUser()
......
...@@ -172,7 +172,7 @@ class EssendexGateway(XMLObject): ...@@ -172,7 +172,7 @@ class EssendexGateway(XMLObject):
return message_ids.split(",") return message_ids.split(",")
elif result['Result'] == "Error": elif result['Result'] == "Error":
#we get an error when call the gateway #we get an error when call the gateway
raise SMSGatewayError, urllib.unquote(result.get('Message', "Impossible to send the SMS")) raise SMSGatewayError(urllib.unquote(result.get('Message', "Impossible to send the SMS")))
elif result['Result'] == "Test": elif result['Result'] == "Test":
#just a test, no message id #just a test, no message id
return None return None
...@@ -199,7 +199,7 @@ class EssendexGateway(XMLObject): ...@@ -199,7 +199,7 @@ class EssendexGateway(XMLObject):
return result.get('MessageStatus').lower() return result.get('MessageStatus').lower()
elif result['Result'] == "Error": elif result['Result'] == "Error":
#we get an error when call the gateway #we get an error when call the gateway
raise SMSGatewayError, urllib.unquote(result.get('Message', "Impossible to get the message status")) raise SMSGatewayError(urllib.unquote(result.get('Message', "Impossible to get the message status")))
security.declarePublic('receive') security.declarePublic('receive')
def receive(self, REQUEST, **kw): def receive(self, REQUEST, **kw):
...@@ -209,7 +209,7 @@ class EssendexGateway(XMLObject): ...@@ -209,7 +209,7 @@ class EssendexGateway(XMLObject):
datas = REQUEST['BODY'] datas = REQUEST['BODY']
if not datas: if not datas:
raise SMSGatewayError, "Impossible to notify nothing" raise SMSGatewayError("Impossible to notify nothing")
#Get current user #Get current user
sm = getSecurityManager() sm = getSecurityManager()
...@@ -231,18 +231,18 @@ class EssendexGateway(XMLObject): ...@@ -231,18 +231,18 @@ class EssendexGateway(XMLObject):
#Check Account id #Check Account id
if xml['AccountId'] != self.getGatewayAccountId(): if xml['AccountId'] != self.getGatewayAccountId():
raise Unauthorized, 'Bad accound id (%s)' % xml['AccountId'] raise Unauthorized('Bad accound id (%s)' % xml['AccountId'])
if notification_type == 'InboundMessage': if notification_type == 'InboundMessage':
self.notifyReception(xml) self.notifyReception(xml)
elif notification_type == 'MessageDelivered': elif notification_type == 'MessageDelivered':
self.notifyDelivery(xml) self.notifyDelivery(xml)
elif notification_type == 'MessageError': elif notification_type == 'MessageError':
raise SMSGatewayError, "'MessageError' notification is not implemented (%s)" % str(kw) raise SMSGatewayError("'MessageError' notification is not implemented (%s)" % str(kw))
elif notification_type == 'SubscriptionEvent': elif notification_type == 'SubscriptionEvent':
raise SMSGatewayError, "'MessageError' notification is not implemented (%s)" % str(kw) raise SMSGatewayError("'MessageError' notification is not implemented (%s)" % str(kw))
else: else:
raise SMSGatewayError, "Unknow '%s' notification (%s)" % (notification_type, str(kw)) raise SMSGatewayError("Unknow '%s' notification (%s)" % (notification_type, str(kw)))
finally: finally:
#Restore orinal user #Restore orinal user
setSecurityManager(sm) setSecurityManager(sm)
...@@ -345,6 +345,6 @@ class EssendexGateway(XMLObject): ...@@ -345,6 +345,6 @@ class EssendexGateway(XMLObject):
LOG("EssendexGateway", INFO, result) LOG("EssendexGateway", INFO, result)
elif result['Result'] == "Error": elif result['Result'] == "Error":
#we get an error when call the gateway #we get an error when call the gateway
raise SMSGatewayError, urllib.unquote(result.get('Message', "Impossible to get last message list")) raise SMSGatewayError(urllib.unquote(result.get('Message', "Impossible to get last message list")))
...@@ -189,7 +189,7 @@ class MobytGateway(XMLObject): ...@@ -189,7 +189,7 @@ class MobytGateway(XMLObject):
return [result.get('status_info', "")] #return message id (gateway side) return [result.get('status_info', "")] #return message id (gateway side)
elif result['status'] == "KO": elif result['status'] == "KO":
#we get an error when call the gateway #we get an error when call the gateway
raise SMSGatewayError, urllib.unquote(result.get('status_info', "Impossible to send the SMS")) raise SMSGatewayError(urllib.unquote(result.get('status_info', "Impossible to send the SMS")))
elif result['status'] == "Test": elif result['status'] == "Test":
#just a test, no message id #just a test, no message id
return None return None
...@@ -224,7 +224,7 @@ class MobytGateway(XMLObject): ...@@ -224,7 +224,7 @@ class MobytGateway(XMLObject):
elif result['status'] == "KO": elif result['status'] == "KO":
#we get an error when call the gateway #we get an error when call the gateway
raise SMSGatewayError, urllib.unquote(result.get('status_info', "Impossible to get the message status")) raise SMSGatewayError(urllib.unquote(result.get('status_info', "Impossible to get the message status")))
security.declarePublic('receive') security.declarePublic('receive')
def receive(self,REQUEST): def receive(self,REQUEST):
......
...@@ -79,7 +79,7 @@ class VariationEquivalenceTester(Predicate, EquivalenceTesterMixin): ...@@ -79,7 +79,7 @@ class VariationEquivalenceTester(Predicate, EquivalenceTesterMixin):
sorted(prevision_value.items()) sorted(prevision_value.items())
else: else:
# should not happen # should not happen
raise AttributeError, 'prevision and decision values of this divergence tester should be list, tuple or dict.' raise AttributeError('prevision and decision values of this divergence tester should be list, tuple or dict.')
if not result: if not result:
try: try:
# XXX We should use "getTranslatedTestedPropertyTitleList", but it seems to # XXX We should use "getTranslatedTestedPropertyTitleList", but it seems to
......
...@@ -402,11 +402,11 @@ class SyncMLSubscription(XMLObject): ...@@ -402,11 +402,11 @@ class SyncMLSubscription(XMLObject):
try: try:
user = user_folder.getUserById(user_id).__of__(user_folder) # __of__ might got AttributeError user = user_folder.getUserById(user_id).__of__(user_folder) # __of__ might got AttributeError
except AttributeError: except AttributeError:
raise ValueError("User %s cannot be found in user folder, \ raise ValueError("User %s cannot be found in user folder,"
synchronization cannot work with this kind of user" % (user_id,)) " synchronization cannot work with this kind of user" % user_id)
if user is None: if user is None:
raise ValueError("User %s cannot be found in user folder, \ raise ValueError("User %s cannot be found in user folder,"
synchronization cannot work with this kind of user" % (user_id,)) " synchronization cannot work with this kind of user" % user_id)
else: else:
newSecurityManager(None, user) newSecurityManager(None, user)
else: else:
...@@ -1036,11 +1036,11 @@ class SyncMLSubscription(XMLObject): ...@@ -1036,11 +1036,11 @@ class SyncMLSubscription(XMLObject):
else: else:
result_list = query_method(**kw) result_list = query_method(**kw)
else: else:
raise KeyError, 'This Subscriber %s provide no list method:%r'\ raise KeyError('This Subscriber %s provide no list method:%r'
% (self.getPath(), list_method_id) % (self.getPath(), list_method_id))
else: else:
raise KeyError, 'This Subscriber %s provide no list method with id:%r'\ raise KeyError('This Subscriber %s provide no list method with id:%r'
% (self.getPath(), list_method_id) % (self.getPath(), list_method_id))
return result_list return result_list
security.declareProtected(Permissions.ModifyPortalContent, 'generateNewSessionId') security.declareProtected(Permissions.ModifyPortalContent, 'generateNewSessionId')
...@@ -1107,7 +1107,7 @@ class SyncMLSubscription(XMLObject): ...@@ -1107,7 +1107,7 @@ class SyncMLSubscription(XMLObject):
if id == document.getId(): if id == document.getId():
return signature return signature
else: # XXX-Aurel : maybe none is expected # pylint: disable=useless-else-on-loop else: # XXX-Aurel : maybe none is expected # pylint: disable=useless-else-on-loop
raise KeyError, id raise KeyError(id)
security.declareProtected(Permissions.AccessContentsInformation, security.declareProtected(Permissions.AccessContentsInformation,
'getSignatureFromGid') 'getSignatureFromGid')
......
...@@ -77,7 +77,7 @@ class PdataHelper(persistent.Persistent): ...@@ -77,7 +77,7 @@ class PdataHelper(persistent.Persistent):
value = StringIO(value) value = StringIO(value)
if isinstance(value, FileUpload) and not value: if isinstance(value, FileUpload) and not value:
raise ValueError, 'File not specified' raise ValueError('File not specified')
if isinstance(value, Pdata): if isinstance(value, Pdata):
size = self._read_size_from_pdata(value) size = self._read_size_from_pdata(value)
......
...@@ -62,8 +62,8 @@ def encode(format, string_to_encode): # pylint: disable=redefined-builtin ...@@ -62,8 +62,8 @@ def encode(format, string_to_encode): # pylint: disable=redefined-builtin
#elif format is .... put here the other formats #elif format is .... put here the other formats
else:#if there is no format corresponding with format, raise an error else:#if there is no format corresponding with format, raise an error
LOG('encode : unknown or not implemented format : ', INFO, format) LOG('encode : unknown or not implemented format : ', INFO, format)
raise ValueError, "Sorry, the server ask for the format %s but \ raise ValueError("Sorry, the server ask for the format %s but"
it's unknow or not implemented" % format " it's unknown or not implemented" % format)
def decode(format, string_to_decode): # pylint: disable=redefined-builtin def decode(format, string_to_decode): # pylint: disable=redefined-builtin
""" """
...@@ -77,8 +77,7 @@ def decode(format, string_to_decode): # pylint: disable=redefined-builtin ...@@ -77,8 +77,7 @@ def decode(format, string_to_decode): # pylint: disable=redefined-builtin
#elif format is .... put here the other formats #elif format is .... put here the other formats
else:#if there is no format corresponding with format, raise an error else:#if there is no format corresponding with format, raise an error
LOG('decode : unknown or not implemented format :', INFO, format) LOG('decode : unknown or not implemented format :', INFO, format)
raise ValueError, "Sorry, the format %s is unknow or \ raise ValueError("Sorry, the format %s is unknown or not implemented" % format)
not implemented" % format
def isDecodeEncodeTheSame(string_encoded, string_decoded, format): # pylint: disable=redefined-builtin def isDecodeEncodeTheSame(string_encoded, string_decoded, format): # pylint: disable=redefined-builtin
""" """
......
...@@ -45,7 +45,7 @@ def parseTestSuiteResults(file_handler): ...@@ -45,7 +45,7 @@ def parseTestSuiteResults(file_handler):
# when called with a string argument, zipfile.ZipFile will open a local file. # when called with a string argument, zipfile.ZipFile will open a local file.
# we don't want this to happen # we don't want this to happen
if isinstance(file_handler, basestring): if isinstance(file_handler, basestring):
raise Unauthorized, file_handler raise Unauthorized(file_handler)
zf = zipfile.ZipFile(file_handler) zf = zipfile.ZipFile(file_handler)
result = {} result = {}
......
...@@ -88,7 +88,7 @@ class IntegrationModule(XMLObject): ...@@ -88,7 +88,7 @@ class IntegrationModule(XMLObject):
else: else:
return self.getObjectList[item] return self.getObjectList[item]
except ValueError, msg: except ValueError, msg:
raise KeyError, msg raise KeyError(msg)
security.declareProtected(Permissions.AccessContentsInformation, security.declareProtected(Permissions.AccessContentsInformation,
'getGIDFor') 'getGIDFor')
......
...@@ -78,7 +78,7 @@ class IntegrationSite(Folder): ...@@ -78,7 +78,7 @@ class IntegrationSite(Folder):
""" """
if not category: if not category:
LOG("getCategoryFromMapping", ERROR, "empty category provided") LOG("getCategoryFromMapping", ERROR, "empty category provided")
raise ValueError, "Empty category provided" raise ValueError("Empty category provided")
# Split the category to have the base and the variation category # Split the category to have the base and the variation category
_, variation_category = category.split('/', 1) _, variation_category = category.split('/', 1)
...@@ -110,7 +110,7 @@ class IntegrationSite(Folder): ...@@ -110,7 +110,7 @@ class IntegrationSite(Folder):
# only the base category has to be mapped # only the base category has to be mapped
if missing_mapping or current_object.getDestinationReference() is None: if missing_mapping or current_object.getDestinationReference() is None:
# We do not want the process to go on if base category mappings is missing # We do not want the process to go on if base category mappings is missing
raise ValueError, "Mapping not defined for %s" % category raise ValueError("Mapping not defined for %s" % category)
return current_object.getDestinationReference() +'/'+ category.split('/', 1)[1] return current_object.getDestinationReference() +'/'+ category.split('/', 1)[1]
else: else:
# Create default line that has to be mapped by user later # Create default line that has to be mapped by user later
...@@ -125,12 +125,12 @@ class IntegrationSite(Folder): ...@@ -125,12 +125,12 @@ class IntegrationSite(Folder):
missing_mapping = True missing_mapping = True
else: else:
LOG("getCategoryFromMapping", ERROR, "Mapping object for %s not found" %(cat,)) LOG("getCategoryFromMapping", ERROR, "Mapping object for %s not found" %(cat,))
raise ValueError, "Mapping object for %s not found" %(cat,) raise ValueError("Mapping object for %s not found" % cat)
mapped_category = cat_object.getDestinationReference() mapped_category = cat_object.getDestinationReference()
if mapped_category in ("", None) and cat_object.getPortalType() == "Integration Category Mapping": if mapped_category in ("", None) and cat_object.getPortalType() == "Integration Category Mapping":
LOG("getCategoryFromMapping", ERROR, "Mapping not defined for %s" % (cat,)) LOG("getCategoryFromMapping", ERROR, "Mapping not defined for %s" % (cat,))
raise ValueError, "Mapping not defined for %s" % cat raise ValueError("Mapping not defined for %s" % cat)
if mapped_base_category is None: if mapped_base_category is None:
mapped_base_category = mapped_category mapped_base_category = mapped_category
else: else:
...@@ -143,7 +143,7 @@ class IntegrationSite(Folder): ...@@ -143,7 +143,7 @@ class IntegrationSite(Folder):
## category)) ## category))
if missing_mapping: if missing_mapping:
# We do not want the process to go on if mappings are missing # We do not want the process to go on if mappings are missing
raise ValueError, "Mapping not defined for %s" % category raise ValueError("Mapping not defined for %s" % category)
return mapped_variation_category[-1] return mapped_variation_category[-1]
security.declareProtected(Permissions.AccessContentsInformation, security.declareProtected(Permissions.AccessContentsInformation,
...@@ -165,7 +165,7 @@ class IntegrationSite(Folder): ...@@ -165,7 +165,7 @@ class IntegrationSite(Folder):
destination_reference=base_category, destination_reference=base_category,
) )
if len(mapping) != 1: if len(mapping) != 1:
raise IndexError, 'The integration base category mapping %s must be mapped and with only one base_category' % (base_category) raise IndexError('The integration base category mapping %s must be mapped and with only one base_category' % base_category)
mapping = mapping[0].getObject() mapping = mapping[0].getObject()
# retrieve the corresponding category integration mapping # retrieve the corresponding category integration mapping
...@@ -174,7 +174,7 @@ class IntegrationSite(Folder): ...@@ -174,7 +174,7 @@ class IntegrationSite(Folder):
destination_reference=category, destination_reference=category,
) )
if len(mapping_line) > 1: if len(mapping_line) > 1:
raise IndexError, 'The integration category mapping %s must be mapped with only one category' % (variation) raise IndexError('The integration category mapping %s must be mapped with only one category' % variation)
try: try:
# shared variation # shared variation
return '/'.join( return '/'.join(
...@@ -204,7 +204,7 @@ class IntegrationSite(Folder): ...@@ -204,7 +204,7 @@ class IntegrationSite(Folder):
destination_reference=property_name, destination_reference=property_name,
) )
if len(mapping_line) > 1: if len(mapping_line) > 1:
raise IndexError, 'The integration property mapping %s must be mapped with only one category' % (property_name) raise IndexError('The integration property mapping %s must be mapped with only one category' % property_name)
elif len(mapping_line) == 0: elif len(mapping_line) == 0:
return property_name return property_name
else: else:
......
...@@ -134,7 +134,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate): ...@@ -134,7 +134,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate):
last_request_error="No connection available, connector is %s" %(self.getSourceValue(),)) last_request_error="No connection available, connector is %s" %(self.getSourceValue(),))
return [] return []
else: else:
raise ValueError, "No connection available" raise ValueError("No connection available")
# Add specific parameters defined on integration site # Add specific parameters defined on integration site
site = self.getIntegrationSite() site = self.getIntegrationSite()
...@@ -236,7 +236,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate): ...@@ -236,7 +236,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate):
if test_mode: if test_mode:
self._edit(last_request_error="Bad XML returned by request, impossible to parse it") self._edit(last_request_error="Bad XML returned by request, impossible to parse it")
else: else:
raise ValueError, "Bad XML returned by request %s with kw = %s, xml = %s" %(self.getPath(), kw, xml) raise ValueError("Bad XML returned by request %s with kw = %s, xml = %s" %(self.getPath(), kw, xml))
brain = getBrain(self.brain_class_file, self.brain_class_name, reload=1) brain = getBrain(self.brain_class_file, self.brain_class_name, reload=1)
...@@ -269,17 +269,17 @@ class WebServiceRequest(XMLObject, ZopePageTemplate): ...@@ -269,17 +269,17 @@ class WebServiceRequest(XMLObject, ZopePageTemplate):
try: try:
long(item) long(item)
except ValueError: except ValueError:
raise KeyError, "Item %s does not exists call by Web Service Request %s : not a long" % (item, raise KeyError("Item %s does not exists call by Web Service Request %s : not a long" % (item,
self.getTitle(),) self.getTitle(),))
kw = {self.getIDParameterName() : str(item), } kw = {self.getIDParameterName() : str(item), }
object_list = self(**kw) object_list = self(**kw)
if len(object_list) == 1: if len(object_list) == 1:
return object_list[0] return object_list[0]
else: else:
raise KeyError, "Item %s does not exists call by Web Service Request %s with params %s return %d results" % (item, raise KeyError("Item %s does not exists call by Web Service Request %s with params %s return %d results" % (item,
self.getTitle(), self.getTitle(),
kw, kw,
len(object_list)) len(object_list)))
def parse_dict(self, parser_dict, dict_list): def parse_dict(self, parser_dict, dict_list):
""" Render the dict list mapped by the parser dict. """ """ Render the dict list mapped by the parser dict. """
......
...@@ -69,6 +69,6 @@ class WebServiceRequestGroup(XMLObject): ...@@ -69,6 +69,6 @@ class WebServiceRequestGroup(XMLObject):
# after browsing all web service requests check that item exists and only # after browsing all web service requests check that item exists and only
# one time # one time
if len(object_list) != 1: if len(object_list) != 1:
raise KeyError, "No entry for the item %s" % item raise KeyError("No entry for the item %s" % item)
return object_list[0] return object_list[0]
...@@ -125,11 +125,11 @@ class TioSafeBaseConduit(ERP5Conduit): ...@@ -125,11 +125,11 @@ class TioSafeBaseConduit(ERP5Conduit):
if getattr(self, 'integration_site', None) is None: if getattr(self, 'integration_site', None) is None:
related_object_list = [x.getObject() for x in sync_object.Base_getRelatedObjectList()] related_object_list = [x.getObject() for x in sync_object.Base_getRelatedObjectList()]
if len(related_object_list) != 1: if len(related_object_list) != 1:
raise ValueError, "Impossible to find related object to %s : %s" %(sync_object.getPath(), related_object_list) raise ValueError("Impossible to find related object to %s : %s" %(sync_object.getPath(), related_object_list))
integration_site = related_object_list[0].getParentValue() integration_site = related_object_list[0].getParentValue()
if integration_site.getPortalType() != "Integration Site": if integration_site.getPortalType() != "Integration Site":
raise ValueError, "Did not get an Integration Site object instead %s : %s" %(integration_site.getPortalType(), raise ValueError("Did not get an Integration Site object instead %s : %s" %(integration_site.getPortalType(),
integration_site.getPath()) integration_site.getPath()))
self.integration_site = integration_site self.integration_site = integration_site
return self.integration_site return self.integration_site
...@@ -142,14 +142,14 @@ class TioSafeBaseConduit(ERP5Conduit): ...@@ -142,14 +142,14 @@ class TioSafeBaseConduit(ERP5Conduit):
module_id = "%s_module" %(object_type.lower()) module_id = "%s_module" %(object_type.lower())
module = getattr(site, module_id, None) module = getattr(site, module_id, None)
if module is None: if module is None:
raise ValueError, "Impossible to find integration module object on %s for %s" %(site.getPath(), object_type) raise ValueError("Impossible to find integration module object on %s for %s" %(site.getPath(), object_type))
if synchronization_type == "publication": if synchronization_type == "publication":
return module.getSourceSectionValue() return module.getSourceSectionValue()
elif synchronization_type == "subscription": elif synchronization_type == "subscription":
return module.getDestinationSectionValue() return module.getDestinationSectionValue()
else: else:
raise ValueError, 'Unknown type %s' %(synchronization_type,) raise ValueError('Unknown type %s' %(synchronization_type,))
def updateNode(self, xml=None, object=None, previous_xml=None, force=False, def updateNode(self, xml=None, object=None, previous_xml=None, force=False,
simulate=False, reset=False, xpath_expression=None, **kw): simulate=False, reset=False, xpath_expression=None, **kw):
......
...@@ -106,7 +106,7 @@ class TioSafeBrain(Explicit): ...@@ -106,7 +106,7 @@ class TioSafeBrain(Explicit):
module_list.append(module) module_list.append(module)
if not len(module_list): if not len(module_list):
raise ValueError, "Impossible to find a module for %s" %(object_type) raise ValueError("Impossible to find a module for %s" % object_type)
sync_object_list = [] sync_object_list = []
for module in module_list: for module in module_list:
...@@ -129,12 +129,12 @@ class TioSafeBrain(Explicit): ...@@ -129,12 +129,12 @@ class TioSafeBrain(Explicit):
# 2. sync_type != tiosafe and destination_portal_type != Integration Module # 2. sync_type != tiosafe and destination_portal_type != Integration Module
sync_object_list.append(module_destination.getPath()) sync_object_list.append(module_destination.getPath())
else: else:
raise ValueError, "Impossible to find pub/sub related to Integration Module, pub = %s with source = %s, sub = %s with source = %s" %( raise ValueError("Impossible to find pub/sub related to Integration Module, pub = %s with source = %s, sub = %s with source = %s" %(
module.getSourceSection(), module.getSourceSection(),
module_source.getSource(), module_source.getSource(),
module.getDestinationSection(), module.getDestinationSection(),
module_destination.getSource(), module_destination.getSource(),
) ))
return sync_object_list return sync_object_list
# Cache sync object list # Cache sync object list
...@@ -175,7 +175,7 @@ class TioSafeBrain(Explicit): ...@@ -175,7 +175,7 @@ class TioSafeBrain(Explicit):
try: try:
prop_value = getattr(self, prop) prop_value = getattr(self, prop)
except AttributeError: except AttributeError:
raise AttributeError, "The brain doesn't have the property %s" % prop raise AttributeError("The brain doesn't have the property %s" % prop)
gid += " %s" %(prop_value,) gid += " %s" %(prop_value,)
self.gid = gid self.gid = gid
...@@ -401,7 +401,7 @@ class Node(TioSafeBrain): ...@@ -401,7 +401,7 @@ class Node(TioSafeBrain):
organisation_gid = None organisation_gid = None
if organisation_gid is None: if organisation_gid is None:
raise ValueError, "Impossible to find organisation for id %s on node %s" %(self.relation, self.path) raise ValueError("Impossible to find organisation for id %s on node %s" %(self.relation, self.path))
else: else:
organisation_gid = "" organisation_gid = ""
# set the tag # set the tag
...@@ -539,7 +539,7 @@ class Transaction(TioSafeBrain): ...@@ -539,7 +539,7 @@ class Transaction(TioSafeBrain):
# Must find a better way to browse specialised objects # Must find a better way to browse specialised objects
specialized_trade_condition = trade_condition.getSpecialiseValue() specialized_trade_condition = trade_condition.getSpecialiseValue()
if specialized_trade_condition is None or specialized_trade_condition.getPortalType() == "Business Process": if specialized_trade_condition is None or specialized_trade_condition.getPortalType() == "Business Process":
raise ValueError, 'Impossible to find a trade condition containing VAT lines, last trade condition was %s, parent was %s' %(specialized_trade_condition, trade_condition) raise ValueError('Impossible to find a trade condition containing VAT lines, last trade condition was %s, parent was %s' %(specialized_trade_condition, trade_condition))
else: else:
trade_condition = specialized_trade_condition trade_condition = specialized_trade_condition
...@@ -679,7 +679,7 @@ class Transaction(TioSafeBrain): ...@@ -679,7 +679,7 @@ class Transaction(TioSafeBrain):
elif line_type == 'Delivery': elif line_type == 'Delivery':
resource = integration_site.getDestinationCarrierValue() resource = integration_site.getDestinationCarrierValue()
else: else:
raise ValueError, 'Try to work on "%s" which is an invalid type.' % line_type raise ValueError('Try to work on "%s" which is an invalid type.' % line_type)
# after the work on the line set the resource value which will be # after the work on the line set the resource value which will be
# render in the xml # render in the xml
movement_dict['resource'] = resource_gid movement_dict['resource'] = resource_gid
......
...@@ -102,8 +102,9 @@ class TioSafeNodeConduit(TioSafeBaseConduit): ...@@ -102,8 +102,9 @@ class TioSafeNodeConduit(TioSafeBaseConduit):
try: try:
previous_value = previous_xml[0].text previous_value = previous_xml[0].text
except IndexError: except IndexError:
raise IndexError, 'Too little or too many value, only one is required for %s' % ( raise IndexError(
previous_xml 'Too little or too many value, only one is required for %s'
% previous_xml
) )
# check if it'a work on person or on address # check if it'a work on person or on address
......
...@@ -164,8 +164,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit): ...@@ -164,8 +164,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit):
try: try:
previous_value = previous_xml[0].text previous_value = previous_xml[0].text
except IndexError: except IndexError:
raise ValueError, 'Too little or too many value, only one is required for %s' % ( raise ValueError(
previous_xml 'Too little or too many value, only one is required for %s'
% previous_xml
) )
# check if it'a work on product or on categories # check if it'a work on product or on categories
...@@ -268,8 +269,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit): ...@@ -268,8 +269,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit):
previous_xml[0].text, previous_xml[0].text,
) )
except IndexError: except IndexError:
raise IndexError, 'Too little or too many value, only one is required for %s' % ( raise IndexError(
previous_xml 'Too little or too many value, only one is required for %s'
% previous_xml
) )
# retrieve the current value to check if exists a conflict # retrieve the current value to check if exists a conflict
......
...@@ -78,7 +78,7 @@ class AccountingERP5IntegrationConduit(TioSafeBaseConduit): ...@@ -78,7 +78,7 @@ class AccountingERP5IntegrationConduit(TioSafeBaseConduit):
'PP', 'SA', 'SR', 'VP', 'VR'): 'PP', 'SA', 'SR', 'VP', 'VR'):
return 'Payment Transaction' return 'Payment Transaction'
else: else:
raise "getObjectType: ERROR journal code unknow" raise Exception("getObjectType: ERROR journal code unknown")
def constructContent(self, object, object_id, portal_type): # pylint: disable=redefined-builtin def constructContent(self, object, object_id, portal_type): # pylint: disable=redefined-builtin
""" """
......
...@@ -76,8 +76,8 @@ class ERP5NodeConduit(TioSafeBaseConduit): ...@@ -76,8 +76,8 @@ class ERP5NodeConduit(TioSafeBaseConduit):
if len(stc_list) == 0: if len(stc_list) == 0:
self._createSaleTradeCondition(object, **kw) self._createSaleTradeCondition(object, **kw)
elif len(stc_list) > 1: elif len(stc_list) > 1:
raise ValueError, "Multiple trade condition (%s) retrieved for %s" \ raise ValueError("Multiple trade condition (%s) retrieved for %s"
% ([x.path for x in stc_list], object.getTitle()) % ([x.path for x in stc_list], object.getTitle()))
else: else:
stc = stc_list[0].getObject() stc = stc_list[0].getObject()
stc.edit( stc.edit(
...@@ -155,7 +155,8 @@ class ERP5NodeConduit(TioSafeBaseConduit): ...@@ -155,7 +155,8 @@ class ERP5NodeConduit(TioSafeBaseConduit):
if link_object is not None: if link_object is not None:
document.setCareerSubordinationValue(link_object) document.setCareerSubordinationValue(link_object)
else: else:
raise ValueError, "Impossible to find organisation %s in %s" %(organisation_gid, synchronization_list) raise ValueError("Impossible to find organisation %s in %s"
% (organisation_gid, synchronization_list))
document.reindexObject() document.reindexObject()
return [] return []
......
...@@ -151,7 +151,7 @@ class ERP5PaymentTransactionConduit(TioSafeBaseConduit): ...@@ -151,7 +151,7 @@ class ERP5PaymentTransactionConduit(TioSafeBaseConduit):
if tag in node_dict: if tag in node_dict:
node_dict[tag](document=sub_object, xml=node, **kw) node_dict[tag](document=sub_object, xml=node, **kw)
else: else:
raise ValueError, "This is an unknown sub-element %s on %s" %(tag, sub_object.getPath()) raise ValueError("This is an unknown sub-element %s on %s" %(tag, sub_object.getPath()))
elif tag in ['start_date', 'stop_date']: elif tag in ['start_date', 'stop_date']:
if not node.text: if not node.text:
node.text = None node.text = None
......
...@@ -141,7 +141,7 @@ class ERP5ResourceConduit(TioSafeBaseConduit): ...@@ -141,7 +141,7 @@ class ERP5ResourceConduit(TioSafeBaseConduit):
conflict_list = self._createMapping(sub_object, mapping_list) conflict_list = self._createMapping(sub_object, mapping_list)
if len(conflict_list): if len(conflict_list):
raise ValueError, "Conflict on creation of resource, should not happen, conflict = %r" %(conflict_list) raise ValueError("Conflict on creation of resource, should not happen, conflict = %r" % conflict_list)
self.newObject( self.newObject(
object=sub_object, object=sub_object,
...@@ -232,7 +232,7 @@ class ERP5ResourceConduit(TioSafeBaseConduit): ...@@ -232,7 +232,7 @@ class ERP5ResourceConduit(TioSafeBaseConduit):
ss_list = portal.sale_supply_module.searchFolder(title=name, ss_list = portal.sale_supply_module.searchFolder(title=name,
validation_state='validated') validation_state='validated')
if len(ss_list) > 1: if len(ss_list) > 1:
raise ValueError, "Too many sale supplies, does not know which to choose" raise ValueError("Too many sale supplies, does not know which to choose")
if len(ss_list) == 0: if len(ss_list) == 0:
# Create a new one # Create a new one
ss = portal.sale_supply_module.newContent(title=name) ss = portal.sale_supply_module.newContent(title=name)
...@@ -249,7 +249,7 @@ class ERP5ResourceConduit(TioSafeBaseConduit): ...@@ -249,7 +249,7 @@ class ERP5ResourceConduit(TioSafeBaseConduit):
pref_list = [x for x in portal.portal_preferences.objectValues(portal_type="System Preference")\ pref_list = [x for x in portal.portal_preferences.objectValues(portal_type="System Preference")\
if x.getPreferenceState()=="global"] if x.getPreferenceState()=="global"]
if len(pref_list) > 1: if len(pref_list) > 1:
raise ValueError, "Too many system preferences, does not know which to choose" raise ValueError("Too many system preferences, does not know which to choose")
elif len(pref_list) == 0: elif len(pref_list) == 0:
pref = portal.portal_preferences.newContent(portal_type="System Preference", pref = portal.portal_preferences.newContent(portal_type="System Preference",
title="default system preference for TioSafe", title="default system preference for TioSafe",
...@@ -376,8 +376,9 @@ class ERP5ResourceConduit(TioSafeBaseConduit): ...@@ -376,8 +376,9 @@ class ERP5ResourceConduit(TioSafeBaseConduit):
try: try:
previous_value = previous_xml[0].text previous_value = previous_xml[0].text
except IndexError: except IndexError:
raise IndexError, 'Too little or too many value, only one is required for %s' % ( raise IndexError(
previous_xml, 'Too little or too many value, only one is required for %s'
% previous_xml
) )
if isinstance(previous_value, unicode): if isinstance(previous_value, unicode):
...@@ -545,8 +546,9 @@ class ERP5ResourceConduit(TioSafeBaseConduit): ...@@ -545,8 +546,9 @@ class ERP5ResourceConduit(TioSafeBaseConduit):
try: try:
previous_value = previous_xml[0].text previous_value = previous_xml[0].text
except IndexError: except IndexError:
raise IndexError, 'Too little or too many value, only one is required for %s' % ( raise IndexError(
previous_xml 'Too little or too many value, only one is required for %s'
% previous_xml
) )
if isinstance(previous_value, unicode): if isinstance(previous_value, unicode):
......
...@@ -106,7 +106,7 @@ class ERP5TransactionConduit(TioSafeBaseConduit): ...@@ -106,7 +106,7 @@ class ERP5TransactionConduit(TioSafeBaseConduit):
if tag in node_dict: if tag in node_dict:
node_dict[tag](document=sub_object, xml=node, **kw) node_dict[tag](document=sub_object, xml=node, **kw)
else: else:
raise ValueError, "This is an unknown sub-element %s on %s" %(tag, sub_object.getPath()) raise ValueError("This is an unknown sub-element %s on %s" %(tag, sub_object.getPath()))
if tag == 'currency': if tag == 'currency':
link_object = object.portal_catalog.getResultValue( link_object = object.portal_catalog.getResultValue(
portal_type='Currency', portal_type='Currency',
...@@ -285,7 +285,7 @@ class ERP5TransactionConduit(TioSafeBaseConduit): ...@@ -285,7 +285,7 @@ class ERP5TransactionConduit(TioSafeBaseConduit):
break break
# in the worse case save the line with the unknown product # in the worse case save the line with the unknown product
if link_object is None: if link_object is None:
raise ValueError, "Impossible to find related resource for gid %s" %(link_gid) raise ValueError("Impossible to find related resource for gid %s" % link_gid)
# set the resource in the dict # set the resource in the dict
movement_dict_value[tag] = link_object movement_dict_value[tag] = link_object
......
...@@ -160,11 +160,11 @@ class TioSafeBaseConduit(ERP5Conduit): ...@@ -160,11 +160,11 @@ class TioSafeBaseConduit(ERP5Conduit):
else: else:
related_object_list = [x.getObject() for x in sync_object.Base_getRelatedObjectList()] related_object_list = [x.getObject() for x in sync_object.Base_getRelatedObjectList()]
if len(related_object_list) != 1: if len(related_object_list) != 1:
raise ValueError, "Impossible to find related object to %s : %s" %(sync_object.getPath(), related_object_list) raise ValueError("Impossible to find related object to %s : %s" %(sync_object.getPath(), related_object_list))
integration_site = related_object_list[0].getParentValue() integration_site = related_object_list[0].getParentValue()
if integration_site.getPortalType() != "Integration Site": if integration_site.getPortalType() != "Integration Site":
raise ValueError, "Did not get an Integration Site object instead %s : %s" %(integration_site.getPortalType(), raise ValueError("Did not get an Integration Site object instead %s : %s" %(integration_site.getPortalType(),
integration_site.getPath()) integration_site.getPath()))
self.integration_site = integration_site self.integration_site = integration_site
return self.integration_site return self.integration_site
...@@ -187,7 +187,7 @@ class TioSafeBaseConduit(ERP5Conduit): ...@@ -187,7 +187,7 @@ class TioSafeBaseConduit(ERP5Conduit):
elif synchronization_type == "subscription": elif synchronization_type == "subscription":
result_list.append(module.getDestinationSectionValue()) result_list.append(module.getDestinationSectionValue())
else: else:
raise ValueError, 'Unknown type %s' %(synchronization_type,) raise ValueError('Unknown type %s' %(synchronization_type,))
return result_list return result_list
......
...@@ -104,8 +104,9 @@ class TioSafeNodeConduit(TioSafeBaseConduit): ...@@ -104,8 +104,9 @@ class TioSafeNodeConduit(TioSafeBaseConduit):
try: try:
previous_value = previous_xml[0].text previous_value = previous_xml[0].text
except IndexError: except IndexError:
raise IndexError, 'Too little or too many value, only one is required for %s' % ( raise IndexError(
previous_xml 'Too little or too many value, only one is required for %s'
% previous_xml
) )
# check if it'a work on person or on address # check if it'a work on person or on address
......
...@@ -80,7 +80,7 @@ class TioSafeResourceConduit(TioSafeBaseConduit): ...@@ -80,7 +80,7 @@ class TioSafeResourceConduit(TioSafeBaseConduit):
if create_method is not None: if create_method is not None:
create_result = create_method(**keyword) create_result = create_method(**keyword)
else: else:
raise ValueError, 'Impossible to find a create method named %s and object %s' %(create_method_id, object.getPath(),) raise ValueError('Impossible to find a create method named %s and object %s' %(create_method_id, object.getPath(),))
if len(create_result): if len(create_result):
# We suppose the id of the object created was returned by the plugin # We suppose the id of the object created was returned by the plugin
new_id = create_result[0].getId() new_id = create_result[0].getId()
...@@ -127,7 +127,7 @@ class TioSafeResourceConduit(TioSafeBaseConduit): ...@@ -127,7 +127,7 @@ class TioSafeResourceConduit(TioSafeBaseConduit):
if delete_method is not None: if delete_method is not None:
return delete_method(product_id=object_id) return delete_method(product_id=object_id)
else: else:
raise ValueError, 'Impossible to find a delete method named %s and object %s' %(delete_method_id, object.getPath(),) raise ValueError('Impossible to find a delete method named %s and object %s' %(delete_method_id, object.getPath(),))
def _updateXupdateUpdate(self, document=None, xml=None, previous_xml=None, **kw): def _updateXupdateUpdate(self, document=None, xml=None, previous_xml=None, **kw):
...@@ -145,8 +145,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit): ...@@ -145,8 +145,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit):
try: try:
previous_value = previous_xml[0].text previous_value = previous_xml[0].text
except IndexError: except IndexError:
raise ValueError, 'Too little or too many value, only one is required for %s' % ( raise ValueError(
previous_xml 'Too little or too many value, only one is required for %s'
% previous_xml
) )
if isinstance(previous_value, unicode): if isinstance(previous_value, unicode):
...@@ -206,8 +207,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit): ...@@ -206,8 +207,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit):
selected_previous_xml[0].text, selected_previous_xml[0].text,
) )
except IndexError: except IndexError:
raise IndexError, 'Too little or too many value, only one is required for %s' % ( raise IndexError(
previous_xml 'Too little or too many value, only one is required for %s'
% previous_xml
) )
LOG("TiosafeResourceConduit.del", 300, "will remove category %s from %s" %(tag, previous_xml.text)) LOG("TiosafeResourceConduit.del", 300, "will remove category %s from %s" %(tag, previous_xml.text))
# retrieve the current value to check if exists a conflict # retrieve the current value to check if exists a conflict
......
...@@ -2,7 +2,7 @@ im = context ...@@ -2,7 +2,7 @@ im = context
pub = im.getSourceSectionValue() pub = im.getSourceSectionValue()
pub_sub_list = pub.objectValues() pub_sub_list = pub.objectValues()
if not len(pub_sub_list): if not len(pub_sub_list):
raise ValueError, "%s sub in pub %s for im %s" %(len(pub_sub_list), pub.getPath(), im.getPath()) raise ValueError("%s sub in pub %s for im %s" %(len(pub_sub_list), pub.getPath(), im.getPath()))
else: else:
pub_sub = pub_sub_list[0] pub_sub = pub_sub_list[0]
#pub_sub = im.getSourceSectionValue().objectValues()[0] #pub_sub = im.getSourceSectionValue().objectValues()[0]
......
...@@ -44,7 +44,7 @@ if pub_method is not None and sub_method is not None: ...@@ -44,7 +44,7 @@ if pub_method is not None and sub_method is not None:
sub_xml.append(getattr(ob, sub_xml_method)()) sub_xml.append(getattr(ob, sub_xml_method)())
else: else:
raise ValueError, "Impossible to get method, pub_method = %s from %s, sub_method = %s from %s" %(pub_method, pub_list, sub_method, sub_list,) raise ValueError("Impossible to get method, pub_method = %s from %s, sub_method = %s from %s" %(pub_method, pub_list, sub_method, sub_list,))
pub_xml = '\n'.join(pub_xml) pub_xml = '\n'.join(pub_xml)
sub_xml = '\n'.join(sub_xml) sub_xml = '\n'.join(sub_xml)
......
...@@ -56,10 +56,8 @@ except ValidationFailed, error_message: ...@@ -56,10 +56,8 @@ except ValidationFailed, error_message:
if len(message) > 2000: # too long message will generate a too long URI if len(message) > 2000: # too long message will generate a too long URI
# that would become an error. # that would become an error.
message = "%s ..." % message[:(2000 - 4)] message = "%s ..." % message[:(2000 - 4)]
raise Redirect, "%s?portal_status_message=%s" % ( context.Base_redirect(keep_items={'portal_status_message':message})
context.getAbsoluteUrl(),
message
)
transaction.confirm() transaction.confirm()
return transaction.getRelativeUrl() return transaction.getRelativeUrl()
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.
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.
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