Commit debb2043 authored by Julien Muchembled's avatar Julien Muchembled

wip

parent ea5e3ed7
...@@ -21,4 +21,4 @@ if node is None: ...@@ -21,4 +21,4 @@ if node is None:
# 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)
...@@ -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(
......
...@@ -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,
......
...@@ -230,7 +230,7 @@ class CertificateAuthorityTool(BaseTool): ...@@ -230,7 +230,7 @@ class CertificateAuthorityTool(BaseTool):
except Exception: except Exception:
# do not raise during cleanup # do not raise during cleanup
pass pass
reraise(e[0], e[1], e[2]) reraise(*e)
finally: finally:
self._unlockCertificateAuthority() self._unlockCertificateAuthority()
...@@ -273,7 +273,7 @@ class CertificateAuthorityTool(BaseTool): ...@@ -273,7 +273,7 @@ class CertificateAuthorityTool(BaseTool):
except Exception: except Exception:
# do not raise during cleanup # do not raise during cleanup
pass pass
reraise(e[0], e[1], e[2]) reraise(*e)
finally: finally:
self._unlockCertificateAuthority() self._unlockCertificateAuthority()
......
...@@ -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.
......
...@@ -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
......
...@@ -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):
......
...@@ -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)
......
...@@ -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()
......
...@@ -22,7 +22,7 @@ for paysheet in paysheet_list: ...@@ -22,7 +22,7 @@ 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
......
...@@ -97,7 +97,7 @@ for task_line in result_list: ...@@ -97,7 +97,7 @@ 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)
......
...@@ -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,10 +1036,10 @@ class SyncMLSubscription(XMLObject): ...@@ -1036,10 +1036,10 @@ 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
......
...@@ -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
""" """
......
...@@ -102,9 +102,10 @@ class TioSafeNodeConduit(TioSafeBaseConduit): ...@@ -102,9 +102,10 @@ 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
if tag in ['street', 'zip', 'city', 'country']: if tag in ['street', 'zip', 'city', 'country']:
......
...@@ -164,9 +164,10 @@ class TioSafeResourceConduit(TioSafeBaseConduit): ...@@ -164,9 +164,10 @@ 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
if tag.split('[')[0] == 'category': if tag.split('[')[0] == 'category':
...@@ -268,9 +269,10 @@ class TioSafeResourceConduit(TioSafeBaseConduit): ...@@ -268,9 +269,10 @@ 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
current_value = etree.XML(document.asXML()).xpath(tag)[0].text current_value = etree.XML(document.asXML()).xpath(tag)[0].text
......
...@@ -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 Exception("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,7 +76,7 @@ class ERP5NodeConduit(TioSafeBaseConduit): ...@@ -76,7 +76,7 @@ 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()
...@@ -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 []
......
...@@ -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,
...@@ -376,9 +376,10 @@ class ERP5ResourceConduit(TioSafeBaseConduit): ...@@ -376,9 +376,10 @@ 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):
previous_value = previous_value.encode('utf-8') previous_value = previous_value.encode('utf-8')
...@@ -545,9 +546,10 @@ class ERP5ResourceConduit(TioSafeBaseConduit): ...@@ -545,9 +546,10 @@ 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):
previous_value = previous_value.encode('utf-8') previous_value = previous_value.encode('utf-8')
......
...@@ -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
......
...@@ -104,9 +104,10 @@ class TioSafeNodeConduit(TioSafeBaseConduit): ...@@ -104,9 +104,10 @@ 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
if tag in ['street', 'zip', 'city', 'country']: if tag in ['street', 'zip', 'city', 'country']:
......
...@@ -145,9 +145,10 @@ class TioSafeResourceConduit(TioSafeBaseConduit): ...@@ -145,9 +145,10 @@ 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):
previous_value = previous_value.encode('utf-8') previous_value = previous_value.encode('utf-8')
...@@ -206,9 +207,10 @@ class TioSafeResourceConduit(TioSafeBaseConduit): ...@@ -206,9 +207,10 @@ 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
current_value = etree.XML(object_xml).xpath(tag)[0].text current_value = etree.XML(object_xml).xpath(tag)[0].text
......
...@@ -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()
...@@ -19,7 +19,7 @@ for result in result_list: ...@@ -19,7 +19,7 @@ for result in result_list:
raise RuntimeError("One property is not the same that you wanted : you asked '%s' and expecting '%s' but get '%s'" % (key, kw[key], method())) raise RuntimeError("One property is not the same that you wanted : you asked '%s' and expecting '%s' but get '%s'" % (key, kw[key], method()))
# check that every object are owner by you # check that every object are owner by you
if strict_check_mode and object.Base_getOwnerId() not in [owner_id, functional_test_username, 'System Processes','zope', functional_another_test_username]: if strict_check_mode and object.Base_getOwnerId() not in [owner_id, functional_test_username, 'System Processes','zope', functional_another_test_username]:
raise RuntimeError("You have try to clean an item who haven't you as owner : %s is owned by %s and you are %s" % \ raise RuntimeError("You have try to clean an item who haven't you as owner : %s is owned by %s and you are %s" %
(object.getTitle(), object.Base_getOwnerId(), owner_id)) (object.getTitle(), object.Base_getOwnerId(), owner_id))
if strict_check_mode and max_count is not None: if strict_check_mode and max_count is not None:
......
...@@ -2094,7 +2094,7 @@ class RegisteredSkinSelectionTemplateItem(BaseTemplateItem): ...@@ -2094,7 +2094,7 @@ class RegisteredSkinSelectionTemplateItem(BaseTemplateItem):
if skin_selection_id in selection_list: if skin_selection_id in selection_list:
self._objects.setdefault(skin_folder_id, []).append(skin_selection_id) self._objects.setdefault(skin_folder_id, []).append(skin_selection_id)
else: else:
raise NotFound('No skin selection %s found for skin folder %s.' \ raise NotFound('No skin selection %s found for skin folder %s.'
% (skin_selection_id, skin_folder_id)) % (skin_selection_id, skin_folder_id))
# Function to generate XML Code Manually # Function to generate XML Code Manually
...@@ -2575,9 +2575,9 @@ class PortalTypeWorkflowChainTemplateItem(BaseTemplateItem): ...@@ -2575,9 +2575,9 @@ class PortalTypeWorkflowChainTemplateItem(BaseTemplateItem):
'in chain for portal_type %s' % (workflow_name, portal_type)) 'in chain for portal_type %s' % (workflow_name, portal_type))
self._objects.setdefault(portal_type, []).append(workflow) self._objects.setdefault(portal_type, []).append(workflow)
elif not self.is_bt_for_diff: elif not self.is_bt_for_diff:
raise NotFound('No workflow chain found for portal type %s. This '\ raise NotFound('No workflow chain found for portal type %s.'
'is probably a sign of a missing dependency.'\ ' This is probably a sign of a missing dependency.'
% portal_type) % portal_type)
# Function to generate XML Code Manually # Function to generate XML Code Manually
def generateXml(self, path=None): def generateXml(self, path=None):
...@@ -2692,8 +2692,8 @@ class PortalTypeWorkflowChainTemplateItem(BaseTemplateItem): ...@@ -2692,8 +2692,8 @@ class PortalTypeWorkflowChainTemplateItem(BaseTemplateItem):
# improve the error message # improve the error message
for wf_id in self._objects[path]: for wf_id in self._objects[path]:
if wf_id.startswith('-'): if wf_id.startswith('-'):
raise ValueError('"%s" is not a workflow ID for %s' % \ raise ValueError('"%s" is not a workflow ID for %s'
(wf_id, portal_type)) % (wf_id, portal_type))
chain_dict[chain_key] = self._objects[path] chain_dict[chain_key] = self._objects[path]
else: else:
if context.portal_types.getTypeInfo(portal_type) is None: if context.portal_types.getTypeInfo(portal_type) is None:
...@@ -2913,8 +2913,8 @@ class PortalTypeAllowedContentTypeTemplateItem(BaseTemplateItem): ...@@ -2913,8 +2913,8 @@ class PortalTypeAllowedContentTypeTemplateItem(BaseTemplateItem):
if type_information is None: if type_information is None:
if not property_list: if not property_list:
continue continue
raise AttributeError("Portal type '%s' not found while " \ raise AttributeError("Portal type '%s' not found while installing %s"
"installing %s" % (portal_id, self.getTitle())) % (portal_id, self.getTitle()))
old_property_list = old_objects.get(key, ()) old_property_list = old_objects.get(key, ())
object_property_list = getattr(type_information, self.class_property, ()) object_property_list = getattr(type_information, self.class_property, ())
# merge differences between portal types properties # merge differences between portal types properties
...@@ -6046,8 +6046,9 @@ Business Template is a set of definitions, such as skins, portal types and categ ...@@ -6046,8 +6046,9 @@ Business Template is a set of definitions, such as skins, portal types and categ
""" """
missing_dep_list = self.getMissingDependencyList() missing_dep_list = self.getMissingDependencyList()
if len(missing_dep_list) != 0: if len(missing_dep_list) != 0:
raise BusinessTemplateMissingDependency('Impossible to install %s, please install the following dependencies before: %s' \ raise BusinessTemplateMissingDependency(
%(self.getTitle(), repr(missing_dep_list))) 'Impossible to install %s, please install the following dependencies before: %r'
% (self.getTitle(), missing_dep_list))
security.declareProtected(Permissions.ManagePortal, 'getMissingDependencyList') security.declareProtected(Permissions.ManagePortal, 'getMissingDependencyList')
def getMissingDependencyList(self): def getMissingDependencyList(self):
......
...@@ -69,7 +69,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): ...@@ -69,7 +69,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator):
""" """
# Check the arguments # Check the arguments
if id_group in (None, 'None'): if id_group in (None, 'None'):
raise ValueError('%s is not a valid group Id.' % (repr(id_group), )) raise ValueError('%r is not a valid group Id.' % id_group)
if default is None: if default is None:
default = 0 default = 0
......
...@@ -55,7 +55,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator): ...@@ -55,7 +55,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator):
persistent. persistent.
""" """
if id_group in (None, 'None'): if id_group in (None, 'None'):
raise ValueError('%s is not a valid group Id.' % (repr(id_group), )) raise ValueError('%r is not a valid group Id.' % id_group)
if default is None: if default is None:
default = 0 default = 0
last_id_dict = getattr(self, 'last_id_dict', None) last_id_dict = getattr(self, 'last_id_dict', None)
......
...@@ -500,8 +500,8 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -500,8 +500,8 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
pass pass
else: else:
if portal_activities.countMessage(path=ob.getPath())>0: if portal_activities.countMessage(path=ob.getPath())>0:
raise ActivityPendingError('Sorry, pending activities prevent ' \ raise ActivityPendingError(
+ 'changing id at this current stage') 'Sorry, pending activities prevent changing id at this current stage')
# Search for categories that have to be updated in sub objects. # Search for categories that have to be updated in sub objects.
ob._recursiveSetActivityAfterTag(ob) ob._recursiveSetActivityAfterTag(ob)
......
...@@ -114,7 +114,7 @@ class IdTool(BaseTool): ...@@ -114,7 +114,7 @@ class IdTool(BaseTool):
Generate the next id in the sequence of ids of a particular group Generate the next id in the sequence of ids of a particular group
""" """
if id_group in (None, 'None'): if id_group in (None, 'None'):
raise ValueError('%s is not a valid id_group' % (repr(id_group), )) raise ValueError('%r is not a valid id_group' % id_group)
# for compatibilty with sql data, must not use id_group as a list # for compatibilty with sql data, must not use id_group as a list
if not isinstance(id_group, str): if not isinstance(id_group, str):
id_group = repr(id_group) id_group = repr(id_group)
...@@ -174,7 +174,7 @@ class IdTool(BaseTool): ...@@ -174,7 +174,7 @@ class IdTool(BaseTool):
Generate a list of next ids in the sequence of ids of a particular group Generate a list of next ids in the sequence of ids of a particular group
""" """
if id_group in (None, 'None'): if id_group in (None, 'None'):
raise ValueError('%s is not a valid id_group' % (repr(id_group), )) raise ValueError('%r is not a valid id_group' % id_group)
# for compatibilty with sql data, must not use id_group as a list # for compatibilty with sql data, must not use id_group as a list
if not isinstance(id_group, str): if not isinstance(id_group, str):
id_group = repr(id_group) id_group = repr(id_group)
...@@ -208,17 +208,13 @@ class IdTool(BaseTool): ...@@ -208,17 +208,13 @@ class IdTool(BaseTool):
# XXX It's temporary, a New API will be implemented soon # XXX It's temporary, a New API will be implemented soon
# the code will be change # the code will be change
portal = self.getPortalObject() portal = self.getPortalObject()
query = getattr(portal, 'IdTool_zGenerateId', None) try:
commit = getattr(portal, 'IdTool_zCommit', None) query = portal.IdTool_zGenerateId
commit = portal.IdTool_zCommit
if query is None or commit is None: except AttributeError:
portal_catalog = getattr(self, 'portal_catalog').getSQLCatalog() portal_catalog = portal.portal_catalog.getSQLCatalog()
query = getattr(portal_catalog, 'z_portal_ids_generate_id') query = portal_catalog.z_portal_ids_generate_id
commit = getattr(portal_catalog, 'z_portal_ids_commit') commit = portal_catalog.z_portal_ids_commit
if None in (query, commit):
raise AttributeError('Error while generating Id: ' \
'idTool_zGenerateId and/or idTool_zCommit could not ' \
'be found.')
try: try:
result = query(id_group=id_group, id_count=id_count, default=default) result = query(id_group=id_group, id_count=id_count, default=default)
finally: finally:
...@@ -304,14 +300,10 @@ class IdTool(BaseTool): ...@@ -304,14 +300,10 @@ class IdTool(BaseTool):
# XXX It's temporary, a New API will be implemented soon # XXX It's temporary, a New API will be implemented soon
# the code will be change # the code will be change
portal = self.getPortalObject() portal = self.getPortalObject()
query = getattr(portal, 'IdTool_zGetLastId', None) try:
if query is None: query = portal.IdTool_zGetLastId
portal_catalog = getattr(self, 'portal_catalog').getSQLCatalog() except AttributeError:
query = getattr(portal_catalog, 'z_portal_ids_get_last_id') query = portal.portal_catalog.getSQLCatalog().z_portal_ids_get_last_id
if query is None:
raise AttributeError('Error while getting last Id: ' \
'IdTool_zGetLastId could not ' \
'be found.')
result = query(id_group=id_group) result = query(id_group=id_group)
if len(result): if len(result):
try: try:
......
...@@ -944,7 +944,7 @@ class TemplateTool (BaseTool): ...@@ -944,7 +944,7 @@ class TemplateTool (BaseTool):
undependent_list.append(dependency_id) undependent_list.append(dependency_id)
if len(sorted_bt_list) != len(bt_list): if len(sorted_bt_list) != len(bt_list):
raise NotImplementedError("Circular dependencies on %s" % reverse_dependency_dict.keys()) raise NotImplementedError("Circular dependencies on %s" % list(reverse_dependency_dict))
else: else:
return sorted_bt_list return sorted_bt_list
...@@ -1192,7 +1192,7 @@ class TemplateTool (BaseTool): ...@@ -1192,7 +1192,7 @@ class TemplateTool (BaseTool):
candidate.uid)) candidate.uid))
break break
else: else:
raise BusinessTemplateMissingDependency("Unable to resolve dependencies for %s, options are %s" \ raise BusinessTemplateMissingDependency("Unable to resolve dependencies for %s, options are %s"
% (dep_id, provider_list)) % (dep_id, provider_list))
if len(template_title_list) > 0: if len(template_title_list) > 0:
...@@ -1224,7 +1224,7 @@ class TemplateTool (BaseTool): ...@@ -1224,7 +1224,7 @@ class TemplateTool (BaseTool):
if not checkAvailability(i[1].replace(".bt5", ""))] if not checkAvailability(i[1].replace(".bt5", ""))]
if not install_dependency and len(missing_dependency_list) > 0: if not install_dependency and len(missing_dependency_list) > 0:
raise BusinessTemplateMissingDependency("Impossible to install, please install the following dependencies before: %s" \ raise BusinessTemplateMissingDependency("Impossible to install, please install the following dependencies before: %s"
% [x[1] for x in missing_dependency_list]) % [x[1] for x in missing_dependency_list])
activate_kw = dict(activity="SQLQueue", tag="start_%s" % (time.time())) activate_kw = dict(activity="SQLQueue", tag="start_%s" % (time.time()))
......
...@@ -303,13 +303,12 @@ class Amount(Base, VariatedMixin): ...@@ -303,13 +303,12 @@ class Amount(Base, VariatedMixin):
variation_list = [] variation_list = []
for property_id, property_value in property_dict.items(): for property_id, property_value in property_dict.items():
if property_id not in variation_list: if property_id not in variation_list:
raise KeyError("Can not set the property variation '%s'" % \ raise KeyError("Can not set the property variation %r" % property_id)
property_id)
else: else:
try: try:
self.setProperty(property_id, property_value) self.setProperty(property_id, property_value)
except KeyError: except KeyError:
LOG("Amount", ERROR, "Can not set %s with value %s on %s" % \ LOG("Amount", ERROR, "Can not set %s with value %s on %s" %
(property_id, property_value, self.getRelativeUrl())) (property_id, property_value, self.getRelativeUrl()))
raise raise
......
...@@ -3,4 +3,4 @@ local_role_list = context.get_local_roles() ...@@ -3,4 +3,4 @@ local_role_list = context.get_local_roles()
for group, role_list in local_role_list: for group, role_list in local_role_list:
if 'Owner' in role_list: if 'Owner' in role_list:
return group return group
raise ValueError('Context (%s) has no owner (see local roles).' % (repr(context), )) raise ValueError('Context (%r) has no owner (see local roles).' % context)
...@@ -120,8 +120,8 @@ for skin_folder_id in skin_id_list: ...@@ -120,8 +120,8 @@ for skin_folder_id in skin_id_list:
# As the form will be deleted, no need to manage its fields # As the form will be deleted, no need to manage its fields
pass pass
else: else:
raise KeyError('Unexpected form handling %s for %s' % \ raise KeyError('Unexpected form handling %s for %s'
(modified_object_dict[form_path], form_path)) % (modified_object_dict[form_path], form_path))
elif form_id not in (field_library_id, alternate_field_library_id, elif form_id not in (field_library_id, alternate_field_library_id,
'Base_viewFieldLibrary',): 'Base_viewFieldLibrary',):
# Check that proxy field are proxified to field library # Check that proxy field are proxified to field library
......
...@@ -186,8 +186,6 @@ class IntrospectionTool(LogMixin, BaseTool): ...@@ -186,8 +186,6 @@ class IntrospectionTool(LogMixin, BaseTool):
raise IOError('The file path must be relative not absolute') raise IOError('The file path must be relative not absolute')
instance_home = getConfiguration().instancehome instance_home = getConfiguration().instancehome
file_path = os.path.join(instance_home, file_path) file_path = os.path.join(instance_home, file_path)
if not os.path.exists(file_path):
raise IOError('The file: %s does not exist.' % file_path)
if compressed: if compressed:
tmp_file_path = tempfile.mktemp(dir=tmp_file_path) tmp_file_path = tempfile.mktemp(dir=tmp_file_path)
...@@ -235,9 +233,6 @@ class IntrospectionTool(LogMixin, BaseTool): ...@@ -235,9 +233,6 @@ class IntrospectionTool(LogMixin, BaseTool):
Do a 'tail -f -n line_number filename' Do a 'tail -f -n line_number filename'
""" """
log_file = os.path.join(getConfiguration().instancehome, file_name) log_file = os.path.join(getConfiguration().instancehome, file_name)
if not os.path.exists(log_file):
raise IOError('The file: %s does not exist.' % log_file)
char_per_line = 75 char_per_line = 75
with open(log_file,'r') as tailed_file: with open(log_file,'r') as tailed_file:
......
...@@ -196,7 +196,7 @@ class SimulationTool(BaseTool): ...@@ -196,7 +196,7 @@ class SimulationTool(BaseTool):
if not as_text: if not as_text:
prop_value = category_tool.getCategoryValue(prop) prop_value = category_tool.getCategoryValue(prop)
if prop_value is None: if prop_value is None:
raise ValueError('Category %s does not exists' % prop) raise ValueError('Category %s does not exist' % prop)
property_uid_list.append(prop_value.getUid()) property_uid_list.append(prop_value.getUid())
else: else:
property_uid_list.append(prop) property_uid_list.append(prop)
...@@ -205,7 +205,7 @@ class SimulationTool(BaseTool): ...@@ -205,7 +205,7 @@ class SimulationTool(BaseTool):
if not as_text: if not as_text:
prop_value = category_tool.getCategoryValue(property_item) prop_value = category_tool.getCategoryValue(property_item)
if prop_value is None: if prop_value is None:
raise ValueError('Category %s does not exists' % property_item) raise ValueError('Category %s does not exist' % property_item)
property_uid_list.append(prop_value.getUid()) property_uid_list.append(prop_value.getUid())
else: else:
property_uid_list.append(property_item) property_uid_list.append(property_item)
...@@ -217,7 +217,7 @@ class SimulationTool(BaseTool): ...@@ -217,7 +217,7 @@ class SimulationTool(BaseTool):
if not as_text: if not as_text:
prop_value = category_tool.getCategoryValue(property_item) prop_value = category_tool.getCategoryValue(property_item)
if prop_value is None: if prop_value is None:
raise ValueError('Category %s does not exists' % property_item) raise ValueError('Category %s does not exist' % property_item)
tmp_uid_list.append(prop_value.getUid()) tmp_uid_list.append(prop_value.getUid())
else: else:
tmp_uid_list.append(property_item) tmp_uid_list.append(property_item)
...@@ -1140,14 +1140,12 @@ class SimulationTool(BaseTool): ...@@ -1140,14 +1140,12 @@ class SimulationTool(BaseTool):
return result return result
total_result = 0.0 total_result = 0.0
if len(result) > 0: if result:
if len(result) != 1: result, = result
raise ValueError('Sorry we must have only one')
result = result[0]
if hasattr(result, "converted_quantity"): try:
total_result = result.converted_quantity total_result = result.converted_quantity
else: except AttributeError:
inventory = result.total_quantity inventory = result.total_quantity
if inventory is not None: if inventory is not None:
total_result = inventory total_result = inventory
......
...@@ -2994,11 +2994,11 @@ class TestInventoryCacheTable(InventoryAPITestCase): ...@@ -2994,11 +2994,11 @@ class TestInventoryCacheTable(InventoryAPITestCase):
# Leads to rasing exception instead of calling self.assert[...] method. # Leads to rasing exception instead of calling self.assert[...] method.
if not success: if not success:
if ordered_check: if ordered_check:
raise AssertionError('Line %r\ndo not match\n %r' % \ raise AssertionError('Line %r\ndo not match\n %r' %
(inventory_list[inventory_position], (inventory_list[inventory_position],
criterion_dict)) criterion_dict))
else: else:
raise AssertionError('No line in %r\n match\n %r' % \ raise AssertionError('No line in %r\n match\n %r' %
(inventory_list, criterion_dict)) (inventory_list, criterion_dict))
# Check all expected lines have been found. # Check all expected lines have been found.
self.assertFalse(inventory_list) self.assertFalse(inventory_list)
......
...@@ -244,7 +244,8 @@ class TestXHTMLMixin(ERP5TypeTestCase): ...@@ -244,7 +244,8 @@ class TestXHTMLMixin(ERP5TypeTestCase):
stdout, stderr = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, stdout, stderr = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE,
close_fds=True).communicate(body) close_fds=True).communicate(body)
except OSError, e: except OSError, e:
raise OSError('%r\n%r' % (os.environ, e)) e.strerror += '\n%r' % os.environ
raise
if stdout: if stdout:
error_list.append((check_path, stdout)) error_list.append((check_path, stdout))
if error_list: if error_list:
......
...@@ -1402,9 +1402,10 @@ def get_field_meta_type_and_proxy_flag(field): ...@@ -1402,9 +1402,10 @@ def get_field_meta_type_and_proxy_flag(field):
try: try:
return field.getRecursiveTemplateField().meta_type, True return field.getRecursiveTemplateField().meta_type, True
except AttributeError: except AttributeError:
raise AttributeError('The proxy target of %s.%s field does not '\ raise AttributeError(
'exists. Please check the field setting.' % \ 'The proxy target of %s.%s field does not exist.'
(field.aq_parent.id, field.getId())) ' Please check the field settings.'
% (field.aq_parent.id, field.getId()))
else: else:
return field.meta_type, False return field.meta_type, False
......
...@@ -80,8 +80,8 @@ class PDFParser: ...@@ -80,8 +80,8 @@ class PDFParser:
command_output = commands.getstatusoutput('pdfinfo %s' % \ command_output = commands.getstatusoutput('pdfinfo %s' % \
temp_pdf_name) temp_pdf_name)
if command_output[0] != 0: if command_output[0] != 0:
raise ValueError('Error: convert command failed with the following'\ raise ValueError('Error: convert command failed with the following'
'error message : \n%s' % command_output[1]) ' error message:\n%s' % command_output[1])
# get the pdf page size # get the pdf page size
rawstr = r''' rawstr = r'''
...@@ -176,7 +176,7 @@ class PDFParser: ...@@ -176,7 +176,7 @@ class PDFParser:
command_output = commands.getstatusoutput('pdftk %s output %s flatten'\ command_output = commands.getstatusoutput('pdftk %s output %s flatten'\
% (temp_input_name, temp_output_name)) % (temp_input_name, temp_output_name))
if command_output[0] != 0: if command_output[0] != 0:
raise IOError("pdftk failed with the following error %s"\ raise IOError("pdftk failed with the following error %s"
% command_output[1]) % command_output[1])
temp_output = open(temp_output_name,'rb') temp_output = open(temp_output_name,'rb')
temp_output.seek(0) temp_output.seek(0)
......
...@@ -1258,8 +1258,8 @@ class SelectionTool( BaseTool, SimpleItem ): ...@@ -1258,8 +1258,8 @@ class SelectionTool( BaseTool, SimpleItem ):
relation_index += 1 relation_index += 1
if not relation_field_found: if not relation_field_found:
# We didn't find the field... # We didn't find the field...
raise SelectionError("SelectionTool: can not find the relation" \ raise SelectionError("SelectionTool: can not find the relation field %s"
" field %s" % index) % index)
else: else:
# Field found # Field found
field_key = field.generate_field_key() field_key = field.generate_field_key()
......
...@@ -28,7 +28,7 @@ ...@@ -28,7 +28,7 @@
from __future__ import absolute_import from __future__ import absolute_import
import unittest import unittest
from Products.ERP5OOo.tests.testOOoStyle import TestOOoStyle from .testOOoStyle import TestOOoStyle
class TestOOoStyleWithFlare(TestOOoStyle): class TestOOoStyleWithFlare(TestOOoStyle):
"""Tests ODF styles for ERP5 with Flare.""" """Tests ODF styles for ERP5 with Flare."""
......
...@@ -95,17 +95,16 @@ class CesarCipher: ...@@ -95,17 +95,16 @@ class CesarCipher:
crypted_letter = str(ord(login[i]) + self.encrypted_key[delta]) crypted_letter = str(ord(login[i]) + self.encrypted_key[delta])
#ord is the inverse of chr() for 8-bit (1111 1111 = 256) #ord is the inverse of chr() for 8-bit (1111 1111 = 256)
#so crypted_letter max id 512 #so crypted_letter max id 512
#we ajust lenght to be able to decrypt by block #we ajust length to be able to decrypt by block
crypted_letter = crypted_letter.rjust(self.block_length, '0') crypted_letter = crypted_letter.rjust(self.block_length, '0')
crypted_login += crypted_letter crypted_login += crypted_letter
return crypted_login return crypted_login
def decrypt(self, crypted_login): def decrypt(self, crypted_login):
login = '' login = ''
#check lenght of the string
clogin_length = len(crypted_login) clogin_length = len(crypted_login)
if clogin_length % self.block_length != 0: if clogin_length % self.block_length != 0:
raise ValueError("Lenght is not good") raise ValueError("Invalid length")
#decrypt block per block #decrypt block per block
position = 0 position = 0
key_length = len(self.encrypted_key) key_length = len(self.encrypted_key)
......
...@@ -73,17 +73,19 @@ def _setUserNameForAccessLog(username, REQUEST): ...@@ -73,17 +73,19 @@ def _setUserNameForAccessLog(username, REQUEST):
def initialize(context): def initialize(context):
from . import ERP5UserManager from . import (
from . import ERP5LoginUserManager ERP5UserManager,
from . import ERP5GroupManager ERP5LoginUserManager,
from . import ERP5RoleManager ERP5GroupManager,
from . import ERP5UserFactory ERP5RoleManager,
from . import ERP5KeyAuthPlugin ERP5UserFactory,
from . import ERP5ExternalAuthenticationPlugin ERP5KeyAuthPlugin,
from . import ERP5BearerExtractionPlugin ERP5ExternalAuthenticationPlugin,
from . import ERP5ExternalOauth2ExtractionPlugin ERP5BearerExtractionPlugin,
from . import ERP5AccessTokenExtractionPlugin ERP5ExternalOauth2ExtractionPlugin,
from . import ERP5DumbHTTPExtractionPlugin ERP5AccessTokenExtractionPlugin,
ERP5DumbHTTPExtractionPlugin,
)
registerMultiPlugin(ERP5UserManager.ERP5UserManager.meta_type) registerMultiPlugin(ERP5UserManager.ERP5UserManager.meta_type)
registerMultiPlugin(ERP5LoginUserManager.ERP5LoginUserManager.meta_type) registerMultiPlugin(ERP5LoginUserManager.ERP5LoginUserManager.meta_type)
......
...@@ -243,8 +243,8 @@ class CachingMethod: ...@@ -243,8 +243,8 @@ class CachingMethod:
cache_factory is the id of the cache_factory to use. cache_factory is the id of the cache_factory to use.
""" """
if not callable(callable_object): if not callable(callable_object):
raise CachedMethodError("callable_object %s is not callable" % str( raise CachedMethodError("callable_object %r is not callable"
callable_object)) % (callable_object,))
if not id: if not id:
raise CachedMethodError("id must be specified") raise CachedMethodError("id must be specified")
self.id = id self.id = id
......
...@@ -163,8 +163,8 @@ class CopyContainer: ...@@ -163,8 +163,8 @@ class CopyContainer:
pass # There is no activity tool pass # There is no activity tool
else: else:
if portal_activities.countMessage(path=ob.getPath())>0: if portal_activities.countMessage(path=ob.getPath())>0:
raise ActivityPendingError('Sorry, pending activities prevent ' \ raise ActivityPendingError(
+ 'changing id at this current stage') 'Sorry, pending activities prevent changing id at this current stage')
# Search for categories that have to be updated in sub objects. # Search for categories that have to be updated in sub objects.
self._recursiveSetActivityAfterTag(ob) self._recursiveSetActivityAfterTag(ob)
......
...@@ -247,7 +247,7 @@ if memcache is not None: ...@@ -247,7 +247,7 @@ if memcache is not None:
def _prefixKey(self, key): def _prefixKey(self, key):
if not isinstance(key, basestring): if not isinstance(key, basestring):
raise TypeError('Key %s is not a string. Only strings are supported as key in SharedDict' % (repr(key), )) raise TypeError('Key %r is not a string. Only strings are supported as key in SharedDict' % (key,))
return '%s_%s' % (self.prefix, key) return '%s_%s' % (self.prefix, key)
def __getitem__(self, key): def __getitem__(self, key):
...@@ -318,7 +318,7 @@ else: ...@@ -318,7 +318,7 @@ else:
if this function is called and memcachedtool is disabled, fail loudly if this function is called and memcachedtool is disabled, fail loudly
with a meaningfull message. with a meaningfull message.
""" """
raise RuntimeError('MemcachedTool is disabled. You should ask the'\ raise RuntimeError('MemcachedTool is disabled. You should ask the'
' server administrator to enable it by installing python-memcached.') ' server administrator to enable it by installing python-memcached.')
memcached_tool_configure = failingMethod memcached_tool_configure = failingMethod
......
...@@ -254,7 +254,7 @@ def convertToUpperCase(key): ...@@ -254,7 +254,7 @@ def convertToUpperCase(key):
return _cached_convertToUpperCase[key] return _cached_convertToUpperCase[key]
except KeyError: except KeyError:
if not isinstance(key, basestring): if not isinstance(key, basestring):
raise TypeError('%s is not a string' % (key,)) raise TypeError('%r is not a string' % (key,))
_cached_convertToUpperCase[key] = ''.join([part.capitalize() for part in key.split('_')]) _cached_convertToUpperCase[key] = ''.join([part.capitalize() for part in key.split('_')])
return _cached_convertToUpperCase[key] return _cached_convertToUpperCase[key]
...@@ -279,7 +279,7 @@ def convertToMixedCase(key): ...@@ -279,7 +279,7 @@ def convertToMixedCase(key):
a method name according to the ERP5 naming conventions a method name according to the ERP5 naming conventions
""" """
if not isinstance(key, basestring): if not isinstance(key, basestring):
raise TypeError('%s is not a string' % (key,)) raise TypeError('%r is not a string' % (key,))
parts = str(key).split('_', 1) parts = str(key).split('_', 1)
if len(parts) == 2: if len(parts) == 2:
parts[1] = convertToUpperCase(parts[1]) parts[1] = convertToUpperCase(parts[1])
......
...@@ -199,8 +199,8 @@ class Matrix(object): ...@@ -199,8 +199,8 @@ class Matrix(object):
""" """
script = self._getTypeBasedMethod('asCellRange', **kw) script = self._getTypeBasedMethod('asCellRange', **kw)
if script is None: if script is None:
raise UnboundLocalError("Did not find cell range script for portal type: %r" %\ raise LookupError("Did not find cell range script for portal type: %r"
self.getPortalType()) % self.getPortalType())
cell_range = script(base_id=base_id, matrixbox=0, **kw) cell_range = script(base_id=base_id, matrixbox=0, **kw)
self._setCellRange(base_id=base_id, *cell_range) self._setCellRange(base_id=base_id, *cell_range)
...@@ -334,7 +334,7 @@ class Matrix(object): ...@@ -334,7 +334,7 @@ class Matrix(object):
cell_id = self.keyToId(kw, base_id = base_id) cell_id = self.keyToId(kw, base_id = base_id)
if cell_id is None: if cell_id is None:
raise KeyError('Invalid key: %s' % str(kw)) raise KeyError('Invalid key: ' + str(kw))
cell = self.get(cell_id) cell = self.get(cell_id)
if cell is not None: if cell is not None:
......
...@@ -129,16 +129,16 @@ def DateTime_parse(self, st, datefmt=getDefaultDateFormat()): ...@@ -129,16 +129,16 @@ def DateTime_parse(self, st, datefmt=getDefaultDateFormat()):
# Check for month name: # Check for month name:
if MonthNumbers.has_key(s): if MonthNumbers.has_key(s):
v=MonthNumbers[s] v=MonthNumbers[s]
if month is None: month=v if month is None:
else: raise SyntaxError(st) month = v
continue continue
# Check for time modifier: # Check for time modifier:
if s in TimeModifiers: elif s in TimeModifiers:
if tm is None: tm=s if tm is None:
else: raise SyntaxError(st) tm = s
continue continue
# Check for and skip day of week: # Check for and skip day of week:
if DayOfWeekNames.has_key(s): elif DayOfWeekNames.has_key(s):
continue continue
raise SyntaxError(st) raise SyntaxError(st)
......
...@@ -83,9 +83,8 @@ if 1: # For easy diff with original ...@@ -83,9 +83,8 @@ if 1: # For easy diff with original
if args.has_key('optional') and args['optional']: if args.has_key('optional') and args['optional']:
return '' return ''
else: else:
err = 'Invalid empty string value for <em>%s</em>' % name raise ValueError(
raise ValueError(err) 'Invalid empty string value for <em>%s</em>' % name)
if not vs: if not vs:
if self.optional: return '' if self.optional: return ''
......
...@@ -98,9 +98,9 @@ class StringBaseValidator(Validator): ...@@ -98,9 +98,9 @@ class StringBaseValidator(Validator):
value = REQUEST.get(key, REQUEST.get('default_%s' % (key, ))) value = REQUEST.get(key, REQUEST.get('default_%s' % (key, )))
if value is None: if value is None:
if field.get_value('required'): if field.get_value('required'):
raise Exception('Required field %s has not been transmitted. Check that all required fields are in visible groups.' % (repr(field.id), )) raise Exception('Required field %r has not been transmitted. Check that all required fields are in visible groups.' % field.id)
else: else:
raise KeyError('Field %s is not present in request object.' % (repr(field.id), )) raise KeyError('Field %r is not present in request object.' % field.id)
if isinstance(value, str): if isinstance(value, str):
if field.has_value('whitespace_preserve'): if field.has_value('whitespace_preserve'):
if not field.get_value('whitespace_preserve'): if not field.get_value('whitespace_preserve'):
...@@ -538,7 +538,7 @@ class MultiSelectionValidator(Validator): ...@@ -538,7 +538,7 @@ class MultiSelectionValidator(Validator):
def validate(self, field, key, REQUEST): def validate(self, field, key, REQUEST):
if REQUEST.get('default_%s' % (key, )) is None: if REQUEST.get('default_%s' % (key, )) is None:
raise KeyError('Field %s is not present in request object (marker field default_%s not found).' % (repr(field.id), key)) raise KeyError('Field %r is not present in request object (marker field default_%s not found).' % (field.id, key))
values = REQUEST.get(key, []) values = REQUEST.get(key, [])
# NOTE: a hack to deal with single item selections # NOTE: a hack to deal with single item selections
if not isinstance(values, list): if not isinstance(values, list):
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
# -*- coding: utf-8 -*-
from . import XMLObjects from . import XMLObjects
from Products.Formulator.TALESField import TALESMethod from Products.Formulator.TALESField import TALESMethod
from Products.Formulator.MethodField import Method from Products.Formulator.MethodField import Method
......
...@@ -449,8 +449,8 @@ class HBTreeFolder2Base (Persistent): ...@@ -449,8 +449,8 @@ class HBTreeFolder2Base (Persistent):
def _checkId(self, id, allow_dup=0): def _checkId(self, id, allow_dup=0):
if not allow_dup and self.has_key(id): if not allow_dup and self.has_key(id):
raise BadRequestException('The id "%s" is invalid--' raise BadRequestException(
'it is already in use.' % id) 'The id %r is invalid--it is already in use.' % id)
def _setObject(self, id, object, roles=None, user=None, set_owner=1): def _setObject(self, id, object, roles=None, user=None, set_owner=1):
......
...@@ -42,10 +42,10 @@ def initialize(context): ...@@ -42,10 +42,10 @@ def initialize(context):
# (this is a common mistake). # (this is a common mistake).
filename = os.path.split(os.path.split(__file__)[0])[1] filename = os.path.split(os.path.split(__file__)[0])[1]
if filename != 'Localizer': if filename != 'Localizer':
message = ( raise RuntimeError(
"The Localizer product must be installed within the 'Products'" "The Localizer product must be installed within the 'Products'"
" folder with the name 'Localizer' (not '%s').") % filename " folder with the name 'Localizer' (not '%s').") % filename
raise RuntimeError(message) )
# XXX This code has been written by Cornel Nitu, it may be a solution to # XXX This code has been written by Cornel Nitu, it may be a solution to
# upgrade instances. # upgrade instances.
......
...@@ -161,7 +161,7 @@ class subprocesstransform: ...@@ -161,7 +161,7 @@ class subprocesstransform:
stderr=PIPE, close_fds=True) stderr=PIPE, close_fds=True)
data_out, data_err = process.communicate(input=data) data_out, data_err = process.communicate(input=data)
if process.returncode: if process.returncode:
raise OSError(data_err) raise OSError(data_err) # XXX
cache.setData(data_out) cache.setData(data_out)
return cache return cache
......
...@@ -60,7 +60,7 @@ class ERP5LDIFRecordList(LDIFRecordList): ...@@ -60,7 +60,7 @@ class ERP5LDIFRecordList(LDIFRecordList):
if dn!=None: if dn!=None:
raise ValueError('Two lines starting with dn: in one record.') raise ValueError('Two lines starting with dn: in one record.')
if not is_dn(attr_value): if not is_dn(attr_value):
raise ValueError('No valid string-representation of distinguished name %s.' % (repr(attr_value))) raise ValueError('No valid string-representation of distinguished name %r.' % (attr_value,))
dn = attr_value dn = attr_value
elif attr_type=='version' and dn is None: elif attr_type=='version' and dn is None:
version = 1 version = 1
...@@ -71,7 +71,7 @@ class ERP5LDIFRecordList(LDIFRecordList): ...@@ -71,7 +71,7 @@ class ERP5LDIFRecordList(LDIFRecordList):
if changetype!=None: if changetype!=None:
raise ValueError('Two lines starting with changetype: in one record.') raise ValueError('Two lines starting with changetype: in one record.')
if not valid_changetype_dict.has_key(attr_value): if not valid_changetype_dict.has_key(attr_value):
raise ValueError('changetype value %s is invalid.' % (repr(attr_value))) raise ValueError('changetype value %r is invalid.' % (attr_value,))
changetype = attr_value changetype = attr_value
attr_type, attr_value = self._parseAttrTypeandValue() attr_type, attr_value = self._parseAttrTypeandValue()
modify_list = [] modify_list = []
......
...@@ -97,8 +97,8 @@ MySQLdb_version_required = (0,9,2) ...@@ -97,8 +97,8 @@ MySQLdb_version_required = (0,9,2)
_v = getattr(_mysql, 'version_info', (0,0,0)) _v = getattr(_mysql, 'version_info', (0,0,0))
if _v < MySQLdb_version_required: if _v < MySQLdb_version_required:
raise NotSupportedError("ZMySQLDA requires at least MySQLdb %s, %s found" % \ raise NotSupportedError("ZMySQLDA requires at least MySQLdb %s, %s found"
(MySQLdb_version_required, _v)) % (MySQLdb_version_required, _v))
from MySQLdb.converters import conversions from MySQLdb.converters import conversions
from MySQLdb.constants import FIELD_TYPE, CR, ER, CLIENT from MySQLdb.constants import FIELD_TYPE, CR, ER, CLIENT
......
...@@ -195,7 +195,9 @@ class ColumnMap(object): ...@@ -195,7 +195,9 @@ class ColumnMap(object):
if alias is not None: if alias is not None:
self.resolveTable(table_name, alias, group=group) self.resolveTable(table_name, alias, group=group)
elif alias is not None and alias != existing_value: elif alias is not None and alias != existing_value:
raise ValueError('Table %r for group %r is aliased as %r, can\'t alias it now as %r' % (table_name, group, existing_value, alias)) raise ValueError(
"Table %r for group %r is aliased as %r, can't alias it now as %r"
% (table_name, group, existing_value, alias))
def _mapColumns(self, column_table_map, table_usage_dict, column_name_set, group, vote_result_dict): def _mapColumns(self, column_table_map, table_usage_dict, column_name_set, group, vote_result_dict):
mapping_dict = {} mapping_dict = {}
......
...@@ -52,8 +52,8 @@ class ZSQLBrain(Acquisition.Implicit): ...@@ -52,8 +52,8 @@ class ZSQLBrain(Acquisition.Implicit):
def getObject(self, REQUEST=None): def getObject(self, REQUEST=None):
"""Try to return the object for this record""" """Try to return the object for this record"""
if 'path' not in dir(self) and 'PATH' not in dir(self): if 'path' not in dir(self) and 'PATH' not in dir(self):
raise ValueError("Unable to getObject from ZSQLBrain if ZSQL Method "\ raise ValueError("Unable to getObject from ZSQLBrain if ZSQL Method does"
"does not retrieves the `path` column from catalog table.") " not retrieve the `path` column from catalog table.")
obj = self.aq_parent.unrestrictedTraverse(self.getPath()) obj = self.aq_parent.unrestrictedTraverse(self.getPath())
if obj is None: if obj is None:
if REQUEST is None: if REQUEST is None:
......
...@@ -151,8 +151,8 @@ class OperatorBase(object): ...@@ -151,8 +151,8 @@ class OperatorBase(object):
valueDefaultSearchTextRenderer)(value) valueDefaultSearchTextRenderer)(value)
def asSQLExpression(self, column, value_list, only_group_columns): def asSQLExpression(self, column, value_list, only_group_columns):
raise NotImplementedError('This method must be overloaded by a subclass ' \ raise NotImplementedError('This method must be overloaded by a subclass'
'to be able to get an SQL representation of this operator.') ' to be able to get an SQL representation of this operator.')
def __repr__(self): def __repr__(self):
return '<%s(%r) at %s>' % (self.__class__.__name__, self.getOperator(), id(self)) return '<%s(%r) at %s>' % (self.__class__.__name__, self.getOperator(), id(self))
......
...@@ -60,7 +60,7 @@ class AutoQuery(Query): ...@@ -60,7 +60,7 @@ class AutoQuery(Query):
self.operator = operator self.operator = operator
self.ignore_empty_string = kw.pop('ignore_empty_string', True) self.ignore_empty_string = kw.pop('ignore_empty_string', True)
if 'key' in kw and len(kw) > 2: if 'key' in kw and len(kw) > 2:
raise ValueError('"key" parameter cannot be used when more than one column is given. key=%r' % (kw['key'], )) raise ValueError('"key" parameter cannot be used when more than one column is given. key=%(key)r' % kw)
self.search_key = kw.pop('key', None) self.search_key = kw.pop('key', None)
def _createWrappedQuery(self, sql_catalog): def _createWrappedQuery(self, sql_catalog):
...@@ -107,7 +107,7 @@ class AutoQuery(Query): ...@@ -107,7 +107,7 @@ class AutoQuery(Query):
if self.table_alias_list is not None: if self.table_alias_list is not None:
query.setTableAliasList(self.table_alias_list) query.setTableAliasList(self.table_alias_list)
if query is None: if query is None:
raise ValueError('%r failed generating a query from its parameters.' % (self, )) raise ValueError('%r failed generating a query from its parameters.' % self)
self.wrapped_query = query self.wrapped_query = query
def _asSearchTextExpression(self, sql_catalog, column=None): def _asSearchTextExpression(self, sql_catalog, column=None):
......
...@@ -45,13 +45,13 @@ class Query(object): ...@@ -45,13 +45,13 @@ class Query(object):
""" """
To enable SQL rendering, overload this method in a subclass. To enable SQL rendering, overload this method in a subclass.
""" """
raise TypeError('A %s cannot be rendered as an SQL expression.' % (self.__class__.__name__, )) raise TypeError('A %s cannot be rendered as an SQL expression.' % self.__class__.__name__)
def _asSearchTextExpression(self, sql_catalog, column=None): def _asSearchTextExpression(self, sql_catalog, column=None):
""" """
To enable Search Text rendering, overload this method in a subclass. To enable Search Text rendering, overload this method in a subclass.
""" """
raise TypeError('A %s cannot be rendered as a SearchText expression.' % (self.__class__.__name__, )) raise TypeError('A %s cannot be rendered as a SearchText expression.' % self.__class__.__name__)
def asSearchTextExpression(self, sql_catalog, column=None): def asSearchTextExpression(self, sql_catalog, column=None):
return self._asSearchTextExpression(sql_catalog, column=column)[1] return self._asSearchTextExpression(sql_catalog, column=column)[1]
...@@ -60,7 +60,7 @@ class Query(object): ...@@ -60,7 +60,7 @@ class Query(object):
""" """
This method must always be overloaded by subclasses. This method must always be overloaded by subclasses.
""" """
raise NotImplementedError('%s is incompletely implemented.' % (self.__class__.__name__, )) raise NotImplementedError('%s is incompletely implemented.' % self.__class__.__name__)
verifyClass(IQuery, Query) verifyClass(IQuery, Query)
...@@ -67,7 +67,7 @@ class SimpleQuery(Query): ...@@ -67,7 +67,7 @@ class SimpleQuery(Query):
""" """
self.search_key = search_key self.search_key = search_key
if len(kw) != 1: if len(kw) != 1:
raise ValueError('SimpleQuery can support one and one only column. Got %r.' % (kw, )) raise ValueError('SimpleQuery can support one and one only column. Got %r.' % kw)
self.column, value = kw.popitem() self.column, value = kw.popitem()
# Usability improvement code (those changes should not be needed when # Usability improvement code (those changes should not be needed when
# this Query is instanciated by a SearchKey, as operator should be correct # this Query is instanciated by a SearchKey, as operator should be correct
......
...@@ -141,7 +141,7 @@ def getPeriodBoundaries(value): ...@@ -141,7 +141,7 @@ def getPeriodBoundaries(value):
elif isinstance(value, DateTime): elif isinstance(value, DateTime):
raise TypeError('Impossible to guess a precision from a DateTime type.') raise TypeError('Impossible to guess a precision from a DateTime type.')
else: else:
raise TypeError('Unknown date type: %r' % (value)) raise TypeError('Unknown date type: %r' % (value,))
delta = delta_list[delimiter_count] delta = delta_list[delimiter_count]
if callable(delta): if callable(delta):
delta = delta(first_date) delta = delta(first_date)
......
...@@ -243,21 +243,21 @@ class SearchKey(object): ...@@ -243,21 +243,21 @@ class SearchKey(object):
comparison_operator = single_operator_dict[value_range] comparison_operator = single_operator_dict[value_range]
elif value_range in dual_operator_dict: elif value_range in dual_operator_dict:
if not isinstance(actual_value, (tuple, list)): if not isinstance(actual_value, (tuple, list)):
raise TypeError('Operator %r requires value to be a '\ raise TypeError(
'tuple/list. (%r)' % (value_range, 'Operator %r requires value to be a tuple/list. (%r)'
search_value)) % (value_range, search_value))
if len(actual_value) != 2: if len(actual_value) != 2:
raise TypeError('Operator %r requires value to have a length '\ raise TypeError(
'of 2. len(%r) = %i (%r)' % (value_range, 'Operator %r requires value to have a length of 2. len(%r) = %s (%r)'
actual_value, len(actual_value), search_value)) % (value_range, actual_value, len(actual_value), search_value))
comparison_operator = dual_operator_dict[value_range] comparison_operator = dual_operator_dict[value_range]
logical_operator = 'and' logical_operator = 'and'
else: else:
raise ValueError('Unknown "range" value in %r' % (search_value, )) raise ValueError('Unknown "range" value in %r' % search_value)
if value_operator is not None: if value_operator is not None:
if not isinstance(value_operator, basestring): if not isinstance(value_operator, basestring):
raise TypeError('Operator must be of a string type. Got a %r' % \ raise TypeError('Operator must be of a string type. Got a %r'
(type(value_operator), )) % type(value_operator))
value_operator = value_operator.lower() value_operator = value_operator.lower()
if not isinstance(actual_value, (tuple, list)): if not isinstance(actual_value, (tuple, list)):
raise TypeError('When specifying an operator, query must be a list.') raise TypeError('When specifying an operator, query must be a list.')
......
...@@ -52,7 +52,7 @@ class ParserPool(object): ...@@ -52,7 +52,7 @@ class ParserPool(object):
parser_registry = self.parser_registry parser_registry = self.parser_registry
name = '.'.join((parser.__module__, parser.__name__)) name = '.'.join((parser.__module__, parser.__name__))
if name in parser_registry: if name in parser_registry:
raise ValueError('Duplicate parser for name %r' % (name, )) raise ValueError('Duplicate parser for name %r' % name)
parser_registry[name] = parser parser_registry[name] = parser
return name return name
......
...@@ -294,8 +294,8 @@ class ZCatalog(Folder, Persistent, Implicit): ...@@ -294,8 +294,8 @@ class ZCatalog(Folder, Persistent, Implicit):
ERP5Site_reindexAll. ERP5Site_reindexAll.
""" """
if self.getHotReindexingState() == HOT_REINDEXING_FINISHED_STATE: if self.getHotReindexingState() == HOT_REINDEXING_FINISHED_STATE:
raise Exception('cancelHotReindexing called while no Hot Reindexing '\ raise Exception(
'was runing. Nothing done.') 'cancelHotReindexing called while no Hot Reindexing was running. Nothing done.')
# Remove hot reindexing state # Remove hot reindexing state
self._setHotReindexingState(HOT_REINDEXING_FINISHED_STATE) self._setHotReindexingState(HOT_REINDEXING_FINISHED_STATE)
portal_activities = getToolByName(self, 'portal_activities') portal_activities = getToolByName(self, 'portal_activities')
...@@ -324,9 +324,9 @@ class ZCatalog(Folder, Persistent, Implicit): ...@@ -324,9 +324,9 @@ class ZCatalog(Folder, Persistent, Implicit):
transaction. transaction.
""" """
if self.getHotReindexingState() != HOT_REINDEXING_DOUBLE_INDEXING_STATE: if self.getHotReindexingState() != HOT_REINDEXING_DOUBLE_INDEXING_STATE:
raise Exception('playBackRecordedObjectList was called while '\ raise Exception('playBackRecordedObjectList was called while'
'hot_reindexing_state was not "%s". Playback aborted.' \ ' hot_reindexing_state was not %r. Playback aborted.'
% (HOT_REINDEXING_DOUBLE_INDEXING_STATE, )) % HOT_REINDEXING_DOUBLE_INDEXING_STATE)
catalog_object = self.getSQLCatalog(sql_catalog_id) catalog_object = self.getSQLCatalog(sql_catalog_id)
result = catalog_object.readRecordedObjectList(catalog=catalog) result = catalog_object.readRecordedObjectList(catalog=catalog)
if len(result): if len(result):
...@@ -338,7 +338,7 @@ class ZCatalog(Folder, Persistent, Implicit): ...@@ -338,7 +338,7 @@ class ZCatalog(Folder, Persistent, Implicit):
if obj is not None: if obj is not None:
obj.reindexObject(sql_catalog_id=sql_catalog_id) obj.reindexObject(sql_catalog_id=sql_catalog_id)
else: else:
raise ValueError('%s is not a valid value for "catalog".' % (catalog, )) raise ValueError('%r is not a valid value for "catalog".' % (catalog, ))
catalog_object.deleteRecordedObjectList(uid_list=[o.uid for o in result]) catalog_object.deleteRecordedObjectList(uid_list=[o.uid for o in result])
# Re-schedule the same action in case there are remaining rows in the # Re-schedule the same action in case there are remaining rows in the
# table. This can happen if the database connector limits the number # table. This can happen if the database connector limits the number
...@@ -432,10 +432,9 @@ class ZCatalog(Folder, Persistent, Implicit): ...@@ -432,10 +432,9 @@ class ZCatalog(Folder, Persistent, Implicit):
raise CatalogError('hot reindexing process is already running %s -%s' %(self, self.hot_reindexing_state)) raise CatalogError('hot reindexing process is already running %s -%s' %(self, self.hot_reindexing_state))
if source_sql_catalog_id == destination_sql_catalog_id: if source_sql_catalog_id == destination_sql_catalog_id:
raise CatalogError('Hot reindexing cannot be done with the same '\ raise CatalogError("Hot reindexing cannot be done with the same catalog"
'catalog as both source and destination. What'\ " as both source and destination. What you want to do"
' you want to do is a "clear catalog" and an '\ " is a 'clear catalog' and an 'ERP5Site_reindexAll'.")
'"ERP5Site_reindexAll".')
if source_sql_catalog_id != self.getDefaultSqlCatalogId(): if source_sql_catalog_id != self.getDefaultSqlCatalogId():
LOG('ZSQLCatalog', 0, 'Warning : Hot reindexing is started with a '\ LOG('ZSQLCatalog', 0, 'Warning : Hot reindexing is started with a '\
...@@ -1155,7 +1154,7 @@ class ZCatalog(Folder, Persistent, Implicit): ...@@ -1155,7 +1154,7 @@ class ZCatalog(Folder, Persistent, Implicit):
try: add_result=result.append try: add_result=result.append
except AttributeError: except AttributeError:
raise AttributeError(`result`) raise AttributeError(repr(result))
for id, ob in items: for id, ob in items:
if pre: p="%s/%s" % (pre, id) if pre: p="%s/%s" % (pre, id)
......
...@@ -103,7 +103,7 @@ class ReferenceQuery: ...@@ -103,7 +103,7 @@ class ReferenceQuery:
value = MatchList([value]) value = MatchList([value])
self.value = value self.value = value
elif len(kw) > 1: elif len(kw) > 1:
raise ValueError('kw must not have more than one item: %r' % (kw, )) raise ValueError('kw must not have more than one item: %r' % kw)
def __eq__(self, other): def __eq__(self, other):
if isinstance(other, SimpleQuery): if isinstance(other, SimpleQuery):
......
...@@ -713,13 +713,14 @@ class _FilesystemProxy( Folder ): ...@@ -713,13 +713,14 @@ class _FilesystemProxy( Folder ):
return self.__class__( key, self._fsobjs[ 'subdirs' ][ key ] return self.__class__( key, self._fsobjs[ 'subdirs' ][ key ]
).__of__( self.aq_parent ) ).__of__( self.aq_parent )
if key in _SUPPORT_FILES.keys(): try:
return _SUPPORT_FILES[ key ].__of__( self ) file = _SUPPORT_FILES[key]
except KeyError:
if default is not _MARKER: if default is _MARKER:
raise
return default return default
raise KeyError(key) return file.__of__(self)
security.declareProtected( View, 'listTestCases' ) security.declareProtected( View, 'listTestCases' )
def listTestCases( self, prefix=() ): def listTestCases( self, prefix=() ):
......
...@@ -3,6 +3,7 @@ import os, subprocess, re ...@@ -3,6 +3,7 @@ import os, subprocess, re
# test_suite is provided by 'run_test_suite' # test_suite is provided by 'run_test_suite'
from test_suite import ERP5TypeTestSuite from test_suite import ERP5TypeTestSuite
import sys import sys
from itertools import chain
HERE = os.path.dirname(__file__) HERE = os.path.dirname(__file__)
...@@ -34,10 +35,10 @@ class _ERP5(ERP5TypeTestSuite): ...@@ -34,10 +35,10 @@ class _ERP5(ERP5TypeTestSuite):
path = "%s/../" % HERE path = "%s/../" % HERE
component_re = re.compile(".*/([^/]+)/TestTemplateItem/portal_components" component_re = re.compile(".*/([^/]+)/TestTemplateItem/portal_components"
"/test\.[^.]+\.([^.]+).py$") "/test\.[^.]+\.([^.]+).py$")
for test_path in ( for test_path in chain(
glob('%s/product/*/tests/test*.py' % path) + glob(path + '/product/*/tests/test*.py'),
glob('%s/bt5/*/TestTemplateItem/test*.py' % path) + glob(path + '/bt5/*/TestTemplateItem/test*.py'),
glob('%s/bt5/*/TestTemplateItem/portal_components/test.*.test*.py' % path)): glob(path + '/bt5/*/TestTemplateItem/portal_components/test.*.test*.py')):
component_re_match = component_re.match(test_path) component_re_match = component_re.match(test_path)
if component_re_match is not None: if component_re_match is not None:
test_case = "%s:%s" % (component_re_match.group(1), test_case = "%s:%s" % (component_re_match.group(1),
...@@ -204,32 +205,30 @@ class ERP5BusinessTemplateCodingStyleTestSuite(_ERP5): ...@@ -204,32 +205,30 @@ class ERP5BusinessTemplateCodingStyleTestSuite(_ERP5):
"""Run coding style test on all business templates. """Run coding style test on all business templates.
""" """
def getTestList(self): def getTestList(self):
test_list = [] test_list = [
for business_template_path in ( os.path.basename(business_template_path)
glob('%s/../bt5/*' % HERE) for path in chain(
+ glob('%s/../product/ERP5/bootstrap/*' % HERE)): glob(HERE + '/../bt5/*'),
glob(HERE + '/../product/ERP5/bootstrap/*'))
# we skip coding style check for business templates having this marker # we skip coding style check for business templates having this marker
# property. Since the property is not exported (on purpose), modified business templates # property. Since the property is not exported (on purpose), modified business templates
# will be candidate for coding style test again. # will be candidate for coding style test again.
if os.path.isdir(business_template_path) and \ if not os.path.exists(path + '/bt/skip_coding_style_test')
not os.path.exists(os.path.join(business_template_path, 'bt/skip_coding_style_test')): ]
test_list.append(os.path.basename(business_template_path)) for path in glob(HERE + '/../product/*'):
for product_path in (glob('%s/../product/*' %(HERE)) if not os.path.exists(path + '/skip_coding_style_test'):
+ glob('%s/../bt5' % HERE)): test_list.append("Python3Style." + os.path.basename(path))
if os.path.isdir(product_path) and \
not os.path.exists(os.path.join(product_path, 'skip_coding_style_test')):
test_list.append("Python3Style."+os.path.basename(product_path))
return test_list return test_list
def run(self, full_test): def run(self, full_test):
if full_test.split('.')[0] == "Python3Style": if full_test.startswith("Python3Style."):
return self.runUnitTest('Python3StyleTest', TESTED_PRODUCT=full_test.split('.')[1]) return self.runUnitTest('Python3StyleTest', TESTED_PRODUCT=full_test[13:])
return self.runUnitTest('CodingStyleTest', TESTED_BUSINESS_TEMPLATE=full_test) return self.runUnitTest('CodingStyleTest', TESTED_BUSINESS_TEMPLATE=full_test)
def getLogDirectoryPath(self, *args, **kw): def getLogDirectoryPath(self, *args, **kw):
log_directory = os.path.join( log_directory = os.path.join(
self.log_directory, self.log_directory,
'{}-{}'.format(args[-1], kw.get('TESTED_BUSINESS_TEMPLATE', kw.get('TESTED_PRODUCT')))) args[-1] + '-' + (kw.get('TESTED_BUSINESS_TEMPLATE') or kw['TESTED_PRODUCT']))
os.mkdir(log_directory) os.mkdir(log_directory)
return log_directory return log_directory
......
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