diff --git a/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_period_workflow/scripts/checkDates.py b/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_period_workflow/scripts/checkDates.py index 881f3fec7ba861bada4bb8f18395eb4449f7532b..b804e3596d651b91bb767c0060c7f9aa62920800 100644 --- a/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_period_workflow/scripts/checkDates.py +++ b/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_period_workflow/scripts/checkDates.py @@ -10,7 +10,7 @@ start_date = closing_period.getStartDate() stop_date = closing_period.getStopDate() 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 = closing_period.getParentValue().searchFolder( simulation_state=valid_state_list, @@ -21,18 +21,18 @@ for period in period_list: period = period.getObject() if period.getSimulationState() in valid_state_list: 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.", - mapping={'date': start_date}) + mapping={'date': start_date})) if len(period_list) > 1: last_period = period_list[-1].getObject() if last_period.getId() == closing_period.getId(): last_period = period_list[-2].getObject() if (start_date - last_period.getStopDate()) > 1: - raise ValidationFailed, translateString( + raise ValidationFailed(translateString( "Last opened period ends on ${last_openned_date},"+ " this period starts on ${this_period_start_date}."+ " Accounting Periods must be consecutive.", mapping = { 'last_openned_date': last_period.getStopDate(), - 'this_period_start_date': start_date } ) + 'this_period_start_date': start_date } )) diff --git a/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_period_workflow/scripts/checkTransactionsState.py b/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_period_workflow/scripts/checkTransactionsState.py index 80c0f9834b7d0dda3700107f35c50b859c0c75ce..88d69e85e3a97318ee85e41fb731dda0d4d1f1e7 100644 --- a/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_period_workflow/scripts/checkTransactionsState.py +++ b/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_period_workflow/scripts/checkTransactionsState.py @@ -34,7 +34,7 @@ while section.getPortalType() == period.getPortalType(): section_category = section.getGroup(base=True) 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 ! @@ -81,5 +81,5 @@ movement_list = portal.portal_simulation.getMovementHistoryList( limit=1) if movement_list: - raise ValidationFailed, translateString( - "All Accounting Transactions for this organisation during the period have to be closed first.") + raise ValidationFailed(translateString( + "All Accounting Transactions for this organisation during the period have to be closed first.")) diff --git a/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_workflow/scripts/validateTransactionLines.py b/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_workflow/scripts/validateTransactionLines.py index 836e1eaacf2291cc4e3e7dcd594556434ef06006..6f379388d48ade6097bbd76466fa7a072b97b9c7 100644 --- a/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_workflow/scripts/validateTransactionLines.py +++ b/bt5/erp5_accounting/WorkflowTemplateItem/portal_workflow/accounting_workflow/scripts/validateTransactionLines.py @@ -32,21 +32,21 @@ for line in transaction_lines: ): if account is not None and account.getValidationState() != 'validated': - raise ValidationFailed, translateString( + raise ValidationFailed(translateString( "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\ third_party.getValidationState() in invalid_state_list: - raise ValidationFailed, translateString( + raise ValidationFailed(translateString( "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.getValidationState() in invalid_state_list: - raise ValidationFailed, translateString( + raise ValidationFailed(translateString( "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'): # also check that currencies are consistent if we use this quantity for @@ -54,11 +54,11 @@ for line in transaction_lines: bank_account_currency = bank_account.getProperty('price_currency') if bank_account_currency is not None and \ bank_account_currency != line.getResource(): - raise ValidationFailed, translateString( + raise ValidationFailed(translateString( "Bank Account ${bank_account_reference} " "uses ${bank_account_currency} as default currency.", mapping=dict(bank_account_reference=bank_account.getReference(), - bank_account_currency=bank_account.getPriceCurrencyReference())) + bank_account_currency=bank_account.getPriceCurrencyReference()))) source_currency = None source_section = line.getSourceSectionValue() diff --git a/bt5/erp5_accounting_l10n_in/SkinTemplateItem/portal_skins/erp5_accounting_l10n_in/AccountModule_getTrialBalanceReportSectionList.py b/bt5/erp5_accounting_l10n_in/SkinTemplateItem/portal_skins/erp5_accounting_l10n_in/AccountModule_getTrialBalanceReportSectionList.py index a033f80bc4fad3a12ec69d667ad4c246cd72f0fb..016f8c32254f93cb5e3812e4389e46fdd1ca173b 100644 --- a/bt5/erp5_accounting_l10n_in/SkinTemplateItem/portal_skins/erp5_accounting_l10n_in/AccountModule_getTrialBalanceReportSectionList.py +++ b/bt5/erp5_accounting_l10n_in/SkinTemplateItem/portal_skins/erp5_accounting_l10n_in/AccountModule_getTrialBalanceReportSectionList.py @@ -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 # or a flat list of all accounts. if request.get('tree_mode', False): - raise 'Tree mode no longer supported' + raise ValueError('Tree mode no longer supported') result = [] params = { diff --git a/bt5/erp5_accounting_ui_test/SkinTemplateItem/portal_skins/erp5_accounting_ui_test/AccountingZuite_createAccountingTransactionList.py b/bt5/erp5_accounting_ui_test/SkinTemplateItem/portal_skins/erp5_accounting_ui_test/AccountingZuite_createAccountingTransactionList.py index 7ddf745376efdc6e9458aae33de23edc9685f9c4..183002a5a26ac13dc9747b56fea47558c6d571dc 100644 --- a/bt5/erp5_accounting_ui_test/SkinTemplateItem/portal_skins/erp5_accounting_ui_test/AccountingZuite_createAccountingTransactionList.py +++ b/bt5/erp5_accounting_ui_test/SkinTemplateItem/portal_skins/erp5_accounting_ui_test/AccountingZuite_createAccountingTransactionList.py @@ -6,7 +6,7 @@ section_title = 'My Organisation' portal = context.getPortalObject() accounting_module = portal.accounting_module year = 2005 -default_date = DateTime(year, 01, 01) +default_date = DateTime(year, 1, 1) business_process = portal.portal_catalog.getResultValue( reference=('default_erp5_business_process', # erp5_configurator diff --git a/bt5/erp5_accounting_ui_test/SkinTemplateItem/portal_skins/erp5_accounting_ui_test/AccountingZuite_createAccountingTransactionListSalesAndPayments.py b/bt5/erp5_accounting_ui_test/SkinTemplateItem/portal_skins/erp5_accounting_ui_test/AccountingZuite_createAccountingTransactionListSalesAndPayments.py index 9b02f3ab7b316c2fede121ab4e8cf5e9d9bc25b3..e918640346f945fb71f845542ba7d83eada6b877 100644 --- a/bt5/erp5_accounting_ui_test/SkinTemplateItem/portal_skins/erp5_accounting_ui_test/AccountingZuite_createAccountingTransactionListSalesAndPayments.py +++ b/bt5/erp5_accounting_ui_test/SkinTemplateItem/portal_skins/erp5_accounting_ui_test/AccountingZuite_createAccountingTransactionListSalesAndPayments.py @@ -101,8 +101,8 @@ for month in range(1, month_count + 1): source_payment=getBankAccountByTitle('My default bank account'), destination_section=getOrganisationByTitle(client_title), created_by_builder=1, - start_date=DateTime(year, month, day, 01, 01) + 10, - stop_date=DateTime(year, month, day, 01, 01) + 10, + start_date=DateTime(year, month, day, 1, 1) + 10, + stop_date=DateTime(year, month, day, 1, 1) + 10, causality_value=tr, resource=euro_resource, ) diff --git a/bt5/erp5_administration/SkinTemplateItem/portal_skins/erp5_administration/ERP5Site_dumpPortalSkinsContent.py b/bt5/erp5_administration/SkinTemplateItem/portal_skins/erp5_administration/ERP5Site_dumpPortalSkinsContent.py index 99ee7605d3534c76168c38ed61c406aa26196e6b..775317b2b5c947ac1f21d9ec3bb355d79442f137 100644 --- a/bt5/erp5_administration/SkinTemplateItem/portal_skins/erp5_administration/ERP5Site_dumpPortalSkinsContent.py +++ b/bt5/erp5_administration/SkinTemplateItem/portal_skins/erp5_administration/ERP5Site_dumpPortalSkinsContent.py @@ -13,7 +13,7 @@ def getSkinHash(skin, skin_container): content = skin.formXML() if isinstance(content, unicode): content = content.encode('utf8', 'repr') - except AttributeError, e: + except AttributeError as e: # This can happen with dead proxy fields. content = "broken form %s" % e content = 'ignore' diff --git a/bt5/erp5_advanced_invoicing/SkinTemplateItem/portal_skins/erp5_advanced_invoicing/SaleInvoice_postGeneration.py b/bt5/erp5_advanced_invoicing/SkinTemplateItem/portal_skins/erp5_advanced_invoicing/SaleInvoice_postGeneration.py index 9b1ae194ae72fad70902313798977ee6208b3579..ac8e65906edeed212f248c78ff8eb3da02dc9684 100644 --- a/bt5/erp5_advanced_invoicing/SkinTemplateItem/portal_skins/erp5_advanced_invoicing/SaleInvoice_postGeneration.py +++ b/bt5/erp5_advanced_invoicing/SkinTemplateItem/portal_skins/erp5_advanced_invoicing/SaleInvoice_postGeneration.py @@ -4,7 +4,7 @@ the new Invoice. from Products.ERP5Type.Message import translateString 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 diff --git a/bt5/erp5_apparel/SkinTemplateItem/portal_skins/erp5_apparel/ApparelFabricItem_fastInput.py b/bt5/erp5_apparel/SkinTemplateItem/portal_skins/erp5_apparel/ApparelFabricItem_fastInput.py index c30b96a2600b41ef28a066fb3706097e487369b6..29fb9c0d65f5181e979e59e6c2bd40273811e155 100644 --- a/bt5/erp5_apparel/SkinTemplateItem/portal_skins/erp5_apparel/ApparelFabricItem_fastInput.py +++ b/bt5/erp5_apparel/SkinTemplateItem/portal_skins/erp5_apparel/ApparelFabricItem_fastInput.py @@ -196,7 +196,7 @@ try: cell.edit(quantity=total_quantity) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: redirect_url = '%s/view?%s' % ( context.absolute_url() , 'portal_status_message=%s' % localizer.erp5_ui.gettext("input failed.") ) diff --git a/bt5/erp5_archive/SkinTemplateItem/portal_skins/erp5_archive/Archive_createInventory.py b/bt5/erp5_archive/SkinTemplateItem/portal_skins/erp5_archive/Archive_createInventory.py index fe68e476854ad32aaeeb49cd932ea79034bacc4a..84080ed121dd78b8f264adec9eacd44deb0fb9ad 100644 --- a/bt5/erp5_archive/SkinTemplateItem/portal_skins/erp5_archive/Archive_createInventory.py +++ b/bt5/erp5_archive/SkinTemplateItem/portal_skins/erp5_archive/Archive_createInventory.py @@ -69,7 +69,7 @@ for inventory in node_inventory_list: inv_line.updateCellRange(script_id='CashDetail_asCellRange', base_id=base_id) # create cell cell_range_key_list = inv_line.getCellRangeKeyList(base_id=base_id) - if cell_range_key_list <> [[None, None]] : + if cell_range_key_list != [[None, None]] : for k in cell_range_key_list: category_list = filter(lambda k_item: k_item is not None, k) cell = inv_line.newCell(*k, **line_kwd) diff --git a/bt5/erp5_archive/WorkflowTemplateItem/portal_workflow/archive_inventory_workflow/scripts/validateConsistency.py b/bt5/erp5_archive/WorkflowTemplateItem/portal_workflow/archive_inventory_workflow/scripts/validateConsistency.py index 59c45bd31bcf7bb4b90f781555f36e84c5acc0e3..b21a55d09297c82f6cbbc099f90b6d409ab0db7f 100644 --- a/bt5/erp5_archive/WorkflowTemplateItem/portal_workflow/archive_inventory_workflow/scripts/validateConsistency.py +++ b/bt5/erp5_archive/WorkflowTemplateItem/portal_workflow/archive_inventory_workflow/scripts/validateConsistency.py @@ -8,17 +8,17 @@ start_date = inventory.getStartDate() if start_date is None: text = "Sorry, you must define the inventory date" message = Message(domain='ui', message=text) - raise ValidationFailed, message + raise ValidationFailed(message) # Make sure the node is defined node = inventory.getDestination() if node is None: text = "Sorry, you must define the inventory warehouse" message = Message(domain='ui', message=text) - raise ValidationFailed, message + raise ValidationFailed(message) # use of the constraint error_list = inventory.checkConsistency() if len(error_list) > 0: - raise ValidationFailed, (error_list[0].getTranslatedMessage(),) + raise ValidationFailed(error_list[0].getTranslatedMessage(),) diff --git a/bt5/erp5_archive/WorkflowTemplateItem/portal_workflow/archive_workflow/scripts/checkArchive.py b/bt5/erp5_archive/WorkflowTemplateItem/portal_workflow/archive_workflow/scripts/checkArchive.py index 8281d1ebf9eaaa2994930edaff84546d08e1290c..d330f8d1141c9f917eb911f696d525157dae0a7d 100644 --- a/bt5/erp5_archive/WorkflowTemplateItem/portal_workflow/archive_workflow/scripts/checkArchive.py +++ b/bt5/erp5_archive/WorkflowTemplateItem/portal_workflow/archive_workflow/scripts/checkArchive.py @@ -11,7 +11,7 @@ catalog_id = archive.getCatalogId() if "deferred" not in archive.getDeferredConnectionId(): 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): return cmp(a.getStopDateRangeMax(), b.getStopDateRangeMax()) @@ -32,7 +32,7 @@ if archive.getStopDateRangeMax() is not None: break if previous_archive.getStopDateRangeMax().Date() != min_stop_date: msg = Message(domain='ui', message='Archive are not contiguous.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) else: previous_archive_list = [x.getObject() for x in archive.portal_catalog(portal_type="Archive", validation_state='ready')] @@ -47,7 +47,7 @@ else: break if previous_archive.getStopDateRangeMax().Date() != min_stop_date: msg = Message(domain='ui', message='Archive are not contiguous.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Check the catalog @@ -57,4 +57,4 @@ previous_archive_list = [x.getObject() for x in archive.portal_catalog(portal_ty for arch in previous_archive_list: if arch.getCatalogId() == catalog_id and arch is not previous_archive: msg = Message(domain='ui', message='Use of a former catalog is prohibited.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashExchange_getBaobabSource.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashExchange_getBaobabSource.py index 0f30da71ed8a19fb8d46634d67e63c9f3078a098..c1007ae3a71778a019fbb29768803dc368263619 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashExchange_getBaobabSource.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashExchange_getBaobabSource.py @@ -9,4 +9,4 @@ for site in site_list: return site from Products.ERP5Type.Message import Message message = Message(domain="ui", message="The owner is not assigned to the right vault.") -raise ValueError,message +raise ValueError(message) diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashToCurrencyPurchase_getBaobabSource.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashToCurrencyPurchase_getBaobabSource.py index 0f30da71ed8a19fb8d46634d67e63c9f3078a098..c1007ae3a71778a019fbb29768803dc368263619 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashToCurrencyPurchase_getBaobabSource.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashToCurrencyPurchase_getBaobabSource.py @@ -9,4 +9,4 @@ for site in site_list: return site from Products.ERP5Type.Message import Message message = Message(domain="ui", message="The owner is not assigned to the right vault.") -raise ValueError,message +raise ValueError(message) diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashToCurrencySale_getBaobabSource.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashToCurrencySale_getBaobabSource.py index 0f30da71ed8a19fb8d46634d67e63c9f3078a098..c1007ae3a71778a019fbb29768803dc368263619 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashToCurrencySale_getBaobabSource.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CashToCurrencySale_getBaobabSource.py @@ -9,4 +9,4 @@ for site in site_list: return site from Products.ERP5Type.Message import Message message = Message(domain="ui", message="The owner is not assigned to the right vault.") -raise ValueError,message +raise ValueError(message) diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/ClassificationSurvey_init.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/ClassificationSurvey_init.py index 645845dcf023d2b1ff49bf4181a440e0f4188c23..def983a56fd68516ab9ecde9c86c8bc526a5743e 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/ClassificationSurvey_init.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/ClassificationSurvey_init.py @@ -1,6 +1,6 @@ site_list = context.Baobab_getUserAssignedSiteList() if len(site_list) == 0: - raise ValueError, "Unable to determine site" + raise ValueError("Unable to determine site") site = site_list[0] site = context.Baobab_getVaultSite(site) diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CounterRendering_getBaobabSource.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CounterRendering_getBaobabSource.py index d3722e978563d16e9f0e2adc8e39ad9b2a700f0c..bf02853bf1acba335321bcf91bccadd6608ac7dd 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CounterRendering_getBaobabSource.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CounterRendering_getBaobabSource.py @@ -9,4 +9,4 @@ for site in site_list: return site from Products.ERP5Type.Message import Message message = Message(domain="ui", message="Object owner is not assigned to a counter.") -raise ValueError,message +raise ValueError(message) diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CurrencySaleOrPurchase_validateVaultBalance.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CurrencySaleOrPurchase_validateVaultBalance.py index 92bae60b0b819586c569b823efbd178afb11532d..b5dda91e9037d996b719bec8ea16b958dded5913 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CurrencySaleOrPurchase_validateVaultBalance.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/CurrencySaleOrPurchase_validateVaultBalance.py @@ -21,15 +21,15 @@ else: # check if an exchange rate is defined if total_quantity is None: - raise ValidationFailed, (Message(domain='ui', + raise ValidationFailed(Message(domain='ui', message="No exchange rate defined for this currency at document date.")) # check resource on currency fastinput doc_resource = context.getResource() for line in context.contentValues(portal_type=foreign_currency_portal_type): if line.getResourceValue().getPriceCurrency() != doc_resource: - raise ValidationFailed, (Message(domain="ui", - message="Resource defined on document is different from currency cash."), ) + raise ValidationFailed(Message(domain="ui", + message="Resource defined on document is different from currency cash."),) # check outgoing amount if is_currency_sale: @@ -38,7 +38,7 @@ else: amount = context.getQuantity() if amount is None or amount <= 0: msg = Message(domain="ui", message="Amount is not valid.") - raise ValidationFailed, (msg, ) + raise ValidationFailed(msg,) # Reverse error messages in cash of currency purchase default_msg = "Received amount is different from input cash." @@ -49,18 +49,18 @@ if not is_currency_sale: # Check default currency amount consistency if context.getTotalPrice(portal_type=[default_currency_portal_type, 'Cash Delivery Cell'], fast=0) != context.getQuantity(): - raise ValidationFailed, (Message(domain="ui", message=default_msg), ) + raise ValidationFailed(Message(domain="ui", message=default_msg),) # Check foreign currency amount consistency if context.getTotalPrice(portal_type=[foreign_currency_portal_type, 'Cash Delivery Cell'], fast=0) != context.getSourceTotalAssetPrice(): - raise ValidationFailed, (Message(domain="ui", message=foreign_msg), ) + raise ValidationFailed(Message(domain="ui", message=foreign_msg),) # Check outgoing inventory resource_one = context.CashDelivery_checkCounterInventory( portal_type=outgoing_portal_type) if resource_one == 2: - raise ValidationFailed, (Message(domain="ui", message="No Resource."), ) + raise ValidationFailed(Message(domain="ui", message="No Resource."),) elif resource_one == 1: - raise ValidationFailed, (Message(domain="ui", - message="Insufficient balance"), ) + raise ValidationFailed(Message(domain="ui", + message="Insufficient balance"),) diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/DestructionSurvey_init.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/DestructionSurvey_init.py index 1f87574ad2f7f4ae75bb2d65f132abc5b0ff3180..5803ca5ae8aab2592b145187612401a4711a71df 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/DestructionSurvey_init.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/DestructionSurvey_init.py @@ -2,7 +2,7 @@ site = context.Baobab_getUserAssignedRootSite() if site in ('', None): from Products.ERP5Type.Message import Message message = Message(domain="ui", message="The owner is not assigned to the right vault.") - raise ValueError,message + raise ValueError(message) context.setSource("%s/caveau/auxiliaire/encaisse_des_billets_a_ventiler_et_a_detruire" %(site,)) diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/InternalMoneyDeposit_getBaobabDestination.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/InternalMoneyDeposit_getBaobabDestination.py index 12722a51bb6028094ea223d7e077e6f7ae58b595..4949bb86d40de8e6aedd439eac79e6b4ee056698 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/InternalMoneyDeposit_getBaobabDestination.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/InternalMoneyDeposit_getBaobabDestination.py @@ -9,4 +9,4 @@ for site in site_list: return site + '/encaisse_des_billets_et_monnaies/entrante' from Products.ERP5Type.Message import Message message = Message(domain="ui", message="Object owner is not assigned to a counter.") -raise ValueError,message +raise ValueError(message) diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/MoneyDeposit_getBaobabDestination.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/MoneyDeposit_getBaobabDestination.py index ac0f0ea7c581d06744b0e51c235ce0244ad242ee..590cf8825c81db24c9bd0a3b61b13a9b94d1450e 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/MoneyDeposit_getBaobabDestination.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/MoneyDeposit_getBaobabDestination.py @@ -15,6 +15,6 @@ if source_trade is None or context.getSimulationState() != 'delivered': return source_trade from Products.ERP5Type.Message import Message message = Message(domain="ui", message="The owner is not assigned to the right vault.") - raise ValueError,message + raise ValueError(message) else: return source_trade diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/MutilatedBanknote_init.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/MutilatedBanknote_init.py index 4afa26fed38e8b0259862d4897417fb2a361af5f..1424e81850be17628ec4923970fe6ae7399c4e60 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/MutilatedBanknote_init.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/MutilatedBanknote_init.py @@ -1,7 +1,7 @@ user_site = context.Baobab_getUserAssignedRootSite() user_counter = context.Baobab_getUserAssignedSiteList()[0] if user_site in ('', None) or user_counter in ('', None): - raise ValueError, "Unable to determine site" + raise ValueError("Unable to determine site") if 'guichet' not in user_counter: - raise ValueError, "You are not assigned to a counter" + raise ValueError("You are not assigned to a counter") context.edit(source=user_counter, source_trade=user_site) diff --git a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/OutgoingCashSortingCell_getBaobabDestination.py b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/OutgoingCashSortingCell_getBaobabDestination.py index 5dc513cbf3880436b3899edf96d9cf41283e405d..22a21f20c1d9b8d53217d17e5ec76b36e92b524d 100644 --- a/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/OutgoingCashSortingCell_getBaobabDestination.py +++ b/bt5/erp5_banking_cash/SkinTemplateItem/portal_skins/erp5_banking_cash/OutgoingCashSortingCell_getBaobabDestination.py @@ -21,7 +21,7 @@ if resource_portal_type == 'Banknote': # This case is/must be protected by a constraint: a document containing a # line matching this condition must not get validated. # XXX: Maybe we should return None here instead of raising. - raise Exception, 'Should not be here' + raise Exception('Should not be here') elif emission_letter == site_letter: if cash_status == "valid": # banknote 'valid' from same country -> caisse de reserve / billets et monnaies diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_balance_regulation_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_balance_regulation_workflow/scripts/validateVaultBalance.py index 08e4e82c4cca8d9d076f98def419e73387f0cf08..400a704091b8fe6d11864b0634d25a989f87f3b5 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_balance_regulation_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_balance_regulation_workflow/scripts/validateVaultBalance.py @@ -9,7 +9,7 @@ vault = transaction.getSource() if not (vault.endswith('encaisse_des_billets_et_monnaies') or vault.endswith('encaisse_des_externes')or \ 'encaisse_des_devises' in vault): msg = Message(domain="ui", message="Invalid source.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) root_site = context.Baobab_getVaultSite(vault) site_emission_letter = context.Baobab_getSiteEmissionLetter(site=root_site) @@ -17,7 +17,7 @@ if vault.endswith('encaisse_des_externes'): for line in transaction.getMovementList(portal_type=['Outgoing Cash Balance Regulation Line','Cash Delivery Cell']): if line.getEmissionLetter() == site_emission_letter: msg = Message(domain="ui", message="You must not select the local emission letter.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check resource between line and document doc_resource = transaction.getResource() @@ -27,10 +27,10 @@ for line in transaction.contentValues(portal_type=['Outgoing Cash Balance Regula res = line.getResourceValue() if res.getPriceCurrency() != doc_resource: msg = Message(domain="ui", message="Resource defined on document is different from input cash.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if resource_type is not None and res.getPortalType() != resource_type: msg = Message(domain="ui", message="You can't use both banknote and coin on same document.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) resource_type = res.getPortalType() # check again that we are in the good accounting date @@ -56,19 +56,19 @@ outgoing_total = transaction.getTotalPrice(portal_type =['Outgoing Cash Balance if amount != incoming_total: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if resource_one == 2: msg = Message(domain="ui", message="No resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif resource_one == 1: msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if resource_two == 2: msg = Message(domain="ui", message="No resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if incoming_total != outgoing_total: msg = Message(domain="ui", message="No same balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_exchange_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_exchange_workflow/scripts/validateVaultBalance.py index 1763dfc91094dc8fce5ea436a83c7464473d51fb..3227071bc6a18eda1c9120b7d81f00eea454ebb1 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_exchange_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_exchange_workflow/scripts/validateVaultBalance.py @@ -39,16 +39,16 @@ amount_total = transaction.getSourceTotalAssetPrice() if resource_two == 2: msg = Message(domain="ui", message="No resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif resource_two == 1: msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if incoming_total != outgoing_total: msg = Message(domain="ui", message="No same balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if amount_total != outgoing_total: msg = Message(domain="ui", message="Amount not correct.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_new_not_emitted_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_new_not_emitted_workflow/scripts/validateVaultBalance.py index f85f041786bab0dcbef786ba678b967b335885c5..7e2a085da3860e40828434a6fe9c285b6921d4fc 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_new_not_emitted_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_new_not_emitted_workflow/scripts/validateVaultBalance.py @@ -14,14 +14,14 @@ transaction.Baobab_checkCounterDateOpen(site=vault, date=transaction.getStartDat vliste = transaction.checkConsistency() transaction.log('vliste', vliste) if len(vliste) != 0: - raise ValidationFailed, (vliste[0].getMessage(),) + raise ValidationFailed(vliste[0].getMessage(),) portal_type_with_no_space = transaction.getPortalType().replace(' ','') check_path_script = getattr(transaction,'%s_checkPath' % portal_type_with_no_space,None) if check_path_script is not None: message = check_path_script() if message is not None: - raise ValidationFailed, (message,) + raise ValidationFailed(message,) resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_type='Cash Movement New Not Emitted Line') @@ -32,10 +32,10 @@ total_price = transaction.getTotalPrice(portal_type=['Cash Movement New Not Emit if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_workflow/scripts/setMovementStopDate.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_workflow/scripts/setMovementStopDate.py index 3c88affcab2a226abc8aa79d10bb749ba3cbbae7..aa3170748d4fca9e3ca1d0a3986ea3c4eaf5a5f7 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_workflow/scripts/setMovementStopDate.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_workflow/scripts/setMovementStopDate.py @@ -8,6 +8,6 @@ transaction = state_change['object'] stop_date_key = 'stop_date' if not state_change.kwargs.has_key(stop_date_key): msg = Message(domain = "ui", message="No stop date provided") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) transaction.setStopDate(state_change.kwargs[stop_date_key]) context.validateDestinationCounterDate(state_change, **kw) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_workflow/scripts/validateVaultBalance.py index 97c4737bd0b564f51513f613f1280c8a9932a8a9..16a5bfa45a31cc92d9219fe7281b18b10a0f7b01 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_movement_workflow/scripts/validateVaultBalance.py @@ -9,12 +9,12 @@ vaultDestination = transaction.getDestination() if vault is None: msg = Message(domain="ui", message="Sorry, you must define a source.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if transaction.isCurrencyHandover() and vaultDestination is not None: msg = Message(domain="ui", message="Sorry, you must not set a destination in case of currency handover.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # if not transaction.isCurrencyHandover() and vaultDestination is not None: # msg = Message(domain="ui", @@ -24,7 +24,7 @@ if transaction.isCurrencyHandover() and vaultDestination is not None: if not transaction.isCurrencyHandover() and vaultDestination is None: msg = Message(domain="ui", message="Sorry, you must define a destination.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # use of the constraint : Test source and destination @@ -46,7 +46,7 @@ if check_path_script is not None: message = check_path_script() transaction.log('check_path_script','found') if message is not None: - raise ValidationFailed, (message,) + raise ValidationFailed(message,) resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_type='Cash Delivery Line') @@ -57,10 +57,10 @@ total_price = transaction.getTotalPrice(portal_type=['Cash Delivery Line','Cash if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_sorting_statistic_workflow/scripts/checkConsistency.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_sorting_statistic_workflow/scripts/checkConsistency.py index c20b24655a6ddd65bf44e628c7329cf8d7a205a1..b2045df9a8d506712acce31c6cded3a9ebd75c1b 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_sorting_statistic_workflow/scripts/checkConsistency.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_sorting_statistic_workflow/scripts/checkConsistency.py @@ -18,4 +18,4 @@ for resource, total_quantity in resource_dict.items(): resource_value = portal.restrictedTraverse(resource) message = Message(domain='ui', message="Sorry, you must have a quantity of 1 for : $resource_title", mapping={'resource_title': resource_value.getTranslatedTitle()}) - raise ValidationFailed, message + raise ValidationFailed(message) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_sorting_workflow/scripts/validateBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_sorting_workflow/scripts/validateBalance.py index cb9ff85b3ae89ede590ce93a255a7ba2f21781b7..5e1f7540a481167d5324a3b372af9b701f67ee8b 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_sorting_workflow/scripts/validateBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/cash_sorting_workflow/scripts/validateBalance.py @@ -6,7 +6,7 @@ transaction = state_change['object'] # use of the constraint : Test if quantity is multiple of 1000 vliste = transaction.checkConsistency() if len(vliste) != 0: - raise ValidationFailed, (vliste[0].getMessage(),) + raise ValidationFailed(vliste[0].getMessage(),) # check again that we are in the good accounting date vault = transaction.getSource() @@ -23,10 +23,10 @@ resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_ if input_cash != output_cash : msg=Message(domain="ui", message="Incoming cash amount is different from outgoing cash amount.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif price != output_cash : msg=Message(domain='ui',message='Amount differs from cash total.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif resource != 0 : msg=Message(domain='ui',message='Insufficient Balance.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/classification_survey_workflow/scripts/validateBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/classification_survey_workflow/scripts/validateBalance.py index 07a1c6686c0f9910c517bc3a74a78e4cfda03037..de27095d480f5f95c52e2358f94de97445beacc2 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/classification_survey_workflow/scripts/validateBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/classification_survey_workflow/scripts/validateBalance.py @@ -22,10 +22,10 @@ output_cash = transaction.getTotalPrice(portal_type=['Outgoing Classification Su if input_cash != output_cash : msg=Message(domain="ui", message="Incoming cash amount is different from outgoing cash amount.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif price != output_cash : msg=Message(domain='ui',message='Amount differs from cash total.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif resource != 0 : msg=Message(domain='ui',message='Insufficient Balance.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/counter_rendering_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/counter_rendering_workflow/scripts/validateVaultBalance.py index 1ea33324a850eec3cdbc35f99e26d5cec1d2e541..6c3da248fe963f96dd52a5d14ec387a674fe2528 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/counter_rendering_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/counter_rendering_workflow/scripts/validateVaultBalance.py @@ -26,10 +26,10 @@ total_price = transaction.getTotalPrice(portal_type=['Cash Delivery Line','Cash if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/destruction_survey_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/destruction_survey_workflow/scripts/validateVaultBalance.py index ca4051fdfebd16f206d0e564ca7ed288ace5ae45..7bacebd482a759d3dcaf63bd16e37db9776658f7 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/destruction_survey_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/destruction_survey_workflow/scripts/validateVaultBalance.py @@ -15,10 +15,10 @@ total_price = transaction.getTotalPrice(portal_type=['Cash Delivery Line','Cash if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/foreign_cash_reception_workflow/scripts/checkConsistency.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/foreign_cash_reception_workflow/scripts/checkConsistency.py index 761f309e8cbaad2377595ab50009e8f4535be236..a77af101eebf24a0c540835db57eda6b93ad5d67 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/foreign_cash_reception_workflow/scripts/checkConsistency.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/foreign_cash_reception_workflow/scripts/checkConsistency.py @@ -9,18 +9,18 @@ transaction = state_change['object'] vliste = object.checkConsistency() object.log('vliste', vliste) if len(vliste) != 0: - raise ValidationFailed, (vliste[0].getMessage(),) + raise ValidationFailed(vliste[0].getMessage(),) dest = object.getDestination() # check again that we are in the good accounting date transaction.Baobab_checkCounterDateOpen(site=dest, date=transaction.getStartDate()) if not 'encaisse_des_devises' in object.getDestination(): msg = Message(domain="ui", message="Wrong Destination Selected.") - raise validationFailed, (msg,) + raise validationFailed(msg,) object_price = object.getSourceTotalAssetPrice() line_price = object.getTotalPrice(portal_type=['Cash Delivery Line','Cash Delivery Cell'],fast=0) if object_price != line_price: msg = Message(domain="ui", message="Amount differs between document and lines.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/historical_operation_workflow/scripts/checkConsistency.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/historical_operation_workflow/scripts/checkConsistency.py index 2626e09bc3ebbe6c859349c1665b288cffcb2aa8..97dcb602eb7f50d9d8832ada11d43710ea679fb8 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/historical_operation_workflow/scripts/checkConsistency.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/historical_operation_workflow/scripts/checkConsistency.py @@ -7,13 +7,13 @@ total_cash = delivery.getTotalPrice(fast=0,portal_type=('Cash Delivery Line','Ca if len(delivery.objectValues(portal_type="Cash Delivery Line")) == 0: msg=Message(domain='ui',message='No resource defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if total_cash != delivery.getSourceTotalAssetPrice(): msg=Message(domain='ui',message='Amount differs from cash total.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) historical_operation_type = delivery.getHistoricalOperationTypeValue() if historical_operation_type is None: msg=Message(domain='ui',message='You must define an historical operation type.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/internal_money_deposit_workflow/scripts/validateCounter.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/internal_money_deposit_workflow/scripts/validateCounter.py index 14db5573838a5ddf37cc34aa2a6278ca095c3e8b..c2d6726e3acd69e2f8934ac0b78455017b523c92 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/internal_money_deposit_workflow/scripts/validateCounter.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/internal_money_deposit_workflow/scripts/validateCounter.py @@ -16,7 +16,7 @@ context.Baobab_checkCounterOpened(destination) if transaction.getResource() is None: msg = Message(domain="ui", message="No resource defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Check getBaobabSource and getBaobabDestination #transaction.Base_checkBaobabSourceAndDestination() @@ -29,11 +29,11 @@ lettering = transaction.getGroupingReference() if lettering is None: msg = Message(domain='ui', message='No lettering defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if destination is None: msg = Message(domain='ui', message='No counter defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) @@ -43,4 +43,4 @@ cash_detail = transaction.getTotalPrice(portal_type = ['Cash Delivery Line', 'Ca if price != cash_detail: msg = Message(domain="ui", message="Amount differs from input.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/internal_money_payment_workflow/scripts/validateCounter.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/internal_money_payment_workflow/scripts/validateCounter.py index 1259c1c7a0143dad30f158e310e8328d81adaa3d..66311e498c6f02dd093779a6234d9a372ce1b9f6 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/internal_money_payment_workflow/scripts/validateCounter.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/internal_money_payment_workflow/scripts/validateCounter.py @@ -16,7 +16,7 @@ context.Baobab_checkCounterOpened(source) if transaction.getPaymentType() in (None, ""): msg = Message(domain="ui", message="No payment type defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) #test if the source or the destination is correct @@ -28,11 +28,11 @@ total_price = transaction.getTotalPrice(portal_type=('Cash Delivery Line','Cash if amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if source is None: msg = Message(domain='ui', message='No counter defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) @@ -47,4 +47,4 @@ resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_t if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_destruction_workflow/scripts/setMovementStopDate.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_destruction_workflow/scripts/setMovementStopDate.py index 3c88affcab2a226abc8aa79d10bb749ba3cbbae7..aa3170748d4fca9e3ca1d0a3986ea3c4eaf5a5f7 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_destruction_workflow/scripts/setMovementStopDate.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_destruction_workflow/scripts/setMovementStopDate.py @@ -8,6 +8,6 @@ transaction = state_change['object'] stop_date_key = 'stop_date' if not state_change.kwargs.has_key(stop_date_key): msg = Message(domain = "ui", message="No stop date provided") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) transaction.setStopDate(state_change.kwargs[stop_date_key]) context.validateDestinationCounterDate(state_change, **kw) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_destruction_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_destruction_workflow/scripts/validateVaultBalance.py index 8e87a379ad5d44bd15e538c6d79d848dd5662671..ba62f9a3a82621b181065123bbff29c0eb29a3a6 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_destruction_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_destruction_workflow/scripts/validateVaultBalance.py @@ -13,13 +13,13 @@ if check_source_counter_date: if 'encaisse_des_externes' not in vault and \ 'encaisse_des_billets_retires_de_la_circulation' not in vault: msg = Message(domain="ui", message="Invalid source.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if 'encaisse_des_externes' in vault: source_section = transaction.getSourceSection() if source_section is None: msg = Message(domain="ui", message="Invalid Foreign Agency.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # In case of dematerialization, we must have only coins @@ -27,43 +27,43 @@ if transaction.isDematerialization(): for line in transaction.objectValues(portal_type='Monetary Destruction Line'): if line.getResourceValue().getPortalType() != 'Coin': msg = Message(domain="ui", message="Sorry, dematerialization is possible only with coins.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Not possible from auxiliary agency if 'auxiliaire' in vault: msg = Message(domain="ui", message="You can't do this operation on auxiliary site.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Also we must make sure that the source_section is defined source_section = transaction.getSourceSection() if source_section is None: msg = Message(domain="ui", message="Sorry, dematerialization is possible only if the external agency is defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if 'encaisse_des_billets_retires_de_la_circulation' not in vault: msg = Message(domain="ui", message="Invalid source.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if source_section in source_object.getPath(): msg = Message(domain="ui", message="You can't used this site.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Check specific for auxiliary agencies elif "principale" not in vault: site = transaction.getSourceSection() if site in (None, ""): msg = Message(domain="ui", message="You must select a foreign agency.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) source_country_site = transaction.Baobab_getVaultSite(source_object) source_country = transaction.Baobab_getCountryForSite(source_country_site) site_country = transaction.Baobab_getCountryForSite(site) if 'encaisse_des_externes' in vault and \ site_country == source_country: msg = Message(domain="ui", message="You must select an agency from a foreign country.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif 'encaisse_des_billets_retires_de_la_circulation' in vault and \ site_country != source_country: msg = Message(domain="ui", message="You must select an agency from the same country.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Get price and total_price. @@ -73,10 +73,10 @@ resource = transaction.CashDelivery_checkCounterInventory(source=source_object.g if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_issue_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_issue_workflow/scripts/validateVaultBalance.py index 287ca2124f9abc2db7849957c5581f6598115f6a..6cef54f03cf69a409b58da22d43c4511133705b3 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_issue_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_issue_workflow/scripts/validateVaultBalance.py @@ -7,7 +7,7 @@ transaction = state_change['object'] vliste = transaction.checkConsistency() transaction.log('vliste', vliste) if len(vliste) != 0: - raise ValidationFailed, (vliste[0].getMessage(),) + raise ValidationFailed(vliste[0].getMessage(),) vault = transaction.getSource() resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_type='Monetary Issue Line') @@ -21,10 +21,10 @@ total_price = transaction.getTotalPrice(portal_type=['Monetary Issue Line','Cash if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_recall_workflow/scripts/ValidateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_recall_workflow/scripts/ValidateVaultBalance.py index 3fc07be861e214d6deecb73de5667f304a9305fe..a5bdab5c3461c00fedfae9ddf0f7f755ee64a9ba 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_recall_workflow/scripts/ValidateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_recall_workflow/scripts/ValidateVaultBalance.py @@ -7,7 +7,7 @@ vault = transaction.getSource() if ('encaisse_des_billets_et_monnaies' not in vault): msg = Message(domain="ui", message="Invalid source.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_type='Monetary Recall Line') @@ -25,10 +25,10 @@ total_price = transaction.getTotalPrice(portal_type=['Monetary Recall Line','Cas if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_reception_workflow/scripts/checkDestination.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_reception_workflow/scripts/checkDestination.py index 86a33b59e467b468df5d734a0a650f53ac58e443..1182e3c3a5405e6eade31423e8e701bfd9a19a50 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_reception_workflow/scripts/checkDestination.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_reception_workflow/scripts/checkDestination.py @@ -7,18 +7,18 @@ object = state_change['object'] vliste = object.checkConsistency() object.log('vliste', vliste) if len(vliste) != 0: - raise ValidationFailed, (vliste[0].getMessage(),) + raise ValidationFailed(vliste[0].getMessage(),) # first check if we have line defined if len(object.objectValues(portal_type='Cash Delivery Line')) == 0: msg = Message(domain="ui", message="No line defined on document.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) dest = object.getDestinationValue() if dest is None or 'encaisse_des_billets_retires_de_la_circulation' in dest.getRelativeUrl(): msg = Message(domain="ui", message="Wrong Destination Selected.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check again that we are in the good accounting date object.Baobab_checkCounterDateOpen(site=dest, date=object.getStartDate()) @@ -32,4 +32,4 @@ if 'transit' not in dest.getRelativeUrl(): line_letter = first_movement.getEmissionLetter() if line_letter.lower() != dest.getCodification()[0].lower(): msg = Message(domain="ui", message="Letter defined on line do not correspond to destination site.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_survey_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_survey_workflow/scripts/validateVaultBalance.py index 2317fe60747e1c5345c36d285c92d4c9dd5bd2eb..f1c39cc00f0fd4a60d400cc503b085a4211175c5 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_survey_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/monetary_survey_workflow/scripts/validateVaultBalance.py @@ -8,7 +8,7 @@ destination = transaction.getDestination() if vault is None or destination is None: msg = Message(domain="ui", message="You must define source and destination.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check we are in an opened accounting day @@ -16,19 +16,19 @@ transaction.Baobab_checkCounterDateOpen(site=vault, date=date) if ('encaisse_des_billets_et_monnaies' not in vault) and ('encaisse_des_billets_a_ventiler_et_a_detruire' not in vault): msg = Message(domain="ui", message="Invalid source.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if ('encaisse_des_billets_et_monnaies' not in destination) and ('encaisse_des_billets_a_ventiler_et_a_detruire' not in destination): msg = Message(domain="ui", message="Invalid destination.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if ('encaisse_des_billets_et_monnaies' in vault) and ('encaisse_des_billets_a_ventiler_et_a_detruire' not in destination): msg = Message(domain="ui", message="Impossible Monetary Survey.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if ('encaisse_des_billets_a_ventiler_et_a_detruire' in vault) and ('encaisse_des_billets_et_monnaies' not in destination): msg = Message(domain="ui", message="Impossible Monetary Survey Reintregration.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_type='Cash Delivery Line') # Get price and total_price. @@ -37,10 +37,10 @@ total_price = transaction.getTotalPrice(portal_type=['Cash Delivery Line','Cash if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_rendering_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_rendering_workflow/scripts/validateVaultBalance.py index d76f2e083db8aece14f56bf047bc97646ab16f9e..fb7ceb0fd1b1af77a396279cde09b0858e2e5655 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_rendering_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_rendering_workflow/scripts/validateVaultBalance.py @@ -22,10 +22,10 @@ total_price = transaction.getTotalPrice(portal_type=['Cash Delivery Line','Cash if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_workflow/scripts/validateCounter.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_workflow/scripts/validateCounter.py index e9d012c1b3cb3614af951c1dffaaa2a92201f5b1..5c0fefd746d6de60b488fbca770bdbc2cc93986f 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_workflow/scripts/validateCounter.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_workflow/scripts/validateCounter.py @@ -9,12 +9,12 @@ transaction.log('destination:',destination) amount = transaction.getSourceTotalAssetPrice() if amount is None: msg = Message(domain="ui", message="Sorry, you have to define a quantity.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) destination_payment = transaction.getDestinationPayment() if destination_payment is None: msg = Message(domain="ui", message="Sorry, you have to define an account.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) var_state = transaction.getSimulationState() if var_state == 'confirmed': @@ -24,11 +24,11 @@ if var_state == 'confirmed': if amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if destination is None: msg = Message(domain='ui', message='No counter defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check we are in an opened accounting day diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_workflow/scripts/validateVaultBalance.py index fa0e91c892b288d03d9e8f331f291c99351b4865..1586996e87de048bc0c07ea8913bcc7216d97864 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/money_deposit_workflow/scripts/validateVaultBalance.py @@ -40,10 +40,10 @@ cash_detail = transaction.getTotalPrice(portal_type=['Cash Delivery Line','Cash #transaction.log("price vs cash detail", str((price, cash_detail))) if resource == 3: msg = Message(domain="ui", message="No banknote or coin defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif resource == 2: msg = Message(domain="ui", message="No resource defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif price != cash_detail: msg = Message(domain="ui", message="Amount differs from input.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionDeliver.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionDeliver.py index 8106797f70aeafa615f4c29b3178d397949238fb..27aaeff085bf4792b9c9eb4e5cd17e2be575bb86 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionDeliver.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionDeliver.py @@ -18,15 +18,15 @@ for outgoing_line in ob.objectValues(portal_type="Outgoing Mutilated Banknote Li if len(ob.objectValues(portal_type="Outgoing Mutilated Banknote Line")) == 0: msg = Message(domain = "ui", message="You must defined returned banknote.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if ob.getDestinationTotalAssetPrice() != ob.getTotalPrice(portal_type="Outgoing Mutilated Banknote Line", fast=0): msg = Message(domain = "ui", message="Returned value different from exchanged value.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # now check balance resource = ob.CashDelivery_checkCounterInventory(source=vault, portal_type='Outgoing Mutilated Banknote Line', same_source=1) if resource == 2: msg = Message(domain="ui", message="No Returned banknote defined.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionFinish.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionFinish.py index 86ef763b57f713420dc84ee292e7c79f5bee3c7e..f002124af2865edd3ddfe62612380066c8316a7d 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionFinish.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionFinish.py @@ -12,14 +12,14 @@ for exchanged_line in ob.objectValues(portal_type='Exchanged Mutilated Banknote if ob.getDestinationTotalAssetPrice() == 0: msg = Message(domain = "ui", message="Exchanged amount must be defined on document.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if len(ob.objectValues(portal_type='Exchanged Mutilated Banknote Line')) == 0: msg = Message(domain = "ui", message="You must defined exchanged banknote line.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) exchanged_mutilated_banknote_total_price = ob.getTotalPrice(portal_type='Exchanged Mutilated Banknote Line', fast=0) if exchanged_mutilated_banknote_total_price > ob.getTotalPrice(portal_type='Incoming Mutilated Banknote Line', fast=0): msg = Message(domain = "ui", message="Total exchanged greater than total supply.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if exchanged_mutilated_banknote_total_price != ob.getDestinationTotalAssetPrice(): msg = Message(domain = "ui", message="Exchanged amount differ between line and document.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionPlan.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionPlan.py index 5404157657393021985b9d85898f333d866bf21f..f1b1adcb6ff05de27830ce89d793ee0b5b1644d8 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionPlan.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionPlan.py @@ -6,4 +6,4 @@ ob = state_change['object'] # check presence of banknote if len(ob.objectValues(portal_type="Exchanged Mutilated Banknote Line")) != 0: msg = Message(domain = "ui", message="Transition forbidden with exchanged banknote line defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionStop.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionStop.py index cad89b7c7203e2660e4e150e96212e3854470e6a..fd8b916a9bd2565a1092518eea93516890ce421d 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionStop.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/mutilated_banknote_workflow/scripts/CheckTransitionStop.py @@ -10,19 +10,19 @@ ob.Baobab_checkCounterDateOpen(site=ob.getSource(), date=ob.getStartDate()) # check presence of banknote if len(ob.objectValues()) == 0: msg = Message(domain = "ui", message="No mutilated banknotes defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check price defined if ob.getSourceTotalAssetPrice() != ob.getTotalPrice(portal_type='Incoming Mutilated Banknote Line', fast=0): msg = Message(domain = "ui", message="Amount differ between document and line.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check reporter defined if ob.getDeponent() in (None, ""): msg = Message(domain = "ui", message="You must define a reporter.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check original site defined is hq if "siege" in ob.getSource() and ob.getSourceTrade() is None: msg = Message(domain = "ui", message="You must define the original site.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/usual_cash_rendering_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/usual_cash_rendering_workflow/scripts/validateVaultBalance.py index 84a12aba46e07aad3e940eb25d67855ef9697eee..02becdf4877ca85aa3b58d447937d1b42c90885c 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/usual_cash_rendering_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/usual_cash_rendering_workflow/scripts/validateVaultBalance.py @@ -9,7 +9,7 @@ vaultDestination = transaction.getDestination() # use of the constraint vliste = transaction.checkConsistency() if len(vliste) != 0: - raise ValidationFailed, (vliste[0].getTranslatedMessage(),) + raise ValidationFailed(vliste[0].getTranslatedMessage(),) # check we are in an opened accounting day transaction.Baobab_checkCounterDateOpen(site=vault, date=date) @@ -19,7 +19,7 @@ if 'reserve' in vault and 'salle_tri' in vaultDestination: mapping={'source':transaction.getSourceValue().getParentValue().getTitle(), 'destination':transaction.getDestinationValue().getParentValue().getTitle()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_type='Cash Delivery Line') # Get price and total_price. @@ -28,10 +28,10 @@ total_price = transaction.getTotalPrice(portal_type=['Cash Delivery Line','Cash if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/usual_cash_transfer_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/usual_cash_transfer_workflow/scripts/validateVaultBalance.py index 5d83d1eb686934b659acf0bbe89f1f95defc2235..6305452a3246aa1774b306ea5cfd8f6109fdf991 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/usual_cash_transfer_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/usual_cash_transfer_workflow/scripts/validateVaultBalance.py @@ -19,7 +19,7 @@ context.Baobab_checkCounterOpened(source_counter) vliste = transaction.checkConsistency() transaction.log('vliste', vliste) if len(vliste) != 0: - raise ValidationFailed, (vliste[0].getMessage(),) + raise ValidationFailed(vliste[0].getMessage(),) resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_type='Cash Delivery Line') @@ -29,10 +29,10 @@ total_price = transaction.getTotalPrice(portal_type=['Cash Delivery Line','Cash if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/vault_transfer_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/vault_transfer_workflow/scripts/validateVaultBalance.py index d3f1f05686f635c237d2370c9e58d518aaa7516c..51e0465f1bb05c785ad32f9941c26185d48fbcbd 100644 --- a/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/vault_transfer_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_cash/WorkflowTemplateItem/portal_workflow/vault_transfer_workflow/scripts/validateVaultBalance.py @@ -8,13 +8,13 @@ vaultDestination = transaction.getDestination() if vault is None or vaultDestination is None: msg = Message(domain="ui", message="You must define vaults.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # use of the constraint : Test source and destination vliste = transaction.checkConsistency() transaction.log('vliste', vliste) if len(vliste) != 0: - raise ValidationFailed, (vliste[0].getMessage(),) + raise ValidationFailed(vliste[0].getMessage(),) # check we are in an opened accounting day transaction.Baobab_checkCounterDateOpen(site=vaultDestination, date=date) @@ -25,7 +25,7 @@ if 'reserve' in vault and 'salle_tri' in vaultDestination: mapping={'source':transaction.getSourceValue().getParentValue().getTitle(), 'destination':transaction.getDestinationValue().getParentValue().getTitle()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) resource = transaction.CashDelivery_checkCounterInventory(source=vault, portal_type='Vault Transfer Line') # Get price and total_price. @@ -34,10 +34,10 @@ total_price = transaction.getTotalPrice(portal_type=['Vault Transfer Line','Vaul if resource == 2: msg = Message(domain="ui", message="No Resource.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif amount != total_price: msg = Message(domain="ui", message="Amount differ from total price.") - raise ValidationFailed, (msg,) -elif resource <> 0 : + raise ValidationFailed(msg,) +elif resource != 0 : msg = Message(domain="ui", message="Insufficient Balance.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_check/ExtensionTemplateItem/portal_components/extension.erp5.CheckbookReceptionImport.py b/bt5/erp5_banking_check/ExtensionTemplateItem/portal_components/extension.erp5.CheckbookReceptionImport.py index da42c1ce30f9d1b8917022d0173290ca9e79567a..894514cf374410959151339a3398cd5197911a2d 100644 --- a/bt5/erp5_banking_check/ExtensionTemplateItem/portal_components/extension.erp5.CheckbookReceptionImport.py +++ b/bt5/erp5_banking_check/ExtensionTemplateItem/portal_components/extension.erp5.CheckbookReceptionImport.py @@ -43,7 +43,7 @@ def CheckbookReception_importItemFile(self, import_file=None, REQUEST=None, **kw 'Check Model'], reference = reference_dict[checkbook_type]) if len(resource_list) != 1: - raise ValueError, "The import does not support this type : %s" % checkbook_type + raise ValueError("The import does not support this type : %s" % checkbook_type) resource = resource_list[0].getObject() resource_relative_url = resource.getRelativeUrl() resource_amount_dict = {} diff --git a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/Base_checkCheck.py b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/Base_checkCheck.py index e5d568ce47910096cd14e61c3039e2c92e4dc200..39c53d08ee36603cdc182745dce75f68a1b9ad7e 100644 --- a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/Base_checkCheck.py +++ b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/Base_checkCheck.py @@ -18,6 +18,6 @@ if simulation_state != 'confirmed': msg = Message(domain='ui', message=bad_simulation_state_dict[simulation_state]) else: msg = 'Invalid and unhandled simulation state: %s' % (simulation_state, ) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) return check diff --git a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/Base_checkOrCreateCheck.py b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/Base_checkOrCreateCheck.py index 9abef0b5ff4786ed8527f2477e8d87e525e74f89..20cd82fba3d649c51cc04f9f508417f5212757ea 100644 --- a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/Base_checkOrCreateCheck.py +++ b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/Base_checkOrCreateCheck.py @@ -15,11 +15,11 @@ if bank_account is None: if bank_account is None: msg = Message(domain='ui',message='Sorry, you must select an account') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if resource is None: msg = Message(domain='ui',message='Sorry, you must select a resource') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if reference is not None: reference_list = [reference] @@ -38,11 +38,11 @@ elif reference_range_min is not None or reference_range_max is not None: reference_range_max = int(reference_range_max) except ValueError: msg = Message(domain='ui', message='Sorry, make sure you have entered the right check number.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if reference_range_min>reference_range_max : msg = Message(domain='ui', message='Sorry, the min number must be less than the max number.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) for ref in range(reference_range_min,reference_range_max+1): # We will look for each reference and add the right number @@ -59,7 +59,7 @@ for check_reference in reference_list: # just raise an error. if context.portal_activities.countMessageWithTag(message_tag) != 0: msg = Message(domain='ui', message="There are operations pending that prevent to validate this document. Please try again later.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) result = context.portal_catalog(portal_type = 'Check', reference = check_reference, destination_payment_uid = bank_account.getUid(), default_resource_uid = resource_value.uid, @@ -70,13 +70,13 @@ for check_reference in reference_list: msg = Message(domain = "ui", message="Sorry, the $type $reference for the account $account does not exist", mapping={'reference' : check_reference, 'account': bank_account.getInternalBankAccountNumber(), 'type': resource_value.getTitle()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif result_len > 1: msg = Message(domain = "ui", message="Sorry, the $type $reference for the account $account is duplicated", mapping={'reference' : reference, 'account': bank_account.getInternalBankAccountNumber(), 'type': resource_value.getTitle()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) reference_dict[check_reference] = {} reference_dict[check_reference]['result'] = result @@ -96,10 +96,10 @@ for check_reference in reference_list: composition_related_list = resource_value.getCompositionRelatedValueList() if len(composition_related_list) == 0: msg = Message(domain = "ui", message="Sorry, no checkbook model found") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if len(composition_related_list) != 1: msg = Message(domain = "ui", message="Sorry, too many many checkbook model found") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) generic_model = composition_related_list[0] #generic_model = context.portal_catalog(portal_type = 'Checkbook Model', title = 'Generic')[0].getObject() @@ -120,7 +120,7 @@ for check_reference in reference_list: checkbook_tag = "checkbook_%s_%s" % (resource, bank_account_uid) if context.portal_activities.countMessageWithTag(checkbook_tag) != 0: msg = Message(domain='ui', message="There are operations pending that prevent to validate this document. Please try again later.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) checkbook = context.checkbook_module.newContent(portal_type = 'Checkbook', title = 'Generic', resource_value = generic_model, diff --git a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckDelivery_generateCheckDetailInputDialog.py b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckDelivery_generateCheckDetailInputDialog.py index 6660e63a336e12eb781f95fb8a8e0a8741922543..88738bbab9efe1445ea9d8cd4473b1d65c2aea5f 100644 --- a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckDelivery_generateCheckDetailInputDialog.py +++ b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckDelivery_generateCheckDetailInputDialog.py @@ -43,7 +43,7 @@ def convertTravelerCheckReferenceToInt(traveler_check_reference): def convertCheckReferenceToInt(check_reference): if len(check_reference) != 7: - raise ValueError, 'Check reference must be 7-char long.' + raise ValueError('Check reference must be 7-char long.') return int(check_reference) # listbox is not passed at the first time when this script is called. diff --git a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookDelivery_checkAggregateStockList.py b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookDelivery_checkAggregateStockList.py index 30d4fe006242ce49dbbc8ebf7676d306cdcf8d17..e6987e9bbd24ca3ae5c29ac3abbbe05067d5de74 100644 --- a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookDelivery_checkAggregateStockList.py +++ b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookDelivery_checkAggregateStockList.py @@ -16,4 +16,4 @@ for line in context.getMovementList(): reference = '%s - %s' % (aggregate_value.getReferenceRangeMin() or '', aggregate_value.getReferenceRangeMax() or '') msg = Message(domain="ui", message="Sorry, the item with reference $reference is not available any more", mapping={'reference':reference}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookReceptionLine_checkOrCreateItemList.py b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookReceptionLine_checkOrCreateItemList.py index e8bf89d85750e5a17daafe4ed064bb4fcc06cce2..94356fc9b2391cf979031342d926ed6d2dfbc29c 100644 --- a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookReceptionLine_checkOrCreateItemList.py +++ b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookReceptionLine_checkOrCreateItemList.py @@ -27,7 +27,7 @@ def validateTravelerCheckReferenceFormat(traveler_check_reference): """ if len(traveler_check_reference) != 10: message = Message(domain='ui', message='Traveler check reference must be 10-char long.') - raise ValueError, (message,) + raise ValueError(message,) int(traveler_check_reference[4:]) def getTravelerCheckReferenceNumber(traveler_check_reference): @@ -51,10 +51,10 @@ def generateTravelerCheckReference(number, original_traveler_check_reference): """ if not same_type(number, 0): message = Message(domain='ui', message='Traveler check number must be only numeric.') - raise ValueError, (message, ) + raise ValueError(message,) if len(str(number)) > 6: message = Message(domain='ui', message='Traveler check number representation length must not exceed 6 char.') - raise ValueError, (message,) + raise ValueError(message,) prefix = getTravelerCheckReferencePrefix(original_traveler_check_reference) return '%s%06d' % (prefix, number) @@ -69,7 +69,7 @@ def assertReferenceMatchListEmpty(match_list, internal_bank_account_number): matched_reference_list.append('%s (%s)' % (match.getReference(), internal_bank_account_number)) message = Message(domain='ui', message='The following references are already allocated : $reference_list', mapping={'reference_list': matched_reference_list}) - raise ValidationFailed, (message,) + raise ValidationFailed(message,) def checkReferenceListUniqueness(reference_list, model_uid, destination_payment_value, unique_per_account): """ @@ -101,7 +101,7 @@ def checkReferenceListUniqueness(reference_list, model_uid, destination_payment_ if encountered_check_identifiers_dict.has_key(tag): message = Message(domain='ui', message='The following references are already allocated : $reference_list', mapping={'reference_list': ['%s (%s)' % (reference, internal_bank_account_number) ]}) - raise ValidationFailed, (message,) + raise ValidationFailed(message,) encountered_check_identifiers_dict[tag] = None start_date = checkbook_reception.getStartDate() @@ -149,7 +149,7 @@ if resource.getAccountNumberEnabled(): context.log('context.getRelativeUrl() before getUid of destination payment', context.getRelativeUrl()) if destination_payment_value is None: message = Message(domain='ui', message='There is not destination payment on line with id: $id', mapping={'id': context.getId()}) - raise ValueError, (message,) + raise ValueError(message,) destination_trade = line.getDestinationTrade() else: destination_payment_value = None diff --git a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookReception_checkOrCreateItemList.py b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookReception_checkOrCreateItemList.py index 8231cb3a7783a0e93d3ca76a7b8e0a039e70530e..f6e27deb9bf50dc57f5e0271cdeda6e288f5a756 100644 --- a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookReception_checkOrCreateItemList.py +++ b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/CheckbookReception_checkOrCreateItemList.py @@ -12,7 +12,7 @@ from Products.ERP5Type.Message import Message destination_id = context.getDestinationId() if destination_id is None: msg = Message(domain='ui', message='Sorry, you must define the site') - raise ValidationFailed, (msg, ) + raise ValidationFailed(msg,) # serialize destination vault to only have one operation at a time destination_value = context.getDestinationValue() @@ -28,7 +28,7 @@ else: msg = Message(domain='ui', message='Sorry, there is already a checkbook reception newly validated') checkbook_reception_tag = "CheckbookReception_%s" % destination_id if context.portal_activities.countMessageWithTag(checkbook_reception_tag) != 0: - raise ValidationFailed, (msg, ) + raise ValidationFailed(msg,) if check == 1: encountered_check_identifiers_dict = {} diff --git a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/TravelerCheckPurchase_init.py b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/TravelerCheckPurchase_init.py index 46769acde2a51d958da607fb373e37b98611bc97..6aee4421c6ccccd5194648df7d7a3ac5da578d18 100644 --- a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/TravelerCheckPurchase_init.py +++ b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/TravelerCheckPurchase_init.py @@ -27,5 +27,5 @@ for site in site_list: if user_site is None: from Products.ERP5Type.Message import Message message = Message(domain="ui", message="The owner is not assigned to the right vault.") - raise ValueError,message + raise ValueError(message) context.setSource(user_site) diff --git a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/TravelerCheckSale_getBaobabSource.py b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/TravelerCheckSale_getBaobabSource.py index d83debd57e4e9b45dbb59bfede40118e514f3f4f..e37595aeb50d22c6b6fe5685a64120676ec618f7 100644 --- a/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/TravelerCheckSale_getBaobabSource.py +++ b/bt5/erp5_banking_check/SkinTemplateItem/portal_skins/erp5_banking_check_operation/TravelerCheckSale_getBaobabSource.py @@ -9,4 +9,4 @@ for site in site_list: return site + '/encaisse_des_billets_et_monnaies' from Products.ERP5Type.Message import Message message = Message(domain="ui", message="The owner is not assigned to the right vault.") -raise ValueError,message +raise ValueError(message) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/checkAccountIsOverdraftFacility.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/checkAccountIsOverdraftFacility.py index 570f76dcaa4d90e64c43439b86b43d13bcfc57ab..8cb05fa58fa6abf5abf6c1a1bc6835815e5619be 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/checkAccountIsOverdraftFacility.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/checkAccountIsOverdraftFacility.py @@ -9,8 +9,8 @@ for line in txn.contentValues(filter = {'portal_type' : 'Check Operation Line'} if account is None: msg = Message(domain='ui', message="No account defined on line") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if not account.isOverdraftFacility(): msg = Message(domain='ui', message="Can't sent to manual validation because of not overdraft facility for this bank account") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/checkCheckBeforeDelivery.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/checkCheckBeforeDelivery.py index 246ad4f5276626df70e04b9045e52b9eea0a65b3..679111a31b1b8f77c5e55aa8481ad874f5b5385c 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/checkCheckBeforeDelivery.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/checkCheckBeforeDelivery.py @@ -37,14 +37,14 @@ else: if error['error_code'] == 1: msg = Message(domain='ui', message="Bank account $account is not sufficient on line $line.", mapping={"account": source_bank_account.getInternalBankAccountNumber(), "line" : check_operation_line.getId()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif error['error_code'] == 2: msg = Message(domain='ui', message="Bank account $account is not valid on $line.", mapping={"account": source_bank_account.getInternalBankAccountNumber(), "line" : check_operation_line.getId()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif error['error_code'] != 0: msg = Message(domain='ui', message="Unknown error code.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) context.validateSourceAndDestination(state_change) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/validateConsistency.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/validateConsistency.py index 2c921b212443d82697462a3dc3d21e3776e7785d..f704f26e3ff98af9417780ed8e9a683dd218521e 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/validateConsistency.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/validateConsistency.py @@ -12,34 +12,34 @@ transaction.Baobab_checkAccountingDateOpen(site=site, date=date) if transaction.getDestinationSection() not in ("", None) and \ transaction.getDestinationPayment() not in ("", None): msg = Message(domain='ui', message="You can't defined both account and accounting code.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if transaction.getDestinationSection() in ("", None) and \ transaction.getDestinationPayment() in ("", None): msg = Message(domain='ui', message="You must defined an account or and accounting code as destination.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if transaction.getSite() in ("", None): msg = Message(domain='ui', message="You must defined site on document.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Check the amount. price = transaction.getSourceTotalAssetPrice() if price is None or price <= 0: msg = Message(domain='ui', message='Amount is not valid.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Check the bank account. destination_bank_account = transaction.getDestinationPaymentValue() if destination_bank_account is not None: if destination_bank_account.getValidationState() != 'valid': msg = Message(domain='ui', message='Destination bank account is not valid.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Check if the total price is equal to the total asset price. if transaction.getTotalPrice(fast=0, portal_type = 'Check Operation Line') != transaction.getSourceTotalAssetPrice(): msg = Message(domain='ui', message="Total price doesn't match.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) seen_check_dict = {} @@ -51,13 +51,13 @@ for check_operation_line in transaction.contentValues(filter = {'portal_type' : if check_operation_line.getDescription() in (None, ''): msg = Message(domain='ui', message='The description is not defined on line $line.' , mapping={"line" : check_operation_line.getId()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) source_bank_account = check_operation_line.getSourcePaymentValue() if source_bank_account is None: msg = Message(domain='ui', message='Bank account not defined on line $line.' , mapping={"line" : check_operation_line.getId()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) check_number = check_operation_line.getAggregateFreeText() check_type = check_operation_line.getAggregateResource() @@ -65,29 +65,29 @@ for check_operation_line in transaction.contentValues(filter = {'portal_type' : if check_number: msg = Message(domain='ui', message='Check is defined on line $line.' , mapping={"line" : check_operation_line.getId()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if check_type is not None: msg = Message(domain='ui', message='Check type is defined on line $line.' , mapping={"line" : check_operation_line.getId()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) else: if not check_number: msg = Message(domain='ui', message='Check is not defined on line $line.' , mapping={"line" : check_operation_line.getId()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if check_type is None: msg = Message(domain='ui', message='Check type is not defined on line $line.' , mapping={"line" : check_operation_line.getId()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) seen_check_dict_key = (source_bank_account, check_type, check_number) seen_check = seen_check_dict.get(seen_check_dict_key) if seen_check is not None: msg = Message(domain='ui', message='Check on line $line is already used on line $oldline.' , mapping={"line" : check_operation_line.getId(), "oldline": seen_check}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) seen_check_dict[seen_check_dict_key] = check_operation_line.getId() # Test check is valid based on date diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/validatePlanActionConsistency.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/validatePlanActionConsistency.py index 974f50f8a9c9e547a8df8757c1682d68275c7b8f..2879fcb3db59fb22293839a1df89d80b7b1a2f15 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/validatePlanActionConsistency.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_deposit_workflow/scripts/validatePlanActionConsistency.py @@ -15,13 +15,13 @@ for account_path, amount in amount_dict.items(): error = transaction.BankAccount_checkBalance(account_path, amount)['error_code'] source_bank_account = bank_account_dict[account_path] if error == 1: - raise ValidationFailed, (Message(domain='ui', message="Bank account $account is not sufficient.", - mapping={"account": source_bank_account.getInternalBankAccountNumber()}), ) + raise ValidationFailed(Message(domain='ui', message="Bank account $account is not sufficient.", + mapping={"account": source_bank_account.getInternalBankAccountNumber()}),) elif error == 2: - raise ValidationFailed, (Message(domain='ui', message="Bank account $account is not valid.", - mapping={"account": source_bank_account.getInternalBankAccountNumber()}), ) + raise ValidationFailed(Message(domain='ui', message="Bank account $account is not valid.", + mapping={"account": source_bank_account.getInternalBankAccountNumber()}),) elif error != 0: - raise ValidationFailed, (Message(domain='ui', message="Unknown error code."),) + raise ValidationFailed(Message(domain='ui', message="Unknown error code."),) context.validateConsistency(state_change) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/checkAccountIsOverdraftFacility.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/checkAccountIsOverdraftFacility.py index 6b5f06bdfef127de166838d170023c6ab1a019f1..a5e7276bb8ed45b960f6fa37937060e0c67c1d6a 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/checkAccountIsOverdraftFacility.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/checkAccountIsOverdraftFacility.py @@ -6,7 +6,7 @@ date = transaction.getStartDate() source = transaction.getSource(None) if source is None: msg = Message(domain='ui', message='No counter defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check we are in an opened accounting day transaction.Baobab_checkCounterDateOpen(site=source, date=date) @@ -21,7 +21,7 @@ bank_account = transaction.getDestinationPaymentValue() if not bank_account.isOverdraftFacility(): msg = Message(domain='ui', message="Can't sent to manual validation because of not overdraft facility for this bank account") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) price = transaction.getSourceTotalAssetPrice() @@ -31,7 +31,7 @@ bank_account.serialize() # Make sure there are no other operations pending for this account if transaction.BankAccount_isMessagePending(bank_account): msg = Message(domain='ui', message="There are operations pending for this account that prevent form calculating its position. Please try again later.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Index the banking operation line so it impacts account position transaction.BankingOperationLine_index(line) @@ -39,4 +39,4 @@ transaction.BankingOperationLine_index(line) # Check if the banking operation is correct. Do not depend on catalog because line might not be indexed immediatelly. if - price != (line.getPrice() * line.getQuantity()): msg = Message(domain='ui', message='Banking operation and check payment price do not match.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validateConsistency.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validateConsistency.py index fb32219c81c695150009e5bd0fa567b65eeac3ec..7890074fb91ab5c20a6fa42f4ed3c1aee479b449 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validateConsistency.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validateConsistency.py @@ -16,14 +16,14 @@ else: while True: if not hasattr(site, 'getVaultTypeList'): msg = Message(domain = 'ui', message = 'The site value is misconfigured; report this to system administrators.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if 'site' in site.getVaultTypeList(): break site = site.getParentValue() if site is None: msg = Message(domain = 'ui', message = 'Impossible to determine site for the transaction.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) date = transaction.getStartDate() @@ -40,13 +40,13 @@ document_date = DateTime(date).Date() price = transaction.getSourceTotalAssetPrice() if price is None or price <= 0: msg = Message(domain="ui", message="Amount is not valid.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Check the bank account. bank_account = transaction.getDestinationPaymentValue() if bank_account is None: msg = Message(domain='ui', message='Bank account is not defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Check the check. check_number = transaction.getAggregateFreeText() @@ -59,10 +59,10 @@ transaction.edit(aggregate_resource=check_resource) if not check_number: msg = Message(domain='ui', message="Check not defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if check_resource is None: msg = Message(domain='ui', message="Check type not defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) check = transaction.Base_checkCheck(reference=check_number, bank_account=bank_account, resource=check_resource) @@ -79,10 +79,10 @@ if no_balance_check == 1: error = transaction.BankAccount_checkAvailableBalance(bank_account.getRelativeUrl(), price) if error['error_code'] == 1: msg = Message(domain='ui', message="Bank account is not sufficient.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif error['error_code'] == 2: msg = Message(domain='ui', message="Bank account is not valid.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif error['error_code'] != 0: msg = Message(domain='ui', message="Unknown error code.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validatePositionAccounting.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validatePositionAccounting.py index 599a3c9161bf27abb703086a55a2baf6144ac848..c16abf7d00a8e1788087b691fe4a4f7c423d0039 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validatePositionAccounting.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validatePositionAccounting.py @@ -6,7 +6,7 @@ date = transaction.getStartDate() source = transaction.getSource(None) if source is None: msg = Message(domain='ui', message='No counter defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check we are in an opened accounting day transaction.Baobab_checkCounterDateOpen(site=source, date=date) @@ -28,7 +28,7 @@ bank_account.serialize() # Make sure there are no other operations pending for this account if transaction.BankAccount_isMessagePending(bank_account): msg = Message(domain='ui', message="There are operations pending for this account that prevent form calculating its position. Please try again later.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Index the banking operation line so it impacts account position transaction.BankingOperationLine_index(line) @@ -36,17 +36,17 @@ transaction.BankingOperationLine_index(line) # Check if the banking operation is correct. Do not depend on catalog because line might not be indexed immediatelly. if - price != (line.getPrice() * line.getQuantity()): msg = Message(domain='ui', message='Banking operation and check payment price do not match.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Test if the account balance is sufficient. if state_change['transition'].getId() != "agree_action": error = transaction.BankAccount_checkAvailableBalance(bank_account.getRelativeUrl(), price) if error['error_code'] == 1: msg = Message(domain='ui', message="Bank account is not sufficient.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif error['error_code'] == 2: msg = Message(domain='ui', message="Bank account is not valid.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif error['error_code'] != 0: msg = Message(domain='ui', message="Unknown error code.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validateVaultBalance.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validateVaultBalance.py index 18f1f6c4c3b50f9cc9d06e7a9c9329c7e79600a2..4f3d314e32e7d4bbfccf47a36acc6b94239ed6bf 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validateVaultBalance.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/check_payment_workflow/scripts/validateVaultBalance.py @@ -18,7 +18,7 @@ for site in site_list: if baobab_source is None: msg = Message(domain="ui", message="Unable to determine counter from user assignement.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) source = baobab_source source_object = context.portal_categories.getCategoryValue(source) @@ -40,16 +40,16 @@ cash_detail = transaction.getTotalPrice(portal_type = ('Cash Delivery Line','Cas #transaction.log("price vs cash detail", str((price, cash_detail))) if resource == 3: msg = Message(domain="ui", message="No banknote or coin defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif resource == 2: msg = Message(domain="ui", message="No resource defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif price != cash_detail: msg = Message(domain="ui", message="Amount differs from input.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif resource == 1: msg = Message(domain="ui", message="Insufficient Balance in counter.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) transaction.Base_checkCheck(None, None, None, check=transaction.getAggregateValue()) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_delivery_workflow/scripts/checkConsistency.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_delivery_workflow/scripts/checkConsistency.py index 6534d2c30f3cbf386cbc0ebf8827da87e5dfc6de..22fa679309d19928e7c624991241ef1ea3e201be 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_delivery_workflow/scripts/checkConsistency.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_delivery_workflow/scripts/checkConsistency.py @@ -11,16 +11,16 @@ date = transaction.getStartDate() source = transaction.getBaobabSource(None) if source is None: msg = Message(domain='ui', message='No counter defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) destination_payment = transaction.getDestinationPayment() if destination_payment is None: msg = Message(domain='ui', message='No account defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if sum([len(x.getAggregateList()) for x in transaction.objectValues(portal_type=['Checkbook Delivery Line'])]) == 0: msg = Message(domain='ui', message='No checkbook selected for delivery.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) at_date = transaction.getStartDate() transaction.CheckbookDelivery_checkAggregateStockList(at_date=at_date, node_url = source) @@ -44,13 +44,13 @@ for line in line_list: if aggregate.getPortalType()=='Check': if aggregate.getSimulationState() != 'draft': message = Message(domain='ui', message='Sorry, the check is not new') - raise ValidationFailed, (message,) + raise ValidationFailed(message,) if aggregate.getPortalType()=='Checkbook': if aggregate.getValidationState() != 'draft': message = Message(domain='ui', message='Sorry, the checkbook is not new') - raise ValidationFailed, (message,) + raise ValidationFailed(message,) for check in aggregate.objectValues(portal_type='Check'): if check.getSimulationState() != 'draft': message = Message(domain='ui', message='Sorry, there is a check wich is not in the new state inside the checkbook') - raise ValidationFailed, (message,) + raise ValidationFailed(message,) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_reception_workflow/scripts/CheckbookReception_validateData.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_reception_workflow/scripts/CheckbookReception_validateData.py index 6176fd6e2dc673ada96c26d56bf62851e572b659..b07c1e116c27979584b1c39ec75930743dcd988d 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_reception_workflow/scripts/CheckbookReception_validateData.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_reception_workflow/scripts/CheckbookReception_validateData.py @@ -7,15 +7,15 @@ object = state_change['object'] destination = object.getDestination() if destination is None: message = Message(domain="ui",message="Please select a destination") - raise ValidationFailed, (message,) + raise ValidationFailed(message,) # Check that the destination is not empty description = object.getDescription() if description in (None, ''): message = Message(domain="ui",message="Please set a description") - raise ValidationFailed, (message,) + raise ValidationFailed(message,) # Check that there is a least one line if len(object.objectValues())==0: message = Message(domain="ui",message="Please enter some check or checkbooks") - raise ValidationFailed, (message,) + raise ValidationFailed(message,) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_usual_cash_transfer_workflow/scripts/validateCheckbookVaultTransferConsistency.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_usual_cash_transfer_workflow/scripts/validateCheckbookVaultTransferConsistency.py index 7f21b071bbb0dc85fb6e5b9b21dc8db5fb1f6490..4119405cf6fec0ee86ac240565557e6722ff2be5 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_usual_cash_transfer_workflow/scripts/validateCheckbookVaultTransferConsistency.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_usual_cash_transfer_workflow/scripts/validateCheckbookVaultTransferConsistency.py @@ -19,4 +19,4 @@ at_date = transaction.getStartDate() transaction.CheckbookDelivery_checkAggregateStockList(at_date=at_date, node_url = source) if msg is not None: - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_vault_transfer_workflow/scripts/validateCheckbookVaultTransferConsistency.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_vault_transfer_workflow/scripts/validateCheckbookVaultTransferConsistency.py index ab277ef165b9f0e1d86d9d28093c43aab7c8b5ef..afcf4bedfbda066da55eb17d18ba4f43b5c03cf7 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_vault_transfer_workflow/scripts/validateCheckbookVaultTransferConsistency.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/checkbook_vault_transfer_workflow/scripts/validateCheckbookVaultTransferConsistency.py @@ -17,4 +17,4 @@ at_date = transaction.getStartDate() transaction.CheckbookDelivery_checkAggregateStockList(at_date=at_date, node_url = source) if msg is not None: - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/liftPositionAccounting.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/liftPositionAccounting.py index 2061654c5a3c7a808311474c507ec0cd39de1e82..53ee720d56f2e31d60028639015c03c7087f6cd2 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/liftPositionAccounting.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/liftPositionAccounting.py @@ -7,7 +7,7 @@ date = transaction.getStartDate() source = transaction.getSource(None) if source is None: msg = Message(domain='ui', message='No counter defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # No need to check the counter date for stop payment #if not transaction.Baobab_checkCounterDateOpen(site=source, date=date): @@ -24,17 +24,17 @@ for movement in movement_list: for item in aggregate_value_list: if item.getPortalType()!='Check': msg = Message(domain = "ui", message="Sorry, You should select a check") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if item.getSimulationState()!='stopped': msg = Message(domain = "ui", message="Sorry, this check is not stopped") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) debit_required = transaction.isDebitRequired() if debit_required: if transaction.getSimulationState() == 'started': stop_date = state_change.kwargs.get('stop_date') if stop_date is None: msg = Message(domain = "ui", message="No stop date provided") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) transaction.setStopDate(stop_date) # Source and destination will be updated automaticaly based on the category of bank account diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/updateCheck.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/updateCheck.py index 2235947280d950a3c4c961193c50404f9ae52304..ac745813c8604cb8034879e82a1f78b8404691b0 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/updateCheck.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/updateCheck.py @@ -14,7 +14,7 @@ ref_max = transaction.getReferenceRangeMin() if ref_min is not None or ref_max is not None: if len(aggregate_list)==0: msg = Message(domain='ui', message='Sorry, no check was found, but there is a reference.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) for aggregate in aggregate_list: if aggregate.getPortalType()=='Check': aggregate.setStopDate(transaction.getStartDate()) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/validatePositionAccounting.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/validatePositionAccounting.py index d4d062c1e4f65ba103766db5a5d957056f8563c8..ddcf7fd9cda175011b6ab3e00d43b8402fbe6e42 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/validatePositionAccounting.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/stop_payment_workflow/scripts/validatePositionAccounting.py @@ -10,7 +10,7 @@ now = DateTime() source = transaction.getSource(None) if source is None: msg = Message(domain='ui', message='No counter defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # No need for stop payment to check the counter date #if not transaction.Baobab_checkCounterDateOpen(site=source, date=date): @@ -64,10 +64,10 @@ for movement in movement_list: for item in aggregate_value_list: if item.getPortalType()!='Check': msg = Message(domain = "ui", message="Sorry, You should select a check") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if item.getSimulationState()!='confirmed': msg = Message(domain = "ui", message="Sorry, this check is not issued") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Test check is valid based on date transaction.Check_checkIntervalBetweenDate(resource=item.getResourceValue(), start_date=date, @@ -78,7 +78,7 @@ for movement in movement_list: debit_required = transaction.isDebitRequired() if total_debit in (None,0.0) and debit_required: msg = Message(domain = "ui", message="Sorry, you forgot to give the amount") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if debit_required: # Source and destination will be updated automaticaly based on the category of bank account # The default account chosen should act as some kind of *temp* account or *parent* account @@ -101,7 +101,7 @@ if debit_required: # Make sure there are no other operations pending for this account if transaction.BankAccount_isMessagePending(bank_account): msg = Message(domain='ui', message="There are operations pending for this account that prevent form calculating its position. Please try again later.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Index the banking operation line so it impacts account position transaction.BankingOperationLine_index(line) @@ -110,10 +110,10 @@ if debit_required: error = transaction.BankAccount_checkBalance(bank_account.getRelativeUrl(), total_debit) if error['error_code'] == 1: msg = Message(domain='ui', message="Bank account is not sufficient.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif error['error_code'] == 2: msg = Message(domain='ui', message="Bank account is not valid.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif error['error_code'] != 0: msg = Message(domain='ui', message="Unknown error code.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/traveler_check_purchase_workflow/scripts/validatePositionAccounting.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/traveler_check_purchase_workflow/scripts/validatePositionAccounting.py index 4192ddc6636fb39854939993bbfc393ef4b9fd3c..8e580f84593fb9e5678bad3e397e6d9551c35aa7 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/traveler_check_purchase_workflow/scripts/validatePositionAccounting.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/traveler_check_purchase_workflow/scripts/validatePositionAccounting.py @@ -7,7 +7,7 @@ date = transaction.getStartDate() source = transaction.getSource(None) if source is None: msg = Message(domain='ui', message='No counter defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check we don't change of user transaction.Baobab_checkSameUserVault(source) @@ -28,7 +28,7 @@ for movement in movement_list: if item.getPortalType()=='Check': if item.getSimulationState()!='confirmed': msg = Message(domain = "ui", message="Sorry, one traveler check was not sale yet") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if item.getPrice() is not None: # then we must calculate the exchange value at the # time where the item was first delivered @@ -40,11 +40,11 @@ for movement in movement_list: start_date=item.getStartDate())[0] if base_price is None: msg = Message(domain = "ui", message="Sorry, no valid price was found for this currency") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) total_credit += base_price*item.getPrice() else: msg = Message(domain = "ui", message="Sorry, the price was not defined on some traveler checks") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if total_credit>0: total_credit = round(total_credit,0) diff --git a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/traveler_check_sale_workflow/scripts/validatePositionAccounting.py b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/traveler_check_sale_workflow/scripts/validatePositionAccounting.py index 36c39a711549559be7eacbeec78fd40d8b17d4c4..b838681098bdab05509e251bad54159c8668cd1e 100644 --- a/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/traveler_check_sale_workflow/scripts/validatePositionAccounting.py +++ b/bt5/erp5_banking_check/WorkflowTemplateItem/portal_workflow/traveler_check_sale_workflow/scripts/validatePositionAccounting.py @@ -6,7 +6,7 @@ transaction = state_change['object'] # check we have defined an account if transaction.getDestinationPayment() is None: msg = Message(domain = "ui", message="Sorry, no account selected") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # First we have to look if we have some checks with some prices, # if so, this means that we are saling such kinds of check, thus @@ -18,7 +18,7 @@ for movement in movement_list: for item in aggregate_value_list: if item.getSimulationState()!='draft': msg = Message(domain = "ui", message="Sorry, one traveler check was already saled") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if item.getPortalType()=='Check': if item.getPrice() is not None: # then we must calculate the exchange value @@ -29,11 +29,11 @@ for movement in movement_list: currency_exchange_type='transfer')[0] if base_price is None: msg = Message(domain = "ui", message="Sorry, no valid price was found for this currency") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) total_debit += base_price*item.getPrice() else: msg = Message(domain = "ui", message="Sorry, the price was not defined on some traveler checks") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if total_debit>0: total_debit = round(total_debit) # Source and destination will be updated automaticaly based on the category of bank account @@ -53,7 +53,7 @@ if total_debit>0: if bank_account is None: msg = Message(domain='ui', message="Sorry, no account defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) price = total_debit @@ -63,7 +63,7 @@ if total_debit>0: # Make sure there are no other operations pending for this account if context.BankAccount_isMessagePending(bank_account): msg = Message(domain='ui', message="There are operations pending for this account that prevent form calculating its position. Please try again later.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Index the banking operation line so it impacts account position context.BankingOperationLine_index(line) @@ -72,23 +72,23 @@ if total_debit>0: error = transaction.BankAccount_checkBalance(bank_account.getRelativeUrl(), price) if error['error_code'] == 1: msg = Message(domain='ui', message="Bank account is not sufficient.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif error['error_code'] == 2: msg = Message(domain='ui', message="Bank account is not valid.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif error['error_code'] != 0: msg = Message(domain='ui', message="Unknown error code.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if total_debit==0: msg = Message(domain='ui', message='Please select at least one traveler check.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) date = transaction.getStartDate() source = transaction.getSource(None) if source is None: msg = Message(domain='ui', message='No counter defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check we are in an opened accounting day transaction.Baobab_checkCounterDateOpen(site=source, date=date) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/AccountingDate_init.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/AccountingDate_init.py index 70220cb849363c6551cb1ec8653b3bb8bb627bfa..d40eea5aa44cac8de5a4a4816f49523958c52733 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/AccountingDate_init.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/AccountingDate_init.py @@ -2,7 +2,7 @@ from DateTime import DateTime user_site_list = context.Baobab_getUserAssignedSiteList() if len(user_site_list) == 0: - raise ValueError, "You cannot create an AccountingDate if you don't have an assignment." + raise ValueError("You cannot create an AccountingDate if you don't have an assignment.") site = context.Baobab_getVaultSite(user_site_list[0]) context.setSiteValue(site) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getMessageTag.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getMessageTag.py index 192ade209e5c48ddba0934f08b9ac11f12993eac..e157c0323b59bd0a790edba892a1a3e1dc504062 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getMessageTag.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getMessageTag.py @@ -1,4 +1,4 @@ reference = bank_account.getReference() if not same_type(reference, ''): - raise TypeError, 'Reference is not a string: %s.getReference() == %s' % (repr(bank_account), repr(reference)) + raise TypeError('Reference is not a string: %s.getReference() == %s' % (repr(bank_account), repr(reference))) return 'bank_account_%s' % (reference, ) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getPosition.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getPosition.py index 6fcd12110d8c8626335ffba56f7a3e1982440e41..f7b80351f6c63fee6109b4a1ead2d4e62b699781 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getPosition.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getPosition.py @@ -1,7 +1,7 @@ bank_account = context resource = bank_account.getPriceCurrencyValue() if resource is None: - raise AttributeError, 'No currency defined on %s' % payment + raise AttributeError('No currency defined on %s' % payment) account_balance = getattr(resource, get_inventory_id)( payment_uid=bank_account.getUid(), optimisation__=False, # XXX: optimisation disabled as it has bugs diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getReportInformationList.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getReportInformationList.py index 1ff835fb72acc1f5717d8a8d6df8a5eec1e82519..9eb5b7b9a231698d20a747660d4b511ffbd38517 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getReportInformationList.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/BankAccount_getReportInformationList.py @@ -6,7 +6,7 @@ portal_type = "Bank Account" if reference is None: message = Message(domain="ui", message="Please give a reference") - raise ValueError, message + raise ValueError(message) #context.log('reference',reference) account_list = catalog(string_index=reference, portal_type=portal_type, validation_state=('valid', 'closed')) @@ -17,10 +17,10 @@ if len(account_list) == 0: #context.log('len 2',len(account_list)) if len(account_list) == 0: message = Message(domain="ui", message="No bank account have this reference") - raise ValueError, message + raise ValueError(message) if force_one_account and len(account_list) != 1: message = Message(domain="ui", message="More than one account match this research") - raise ValueError, message + raise ValueError(message) account_list = [x.getObject() for x in account_list] diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkAccountingDateOpen.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkAccountingDateOpen.py index a05f37fe76e3473e8e084f5b0de592bc046e5429..715fe6dd3b443e88bb19a533d792834bf16b1e9e 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkAccountingDateOpen.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkAccountingDateOpen.py @@ -35,6 +35,6 @@ else: if DateTime(date) < opened_accounting_date: msg = Message(domain = "ui", message="Transaction date incompatible with opened accounting date ${accounting_date}.", mapping={'accounting_date': opened_accounting_date}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) return "ok" diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkCounterDateOpen.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkCounterDateOpen.py index 32f6e4323f395ad4c784362b79dc15df25b40d54..db051a9b9e354783c701ad73fccd8ba3f4813ebb 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkCounterDateOpen.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkCounterDateOpen.py @@ -27,4 +27,4 @@ site = context.Baobab_getVaultSite(site) if context.portal_catalog.countResults(portal_type='Counter Date', start_date=date, site_id=site.getId(), simulation_state="open")[0][0] == 0: msg = Message(domain = "ui", message="Transaction not in the good counter date") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkCounterOpened.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkCounterOpened.py index 1326d96fbac77d679cf61ca473c5fae55d8a481c..2bf6fa22233684cc514461a3435fd593134b2fb4 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkCounterOpened.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkCounterOpened.py @@ -18,4 +18,4 @@ for counter_ob in counter_list: found = 1 if found == 0: msg = Message(domain = "ui", message="Counter is not opened") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkRemainingOperation.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkRemainingOperation.py index 5ee5f77b46091d56a9586f91149a27ad9fe9e414..1c62301b1dc1ee5eef583c568132045638b10730 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkRemainingOperation.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkRemainingOperation.py @@ -14,4 +14,4 @@ for document in document_list: message = Message(domain="ui", message="Sorry, the $portal_type (reference:$reference) is not finished", mapping={'portal_type':portal_type,'reference':reference}) - raise ValidationFailed,message + raise ValidationFailed(message) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkSameUserVault.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkSameUserVault.py index 3b7a6114dabea392c783841959545b937d5e829c..42da0cedd9673203b73e8bbaa5aab8453fcb2a96 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkSameUserVault.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkSameUserVault.py @@ -8,4 +8,4 @@ for site in site_list: return msg = Message(domain = "ui", message="Vault differ between initialisation and transition") -raise ValidationFailed, (msg,) +raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkStockBeforeClosingDate.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkStockBeforeClosingDate.py index 78dcaf7e098e9729b990e23047b7bcf2ecc5be5f..934db8971e6a108f770d757a55e7dde74ae95cce 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkStockBeforeClosingDate.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_checkStockBeforeClosingDate.py @@ -35,13 +35,13 @@ for counter_vault in counter_vault_list: message = Message(domain='ui', message='Sorry, some resources are still remaining here : $counter_title', mapping={'counter_title':counter_title}) - raise ValidationFailed,message + raise ValidationFailed(message) max_price = context.portal_preferences.getPreferredUsualCashMaxRenderingPrice() if max_price is None: message = Message(domain='ui', message='Sorry, you must defined the max price for the usual cash in your preference') - raise ValidationFailed,message + raise ValidationFailed(message) usual_cash = site.getRelativeUrl() + '/surface/caisse_courante/encaisse_des_billets_et_monnaies' inventory_list = context.portal_simulation.getCurrentInventoryList( @@ -53,4 +53,4 @@ context.log('current_price',total_price) if total_price > max_price: message = Message(domain='ui', message='Sorry, the amount in the usual cash is too high') - raise ValidationFailed,message + raise ValidationFailed(message) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getCountryForSite.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getCountryForSite.py index 1ba4a0e77a7b56a9652925e12f1f90689c59ed1c..eceda75126fd38825f67b245a636f0c1fbe9a124 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getCountryForSite.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getCountryForSite.py @@ -10,7 +10,7 @@ def getCountry(site): organisation = context.organisation_module[orga_id] country = organisation.getDefaultRegionTitle() if country is None: - raise ValueError, "No Region found for site %s / %s defined by organisation %s" %(site.getPath(), site.getCodification(), organisation.getPath()) + raise ValueError("No Region found for site %s / %s defined by organisation %s" %(site.getPath(), site.getCodification(), organisation.getPath())) return country diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getVaultCurrency.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getVaultCurrency.py index 4d05fb24b8063e10f826cdcaefaf5478f9601bc8..faf15a2dbacb65a633ebb0b6e17706aba733e8f1 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getVaultCurrency.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getVaultCurrency.py @@ -16,4 +16,4 @@ if 'encaisse_des_devises' in vault_list: else: return context.currency_module[context.Baobab_getPortalReferenceCurrencyID()].getRelativeUrl() -raise ValueError, 'No currency found for vault %s' %vault +raise ValueError('No currency found for vault %s' %vault) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getVaultSite.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getVaultSite.py index 6b3247ba9cd2fc1f49a9ecb4e96b03f8361139b2..e8627072e4cce3ef25adc9add56dc12070316aa9 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getVaultSite.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Baobab_getVaultSite.py @@ -10,7 +10,7 @@ while True: if not hasattr(site, 'getVaultTypeList'): context.log('no getVaultTypeList on :', site.getRelativeUrl()) msg = Message(domain = 'ui', message = 'The site value is misconfigured; report this to system administrators.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if 'site' in site.getVaultTypeList(): break site = site.getParentValue() diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Base_checkBaobabSourceAndDestination.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Base_checkBaobabSourceAndDestination.py index dcaa16b4a559fe80d14f5302220952ad48033eeb..433ab1eacd7ef9d444b3a4584448a55db58dd97f 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Base_checkBaobabSourceAndDestination.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Base_checkBaobabSourceAndDestination.py @@ -16,4 +16,4 @@ for object in object_to_check_list: except KeyError: context.log('Error on ', (context.getRelativeUrl(),node_url)) msg = Message(domain='ui',message='Sorry, wrong source or destination') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Base_getCheckModelByReference.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Base_getCheckModelByReference.py index 5a88f01ad7b247b0f1fd727f5e36522bb0aed385..3bbd9331292e976c37153f7d252972c55897f591 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Base_getCheckModelByReference.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Base_getCheckModelByReference.py @@ -2,7 +2,7 @@ from Products.DCWorkflow.DCWorkflow import ValidationFailed from Products.ERP5Type.Message import Message if reference is None: msg = Message(domain='ui', message="Check not defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) model_list = [x for x in context.checkbook_model_module.objectValues() if x.getReference() == reference @@ -11,8 +11,8 @@ model_list = [x model_list_len = len(model_list) if model_list_len == 0: msg = Message(domain='ui', message="Check not defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if model_list_len > 1: msg = Message(domain='ui', message="Two many check models with this reference.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) return model_list[0] diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDelivery_checkCounterInventory.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDelivery_checkCounterInventory.py index b271109c355ea7e103bd133e76edbe372ee7dbc0..5ed2bc1fd1a08a9b0315158cad1d7c26f38a364e 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDelivery_checkCounterInventory.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDelivery_checkCounterInventory.py @@ -51,7 +51,7 @@ activity_tool = context.portal_activities def checkActivities(source_counter): if activity_tool.countMessageWithTag(source_counter): msg = Message(domain='ui', message="There are operations pending for this vault that prevent form calculating its position. Please try again later.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) inventory_list = context.portal_simulation.getCurrentInventoryList( #at_date=start_date, @@ -85,7 +85,7 @@ for line in line_list : serialize_dict[source_counter] = 1 if source_counter is None: msg = Message(domain="ui", message="No source counter define to check inventory.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) #context.log("CashDelivery_checkCounterInventory", "source_counter = %s" %source_counter) source_object = context.portal_categories.getCategoryValue(source_counter) source_object.serialize() @@ -108,9 +108,9 @@ for line in line_list : 'letter': cell.getEmissionLetterTitle(), 'status': cell.getCashStatusTranslatedTitle(), 'variation':cell.getVariationTitle()}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) else : - raise ValueError, 'This script must not be used on movements without cells. It is deprecated and dangerous, therefor it raises.' + raise ValueError('This script must not be used on movements without cells. It is deprecated and dangerous, therefor it raises.') # inventory_value = context.portal_simulation.getCurrentInventory(section=source_counter, resource=line_resource) # if inventory_value - line.getQuantity() < 0 : # msg = Message(domain='ui', message='Insufficient balance for $resource, letter $letter, status $status and variation $variation', mapping={'resource':line.getResourceTranslatedTitle(), diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDetail_getVariationForMatrixInput.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDetail_getVariationForMatrixInput.py index 327694220200641b5b423762a404b0cfb248abd7..5cf35d37b414a75688df1c09d4b32245dd07632c 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDetail_getVariationForMatrixInput.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDetail_getVariationForMatrixInput.py @@ -22,13 +22,13 @@ else : default_column_base = 'variation' allow_add_line = False -if len(default_emission_letter_list) > 1 and default_column_base <> 'emission_letter': +if len(default_emission_letter_list) > 1 and default_column_base != 'emission_letter': return_list.append(['emission_letter','Emission Letter']) allow_add_line = True -if len(default_cash_status_list) > 1 and default_column_base <> 'cash_status': +if len(default_cash_status_list) > 1 and default_column_base != 'cash_status': return_list.append(['cash_status','Cash Status']) allow_add_line = True -if len(default_variation_list) > 1 and default_column_base <> 'variation': +if len(default_variation_list) > 1 and default_column_base != 'variation': return_list.append(['variation','Variation']) allow_add_line = True diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDetail_saveFastInputLine.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDetail_saveFastInputLine.py index d7f1281cce1275fc4db71e04b77da2f27901e96d..413548cbdd05ec536f2ddc0be68742755e31f9c5 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDetail_saveFastInputLine.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CashDetail_saveFastInputLine.py @@ -205,7 +205,7 @@ if not error: line.updateCellRange(script_id='CashDetail_asCellRange', base_id=cell_base_id) # create cell cell_range_key_list = line.getCellRangeKeyList(base_id=cell_base_id) - if cell_range_key_list <> [[None, None]] : + if cell_range_key_list != [[None, None]] : for k in cell_range_key_list: # check we don't create a cell for variation which is not defined key = "%s_%s_%s" %(k[2], k[0], k[1]) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Check_checkIntervalBetweenDate.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Check_checkIntervalBetweenDate.py index 04db4d0454910d15a053ba2a8fbcdfff9a279241..3978ec8fe513230e90c273c0ab70e82548b45ceb 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Check_checkIntervalBetweenDate.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/Check_checkIntervalBetweenDate.py @@ -16,11 +16,11 @@ if 'compte' in resource_title: if interval['month'] > 0 or interval["day"] > 0: msg = Message(domain='ui', message="Check $check is more than 3 years old.", mapping={"check" : check_nb}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif interval['year'] > 3: msg = Message(domain='ui', message="Check $check is more than 3 years old.", mapping={"check" : check_nb}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif 'virement' in resource_title: interval = getIntervalBetweenDates(start_date, stop_date) @@ -29,8 +29,8 @@ elif 'virement' in resource_title: if interval["day"] > 0: msg = Message(domain='ui', message="Check $check is more than 3 month old.", mapping={"check" : check_nb}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) elif interval['month'] > 3 or interval['year'] > 0: msg = Message(domain='ui', message="Check $check is more than 3 month old.", mapping={"check" : check_nb}) - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CounterDate_init.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CounterDate_init.py index 53c8a6006dd042876ecc93fdceacdd49a1765c95..492ba1ef4339420e74a3406acfca263df34e37ed 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CounterDate_init.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CounterDate_init.py @@ -2,7 +2,7 @@ from DateTime import DateTime user_site_list = context.Baobab_getUserAssignedSiteList() if len(user_site_list) == 0: - raise ValueError, "You cannot create a CounterDate if you don't have an assignment." + raise ValueError("You cannot create a CounterDate if you don't have an assignment.") site = context.Baobab_getVaultSite(user_site_list[0]) context.setSiteValue(site) diff --git a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CounterModule_getVaultTransactionList.py b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CounterModule_getVaultTransactionList.py index 97d45120cf620b95b59a4ffca1252d4404f48948..5c490dd0c4181b49ae8be4275f09e6f85d7c017e 100644 --- a/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CounterModule_getVaultTransactionList.py +++ b/bt5/erp5_banking_core/SkinTemplateItem/portal_skins/erp5_banking_core/CounterModule_getVaultTransactionList.py @@ -40,7 +40,7 @@ if same_type(vault, 'a'): vault_url_list = [vault,] #context.log("vault_url_list", vault_url_list) if vault_url_list is None: - raise ValueError, "The vault must be defined" + raise ValueError("The vault must be defined") for vault_url in vault_url_list: vault_dict[vault_url] = 1 vault_inventory_dict[vault_url] = {} @@ -67,7 +67,7 @@ total_inventory_list = [] inventory_kw = {} #context.log('CounterModule_getVaultTransactionList, vault_report_type',vault_report_type) if vault_report_type == 'inventory' and from_date is not None: - raise ValueError, "The from date must be None in the case of inventory" + raise ValueError("The from date must be None in the case of inventory") if vault_report_type is None or vault_report_type=='inventory': inventory_kw['group_by_variation'] = 1 inventory_kw['group_by_resource'] = 1 diff --git a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/accounting_cancellation_workflow/scripts/validateConsistency.py b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/accounting_cancellation_workflow/scripts/validateConsistency.py index 7352722bb707f28ae711d7c62aa4b188ec4b9f56..91ee72880f1edbe2d7b8dec70308c921408b63ee 100644 --- a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/accounting_cancellation_workflow/scripts/validateConsistency.py +++ b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/accounting_cancellation_workflow/scripts/validateConsistency.py @@ -16,13 +16,13 @@ transaction.Baobab_checkAccountingDateOpen(site=site, date=date) price = transaction.getSourceTotalAssetPrice() if price is None or price <= 0: msg = Message(domain='ui', message='Amount is not valid.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if transaction.getSiteValue() is None: msg = Message(domain='ui', message='Sorry, no site defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if transaction.getResource() is None: msg = Message(domain='ui', message='No resource defined.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Check the source bank account. source_bank_account = transaction.getSourcePaymentValue() @@ -31,7 +31,7 @@ source_bank_account = transaction.getSourcePaymentValue() nb_transfer_line = len(transaction.objectValues(portal_type='Accounting Cancellation Line')) if nb_transfer_line == 0: msg = Message(domain='ui', message='You must add line before validating the operation') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # only one line can be defined with SICA/STAR, on order as it can be cancel or reject later #if transaction.getExternalSoftware() in ('sica', 'star') and nb_transfer_line != 1: @@ -46,21 +46,21 @@ for line in transaction.objectValues(portal_type='Accounting Cancellation Line') if line.getSourcePaymentReference(None) is None and \ line.getSourceSection() is None: msg = Message(domain='ui', message="No account defined on line.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check we don't have both account and accounting code defined if line.getDestinationPayment(None) is not None \ and line.getDestinationSection() is not None: msg = Message(domain='ui', message="You can't defined account and accounting code on line.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # check that at least destination_payment or destination_section is defined if line.getDestinationPayment() is None and \ line.getDestinationSection() is None: msg = Message(domain='ui', message="Destination account is not defined.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Index the banking operation line so it impacts account position if line.getSourcePaymentReference() not in (None, ''): context.BankingOperationLine_index(line, source=1) if total_line_price != transaction.getSourceTotalAssetPrice(): msg = Message(domain='ui', message="Total price doesn't match between line and document.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/bank_account_workflow/scripts/checkBankAccount.py b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/bank_account_workflow/scripts/checkBankAccount.py index 238f9dab6b7b922b2995626ad1913848956e1691..07ead2ea1b7d6ff9314b300771dd11e693122516 100644 --- a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/bank_account_workflow/scripts/checkBankAccount.py +++ b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/bank_account_workflow/scripts/checkBankAccount.py @@ -7,14 +7,14 @@ bank_account = state_change['object'] if bank_account.getParentValue().getPortalType()!= 'Person': vliste = bank_account.checkConsistency() if len(vliste) != 0: - raise ValidationFailed, (vliste[0].getTranslatedMessage(),) + raise ValidationFailed(vliste[0].getTranslatedMessage(),) if bank_account.getParentValue().getPortalType()== 'Person': # Can't have two bank account for obj in bank_account.getParentValue().objectValues(): if obj.getPortalType() == "Bank Account" and obj.getValidationState() not in ('draft', 'closed') \ and obj.getSource() == bank_account.getSource() and obj.getPath()!= bank_account.getPath(): - raise ValidationFailed, "You cannot open two bank accounts for the same person on the same site" + raise ValidationFailed("You cannot open two bank accounts for the same person on the same site") valid_state = ["valid", "being_closed", "validating_closing", "being_modified", "validating_modification", "closed"] @@ -26,7 +26,7 @@ same_ref_list = context.portal_catalog(validation_state=valid_state, for doc in same_ref_list: if doc.getPath() != bank_account.getPath(): context.log("doc path %s" %(doc.getPath(),)) - raise ValidationFailed, "Bank account with same reference already exists" + raise ValidationFailed("Bank account with same reference already exists") # Same for internal reference if exists @@ -38,4 +38,4 @@ if bank_account.getInternalBankAccountNumber() not in ("", None): for doc in same_ref_list: if doc.getPath() != bank_account.getPath(): context.log("doc path %s" %(doc.getPath(),)) - raise ValidationFailed, "Bank account with same internal reference already exists" + raise ValidationFailed("Bank account with same internal reference already exists") diff --git a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/checkbook_workflow/scripts/Checkbook_deleteAllCheckList.py b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/checkbook_workflow/scripts/Checkbook_deleteAllCheckList.py index b11014a712026ed3a20e13b85f70964df34fc839..5191225345c24fc2c14015c2b127c0961aa7cb6c 100644 --- a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/checkbook_workflow/scripts/Checkbook_deleteAllCheckList.py +++ b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/checkbook_workflow/scripts/Checkbook_deleteAllCheckList.py @@ -5,4 +5,4 @@ for check in checkbook.objectValues(): if check.getSimulationState() != 'deleted': msg = Message(domain="ui", message="Sorry, no way to delete this check $id", mapping = {'id' : check.getId()}) - raise ValueError, (msg,) + raise ValueError(msg,) diff --git a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/checkbook_workflow/scripts/checkConsistency.py b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/checkbook_workflow/scripts/checkConsistency.py index 490854d10cd905d696b0e85406e5a295d869fd15..7549b265a4133a345b61480cf230ef12cc26d14b 100644 --- a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/checkbook_workflow/scripts/checkConsistency.py +++ b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/checkbook_workflow/scripts/checkConsistency.py @@ -8,4 +8,4 @@ if len(check_result) > 0: check_type = N_(check_result[0][-1]) # TODO: use nice url encoding method there instead of replace() check_details = check_result[0][-2].replace('<', '<').replace('>', '>') - raise ValidationFailed, "%s : %s" % (check_type, check_details) + raise ValidationFailed("%s : %s" % (check_type, check_details)) diff --git a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_date_workflow/scripts/closeAllCounter.py b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_date_workflow/scripts/closeAllCounter.py index 342354f7b8f0721b5c8a4759dafbe8afb800841a..5c0f733be5cc6fe3f8fa28b3924afa700085327f 100644 --- a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_date_workflow/scripts/closeAllCounter.py +++ b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_date_workflow/scripts/closeAllCounter.py @@ -8,7 +8,7 @@ site = transaction.getSiteValue() while True: if not hasattr(site, 'getVaultTypeList'): msg = Message(domain = 'ui', message = 'The site value is misconfigured; report this to system administrators.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if 'site' in site.getVaultTypeList(): break site = site.getParentValue() diff --git a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_workflow/scripts/cancelRemainingOperation.py b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_workflow/scripts/cancelRemainingOperation.py index 696aa78df874fdc4276d7ddba07f1e7e947b8314..162c10eeddc50368f0a2fa7b618d9495685dfbf7 100644 --- a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_workflow/scripts/cancelRemainingOperation.py +++ b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_workflow/scripts/cancelRemainingOperation.py @@ -13,7 +13,7 @@ date_list = [x.getObject() for x in context.portal_catalog(**kwd)] current_date = None if len(date_list) == 0: msg = Message(domain = 'ui', message = 'No Counter Date found for this counter') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) else: current_date = date_list[0].getStartDate() diff --git a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_workflow/scripts/checkDateOpened.py b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_workflow/scripts/checkDateOpened.py index e398d15a5aea0687d27d7d22a07aa06e4eac62cb..b3a60a526837e31f5325ae08fef024d4dd20a953 100644 --- a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_workflow/scripts/checkDateOpened.py +++ b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/counter_workflow/scripts/checkDateOpened.py @@ -8,7 +8,7 @@ site = transaction.getSiteValue() while True: if not hasattr(site, 'getVaultTypeList'): msg = Message(domain = 'ui', message = 'The site value is misconfigured; report this to system administrators.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) if 'site' in site.getVaultTypeList(): break site = site.getParentValue() @@ -18,4 +18,4 @@ date_list = [x.getObject() for x in context.portal_catalog(**kwd)] if len(date_list) == 0: msg = Message(domain='ui', message="Counter date is not opened.") - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) diff --git a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/currency_exchange_line_workflow/scripts/checkSingleExchangeLine.py b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/currency_exchange_line_workflow/scripts/checkSingleExchangeLine.py index 8ed06f23ed1e3ddbb3b00bf5f308ef11fb39f6e6..700af6a1b8bdf5ceb8ca292796656f7bc3e43086 100644 --- a/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/currency_exchange_line_workflow/scripts/checkSingleExchangeLine.py +++ b/bt5/erp5_banking_core/WorkflowTemplateItem/portal_workflow/currency_exchange_line_workflow/scripts/checkSingleExchangeLine.py @@ -10,7 +10,7 @@ exchange_line = state_change['object'] if exchange_line.getBasePrice() in (None, 0, 0.0): msg = Message(domain = 'ui', message = 'Sorry, you must define a fixing price.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # We have to looking for other currency exchanges lines @@ -34,7 +34,7 @@ line_list = [x for x in exchange_line.portal_domains.searchPredicateList(temp_ob start_date = exchange_line.getStartDate() if start_date is None: msg = Message(domain = 'ui', message = 'Sorry, you must define a start date.') - raise ValidationFailed, (msg,) + raise ValidationFailed(msg,) # Make sure there is not two exchange lines wich defines the same dates # for this particular ressource and price_currency diff --git a/bt5/erp5_barcode/ExtensionTemplateItem/portal_components/extension.erp5.Barcode.py b/bt5/erp5_barcode/ExtensionTemplateItem/portal_components/extension.erp5.Barcode.py index a6f3ef1f9dc5d9f687511c36a65924e122967883..cf9f783961ff51193c565bd6ea9371770260668e 100644 --- a/bt5/erp5_barcode/ExtensionTemplateItem/portal_components/extension.erp5.Barcode.py +++ b/bt5/erp5_barcode/ExtensionTemplateItem/portal_components/extension.erp5.Barcode.py @@ -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) ret = os.system(ps2pdf_command) if ret != 0: - raise RuntimeError, 'PS Conversion Failed' + raise RuntimeError('PS Conversion Failed') file = open(new_pdf_file_path, 'rb') result = file.read() file_size = len(result) @@ -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) ret = os.system(text_command) 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): margin = '%sx%s' % (horizontal_padding, vertical_padding) @@ -139,7 +139,7 @@ def printBarcodeSheet(self, sheet_number=1, input_list=[], test=False): barcode_command += ' -o %s ' %(new_ps_file_path) ret = os.system(barcode_command) if ret != 0: - raise RuntimeError, 'Barcode PS File Creation Failed' + raise RuntimeError('Barcode PS File Creation Failed') if test: return getPdfOutput(self, new_ps_file_path, file_name='TestReferenceSheet.pdf') diff --git a/bt5/erp5_base/ExtensionTemplateItem/portal_components/extension.erp5.BarcodeUtils.py b/bt5/erp5_base/ExtensionTemplateItem/portal_components/extension.erp5.BarcodeUtils.py index e5d67277d2ba77da86f9ff937e4bc57d956e3aef..2ebb098be2e422356c1bb356ef6d5628d8a7014f 100644 --- a/bt5/erp5_base/ExtensionTemplateItem/portal_components/extension.erp5.BarcodeUtils.py +++ b/bt5/erp5_base/ExtensionTemplateItem/portal_components/extension.erp5.BarcodeUtils.py @@ -29,7 +29,7 @@ def generateBarcodeImage(self, barcode_type, data, REQUEST=None): fp.seek(0) output = fp.read() 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: REQUEST.RESPONSE.setHeader('Content-Type', 'image/png') return output diff --git a/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_getCareerStartDate.py b/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_getCareerStartDate.py index a14210c3f3ee52676a42654fc734a03c79a87dc2..f6d9cbb60f636cfe53e0249e3133c7ca12dae2e7 100644 --- a/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_getCareerStartDate.py +++ b/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_getCareerStartDate.py @@ -17,4 +17,4 @@ for career_step in career_step_list : # for now, we only return the first one. return career_step.getStartDate() -raise ValueError, 'No Career Step Defined.' +raise ValueError('No Career Step Defined.') diff --git a/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_shiftDefaultCareer.py b/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_shiftDefaultCareer.py index a374840ce46e90141c5fb4a7ee7b771acee8b089..172c0836ee8870acb0daf521e7334adbdf1f884e 100644 --- a/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_shiftDefaultCareer.py +++ b/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_shiftDefaultCareer.py @@ -21,7 +21,7 @@ else: new_id = person.generateNewId() try: default_career.setId(new_id) - except ActivityPendingError, error: + except ActivityPendingError as error: message = Base_translateString("%s" % error) return context.Base_redirect(form_id=form_id, selection_name=selection_name, diff --git a/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_updateUserSecurityGroup.py b/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_updateUserSecurityGroup.py index e064bcb900b1715511d9cccefc9e3cddd40b5e93..4895c223905ca821a966ab3c76d8202dc8b99dae 100644 --- a/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_updateUserSecurityGroup.py +++ b/bt5/erp5_base/SkinTemplateItem/portal_skins/erp5_base/Person_updateUserSecurityGroup.py @@ -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. # 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(): - raise RuntimeError, "Error: Zope user '%s' doesn't exist in the acl_users folder" % (user_name) + raise RuntimeError("Error: Zope user '%s' doesn't exist in the acl_users folder" % (user_name)) category_list = [] security_group_list = [] diff --git a/bt5/erp5_base/WorkflowTemplateItem/portal_workflow/assignment_workflow/scripts/Assignment_checkActiveAssignmentConsistency.py b/bt5/erp5_base/WorkflowTemplateItem/portal_workflow/assignment_workflow/scripts/Assignment_checkActiveAssignmentConsistency.py index 7e484debc832cc798fd3c5fde7dd897c970d8c05..658d20b6bfdeaf7e6a31cca9cdd285f591f25737 100644 --- a/bt5/erp5_base/WorkflowTemplateItem/portal_workflow/assignment_workflow/scripts/Assignment_checkActiveAssignmentConsistency.py +++ b/bt5/erp5_base/WorkflowTemplateItem/portal_workflow/assignment_workflow/scripts/Assignment_checkActiveAssignmentConsistency.py @@ -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. 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.") diff --git a/bt5/erp5_budget/WorkflowTemplateItem/portal_workflow/budget_transaction_workflow/scripts/BudgetTransaction_checkFeasability.py b/bt5/erp5_budget/WorkflowTemplateItem/portal_workflow/budget_transaction_workflow/scripts/BudgetTransaction_checkFeasability.py index 6a84637e93ec3271a6e1db7116a85fb2cd1ec0b7..c3c839e873c03bf14bdf28da09efe22e83400681 100644 --- a/bt5/erp5_budget/WorkflowTemplateItem/portal_workflow/budget_transaction_workflow/scripts/BudgetTransaction_checkFeasability.py +++ b/bt5/erp5_budget/WorkflowTemplateItem/portal_workflow/budget_transaction_workflow/scripts/BudgetTransaction_checkFeasability.py @@ -8,4 +8,4 @@ for elem in consistency: error_msg =error_msg+' '+elem[4] if consistency != []: - raise ValidationFailed, str(error_msg) + raise ValidationFailed(str(error_msg)) diff --git a/bt5/erp5_calendar/SkinTemplateItem/portal_skins/erp5_calendar/PersonModule_getLeaveRequestReportLineList.py b/bt5/erp5_calendar/SkinTemplateItem/portal_skins/erp5_calendar/PersonModule_getLeaveRequestReportLineList.py index 838953f9d8088637416f76759aa0d09832a88689..ea78b528d7e10a9c47ac1a7b6f09249712f54f9d 100644 --- a/bt5/erp5_calendar/SkinTemplateItem/portal_skins/erp5_calendar/PersonModule_getLeaveRequestReportLineList.py +++ b/bt5/erp5_calendar/SkinTemplateItem/portal_skins/erp5_calendar/PersonModule_getLeaveRequestReportLineList.py @@ -42,8 +42,8 @@ for person in person_value_list: resource = inventory.resource_relative_url if inventory.resource_uid in presence_resource_uid_list: - raise ValueError, "This report does not work when same resource are"\ - " used in presence and leave." + raise ValueError("This report does not work when same resource are"\ + " used in presence and leave.") person_time = (person_planned_time - person.getAvailableTime( from_date=from_date, diff --git a/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/Resource_addToShoppingCart.py b/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/Resource_addToShoppingCart.py index e2daf3fd8e7a6141f13fcb0d0895be04339e3432..6c3c12fa97ebf49f8f90f9d36e0b71058319f979 100644 --- a/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/Resource_addToShoppingCart.py +++ b/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/Resource_addToShoppingCart.py @@ -14,7 +14,7 @@ if form_id is not None: # button itself try: params = form.validate_all_to_request(request) - except FormValidationError, validation_errors: + except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/SaleOrder_finalizeShopping.py b/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/SaleOrder_finalizeShopping.py index bfbcc471cf0f044019486f74c7f3cca89e9a4706..9f44765bd89d2e2df33fb75d9cfcaf1447677bf5 100644 --- a/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/SaleOrder_finalizeShopping.py +++ b/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/SaleOrder_finalizeShopping.py @@ -21,7 +21,7 @@ if isAnon: #Check if payment is sucessfull 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() module = context.getDefaultModule(portal_type) diff --git a/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/SaleOrder_setShoppingCartBuyer.py b/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/SaleOrder_setShoppingCartBuyer.py index 9ca9ae78beb526056e55d1399a459f020aa38f8d..578c65d8394e499310512c86f6c968bc122faf0d 100644 --- a/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/SaleOrder_setShoppingCartBuyer.py +++ b/bt5/erp5_commerce/SkinTemplateItem/portal_skins/erp5_commerce/SaleOrder_setShoppingCartBuyer.py @@ -1,6 +1,6 @@ """Set connected user as shopping cart customer""" 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() diff --git a/bt5/erp5_content_translation/SkinTemplateItem/portal_skins/erp5_content_translation/Base_editContentTranslationMessage.py b/bt5/erp5_content_translation/SkinTemplateItem/portal_skins/erp5_content_translation/Base_editContentTranslationMessage.py index b50129ecb176cb3390bc5227ce67e50eb8cd4d3e..7b3937dffdf1eb9658e63d720646ed68c5df9323 100644 --- a/bt5/erp5_content_translation/SkinTemplateItem/portal_skins/erp5_content_translation/Base_editContentTranslationMessage.py +++ b/bt5/erp5_content_translation/SkinTemplateItem/portal_skins/erp5_content_translation/Base_editContentTranslationMessage.py @@ -31,7 +31,7 @@ edit_order = form.edit_order try: # Validate form.validate_all_to_request(request) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRecovery_sendPasswordResetLink.py b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRecovery_sendPasswordResetLink.py index ab3725ec2181a118e0121d338e94df861d8e6f93..1fa6eeb5ce04102fb4c271d02754f18b48930b90 100644 --- a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRecovery_sendPasswordResetLink.py +++ b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRecovery_sendPasswordResetLink.py @@ -10,7 +10,7 @@ if context.hasDocumentReference(): else: message_reference = portal.portal_preferences.getPreferredCredentialPasswordRecoveryMessageReference() if message_reference is None: - raise ValueError, "Preference not configured" + raise ValueError("Preference not configured") notification_message = portal.NotificationTool_getDocumentValue(message_reference, context.getLanguage()) diff --git a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRecovery_sendUsernameRecoveryMessage.py b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRecovery_sendUsernameRecoveryMessage.py index 244c6095f5ba49d3c21549c5d48c9845b37bcf7b..5c9017f4c3479fd02beed708801e8f2e6218a8cb 100644 --- a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRecovery_sendUsernameRecoveryMessage.py +++ b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRecovery_sendUsernameRecoveryMessage.py @@ -17,7 +17,7 @@ if context.hasDocumentReference(): else: message_reference = portal.portal_preferences.getPreferredCredentialUsernameRecoveryMessageReference() if message_reference is None: - raise ValueError, "Preference not configured" + raise ValueError("Preference not configured") notification_message = portal.NotificationTool_getDocumentValue(message_reference, context.getLanguage()) diff --git a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRequest_createUser.py b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRequest_createUser.py index adc98c2d042a53489fa67451a38a51fe6d8b87a8..c8e5c56cf7b992f2df9c211ab1bacae8793077bb 100644 --- a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRequest_createUser.py +++ b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRequest_createUser.py @@ -6,7 +6,7 @@ #Don't allow to call from url 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_preferences = context.portal_preferences @@ -27,7 +27,7 @@ if user_id and login.hasPassword(): reference = context.getReference() if not login.hasReference(): if not reference: - raise ValueError, "Impossible to create an account without login" + raise ValueError("Impossible to create an account without login") login.setReference(reference) if not user_id: person.setUserId(reference) diff --git a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRequest_sendAcceptedNotification.py b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRequest_sendAcceptedNotification.py index 25d35ea0adc390e9fb55d74fe3d502f385b84744..f0a0e2705b839b9b33c0544b12c7a39e0b4d7ec2 100644 --- a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRequest_sendAcceptedNotification.py +++ b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialRequest_sendAcceptedNotification.py @@ -16,7 +16,7 @@ notification_reference = 'credential_request-confirmation-%s' % notification_typ notification_message = portal.portal_notifications.getDocumentValue(reference=notification_reference, language=recipient.getLanguage()) 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 notification_mapping_dict = {'login_name': login} diff --git a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialUpdate_copyDefaultImage.py b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialUpdate_copyDefaultImage.py index c4ee3c1376ef34cebd78be5599e3c19a0d83ee30..f9d6ea46f164b600ca11c75221bad51eaaed23bf 100644 --- a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialUpdate_copyDefaultImage.py +++ b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/CredentialUpdate_copyDefaultImage.py @@ -3,7 +3,7 @@ Proxy Manager -- allow to update all image property""" 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(property): return "".join([x.capitalize() for x in property.split('_')]) diff --git a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/Credential_checkConsistency.py b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/Credential_checkConsistency.py index cd5a2e65d01c607247d14f898b43db1c135267b8..5dd0af451a5b383114b896db99afdf07e8c30864 100644 --- a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/Credential_checkConsistency.py +++ b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/Credential_checkConsistency.py @@ -8,4 +8,4 @@ Assignee -- allow to check credential informations""" for portal_type in destination_decision_type: destination = context.getDestinationDecisionValue(portal_type=portal_type) 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)) diff --git a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/Credential_updatePersonPassword.py b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/Credential_updatePersonPassword.py index 23ffb448e46a25e658818f27a35c9d0c038afeef..d3ff67a75aa2a06f1ffed806c979b5a9e5e3594a 100644 --- a/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/Credential_updatePersonPassword.py +++ b/bt5/erp5_credential/SkinTemplateItem/portal_skins/erp5_credential/Credential_updatePersonPassword.py @@ -14,16 +14,16 @@ if context.getPassword(): if login.getReference() == reference: break else: - raise RuntimeError, 'Person %s does not have a validated Login with reference %r' % \ - (person.getRelativeUrl(), reference) + raise RuntimeError('Person %s does not have a validated Login with reference %r' % \ + (person.getRelativeUrl(), reference)) else: # BBB when login reference is not set in Credential Update document. if login_list: user_id = person.Person_getUserId() login = sorted(login_list, key=lambda x:x.getReference() == user_id, reverse=True)[0] else: - raise RuntimeError, 'Person %s does not have a validated Login with reference %r' % \ - (person.getRelativeUrl(), reference) + raise RuntimeError('Person %s does not have a validated Login with reference %r' % \ + (person.getRelativeUrl(), reference)) else: # BBB login = person diff --git a/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Base_addEvent.py b/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Base_addEvent.py index 1bd37f9f6be25c83383c8a6329630db99e7fca21..c3d42661727f735cc5f2ff4bd0bf16c6a6616957 100644 --- a/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Base_addEvent.py +++ b/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Base_addEvent.py @@ -47,7 +47,7 @@ elif direction == 'incoming': destination_url = destination or person destination_section_url = organisation else: - raise NotImplementedError, 'The specified direction is not handled: %r' % (direction,) + raise NotImplementedError('The specified direction is not handled: %r' % (direction,)) event_kw = { 'portal_type' : portal_type, diff --git a/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Event_createRelatedEvent.py b/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Event_createRelatedEvent.py index 9b209609dbdd3dbc89e6374b92a66d6d882bf9d2..a3149b8934f009cfad9d820fb676d64f7011479f 100644 --- a/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Event_createRelatedEvent.py +++ b/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Event_createRelatedEvent.py @@ -7,7 +7,7 @@ date = DateTime() portal = context.getPortalObject() if portal_type not in portal.event_module.getVisibleAllowedContentTypeList(): - raise WorkflowException, "You Don't Have Permission to Add New Event" + raise WorkflowException("You Don't Have Permission to Add New Event") # Create the draft Event related_event = portal.event_module.newContent( diff --git a/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Folder_getTicketDetailedEventsLineList.py b/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Folder_getTicketDetailedEventsLineList.py index c3c3771fd3f7d8de19e9dee13f641191d8e16ff0..5e1a3148f6037c5a69ebccc111052c137771eb7d 100644 --- a/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Folder_getTicketDetailedEventsLineList.py +++ b/bt5/erp5_crm/SkinTemplateItem/portal_skins/erp5_crm/Folder_getTicketDetailedEventsLineList.py @@ -49,7 +49,7 @@ for r_ticket in ticket_list: for r_event_causality in event_causality_list: event_causality = r_event_causality.getObject() #check that one event it isn't related by causality and follow-up with the same ticket - if ticket.getUid() <> event_causality.getFollowUpUid(): + if ticket.getUid() != event_causality.getFollowUpUid(): line_list.append(Object(uid='new_', ticket='', type=event_causality.getTranslatedPortalType(), diff --git a/bt5/erp5_crm/WorkflowTemplateItem/portal_workflow/event_workflow/scripts/Event_createEventForAcknowledge.py b/bt5/erp5_crm/WorkflowTemplateItem/portal_workflow/event_workflow/scripts/Event_createEventForAcknowledge.py index 940baffd93c311de0da17b549a482206f3ed5efd..1139aa1c07c07b8010952d0a0ad4edaae06d04a7 100644 --- a/bt5/erp5_crm/WorkflowTemplateItem/portal_workflow/event_workflow/scripts/Event_createEventForAcknowledge.py +++ b/bt5/erp5_crm/WorkflowTemplateItem/portal_workflow/event_workflow/scripts/Event_createEventForAcknowledge.py @@ -24,7 +24,7 @@ follow_up = event.getFollowUp() if follow_up is None: 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: event.Event_createFollowUpTicket(follow_up_ticket_title, diff --git a/bt5/erp5_deferred_style/SkinTemplateItem/portal_skins/erp5_deferred_style_core/Base_computeReportSection.py b/bt5/erp5_deferred_style/SkinTemplateItem/portal_skins/erp5_deferred_style_core/Base_computeReportSection.py index 0347912cfcbf21508b701d391cdd3c82e3184f55..6e7160c56d5b3b2fdcb788a3c85d5e0acdee76c7 100644 --- a/bt5/erp5_deferred_style/SkinTemplateItem/portal_skins/erp5_deferred_style_core/Base_computeReportSection.py +++ b/bt5/erp5_deferred_style/SkinTemplateItem/portal_skins/erp5_deferred_style_core/Base_computeReportSection.py @@ -13,7 +13,7 @@ with portal.Localizer.translationContext(localizer_language): if field.getRecursiveTemplateField().meta_type == 'ReportBox': report_section_list.extend(field.render()) 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'))) diff --git a/bt5/erp5_development_wizard/ExtensionTemplateItem/portal_components/extension.erp5.Development.py b/bt5/erp5_development_wizard/ExtensionTemplateItem/portal_components/extension.erp5.Development.py index 785e2e26414c07287e08dbe83c48bfc1c8e7d3e4..268b15acaa35d9f276ec6897f8611af380288183 100644 --- a/bt5/erp5_development_wizard/ExtensionTemplateItem/portal_components/extension.erp5.Development.py +++ b/bt5/erp5_development_wizard/ExtensionTemplateItem/portal_components/extension.erp5.Development.py @@ -36,7 +36,7 @@ def Base_runPythonScript(self, code): code = '\n'.join(code_line_list) script.write(code) if script._code is None: - raise ValueError, repr(script.errors) + raise ValueError(repr(script.errors)) return script() diff --git a/bt5/erp5_discussion/SkinTemplateItem/portal_skins/erp5_discussion/WebSection_createNewDiscussionThread.py b/bt5/erp5_discussion/SkinTemplateItem/portal_skins/erp5_discussion/WebSection_createNewDiscussionThread.py index c456a6c917b54877463a3e6a2e4c0b0d07636c18..04cadaff378f968dcf9e52d4b22c909c6bbb0bb1 100644 --- a/bt5/erp5_discussion/SkinTemplateItem/portal_skins/erp5_discussion/WebSection_createNewDiscussionThread.py +++ b/bt5/erp5_discussion/SkinTemplateItem/portal_skins/erp5_discussion/WebSection_createNewDiscussionThread.py @@ -119,7 +119,7 @@ if send_notification_text not in ('', None): notification_reference = 'forum-new-thread' notification_message = context.NotificationTool_getDocumentValue(notification_reference, 'en') 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(), 'url': discussion_thread.absolute_url(), diff --git a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Base_getAdvancedSearchResultList.py b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Base_getAdvancedSearchResultList.py index c5f4008715224e70ab6419adf46f266d519edc8b..4f2ed4589c8c536f781636f0b8e37286fda0e54d 100644 --- a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Base_getAdvancedSearchResultList.py +++ b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Base_getAdvancedSearchResultList.py @@ -27,7 +27,7 @@ if searchabletext is None: searchabletext = selection_object.get('searchabletext') if searchabletext is None: - raise ValueError, "No search string specified." + raise ValueError("No search string specified.") parsed_search_string = context.Base_parseSearchString(searchabletext) diff --git a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_getPreviewAsHTML.py b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_getPreviewAsHTML.py index 5d323c8137cedf1e9e12be65846f572fa07433bb..6bf18790354cb3d32eb024536fe2ff127d7ee00b 100644 --- a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_getPreviewAsHTML.py +++ b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_getPreviewAsHTML.py @@ -8,7 +8,7 @@ try: return result if not context.hasBaseData(): error_message = context.Base_translateString("This document is not converted yet.") -except Exception, e: +except Exception as e: from Products.ERP5Type.Log import log log("asStrippedHTML", str(e)) error_message = "%s %s" % (context.Base_translateString("Preview Error:"), diff --git a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_tryToConvertToBaseFormat.py b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_tryToConvertToBaseFormat.py index 6b222d60d1ef8b7ff6b4f6b96a7d0a0afd80b760..9507969b1c87d48bfeb819ca5e74895a5376c822 100644 --- a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_tryToConvertToBaseFormat.py +++ b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_tryToConvertToBaseFormat.py @@ -11,13 +11,13 @@ if context.getExternalProcessingState() not in ('converted', 'empty'): return context.convertToBaseFormat() except ConflictError: raise - except ConversionError, e: + except ConversionError as e: message = 'Conversion Error: %s' % (str(e) or 'undefined.') - except Fault, e: + except Fault as e: message = 'XMLFault: %s' % (repr(e) or 'undefined.') - except SocketError, e: + except SocketError as e: message = 'Socket Error: %s' % (repr(e) or 'undefined.') - except Exception, e: + except Exception as e: message = 'Problem: %s' % (repr(e) or 'undefined.') except: message = 'Problem: unknown' diff --git a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_tryToUpdateBaseMetadata.py b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_tryToUpdateBaseMetadata.py index 4ef7dab1315ebe6e51ded3eeaeea12cc1ef7934a..7e753764fa67503e34c78a0d93b31db6b74a2ebb 100644 --- a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_tryToUpdateBaseMetadata.py +++ b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/Document_tryToUpdateBaseMetadata.py @@ -7,9 +7,9 @@ try: return context.updateBaseMetadata(**kw) except ConflictError: raise -except ConversionError, e: +except ConversionError as e: message = 'Conversion Error: %s' % (str(e) or 'undefined.') -except Exception, e: +except Exception as e: message = 'Problem: %s' % (repr(e) or 'undefined.') except: message = 'Problem: unknown' diff --git a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromAssignmentTree.py b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromAssignmentTree.py index 6f2f4f3eeaa6f253356dec61a39b070f5f43818d..b137e83618c1e495f58853adf3095758f3c60e4c 100644 --- a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromAssignmentTree.py +++ b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromAssignmentTree.py @@ -34,7 +34,7 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment if root: category_value=category_value.split('/')[0] category_dict[base_category] = category_value 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) # 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 :) @@ -44,7 +44,7 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment cdict = category_dict.copy() cdict[base_category] = '/'.join(grouplist[:-i]) category_list.append(cdict) - except RuntimeError,e: + except RuntimeError as e: log(str(e)) return category_list diff --git a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromDestination.py b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromDestination.py index 6c8a23a8e12a7434b29c6b11457533a99b945db3..847fa6e51c388294ca2acf8a25661f1c9fdf67ae 100644 --- a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromDestination.py +++ b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromDestination.py @@ -15,7 +15,7 @@ for ob in object.getDestinationValueList(): if category_value not in (None, ''): category_dict[base_category] = category_value 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) log(category_list) diff --git a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromDestinationAssignment.py b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromDestinationAssignment.py index a58c1bcd0f859825f873b7fc8c374bb5b06108a3..7743d1a390ee0475c72e19f3456b2288f770c46c 100644 --- a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromDestinationAssignment.py +++ b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromDestinationAssignment.py @@ -18,7 +18,7 @@ for person_object in object.getDestinationValueList(portal_type='Person'): if category_value not in (None, ''): category_dict[base_category] = category_value 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) return category_list diff --git a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromObjectAssignment.py b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromObjectAssignment.py index c378a7735f0ff584eb182334da832cd8136aa6ad..66ad2fdf9ba06795531ede7c90ee2a4f0cbf18a7 100644 --- a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromObjectAssignment.py +++ b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromObjectAssignment.py @@ -22,7 +22,7 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment if category_value not in (None, ''): category_dict[base_category] = category_value 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) return category_list diff --git a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromUser.py b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromUser.py index f11264227f072d8b9cc90e3e59ee2674dbc5f347..f712d0e4a802b905c68d582d99b60b50e1654ac7 100644 --- a/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromUser.py +++ b/bt5/erp5_dms/SkinTemplateItem/portal_skins/erp5_dms/ERP5Type_getSecurityCategoryFromUser.py @@ -18,7 +18,7 @@ for base_category in base_category_list: if category_value not in (None, ''): category_dict[base_category] = category_value 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) return category_list diff --git a/bt5/erp5_egov/ExtensionTemplateItem/portal_components/extension.erp5.Captcha.py b/bt5/erp5_egov/ExtensionTemplateItem/portal_components/extension.erp5.Captcha.py index 654dcde269f012f8e27c592feea43cf50570a673..5c3c295013a241739a6eb1b5096ca72fd14e9265 100644 --- a/bt5/erp5_egov/ExtensionTemplateItem/portal_components/extension.erp5.Captcha.py +++ b/bt5/erp5_egov/ExtensionTemplateItem/portal_components/extension.erp5.Captcha.py @@ -52,7 +52,7 @@ def generateBgFile(size_x, size_y): tmp_file.close() if not os.path.exists('/usr/bin/convert'): - raise ValueError, "convert command is not installed" + raise ValueError("convert command is not installed") convert_options = 'plasma:fractal -blur 0x5 -shade 120x45 -normalize' #convert_options = 'plasma:fractal' cmd = '/usr/bin/convert -size %sx%s %s jpg:%s' % (size_x, size_y, diff --git a/bt5/erp5_egov/ExtensionTemplateItem/portal_components/extension.erp5.EGovSecurity.py b/bt5/erp5_egov/ExtensionTemplateItem/portal_components/extension.erp5.EGovSecurity.py index da8c70fa877d84560b473b8ebfea2ad55592321c..3781194faa379d4c9f0e8fa09832ad84036fea36 100644 --- a/bt5/erp5_egov/ExtensionTemplateItem/portal_components/extension.erp5.EGovSecurity.py +++ b/bt5/erp5_egov/ExtensionTemplateItem/portal_components/extension.erp5.EGovSecurity.py @@ -205,7 +205,7 @@ def getSecurityCategoryFromAssignment(self, base_category_list, user_name, if len(person_object_list) != 1: if len(person_object_list) > 1: - raise ConsistencyError, "Error: There is more than one Person with reference '%s'" % user_name + raise ConsistencyError("Error: There is more than one Person with reference '%s'" % user_name) else: # if a person_object was not found in the module, we do nothing more # this happens for example when a manager with no associated person @@ -271,7 +271,7 @@ def getSecurityCategoryFromEntity(self, base_category_list, entity_name, if len(object_list) != 1: if len(object_list) > 1: - raise ConsistencyError, "Error: There is more than one Entity with reference '%s'" % entity_name + raise ConsistencyError("Error: There is more than one Entity with reference '%s'" % entity_name) else: # if a person_object was not found in the module, we do nothing more # this happens for example when a manager with no associated person diff --git a/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/EGov_Base_editAndNextStep.py b/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/EGov_Base_editAndNextStep.py index 6de23f6faa62291926c4d05bdfef6be75bb64c9b..14e05e573854a60467af4baf47cd8d229d862c40 100644 --- a/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/EGov_Base_editAndNextStep.py +++ b/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/EGov_Base_editAndNextStep.py @@ -129,7 +129,7 @@ if not next_url_dict.has_key(form_id): message="" context.portal_workflow.doActionFor(context, submit_action) - except ValidationFailed, message: + except ValidationFailed as message: context.pdb() return request['RESPONSE'].redirect( "%s/%s?portal_status_message=%s" % diff --git a/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/Organisation_sendCrendentialsByEMail.py b/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/Organisation_sendCrendentialsByEMail.py index a0e63172c4474a478eb0f78d3d162bc92ac25bdd..005c31cb59c963678e8dfc7bb3ef687184e0684c 100644 --- a/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/Organisation_sendCrendentialsByEMail.py +++ b/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/Organisation_sendCrendentialsByEMail.py @@ -16,12 +16,12 @@ result = portal_catalog(portal_type='Organisation', if len(result) > 1: msg = "Error : There is more than one company with the NINEA code ${code}" msg = translateString(msg, mapping=dict(code=vat_code)) - raise ValidationFailed, msg + raise ValidationFailed(msg) if len(result) == 0: msg = "No organisation with the NINEA code ${code}" msg = translateString(msg, mapping=dict(code=vat_code)) - raise ValidationFailed, msg + raise ValidationFailed(msg) organisation = result[0] diff --git a/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/Person_sendCrendentialsByEMail.py b/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/Person_sendCrendentialsByEMail.py index 0f2e29e891ecd3534c921b05441a7ac9b1e30024..8876e2b8672b6ff3f68277a015abdd4d624c8ae3 100644 --- a/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/Person_sendCrendentialsByEMail.py +++ b/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov/Person_sendCrendentialsByEMail.py @@ -18,14 +18,14 @@ if len(result) > 1: msg = translateString(msg, mapping=dict(title=context.getTitle(), email=context.getDefaultEmailText())) - raise ValidationFailed, msg + raise ValidationFailed(msg) if len(result) == 0: msg = "Error : No person with the title ${title} and the email ${email}" msg = translateString(msg, mapping=dict(title=context.getTitle(), email=context.getDefaultEmailText())) - raise ValidationFailed, msg + raise ValidationFailed(msg) person = result[0] diff --git a/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov_security/ERP5Type_getSecurityCategoryFromAssignmentTree.py b/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov_security/ERP5Type_getSecurityCategoryFromAssignmentTree.py index f99a0ac22641e0dd00892c751682088d105532f6..1cb870db9b71c14a08ef3b815a7e623aea93b1b9 100644 --- a/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov_security/ERP5Type_getSecurityCategoryFromAssignmentTree.py +++ b/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov_security/ERP5Type_getSecurityCategoryFromAssignmentTree.py @@ -21,7 +21,7 @@ person_object_list = [x.getObject() for x in person_module.searchFolder(portal_t if len(person_object_list) != 1: if len(person_object_list) > 1: - raise ConsistencyError, "Error: There is more than one Person with reference '%s'" % user_name + raise ConsistencyError("Error: There is more than one Person with reference '%s'" % user_name) else: # if a person_object was not found in the module, we do nothing more # this happens for example when a manager with no associated person object @@ -48,7 +48,7 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment if root: category_value=category_value.split('/')[0] category_dict[base_category] = category_value 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) # 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 :) @@ -58,7 +58,7 @@ for assignment in person_object.contentValues(filter={'portal_type': 'Assignment cdict = category_dict.copy() cdict[base_category] = '/'.join(grouplist[:-i]) category_list.append(cdict) - except RuntimeError,e: + except RuntimeError as e: log(str(e)) return category_list diff --git a/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov_theme/Workflow_statusModify.py b/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov_theme/Workflow_statusModify.py index 1204e14ef7fb5176a30dcc026451670611572f56..ff5707b7787c00dba8ac66efa720f9a04e07ea4b 100644 --- a/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov_theme/Workflow_statusModify.py +++ b/bt5/erp5_egov/SkinTemplateItem/portal_skins/erp5_egov_theme/Workflow_statusModify.py @@ -15,7 +15,7 @@ try: request.set('editable_mode', 1) form.validate_all_to_request(request) request.set('editable_mode', editable_mode) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) @@ -54,7 +54,7 @@ try: context, doaction_param_list['workflow_action'], **doaction_param_list) -except ValidationFailed, error_message: +except ValidationFailed as error_message: if getattr(error_message, 'msg', None): # use of Message class to store message+mapping+domain message = error_message.msg diff --git a/bt5/erp5_egov/WorkflowTemplateItem/portal_workflow/egov_interaction_workflow/scripts/PDFDocument_validateFormDataBeforeSubmission.py b/bt5/erp5_egov/WorkflowTemplateItem/portal_workflow/egov_interaction_workflow/scripts/PDFDocument_validateFormDataBeforeSubmission.py index f16f3f1ad91a3d9b082c6780c54473d28daefce9..50679a1b1b767b6c2781b719bfa494f477959175 100644 --- a/bt5/erp5_egov/WorkflowTemplateItem/portal_workflow/egov_interaction_workflow/scripts/PDFDocument_validateFormDataBeforeSubmission.py +++ b/bt5/erp5_egov/WorkflowTemplateItem/portal_workflow/egov_interaction_workflow/scripts/PDFDocument_validateFormDataBeforeSubmission.py @@ -7,4 +7,4 @@ N_ = portal.Base_translateString if document.PDFDocument_getRequirementCount() != 0: message = '%s following document (s) are missing to submit the request ' % document.PDFDocument_getRequirementCount() message = N_(message) - raise ValidationFailed, message + raise ValidationFailed(message) diff --git a/bt5/erp5_egov/WorkflowTemplateItem/portal_workflow/egov_interaction_workflow/scripts/checkAccountInexistance.py b/bt5/erp5_egov/WorkflowTemplateItem/portal_workflow/egov_interaction_workflow/scripts/checkAccountInexistance.py index f35f959bb5c37dd91dfc8e90b2f3f9b462fc1f4d..473bee48cfb3e7caa3ea49355305a81c677ec375 100644 --- a/bt5/erp5_egov/WorkflowTemplateItem/portal_workflow/egov_interaction_workflow/scripts/checkAccountInexistance.py +++ b/bt5/erp5_egov/WorkflowTemplateItem/portal_workflow/egov_interaction_workflow/scripts/checkAccountInexistance.py @@ -12,9 +12,9 @@ result = portal_catalog(portal_type='Organisation', vat_code=ninea) if len(result) > 1: msg = "Error : There is more than one company with the NINEA code ${code}" msg = translateString(msg, mapping=dict(code=ninea)) - raise ValidationFailed, msg + raise ValidationFailed(msg) if len(result) == 1 and result[0].getObject().getReference(): msg = "Error : A company with the NINEA code ${code} already exists and have already an account" msg = translateString(msg, mapping=dict(code=ninea)) - raise ValidationFailed, msg + raise ValidationFailed(msg) diff --git a/bt5/erp5_email_reader/DocumentTemplateItem/portal_components/document.erp5.EmailReader.py b/bt5/erp5_email_reader/DocumentTemplateItem/portal_components/document.erp5.EmailReader.py index 9296a006ccaeae6e227c79579616f022090fc8d4..1b964d295c2d9684c8f729f73ef16f5413266715 100644 --- a/bt5/erp5_email_reader/DocumentTemplateItem/portal_components/document.erp5.EmailReader.py +++ b/bt5/erp5_email_reader/DocumentTemplateItem/portal_components/document.erp5.EmailReader.py @@ -332,7 +332,7 @@ class EmailReader(ExternalSource): # This is very sequential and could be improved probably try: message_uid_list = self._getMailServer().getMessageUIDList(message_folder=message_folder) - except ValueError, error_message: # Use a better exception here XXX + except ValueError as error_message: # Use a better exception here XXX message_uid_list = [] # Reduce list size based on asumption of growing sequence of uids latest_uid = self._latest_uid.get(message_folder, 0) diff --git a/bt5/erp5_forge/ExtensionTemplateItem/portal_components/extension.erp5.Glossary.py b/bt5/erp5_forge/ExtensionTemplateItem/portal_components/extension.erp5.Glossary.py index bdcf921103c9732d518a3696aaab8fa5d1ddaad9..93fe7e3d5f22bbc663b02d6c588cab34e601f885 100644 --- a/bt5/erp5_forge/ExtensionTemplateItem/portal_components/extension.erp5.Glossary.py +++ b/bt5/erp5_forge/ExtensionTemplateItem/portal_components/extension.erp5.Glossary.py @@ -153,4 +153,4 @@ def setGuard(self, guard): if isinstance(self, TransitionDefinition): self.guard = guard else: - raise ValueError, "not a TransitionDefinition" + raise ValueError("not a TransitionDefinition") diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/BugLine_send.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/BugLine_send.py index 5e8cb3dfcda81a95a111d59c7a59d59a2282eedb..61173586676900b487f7209cc9609a3991b12688 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/BugLine_send.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/BugLine_send.py @@ -37,7 +37,7 @@ if to_url is None: else: to_url_list.append(email) else: - raise ValueError, 'Recipient %s has no defined email' % recipient + raise ValueError('Recipient %s has no defined email' % recipient) elif same_type(to_url, ''): to_url_list.append(to_url) diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/CategoryTool_generateTranslationFile.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/CategoryTool_generateTranslationFile.py index 36c0072c0de2844bf20e46d065fad9831d14e1ed..47b3f645b544cbaae747ec3e6291ae63af3f957d 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/CategoryTool_generateTranslationFile.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/CategoryTool_generateTranslationFile.py @@ -1,6 +1,7 @@ """Return a po file from a spreadsheet of categories.""" from Products.ERP5Type.Message import translateString from Products.ERP5Type.Document import newTempBase +from zExceptions import Redirect # Initialise some general variables detailed_report_result = [] @@ -13,7 +14,7 @@ request = container.REQUEST response = request.RESPONSE if import_filename=='': - raise ValueError, "You must upload a file" + raise ValueError("You must upload a file") def addReportLine(error, category, message): report_line = newTempBase(context, 'item') @@ -24,9 +25,9 @@ def invalid_category_spreadsheet_handler(message): # action taken when an invalid spreadsheet is provided. # 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: - raise 'Redirect', '%s/view?portal_status_message=%s' % ( + raise Redirect('%s/view?portal_status_message=%s' % ( context.portal_categories.absolute_url(), - message) + message)) category_list_mapping = context.Base_getCategoriesSpreadSheetMapping(import_file, invalid_spreadsheet_error_handler=invalid_category_spreadsheet_handler) diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/diff.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/diff.py index 83e96105c4064552184fdc92572d62bdaebc100d..4199800cb71e3bfc837227f84fa25fb6ef766189 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/diff.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_forge/diff.py @@ -20,7 +20,7 @@ elif kw_len == 2: object_a = getObjectFromArg(kw_value_list[0]) object_b = getObjectFromArg(kw_value_list[1]) else: - raise ValueError, '%s is not a valid number of arguments for diff.' % (kw_len, ) + raise ValueError('%s is not a valid number of arguments for diff.' % (kw_len, )) diff_dict, missing_in_a_dict, missing_in_b_dict = diff_recursive(object_a, object_b) diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_glossary/GlossaryModule_getPOFile.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_glossary/GlossaryModule_getPOFile.py index 8df5e16ffbffc161c780692086c60b973fcfa1ea..c9ecb8e39a396dab6b29859e7b89648e76ac5a49 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_glossary/GlossaryModule_getPOFile.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_glossary/GlossaryModule_getPOFile.py @@ -52,7 +52,7 @@ for i in catalog(portal_type='Glossary Term', business_field_uid=term.getBusinessFieldUid()) if english_term is None: continue - raise ValueError, 'Corresponding English term to "%s" does not exist in glossary.' % term.Title() + raise ValueError('Corresponding English term to "%s" does not exist in glossary.' % term.Title()) translated_title = term.getTitle() translated_description = term.getDescription() @@ -63,7 +63,7 @@ for i in catalog(portal_type='Glossary Term', if translated_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: print formatMessage(english=format(english_title), translation=format(translated_title), @@ -71,7 +71,7 @@ for i in catalog(portal_type='Glossary Term', if translated_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: print formatMessage(english=format(english_description), diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/BusinessTemplate_getModifiableFieldList.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/BusinessTemplate_getModifiableFieldList.py index 78d02f118bc61c8ef26f957a79cb8cdcde9edddb..fd32db4d8040bea48299fec373868c8e38e92475 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/BusinessTemplate_getModifiableFieldList.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/BusinessTemplate_getModifiableFieldList.py @@ -95,7 +95,7 @@ for skin_folder_id in skin_id_list: alternate_field_library_id))): obj = getForm(skin_folder, object_id) if obj is None: - raise KeyError, '%s/%s' % (skin_folder_id, object_id) + raise KeyError('%s/%s' % (skin_folder_id, object_id)) elif obj.meta_type == 'ERP5 Form': modified_object_dict['%s/%s' % (skin_folder_id, object_id)] = \ '4_delete_form' @@ -120,8 +120,8 @@ for skin_folder_id in skin_id_list: # As the form will be deleted, no need to manage its fields pass else: - raise KeyError, 'Unexpected form handling %s for %s' % \ - (modified_object_dict[form_path], form_path) + raise KeyError('Unexpected form handling %s for %s' % \ + (modified_object_dict[form_path], form_path)) elif form_id not in (field_library_id, alternate_field_library_id, 'Base_viewFieldLibrary',): # Check that proxy field are proxified to field library diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/BusinessTemplate_modifyFieldList.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/BusinessTemplate_modifyFieldList.py index cb375f20b463d03f0536af5e328a74f822305c7d..96f34628175a5c32325d5a5218714ab61cdd9d36 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/BusinessTemplate_modifyFieldList.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/BusinessTemplate_modifyFieldList.py @@ -8,7 +8,7 @@ for listbox_line in listbox_line_list: if not choice: continue elif len(choice) > 1: - raise ValueError, 'Unknown choice %s' % choice + raise ValueError('Unknown choice %s' % choice) else: choice = choice[0] if choice.startswith('0_'): @@ -29,6 +29,6 @@ for listbox_line in listbox_line_list: # skin_folder.manage_addProduct['ERP5Form'].addERP5Form(id=form_id, title='') # raise NotImplementedError else: - raise ValueError, 'Unknown choice %s' % choice + raise ValueError('Unknown choice %s' % choice) context.Base_redirect() diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/SkinsTool_getNotAssignedFieldList.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/SkinsTool_getNotAssignedFieldList.py index fc83c8a5ec8b9efecb81a8278dad60e49c1bcb87..a25174a03f7f6067a0f1ebacbfa7338d14ca66f7 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/SkinsTool_getNotAssignedFieldList.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_toolbox/SkinsTool_getNotAssignedFieldList.py @@ -6,7 +6,7 @@ for form_path, form in context.ZopeFind( context.portal_skins, obj_metatypes=['ERP5 Form'], search_sub=1): try: groups = form.get_groups() - except AttributeError, e: + except AttributeError as e: print "%s is broken: %s" % (form_path, e) if 'not_assigned' in groups: print 'Not assigned fields in %s: %s' % (form_path, diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doSvnCheckout.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doSvnCheckout.py index 6a73fe650742bb3a94825cde1b859346a4b0297a..61975a5ea46ba1777e4d96f9caf5fe079398dcf1 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doSvnCheckout.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doSvnCheckout.py @@ -3,10 +3,10 @@ from Products.ERP5VCS.SubversionClient import SubversionSSLTrustError, Subversio vcs_tool = context.getVcsTool() try: entry_dict = vcs_tool.checkout(context, url) -except SubversionSSLTrustError, error: +except SubversionSSLTrustError as error: context.REQUEST.set('portal_status_message', 'SSL Certificate was not recognized') return context.asContext(trust_dict = error.getTrustDict(), caller='info').BusinessTemplate_viewSvnSSLTrust() -except SubversionLoginError, error1 : +except SubversionLoginError as error1 : context.REQUEST.set('portal_status_message', 'Server needs authentication, no cookie found') return context.asContext(caller='info', realm = error1.getRealm(), username = vcs_tool.getPreferredUsername()).BusinessTemplate_viewSvnLogin() return entry_dict diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doVcsCommit.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doVcsCommit.py index b3d8af37e4f5214dcfc75fd2feee56354460eb72..fab70b2a1fdfe769f47ec3c3f262ca2410fc818b 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doVcsCommit.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doVcsCommit.py @@ -19,5 +19,5 @@ if not changelog.strip(): try: return context.getVcsTool().commit(changelog, **kw) -except Exception, error: +except Exception as error: return context.BusinessTemplate_handleException(error, script.id) diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doVcsUpdate.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doVcsUpdate.py index 24598c436c14f0cb066e892183135d4a8e990433..a9fdc24be0543c2904cd6eca05d60f6b521d7184 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doVcsUpdate.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_doVcsUpdate.py @@ -1,6 +1,6 @@ try: new_bt = context.getVcsTool().update(keep) -except Exception, error: +except Exception as error: return context.BusinessTemplate_handleException( error, script.id, form_id=form_id, keep=keep) diff --git a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_handleException.py b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_handleException.py index 9cad8897f45e8dc4106280ac5df710508d950157..97af38cfced68a3b827095fe692532c41b611fa5 100644 --- a/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_handleException.py +++ b/bt5/erp5_forge/SkinTemplateItem/portal_skins/erp5_vcs/BusinessTemplate_handleException.py @@ -3,15 +3,15 @@ from Products.ERP5VCS.SubversionClient import SubversionSSLTrustError, Subversio try: raise exception -except SubversionSSLTrustError, e: +except SubversionSSLTrustError as e: message = 'SSL Certificate was not recognized' kw = dict(trust_dict=e.getTrustDict()) method = 'BusinessTemplate_viewSvnSSLTrust' -except SubversionLoginError, e: +except SubversionLoginError as e: message = 'Server needs authentication, no cookie found' kw = dict(realm=e.getRealm(), username=context.getVcsTool().getPreferredUsername()) method = 'BusinessTemplate_viewSvnLogin' -except GitLoginError, e: +except GitLoginError as e: message = str(e) kw = dict(remote_url=context.getVcsTool().getRemoteUrl()) method = 'BusinessTemplate_viewGitLogin' diff --git a/bt5/erp5_full_text_mroonga_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py b/bt5/erp5_full_text_mroonga_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py index 948b0d91f005564c5175d8c32a6f05ae4d2812fb..cb97ac1ac765593cc602782fb1b36ce6a4a036ca 100644 --- a/bt5/erp5_full_text_mroonga_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py +++ b/bt5/erp5_full_text_mroonga_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py @@ -21,7 +21,7 @@ for group_object in object_list: except Unauthorized: # should happen in tricky testERP5Catalog tests only # Fake activity success: if indexation cannot View document, ignore it. group_object.result = None - except Exception, e: + except Exception as e: group_object.raised() else: for property, value in tmp_dict.iteritems(): diff --git a/bt5/erp5_full_text_myisam_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py b/bt5/erp5_full_text_myisam_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py index 5a4e26354a477f62e69dffdbbaf796351afa08d2..65b0e03fdc1cfb5bfafef2b09ad9a51864d5bf27 100644 --- a/bt5/erp5_full_text_myisam_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py +++ b/bt5/erp5_full_text_myisam_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py @@ -26,7 +26,7 @@ for path in path_list: raise except Unauthorized: # should happen in tricky testERP5Catalog tests only continue - except Exception, e: + except Exception as e: exception = e failed_path_list.append(path) else: @@ -39,7 +39,7 @@ if len(failed_path_list): context.activate(activity='SQLQueue', priority=5).SQLCatalog_deferFullTextIndexActivity(path_list=failed_path_list) else: # 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: return method(**parameter_dict) diff --git a/bt5/erp5_full_text_sphinxse_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py b/bt5/erp5_full_text_sphinxse_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py index 19e97cec7a6477fad8e7ba96b6380755b9f15741..a88025ad2c6f2386973106c4d3c67ca016294516 100644 --- a/bt5/erp5_full_text_sphinxse_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py +++ b/bt5/erp5_full_text_sphinxse_catalog/CatalogMethodTemplateItem/portal_catalog/erp5_mysql_innodb/SQLCatalog_deferFullTextIndexActivity.py @@ -26,7 +26,7 @@ for path in path_list: raise except Unauthorized: # should happen in tricky testERP5Catalog tests only continue - except Exception, e: + except Exception as e: exception = e failed_path_list.append(path) else: @@ -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) else: # 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: method(**parameter_dict) diff --git a/bt5/erp5_graph_editor/SkinTemplateItem/portal_skins/erp5_graph_editor/DCWorkflow_edit.py b/bt5/erp5_graph_editor/SkinTemplateItem/portal_skins/erp5_graph_editor/DCWorkflow_edit.py index cef86b514bdd644c0382fd9401e89b2a894edb3b..1e3023fec1635ffbd2fa9bf51ab19778ede950a5 100644 --- a/bt5/erp5_graph_editor/SkinTemplateItem/portal_skins/erp5_graph_editor/DCWorkflow_edit.py +++ b/bt5/erp5_graph_editor/SkinTemplateItem/portal_skins/erp5_graph_editor/DCWorkflow_edit.py @@ -7,7 +7,7 @@ edit_order = form.edit_order try: # Validate form.validate_all_to_request(request, key_prefix='my_') -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request result = {} result['field_errors'] = {} diff --git a/bt5/erp5_hal_json_style/SkinTemplateItem/portal_skins/erp5_hal_json_style/Workflow_statusModify.py b/bt5/erp5_hal_json_style/SkinTemplateItem/portal_skins/erp5_hal_json_style/Workflow_statusModify.py index cb5fe85e6d206330a3610c6f33a26bc38143e0e0..3e7547ef0a7be98e8772a641e6a1965a83940bf1 100644 --- a/bt5/erp5_hal_json_style/SkinTemplateItem/portal_skins/erp5_hal_json_style/Workflow_statusModify.py +++ b/bt5/erp5_hal_json_style/SkinTemplateItem/portal_skins/erp5_hal_json_style/Workflow_statusModify.py @@ -18,7 +18,7 @@ try: request.set('editable_mode', 1) form.validate_all_to_request(request) request.set('editable_mode', editable_mode) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) @@ -69,7 +69,7 @@ try: context, doaction_param_list['workflow_action'], **doaction_param_list) -except ValidationFailed, error_message: +except ValidationFailed as error_message: if getattr(error_message, 'msg', None): # use of Message class to store message+mapping+domain message = error_message.msg diff --git a/bt5/erp5_invoicing/SkinTemplateItem/portal_skins/erp5_invoicing/InvoiceTransaction_postGeneration.py b/bt5/erp5_invoicing/SkinTemplateItem/portal_skins/erp5_invoicing/InvoiceTransaction_postGeneration.py index 3d993dde6b8fadd1d0cf4ad98fad5aadcc15d602..d0410997447b9db6c07ce0f4f2c98f6ad6a6019b 100644 --- a/bt5/erp5_invoicing/SkinTemplateItem/portal_skins/erp5_invoicing/InvoiceTransaction_postGeneration.py +++ b/bt5/erp5_invoicing/SkinTemplateItem/portal_skins/erp5_invoicing/InvoiceTransaction_postGeneration.py @@ -4,7 +4,7 @@ the new Invoice. from Products.ERP5Type.Message import translateString 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 diff --git a/bt5/erp5_knowledge_pad/SkinTemplateItem/portal_skins/erp5_knowledge_pad/KnowledgeBox_baseEdit.py b/bt5/erp5_knowledge_pad/SkinTemplateItem/portal_skins/erp5_knowledge_pad/KnowledgeBox_baseEdit.py index b0e5d4350ddd8d9709328c050f89428262ec654f..51a8fd7c38aa41072970efe18fe4bf66655a27b6 100644 --- a/bt5/erp5_knowledge_pad/SkinTemplateItem/portal_skins/erp5_knowledge_pad/KnowledgeBox_baseEdit.py +++ b/bt5/erp5_knowledge_pad/SkinTemplateItem/portal_skins/erp5_knowledge_pad/KnowledgeBox_baseEdit.py @@ -16,7 +16,7 @@ form = getattr(box, form_id) try: # Validate form.validate_all_to_request(request, key_prefix=form_fields_main_prefix) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/bt5/erp5_ods_style/SkinTemplateItem/portal_skins/erp5_ods_style/Listbox_getReportTreeStructure.py b/bt5/erp5_ods_style/SkinTemplateItem/portal_skins/erp5_ods_style/Listbox_getReportTreeStructure.py index fd689bb4c0820b1f94ffc02fdf0f7a29da906593..c72510ce8d6594b8a748e87816e3620b5c7a72c1 100644 --- a/bt5/erp5_ods_style/SkinTemplateItem/portal_skins/erp5_ods_style/Listbox_getReportTreeStructure.py +++ b/bt5/erp5_ods_style/SkinTemplateItem/portal_skins/erp5_ods_style/Listbox_getReportTreeStructure.py @@ -25,7 +25,7 @@ def order_line_list(line_list, current_structure, depth=0, index=0, last_dict=No index += 1 index = order_line_list(line_list, new_structure, depth=new_depth, index=index, last_dict=last_dict) elif section_depth > (depth +2): - raise ValueError, "A depth is missing" + raise ValueError("A depth is missing") else: return index if index < len(line_list): diff --git a/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_getReportResultListTitle.py b/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_getReportResultListTitle.py index 325b218aa92809dd575e97fcc2ae4490444407ac..884b4e30d2b9a0944b07dbf6b0e2a219a2575105 100644 --- a/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_getReportResultListTitle.py +++ b/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_getReportResultListTitle.py @@ -10,4 +10,4 @@ if active_process_path is not None: return '%s lines imported sucessfully' % \ 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') diff --git a/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_importFile.py b/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_importFile.py index 76906f8de237eb59e1edf58126dc0294b09db721..cbc3790ef97d1b9f0dde4d1361e6e8b71fd6e6ec 100644 --- a/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_importFile.py +++ b/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_importFile.py @@ -115,7 +115,7 @@ else: # portal_type should be the same for all columns 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 not mapping: @@ -166,7 +166,7 @@ else: active_process=active_process_path) 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(), portal_type, diff --git a/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_importFileLineDefaultScript.py b/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_importFileLineDefaultScript.py index 2fa88fe4d8889fb854c5b3d5adb41f04219f46a9..fcf4cfea216e47831702f4ca4dc59a95951d0270 100644 --- a/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_importFileLineDefaultScript.py +++ b/bt5/erp5_ooo_import/SkinTemplateItem/portal_skins/erp5_ooo_import/Base_importFileLineDefaultScript.py @@ -30,7 +30,7 @@ for allowed_portal_type in container.allowedContentTypes(): break if portal_type_object is None: - raise ValueError, 'Disallowed subobject type: %s' % portal_type + raise ValueError('Disallowed subobject type: %s' % portal_type) else: # Default result success = 1 @@ -57,7 +57,7 @@ else: **imported_line_property_dict) except ConflictError: raise - except Exception, error: + except Exception as error: translated_msg = Message('erp5_ui', 'An error Occurred while creating object: ${error}', mapping=dict(error=Message('erp5_ui', @@ -75,7 +75,7 @@ else: new_object.edit(**category_dict) except ConflictError: raise - except Exception, error: + except Exception as error: #context.log('category: %s' %category) translated_msg = Message( 'erp5_ui', diff --git a/bt5/erp5_open_trade/SkinTemplateItem/portal_skins/erp5_open_trade/OpenSaleOrderLine_getPeriodicityLineValueList.py b/bt5/erp5_open_trade/SkinTemplateItem/portal_skins/erp5_open_trade/OpenSaleOrderLine_getPeriodicityLineValueList.py index 8c89d11d26a03e96f1ccd2c0c1422adcbf17bd7a..d1cf52d36235b25846d6deefe5e2d22d72d2966e 100644 --- a/bt5/erp5_open_trade/SkinTemplateItem/portal_skins/erp5_open_trade/OpenSaleOrderLine_getPeriodicityLineValueList.py +++ b/bt5/erp5_open_trade/SkinTemplateItem/portal_skins/erp5_open_trade/OpenSaleOrderLine_getPeriodicityLineValueList.py @@ -21,4 +21,4 @@ for sale_trade_condition in sale_trade_condition_list: if periodicity_line.getResourceUid()==resource_uid: 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()) diff --git a/bt5/erp5_open_trade/SkinTemplateItem/portal_skins/erp5_open_trade/SaleOrder_copyOpenSaleOrderProperties.py b/bt5/erp5_open_trade/SkinTemplateItem/portal_skins/erp5_open_trade/SaleOrder_copyOpenSaleOrderProperties.py index ecba9dcf30713c956af284661e2af7fde0c870fa..9ff34612ced5c22eadf1c1f184a9fb8a5472b2e5 100644 --- a/bt5/erp5_open_trade/SkinTemplateItem/portal_skins/erp5_open_trade/SaleOrder_copyOpenSaleOrderProperties.py +++ b/bt5/erp5_open_trade/SkinTemplateItem/portal_skins/erp5_open_trade/SaleOrder_copyOpenSaleOrderProperties.py @@ -1,5 +1,5 @@ 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() diff --git a/bt5/erp5_open_trade_periodicity_line/SkinTemplateItem/portal_skins/erp5_open_trade_periodicity_line/PeriodicityLine_calculateScopeTypeStopDate.py b/bt5/erp5_open_trade_periodicity_line/SkinTemplateItem/portal_skins/erp5_open_trade_periodicity_line/PeriodicityLine_calculateScopeTypeStopDate.py index 3fda060b9a398d9b2f0a84b5a85d7067c9e88086..56280aa1e1cf272b4ee7994fb3100e36d0b329f7 100644 --- a/bt5/erp5_open_trade_periodicity_line/SkinTemplateItem/portal_skins/erp5_open_trade_periodicity_line/PeriodicityLine_calculateScopeTypeStopDate.py +++ b/bt5/erp5_open_trade_periodicity_line/SkinTemplateItem/portal_skins/erp5_open_trade_periodicity_line/PeriodicityLine_calculateScopeTypeStopDate.py @@ -28,4 +28,4 @@ elif scope_type=='until_the_end_of_month': return DateTime(year, month, day) return getEndOfMonth(start_date) -raise ValueError, 'Unknown scope type: %s' % scope_type +raise ValueError('Unknown scope type: %s' % scope_type) diff --git a/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetModelLine_asCellRange.py b/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetModelLine_asCellRange.py index f5311585be0bcae557999c0601ce96387f520b58..c0ad84d0813ef8c9524b0eeb8f244fa073bf9cd9 100644 --- a/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetModelLine_asCellRange.py +++ b/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetModelLine_asCellRange.py @@ -45,8 +45,8 @@ if matrixbox : translateString('${contribution_share_title} (Amount or Percent)', mapping=dict(contribution_share_title=category_item[0])))) else: - raise ValueError, "PaySheetModelLine_asCellRange: the two categories "\ - "must could be only contribution_share and salary_range" + raise ValueError("PaySheetModelLine_asCellRange: the two categories "\ + "must could be only contribution_share and salary_range") cell_range.append(category_cell_range) cell_range = filter(lambda x: x != [], cell_range) diff --git a/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetModel_asCellRange.py b/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetModel_asCellRange.py index 9964b6b32a56fbda2c9de290bf73f47ef02d4dc1..b2cc0a829ac7bcf44f43ef4a4a3525a4476a95ab 100644 --- a/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetModel_asCellRange.py +++ b/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetModel_asCellRange.py @@ -9,7 +9,7 @@ category_list = [] for category in context.getVariationSettingsCategoryList(): category_name = category.replace('salary_range/','',1) if context.portal_categories.getCategoryValue(category) is None: - raise ValueError, 'no category %s' % category + raise ValueError('no category %s' % category) else: if matrixbox: category_list.extend(context.portal_categories.getCategoryValue(category).getCategoryChildLogicalPathItemList(checked_permission='View', is_right_display=1, base=1)[1:]) diff --git a/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getODTDataDict.py b/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getODTDataDict.py index f2c105c86f048d2a0306abc1230391b4867909d2..72a28c06c724a78db3d4970a88b80d77418ad42b 100644 --- a/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getODTDataDict.py +++ b/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getODTDataDict.py @@ -105,9 +105,9 @@ def getSocialOrganisationValue(): business_path_list = business_process.getTradeModelPathValueList(trade_phase=\ 'payroll/invoicing/social_security', context=context) 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. '\ - '%s have same trade_phase' % repr(business_path_list) + '%s have same trade_phase' % repr(business_path_list)) if len(business_path_list) == 1: business_path = business_path_list[0] return business_path.getSourceSectionValue() diff --git a/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getYearToDateBaseContributionTotalPrice.py b/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getYearToDateBaseContributionTotalPrice.py index 7a75a335317bf4f989f27ca08f7bfba1515a25e6..edbc9c8b0bf440d61af7fef9b69eb16a701a22dd 100644 --- a/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getYearToDateBaseContributionTotalPrice.py +++ b/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getYearToDateBaseContributionTotalPrice.py @@ -26,7 +26,7 @@ base_contribution_uid_list = [] for category in base_contribution_list: category_value = base_amount.restrictedTraverse(category) 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()) params = { diff --git a/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getYearToDateWorkTimeSalary.py b/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getYearToDateWorkTimeSalary.py index dd60d25c03a275ecefc97cf9368d36f3584ce0e6..abd30c0e68a9d2aed0766cdb793be3036455b802 100644 --- a/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getYearToDateWorkTimeSalary.py +++ b/bt5/erp5_payroll/SkinTemplateItem/portal_skins/erp5_payroll/PaySheetTransaction_getYearToDateWorkTimeSalary.py @@ -22,8 +22,8 @@ for paysheet in paysheet_list: if annotation_line is None: annotation_line = getattr(paysheet, 'work_time_annotation_line', None) if annotation_line is None: - raise ValueError, "Paysheet %s has no Annotation Line with reference work_time_annotation_line"\ - % paysheet.getRelativeUrl() + raise ValueError("Paysheet %s has no Annotation Line with reference work_time_annotation_line"\ + % paysheet.getRelativeUrl()) nb_heures = annotation_line.getQuantity() yearly_work_time += nb_heures diff --git a/bt5/erp5_payroll_l10n_fr/TestTemplateItem/portal_components/test.erp5.testDSNSocialDeclarationReport.py b/bt5/erp5_payroll_l10n_fr/TestTemplateItem/portal_components/test.erp5.testDSNSocialDeclarationReport.py index ebbf8b066799842a767687f2e816b45036fb4836..c8baaabd499d84eae66a2b9a6d718bdee4deb790 100644 --- a/bt5/erp5_payroll_l10n_fr/TestTemplateItem/portal_components/test.erp5.testDSNSocialDeclarationReport.py +++ b/bt5/erp5_payroll_l10n_fr/TestTemplateItem/portal_components/test.erp5.testDSNSocialDeclarationReport.py @@ -52,7 +52,7 @@ class TestDSNSocialDeclarationReport(ERP5TypeTestCase): """ self.portal = self.getPortalObject() self.dsn_module = self.portal.getDefaultModuleValue("DSN Monthly Report") - self.pinDateTime(DateTime(2015, 12, 01)) + self.pinDateTime(DateTime(2015, 12, 1)) # Create the id_group 'dsn_event_counter' self.portal.portal_ids.generateNewId(id_group='dsn_event_counter', id_generator='continuous_integer_increasing') diff --git a/bt5/erp5_payzen_secure_payment/DocumentTemplateItem/portal_components/document.erp5.PayzenService.py b/bt5/erp5_payzen_secure_payment/DocumentTemplateItem/portal_components/document.erp5.PayzenService.py index 09ca4356a513cbfd3f4ac2194c1bc4c96dbda9a5..6876652a9d54c339db371f66899eed51c0868bb3 100644 --- a/bt5/erp5_payzen_secure_payment/DocumentTemplateItem/portal_components/document.erp5.PayzenService.py +++ b/bt5/erp5_payzen_secure_payment/DocumentTemplateItem/portal_components/document.erp5.PayzenService.py @@ -341,7 +341,7 @@ class PayzenService(XMLObject, PayzenSOAP): # backward compatibility: message_list.append(err[3]) if message_list: - raise ValidationFailed, message_list + raise ValidationFailed(message_list) temp_document = newTempDocument(self, 'id') temp_document.edit( diff --git a/bt5/erp5_pdm_ui_test/SkinTemplateItem/portal_skins/erp5_pdm_ui_test/PdmZuite_createDelivery.py b/bt5/erp5_pdm_ui_test/SkinTemplateItem/portal_skins/erp5_pdm_ui_test/PdmZuite_createDelivery.py index 2c79955dc6d90973306d7b6a186efcd1e0beaf09..4c4ff015c4d70095c73b23e3bdefc8ba47dfc967 100644 --- a/bt5/erp5_pdm_ui_test/SkinTemplateItem/portal_skins/erp5_pdm_ui_test/PdmZuite_createDelivery.py +++ b/bt5/erp5_pdm_ui_test/SkinTemplateItem/portal_skins/erp5_pdm_ui_test/PdmZuite_createDelivery.py @@ -78,7 +78,7 @@ else: break if delivery.getSimulationState() != state: - raise ImplementationError, 'Delivery state is %s and not %s' % (delivery.getSimulationState(), state) + raise ImplementationError('Delivery state is %s and not %s' % (delivery.getSimulationState(), state)) return "Delivery Created." diff --git a/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getMonthlyReportSectionList.py b/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getMonthlyReportSectionList.py index 3bcb817df77aa45a68eb683f4d1be2315a627ca7..104f1fc1de8d415f6b611a09c3e3bfb1117bb25f 100644 --- a/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getMonthlyReportSectionList.py +++ b/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getMonthlyReportSectionList.py @@ -98,9 +98,9 @@ for task_line in result_list: source_uid = task_line.node_uid if source_uid is None: # 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}", - mapping = {'task_relative_url': task_line.getRelativeUrl()}) + mapping = {'task_relative_url': task_line.getRelativeUrl()})) source_dict = source_uid_dict.get(source_uid, None) if source_dict is None: source_value = task_line.getSourceValue() diff --git a/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getPlanningBoxReportList.py b/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getPlanningBoxReportList.py index 5f4177a0166f0f33f362910970b672b1aaa6f959..d64b22329937396075010b6054e42c2185208ed4 100644 --- a/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getPlanningBoxReportList.py +++ b/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getPlanningBoxReportList.py @@ -19,7 +19,7 @@ if selection is not None: elif selection.report_path == 'parent': return context.searchFolder(**kw) else: - raise NotImplementedError, "Unknow domain %s" % selection.report_path + raise NotImplementedError("Unknow domain %s" % selection.report_path) return context.portal_catalog(**kw) diff --git a/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getSummaryList.py b/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getSummaryList.py index 73947e9dd748bb634ea9afb20beb7d6706501033..5526fea5ba715678392df0ab90a7f4fdd01ec9ab 100644 --- a/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getSummaryList.py +++ b/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/Project_getSummaryList.py @@ -33,7 +33,7 @@ for task in task_list: update_kw['real_start_date'] = task_line.getStartDate() update_kw['real_stop_date'] = task_line.getStopDate() 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': update_kw['initial_quantity'] = task_line.getQuantity() update_kw['initial_start_date'] = task_line.getStartDate() diff --git a/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/TaskReportModule_exportTaskReportListAsiCalendar.py b/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/TaskReportModule_exportTaskReportListAsiCalendar.py index 4453ae16f19009829951d94a4e5a55a7d33c6eef..f4d25bb49ab667beb135d9539a4e29c55dd83533 100644 --- a/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/TaskReportModule_exportTaskReportListAsiCalendar.py +++ b/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/TaskReportModule_exportTaskReportListAsiCalendar.py @@ -1,10 +1,11 @@ """Export the current selection in task report module in iCalendar format. """ +from zExceptions import Unauthorized # XXX bypass CookieCrumbler if context.REQUEST.AUTHENTICATED_USER.getUserName() == 'Anonymous User': if context.REQUEST.get('disable_cookie_login__', 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") def formatDate(date): diff --git a/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/TaskReport_copyOrderPropertiesAndNotifyAssignee.py b/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/TaskReport_copyOrderPropertiesAndNotifyAssignee.py index d4d0fa4d1d85dc9a3da34381e60be9544b4398dc..2e9bf089235e140d5c5c9e6409ba0478108017a6 100644 --- a/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/TaskReport_copyOrderPropertiesAndNotifyAssignee.py +++ b/bt5/erp5_project/SkinTemplateItem/portal_skins/erp5_project/TaskReport_copyOrderPropertiesAndNotifyAssignee.py @@ -1,5 +1,5 @@ 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: from zExceptions import Unauthorized diff --git a/bt5/erp5_promise/SkinTemplateItem/portal_skins/erp5_promise/Alarm_checkPromiseBt5.py b/bt5/erp5_promise/SkinTemplateItem/portal_skins/erp5_promise/Alarm_checkPromiseBt5.py index 8aefabfd2a3c06141973caa214bac15fc0f2255c..0ebfb398d43343035c04bc667d97ec01dfe25c11 100644 --- a/bt5/erp5_promise/SkinTemplateItem/portal_skins/erp5_promise/Alarm_checkPromiseBt5.py +++ b/bt5/erp5_promise/SkinTemplateItem/portal_skins/erp5_promise/Alarm_checkPromiseBt5.py @@ -18,7 +18,7 @@ try: message_list = template_tool.upgradeSite(bt5_list, dry_run=True, update_catalog=CATALOG_UPDATABLE) severity = len(message_list) -except BusinessTemplateUnknownError, error: +except BusinessTemplateUnknownError as error: severity = -1 detail = str(error) diff --git a/bt5/erp5_real_time_inventory_accounting_test/TestTemplateItem/portal_components/test.erp5.testRealTimeInventoryAccounting.py b/bt5/erp5_real_time_inventory_accounting_test/TestTemplateItem/portal_components/test.erp5.testRealTimeInventoryAccounting.py index 07811978de5761a3daad0230f50530d49fb841af..134cae26c7358fe6c4075c8e36dfd15db01a6e08 100644 --- a/bt5/erp5_real_time_inventory_accounting_test/TestTemplateItem/portal_components/test.erp5.testRealTimeInventoryAccounting.py +++ b/bt5/erp5_real_time_inventory_accounting_test/TestTemplateItem/portal_components/test.erp5.testRealTimeInventoryAccounting.py @@ -54,7 +54,7 @@ class TestRealTimeInventoryAccountingMixin: self.portal.portal_workflow.doActionFor(document, workflow_method_id) else: getattr(document, workflow_method_id)() - except ValidationFailed, error: + except ValidationFailed as error: self.fail("Transition '%s' on %r should have succeeded (%s)" % \ (workflow_method_id, document, sorted([m.message for m in error.msg]))) diff --git a/bt5/erp5_registry_ohada/DocumentTemplateItem/PsjPerson.py b/bt5/erp5_registry_ohada/DocumentTemplateItem/PsjPerson.py index 581550272fb7302589ebcd7382ac553bc9261f90..21439b7e8e546dda30e44c8729a532e2eb887b2b 100644 --- a/bt5/erp5_registry_ohada/DocumentTemplateItem/PsjPerson.py +++ b/bt5/erp5_registry_ohada/DocumentTemplateItem/PsjPerson.py @@ -165,7 +165,7 @@ class PsjPerson(XMLObject): user_list = acl_users.searchUsers(id=value, exact_match=True) if len(user_list) > 0: - raise RuntimeError, 'user id %s already exist' % (value,) + raise RuntimeError('user id %s already exist' % (value,)) break self._setReference(value) self.reindexObject() diff --git a/bt5/erp5_registry_ohada/ExtensionTemplateItem/CupsUtils.py b/bt5/erp5_registry_ohada/ExtensionTemplateItem/CupsUtils.py index 1f888f8cb1c5bbda94fbaf45a6d6ebcd8460a193..2ddec5c7fc236149ad8980ba5837c3a457c8ae36 100644 --- a/bt5/erp5_registry_ohada/ExtensionTemplateItem/CupsUtils.py +++ b/bt5/erp5_registry_ohada/ExtensionTemplateItem/CupsUtils.py @@ -42,7 +42,7 @@ def printFile(printer_name, file_path_to_print, use_ps_file=True, nb_copy=1): file_path_to_print = convertPdfIntoPs(file_path_to_print) if not os.path.exists('/usr/bin/lp'): - raise ValueError, "lp command is not installed" + raise ValueError("lp command is not installed") cmd = '/usr/bin/lp -d %s -n %s %s' % (printer_name, nb_copy, file_path_to_print) result = commands.getstatusoutput(cmd) @@ -71,7 +71,7 @@ def convertPdfIntoPs(file_path_to_print): if not os.path.exists('/usr/bin/pdf2ps'): - raise ValueError, "pdf2ps command is not installed" + raise ValueError("pdf2ps command is not installed") cmd = '/usr/bin/pdf2ps %s %s'%(file_path_to_print, ps_file_name) result = commands.getstatusoutput(cmd) if result[0] != 0: @@ -88,7 +88,7 @@ def getPrinterList(self): return the list of installed printers ''' if not os.path.exists('/usr/bin/lpstat'): - raise ValueError, "lpstat command is not installed" + raise ValueError("lpstat command is not installed") cmd = '/usr/bin/lpstat -a' result = commands.getstatusoutput(cmd) if result[0] != 0: diff --git a/bt5/erp5_registry_ohada/ExtensionTemplateItem/PdftkUtils.py b/bt5/erp5_registry_ohada/ExtensionTemplateItem/PdftkUtils.py index 1cd0bdc557831ef07b147d6e24c2c33c02da56a4..abb8887ee89d0dd7624a64d14955169bdebf0eb1 100644 --- a/bt5/erp5_registry_ohada/ExtensionTemplateItem/PdftkUtils.py +++ b/bt5/erp5_registry_ohada/ExtensionTemplateItem/PdftkUtils.py @@ -65,8 +65,8 @@ def addBackgroundOnPdfFile(orginal_pdf, background_pdf): orginal_pdf_file.close() background_pdf_file.close() - raise ValueError, 'Error: pdftk command failed with the following'\ - 'error message : \n%s' % result[1] + raise ValueError('Error: pdftk command failed with the following'\ + 'error message : \n%s' % result[1]) finally: background_pdf_file.close() @@ -107,8 +107,8 @@ def mergePDF(pdf_document_list): for tmp_file in tmp_pdf_list: tmp_file.close() - raise ValueError, 'Error: pdftk command failed with the following'\ - 'error message : \n%s' % result[1] + raise ValueError('Error: pdftk command failed with the following'\ + 'error message : \n%s' % result[1]) else: # going to the begining of the input file diff --git a/bt5/erp5_registry_ohada/SkinTemplateItem/portal_skins/erp5_registry_ohada/Form_getDestinationFormRelatedValueList.py b/bt5/erp5_registry_ohada/SkinTemplateItem/portal_skins/erp5_registry_ohada/Form_getDestinationFormRelatedValueList.py index 1abf90d081422d72c56bfb03543ca900ae0ba328..7a769be9187bb867d5af3220fd55bfef1371bf34 100644 --- a/bt5/erp5_registry_ohada/SkinTemplateItem/portal_skins/erp5_registry_ohada/Form_getDestinationFormRelatedValueList.py +++ b/bt5/erp5_registry_ohada/SkinTemplateItem/portal_skins/erp5_registry_ohada/Form_getDestinationFormRelatedValueList.py @@ -11,7 +11,7 @@ for assignment in assignment_list: rccm = current_object.getCorporateRegistrationCode() pers_result = context.ERP5RegistryOhada_getRelatedPersonList() if len(pers_result) < 1: - raise ValidationFailed, 'There is no Person corresponding to the corporate registration code %s' % rccm + raise ValidationFailed('There is no Person corresponding to the corporate registration code %s' % rccm) person = pers_result[0].getObject() #legal_form = person.getSocialForm() if assignment.getFunction()=='entreprise/associe' : diff --git a/bt5/erp5_registry_ohada/SkinTemplateItem/portal_skins/erp5_registry_ohada/Person_updateUserSecurityGroup.py b/bt5/erp5_registry_ohada/SkinTemplateItem/portal_skins/erp5_registry_ohada/Person_updateUserSecurityGroup.py index e064bcb900b1715511d9cccefc9e3cddd40b5e93..4895c223905ca821a966ab3c76d8202dc8b99dae 100644 --- a/bt5/erp5_registry_ohada/SkinTemplateItem/portal_skins/erp5_registry_ohada/Person_updateUserSecurityGroup.py +++ b/bt5/erp5_registry_ohada/SkinTemplateItem/portal_skins/erp5_registry_ohada/Person_updateUserSecurityGroup.py @@ -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. # 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(): - raise RuntimeError, "Error: Zope user '%s' doesn't exist in the acl_users folder" % (user_name) + raise RuntimeError("Error: Zope user '%s' doesn't exist in the acl_users folder" % (user_name)) category_list = [] security_group_list = [] diff --git a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/egov_form_validation_workflow/scripts/confirmChoiceSet.py b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/egov_form_validation_workflow/scripts/confirmChoiceSet.py index 1e2c7f9d3006bc8c9dc4619e14cbd9218e8bc5fb..7593bf7c120087f18cf6a06fd9651e3304b8afd4 100644 --- a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/egov_form_validation_workflow/scripts/confirmChoiceSet.py +++ b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/egov_form_validation_workflow/scripts/confirmChoiceSet.py @@ -2,4 +2,4 @@ from Products.DCWorkflow.DCWorkflow import ValidationFailed request_eform = state_change['object'] if not (request_eform.getMoralPerson() or request_eform.getBranch() or request_eform.getSecondCompany()): - raise ValidationFailed, 'Role for the organisation has not been defined, you cannot validate it' + raise ValidationFailed('Role for the organisation has not been defined, you cannot validate it') diff --git a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/egov_form_validation_workflow/scripts/verifyOrganisationExists.py b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/egov_form_validation_workflow/scripts/verifyOrganisationExists.py index 80540c481a90535568cd3876eb1b52eb15a3e34d..c9bcaeeda319ba4f36f88f512dee7cc7dde6e553 100644 --- a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/egov_form_validation_workflow/scripts/verifyOrganisationExists.py +++ b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/egov_form_validation_workflow/scripts/verifyOrganisationExists.py @@ -13,4 +13,4 @@ if request_eform.getPortalType() == 'P2': or request_eform.getCompanyCorporateRegistrationCode(), ignore_empty_string = 0) if not len(organisation_list): - raise ValidationFailed, 'Organisation was not found for this person' + raise ValidationFailed('Organisation was not found for this person') diff --git a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_assignment_workflow/scripts/Assignment_checkActiveAssignmentConsistency.py b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_assignment_workflow/scripts/Assignment_checkActiveAssignmentConsistency.py index 7e484debc832cc798fd3c5fde7dd897c970d8c05..658d20b6bfdeaf7e6a31cca9cdd285f591f25737 100644 --- a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_assignment_workflow/scripts/Assignment_checkActiveAssignmentConsistency.py +++ b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_assignment_workflow/scripts/Assignment_checkActiveAssignmentConsistency.py @@ -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. 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.") diff --git a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/createPersonFromP0.py b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/createPersonFromP0.py index 3d0b9b75420b3d3e19fde2a0c807ebedef936cca..32aa880a9d3d81d0b0d3d441bd897b41fc51f6d0 100644 --- a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/createPersonFromP0.py +++ b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/createPersonFromP0.py @@ -24,11 +24,11 @@ else: organisation_list = portal.organisation_module.searchFolder(\ corporate_registration_code=rccm) if len(organisation_list) >1 : - raise ValidationFailed, "Error : There is more than one organisation with the "\ - " rccm number '%s'" % rccm + raise ValidationFailed("Error : There is more than one organisation with the "\ + " rccm number '%s'" % rccm) elif len(organisation_list) == 0: - raise ValidationFailed, "Error : There is no organisation with the "\ - " rccm number '%s'" % rccm + raise ValidationFailed("Error : There is no organisation with the "\ + " rccm number '%s'" % rccm) organisation = organisation_list[0].getObject() if request_eform.getBeginning(): @@ -108,15 +108,15 @@ if request_eform.getBeginning() or request_eform.getOpening(): else: # person exists if len(person_list) >1 : - raise ValidationFailed, "Error : There is more than one person with the "\ + raise ValidationFailed("Error : There is more than one person with the "\ " title '%s', birth date '%s' and birthplace '%s'" % (request_eform.getTitle(), request_eform.getStartDate(), - request_eform.getDefaultBirthplaceAddressCity()) + request_eform.getDefaultBirthplaceAddressCity())) elif len(person_list) == 0: - raise ValidationFailed, "Error : There is nobody with the "\ + raise ValidationFailed("Error : There is nobody with the "\ " title '%s', birth date '%s' and birthplace '%s'" % (request_eform.getTitle(), request_eform.getStartDate(), - request_eform.getDefaultBirthplaceAddressCity()) + request_eform.getDefaultBirthplaceAddressCity())) else: person = person_list[0] diff --git a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/modifyPhysicalPersonFromP2.py b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/modifyPhysicalPersonFromP2.py index 3ee7ef008eb6f9a720e06904a9df65e87437ee99..43aa252197c71805da5ac26399ae8a0733823687 100644 --- a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/modifyPhysicalPersonFromP2.py +++ b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/modifyPhysicalPersonFromP2.py @@ -54,17 +54,17 @@ person_list=[person.getObject() for person in \ context.portal_catalog(portal_type='Person',query=query)] if len(person_list) >1 : - raise ValidationFailed, "Error : There is more than one person with the "\ + raise ValidationFailed("Error : There is more than one person with the "\ " title '%s', birth date '%s' and birthplace '%s'" % ( request_eform.getTitle(), request_eform.getOwnerBirthday(), - request_eform.getOwnerBirthplace()) + request_eform.getOwnerBirthplace())) elif len(person_list) == 0: - raise ValidationFailed, "Error : There is nobody with the "\ + raise ValidationFailed("Error : There is nobody with the "\ " title '%s', birth date '%s' and birthplace '%s'" % ( request_eform.getTitle(), request_eform.getOwnerBirthday(), - request_eform.getOwnerBirthplace()) + request_eform.getOwnerBirthplace())) else: # Modify person based on properties filled in P2 diff --git a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/printPDFForm.py b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/printPDFForm.py index afe238f3e71afcbcb7e8943ac6afa8b3fe556157..3dda39e3b7c8e117dab91f50f6b1ecaad019326a 100644 --- a/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/printPDFForm.py +++ b/bt5/erp5_registry_ohada/WorkflowTemplateItem/portal_workflow/ohada_form_validation_interaction_workflow/scripts/printPDFForm.py @@ -9,7 +9,7 @@ form_pdf_portal_type = request_eform.getPortalType() pdf_view_name = '%s_view%sAsPdf' % (form_pdf_portal_type, form_pdf_portal_type) form_view_pdf = getattr(request_eform, pdf_view_name, None) if form_view_pdf is None: - raise ValidationFailed, 'PDF view %s not found' % pdf_view_name + raise ValidationFailed('PDF view %s not found' % pdf_view_name) signed_pdf_name = context.addBackgroundOnPdfFile(form_view_pdf.generatePDF(), getattr(context,'signature.pdf')) @@ -27,7 +27,7 @@ for form_bis in form_bis_list: view_name = '%s_view%sAsPdf' % (form_portal_type, form_portal_type) form_pdf_view = getattr(form_bis, view_name, None) if form_pdf_view is None: - raise ValidationFailed, 'PDF view %s not found' % form_pdf_view + raise ValidationFailed('PDF view %s not found' % form_pdf_view) form_bis_signed_pdf_name = context.addBackgroundOnPdfFile(form_pdf_view.generatePDF(), getattr(context,'signature.pdf')) context.printFile(printer_name = printer_name, diff --git a/bt5/erp5_simulation/SkinTemplateItem/portal_skins/erp5_simulation/Base_editConfiguration.py b/bt5/erp5_simulation/SkinTemplateItem/portal_skins/erp5_simulation/Base_editConfiguration.py index ffac37dbb1b9f86d924f72420bef21f84d7a1d12..63c186f624e24979f03221221f354cab49aa6cbd 100644 --- a/bt5/erp5_simulation/SkinTemplateItem/portal_skins/erp5_simulation/Base_editConfiguration.py +++ b/bt5/erp5_simulation/SkinTemplateItem/portal_skins/erp5_simulation/Base_editConfiguration.py @@ -33,7 +33,7 @@ try: # Update basic attributes context.updateConfiguration(**kw) context.reindexObject() -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/bt5/erp5_sql_browser/SkinTemplateItem/portal_skins/erp5_sql_browser/ZMySQLDAConnection_getQueryResultAsJSON.py b/bt5/erp5_sql_browser/SkinTemplateItem/portal_skins/erp5_sql_browser/ZMySQLDAConnection_getQueryResultAsJSON.py index 760cbc1ccc339684f1d78dc188b78fb145a1da39..a6d0b43b3744b2187f73a40664f7b4c51c1abc16 100644 --- a/bt5/erp5_sql_browser/SkinTemplateItem/portal_skins/erp5_sql_browser/ZMySQLDAConnection_getQueryResultAsJSON.py +++ b/bt5/erp5_sql_browser/SkinTemplateItem/portal_skins/erp5_sql_browser/ZMySQLDAConnection_getQueryResultAsJSON.py @@ -10,7 +10,7 @@ try: results = context.manage_test(query) data = [ results.names() ] data.extend(results.tuples()) -except Exception, e: +except Exception as e: response.setStatus(500) try: response.write(str(e[1])) diff --git a/bt5/erp5_test_result/DocumentTemplateItem/portal_components/document.erp5.ERP5ScalabilityDistributor.py b/bt5/erp5_test_result/DocumentTemplateItem/portal_components/document.erp5.ERP5ScalabilityDistributor.py index bd769188429ae212bf6c0afd847cf8161e5195c7..19f92fdf85912edc831f3415730f0e1960f7ea8c 100644 --- a/bt5/erp5_test_result/DocumentTemplateItem/portal_components/document.erp5.ERP5ScalabilityDistributor.py +++ b/bt5/erp5_test_result/DocumentTemplateItem/portal_components/document.erp5.ERP5ScalabilityDistributor.py @@ -129,7 +129,7 @@ class ERP5ScalabilityDistributor(ERP5ProjectUnitTestDistributor): if test_node.getValidationState() != 'validated': try: test_node.validate() - except Exception, e: + except Exception as e: LOG('Test Node Validate',ERROR,'%s' %e) return test_node return None diff --git a/bt5/erp5_test_result/ExtensionTemplateItem/portal_components/extension.erp5.TestResults.py b/bt5/erp5_test_result/ExtensionTemplateItem/portal_components/extension.erp5.TestResults.py index 194c7cb32d689a0a69c27dc34ffe7fec7c64f05a..c572892a18bd0ae825096e2646074b856bfe3764 100644 --- a/bt5/erp5_test_result/ExtensionTemplateItem/portal_components/extension.erp5.TestResults.py +++ b/bt5/erp5_test_result/ExtensionTemplateItem/portal_components/extension.erp5.TestResults.py @@ -47,7 +47,7 @@ def parseTestSuiteResults(file_handler): # when called with a string argument, zipfile.ZipFile will open a local file. # we don't want this to happen if isinstance(file_handler, basestring): - raise Unauthorized, file_handler + raise Unauthorized(file_handler) zf = zipfile.ZipFile(file_handler) result = {} diff --git a/bt5/erp5_tiosafe_core/DocumentTemplateItem/portal_components/document.erp5.WebServiceRequest.py b/bt5/erp5_tiosafe_core/DocumentTemplateItem/portal_components/document.erp5.WebServiceRequest.py index bcb0b6645ff2cbbe42113e7be849406425fd0ef8..cc0083803b51a0411e2256f819835783ccabbd86 100644 --- a/bt5/erp5_tiosafe_core/DocumentTemplateItem/portal_components/document.erp5.WebServiceRequest.py +++ b/bt5/erp5_tiosafe_core/DocumentTemplateItem/portal_components/document.erp5.WebServiceRequest.py @@ -134,7 +134,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate): last_request_error="No connection available, connector is %s" %(self.getSourceValue(),)) return [] else: - raise ValueError, "No connection available" + raise ValueError("No connection available") # Add specific parameters defined on integration site site = self.getIntegrationSite() @@ -184,7 +184,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate): # Call the method try: url, xml = callRequest(self, method_name, *args, **kw) - except ConnectionError, msg: + except ConnectionError as msg: if test_mode: error = msg url = connection.url @@ -236,7 +236,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate): if test_mode: self._edit(last_request_error="Bad XML returned by request, impossible to parse it") 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) @@ -269,17 +269,17 @@ class WebServiceRequest(XMLObject, ZopePageTemplate): try: long(item) except ValueError: - raise KeyError, "Item %s does not exists call by Web Service Request %s : not a long" % (item, - self.getTitle(),) + raise KeyError("Item %s does not exists call by Web Service Request %s : not a long" % (item, + self.getTitle(),)) kw = {self.getIDParameterName() : str(item), } object_list = self(**kw) if len(object_list) == 1: return object_list[0] 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(), kw, - len(object_list)) + len(object_list))) def parse_dict(self, parser_dict, dict_list): """ Render the dict list mapped by the parser dict. """ diff --git a/bt5/erp5_tiosafe_core/DocumentTemplateItem/portal_components/document.erp5.WebServiceRequestGroup.py b/bt5/erp5_tiosafe_core/DocumentTemplateItem/portal_components/document.erp5.WebServiceRequestGroup.py index e94a7dc7cbafc39bc72844d4ac764f8cecb209c9..5a3b52ea7b0f85459682236d64f06591d405effa 100644 --- a/bt5/erp5_tiosafe_core/DocumentTemplateItem/portal_components/document.erp5.WebServiceRequestGroup.py +++ b/bt5/erp5_tiosafe_core/DocumentTemplateItem/portal_components/document.erp5.WebServiceRequestGroup.py @@ -69,6 +69,6 @@ class WebServiceRequestGroup(XMLObject): # after browsing all web service requests check that item exists and only # one time 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] diff --git a/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeBaseConduit.py b/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeBaseConduit.py index 57e7e04bf87b1a806a66b867e3ac73a8abf16d07..a9d8f18752ad8dca54e9f5d09049c50b44c42b64 100644 --- a/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeBaseConduit.py +++ b/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeBaseConduit.py @@ -125,11 +125,11 @@ class TioSafeBaseConduit(ERP5Conduit): if getattr(self, 'integration_site', None) is None: related_object_list = [x.getObject() for x in sync_object.Base_getRelatedObjectList()] 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() if integration_site.getPortalType() != "Integration Site": - raise ValueError, "Did not get an Integration Site object instead %s : %s" %(integration_site.getPortalType(), - integration_site.getPath()) + raise ValueError("Did not get an Integration Site object instead %s : %s" %(integration_site.getPortalType(), + integration_site.getPath())) self.integration_site = integration_site return self.integration_site @@ -142,14 +142,14 @@ class TioSafeBaseConduit(ERP5Conduit): module_id = "%s_module" %(object_type.lower()) module = getattr(site, module_id, 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": return module.getSourceSectionValue() elif synchronization_type == "subscription": return module.getDestinationSectionValue() 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, simulate=False, reset=False, xpath_expression=None, **kw): diff --git a/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeBrain.py b/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeBrain.py index 5a391ef134a36840db66f561adcf607a541dd14b..b1ab65b0f0d66e7920a92db102e10d84239f4357 100644 --- a/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeBrain.py +++ b/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeBrain.py @@ -70,7 +70,7 @@ class TioSafeBrain(Explicit): error_type, error_value, error_tb = sys.exc_info() LOG("TioSafeBrain.asXML", ERROR, "%s - %s" %(error_type, error_value), error=sys.exc_info()) if debug: - raise ValueError, "%s - %s" %(error_type, error_value) + raise ValueError("%s - %s" %(error_type, error_value)) else: raise @@ -116,7 +116,7 @@ class TioSafeBrain(Explicit): module_list.append(module) 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 = [] for module in module_list: @@ -139,12 +139,12 @@ class TioSafeBrain(Explicit): # 2. sync_type != tiosafe and destination_portal_type != Integration Module sync_object_list.append(module_destination.getPath()) 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_source.getSource(), module.getDestinationSection(), module_destination.getSource(), - ) + )) return sync_object_list # Cache sync object list @@ -185,7 +185,7 @@ class TioSafeBrain(Explicit): try: prop_value = getattr(self, prop) 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,) self.gid = gid @@ -411,7 +411,7 @@ class Node(TioSafeBrain): organisation_gid = 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: organisation_gid = "" # set the tag @@ -549,7 +549,7 @@ class Transaction(TioSafeBrain): # Must find a better way to browse specialised objects specialized_trade_condition = trade_condition.getSpecialiseValue() 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: trade_condition = specialized_trade_condition @@ -689,7 +689,7 @@ class Transaction(TioSafeBrain): elif line_type == 'Delivery': resource = integration_site.getDestinationCarrierValue() 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 # render in the xml movement_dict['resource'] = resource_gid diff --git a/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeNodeConduit.py b/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeNodeConduit.py index b753c3e34b5328234b10818e8525df7d2d506c76..c67f15b71dd17759d1d127ab8ba569bf24a84cd8 100644 --- a/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeNodeConduit.py +++ b/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeNodeConduit.py @@ -102,9 +102,9 @@ class TioSafeNodeConduit(TioSafeBaseConduit): try: previous_value = previous_xml[0].text except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) # check if it'a work on person or on address if tag in ['street', 'zip', 'city', 'country']: diff --git a/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeResourceConduit.py b/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeResourceConduit.py index 7c76914499c12889733abf33c8550c2e894a85dc..6136d01b5e8ccee3bf3286103f9cbb9031471bdf 100644 --- a/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeResourceConduit.py +++ b/bt5/erp5_tiosafe_core/ExtensionTemplateItem/portal_components/extension.erp5.TioSafeResourceConduit.py @@ -164,9 +164,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit): try: previous_value = previous_xml[0].text except IndexError: - raise ValueError, 'Too little or too many value, only one is required for %s' % ( + raise ValueError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) # check if it'a work on product or on categories if tag.split('[')[0] == 'category': @@ -268,9 +268,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit): previous_xml[0].text, ) except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) # retrieve the current value to check if exists a conflict current_value = etree.XML(document.asXML()).xpath(tag)[0].text diff --git a/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationCategoryMapping_init.py b/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationCategoryMapping_init.py index c7105d414fbb7215d9b3edf0b9227a966205a25a..8bb15c096ab22ce3041f34e91c78f0323ca05e31 100644 --- a/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationCategoryMapping_init.py +++ b/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationCategoryMapping_init.py @@ -1 +1 @@ -raise "yo", context +raise ValueError("yo", context) diff --git a/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationModule_getSignatureDiff.py b/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationModule_getSignatureDiff.py index 38d964f59895d780177566553303b438b162ed64..1f65d29b940b0bedc81e9cd4bf49f12a5609fe8b 100644 --- a/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationModule_getSignatureDiff.py +++ b/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationModule_getSignatureDiff.py @@ -2,7 +2,7 @@ im = context pub = im.getSourceSectionValue() pub_sub_list = pub.objectValues() 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: pub_sub = pub_sub_list[0] #pub_sub = im.getSourceSectionValue().objectValues()[0] diff --git a/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationModule_getTioSafeXMLDiff.py b/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationModule_getTioSafeXMLDiff.py index 373d68cf62f98e16f27329ae8a350d8ecbb8f8fe..77d2bf6e785a13120be39a3443a129e215cad6ac 100644 --- a/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationModule_getTioSafeXMLDiff.py +++ b/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/IntegrationModule_getTioSafeXMLDiff.py @@ -44,7 +44,7 @@ if pub_method is not None and sub_method is not None: sub_xml.append(getattr(ob, sub_xml_method)()) 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) sub_xml = '\n'.join(sub_xml) diff --git a/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/WebServiceRequest_test.py b/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/WebServiceRequest_test.py index 8064ad33adc9c2a57e6f05602d954a0d96935c48..7f64838092e4005515267d37e800fac655a45d6f 100644 --- a/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/WebServiceRequest_test.py +++ b/bt5/erp5_tiosafe_core/SkinTemplateItem/portal_skins/erp5_integration/WebServiceRequest_test.py @@ -20,7 +20,7 @@ if context.getLastRequestError() is None: for obj in object_list: try: xml = obj.asXML(debug=True) - except (ValueError, NotImplementedError), msg: + except (ValueError, NotImplementedError) as msg: error = msg continue if not xml: diff --git a/bt5/erp5_tiosafe_document/SkinTemplateItem/portal_skins/erp5_tiosafe_document/DocumentConnector_readDocument.py b/bt5/erp5_tiosafe_document/SkinTemplateItem/portal_skins/erp5_tiosafe_document/DocumentConnector_readDocument.py index fa002b7ffab5ebd6fcdfb0d4d7bfeb0f3b0d4eb2..8c0250732fb12c20272e5c587eaf0da040da9179 100644 --- a/bt5/erp5_tiosafe_document/SkinTemplateItem/portal_skins/erp5_tiosafe_document/DocumentConnector_readDocument.py +++ b/bt5/erp5_tiosafe_document/SkinTemplateItem/portal_skins/erp5_tiosafe_document/DocumentConnector_readDocument.py @@ -6,7 +6,7 @@ document_list = portal.document_module.searchFolder( sort_on=[('version', 'DESC')], ) if len(document_list) != 1: - raise ValueError, "Impossible to find document with reference %s" %(reference) + raise ValueError("Impossible to find document with reference %s" %(reference)) document = document_list[0].getObject() diff --git a/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoBrain.py b/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoBrain.py index 5971e3ef10c06b3f95b885b8815bca8ca14f77d4..3e701dda6bed0c806440f1f01dd2cb6466d0d313 100644 --- a/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoBrain.py +++ b/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoBrain.py @@ -230,7 +230,7 @@ class MagentoTransaction(MagentoBrain): elif line_type == 'Delivery': resource = integration_site.getDestinationCarrierValue() 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 # render in the xml movement_dict['resource'] = resource_gid diff --git a/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoNodeConduit.py b/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoNodeConduit.py index 7702d6fcaa2ec4a4ff586322c4f61f6bf6da8ffb..d0e8c4f963e03ef448a58ae169b1d54f42eb0bbd 100644 --- a/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoNodeConduit.py +++ b/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoNodeConduit.py @@ -110,9 +110,9 @@ class TioSafeNodeConduit(TioSafeBaseConduit): try: previous_value = previous_xml[0].text except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) # check if it'a work on person or on address if tag in ['street', 'zip', 'city', 'country']: diff --git a/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoResourceConduit.py b/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoResourceConduit.py index e016b0ae80d9d3fe567db9f5f515be714a41afa8..2bfdfcb011ac764f89265c6ddc2e0f91549b2fb2 100644 --- a/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoResourceConduit.py +++ b/bt5/erp5_tiosafe_magento/ExtensionTemplateItem/MagentoResourceConduit.py @@ -168,9 +168,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit): try: previous_value = previous_xml[0].text except IndexError: - raise ValueError, 'Too little or too many value, only one is required for %s' % ( + raise ValueError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) # check if it'a work on product or on categories if tag.split('[')[0] == 'category': @@ -272,9 +272,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit): previous_xml[0].text, ) except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) # retrieve the current value to check if exists a conflict current_value = etree.XML(document.asXML()).xpath(tag)[0].text diff --git a/bt5/erp5_tiosafe_magento_test/ExtensionTemplateItem/MagentoTest.py b/bt5/erp5_tiosafe_magento_test/ExtensionTemplateItem/MagentoTest.py index 40bfdeea4e81d4f02c7b7b99e4bffb90bf46b8d0..5144c1818347a679d0ff46ade6cbe956a89e174f 100644 --- a/bt5/erp5_tiosafe_magento_test/ExtensionTemplateItem/MagentoTest.py +++ b/bt5/erp5_tiosafe_magento_test/ExtensionTemplateItem/MagentoTest.py @@ -82,7 +82,7 @@ class MagentoTestConnector: def UserGet(self, *args, **kw): if not kw.has_key('customer_id'): - raise ValueError, "No customer_id in the arguments, got %s / %s" %(args, kw) + raise ValueError("No customer_id in the arguments, got %s / %s" %(args, kw)) customer_id = kw['customer_id'] @@ -91,7 +91,7 @@ class MagentoTestConnector: validation_state='validated') if len(person_list) != 1: - raise KeyError, "Error retrieving user with ID %s" %(customer_id,) + raise KeyError("Error retrieving user with ID %s" %(customer_id,)) else: person = person_list[0].getObject() result_list = [] @@ -108,13 +108,13 @@ class MagentoTestConnector: def UserUpdate(self, *args, **kw): if not kw.has_key('customer_id'): - raise ValueError, "No customer_id int the paramaters, got %s / %s" %(args, kw) + raise ValueError("No customer_id int the paramaters, got %s / %s" %(args, kw)) customer_id = kw['customer_id'] person_list = self.context.getPortalObject().magento_test_module.searchFolder(reference=user_id, portal_type="Magento Test Person") if len(person_list) != 1: - raise KeyError, "Error retrieving person with ID %s" %(customer_id) + raise KeyError("Error retrieving person with ID %s" %(customer_id)) else: person = person_list[0].getObject() context = etree.iterparse(StringIO(kw['data']), events=('end',)) diff --git a/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceBrain.py b/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceBrain.py index d1e05b7456765032a47ede102487d1ffa07a7aa8..2bfd6d69fcf835cd7d9b8b2e3ed1e4a6658ed353 100644 --- a/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceBrain.py +++ b/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceBrain.py @@ -50,7 +50,7 @@ class OscommerceNode(NodeBrain): category = 'Country/%s' % self.country, create_mapping=True, create_mapping_line=True, ).split('/', 1)[-1] - except ValueError, msg: + except ValueError as msg: LOG("OscommerceBrain.OscommerceNode.__init__", ERROR, "Getting category for %s raise with msg = %s" %(value, msg)) self.country = "" diff --git a/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceERP5NodeConduit.py b/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceERP5NodeConduit.py index f5d4e379c4f0d1ab4fde6697ec1a1cefb8cf55ea..f6dec8fad3af015c1aee450fdfd8afa751355a33 100644 --- a/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceERP5NodeConduit.py +++ b/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceERP5NodeConduit.py @@ -58,7 +58,7 @@ class OscommerceERP5NodeConduit(TioSafeBaseConduit): destination=object.getRelativeUrl(), destination_decision=object.getRelativeUrl(), destination_administration=object.getRelativeUrl(), - version=001) + version='001') stc.validate() def afterCreateMethod(self, object, **kw): @@ -105,7 +105,7 @@ class OscommerceERP5NodeConduit(TioSafeBaseConduit): if link_object is not None: document.setCareerSubordinationValue(link_object) 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() return [] diff --git a/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceERP5TransactionConduit.py b/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceERP5TransactionConduit.py index a350554288a4b8ea5a0c79fbe046bc45709531f7..c346520471c8dfcf42f3f4a41048fac9bf597a52 100644 --- a/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceERP5TransactionConduit.py +++ b/bt5/erp5_tiosafe_oscommerce/ExtensionTemplateItem/OscommerceERP5TransactionConduit.py @@ -106,7 +106,7 @@ class OscommerceERP5TransactionConduit(TioSafeBaseConduit): if tag in node_dict: node_dict[tag](document=sub_object, xml=node, **kw) 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': link_object = object.portal_catalog.getResultValue( portal_type='Currency', @@ -290,7 +290,7 @@ class OscommerceERP5TransactionConduit(TioSafeBaseConduit): break # in the worse case save the line with the unknown product 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 movement_dict_value[tag] = link_object diff --git a/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisBrain.py b/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisBrain.py index 808b8a26b7496bbc15da043ea29836bbe3c3327a..25e40aee48ced6a0b2a6a19018825c78a10a1590 100644 --- a/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisBrain.py +++ b/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisBrain.py @@ -50,7 +50,7 @@ class OxatisNode(NodeBrain): category = 'Country/%s' % self.country, create_mapping=True, create_mapping_line=True, ).split('/', 1)[-1] - except ValueError, msg: + except ValueError as msg: LOG("OxatisBrain.OxatisNode.__init__", ERROR, "Getting category for %s raise with msg = %s" %(value, msg)) self.country = "" diff --git a/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisNodeConduit.py b/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisNodeConduit.py index 9a24f8a01a27dfb239c3238be718282b7bfa479c..182aca88e57a58f37999d650bda1583c198e35f9 100644 --- a/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisNodeConduit.py +++ b/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisNodeConduit.py @@ -172,9 +172,9 @@ class OxatisNodeConduit(TioSafeNodeConduit): try: previous_value = previous_xml[0].text except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) if previous_value is None: previous_value = "" diff --git a/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisProductConduit.py b/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisProductConduit.py index a66be02a6e56f743d71cd8f34090d3308a249355..01fd33d5742758c7f9bea5eba8fd2562fa7a76f1 100644 --- a/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisProductConduit.py +++ b/bt5/erp5_tiosafe_oxatis/ExtensionTemplateItem/OxatisProductConduit.py @@ -66,7 +66,7 @@ class OxatisProductConduit(TioSafeResourceConduit): if create_method is not None: create_result = create_method(**keyword) 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): # We suppose the id of the object created was returned by the plugin new_id = create_result[0].getId() @@ -85,7 +85,7 @@ class OxatisProductConduit(TioSafeResourceConduit): if delete_method is not None: return delete_method(product_id=object_id) 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): @@ -112,9 +112,9 @@ class OxatisProductConduit(TioSafeResourceConduit): try: previous_value = previous_xml[0].text except IndexError: - raise ValueError, 'Too little or too many value, only one is required for %s' % ( + raise ValueError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) if isinstance(previous_value, unicode): previous_value = previous_value.encode('utf-8') @@ -157,7 +157,7 @@ class OxatisProductConduit(TioSafeResourceConduit): elif tag == "reference": document.context.product_module.updateProductReference(**keyword) else: - raise ValueError, "Do not know how to update this property %s / %s for %s" %(tag, new_value, document.getId()) + raise ValueError("Do not know how to update this property %s / %s for %s" %(tag, new_value, document.getId())) elif base_tag.startswith("mapping"): index = int(base_tag[-2]) diff --git a/bt5/erp5_tiosafe_oxatis/PathTemplateItem/portal_integrations/oxatis/product_module/getObjectList.py b/bt5/erp5_tiosafe_oxatis/PathTemplateItem/portal_integrations/oxatis/product_module/getObjectList.py index eaeee741b4a7c128aa4e7ec92f00c01cfa3bb8d8..77e7df7b4d55b4d102b2b9f50d47d9e8f93232a3 100644 --- a/bt5/erp5_tiosafe_oxatis/PathTemplateItem/portal_integrations/oxatis/product_module/getObjectList.py +++ b/bt5/erp5_tiosafe_oxatis/PathTemplateItem/portal_integrations/oxatis/product_module/getObjectList.py @@ -3,8 +3,8 @@ if id: try: long(id) except ValueError: - raise KeyError, "Item %s does not exists call by Python Script %s : not a long" % (id, - context.getTitle(),) + raise KeyError("Item %s does not exists call by Python Script %s : not a long" % (id, + context.getTitle(),)) product_list = context.getProductList(*args, **kw) diff --git a/bt5/erp5_tiosafe_oxatis_test/ExtensionTemplateItem/OxatisTest.py b/bt5/erp5_tiosafe_oxatis_test/ExtensionTemplateItem/OxatisTest.py index 41467080c6b5bb317c3ee634b40dbb0179950bb3..e96faf1f1922c38993c2c383fb6a39d51589e334 100644 --- a/bt5/erp5_tiosafe_oxatis_test/ExtensionTemplateItem/OxatisTest.py +++ b/bt5/erp5_tiosafe_oxatis_test/ExtensionTemplateItem/OxatisTest.py @@ -223,7 +223,7 @@ class OxatisTestConnector: user_list = etree.SubElement(data, "UserList") # retrieve the date from given xml if not kw.has_key('data'): - raise ValueError, "No data passed to UserGetList, got %s / %s" %(args, kw) + raise ValueError("No data passed to UserGetList, got %s / %s" %(args, kw)) # parse the data to retrieve the date context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="LatestModifiedDateStart") for event, element in context: @@ -261,7 +261,7 @@ class OxatisTestConnector: def UserUpdate(self, *args, **kw): if not kw.has_key('data'): - raise ValueError, "No data passed to UserGet, got %s / %s" %(args, kw) + raise ValueError("No data passed to UserGet, got %s / %s" %(args, kw)) # Must check xml validity here # parse the data to retrieve the user id context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="OxID") @@ -293,7 +293,7 @@ class OxatisTestConnector: def UserGet(self, *args, **kw): if not kw.has_key('data'): - raise ValueError, "No data passed to UserGet, got %s / %s" %(args, kw) + raise ValueError("No data passed to UserGet, got %s / %s" %(args, kw)) # Must check xml validity here # parse the data to retrieve the user id context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="OxID") @@ -341,7 +341,7 @@ class OxatisTestConnector: products = etree.SubElement(data, "ProductList") # retrieve the date from given xml if not kw.has_key('data'): - raise ValueError, "No data passed to UserGetList, got %s / %s" %(args, kw) + raise ValueError("No data passed to UserGetList, got %s / %s" %(args, kw)) # parse the data to retrieve the date context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="LatestModifiedDateStart") for event, element in context: @@ -372,7 +372,7 @@ class OxatisTestConnector: def ProductGet(self, *args, **kw): if not kw.has_key('data'): - raise ValueError, "No data passed to ProductGet, got %s / %s" %(args, kw) + raise ValueError("No data passed to ProductGet, got %s / %s" %(args, kw)) # Must check xml validity here # parse the data to retrieve the product id context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="OxID") @@ -421,7 +421,7 @@ class OxatisTestConnector: def ProductDelete(self, *args, **kw): if not kw.has_key('data'): - raise ValueError, "No data passed to ProductGet, got %s / %s" %(args, kw) + raise ValueError("No data passed to ProductGet, got %s / %s" %(args, kw)) # Must check xml validity here # parse the data to retrieve the product id context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="OxID") @@ -443,7 +443,7 @@ class OxatisTestConnector: def ProductUpdateName(self, *args, **kw): if not kw.has_key('data'): - raise ValueError, "No data passed to ProductGet, got %s / %s" %(args, kw) + raise ValueError("No data passed to ProductGet, got %s / %s" %(args, kw)) # Must check xml validity here # parse the data to retrieve the product id context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="OxID") @@ -468,7 +468,7 @@ class OxatisTestConnector: def ProductUpdateDescriptions(self, *args, **kw): if not kw.has_key('data'): - raise ValueError, "No data passed to ProductGet, got %s / %s" %(args, kw) + raise ValueError("No data passed to ProductGet, got %s / %s" %(args, kw)) # Must check xml validity here # parse the data to retrieve the product id context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="OxID") @@ -497,7 +497,7 @@ class OxatisTestConnector: # def OrderGetList(self, *args, **kw): if not kw.has_key('data'): - raise ValueError, "No data passed to OrderGet, got %s / %s" %(args, kw) + raise ValueError("No data passed to OrderGet, got %s / %s" %(args, kw)) # Must check xml validity here # parse the data to retrieve the order id context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="OrderDateStart") @@ -549,7 +549,7 @@ class OxatisTestConnector: def OrderGetDetails(self, *args, **kw): if not kw.has_key('data'): - raise ValueError, "No data passed to OrderGet, got %s / %s" %(args, kw) + raise ValueError("No data passed to OrderGet, got %s / %s" %(args, kw)) # Must check xml validity here # parse the data to retrieve the order id context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="OxID") @@ -592,7 +592,7 @@ class OxatisTestConnector: "2" : "Taille", } if not kw.has_key('data'): - raise ValueError, "No data passed to OptionTypesGet, got %s / %s" %(args, kw) + raise ValueError("No data passed to OptionTypesGet, got %s / %s" %(args, kw)) # Must check xml validity here # parse the data to retrieve the base category id context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="OxID") @@ -621,7 +621,7 @@ class OxatisTestConnector: "23" : ("S", "Petite"), } if not kw.has_key('data'): - raise ValueError, "No data passed to OptionsValuesGet, got %s / %s" %(args, kw) + raise ValueError("No data passed to OptionsValuesGet, got %s / %s" %(args, kw)) # Must check xml validity here # parse the data to retrieve the base category id context = etree.iterparse(StringIO(str(kw['data'])), events=('end',), tag="OxID") diff --git a/bt5/erp5_tiosafe_oxatis_test/TestTemplateItem/testOxatisSynchronization.py b/bt5/erp5_tiosafe_oxatis_test/TestTemplateItem/testOxatisSynchronization.py index 3ec187b2d7185a640ff4cdf2777225a50ceb0117..44ac5a41db5f9a1c526cd4f0a1224d64c29998fe 100644 --- a/bt5/erp5_tiosafe_oxatis_test/TestTemplateItem/testOxatisSynchronization.py +++ b/bt5/erp5_tiosafe_oxatis_test/TestTemplateItem/testOxatisSynchronization.py @@ -139,7 +139,7 @@ class TestOxatisSynchronization(ERP5TypeTestCase): diff = "\n" for line in self.oxatis[im].IntegrationModule_getTioSafeXMLDiff(html=False).split('\n'): diff += "%s\n" %(line) - raise AssertionError, diff + raise AssertionError(diff) @@ -301,7 +301,7 @@ class TestOxatisSynchronization(ERP5TypeTestCase): self.assertEqual(test_person.getShippingzipcode(), default_address.getZipCode()) self.assertEqual(test_person.getShippingcity(), default_address.getCity()) else: - raise ValueError, 'bad type' + raise ValueError('bad type') # # Modify persons on the plugin side diff --git a/bt5/erp5_tiosafe_prestashop/ExtensionTemplateItem/PrestashopResourceConduit.py b/bt5/erp5_tiosafe_prestashop/ExtensionTemplateItem/PrestashopResourceConduit.py index 15da282dcf80b30e607c421ffc90493f9047b8c2..783256c9043dc01bba970ecbf8c4f835ef37a950 100644 --- a/bt5/erp5_tiosafe_prestashop/ExtensionTemplateItem/PrestashopResourceConduit.py +++ b/bt5/erp5_tiosafe_prestashop/ExtensionTemplateItem/PrestashopResourceConduit.py @@ -81,7 +81,7 @@ class PrestashopResourceConduit(TioSafeResourceConduit): if create_method is not None: create_result = create_method(**keyword) 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): # We suppose the id of the object created was returned by the plugin new_id = create_result[0].getId() diff --git a/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartBrain.py b/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartBrain.py index a3f15caf16c8cd8bd66e4ae9c5629ddf1c21916e..6eaf6446be49aa3935b66fc66a34fb8863ea7aed 100644 --- a/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartBrain.py +++ b/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartBrain.py @@ -51,7 +51,7 @@ class UbercartNode(NodeBrain): category = 'Country/%s' % self.country, create_mapping=True, create_mapping_line=True, ).split('/', 1)[-1] - except ValueError, msg: + except ValueError as msg: LOG("UbercartBrain.UbercartNode.__init__", ERROR, "Getting category for %s raise with msg = %s" %(self.country, msg)) self.country = "" diff --git a/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartNodeConduit.py b/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartNodeConduit.py index 8b1d212034ecc69fa05465a6301e9196425bad38..70c5e098189e576a5ae26327ff5d8d9f8e92a288 100644 --- a/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartNodeConduit.py +++ b/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartNodeConduit.py @@ -176,9 +176,9 @@ class UbercartNodeConduit(ERP5NodeConduit): try: previous_value = previous_xml[0].text except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) if previous_value is None: previous_value = "" diff --git a/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartResourceConduit.py b/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartResourceConduit.py index 806a328efaf12f4998bb7479ab19dd5014549d9c..a8f60f585fecfadfddfd7a638edabbb2bdd3957d 100644 --- a/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartResourceConduit.py +++ b/bt5/erp5_tiosafe_ubercart/ExtensionTemplateItem/UbercartResourceConduit.py @@ -128,7 +128,7 @@ class UbercartResourceConduit(TioSafeResourceConduit): if delete_method is not None: return delete_method(product_id=object_id) 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): @@ -147,9 +147,9 @@ class UbercartResourceConduit(TioSafeResourceConduit): try: previous_value = previous_xml[0].text.encode("utf-8") except IndexError: - raise ValueError, 'Too little or too many value, only one is required for %s' % ( + raise ValueError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) if isinstance(previous_value, unicode): previous_value = previous_value.encode('utf-8') @@ -269,9 +269,9 @@ class UbercartResourceConduit(TioSafeResourceConduit): previous_xml[0].text.encode("utf-8"), ) except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) # retrieve the current value to check if exists a conflict current_value = etree.XML(document.asXML()).xpath(tag)[0].text.encode("utf-8") diff --git a/bt5/erp5_tiosafe_ubercart_test/ExtensionTemplateItem/ERP5TransactionConduit.py b/bt5/erp5_tiosafe_ubercart_test/ExtensionTemplateItem/ERP5TransactionConduit.py index 79bedb2367917918bd2f7593fb61be265af1b7af..652b5a5c81f9d39cf2533174f00a79ab7024de6d 100644 --- a/bt5/erp5_tiosafe_ubercart_test/ExtensionTemplateItem/ERP5TransactionConduit.py +++ b/bt5/erp5_tiosafe_ubercart_test/ExtensionTemplateItem/ERP5TransactionConduit.py @@ -106,7 +106,7 @@ class ERP5TransactionConduit(TioSafeBaseConduit): if tag in node_dict: node_dict[tag](document=sub_object, xml=node, **kw) 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': link_object = object.portal_catalog.getResultValue( portal_type='Currency', @@ -289,7 +289,7 @@ class ERP5TransactionConduit(TioSafeBaseConduit): break # in the worse case save the line with the unknown product 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 movement_dict_value[tag] = link_object diff --git a/bt5/erp5_tiosafe_ubercart_test/ExtensionTemplateItem/UbercartTest.py b/bt5/erp5_tiosafe_ubercart_test/ExtensionTemplateItem/UbercartTest.py index 7be1b01a5aa714403d7138bb79ec2bd1b2f41c37..92dcd5c1b091626bf42d9747f1a61f38aa358c20 100644 --- a/bt5/erp5_tiosafe_ubercart_test/ExtensionTemplateItem/UbercartTest.py +++ b/bt5/erp5_tiosafe_ubercart_test/ExtensionTemplateItem/UbercartTest.py @@ -184,7 +184,7 @@ class UbercartTestConnector: def getPerson(self, *args, **kw): if not kw.has_key('person_id'): - raise ValueError, "No parameter person_id passed to PersonGet, got %s / %s" %(args, kw) + raise ValueError("No parameter person_id passed to PersonGet, got %s / %s" %(args, kw)) person_id = kw["person_id"] # retrieve the person inside the test module person_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=person_id, @@ -212,7 +212,7 @@ class UbercartTestConnector: def getDeliveredPerson(self, *args, **kw): if not kw.has_key('person_id'): - raise ValueError, "No parameter person_id passed to PersonGet, got %s / %s" %(args, kw) + raise ValueError("No parameter person_id passed to PersonGet, got %s / %s" %(args, kw)) person_id = kw["person_id"] # retrieve the person inside the test module person_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=person_id, @@ -242,7 +242,7 @@ class UbercartTestConnector: if kw.has_key('id') and not kw.has_key('person_id'): kw["person_id"] = kw["id"] if not kw.has_key('person_id'): - raise ValueError, "No parameter person_id passed to PersonGet, got %s / %s" %(args, kw) + raise ValueError("No parameter person_id passed to PersonGet, got %s / %s" %(args, kw)) person_id = kw["person_id"] # retrieve the person inside the test module person_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=person_id, @@ -273,7 +273,7 @@ class UbercartTestConnector: if kw.has_key('id') and not kw.has_key('person_id'): kw["person_id"] = kw["id"] if not kw.has_key('person_id'): - raise ValueError, "No parameter person_id passed to PersonGet, got %s / %s" %(args, kw) + raise ValueError("No parameter person_id passed to PersonGet, got %s / %s" %(args, kw)) person_id = kw["person_id"] # retrieve the person inside the test module person_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=person_id, @@ -355,7 +355,7 @@ class UbercartTestConnector: def getOrganisation(self, *args, **kw): if not kw.has_key('organisation_id'): - raise ValueError, "No parameter organisation_id passed to getOrganisation, got %s / %s" %(args, kw) + raise ValueError("No parameter organisation_id passed to getOrganisation, got %s / %s" %(args, kw)) organisation_id = kw["organisation_id"] # retrieve the organisation inside the test module org_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=organisation_id, @@ -469,7 +469,7 @@ class UbercartTestConnector: def getDeliveryOrganisation(self, *args, **kw): if not kw.has_key('organisation_id'): - raise ValueError, "No parameter organisation_id passed to getOrganisation, got %s / %s" %(args, kw) + raise ValueError("No parameter organisation_id passed to getOrganisation, got %s / %s" %(args, kw)) organisation_id = kw["organisation_id"] # retrieve the organisation inside the test module org_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=organisation_id, @@ -540,7 +540,7 @@ class UbercartTestConnector: def updatePerson(self, *args, **kw): if not kw.has_key('person_id'): - raise ValueError, "No parameter person_id passed to PersonGet, got %s / %s" %(args, kw) + raise ValueError("No parameter person_id passed to PersonGet, got %s / %s" %(args, kw)) person_id = kw["person_id"] # retrieve the person inside the test module person_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=person_id, @@ -572,7 +572,7 @@ class UbercartTestConnector: def getProductCategoryList(self, *args, **kw): if not kw.has_key('product_id'): - raise ValueError, "No product_id passed to getProductCategoryList, got %s / %s" %(args, kw) + raise ValueError("No product_id passed to getProductCategoryList, got %s / %s" %(args, kw)) resource_id = kw['product_id'] # retrieve the product inside the test module resource_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=resource_id, @@ -607,15 +607,15 @@ class UbercartTestConnector: else: kw["product_id"] = kw['id_product'] if not kw.has_key('product_id'): - raise ValueError, "No product_id passed to createProductCategory, got %s / %s" %(args, kw) + raise ValueError("No product_id passed to createProductCategory, got %s / %s" %(args, kw)) resource_id = kw['product_id'] if not kw.has_key('base_category'): - raise ValueError, "No base_category passed to createProductCategory, got %s / %s" %(args, kw) + raise ValueError("No base_category passed to createProductCategory, got %s / %s" %(args, kw)) base_category = kw['base_category'] if base_category.startswith("'") or base_category.startswith('"'): base_category = base_category[1:len(base_category)-1] if not kw.has_key('variation'): - raise ValueError, "No variation passed to createProductCategory, got %s / %s" %(args, kw) + raise ValueError("No variation passed to createProductCategory, got %s / %s" %(args, kw)) variation = kw['variation'] if variation.startswith("'") or variation.startswith('"'): variation= variation[1:len(variation)-1] @@ -643,15 +643,15 @@ class UbercartTestConnector: else: kw["product_id"] = kw['id_product'] if not kw.has_key('product_id'): - raise ValueError, "No product_id passed to deleteProductCategory, got %s / %s" %(args, kw) + raise ValueError("No product_id passed to deleteProductCategory, got %s / %s" %(args, kw)) resource_id = kw['product_id'] if not kw.has_key('base_category'): - raise ValueError, "No base_category passed to deleteProductCategory, got %s / %s" %(args, kw) + raise ValueError("No base_category passed to deleteProductCategory, got %s / %s" %(args, kw)) base_category = kw['base_category'] if base_category.startswith("'") or base_category.startswith('"'): base_category = base_category[1:len(base_category)-1] if not kw.has_key('variation'): - raise ValueError, "No variation passed to deleteProductCategory, got %s / %s" %(args, kw) + raise ValueError("No variation passed to deleteProductCategory, got %s / %s" %(args, kw)) variation = kw['variation'] if variation.startswith("'") or variation.startswith('"'): variation= variation[1:len(variation)-1] @@ -680,15 +680,15 @@ class UbercartTestConnector: def deleteProductCategory(self, *args, **kw): if not kw.has_key('product_id'): - raise ValueError, "No product_id passed to deleteProductCategory, got %s / %s" %(args, kw) + raise ValueError("No product_id passed to deleteProductCategory, got %s / %s" %(args, kw)) resource_id = kw['product_id'] if not kw.has_key('base_category'): - raise ValueError, "No base_category passed to deleteProductCategory, got %s / %s" %(args, kw) + raise ValueError("No base_category passed to deleteProductCategory, got %s / %s" %(args, kw)) base_category = kw['base_category'] if base_category.startswith("'") or base_category.startswith('"'): base_category = base_category[1:len(base_category)-1] if not kw.has_key('variation'): - raise ValueError, "No variation passed to deleteProductCategory, got %s / %s" %(args, kw) + raise ValueError("No variation passed to deleteProductCategory, got %s / %s" %(args, kw)) variation = kw['variation'] if variation.startswith("'") or variation.startswith('"'): variation= variation[1:len(variation)-1] @@ -742,7 +742,7 @@ class UbercartTestConnector: def getProduct(self, *args, **kw): if not kw.has_key('product_id'): - raise ValueError, "No product_id passed to ProductGet, got %s / %s" %(args, kw) + raise ValueError("No product_id passed to ProductGet, got %s / %s" %(args, kw)) resource_id = kw['product_id'] # retrieve the product inside the test module resource_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=resource_id, @@ -789,7 +789,7 @@ class UbercartTestConnector: def createProduct(self, *args, **kw): if not kw.has_key('reference'): - raise ValueError, "No reference passed to createProduct, got %s / %s" %(args, kw) + raise ValueError("No reference passed to createProduct, got %s / %s" %(args, kw)) keywords = {} keywords["reference"] = kw['reference'].strip('"').strip("'") if kw.has_key('title'): @@ -808,7 +808,7 @@ class UbercartTestConnector: def deleteProduct(self, *args, **kw): if not kw.has_key('product_id'): - raise ValueError, "No product_id passed to deleteProduct, got %s / %s" %(args, kw) + raise ValueError("No product_id passed to deleteProduct, got %s / %s" %(args, kw)) resource_id = kw['product_id'] # retrieve the product inside the test module resource_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=resource_id, @@ -825,9 +825,9 @@ class UbercartTestConnector: def updateProduct(self, *args, **kw): if not kw.has_key('product_id') : - raise ValueError, "No product_id passed to updateProductName, got %s / %s" %(args, kw) + raise ValueError("No product_id passed to updateProductName, got %s / %s" %(args, kw)) if not kw.has_key('title') : - raise ValueError, "No title passed to updateProductName, got %s / %s" %(args, kw) + raise ValueError("No title passed to updateProductName, got %s / %s" %(args, kw)) title = kw['title'] resource_id = kw['product_id'] # retrieve the product inside the test module @@ -851,7 +851,7 @@ class UbercartTestConnector: # def getSaleOrder(self, *args, **kw): if not kw.has_key('sale_order_id'): - raise ValueError, "No sale_order_id passed to getSaleOrder, got %s / %s" %(args, kw) + raise ValueError("No sale_order_id passed to getSaleOrder, got %s / %s" %(args, kw)) order_id = kw['sale_order_id'] sale_order_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=order_id, @@ -916,7 +916,7 @@ class UbercartTestConnector: def getSaleOrderLineList(self, *args, **kw): if not kw.has_key('sale_order_id'): - raise ValueError, "No sale_order_id passed to OrderGetDetails, got %s / %s" %(args, kw) + raise ValueError("No sale_order_id passed to OrderGetDetails, got %s / %s" %(args, kw)) sale_order_id = kw['sale_order_id'] sale_order_list = self.context.getPortalObject().ubercart_test_module.searchFolder(id=sale_order_id, diff --git a/bt5/erp5_tiosafe_ubercart_test/TestTemplateItem/testUbercartSynchronisation.py b/bt5/erp5_tiosafe_ubercart_test/TestTemplateItem/testUbercartSynchronisation.py index 19c29635da1bc093a1200d03cef5e41c933970cb..e4e8c44406363665d672b476004655928d353ff8 100644 --- a/bt5/erp5_tiosafe_ubercart_test/TestTemplateItem/testUbercartSynchronisation.py +++ b/bt5/erp5_tiosafe_ubercart_test/TestTemplateItem/testUbercartSynchronisation.py @@ -260,7 +260,7 @@ class TestUbercartSynchronization(ERP5TypeTestCase): self.assertEqual(test_person.getZip(), default_address.getZipCode()) self.assertEqual(test_person.getCity(), default_address.getCity()) else: - raise ValueError, 'bad type' + raise ValueError('bad type') # # Modify persons on the plugin side diff --git a/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/ERP5DeliveredNodeConduit.py b/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/ERP5DeliveredNodeConduit.py index 81ba642906ad9e2678f60ee7de142e1a406645b8..f3842b54bedf20c66dd87421110fbdfc0c840a17 100644 --- a/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/ERP5DeliveredNodeConduit.py +++ b/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/ERP5DeliveredNodeConduit.py @@ -40,7 +40,7 @@ class ERP5DeliveredNodeConduit(ERP5NodeConduit): stc = object.getPortalObject().sale_trade_condition_module.newContent(title="%s %s" %(site.getReference(), object.getTitle()), specialise=default_stc, destination=object.getRelativeUrl(), - version=001) + version='001') stc.validate() def _updateSaleTradeCondition(self, object, **kw): @@ -56,7 +56,7 @@ class ERP5DeliveredNodeConduit(ERP5NodeConduit): if len(stc_list) == 0: self._createSaleTradeCondition(object, **kw) elif len(stc_list) > 1: - raise ValueError, "Multiple trade condition (%s) retrieve for %s" %([x.path for x in stc_list], object.getTitle()) + raise ValueError("Multiple trade condition (%s) retrieve for %s" %([x.path for x in stc_list], object.getTitle())) else: stc = stc_list[0].getObject() stc.edit(destination=object.getRelativeUrl(),) diff --git a/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/ERP5InvoicedNodeConduit.py b/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/ERP5InvoicedNodeConduit.py index 765272cf652c6deaa0f3a4474384b2f3ecf9eb8e..a3296c00d730ccc1b3ffa4500e7e24a3667a7694 100644 --- a/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/ERP5InvoicedNodeConduit.py +++ b/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/ERP5InvoicedNodeConduit.py @@ -42,7 +42,7 @@ class ERP5InvoicedNodeConduit(ERP5NodeConduit): specialise=default_stc, destination_decision=object.getRelativeUrl(), destination_administration=object.getRelativeUrl(), - version=001) + version='001') stc.validate() def _updateSaleTradeCondition(self, object, **kw): @@ -58,7 +58,7 @@ class ERP5InvoicedNodeConduit(ERP5NodeConduit): if len(stc_list) == 0: self._createSaleTradeCondition(object, **kw) elif len(stc_list) > 1: - raise ValueError, "Multiple trade condition (%s) retrieve for %s" %([x.path for x in stc_list], object.getTitle()) + raise ValueError("Multiple trade condition (%s) retrieve for %s" %([x.path for x in stc_list], object.getTitle())) else: stc = stc_list[0].getObject() stc.edit(destination_decision=object.getRelativeUrl(), diff --git a/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartBrain.py b/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartBrain.py index 25dfab75288092580bf7d1c7b247b03838cdee7a..b80dd8f420ba8ef102a4b4799612a70700ee8648 100644 --- a/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartBrain.py +++ b/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartBrain.py @@ -52,7 +52,7 @@ class VirtuemartNode(NodeBrain): category = 'Country/%s' % self.country, create_mapping=True, create_mapping_line=True, ).split('/', 1)[-1] - except ValueError, msg: + except ValueError as msg: LOG("VirtuemartBrain.VirtuemartNode.__init__", ERROR, "Getting category for %s raise with msg = %s" %(self.country, msg)) self.country = "" @@ -91,7 +91,7 @@ class VirtuemartNode(NodeBrain): create_mapping_line=True, ) value = "/".join(value.split('/')[1:]) - except ValueError, msg: + except ValueError as msg: LOG("VirtuemartBrain.VirtuemartNode._generateCoordinatesXML", ERROR, "Getting category for %s raise with msg = %s" %(value, msg)) #return "" diff --git a/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartNodeConduit.py b/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartNodeConduit.py index dbb2147636aab4f150fa4e2fbc47e14b47272f55..51c7d3d5a271d3b06dacdc147ee8d3665bd59336 100644 --- a/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartNodeConduit.py +++ b/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartNodeConduit.py @@ -178,9 +178,9 @@ class VirtuemartNodeConduit(TioSafeNodeConduit): try: previous_value = previous_xml[0].text except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) if previous_value is None: previous_value = "" diff --git a/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartResourceConduit.py b/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartResourceConduit.py index bbfd4f3ca14f8c6d6470857f6f04e57dcfcc4c16..a9a3a92807dd4a81a39ceb1273be290c5bdcff6c 100644 --- a/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartResourceConduit.py +++ b/bt5/erp5_tiosafe_virtuemart/ExtensionTemplateItem/VirtuemartResourceConduit.py @@ -82,7 +82,7 @@ class VirtuemartResourceConduit(TioSafeResourceConduit): if create_method is not None: create_result = create_method(**keyword) 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(),)) LOG('VirtuemartResourceConduit: ', INFO, object.IntegrationSite_lastID(type='Product')[0].showDict()) new_id = object.IntegrationSite_lastID(type='Product')[0].getId() @@ -120,7 +120,7 @@ class VirtuemartResourceConduit(TioSafeResourceConduit): if delete_method is not None: return delete_method(product_id=object_id) 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): @@ -139,9 +139,9 @@ class VirtuemartResourceConduit(TioSafeResourceConduit): try: previous_value = previous_xml[0].text except IndexError: - raise ValueError, 'Too little or too many value, only one is required for %s' % ( + raise ValueError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) if isinstance(previous_value, unicode): previous_value = previous_value.encode('utf-8') @@ -217,9 +217,9 @@ class VirtuemartResourceConduit(TioSafeResourceConduit): previous_xml[0].text.encode('utf-8'), ) except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) # retrieve the current value to check if exists a conflict current_value = etree.XML(document.asXML()).xpath(tag)[0].text diff --git a/bt5/erp5_tiosafe_virtuemart_test/ExtensionTemplateItem/VirtueMartTest.py b/bt5/erp5_tiosafe_virtuemart_test/ExtensionTemplateItem/VirtueMartTest.py index 2c960964e92df5d1f183f80cca93e22b939530e0..be230f6721a5deee3663e00ba504864ec1572577 100644 --- a/bt5/erp5_tiosafe_virtuemart_test/ExtensionTemplateItem/VirtueMartTest.py +++ b/bt5/erp5_tiosafe_virtuemart_test/ExtensionTemplateItem/VirtueMartTest.py @@ -181,7 +181,7 @@ class VirtueMartTestConnector: def updatePerson(self, *args, **kw): LOG("Viewing updatePerson ", INFO, "kw: %s" %(kw)) if not kw.has_key('person_id'): - raise ValueError, "No parameter person_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter person_id given, got %s / %s" %(args, kw)) person_id = kw["person_id"] # get corresponding person from test module person_list = self.context.getPortalObject().virtuemart_test_module.searchFolder(id=person_id, @@ -213,7 +213,7 @@ class VirtueMartTestConnector: def deletePerson(self, *args, **kw): if not kw.has_key('person_id'): - raise ValueError, "No parameter person_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter person_id given, got %s / %s" %(args, kw)) person_id = kw['person_id'] # get corresponding person from test module person_list = self.context.getPortalObject().virtuemart_test_module.searchFolder(id=person_id, @@ -264,7 +264,7 @@ class VirtueMartTestConnector: def createAddress(self, *args, **kw): if not kw.has_key('person_id'): - raise ValueError, "No person_id given, got %s / %s" %(args, kw) + raise ValueError("No person_id given, got %s / %s" %(args, kw)) keywords = {} if kw.has_key('street'): keywords["street"] = kw['street'].strip('"').strip("'") @@ -286,7 +286,7 @@ class VirtueMartTestConnector: def updateAddress(self, *args, **kw): LOG("Viewing updateAddress ", INFO, "kw: %s" %(kw)) if not kw.has_key('person_id') : - raise ValueError, "No parameter person_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter person_id given, got %s / %s" %(args, kw)) keywords = {} if kw.has_key('street'): keywords["street"] = kw['street'].strip('"').strip("'") @@ -431,7 +431,7 @@ class VirtueMartTestConnector: def createProduct(self, *args, **kw): if not kw.has_key('reference'): - raise ValueError, "No reference passed to createProduct, got %s / %s" %(args, kw) + raise ValueError("No reference passed to createProduct, got %s / %s" %(args, kw)) keywords = {} keywords["reference"] = kw['reference'].strip('"').strip("'") if kw.has_key('title'): @@ -453,7 +453,7 @@ class VirtueMartTestConnector: def deleteProduct(self, *args, **kw): if not kw.has_key('product_id'): - raise ValueError, "No parameter product_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter product_id given, got %s / %s" %(args, kw)) resource_id = kw['product_id'] # retrieve the product inside the test module resource_list = self.context.getPortalObject().virtuemart_test_module.searchFolder(id=resource_id, @@ -470,7 +470,7 @@ class VirtueMartTestConnector: def updateProduct(self, *args, **kw): if not kw.has_key('product_id') : - raise ValueError, "No parameter product_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter product_id given, got %s / %s" %(args, kw)) keywords = {} if kw.has_key('title'): keywords["title"] = kw['title'].strip('"').strip("'") @@ -498,9 +498,9 @@ class VirtueMartTestConnector: def createProductCategory(self, *args, **kw): if not kw.has_key('product_id'): - raise ValueError, "No parameter product_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter product_id given, got %s / %s" %(args, kw)) if not kw.has_key('base_category') or not kw.has_key('variation'): - raise ValueError, "No parameter base_category or variation given, got %s " %(kw) + raise ValueError("No parameter base_category or variation given, got %s " %(kw)) base_category = kw['base_category'].strip('"').strip("'") variation = kw['variation'].strip('"').strip("'") category = "%s/%s" % (base_category, variation) @@ -522,9 +522,9 @@ class VirtueMartTestConnector: def deleteProductCategory(self, *args, **kw): if not kw.has_key('product_id'): - raise ValueError, "No parameter product_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter product_id given, got %s / %s" %(args, kw)) if not kw.has_key('base_category') or not kw.has_key('variation'): - raise ValueError, "No parameter base_category or variation given, got %s" %(kw) + raise ValueError("No parameter base_category or variation given, got %s" %(kw)) base_category = kw['base_category'].strip('"').strip("'") variation = kw['variation'].strip('"').strip("'") category = "%s/%s" % (base_category, variation) @@ -551,7 +551,7 @@ class VirtueMartTestConnector: def getProductCategoryList(self, *args, **kw): if not kw.has_key('product_id') and not kw.has_key('group_id'): - raise ValueError, "No parameter product_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter product_id given, got %s / %s" %(args, kw)) if kw.has_key('product_id'): resource_id = kw['product_id'] else: @@ -585,7 +585,7 @@ class VirtueMartTestConnector: def getLastID(self, *args, **kw): if not kw.has_key('type'): - raise ValueError, "No parameter type given, got %s / %s" %(args, kw) + raise ValueError("No parameter type given, got %s / %s" %(args, kw)) type = kw['type'] last_id = -1 @@ -671,7 +671,7 @@ class VirtueMartTestConnector: def getSaleOrderLineList(self, *args, **kw): if not kw.has_key('sale_order_id'): - raise ValueError, "No parameter sale_order_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter sale_order_id given, got %s / %s" %(args, kw)) sale_order_id = kw['sale_order_id'] sale_order_list = self.context.getPortalObject().virtuemart_test_module.searchFolder(id=sale_order_id, @@ -707,7 +707,7 @@ class VirtueMartTestConnector: def getSaleOrderLineCategoryList(self, *args, **kw): if not kw.has_key('sale_order_id'): - raise ValueError, "No parameter sale_order_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter sale_order_id given, got %s / %s" %(args, kw)) sale_order_id = kw['sale_order_id'] # retrieve the sale order from the test module sale_order_list = self.context.getPortalObject().virtuemart_test_module.searchFolder(id=sale_order_id, @@ -719,7 +719,7 @@ class VirtueMartTestConnector: sale_order = sale_order_list[0].getObject() #LOG("Viewing sale_order", INFO, "sale_order: %s" %(sale_order)) if not kw.has_key('sale_order_line_id'): - raise ValueError, "No parameter sale_order_line_id given, got %s / %s" %(args, kw) + raise ValueError("No parameter sale_order_line_id given, got %s / %s" %(args, kw)) sale_order_line_id = kw['sale_order_line_id'] # retrieve the resource from the test module resource_list = sale_order.searchFolder(id=sale_order_line_id, validation_state="validated", diff --git a/bt5/erp5_tiosafe_virtuemart_test/TestTemplateItem/testVirtuemartSynchronization.py b/bt5/erp5_tiosafe_virtuemart_test/TestTemplateItem/testVirtuemartSynchronization.py index d91a6e2024bd8de1ca3c2219b6ad28b39eccc416..57dd0cb478152214355a2975faa3e5216ecfc874 100644 --- a/bt5/erp5_tiosafe_virtuemart_test/TestTemplateItem/testVirtuemartSynchronization.py +++ b/bt5/erp5_tiosafe_virtuemart_test/TestTemplateItem/testVirtuemartSynchronization.py @@ -420,7 +420,7 @@ class TestVirtuemartSynchronization(ERP5TypeTestCase): self.assertEqual(test_person.getZip(), default_address.getZipCode()) self.assertEqual(test_person.getCity(), default_address.getCity()) else: - raise ValueError, 'bad type' + raise ValueError('bad type') mapping_dict = {} diff --git a/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ERP5DeliveredNodeConduit.py b/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ERP5DeliveredNodeConduit.py index 81ba642906ad9e2678f60ee7de142e1a406645b8..f3842b54bedf20c66dd87421110fbdfc0c840a17 100644 --- a/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ERP5DeliveredNodeConduit.py +++ b/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ERP5DeliveredNodeConduit.py @@ -40,7 +40,7 @@ class ERP5DeliveredNodeConduit(ERP5NodeConduit): stc = object.getPortalObject().sale_trade_condition_module.newContent(title="%s %s" %(site.getReference(), object.getTitle()), specialise=default_stc, destination=object.getRelativeUrl(), - version=001) + version='001') stc.validate() def _updateSaleTradeCondition(self, object, **kw): @@ -56,7 +56,7 @@ class ERP5DeliveredNodeConduit(ERP5NodeConduit): if len(stc_list) == 0: self._createSaleTradeCondition(object, **kw) elif len(stc_list) > 1: - raise ValueError, "Multiple trade condition (%s) retrieve for %s" %([x.path for x in stc_list], object.getTitle()) + raise ValueError("Multiple trade condition (%s) retrieve for %s" %([x.path for x in stc_list], object.getTitle())) else: stc = stc_list[0].getObject() stc.edit(destination=object.getRelativeUrl(),) diff --git a/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ERP5InvoicedNodeConduit.py b/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ERP5InvoicedNodeConduit.py index 765272cf652c6deaa0f3a4474384b2f3ecf9eb8e..a3296c00d730ccc1b3ffa4500e7e24a3667a7694 100644 --- a/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ERP5InvoicedNodeConduit.py +++ b/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ERP5InvoicedNodeConduit.py @@ -42,7 +42,7 @@ class ERP5InvoicedNodeConduit(ERP5NodeConduit): specialise=default_stc, destination_decision=object.getRelativeUrl(), destination_administration=object.getRelativeUrl(), - version=001) + version='001') stc.validate() def _updateSaleTradeCondition(self, object, **kw): @@ -58,7 +58,7 @@ class ERP5InvoicedNodeConduit(ERP5NodeConduit): if len(stc_list) == 0: self._createSaleTradeCondition(object, **kw) elif len(stc_list) > 1: - raise ValueError, "Multiple trade condition (%s) retrieve for %s" %([x.path for x in stc_list], object.getTitle()) + raise ValueError("Multiple trade condition (%s) retrieve for %s" %([x.path for x in stc_list], object.getTitle())) else: stc = stc_list[0].getObject() stc.edit(destination_decision=object.getRelativeUrl(), diff --git a/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartBrain.py b/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartBrain.py index dd06b0126ef1b111d23b63b024fa065054b58c1f..ef05546bdcfce739326c00d3bed094b46a975599 100644 --- a/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartBrain.py +++ b/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartBrain.py @@ -52,7 +52,7 @@ class ZencartNode(NodeBrain): category = 'Country/%s' % self.country, create_mapping=True, create_mapping_line=True, ).split('/', 1)[-1] - except ValueError, msg: + except ValueError as msg: LOG("ZencartBrain.ZencartNode.__init__", ERROR, "Getting category for %s raise with msg = %s" %(self.country, msg)) self.country = "" @@ -91,7 +91,7 @@ class ZencartNode(NodeBrain): create_mapping_line=True, ) value = "/".join(value.split('/')[1:]) - except ValueError, msg: + except ValueError as msg: LOG("ZencartBrain.ZencartNode._generateCoordinatesXML", ERROR, "Getting category for %s raise with msg = %s" %(value, msg)) #return "" diff --git a/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartNodeConduit.py b/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartNodeConduit.py index 923484a5e1fc8008901de89072ecb71c2fe4d882..f82e4efedb3dfb10482291673f344f4cf0558ca7 100644 --- a/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartNodeConduit.py +++ b/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartNodeConduit.py @@ -178,9 +178,9 @@ class ZencartNodeConduit(TioSafeNodeConduit): try: previous_value = previous_xml[0].text except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) if previous_value is None: previous_value = "" diff --git a/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartResourceConduit.py b/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartResourceConduit.py index 8e8e9ef4a39fa3cf076c9a82fa34b0295417a8d5..877d8161d33c78450ce718dc9e0e768be41ec0e8 100644 --- a/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartResourceConduit.py +++ b/bt5/erp5_tiosafe_zencart/ExtensionTemplateItem/ZencartResourceConduit.py @@ -82,7 +82,7 @@ class ZencartResourceConduit(TioSafeResourceConduit): if create_method is not None: create_result = create_method(**keyword) 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(),)) new_id = object.IntegrationSite_lastID(type='Product')[0].getId() @@ -119,7 +119,7 @@ class ZencartResourceConduit(TioSafeResourceConduit): if delete_method is not None: return delete_method(product_id=object_id) 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): @@ -138,9 +138,9 @@ class ZencartResourceConduit(TioSafeResourceConduit): try: previous_value = previous_xml[0].text except IndexError: - raise ValueError, 'Too little or too many value, only one is required for %s' % ( + raise ValueError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) if isinstance(previous_value, unicode): previous_value = previous_value.encode('utf-8') @@ -206,9 +206,9 @@ class ZencartResourceConduit(TioSafeResourceConduit): previous_xml[0].text.encode('utf-8'), ) except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) # retrieve the current value to check if exists a conflict current_value = etree.XML(document.asXML()).xpath(tag)[0].text diff --git a/bt5/erp5_travel_expense/SkinTemplateItem/portal_skins/erp5_hr_request/ExpenseValidationRequest_createPurchaseTransaction.py b/bt5/erp5_travel_expense/SkinTemplateItem/portal_skins/erp5_hr_request/ExpenseValidationRequest_createPurchaseTransaction.py index 1ecd972d45b16eecab4979e8b4586a33c0be9c33..3829f95b0f2065c89b9451cffc4e1155e26291c9 100644 --- a/bt5/erp5_travel_expense/SkinTemplateItem/portal_skins/erp5_hr_request/ExpenseValidationRequest_createPurchaseTransaction.py +++ b/bt5/erp5_travel_expense/SkinTemplateItem/portal_skins/erp5_hr_request/ExpenseValidationRequest_createPurchaseTransaction.py @@ -43,7 +43,7 @@ from Products.DCWorkflow.DCWorkflow import ValidationFailed from zExceptions import Redirect try: transaction.Base_checkConsistency() -except ValidationFailed, error_message: +except ValidationFailed as error_message: if getattr(error_message, 'msg', None): # use of Message class to store message+mapping+domain message = error_message.msg @@ -56,10 +56,10 @@ except ValidationFailed, error_message: if len(message) > 2000: # too long message will generate a too long URI # that would become an error. message = "%s ..." % message[:(2000 - 4)] - raise Redirect, "%s?portal_status_message=%s" % ( + raise Redirect("%s?portal_status_message=%s" % ( context.getAbsoluteUrl(), message - ) + )) transaction.confirm() return transaction.getRelativeUrl() diff --git a/bt5/erp5_ui_test_core/ExtensionTemplateItem/portal_components/extension.erp5.ERP5Zuite.py b/bt5/erp5_ui_test_core/ExtensionTemplateItem/portal_components/extension.erp5.ERP5Zuite.py index 83878e044da9d4d5aef00e760ddc12a602ca6317..28b2822fb910f96d6975e0972167a84d29e62454 100644 --- a/bt5/erp5_ui_test_core/ExtensionTemplateItem/portal_components/extension.erp5.ERP5Zuite.py +++ b/bt5/erp5_ui_test_core/ExtensionTemplateItem/portal_components/extension.erp5.ERP5Zuite.py @@ -27,7 +27,7 @@ def urlread(url, safe_return=0): import urllib try: return urllib.urlopen(url).read() - except IOError, e: + except IOError as e: if safe_return: # Return an Selenium test code that will obviously fail. This # prevent zelenium test run get Stalled. diff --git a/bt5/erp5_upgrader/ExtensionTemplateItem/portal_components/extension.erp5.ERP5UpgraderCompatibility.py b/bt5/erp5_upgrader/ExtensionTemplateItem/portal_components/extension.erp5.ERP5UpgraderCompatibility.py index aae2a21d5c6b4ed3aed341b9eaacb64cf550e7f9..4e663e0b521631178da1be8541550e90bb04477d 100644 --- a/bt5/erp5_upgrader/ExtensionTemplateItem/portal_components/extension.erp5.ERP5UpgraderCompatibility.py +++ b/bt5/erp5_upgrader/ExtensionTemplateItem/portal_components/extension.erp5.ERP5UpgraderCompatibility.py @@ -76,6 +76,6 @@ def _getZopeConfigurationFile(relative_path="", mode="r"): instance_home = getConfiguration().instancehome file_path = os.path.join(instance_home, relative_path) if not os.path.exists(file_path): - raise IOError, 'The file: %s does not exist.' % file_path + raise IOError('The file: %s does not exist.' % file_path) return open(file_path, mode) diff --git a/bt5/erp5_upgrader/ExtensionTemplateItem/portal_components/extension.erp5.ERP5UpgraderUtils.py b/bt5/erp5_upgrader/ExtensionTemplateItem/portal_components/extension.erp5.ERP5UpgraderUtils.py index 4ecc288ca42a899c4a431aa354999c7a4944679c..36dcc089ea607944d913387acb7ad96d69cdc0e1 100644 --- a/bt5/erp5_upgrader/ExtensionTemplateItem/portal_components/extension.erp5.ERP5UpgraderUtils.py +++ b/bt5/erp5_upgrader/ExtensionTemplateItem/portal_components/extension.erp5.ERP5UpgraderUtils.py @@ -90,7 +90,7 @@ def ERP5Site_runVerificationScript(self, method_id): return 'Script %s was not Found!' % (method_id) try: integrity_result = method() - except Exception, e: + except Exception as e: # Is it required include the trace back return 'Script %s fail to run, Exception: %s , message: %s .' % (method_id, e.__class__, e ) if len(integrity_result) > 0: diff --git a/bt5/erp5_user_tutorial_ui_test/SkinTemplateItem/portal_skins/erp5_user_tutorial_ui_test/Zuite_checkPortalCatalog.py b/bt5/erp5_user_tutorial_ui_test/SkinTemplateItem/portal_skins/erp5_user_tutorial_ui_test/Zuite_checkPortalCatalog.py index 4a5f6d4642e26d51281990d4ffe107e0c0b7ec20..5a6e09412b5b81b3539aa4b29e60ebaed6ca032f 100644 --- a/bt5/erp5_user_tutorial_ui_test/SkinTemplateItem/portal_skins/erp5_user_tutorial_ui_test/Zuite_checkPortalCatalog.py +++ b/bt5/erp5_user_tutorial_ui_test/SkinTemplateItem/portal_skins/erp5_user_tutorial_ui_test/Zuite_checkPortalCatalog.py @@ -16,11 +16,11 @@ for result in result_list: method_name = 'get%s' % (''.join([x.capitalize() for x in key.split('_')])) method = getattr(object, method_name) if strict_check_mode and method() != kw[key]: - 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 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" % \ - (object.getTitle(), object.Base_getOwnerId(), owner_id) + 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)) if strict_check_mode and max_count is not None: if len(result_list) <= max_count: @@ -29,7 +29,7 @@ if strict_check_mode and max_count is not None: else: return result_list else: - raise RuntimeError, 'The catalog return more item that you ask.' + raise RuntimeError('The catalog return more item that you ask.') if len(result_list) == 0: return None diff --git a/bt5/erp5_web/DocumentTemplateItem/portal_components/document.erp5.StaticWebSection.py b/bt5/erp5_web/DocumentTemplateItem/portal_components/document.erp5.StaticWebSection.py index c23778f04afe4c370c6cbec75cf922f6d216bdd5..9e3f772043e56a9a1bbb75511c238ecc525b4d7b 100644 --- a/bt5/erp5_web/DocumentTemplateItem/portal_components/document.erp5.StaticWebSection.py +++ b/bt5/erp5_web/DocumentTemplateItem/portal_components/document.erp5.StaticWebSection.py @@ -98,7 +98,7 @@ class StaticWebSection(WebSection): try: request.RESPONSE.notFoundError("%s\n%s" % (name, method)) except AttributeError: - raise KeyError, name + raise KeyError(name) security.declareProtected(Permissions.View, '__bobo_traverse__') diff --git a/bt5/erp5_web/SkinTemplateItem/portal_skins/erp5_web_widget_library/WebSite_registerUser.py b/bt5/erp5_web/SkinTemplateItem/portal_skins/erp5_web_widget_library/WebSite_registerUser.py index 197612bfc34d1dbe6f36297f44528a629aecaf14..39de351477e8a69da46c935eac13f930fea616b8 100644 --- a/bt5/erp5_web/SkinTemplateItem/portal_skins/erp5_web_widget_library/WebSite_registerUser.py +++ b/bt5/erp5_web/SkinTemplateItem/portal_skins/erp5_web_widget_library/WebSite_registerUser.py @@ -36,7 +36,7 @@ try: user = context.WebSite_createUser(**kwargs) log(user) msg = 'Thank you for registering. Your password will be sent to the email address that you provided once your account has been validated by the appropriate department.' -except Exception, e: +except Exception as e: msg = str(e) return req.RESPONSE.redirect(context.absolute_url() + '?portal_status_message='+msg) diff --git a/bt5/erp5_web_service/DocumentTemplateItem/portal_components/document.erp5.FTPConnector.py b/bt5/erp5_web_service/DocumentTemplateItem/portal_components/document.erp5.FTPConnector.py index 4f1787aac9a627f9a7f62b9658a743daa4430aff..99c874c3fee3c2d765a569425327e1769b58286d 100644 --- a/bt5/erp5_web_service/DocumentTemplateItem/portal_components/document.erp5.FTPConnector.py +++ b/bt5/erp5_web_service/DocumentTemplateItem/portal_components/document.erp5.FTPConnector.py @@ -113,7 +113,7 @@ class FTPConnector(XMLObject): finally: conn.logout() - def createDirectory(self, path, mode=0777): + def createDirectory(self, path, mode=0o777): """Create a directory `path`, with file mode `mode`. The directory is created immediatly, even if transaction is aborted. diff --git a/bt5/erp5_wizard/SkinTemplateItem/portal_skins/erp5_wizard/Person_createNewGlobalUserAccount.py b/bt5/erp5_wizard/SkinTemplateItem/portal_skins/erp5_wizard/Person_createNewGlobalUserAccount.py index 4d4d323ee99b2fba49b9f30418869c139e672743..55d03ee515bc9cdbe032c6d7092a0d50c85a24a0 100644 --- a/bt5/erp5_wizard/SkinTemplateItem/portal_skins/erp5_wizard/Person_createNewGlobalUserAccount.py +++ b/bt5/erp5_wizard/SkinTemplateItem/portal_skins/erp5_wizard/Person_createNewGlobalUserAccount.py @@ -17,4 +17,4 @@ if portal.Base_validatePersonReference(kw['reference'], context.REQUEST): **kw) else: # user reference is NOT unique (valid) in Nexedi ERP5 - raise ValueError, "User reference not unique" + raise ValueError("User reference not unique") diff --git a/bt5/erp5_wizard/SkinTemplateItem/portal_skins/erp5_wizard/Person_synchroniseExistingAccountWithInstance.py b/bt5/erp5_wizard/SkinTemplateItem/portal_skins/erp5_wizard/Person_synchroniseExistingAccountWithInstance.py index e8deebfccb272e1d91d9510361b6378b9c634db1..f9da79c29fc91df39228cf4fafb135b67da3c877 100644 --- a/bt5/erp5_wizard/SkinTemplateItem/portal_skins/erp5_wizard/Person_synchroniseExistingAccountWithInstance.py +++ b/bt5/erp5_wizard/SkinTemplateItem/portal_skins/erp5_wizard/Person_synchroniseExistingAccountWithInstance.py @@ -14,4 +14,4 @@ if portal.WizardTool_isPersonReferencePresent(kw['reference']): ignore_exceptions = 0, **kw) else: - raise ValueError, "User does not exist yet" + raise ValueError("User does not exist yet") diff --git a/bt5/erp5_xhtml_gadget_style/SkinTemplateItem/portal_skins/erp5_xhtml_gadget_core/Form_save.py b/bt5/erp5_xhtml_gadget_style/SkinTemplateItem/portal_skins/erp5_xhtml_gadget_core/Form_save.py index 1d737b12835328b53eec38a59f5fb655617b607b..8198e79fa5a320604e3f37ec0a063a0b3f480fa0 100644 --- a/bt5/erp5_xhtml_gadget_style/SkinTemplateItem/portal_skins/erp5_xhtml_gadget_core/Form_save.py +++ b/bt5/erp5_xhtml_gadget_style/SkinTemplateItem/portal_skins/erp5_xhtml_gadget_core/Form_save.py @@ -18,7 +18,7 @@ edit_order = form.edit_order try: # Validate form.validate_all_to_request(request, key_prefix=key_prefix) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request result = {} result['field_errors'] = {} diff --git a/erp5/util/benchmark/report.py b/erp5/util/benchmark/report.py index 9fc12c0e94d05e5fdd61b21161d74c463b3082ce..289178a98661a136e6f127380f7d9e0b79b74a71 100755 --- a/erp5/util/benchmark/report.py +++ b/erp5/util/benchmark/report.py @@ -155,8 +155,8 @@ def computeStatisticFromFilenameList(argument_namespace, filename_list, report_dict['results'].setdefault(stat.full_label, []).append(stat) if row_list != label_list: - raise AssertionError, "ERROR: Result labels: %s != %s" % \ - (label_list, row_list) + raise AssertionError("ERROR: Result labels: %s != %s" % \ + (label_list, row_list)) iteration_index = 0 for row_list in reader: diff --git a/erp5/util/testnode/SlapOSControler.py b/erp5/util/testnode/SlapOSControler.py index e70d8751473067db54d36199f81c0ba5c29bb846..0677f9d609a972dbb0bf205a48d28c7e431802a1 100644 --- a/erp5/util/testnode/SlapOSControler.py +++ b/erp5/util/testnode/SlapOSControler.py @@ -278,7 +278,7 @@ class SlapOSControler(object): partition_path = os.path.join(instance_root, partition_reference) if not(os.path.exists(partition_path)): os.mkdir(partition_path) - os.chmod(partition_path, 0750) + os.chmod(partition_path, 0o750) computer.updateConfiguration(xml_marshaller.xml_marshaller.dumps({ 'address': config['ipv4_address'], 'instance_root': instance_root, diff --git a/erp5/util/timinglogparser/__init__.py b/erp5/util/timinglogparser/__init__.py index 1679598c72b8b266310bccaf04cddee27e0237d8..96ac5dfe04880eb3cb7bd5e8c67863e4de723fa4 100755 --- a/erp5/util/timinglogparser/__init__.py +++ b/erp5/util/timinglogparser/__init__.py @@ -185,7 +185,7 @@ for name, value in opts: decimate_count = int(value) if configuration is None: - raise ValueError, '--config is mandatory' + raise ValueError('--config is mandatory') config_file = os.path.splitext(os.path.basename(configuration))[0] config_path = [os.path.dirname(os.path.abspath(configuration))] + sys.path diff --git a/product/CMFActivity/Activity/SQLBase.py b/product/CMFActivity/Activity/SQLBase.py index 600f886ab088bed2aa4209d552380d668c5bb505..ca45e363260f538c8e219c617016e5957daf3006 100644 --- a/product/CMFActivity/Activity/SQLBase.py +++ b/product/CMFActivity/Activity/SQLBase.py @@ -192,8 +192,8 @@ CREATE TABLE %s ( db.query("SET @uid := %s" % getrandbits(UID_SAFE_BITSIZE)) try: db.query(self._insert_template % (self.sql_table, values)) - except MySQLdb.IntegrityError, (code, _): - if code != DUP_ENTRY: + except MySQLdb.IntegrityError as e: + if e.args[0] != DUP_ENTRY: raise reset_uid = True else: diff --git a/product/CMFActivity/Activity/SQLJoblib.py b/product/CMFActivity/Activity/SQLJoblib.py index fd308bcaa3aa6419c62cb580cc8292597c91b3d1..3531e6cbcdb4b2f8544d3f821ddd17ef9d2eef5e 100644 --- a/product/CMFActivity/Activity/SQLJoblib.py +++ b/product/CMFActivity/Activity/SQLJoblib.py @@ -93,8 +93,8 @@ CREATE TABLE %s ( db.query("SET @uid := %s" % getrandbits(UID_SAFE_BITSIZE)) try: db.query(self._insert_template % (self.sql_table, values)) - except MySQLdb.IntegrityError, (code, _): - if code != DUP_ENTRY: + except MySQLdb.IntegrityError as e: + if e.args[0] != DUP_ENTRY: raise reset_uid = True else: diff --git a/product/CMFActivity/ActivityTool.py b/product/CMFActivity/ActivityTool.py index 33a17a36e3832829f9653bf15b5e3f51117ed93a..b87f10e64d8006508c8af9a75ff8a2bfe2567239 100644 --- a/product/CMFActivity/ActivityTool.py +++ b/product/CMFActivity/ActivityTool.py @@ -406,7 +406,7 @@ Named Parameters: %r mail_text += '\nCreated at:\n' + self.call_traceback try: portal.MailHost.send(mail_text) - except (socket.error, MailHostError), message: + except (socket.error, MailHostError) as message: LOG('ActivityTool.notifyUser', WARNING, 'Mail containing failure information failed to be sent: %s' % message) @@ -460,7 +460,7 @@ Named Parameters: %r if exc_info[0] is None: # Raise a dummy exception, ignore it, fetch it and use it as if it was the error causing message non-execution. This will help identifyting the cause of this misbehaviour. try: - raise Exception, 'Message execution failed, but there is no exception to explain it. This is a dummy exception so that one can track down why we end up here outside of an exception handling code path.' + raise Exception('Message execution failed, but there is no exception to explain it. This is a dummy exception so that one can track down why we end up here outside of an exception handling code path.') except Exception: exc_info = sys.exc_info() elif exc_info[0] is SkippedMessage: @@ -1104,7 +1104,7 @@ class ActivityTool (BaseTool): active_threads += 1 else: tic_lock.release() - raise RuntimeError, 'Too many threads' + raise RuntimeError('Too many threads') tic_lock.release() inner_self = aq_inner(self) diff --git a/product/CMFActivity/sbalance.py b/product/CMFActivity/sbalance.py index 4044a3ca34f95fe5a010edc1b60aca58859f3312..9ad1edf07fe33135498a6517ebdb9aeeb7594961 100644 --- a/product/CMFActivity/sbalance.py +++ b/product/CMFActivity/sbalance.py @@ -34,7 +34,7 @@ from select import select import re if not hasattr(socket, 'setdefaulttimeout'): - raise RuntimeError, 'Your Python interpreter is too old. Please upgrade it.' + raise RuntimeError('Your Python interpreter is too old. Please upgrade it.') class ClientInfo: pass @@ -306,7 +306,7 @@ def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hvb:t:T:dfps", ["help", "version", "bind=", "connect-timeout=", "select-timeout=", "debug", "foreground", "packet-dump", "sticky"]) - except getopt.GetoptError, msg: + except getopt.GetoptError as msg: print msg print "Try ``sbalance --help'' for more information." sys.exit(2) diff --git a/product/CMFCategory/tests/testCMFCategory.py b/product/CMFCategory/tests/testCMFCategory.py index 707e65bc15534a18dcdf07fee42ce81afc819b4c..88ebad5dd6f54071424f9eb1bbe64890857ed9de 100644 --- a/product/CMFCategory/tests/testCMFCategory.py +++ b/product/CMFCategory/tests/testCMFCategory.py @@ -809,7 +809,7 @@ class TestCMFCategory(ERP5TypeTestCase): try: p1.setCareerSubordination(o1) - except Exception, e: + except Exception as e: self.assertTrue(isinstance(e, TypeError)) self.assertEqual(e.args[0], 'Category must be of string, tuple of ' 'string or list of string type.') diff --git a/product/ERP5/Capacity/GLPK.py b/product/ERP5/Capacity/GLPK.py index 2f4c2a9f33a2ba34f5358a99aa9be7ba996ed94c..8a5ef33e5d5937d617ba04331840476be1768f8e 100644 --- a/product/ERP5/Capacity/GLPK.py +++ b/product/ERP5/Capacity/GLPK.py @@ -116,7 +116,7 @@ def getOptimalValue(file): glpk.glp_lpx_set_real_parm(lp, glpk.LPX_K_TMLIM, 2000) # XXX ret = glpk.glp_lpx_simplex(lp) if ret != glpk.LPX_E_OK: - raise RuntimeError, "The simplex method of GLPK failed" + raise RuntimeError("The simplex method of GLPK failed") return glpk.glp_lpx_get_obj_val(lp) finally: glpk.glp_lpx_delete_prob(lp) @@ -128,7 +128,7 @@ def solve(matrix, point): import tempfile import os if shape(point)[0] != shape(matrix)[1]: - raise TypeError, "The argument 'point' has a different number of dimensions from the capacity" + raise TypeError("The argument 'point' has a different number of dimensions from the capacity") mod_name = tempfile.mktemp(suffix='.mod') mod = file(mod_name, 'w') try: diff --git a/product/ERP5/Document/Agent.py b/product/ERP5/Document/Agent.py index 6062998b8a9d801707b18296b973f6bac30d2ecf..cb8efb63cf8aaf47e17631bc2696c04821d0cab4 100644 --- a/product/ERP5/Document/Agent.py +++ b/product/ERP5/Document/Agent.py @@ -80,7 +80,7 @@ class Agent(Folder, Image): % self.absolute_url()) return 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) self.manage_upload(file=import_file) diff --git a/product/ERP5/Document/Amount.py b/product/ERP5/Document/Amount.py index d195d8fcbd81147a218d87492803368446dc6711..0110ba9df9943902105378c14b8f314ba602c076 100644 --- a/product/ERP5/Document/Amount.py +++ b/product/ERP5/Document/Amount.py @@ -302,8 +302,8 @@ class Amount(Base, VariatedMixin): variation_list = [] for property_id, property_value in property_dict.items(): if property_id not in variation_list: - raise KeyError, "Can not set the property variation '%s'" % \ - property_id + raise KeyError("Can not set the property variation '%s'" % \ + property_id) else: try: self.setProperty(property_id, property_value) diff --git a/product/ERP5/Document/BalanceTransaction.py b/product/ERP5/Document/BalanceTransaction.py index 6f544357a25cca87433f770dedf13850d1d21305..84834882507ee33a78d2c72d73f4099ecf25dabc 100644 --- a/product/ERP5/Document/BalanceTransaction.py +++ b/product/ERP5/Document/BalanceTransaction.py @@ -44,24 +44,24 @@ class InventoryKey(UserDict): self.data.update(kw) def clear(self): - raise TypeError, 'InventoryKey are immutable' + raise TypeError('InventoryKey are immutable') def pop(self, keys, *args): - raise TypeError, 'InventoryKey are immutable' + raise TypeError('InventoryKey are immutable') def update(self, dict=None, **kwargs): - raise TypeError, 'InventoryKey are immutable' + raise TypeError('InventoryKey are immutable') def __delitem__(self, key): - raise TypeError, 'InventoryKey are immutable' + raise TypeError('InventoryKey are immutable') def __setitem__(self, key, item): - raise TypeError, 'InventoryKey are immutable' + raise TypeError('InventoryKey are immutable') def setdefault(self, key, failobj=None): if key in self.data: return self.data[key] - raise TypeError, 'InventoryKey are immutable' + raise TypeError('InventoryKey are immutable') def __hash__(self): return hash(tuple(self.items())) @@ -162,7 +162,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): for movement in self._getGroupByNodeMovementList(): node_uid = movement.getDestinationUid() if not node_uid: - raise ValueError, "No destination uid for %s" % movement + raise ValueError("No destination uid for %s" % movement) resource_uid = movement.getResourceUid() stock_list = current_stock.setdefault( @@ -188,7 +188,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): for movement in self._getGroupByMirrorSectionMovementList(): node_uid = movement.getDestinationUid() 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() resource_uid = movement.getResourceUid() @@ -219,7 +219,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): for movement in self._getGroupByPaymentMovementList(): node_uid = movement.getDestinationUid() if not node_uid: - raise ValueError, "No destination uid for %s" % movement + raise ValueError("No destination uid for %s" % movement) payment_uid = movement.getDestinationPaymentUid() resource_uid = movement.getResourceUid() @@ -258,7 +258,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): for movement in self._getGroupByNodeMovementList(): node_uid = movement.getDestinationUid() if not node_uid: - raise ValueError, "No destination uid for %s" % movement + raise ValueError("No destination uid for %s" % movement) section_uid = movement.getDestinationSectionUid() stock_list = new_stock.setdefault( @@ -280,7 +280,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): for movement in self._getGroupByMirrorSectionMovementList(): node_uid = movement.getDestinationUid() if not node_uid: - raise ValueError, "No destination uid for %s" % movement + raise ValueError("No destination uid for %s" % movement) section_uid = movement.getDestinationSectionUid() mirror_section_uid = movement.getSourceSectionUid() @@ -305,7 +305,7 @@ class BalanceTransaction(AccountingTransaction, Inventory): for movement in self._getGroupByPaymentMovementList(): node_uid = movement.getDestinationUid() if not node_uid: - raise ValueError, "No destination uid for %s" % movement + raise ValueError("No destination uid for %s" % movement) section_uid = movement.getDestinationSectionUid() payment_uid = movement.getDestinationPaymentUid() diff --git a/product/ERP5/Document/BigFile.py b/product/ERP5/Document/BigFile.py index 977b3e1f1053d98534e8360a879aea58d4fd21b9..7c40312ceabfe9425b31fae0d19b8c52c68a7057 100644 --- a/product/ERP5/Document/BigFile.py +++ b/product/ERP5/Document/BigFile.py @@ -116,7 +116,7 @@ class BigFile(File): file = StringIO(file) if isinstance(file, FileUpload) and not file: - raise ValueError, 'File not specified' + raise ValueError('File not specified') seek=file.seek read=file.read diff --git a/product/ERP5/Document/BusinessTemplate.py b/product/ERP5/Document/BusinessTemplate.py index d86d3c5dcb7563adb38b5ae31b7afefbadae11e1..0d86a18739cb8629d179cd6a2055f12fa60cb3cd 100644 --- a/product/ERP5/Document/BusinessTemplate.py +++ b/product/ERP5/Document/BusinessTemplate.py @@ -570,7 +570,7 @@ class BaseTemplateItem(Implicit, Persistent): else: # As the list of available actions is not strictly defined, # prevent mistake if an action is not handled - raise ValueError, 'Unknown action "%s"' % action + raise ValueError('Unknown action "%s"' % action) def trash(self, context, new_item, **kw): @@ -986,11 +986,11 @@ class ObjectTemplateItem(BaseTemplateItem): try: obj = p.unrestrictedTraverse(relative_url) except ValueError: - raise ValueError, "Can not access to %s" % relative_url + raise ValueError("Can not access to %s" % relative_url) try: obj = obj._getCopy(context) except AttributeError: - raise AttributeError, "Could not find object '%s' during business template processing." % relative_url + raise AttributeError("Could not find object '%s' during business template processing." % relative_url) _recursiveRemoveUid(obj) obj = self.removeProperties(obj, 1, self.isKeepWorkflowObject(relative_url), @@ -1098,7 +1098,7 @@ class ObjectTemplateItem(BaseTemplateItem): try: OFS.XMLExportImport.exportXML(old_object._p_jar, old_object._p_oid, old_io) old_obj_xml = old_io.getvalue() - except (ImportError, UnicodeDecodeError), e: # module is already + except (ImportError, UnicodeDecodeError) as e: # module is already # removed etc. old_obj_xml = '(%s: %s)' % (e.__class__.__name__, e) new_io.close() @@ -1141,7 +1141,7 @@ class ObjectTemplateItem(BaseTemplateItem): else: # As the list of available actions is not strictly defined, # prevent mistake if an action is not handled - raise NotImplementedError, 'Unknown action "%s"' % action + raise NotImplementedError('Unknown action "%s"' % action) return p.portal_trash.backupObject(trashbin, container_path, object_id, save=save, **kw) @@ -1716,7 +1716,7 @@ class PathTemplateItem(ObjectTemplateItem): # If the id has no meta character, do not have to check all objects. obj = folder._getOb(id, None) if obj is None: - raise AttributeError, "Could not resolve '%s' during business template processing." % id + raise AttributeError("Could not resolve '%s' during business template processing." % id) return self._resolvePath(obj, relative_url_list + [id], id_list[1:]) path_list = [] for object_id in fnmatch.filter(folder.objectIds(), id): @@ -1769,7 +1769,7 @@ class PathTemplateItem(ObjectTemplateItem): # Ignore any object without PortalType (non-ERP5 objects) try: portal_type = aq_base(obj).getPortalType() - except Exception, e: + except Exception as e: pass else: if portal_type not in p.portal_types: @@ -1921,7 +1921,7 @@ class CategoryTemplateItem(ObjectTemplateItem): if self.is_bt_for_diff: continue else: - raise ValueError, "%s not found" % relative_url + raise ValueError("%s not found" % relative_url) _recursiveRemoveUid(obj) obj = self.removeProperties(obj, 1, self.isKeepWorkflowObject(relative_url), @@ -2019,8 +2019,8 @@ class RegisteredSkinSelectionTemplateItem(BaseTemplateItem): if skin_selection_id in selection_list: self._objects.setdefault(skin_folder_id, []).append(skin_selection_id) else: - raise NotFound, 'No skin selection %s found for skin folder %s.' \ - % (skin_selection_id, skin_folder_id) + raise NotFound('No skin selection %s found for skin folder %s.' \ + % (skin_selection_id, skin_folder_id)) # Function to generate XML Code Manually def generateXml(self, path=None): @@ -2500,9 +2500,9 @@ class PortalTypeWorkflowChainTemplateItem(BaseTemplateItem): 'in chain for portal_type %s' % (workflow_name, portal_type)) self._objects.setdefault(portal_type, []).append(workflow) 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. This '\ 'is probably a sign of a missing dependency.'\ - % portal_type + % portal_type) # Function to generate XML Code Manually def generateXml(self, path=None): @@ -2617,8 +2617,8 @@ class PortalTypeWorkflowChainTemplateItem(BaseTemplateItem): # improve the error message for wf_id in self._objects[path]: if wf_id.startswith('-'): - raise ValueError, '"%s" is not a workflow ID for %s' % \ - (wf_id, portal_type) + raise ValueError('"%s" is not a workflow ID for %s' % \ + (wf_id, portal_type)) chain_dict[chain_key] = self._objects[path] else: if context.portal_types.getTypeInfo(portal_type) is None: @@ -2734,7 +2734,7 @@ class PortalTypeAllowedContentTypeTemplateItem(BaseTemplateItem): ob = types_tool.getTypeInfo(portal_type) # check properties corresponds to what is defined in site if ob is None: - raise ValueError, "Portal Type %r not found in site" %(portal_type,) + raise ValueError("Portal Type %r not found in site" %(portal_type,)) prop_value = getattr(ob, self.class_property, ()) if allowed_type in prop_value: if self.class_property not in portal_type: @@ -2743,9 +2743,9 @@ class PortalTypeAllowedContentTypeTemplateItem(BaseTemplateItem): key = portal_type self._objects.setdefault(key, []).append(allowed_type) elif not self.is_bt_for_diff: - raise ValueError, "%s %s not found in portal type %s" % ( + raise ValueError("%s %s not found in portal type %s" % ( getattr(self, 'name', self.__class__.__name__), - allowed_type, portal_type) + allowed_type, portal_type)) # Function to generate XML Code Manually def generateXml(self, path=None): @@ -2838,8 +2838,8 @@ class PortalTypeAllowedContentTypeTemplateItem(BaseTemplateItem): if type_information is None: if not property_list: continue - raise AttributeError, "Portal type '%s' not found while " \ - "installing %s" % (portal_id, self.getTitle()) + raise AttributeError("Portal type '%s' not found while " \ + "installing %s" % (portal_id, self.getTitle())) old_property_list = old_objects.get(key, ()) object_property_list = getattr(type_information, self.class_property, ()) # merge differences between portal types properties @@ -3566,7 +3566,7 @@ class SitePropertyTemplateItem(BaseTemplateItem): else: obj = None if obj is None and not self.is_bt_for_diff: - raise NotFound, 'the property %s is not found' % id + raise NotFound('the property %s is not found' % id) self._objects[id] = (prop_type, obj) def _importFile(self, file_name, file): @@ -3875,7 +3875,7 @@ class FilesystemDocumentTemplateItem(BaseTemplateItem): path, name = posixpath.split(key) try: self.local_file_writer_name(name, text, create=0) - except IOError, error: + except IOError as error: LOG(self.__class__.__name__, WARNING, "Cannot install class %r on file system" % name) if error.errno: @@ -4523,7 +4523,7 @@ class CatalogKeyTemplateItemBase(BaseTemplateItem): if key in catalog_key_list: key_list.append(key) elif not self.is_bt_for_diff: - raise NotFound, '%s %r not found in catalog' %(self.key_title, key) + raise NotFound('%s %r not found in catalog' %(self.key_title, key)) if len(key_list) > 0: self._objects[self.key_list_title] = key_list @@ -5389,7 +5389,7 @@ Business Template is a set of definitions, such as skins, portal types and categ trash_tool = getToolByName(site, 'portal_trash', None) if trash_tool is None: - raise AttributeError, 'Trash Tool is not installed' + raise AttributeError('Trash Tool is not installed') if not force and check_dependencies: self.checkDependencies() @@ -5808,8 +5808,7 @@ Business Template is a set of definitions, such as skins, portal types and categ Export this Business Template """ if self.getBuildingState() != 'built': - raise TemplateConditionError, \ - 'Business Template must be built before export' + raise TemplateConditionError('Business Template must be built before export') return self._export(path, local, bta) def _export(self, path=None, local=0, bta=None): @@ -5934,9 +5933,8 @@ Business Template is a set of definitions, such as skins, portal types and categ """ missing_dep_list = self.getMissingDependencyList() if len(missing_dep_list) != 0: - raise BusinessTemplateMissingDependency, \ - 'Impossible to install %s, please install the following dependencies before: %s' \ - %(self.getTitle(), repr(missing_dep_list)) + raise BusinessTemplateMissingDependency('Impossible to install %s, please install the following dependencies before: %s' \ + %(self.getTitle(), repr(missing_dep_list))) security.declareProtected(Permissions.ManagePortal, 'getMissingDependencyList') def getMissingDependencyList(self): @@ -6268,7 +6266,7 @@ Business Template is a set of definitions, such as skins, portal types and categ """ bt_module_id_list = list(self.getTemplateModuleIdList()) if len(bt_module_id_list) == 0: - raise TemplateConditionError, 'No module defined in business template' + raise TemplateConditionError('No module defined in business template') bt_portal_types_id_list = list(self.getTemplatePortalTypeIdList()) @@ -6530,7 +6528,7 @@ Business Template is a set of definitions, such as skins, portal types and categ temp_obj.getReference(), version, source_reference) - except Exception, e: + except Exception as e: LOG("BusinessTemplate", WARNING, "Could not import component '%s' ('%s') from the filesystem" % (temp_obj.getReference(), diff --git a/product/ERP5/Document/CausalityMovementGroup.py b/product/ERP5/Document/CausalityMovementGroup.py index b02e7004c8cb95b61b87d8fc9bec1266b3da4417..75f3afd1a7d92f9c35820fdaa8ec12ad8aacd7ef 100644 --- a/product/ERP5/Document/CausalityMovementGroup.py +++ b/product/ERP5/Document/CausalityMovementGroup.py @@ -57,7 +57,7 @@ class CausalityMovementGroup(MovementGroup): movement = movement.getParentValue().getParentValue() explanation_value = movement.getExplanationValue() if explanation_value is None: - raise ValueError, 'No explanation for movement %s' % movement.getPath() + raise ValueError('No explanation for movement %s' % movement.getPath()) else: # This is a temp movement explanation_value = None diff --git a/product/ERP5/Document/Coordinate.py b/product/ERP5/Document/Coordinate.py index 5e21e2d8104e3c3e7a7393c5b759246037b37102..9ed018f46ccbb35289cef67b8b2cbafe0cf652cb 100644 --- a/product/ERP5/Document/Coordinate.py +++ b/product/ERP5/Document/Coordinate.py @@ -224,13 +224,13 @@ class Coordinate(Base): self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) if REQUEST.environ['REQUEST_METHOD'] != 'PUT': - raise Forbidden, 'REQUEST_METHOD should be PUT.' + raise Forbidden('REQUEST_METHOD should be PUT.') body = REQUEST.get('BODY', '') try: self._writeFromPUT( body ) RESPONSE.setStatus(204) return RESPONSE - except ResourceLockedError, msg: + except ResourceLockedError as msg: get_transaction().abort() RESPONSE.setStatus(423) return RESPONSE diff --git a/product/ERP5/Document/Document.py b/product/ERP5/Document/Document.py index ca3663eddba1c9e3e21e7bf59cce907ffe754d50..36f8147a6865c2aed49d6b041fe6ee33f92ad49d 100644 --- a/product/ERP5/Document/Document.py +++ b/product/ERP5/Document/Document.py @@ -621,7 +621,7 @@ class Document(DocumentExtensibleTraversableMixin, XMLObject, UrlMixin, if existing_document is not None: document = existing_document if not _checkPermission(Permissions.ModifyPortalContent, existing_document): - raise Unauthorized, "[DMS] You are not allowed to update the existing document which has the same coordinates (id %s)" % existing_document.getId() + raise Unauthorized("[DMS] You are not allowed to update the existing document which has the same coordinates (id %s)" % existing_document.getId()) else: update_kw = {} for k in self.propertyIds(): diff --git a/product/ERP5/Document/IdGenerator.py b/product/ERP5/Document/IdGenerator.py index 5d0910bb601eaedc19443ac27b2f2e2125e5a19e..be76d96119bef8f384f58d1a10807a6e25174bc4 100644 --- a/product/ERP5/Document/IdGenerator.py +++ b/product/ERP5/Document/IdGenerator.py @@ -91,7 +91,7 @@ class IdGenerator(Base): """ # For compatibilty with sql data, must not use id_group as a list if not isinstance(id_group, str): - raise TypeError, 'id_group is not a string' + raise TypeError('id_group is not a string') return self._getLatestSpecialiseValue().generateNewIdList(id_group=id_group, id_count=id_count, default=default) diff --git a/product/ERP5/Document/ImmobilisableItem.py b/product/ERP5/Document/ImmobilisableItem.py index 97b9cd36a137ec581fd7b207dae31b011e7135ef..a3573c7be2992f63d88beb423728b63d82f48268 100644 --- a/product/ERP5/Document/ImmobilisableItem.py +++ b/product/ERP5/Document/ImmobilisableItem.py @@ -169,8 +169,7 @@ class ImmobilisableItem(Item, Amount): # Test immobilisation movement if filter_valid and movement.getImmobilisationState() in ('invalid', 'calculating',): - raise ImmobilisationValidityError, \ - '%s : some preceding movements are still in calculating state' % self.getRelativeUrl() + raise ImmobilisationValidityError('%s : some preceding movements are still in calculating state' % self.getRelativeUrl()) immo_list.append(movement) return immo_list @@ -366,8 +365,7 @@ class ImmobilisableItem(Item, Amount): if section_movement.getStopDate() in date_list and \ section_movement not in section_movement_list and \ section_movement not in immobilisation_list: - raise ImmobilisationCalculationError, \ - "Some movements related to item %s have the same date" % self.getRelativeUrl() + raise ImmobilisationCalculationError("Some movements related to item %s have the same date" % self.getRelativeUrl()) elif section_movement.getStopDate() not in date_list and \ section_movement not in section_movement_list: #The section movement is different from immobilisation movements @@ -949,18 +947,16 @@ class ImmobilisableItem(Item, Amount): LOG('ERP5 Warning :', 0, 'Unable to find the ratio calculation script %s for item %s at date %s' % ( '%s/ratioCalculation' % amortisation_method, self.getRelativeUrl(), repr(at_date))) - raise ImmobilisationCalculationError, \ - 'Unable to find the ratio calculation script %s for item %s at date %s' % ( - '%s/ratioCalculation' % amortisation_method, self.getRelativeUrl(), repr(at_date)) + raise ImmobilisationCalculationError('Unable to find the ratio calculation script %s for item %s at date %s' % ( + '%s/ratioCalculation' % amortisation_method, self.getRelativeUrl(), repr(at_date))) current_ratio = ratio_script(**ratio_params) if current_ratio is None: LOG("ERP5 Warning :",0, "Unable to calculate the ratio during the amortisation calculation on item %s at date %s : script %s returned None" % ( self.getRelativeUrl(), repr(at_date), '%s/ratioCalculation' % amortisation_method)) - raise ImmobilisationCalculationError, \ - "Unable to calculate the ratio during the amortisation calculation on item %s at date %s" % ( - repr(self), repr(at_date)) + raise ImmobilisationCalculationError("Unable to calculate the ratio during the amortisation calculation on item %s at date %s" % ( + repr(self), repr(at_date))) # Calculate the value at the beginning of the annuity annuity_start_price = depreciable_price diff --git a/product/ERP5/Document/PDFDocument.py b/product/ERP5/Document/PDFDocument.py index 69437bdc0eee2564ed38af30d3a923e21a0deea6..9168a999617aaa6262a9851810cb37b2de0d4792 100644 --- a/product/ERP5/Document/PDFDocument.py +++ b/product/ERP5/Document/PDFDocument.py @@ -235,7 +235,7 @@ class PDFDocument(Image): '-noframes', '-i', tmp.name] try: command_result = Popen(command, stdout=PIPE).communicate()[0] - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: raise ConversionError('pdftohtml was not found') raise @@ -264,7 +264,7 @@ class PDFDocument(Image): command = ['pdf2djvu', tmp.name] try: command_result = Popen(command, stdout=PIPE).communicate()[0] - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: raise ConversionError('pdf2djvu was not found') raise @@ -293,7 +293,7 @@ class PDFDocument(Image): command = ['pdfinfo', '-meta', '-box', tmp.name] try: command_result = Popen(command, stdout=PIPE).communicate()[0] - except OSError, e: + except OSError as e: if e.errno == errno.ENOENT: raise ConversionError('pdfinfo was not found') raise diff --git a/product/ERP5/Document/PeriodicityLine.py b/product/ERP5/Document/PeriodicityLine.py index f975e35cc6a4c8926261ec602dcbf52cf03b30bc..6be2fe8bf4eae174b3eef8fb4eb534b570bf75eb 100644 --- a/product/ERP5/Document/PeriodicityLine.py +++ b/product/ERP5/Document/PeriodicityLine.py @@ -54,7 +54,7 @@ class PeriodicityLineMixin(PeriodicityMixin): if scope_type: method = self._getTypeBasedMethod('calculateScopeTypeStopDate') if method is None: - raise RuntimeError, 'Type based method calculateScopeTypeStopDate does not exist.' + raise RuntimeError('Type based method calculateScopeTypeStopDate does not exist.') else: return method(scope_type, start_date) elif time_scale: @@ -62,7 +62,7 @@ class PeriodicityLineMixin(PeriodicityMixin): day = length_number return start_date+day else: - raise RuntimeError, 'Unknown time scale: %s' % time_scale + raise RuntimeError('Unknown time scale: %s' % time_scale) else: return None diff --git a/product/ERP5/Document/Resource.py b/product/ERP5/Document/Resource.py index 6ca3463e1f59d850f4d04b3c65f37ede528e9283..333d26d1fea40fdd3be310d47c0d6ea21f23531c 100644 --- a/product/ERP5/Document/Resource.py +++ b/product/ERP5/Document/Resource.py @@ -804,7 +804,7 @@ class Resource(XMLObject, XMLMatrix, VariatedMixin): try: result = quantity * self._getConversionRatio(from_unit, variation_list)\ / self._getConversionRatio(to_unit, variation_list) - except (ArithmeticError, AttributeError, LookupError, TypeError), error: + except (ArithmeticError, AttributeError, LookupError, TypeError) as error: # For compatibility, we only log the error and return None. # No exception for the moment. LOG('Resource.convertQuantity', WARNING, diff --git a/product/ERP5/Document/SQLNonContinuousIncreasingIdGenerator.py b/product/ERP5/Document/SQLNonContinuousIncreasingIdGenerator.py index 2a41905938d2c3d8330e21845a2894d080416cb2..b82c9f4fed1824304aee7f9a72d1aa86e4aebec8 100644 --- a/product/ERP5/Document/SQLNonContinuousIncreasingIdGenerator.py +++ b/product/ERP5/Document/SQLNonContinuousIncreasingIdGenerator.py @@ -69,7 +69,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): """ # Check the arguments if id_group in (None, 'None'): - raise ValueError, '%s is not a valid group Id.' % (repr(id_group), ) + raise ValueError('%s is not a valid group Id.' % (repr(id_group), )) if default is None: default = 0 @@ -94,7 +94,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): new_id = result_query[0]['LAST_INSERT_ID()'] # Commit the changement of new_id portal.IdTool_zCommit() - except ProgrammingError, error: + except ProgrammingError as error: if error[0] != NO_SUCH_TABLE: raise @@ -173,7 +173,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): portal = self.getPortalObject() try: portal.IdTool_zGetValueList() - except ProgrammingError, error: + except ProgrammingError as error: if error[0] != NO_SUCH_TABLE: raise portal.IdTool_zDropTable() @@ -251,7 +251,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): portal = self.getPortalObject() set_last_id_method = portal.IdTool_zSetLastId if not isinstance(id_dict, dict): - raise TypeError, 'the argument given is not a dictionary' + raise TypeError('the argument given is not a dictionary') new_id_dict = {} for key, value in id_dict.items(): if isinstance(value, int): @@ -259,7 +259,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): # The id must be a ScalarMaxConflictResolver object for the persistent dict new_id_dict[key] = ScalarMaxConflictResolver(value) else: - raise TypeError, 'the value in the dictionary given is not a integer' + raise TypeError('the value in the dictionary given is not a integer') # Update persistent dict if self.getStoredInZodb(): if self.last_max_id_dict is None: diff --git a/product/ERP5/Document/SolverTypeInformation.py b/product/ERP5/Document/SolverTypeInformation.py index 7791d6bcdb1cd889da421ef05fc885aecc132fb4..f809827c644dd2139606caa3ab7f34f8113172c9 100644 --- a/product/ERP5/Document/SolverTypeInformation.py +++ b/product/ERP5/Document/SolverTypeInformation.py @@ -220,7 +220,7 @@ class SolverTypeInformation(Predicate, ERP5TypeInformation): solver_portal_type = portal_type solver = configurable else: - raise NotImplementedError, '%s is not supported for configurable argument' % portal_type + raise NotImplementedError('%s is not supported for configurable argument' % portal_type) method = getattr(solver, method_id) return method() diff --git a/product/ERP5/Document/TextDocument.py b/product/ERP5/Document/TextDocument.py index 86bf743ace855a74c0b22a703211e3dfd350c3c6..d6f09355019df53da47c66b0c236f85a713c5e3a 100644 --- a/product/ERP5/Document/TextDocument.py +++ b/product/ERP5/Document/TextDocument.py @@ -365,7 +365,7 @@ class TextDocument(CachedConvertableMixin, BaseConvertableFileMixin, TextContent # if succeeds, not need to change encoding # it's already utf-8 text_content.decode('utf-8') - except (UnicodeDecodeError, LookupError), error_message: + except (UnicodeDecodeError, LookupError) as error_message: text_content, message = guessCharsetAndConvert(self, text_content, content_type) else: diff --git a/product/ERP5/Document/Url.py b/product/ERP5/Document/Url.py index 62101e5798c68d081774a7e9ef13289f5ff9375d..6f1593a81c307c3ab058f8a6a2c3f4b00793133e 100644 --- a/product/ERP5/Document/Url.py +++ b/product/ERP5/Document/Url.py @@ -134,7 +134,7 @@ class Url(Coordinate, UrlMixin): if to_url is None: to_url = self.getUrlString(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') diff --git a/product/ERP5/Document/VariationEquivalenceTester.py b/product/ERP5/Document/VariationEquivalenceTester.py index d7f67b006887f24c6518a4fcfc51b4802b216126..5ec67e6d334901cfe3bb4d3c45a0b31fea9248d8 100644 --- a/product/ERP5/Document/VariationEquivalenceTester.py +++ b/product/ERP5/Document/VariationEquivalenceTester.py @@ -79,7 +79,7 @@ class VariationEquivalenceTester(Predicate, EquivalenceTesterMixin): sorted(prevision_value.items()) else: # 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: try: # XXX We should use "getTranslatedTestedPropertyTitleList", but it seems to diff --git a/product/ERP5/Document/ZODBContinuousIncreasingIdGenerator.py b/product/ERP5/Document/ZODBContinuousIncreasingIdGenerator.py index bec7e1a565f51b09181900d1b5ae2ffe506624b5..ed1b649ead87295e8f66511a40c33cfaa6cae63f 100644 --- a/product/ERP5/Document/ZODBContinuousIncreasingIdGenerator.py +++ b/product/ERP5/Document/ZODBContinuousIncreasingIdGenerator.py @@ -55,7 +55,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator): persistent. """ if id_group in (None, 'None'): - raise ValueError, '%s is not a valid group Id.' % (repr(id_group), ) + raise ValueError('%s is not a valid group Id.' % (repr(id_group), )) if default is None: default = 0 last_id_dict = getattr(self, 'last_id_dict', None) @@ -144,10 +144,10 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator): if clear: self.clearGenerator() if not isinstance(id_dict, dict): - raise TypeError, 'the argument given is not a dictionary' + raise TypeError('the argument given is not a dictionary') for value in id_dict.values(): if not isinstance(value, (int, long)): - raise TypeError, 'the value given in dictionary is not a integer' + raise TypeError('the value given in dictionary is not a integer') self.last_id_dict.update(id_dict) security.declareProtected(Permissions.ModifyPortalContent, diff --git a/product/ERP5/ERP5Site.py b/product/ERP5/ERP5Site.py index 77e33e7e8a5dc3066aae77c8bcead059109797a1..ac3d014bab52cfd9f64cf5f7dcb5de1ddfcb5cc3 100644 --- a/product/ERP5/ERP5Site.py +++ b/product/ERP5/ERP5Site.py @@ -441,8 +441,8 @@ class ERP5Site(FolderMixIn, CMFSite, CacheCookieMixin): pass else: if portal_activities.countMessage(path=ob.getPath())>0: - raise ActivityPendingError, 'Sorry, pending activities prevent ' \ - + 'changing id at this current stage' + raise ActivityPendingError('Sorry, pending activities prevent ' \ + + 'changing id at this current stage') # Search for categories that have to be updated in sub objects. ob._recursiveSetActivityAfterTag(ob) @@ -1744,9 +1744,9 @@ class ERP5Site(FolderMixIn, CMFSite, CacheCookieMixin): Creates a new content """ if id is None: - raise ValueError, 'The id should not be None' + raise ValueError('The id should not be None') if portal_type is None: - raise ValueError, 'The portal_type should not be None' + raise ValueError('The portal_type should not be None') self.portal_types.constructContent(type_name=portal_type, container=self, id=id, diff --git a/product/ERP5/Extensions/RecodeAllDocuments.py b/product/ERP5/Extensions/RecodeAllDocuments.py index 4d89d59e6741f371815ad0d37f44e7f21bad3ede..184b418426cd00195c2302ad86ff27072b99d440 100644 --- a/product/ERP5/Extensions/RecodeAllDocuments.py +++ b/product/ERP5/Extensions/RecodeAllDocuments.py @@ -42,7 +42,7 @@ def recodeDocumentRecursively(document, dry_run=0): message += 'Recoding %s of %s\n' % (id, document.getRelativeUrl()) if not dry_run: setattr(base, id, tuple(value_list)) else: - raise RuntimeError, 'unknown type of value %r' % value + raise RuntimeError('unknown type of value %r' % value) # Call itself recursively. for object in document.objectValues(): diff --git a/product/ERP5/MovementGroup.py b/product/ERP5/MovementGroup.py index e6be376834774d1f3a50ee496f70a6cef9d12864..7242dc6fafeeabb4e3080295623422a24366f9c0 100644 --- a/product/ERP5/MovementGroup.py +++ b/product/ERP5/MovementGroup.py @@ -186,7 +186,7 @@ class MovementGroupNode: """ movement_list = self.getMovementList() if len(movement_list) != 1: - raise ValueError, "Can separate only 2 movements" + raise ValueError("Can separate only 2 movements") else: old_movement = self.getMovementList()[0] @@ -292,7 +292,7 @@ class FakeMovement: self.append(movement) # This object must not be use when there is not 2 or more movements if len(movement_list) < 2: - raise ValueError, "FakeMovement used where it should not." + raise ValueError("FakeMovement used where it should not.") # All movements must share the same getVariationCategoryList # So, verify and raise a error if not # But, if DeliveryBuilder is well configured, this can never append ;) @@ -303,7 +303,7 @@ class FakeMovement: variation_category_list = movement.getVariationCategoryList() variation_category_list.sort() if variation_category_list != reference_variation_category_list: - raise ValueError, "FakeMovement not well used." + raise ValueError("FakeMovement not well used.") def append(self, movement): """ diff --git a/product/ERP5/NotUsed.py b/product/ERP5/NotUsed.py index bc9ffd00f3c30023bb3a3524d307f4076077bbab..de270da1b190cede05e83865b429303494c267f9 100644 --- a/product/ERP5/NotUsed.py +++ b/product/ERP5/NotUsed.py @@ -41,7 +41,7 @@ def callbase(obj, base, methodname='__init__', args=(), kw={}, raiseIfMissing=No try: method = getattr(base, methodname) except AttributeError: if raiseIfMissing: - raise CallbaseError, methodname + raise CallbaseError(methodname) return None if args is None: args = () return method(obj, *args, **kw) diff --git a/product/ERP5/Tool/CertificateAuthorityTool.py b/product/ERP5/Tool/CertificateAuthorityTool.py index e90b596b6eb28375646b34d77e733329db1b9b5b..2c64fd4c600061c4c1d3b9775d68ecedd7461e9e 100644 --- a/product/ERP5/Tool/CertificateAuthorityTool.py +++ b/product/ERP5/Tool/CertificateAuthorityTool.py @@ -196,7 +196,7 @@ class CertificateAuthorityTool(BaseTool): cert = os.path.join(self.certificate_authority_path, 'certs', new_id + '.crt') try: - os.close(os.open(key, os.O_CREAT | os.O_EXCL, 0600)) + os.close(os.open(key, os.O_CREAT | os.O_EXCL, 0o600)) popenCommunicate([self.openssl_binary, 'req', '-utf8', '-nodes', '-config', self.openssl_config, '-new', '-keyout', key, '-out', csr, '-days', '3650'], '%s\n' % common_name, stdin=subprocess.PIPE) diff --git a/product/ERP5/Tool/ContributionTool.py b/product/ERP5/Tool/ContributionTool.py index ee07def80e4d9a35aba00265544be1ecfe1085d6..3830e9fea5fb756b69686010524f0f20d78ee317 100644 --- a/product/ERP5/Tool/ContributionTool.py +++ b/product/ERP5/Tool/ContributionTool.py @@ -251,7 +251,7 @@ class ContributionTool(BaseTool): if document is not None: # document is already uploaded. So overrides file. if not _checkPermission(Permissions.ModifyPortalContent, document): - raise Unauthorized, "[DMS] You are not allowed to update the existing document which has the same coordinates (id %s)" % document.getId() + raise Unauthorized("[DMS] You are not allowed to update the existing document which has the same coordinates (id %s)" % document.getId()) document.edit(file=kw['file']) return document # Temp objects use the standard newContent from Folder @@ -557,7 +557,7 @@ class ContributionTool(BaseTool): try: url = content.asURL() file_object, filename, content_type = self._openURL(url) - except urllib2.URLError, error: + except urllib2.URLError as error: if repeat == 0 or not batch_mode: # XXX - Call the extendBadURLList method,--NOT Implemented-- raise @@ -606,7 +606,7 @@ class ContributionTool(BaseTool): elif document.getCrawlingDepth() > 0: # If this is an index document, stop crawling if crawling_depth is 0 document.activate().crawlContent() - except urllib2.HTTPError, error: + except urllib2.HTTPError as error: if repeat == 0 or not batch_mode: # here we must call the extendBadURLList method,--NOT Implemented-- # which had to add this url to bad URL list, so next time we avoid diff --git a/product/ERP5/Tool/DomainTool.py b/product/ERP5/Tool/DomainTool.py index 7ed2ea48d13e99caea59db3a8c981f76a2dd3b4e..4a9bac04e927f6b52283908452f3451ebe90f449 100644 --- a/product/ERP5/Tool/DomainTool.py +++ b/product/ERP5/Tool/DomainTool.py @@ -378,7 +378,7 @@ class DomainTool(BaseTool): break else: if domain is _MARKER: return default - raise KeyError, subdomain + raise KeyError(subdomain) return domain InitializeClass(DomainTool) diff --git a/product/ERP5/Tool/IdTool.py b/product/ERP5/Tool/IdTool.py index 53e6368e300e4a2beab54a0c862b637caadedfa1..fe44cf8ad7052ee7a40559eeca161b42795d6758 100644 --- a/product/ERP5/Tool/IdTool.py +++ b/product/ERP5/Tool/IdTool.py @@ -113,7 +113,7 @@ class IdTool(BaseTool): Generate the next id in the sequence of ids of a particular group """ if id_group in (None, 'None'): - raise ValueError, '%s is not a valid id_group' % (repr(id_group), ) + raise ValueError('%s is not a valid id_group' % (repr(id_group), )) # for compatibilty with sql data, must not use id_group as a list if not isinstance(id_group, str): id_group = repr(id_group) @@ -170,7 +170,7 @@ class IdTool(BaseTool): Generate a list of next ids in the sequence of ids of a particular group """ if id_group in (None, 'None'): - raise ValueError, '%s is not a valid id_group' % (repr(id_group), ) + raise ValueError('%s is not a valid id_group' % (repr(id_group), )) # for compatibilty with sql data, must not use id_group as a list if not isinstance(id_group, str): id_group = repr(id_group) @@ -212,9 +212,9 @@ class IdTool(BaseTool): query = getattr(portal_catalog, 'z_portal_ids_generate_id') commit = getattr(portal_catalog, 'z_portal_ids_commit') if None in (query, commit): - raise AttributeError, 'Error while generating Id: ' \ + raise AttributeError('Error while generating Id: ' \ 'idTool_zGenerateId and/or idTool_zCommit could not ' \ - 'be found.' + 'be found.') try: result = query(id_group=id_group, id_count=id_count, default=default) finally: @@ -305,9 +305,9 @@ class IdTool(BaseTool): portal_catalog = getattr(self, 'portal_catalog').getSQLCatalog() query = getattr(portal_catalog, 'z_portal_ids_get_last_id') if query is None: - raise AttributeError, 'Error while getting last Id: ' \ + raise AttributeError('Error while getting last Id: ' \ 'IdTool_zGetLastId could not ' \ - 'be found.' + 'be found.') result = query(id_group=id_group) if len(result): try: diff --git a/product/ERP5/Tool/InotifyTool.py b/product/ERP5/Tool/InotifyTool.py index 7b8ac8d5f14cf6297d0950e7713cd6d085ed710c..72aa1b752eea695e0bfc6bf878cf986c1959dafa 100644 --- a/product/ERP5/Tool/InotifyTool.py +++ b/product/ERP5/Tool/InotifyTool.py @@ -87,7 +87,7 @@ class InotifyTool(TimerServiceMixin, BaseTool): p = os.path.join(inode_path, name) try: s = os.lstat(p) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise else: diff --git a/product/ERP5/Tool/IntrospectionTool.py b/product/ERP5/Tool/IntrospectionTool.py index 3d604feb85fcfcc4973628fc35556e667d814a46..7260365529ffe077454c694b6cd746f8c32f7d8c 100644 --- a/product/ERP5/Tool/IntrospectionTool.py +++ b/product/ERP5/Tool/IntrospectionTool.py @@ -132,11 +132,11 @@ class IntrospectionTool(LogMixin, BaseTool): It should return the local file compacted or not as tar.gz. """ if file_path.startswith('/'): - raise IOError, 'The file path must be relative not absolute' + raise IOError('The file path must be relative not absolute') instance_home = getConfiguration().instancehome 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 + raise IOError('The file: %s does not exist.' % file_path) if compressed: tmp_file_path = tempfile.mktemp(dir=tmp_file_path) @@ -185,7 +185,7 @@ class IntrospectionTool(LogMixin, BaseTool): """ 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 + raise IOError('The file: %s does not exist.' % log_file) char_per_line = 75 diff --git a/product/ERP5/Tool/NotificationTool.py b/product/ERP5/Tool/NotificationTool.py index 15f3a3c8be1bebbab7862f5a46f22d7ff4363e2f..8af4b59a4d32e013ca21e1bcf174f9b19c00b219 100644 --- a/product/ERP5/Tool/NotificationTool.py +++ b/product/ERP5/Tool/NotificationTool.py @@ -71,7 +71,7 @@ def buildAttachmentDictList(document_list, document_type_list=()): if getattr(attachment, 'getContentType', None) is not None: mime_type = attachment.getContentType() else: - raise ValueError, "Cannot find mimetype of the document." + raise ValueError("Cannot find mimetype of the document.") if mime_type is not None: try: @@ -218,7 +218,7 @@ class NotificationTool(BaseTool): portal = self.getPortalObject() mailhost = getattr(portal, 'MailHost', None) if mailhost is None: - raise ValueError, "Can't find MailHost." + raise ValueError("Can't find MailHost.") message = buildEmailMessage(from_url, to_url, msg=body, subject=subject, attachment_list=attachment_list, extra_headers=extra_headers, additional_headers=additional_headers) diff --git a/product/ERP5/Tool/SimulationTool.py b/product/ERP5/Tool/SimulationTool.py index 0667ce4341b0a02e1be34e907a5b3d56e5a02769..22eb71225e90bb2346d3777380309a7bf0c1783d 100644 --- a/product/ERP5/Tool/SimulationTool.py +++ b/product/ERP5/Tool/SimulationTool.py @@ -202,7 +202,7 @@ class SimulationTool(BaseTool): if not as_text: prop_value = category_tool.getCategoryValue(prop) if prop_value is None: - raise ValueError, 'Category %s does not exists' % prop + raise ValueError('Category %s does not exists' % prop) property_uid_list.append(prop_value.getUid()) else: property_uid_list.append(prop) @@ -211,7 +211,7 @@ class SimulationTool(BaseTool): if not as_text: prop_value = category_tool.getCategoryValue(property_item) if prop_value is None: - raise ValueError, 'Category %s does not exists' % property_item + raise ValueError('Category %s does not exists' % property_item) property_uid_list.append(prop_value.getUid()) else: property_uid_list.append(property_item) @@ -223,7 +223,7 @@ class SimulationTool(BaseTool): if not as_text: prop_value = category_tool.getCategoryValue(property_item) if prop_value is None: - raise ValueError, 'Category %s does not exists' % property_item + raise ValueError('Category %s does not exists' % property_item) tmp_uid_list.append(prop_value.getUid()) else: tmp_uid_list.append(property_item) @@ -1142,7 +1142,7 @@ class SimulationTool(BaseTool): total_result = 0.0 if len(result) > 0: if len(result) != 1: - raise ValueError, 'Sorry we must have only one' + raise ValueError('Sorry we must have only one') result = result[0] if hasattr(result, "converted_quantity"): @@ -1420,8 +1420,8 @@ class SimulationTool(BaseTool): inventory_cache_kw['date'] = to_date try: cached_sql_result = Resource_zGetInventoryCacheResult(**inventory_cache_kw) - except ProgrammingError, (code, _): - if code != NO_SUCH_TABLE: + except ProgrammingError as e: + if e.args[0] != NO_SUCH_TABLE: raise # First use of the optimisation, we need to create the table LOG("SimulationTool._getCachedInventoryList", INFO, @@ -2364,7 +2364,7 @@ class SimulationTool(BaseTool): elif resource_aggregation_base_category is None or resource_aggregation_depth is None: # XXX use an appropriate error class # XXX should guess a base category instead of emitting an exception - raise RuntimeError, "The resource '%s' is not found in the capacity, and the argument 'resource_aggregation_base_category' or the argument 'resource_aggregation_depth' is not specified" % resource + raise RuntimeError("The resource '%s' is not found in the capacity, and the argument 'resource_aggregation_base_category' or the argument 'resource_aggregation_depth' is not specified" % resource) else: # It is necessary to aggregate resources, to guess the capacity of this resource. @@ -2458,7 +2458,7 @@ class SimulationTool(BaseTool): if done: break if not done: - raise RuntimeError, "Aggregation failed" + raise RuntimeError("Aggregation failed") # Build a matrix from the capacity item list. # LOG('resource_map', 0, str(resource_map)) @@ -2660,9 +2660,9 @@ class SimulationTool(BaseTool): """ # Sanity checks. if len(delivery_list) == 0: - raise self.MergeDeliveryListError, "No delivery is passed" + raise self.MergeDeliveryListError("No delivery is passed") elif len(delivery_list) == 1: - raise self.MergeDeliveryListError, "Only one delivery is passed" + raise self.MergeDeliveryListError("Only one delivery is passed") main_delivery = delivery_list[0] delivery_list = delivery_list[1:] @@ -2678,15 +2678,14 @@ class SimulationTool(BaseTool): main_value = main_delivery.getProperty(attr) value = delivery.getProperty(attr) if main_value != value: - raise self.MergeDeliveryListError, \ - "%s is not the same between %s and %s (%s and %s)" % (attr, delivery.getId(), main_delivery.getId(), value, main_value) + raise self.MergeDeliveryListError("%s is not the same between %s and %s (%s and %s)" % (attr, delivery.getId(), main_delivery.getId(), value, main_value)) # One more sanity check. Check if discounts are the same, if any. main_discount_list = main_delivery.contentValues(filter = {'portal_type': self.getPortalDiscountTypeList()}) for delivery in delivery_list: discount_list = delivery.contentValues(filter = {'portal_type': self.getPortalDiscountTypeList()}) if len(main_discount_list) != len(discount_list): - raise self.MergeDeliveryListError, "Discount is not the same between %s and %s" % (delivery.getId(), main_delivery.getId()) + raise self.MergeDeliveryListError("Discount is not the same between %s and %s" % (delivery.getId(), main_delivery.getId())) for discount in discount_list: for main_discount in main_discount_list: if discount.getDiscount() == main_discount.getDiscount() \ @@ -2695,14 +2694,14 @@ class SimulationTool(BaseTool): and discount.getImmediateDiscount() == main_discount.getImmediateDiscount(): break else: - raise self.MergeDeliveryListError, "Discount is not the same between %s and %s" % (delivery.getId(), main_delivery.getId()) + raise self.MergeDeliveryListError("Discount is not the same between %s and %s" % (delivery.getId(), main_delivery.getId())) # One more sanity check. Check if payment conditions are the same, if any. main_payment_condition_list = main_delivery.contentValues(filter = {'portal_type': self.getPortalPaymentConditionTypeList()}) for delivery in delivery_list: payment_condition_list = delivery.contentValues(filter = {'portal_type': self.getPortalPaymentConditionTypeList()}) if len(main_payment_condition_list) != len(payment_condition_list): - raise self.MergeDeliveryListError, "Payment Condition is not the same between %s and %s" % (delivery.getId(), main_delivery.getId()) + raise self.MergeDeliveryListError("Payment Condition is not the same between %s and %s" % (delivery.getId(), main_delivery.getId())) for condition in payment_condition_list: for main_condition in main_payment_condition_list: if condition.getPaymentMode() == main_condition.getPaymentMode() \ @@ -2713,7 +2712,7 @@ class SimulationTool(BaseTool): and condition.getPaymentTerm() == main_condition.getPaymentTerm(): break else: - raise self.MergeDeliveryListError, "Payment Condition is not the same between %s and %s" % (delivery.getId(), main_delivery.getId()) + raise self.MergeDeliveryListError("Payment Condition is not the same between %s and %s" % (delivery.getId(), main_delivery.getId())) # Make sure that all activities are flushed, to get simulation movements from delivery cells. for delivery in delivery_list: @@ -2867,9 +2866,9 @@ class SimulationTool(BaseTool): price = cell_price, ) else: - raise self.MergeDeliveryListError, "Unknown portal type %s" % str(object_to_update.getPortalType()) + raise self.MergeDeliveryListError("Unknown portal type %s" % str(object_to_update.getPortalType())) else: - raise self.MergeDeliveryListError, "No object to update" + raise self.MergeDeliveryListError("No object to update") # Merge containers. Just copy them from other deliveries into the main. for delivery in delivery_list: @@ -2935,8 +2934,7 @@ class SimulationTool(BaseTool): """ # XXX For now, consider that from_date and to_date are required if (from_date is None) or (to_date is None): - raise NotImplementedError, \ - "getAvailableTime does not managed yet None values" + raise NotImplementedError("getAvailableTime does not managed yet None values") portal = self.getPortalObject() # Calculate portal_type if portal_type == []: diff --git a/product/ERP5/Tool/TemplateTool.py b/product/ERP5/Tool/TemplateTool.py index d6fd92b5b6596758b796ae3f3e756f4d42d4ee00..e4d9e28230bd67fb467f0a9d5cc6f589790b82b0 100644 --- a/product/ERP5/Tool/TemplateTool.py +++ b/product/ERP5/Tool/TemplateTool.py @@ -413,7 +413,7 @@ class TemplateTool (BaseTool): % (self.absolute_url(), psm)) return else : - raise RuntimeError, 'No file or an empty file was specified' + raise RuntimeError('No file or an empty file was specified') # copy to a temp location import_file.seek(0) #Rewind to the beginning of file tempid, temppath = mkstemp() @@ -628,7 +628,7 @@ class TemplateTool (BaseTool): % (self.absolute_url(), psm)) return else: - raise RuntimeError, 'Invalid repository: %s' % repository + raise RuntimeError('Invalid repository: %s' % repository) try: property_dict_list = [] root = doc.documentElement @@ -736,7 +736,7 @@ class TemplateTool (BaseTool): if diff_version == 0: return True; return False; - raise UnsupportedComparingOperator, 'Unsupported comparing operator: %s'%(operator,) + raise UnsupportedComparingOperator('Unsupported comparing operator: %s'%(operator,)) security.declareProtected(Permissions.AccessContentsInformation, 'IsOneProviderInstalled') @@ -768,7 +768,7 @@ class TemplateTool (BaseTool): for property_dict in property_dict_list: provision_list = property_dict.get('provision_list', []) if title in provision_list: - raise BusinessTemplateIsMeta, 'Business Template %s is provided by another one'%(title,) + raise BusinessTemplateIsMeta('Business Template %s is provided by another one'%(title,)) if title == property_dict['title']: if (version_restriction is None) or (self.compareVersionStrings(property_dict['version'], version_restriction)): if (result is None) or (self.compareVersions(property_dict['version'], result[2]) > 0): @@ -776,7 +776,7 @@ class TemplateTool (BaseTool): if result is not None: return (result[0], result[1]) else: - raise BusinessTemplateUnknownError, 'Business Template %s (%s) could not be found in the repositories'%(title, version_restriction or '') + raise BusinessTemplateUnknownError('Business Template %s (%s) could not be found in the repositories'%(title, version_restriction or '')) security.declareProtected(Permissions.AccessContentsInformation, 'getProviderList') @@ -834,7 +834,7 @@ class TemplateTool (BaseTool): try: bt_dep = self.getLastestBTOnRepos(dependency, version_restriction) except BusinessTemplateUnknownError: - raise BusinessTemplateMissingDependency, 'While analysing %s the following dependency could not be satisfied: %s (%s)\nReason: Business Template could not be found in the repositories'%(bt[1], dependency, version_restriction or '') + raise BusinessTemplateMissingDependency('While analysing %s the following dependency could not be satisfied: %s (%s)\nReason: Business Template could not be found in the repositories'%(bt[1], dependency, version_restriction or '')) except BusinessTemplateIsMeta: provider_list = self.getProviderList(dependency) for provider in provider_list: @@ -849,7 +849,7 @@ class TemplateTool (BaseTool): result_list.append(sub_dep) result_list.append(bt_dep) return result_list - raise BusinessTemplateUnknownError, 'The Business Template %s could not be found on repository %s'%(bt[1], bt[0]) + raise BusinessTemplateUnknownError('The Business Template %s could not be found on repository %s'%(bt[1], bt[0])) return [] security.declareProtected(Permissions.ManagePortal, @@ -864,7 +864,7 @@ class TemplateTool (BaseTool): for repository, id in bt_list: if id.startswith(provider): return (repository, id) - raise BusinessTemplateUnknownError, 'Provider not found in bt_list' + raise BusinessTemplateUnknownError('Provider not found in bt_list') security.declareProtected(Permissions.AccessContentsInformation, 'sortBusinessTemplateList') @@ -939,8 +939,7 @@ class TemplateTool (BaseTool): undependent_list.append(dependency_id) if len(sorted_bt_list) != len(bt_list): - raise NotImplementedError, \ - "Circular dependencies on %s" % reverse_dependency_dict.keys() + raise NotImplementedError("Circular dependencies on %s" % reverse_dependency_dict.keys()) else: return sorted_bt_list @@ -1186,13 +1185,12 @@ class TemplateTool (BaseTool): candidate.uid)) break else: - raise BusinessTemplateMissingDependency,\ - "Unable to resolve dependencies for %s, options are %s" \ - % (dep_id, provider_list) + raise BusinessTemplateMissingDependency("Unable to resolve dependencies for %s, options are %s" \ + % (dep_id, provider_list)) if len(template_title_list) > 0: - raise BusinessTemplateUnknownError, 'The Business Template %s could not be found on repositories %s' % \ - (list(template_title_list), self.getRepositoryList()) + raise BusinessTemplateUnknownError('The Business Template %s could not be found on repositories %s' % \ + (list(template_title_list), self.getRepositoryList())) return self.sortBusinessTemplateList(list(bt5_set)) security.declareProtected(Permissions.ManagePortal, @@ -1219,9 +1217,8 @@ class TemplateTool (BaseTool): if not checkAvailability(i[1].replace(".bt5", ""))] if not install_dependency and len(missing_dependency_list) > 0: - raise BusinessTemplateMissingDependency,\ - "Impossible to install, please install the following dependencies before: %s" \ - % [x[1] for x in missing_dependency_list] + raise BusinessTemplateMissingDependency("Impossible to install, please install the following dependencies before: %s" \ + % [x[1] for x in missing_dependency_list]) activate_kw = dict(activity="SQLQueue", tag="start_%s" % (time.time())) for repository, bt_id in resolved_template_list: diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_callDialogMethod.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_callDialogMethod.py index d2e6fceceac04d20820666e7ee462ab82e8148ba..846f4af98f8ae816461b3920ee5ef3dfec289f33 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_callDialogMethod.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_callDialogMethod.py @@ -91,7 +91,7 @@ try: request.set('editable_mode', 1) form.validate_all_to_request(request) request.set('editable_mode', editable_mode) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_checkConsistency.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_checkConsistency.py index 0193bba64e9ac4a0e9af07f9b8afc4dd9d7287d5..d2e34575147ac5ff099c4b09ae042bfaf7866fcb 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_checkConsistency.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_checkConsistency.py @@ -11,4 +11,4 @@ for err in check_result: message_list.append(err[3]) if message_list: - raise ValidationFailed, message_list + raise ValidationFailed(message_list) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_configureSortOn.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_configureSortOn.py index cbe1983b139e45bc708e4c5a33a5d6f19f2d2041..85ad09a919c9bd3fcfca0e67a911a3237ce3231f 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_configureSortOn.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_configureSortOn.py @@ -24,7 +24,7 @@ try: sort_on += [(k, v, t)] i += 1 context.portal_selections.setSelectionSortOrder(selection_name, sort_on) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_configureUI.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_configureUI.py index 2fc3d2593ca2fc17a3926e394433b6a17c7ef839..78f7b2ec57353dfa5654ec19899a8d8a2b91e93f 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_configureUI.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_configureUI.py @@ -67,7 +67,7 @@ try: if k != 'None': columns += [(k , columns_dict[k])] context.portal_selections.setSelectionColumns(selection_name, columns, REQUEST=request) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_createRelation.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_createRelation.py index d08f3da98ba06285c876e658568b393f1345b1df..f14543965257f8934843744a42a329a6030ea0e5 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_createRelation.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_createRelation.py @@ -68,7 +68,7 @@ try: return context.Base_viewCreateRelationDialog( REQUEST=request ) pass # context.newRelation(base_category, my_field.get_value('portal_type')) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_edit.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_edit.py index 98ff4ab4b94a6e436bbbe1d4e0c4351bbd14d942..e0eaf2d4c8c6afbf38ba68256016416c45e130e2 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_edit.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_edit.py @@ -37,7 +37,7 @@ edit_order = form.edit_order try: # Validate form.validate_all_to_request(request, key_prefix=key_prefix) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_editUnrestricted.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_editUnrestricted.py index 26cb8821018853c6fd08a2b8ed95bb30021c6108..1523eef70281540db14f7da26b742e34ab6266d0 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_editUnrestricted.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_editUnrestricted.py @@ -19,7 +19,7 @@ form = getattr(context,form_id) try: # Validate form.validate_all_to_request(request) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) @@ -69,7 +69,7 @@ try: for encapsulated_editor in encapsulated_editor_list: encapsulated_editor.edit(context) -except ActivityPendingError,e: +except ActivityPendingError as e: message = Base_translateString("%s" % e) ignore_layout = int(ignore_layout) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_getOwnerId.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_getOwnerId.py index 3882749eb245ddc4fc45654ea7f54ffaf8cb0221..80f928bc638bc35f41abd2efec4cc9d15af89fa5 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_getOwnerId.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_getOwnerId.py @@ -3,4 +3,4 @@ local_role_list = context.get_local_roles() for group, role_list in local_role_list: if 'Owner' in role_list: return group -raise ValueError, 'Context (%s) has no owner (see local roles).' % (repr(context), ) +raise ValueError('Context (%s) has no owner (see local roles).' % (repr(context), )) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_getWorkflowHistory.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_getWorkflowHistory.py index a2c4c4566a2b9895537c9c0528463d55282bce35..cd71327343d976f1b7d64aab28fff4e2d55e03c2 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_getWorkflowHistory.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_getWorkflowHistory.py @@ -23,7 +23,7 @@ for history_name in history_name_list: history_element_title_list = [] for history_element_title in list_history_item[-1].keys(): - if history_element_title <> history_name: + if history_element_title != history_name: new_title = history_element_title.replace('_', ' ').title() history_element_title_list.append(new_title) @@ -31,7 +31,7 @@ for history_name in history_name_list: for history_item in list_history_item: history_item_info = () for history_element_title in list_history_item[-1].keys(): - if history_element_title <> history_name: + if history_element_title != history_name: history_item_info += (history_item.get(history_element_title),) history_item_list.append(history_item_info) history_item_list.reverse() diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_parseSearchString.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_parseSearchString.py index c287b17d0a592a24a03950c9bc954efa041a129d..c97f7a480e8e10900e54026bc11bf1fefab23260 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_parseSearchString.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_parseSearchString.py @@ -101,7 +101,7 @@ def resolveCriterion(criterion_alias, criterion_value_list): break seen_alias_dict[criterion_alias] = None if next_alias in seen_alias_dict: - raise Exception, 'Endless alias loop detected: lookup of %r reached alias %r twice' % (initial_criterion_alias, next_alias) + raise Exception('Endless alias loop detected: lookup of %r reached alias %r twice' % (initial_criterion_alias, next_alias)) criterion_alias = next_alias return criterion_alias, criterion_value_list diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_searchHandler.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_searchHandler.py index 34ec6dae32444ad062292e8a736377152c2bdedb..0eb9017c054044de79792c7bbe2a1fb9965f01fe 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_searchHandler.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_searchHandler.py @@ -28,7 +28,7 @@ try: url_params_string = make_query(kw) # raise str(kw), url_params_string -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_validateRelation.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_validateRelation.py index b3d7d0af3b3bb8518f2c8c42af6cd51c2b352570..bc88cf3a2266b4eee69a4f999ad8b69ed0264369 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_validateRelation.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_validateRelation.py @@ -179,7 +179,7 @@ try: request.set('default_module', my_field.get_value('default_module')) request.set('portal_type', portal_type[0]) return o.Base_viewCreateRelationDialog( REQUEST=request ) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_workflowStatusModify.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_workflowStatusModify.py index e2e3f45cefdda2dfecd0d22a5de98e0032c7f8f7..205f7918d1cf7f487c26d4964f2d14089b2c9dc6 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_workflowStatusModify.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Base_workflowStatusModify.py @@ -11,7 +11,7 @@ if 1: # keep indentation **kw) except WorkflowException: pass - except ValidationFailed, message: + except ValidationFailed as message: if getattr(message, 'msg', None) and same_type(message.msg, []): message = '. '.join('%s' % x for x in message.msg) if not batch : diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Folder_modifyWorkflowStatus.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Folder_modifyWorkflowStatus.py index 85caeb09691e4d4edf2ccbed4b54ecbf2a775e68..30eb196a5eb200f92421191fe7287c84d1a68c07 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Folder_modifyWorkflowStatus.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Folder_modifyWorkflowStatus.py @@ -18,7 +18,7 @@ for form in (real_form, target_form): request.set('editable_mode', 1) form.validate_all_to_request(request) request.set('editable_mode', editable_mode) - except FormValidationError, validation_errors: + except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Predicate_edit.py b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Predicate_edit.py index a53c793fbcecadbc811b59ae088deb7b04115a72..faf7ff1be3388b98de49fb8f75cec4e97781938e 100644 --- a/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Predicate_edit.py +++ b/product/ERP5/bootstrap/erp5_core/SkinTemplateItem/portal_skins/erp5_core/Predicate_edit.py @@ -43,7 +43,7 @@ try: # Update basic attributes context.edit(REQUEST=request, edit_order=edit_order, **kw) context.reindexObject() -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) diff --git a/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_fckeditor/editor/filemanager/browser/zope/connectors/connectorCPS.py.py b/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_fckeditor/editor/filemanager/browser/zope/connectors/connectorCPS.py.py index 725557620cb2b5f4631d1085617274f4558a9808..f4239e4fca26ec156c3b5d4d981daeaf27268ea1 100644 --- a/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_fckeditor/editor/filemanager/browser/zope/connectors/connectorCPS.py.py +++ b/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_fckeditor/editor/filemanager/browser/zope/connectors/connectorCPS.py.py @@ -207,7 +207,7 @@ def xmlString(results, resourceType, foldersOnly): try: xmlFolders.append('\r '%(ConvertToXmlAttribute(result.id),ConvertToXmlAttribute(titre), tagLinkbyuid, uid, resourceType, ConvertToXmlAttribute(result.meta_type))) - except Exception , e: + except Exception as e: pass else : @@ -216,13 +216,13 @@ def xmlString(results, resourceType, foldersOnly): size=0 try: size= result.getContent().get_size() - except Exception,e: + except Exception as e: pass try: xmlFiles.append('\r '%(ConvertToXmlAttribute(result.getId()),size,ConvertToXmlAttribute(titre), tagPhoto, tagLinkbyuid, uid, resourceType)) - except Exception,e: + except Exception as e: pass xmlFiles.append('\r ') @@ -264,7 +264,7 @@ def GetFoldersAndFiles( resourceType, currentFolder ): if currentFolder != "/" : try: obj = context.restrictedTraverse(currentFolder.lstrip('/')) - except Exception,e: + except Exception as e: obj = context.portal_url.getPortalObject() else : @@ -335,7 +335,7 @@ def GetFolders( resourceType, currentFolder ): results.append(object) elif user.has_role(rolesSeeUnpublishedContent,object) : results.append(object) - except Exception,e: + except Exception as e: pass results = [ s for s in results if user.has_permission('View', s) ] @@ -448,7 +448,7 @@ def UploadFile(resourceType, currentFolder, data, title) : #context.createCPSDocument(context=obj,REQUEST=request) obj.reindexObject() - except Exception , e : + except Exception as e : error = "103" diff --git a/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_fckeditor/editor/filemanager/browser/zope/connectors/connectorERP5.py b/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_fckeditor/editor/filemanager/browser/zope/connectors/connectorERP5.py index 10aacf5988962a167f60693846e65d95f75eab8c..b391e87c180bf48080c06e3c513a4fd28488c8b4 100644 --- a/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_fckeditor/editor/filemanager/browser/zope/connectors/connectorERP5.py +++ b/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_fckeditor/editor/filemanager/browser/zope/connectors/connectorERP5.py @@ -203,7 +203,7 @@ def xmlString(results, resourceType, foldersOnly): try: xmlFolders.append('\r '%(ConvertToXmlAttribute(result.id),ConvertToXmlAttribute(titre), tagLinkbyuid, uid, resourceType, ConvertToXmlAttribute(result.meta_type))) - except Exception , e: + except Exception as e: pass else : @@ -220,12 +220,12 @@ def xmlString(results, resourceType, foldersOnly): unit = " KB" else: unit = " Bytes" - except Exception,e: + except Exception as e: pass try: xmlFiles.append('\r '%(ConvertToXmlAttribute(result.getId()),size,unit,ConvertToXmlAttribute(titre), tagPhoto, tagLinkbyuid, uid, resourceType)) - except Exception,e: + except Exception as e: pass xmlFiles.append('\r ') @@ -266,7 +266,7 @@ def GetFoldersAndFiles( resourceType, currentFolder ): if currentFolder != "/" : try: obj = context.restrictedTraverse(currentFolder.lstrip('/')) - except Exception,e: + except Exception as e: obj = context.portal_url.getPortalObject() else : @@ -332,7 +332,7 @@ def GetFolders( resourceType, currentFolder ): results.append(object) elif user.has_role(rolesSeeUnpublishedContent,object) : results.append(object) - except Exception,e: + except Exception as e: pass results = [ s for s in results if user.has_permission('View', s) ] @@ -435,7 +435,7 @@ def UploadFile(resourceType, currentFolder, data, title) : new_image = obj.newContent(portal_type=typeToAdd, id=idObj, title=titre_data, file=data) new_image.reindexObject() - except Exception , e : + except Exception as e : error = "103" d= ''' diff --git a/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_xhtml_style/Workflow_statusModify.py b/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_xhtml_style/Workflow_statusModify.py index 925223bd27c8a28f135989b87964c96183252ca7..8cc64cc03d00c9a57130de40f572fb2a97e5ff45 100644 --- a/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_xhtml_style/Workflow_statusModify.py +++ b/product/ERP5/bootstrap/erp5_xhtml_style/SkinTemplateItem/portal_skins/erp5_xhtml_style/Workflow_statusModify.py @@ -17,7 +17,7 @@ try: request.set('editable_mode', 1) form.validate_all_to_request(request) request.set('editable_mode', editable_mode) -except FormValidationError, validation_errors: +except FormValidationError as validation_errors: # Pack errors into the request field_errors = form.ErrorFields(validation_errors) request.set('field_errors', field_errors) @@ -67,7 +67,7 @@ try: context, doaction_param_list['workflow_action'], **doaction_param_list) -except ValidationFailed, error_message: +except ValidationFailed as error_message: if getattr(error_message, 'msg', None): # use of Message class to store message+mapping+domain message = error_message.msg diff --git a/product/ERP5/mixin/builder.py b/product/ERP5/mixin/builder.py index a1f01202fe5e8e608a9ddf4bbb6f67bc474bad53..189d49ee44ca1d557ef49a0824b137eec29622ca 100644 --- a/product/ERP5/mixin/builder.py +++ b/product/ERP5/mixin/builder.py @@ -646,8 +646,8 @@ class BuilderMixin(XMLObject, Amount, Predicate): else: movement_list = movement_group_node.getMovementList() if len(movement_list) != 1: - raise CollectError, "DeliveryBuilder: %s unable to distinct those\ - movements: %s" % (self.getId(), str(movement_list)) + raise CollectError("DeliveryBuilder: %s unable to distinct those\ + movements: %s" % (self.getId(), str(movement_list))) else: # XXX Hardcoded value base_id = 'movement' @@ -705,8 +705,8 @@ class BuilderMixin(XMLObject, Amount, Predicate): membership_criterion_base_category_list=movement.\ getVariationBaseCategoryList()) else: - raise MatrixError, 'Cell: %s already exists on %s' % \ - (str(cell_key), str(delivery_line)) + raise MatrixError('Cell: %s already exists on %s' % \ + (str(cell_key), str(delivery_line))) object_to_update = cell self._setUpdated(object_to_update, 'cell') self._setDeliveryMovementProperties( diff --git a/product/ERP5/mixin/cached_convertable.py b/product/ERP5/mixin/cached_convertable.py index db41511b380fff96a38e8a72e86519a9eb05850b..ccc24c5ae86817ab26ccec99d702837534f9e35d 100644 --- a/product/ERP5/mixin/cached_convertable.py +++ b/product/ERP5/mixin/cached_convertable.py @@ -149,7 +149,7 @@ class CachedConvertableMixin: conversion_md5 = None size = len(cached_value) else: - raise NotImplementedError, 'Not able to store type:%r' % type(data) + raise NotImplementedError('Not able to store type:%r' % type(data)) if date is None: date = DateTime() stored_data_dict = {'content_md5': self.getContentMd5(), @@ -203,13 +203,13 @@ class CachedConvertableMixin: 'cache entry invalidated for key:%r' % cache_id) content_md5 = data_dict['content_md5'] if content_md5 != self.getContentMd5(): - raise KeyError, 'Conversion cache key is compromised for %r' % cache_id + raise KeyError('Conversion cache key is compromised for %r' % cache_id) # Fill transactional cache in order to help # querying real cache during same transaction tv[cache_id] = data_dict return data_dict - raise KeyError, 'Conversion cache key does not exists for %r' % cache_id + raise KeyError('Conversion cache key does not exists for %r' % cache_id) security.declareProtected(Permissions.AccessContentsInformation, 'getConversion') def getConversion(self, **kw): diff --git a/product/ERP5/mixin/discoverable.py b/product/ERP5/mixin/discoverable.py index b62f6afa57a2a8e043a84c0c30dcc729b02a77f4..0ee85f2d21c6affb8cc79075a8fbd7501d965c40 100644 --- a/product/ERP5/mixin/discoverable.py +++ b/product/ERP5/mixin/discoverable.py @@ -145,7 +145,7 @@ class DiscoverableMixin(CachedConvertableMixin): result = None if order_id not in VALID_ORDER_KEY_LIST: # Prevent security attack or bad preferences - raise AttributeError, "%s is not in valid order key list" % order_id + raise AttributeError("%s is not in valid order key list" % order_id) method_id = 'getPropertyDictFrom%s' % convertToUpperCase(order_id) method = getattr(self, method_id) if order_id in ('filename', 'file_name',): diff --git a/product/ERP5/mixin/mail_message.py b/product/ERP5/mixin/mail_message.py index ca56e8c1949b450c7a658cbcd013314f48047672..93e507050b3b6453cc3dfa9e016745455536cc99 100644 --- a/product/ERP5/mixin/mail_message.py +++ b/product/ERP5/mixin/mail_message.py @@ -45,7 +45,7 @@ def testCharsetAndConvert(text_content, content_type, encoding): text_content = text_content.decode(encoding).encode('utf-8') else: text_content = text_content.decode().encode('utf-8') - except (UnicodeDecodeError, LookupError), error_message: + except (UnicodeDecodeError, LookupError) as error_message: encoding = guessEncodingFromText(text_content, content_type) if encoding is not None: try: @@ -123,7 +123,7 @@ class MailMessageMixin: for (name, value) in self._getMessage().items(): try: decoded_header = decode_header(value) - except HeaderParseError, error_message: + except HeaderParseError as error_message: decoded_header = () LOG('MailMessageMixin.getContentInformation', INFO, 'Failed to decode %s header of %s with error: %s' % diff --git a/product/ERP5/tests/erp5_url_checker.py b/product/ERP5/tests/erp5_url_checker.py index 33afa7044a02fb4f87fec1b60985d422ca6c321a..77c36eb54218bb748625522879319a651ba9bf87 100644 --- a/product/ERP5/tests/erp5_url_checker.py +++ b/product/ERP5/tests/erp5_url_checker.py @@ -98,7 +98,7 @@ class URLOpener(FancyURLopener): if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) #print "proxy via http:", host, selector - if not host: raise IOError, ('http error', 'no host given') + if not host: raise IOError('http error', 'no host given') if user_passwd: import base64 auth = string.strip(base64.encodestring(user_passwd)) @@ -147,13 +147,15 @@ class Checker(URLOpener): while thread.isAlive(): sleep(0.5) print "Connection to %s went fine" % url - except IOError, (errno, strerror): + except IOError as e: + (errno, strerror) = e.args print "Can't connect to %s because of I/O error(%s): %s" % (url, errno, strerror) def SearchUrl(self, url=None): try: conn = self.open_http(url) - except IOError, (errno, strerror): + except IOError as e: + (errno, strerror) = e.args print "Can't connect to %s because of I/O error(%s): %s" % (url, errno, strerror) diff --git a/product/ERP5/tests/testAccountingRulesSimulationLegacy.py b/product/ERP5/tests/testAccountingRulesSimulationLegacy.py index 75f8c385eb689bebc4dee986d1bee3f9938c37a5..a51b41be9838cf317455527c24c2979868043ebf 100644 --- a/product/ERP5/tests/testAccountingRulesSimulationLegacy.py +++ b/product/ERP5/tests/testAccountingRulesSimulationLegacy.py @@ -541,8 +541,8 @@ class TestAccountingRules(TestAccountingRulesMixin, ERP5TypeTestCase): id = 'empty_invoice', portal_type = self.invoice_portal_type, resource = currency.getRelativeUrl(), - stop_date = DateTime(2004, 01, 01), - start_date = DateTime(2004, 01, 01), + stop_date = DateTime(2004, 1, 1), + start_date = DateTime(2004, 1, 1), source_section = vendor.getRelativeUrl(), destination_section = client.getRelativeUrl(), created_by_builder = 1, @@ -572,8 +572,8 @@ class TestAccountingRules(TestAccountingRulesMixin, ERP5TypeTestCase): portal_type = self.invoice_portal_type, resource = currency.getRelativeUrl(), price_currency = currency.getRelativeUrl(), - stop_date = DateTime(2004, 01, 01), - start_date = DateTime(2004, 01, 01), + stop_date = DateTime(2004, 1, 1), + start_date = DateTime(2004, 1, 1), source_section = vendor.getRelativeUrl(), destination_section = client.getRelativeUrl(), created_by_builder = 1, @@ -610,8 +610,8 @@ class TestAccountingRules(TestAccountingRulesMixin, ERP5TypeTestCase): id = 'other_simple_invoice', portal_type = self.invoice_portal_type, resource = currency.getRelativeUrl(), - stop_date = DateTime(2004, 01, 01), - start_date = DateTime(2004, 01, 01), + stop_date = DateTime(2004, 1, 1), + start_date = DateTime(2004, 1, 1), source_section = vendor.getRelativeUrl(), destination_section = client.getRelativeUrl(), created_by_builder = 1, @@ -693,8 +693,8 @@ class TestAccountingRules(TestAccountingRulesMixin, ERP5TypeTestCase): id = 'simple_invoice_two_lines', portal_type = self.invoice_portal_type, resource = currency.getRelativeUrl(), - stop_date = DateTime(2004, 01, 01), - start_date = DateTime(2004, 01, 01), + stop_date = DateTime(2004, 1, 1), + start_date = DateTime(2004, 1, 1), source_section = vendor.getRelativeUrl(), destination_section = client.getRelativeUrl(), created_by_builder = 1, @@ -738,8 +738,8 @@ class TestAccountingRules(TestAccountingRulesMixin, ERP5TypeTestCase): id = 'simple_invoice_two_cells', portal_type = self.invoice_portal_type, resource = currency.getRelativeUrl(), - stop_date = DateTime(2004, 01, 01), - start_date = DateTime(2004, 01, 01), + stop_date = DateTime(2004, 1, 1), + start_date = DateTime(2004, 1, 1), source_section = vendor.getRelativeUrl(), destination_section = client.getRelativeUrl(), created_by_builder = 1, @@ -815,8 +815,8 @@ class TestAccountingRules(TestAccountingRulesMixin, ERP5TypeTestCase): portal_type = self.invoice_portal_type, resource = currency.getRelativeUrl(), price_currency = currency.getRelativeUrl(), - stop_date = DateTime(2004, 01, 01), - start_date = DateTime(2004, 01, 01), + stop_date = DateTime(2004, 1, 1), + start_date = DateTime(2004, 1, 1), source_section = vendor.getRelativeUrl(), destination_section = client.getRelativeUrl(), created_by_builder = 1, diff --git a/product/ERP5/tests/testAlarm.py b/product/ERP5/tests/testAlarm.py index 578bd9f621d9dd1e2ad71563c1e2a7adeb0e5232..1e271bfc57522c85955e67271403afc263427790 100644 --- a/product/ERP5/tests/testAlarm.py +++ b/product/ERP5/tests/testAlarm.py @@ -142,7 +142,7 @@ class TestAlarm(ERP5TypeTestCase): right_first_date = DateTime(self.date_format % (2006,10,6,15,00,00)) now = DateTime(self.date_format % (2006,10,6,15,00,00)) right_second_date = DateTime(self.date_format % (2006,10,6,21,00,00)) - right_third_date = DateTime(self.date_format % (2006,10,7,06,00,00)) + right_third_date = DateTime(self.date_format % (2006,10,7,6,00,00)) right_fourth_date = DateTime(self.date_format % (2006,10,7,10,00,00)) alarm = self.newAlarm(enabled=True) hour_list = (6,10,15,21) @@ -239,8 +239,8 @@ class TestAlarm(ERP5TypeTestCase): def test_09_SomeMonthDaysSomeHours(self): """- every 1st and 15th every month, at 12 and 14""" - right_first_date = DateTime(self.date_format % (2006,10,01,12,00,00)) - right_second_date = DateTime(self.date_format % (2006,10,01,14,00,00)) + right_first_date = DateTime(self.date_format % (2006,10,1,12,00,00)) + right_second_date = DateTime(self.date_format % (2006,10,1,14,00,00)) right_third_date = DateTime(self.date_format % (2006,10,15,12,00,00)) right_fourth_date = DateTime(self.date_format % (2006,10,15,14,00,00)) alarm = self.newAlarm(enabled=True) @@ -252,9 +252,9 @@ class TestAlarm(ERP5TypeTestCase): def test_10_OnceEvery2Month(self): """- every 1st day of every 2 month, at 6""" - right_first_date = DateTime(self.date_format % (2006,10,01,6,00,00)) - right_second_date = DateTime(self.date_format % (2006,12,01,6,00,00)) - right_third_date = DateTime(self.date_format % (2007,2,01,6,00,00)) + right_first_date = DateTime(self.date_format % (2006,10,1,6,00,00)) + right_second_date = DateTime(self.date_format % (2006,12,1,6,00,00)) + right_third_date = DateTime(self.date_format % (2007,2,1,6,00,00)) alarm = self.newAlarm(enabled=True) alarm.setPeriodicityStartDate(right_first_date) alarm.setPeriodicityMonthDayList((1,)) @@ -337,7 +337,7 @@ class TestAlarm(ERP5TypeTestCase): finally: self.portal.portal_activities.manageClearActivities(keep=0) 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 self.getPortal().portal_skins[skin_folder_id][sense_method_id].ZPythonScript_edit('*args,**kw', 'context.newActiveProcess()') alarm.activeSense() diff --git a/product/ERP5/tests/testCrmReports.py b/product/ERP5/tests/testCrmReports.py index 4ac5c528e006d3b2d4ef08208b81a4e29a85348e..cd72d7aac16022a3dd9ae91561a855564a4c1d9d 100644 --- a/product/ERP5/tests/testCrmReports.py +++ b/product/ERP5/tests/testCrmReports.py @@ -110,7 +110,7 @@ class CrmTestCase(ERP5ReportTestCase): ev = self.event_module.newContent(portal_type=portal_type,**kw) 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()) self._doWorkflowAction(ev,'assign_action', follow_up_ticket_type = ticket.getPortalType(), @@ -118,16 +118,16 @@ class CrmTestCase(ERP5ReportTestCase): elif simulation_state == 'planned': ev.plan() 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() elif simulation_state == 'delivered': ev.start() ev.deliver() 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() 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()) self._doWorkflowAction(ev,'assign_action', follow_up_ticket_type = ticket.getPortalType(), @@ -139,17 +139,17 @@ class CrmTestCase(ERP5ReportTestCase): elif simulation_state == 'deleted': ev.delete() 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.expire() 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.respond() elif simulation_state == 'started': ev.start() 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.order() elif simulation_state == 'stopped': diff --git a/product/ERP5/tests/testERP5Base.py b/product/ERP5/tests/testERP5Base.py index 34e00341a8d187453510102c60611c0e4cee741d..19fd27a948d379d87e238dbd50e258fe880cb849 100644 --- a/product/ERP5/tests/testERP5Base.py +++ b/product/ERP5/tests/testERP5Base.py @@ -815,7 +815,7 @@ class TestERP5Base(ERP5TypeTestCase): """Tests dates on Person objects. """ pers = self.getPersonModule().newContent(portal_type='Person') - birthday = DateTime(1999, 01, 01) + birthday = DateTime(1999, 1, 1) now = DateTime() pers.edit(birthday = birthday) self.assertEqual(birthday, pers.getBirthday()) @@ -830,7 +830,7 @@ class TestERP5Base(ERP5TypeTestCase): """Tests dates on Organisation objects. """ org = self.getOrganisationModule().newContent(portal_type='Organisation') - start_date = DateTime(1999, 01, 01) + start_date = DateTime(1999, 1, 1) now = DateTime() org.edit(start_date = start_date) self.assertEqual(start_date, org.getStartDate()) @@ -980,7 +980,7 @@ class TestERP5Base(ERP5TypeTestCase): subordination_value=first_organisation, start_date=DateTime(1996, 9, 9)) another_cancelled_career.cancel() - self.assertEqual(DateTime(2001, 01, 01), + self.assertEqual(DateTime(2001, 1, 1), person.Person_getCareerStartDate( subordination_relative_url=first_organisation.getRelativeUrl())) diff --git a/product/ERP5/tests/testInventoryAPI.py b/product/ERP5/tests/testInventoryAPI.py index ee3198e615f54071ff20483acb0b7bb72bbf22a3..fadd794a040aa3159f2cb107b33f5a303aea6b33 100644 --- a/product/ERP5/tests/testInventoryAPI.py +++ b/product/ERP5/tests/testInventoryAPI.py @@ -1936,94 +1936,94 @@ class TestMovementHistoryList(InventoryAPITestCase): def test_FromDate(self): getMovementHistoryList = self.getSimulationTool().getMovementHistoryList - for date in [DateTime(2006, 01, day) for day in range(1, 4)]: + for date in [DateTime(2006, 1, day) for day in range(1, 4)]: self._makeMovement(quantity=100, start_date=date, stop_date=date+1) # from_date takes all movements >= self.assertEqual(len(getMovementHistoryList( - from_date=DateTime(2006, 01, 03), + from_date=DateTime(2006, 1, 3), section_uid=self.section.getUid())), 2) self.assertEqual(len(getMovementHistoryList( - from_date=DateTime(2006, 01, 02), + from_date=DateTime(2006, 1, 2), section_uid=self.mirror_section.getUid())), 2) def test_AtDate(self): getMovementHistoryList = self.getSimulationTool().getMovementHistoryList - for date in [DateTime(2006, 01, day) for day in range(1, 4)]: + for date in [DateTime(2006, 1, day) for day in range(1, 4)]: self._makeMovement(quantity=100, start_date=date, stop_date=date+1) # at_date takes all movements <= self.assertEqual(len(getMovementHistoryList( - at_date=DateTime(2006, 01, 03), + at_date=DateTime(2006, 1, 3), section_uid=self.section.getUid())), 2) self.assertEqual(len(getMovementHistoryList( - at_date=DateTime(2006, 01, 02), + at_date=DateTime(2006, 1, 2), section_uid=self.mirror_section.getUid())), 2) def test_ToDate(self): getMovementHistoryList = self.getSimulationTool().getMovementHistoryList - for date in [DateTime(2006, 01, day) for day in range(1, 4)]: + for date in [DateTime(2006, 1, day) for day in range(1, 4)]: self._makeMovement(quantity=100, start_date=date, stop_date=date+1) # to_date takes all movements < self.assertEqual(len(getMovementHistoryList( - to_date=DateTime(2006, 01, 03), + to_date=DateTime(2006, 1, 3), section_uid=self.section.getUid())), 1) self.assertEqual(len(getMovementHistoryList( - to_date=DateTime(2006, 01, 02), + to_date=DateTime(2006, 1, 2), section_uid=self.mirror_section.getUid())), 1) def test_FromDateAtDate(self): getMovementHistoryList = self.getSimulationTool().getMovementHistoryList - for date in [DateTime(2006, 01, day) for day in range(1, 4)]: + for date in [DateTime(2006, 1, day) for day in range(1, 4)]: self._makeMovement(quantity=100, start_date=date, stop_date=date+1) # both from_date and at_date self.assertEqual(len(getMovementHistoryList( - from_date=DateTime(2006, 01, 03), - at_date=DateTime(2006, 01, 03), + from_date=DateTime(2006, 1, 3), + at_date=DateTime(2006, 1, 3), section_uid=self.section.getUid())), 1) self.assertEqual(len(getMovementHistoryList( - from_date=DateTime(2006, 01, 02), - at_date=DateTime(2006, 01, 03), + from_date=DateTime(2006, 1, 2), + at_date=DateTime(2006, 1, 3), section_uid=self.section.getUid())), 2) self.assertEqual(len(getMovementHistoryList( - from_date=DateTime(2005, 01, 02), - at_date=DateTime(2006, 01, 03), + from_date=DateTime(2005, 1, 2), + at_date=DateTime(2006, 1, 3), section_uid=self.section.getUid())), 2) # from other side self.assertEqual(len(getMovementHistoryList( - from_date=DateTime(2006, 01, 02), - at_date=DateTime(2006, 01, 03), + from_date=DateTime(2006, 1, 2), + at_date=DateTime(2006, 1, 3), section_uid=self.mirror_section.getUid())), 2) def test_FromDateToDate(self): getMovementHistoryList = self.getSimulationTool().getMovementHistoryList - for date in [DateTime(2006, 01, day) for day in range(1, 4)]: + for date in [DateTime(2006, 1, day) for day in range(1, 4)]: self._makeMovement(quantity=100, start_date=date, stop_date=date+1) # both from_date and to_date self.assertEqual(len(getMovementHistoryList( - from_date=DateTime(2006, 01, 03), - to_date=DateTime(2006, 01, 03), + from_date=DateTime(2006, 1, 3), + to_date=DateTime(2006, 1, 3), section_uid=self.section.getUid())), 0) self.assertEqual(len(getMovementHistoryList( - from_date=DateTime(2006, 01, 02), - to_date=DateTime(2006, 01, 03), + from_date=DateTime(2006, 1, 2), + to_date=DateTime(2006, 1, 3), section_uid=self.section.getUid())), 1) self.assertEqual(len(getMovementHistoryList( - from_date=DateTime(2005, 01, 02), - to_date=DateTime(2007, 01, 02), + from_date=DateTime(2005, 1, 2), + to_date=DateTime(2007, 1, 2), section_uid=self.section.getUid())), 3) # from other side self.assertEqual(len(getMovementHistoryList( - from_date=DateTime(2006, 01, 02), - to_date=DateTime(2006, 01, 03), + from_date=DateTime(2006, 1, 2), + to_date=DateTime(2006, 1, 3), section_uid=self.mirror_section.getUid())), 1) @@ -2061,7 +2061,7 @@ class TestMovementHistoryList(InventoryAPITestCase): def test_SortOnDate(self): getMovementHistoryList = self.getSimulationTool().getMovementHistoryList - date_list = [DateTime(2006, 01, day) for day in range(1, 10)] + date_list = [DateTime(2006, 1, day) for day in range(1, 10)] reverse_date_list = date_list[:] reverse_date_list.reverse() @@ -2170,7 +2170,7 @@ class TestMovementHistoryList(InventoryAPITestCase): """Test that a running_total_quantity attribute is set on brains """ getMovementHistoryList = self.getSimulationTool().getMovementHistoryList - date_and_qty_list = [(DateTime(2006, 01, day), day) for day in range(1, 10)] + date_and_qty_list = [(DateTime(2006, 1, day), day) for day in range(1, 10)] for date, quantity in date_and_qty_list: self._makeMovement(stop_date=date, quantity=quantity) movement_history_list = getMovementHistoryList( @@ -2189,7 +2189,7 @@ class TestMovementHistoryList(InventoryAPITestCase): """Test that a running_total_price attribute is set on brains """ getMovementHistoryList = self.getSimulationTool().getMovementHistoryList - date_and_price_list = [(DateTime(2006, 01, day), day) for day in range(1, 10)] + date_and_price_list = [(DateTime(2006, 1, day), day) for day in range(1, 10)] for date, price in date_and_price_list: self._makeMovement(stop_date=date, quantity=1, price=price) movement_history_list = getMovementHistoryList( @@ -2209,7 +2209,7 @@ class TestMovementHistoryList(InventoryAPITestCase): value. """ getMovementHistoryList = self.getSimulationTool().getMovementHistoryList - date_and_qty_list = [(DateTime(2006, 01, day), day) for day in range(1, 10)] + date_and_qty_list = [(DateTime(2006, 1, day), day) for day in range(1, 10)] for date, quantity in date_and_qty_list: self._makeMovement(stop_date=date, price=quantity, quantity=quantity) initial_running_total_price=100 @@ -2973,12 +2973,12 @@ class TestInventoryCacheTable(InventoryAPITestCase): # Leads to rasing exception instead of calling self.assert[...] method. if not success: 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], - criterion_dict) + criterion_dict)) else: - raise AssertionError, 'No line in %r\n match\n %r' % \ - (inventory_list, criterion_dict) + raise AssertionError('No line in %r\n match\n %r' % \ + (inventory_list, criterion_dict)) # Check all expected lines have been found. self.assertFalse(inventory_list) diff --git a/product/ERP5/tests/testInventoryModule.py b/product/ERP5/tests/testInventoryModule.py index 125a5b8bb2469d1b33c956d7772e31ec9970e37b..1d5968c7078f9ad391e0cdfd648e24e6806c975f 100644 --- a/product/ERP5/tests/testInventoryModule.py +++ b/product/ERP5/tests/testInventoryModule.py @@ -627,7 +627,7 @@ class TestInventoryModule(TestOrderMixin, ERP5TypeTestCase): specialise=self.business_process, source_value = from_organisation, destination_value = organisation, - start_date=DateTime(2019, 02, 20), + start_date=DateTime(2019, 2, 20), ) resource_value = sequence.get('resource') delivery.newContent( portal_type='Internal Packing List Line', @@ -649,7 +649,7 @@ class TestInventoryModule(TestOrderMixin, ERP5TypeTestCase): self.assertEqual(2, getInventoryQuantity()) inventory = self.getInventoryModule().newContent() - inventory.edit(start_date=DateTime(2019, 02, 21), + inventory.edit(start_date=DateTime(2019, 2, 21), destination_value=organisation, full_inventory=True) inventory.deliver() @@ -694,7 +694,7 @@ class TestInventoryModule(TestOrderMixin, ERP5TypeTestCase): self.assertEqual(2, getInventoryQuantity()) inventory = self.getInventoryModule().newContent() - inventory.edit(start_date=DateTime(2019, 02, 21), + inventory.edit(start_date=DateTime(2019, 2, 21), destination_value=organisation, full_inventory=True) inventory_line = inventory.newContent(portal_type='Inventory Line', diff --git a/product/ERP5/tests/testInvoice.py b/product/ERP5/tests/testInvoice.py index 572504ea2e338ba1f2c7ec66f64c66c53208d306..c849e928fe2520f44d0171dc021496ccdb0060cb 100644 --- a/product/ERP5/tests/testInvoice.py +++ b/product/ERP5/tests/testInvoice.py @@ -1000,7 +1000,7 @@ class TestInvoiceMixin(TestPackingListMixin): """ try: self.tic() - except RuntimeError, exc: + except RuntimeError as exc: invoice = sequence.get('invoice') # check which activities are failing self.assertTrue(str(exc).startswith('tic is looping forever.'), @@ -1359,16 +1359,16 @@ class TestInvoice(TestInvoiceMixin): self.assertEqual(other_resource, invoice_movement.getResourceValue()) - order_line.setStartDate(DateTime(2001, 02, 03)) + order_line.setStartDate(DateTime(2001, 2, 3)) self.tic() invoice_movement = invoice_applied_rule.contentValues()[0] - self.assertEqual(DateTime(2001, 02, 03), + self.assertEqual(DateTime(2001, 2, 3), invoice_movement.getStartDate()) - order_line.setStopDate(DateTime(2002, 03, 04)) + order_line.setStopDate(DateTime(2002, 3, 4)) self.tic() invoice_movement = invoice_applied_rule.contentValues()[0] - self.assertEqual(DateTime(2002, 03, 04), + self.assertEqual(DateTime(2002, 3, 4), invoice_movement.getStopDate()) @newSimulationExpectedFailure @@ -1556,20 +1556,20 @@ class TestInvoice(TestInvoiceMixin): self.assertEqual(456, invoice_transaction_movement.getQuantity()) - order_line.setStartDate(DateTime(2001, 02, 03)) + order_line.setStartDate(DateTime(2001, 2, 3)) self.tic() self.assertEqual(3, len(invoice_transaction_applied_rule)) invoice_transaction_movement = getIncomeSimulationMovement( invoice_transaction_applied_rule) - self.assertEqual(DateTime(2001, 02, 03), + self.assertEqual(DateTime(2001, 2, 3), invoice_transaction_movement.getStartDate()) - order_line.setStopDate(DateTime(2002, 03, 04)) + order_line.setStopDate(DateTime(2002, 3, 4)) self.tic() self.assertEqual(3, len(invoice_transaction_applied_rule)) invoice_transaction_movement = getIncomeSimulationMovement( invoice_transaction_applied_rule) - self.assertEqual(DateTime(2002, 03, 04), + self.assertEqual(DateTime(2002, 3, 4), invoice_transaction_movement.getStopDate()) def test_Invoice_viewAsODT(self): diff --git a/product/ERP5/tests/testPayroll.py b/product/ERP5/tests/testPayroll.py index e735a87c17594810f785194e72002f90240dcf5d..339d1505d2862caf3b041bf148c9765111560ffe 100644 --- a/product/ERP5/tests/testPayroll.py +++ b/product/ERP5/tests/testPayroll.py @@ -321,7 +321,7 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): employee = sequence.get('employee') model.edit(destination_section_value=employer, source_section_value=employee, - effective_date=DateTime(2009,01,01), + effective_date=DateTime(2009,1,1), expiration_date=DateTime(2009,12,31), version='001', reference='basic_model', @@ -557,8 +557,8 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): source_section_value=sequence.get('employee'), destination_section_value=sequence.get('employer'), resource_value=sequence.get('price_currency'), - start_date=DateTime(2009,06,01), - stop_date=DateTime(2009,06,30)) + start_date=DateTime(2009,6,1), + stop_date=DateTime(2009,6,30)) sequence.edit(paysheet = paysheet) def createPaysheetLine(self, document, **kw): @@ -1028,7 +1028,7 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): model.edit(\ price_currency_value=currency, default_payment_condition_trade_date='custom', - default_payment_condition_payment_date=DateTime(2009,05,25), + default_payment_condition_payment_date=DateTime(2009,5,25), work_time_annotation_line_quantity=151.67, work_time_annotation_line_quantity_unit='time/hours', ) @@ -1049,7 +1049,7 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): self.assertEqual(paysheet.getPriceCurrencyValue(), currency) self.assertEqual(paysheet.getDefaultPaymentConditionTradeDate(), 'custom') self.assertEqual(paysheet.getDefaultPaymentConditionPaymentDate(), - DateTime(2009,05,25)) + DateTime(2009,5,25)) self.assertEqual(paysheet.getWorkTimeAnnotationLineQuantity(), 151.67) self.assertEqual(paysheet.getWorkTimeAnnotationLineQuantityUnit(), 'time/hours') @@ -1639,14 +1639,14 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): variation_settings_category_list=['salary_range/france',], reference='fabien_model_2009', effective_date=DateTime(2009, 1, 1), - expiration_date=DateTime(2009, 06, 30)) + expiration_date=DateTime(2009, 6, 30)) model_2 = self.getPortalObject().paysheet_model_module.newContent( \ specialise_value=sequence.get('business_process'), portal_type='Pay Sheet Model', variation_settings_category_list=['salary_range/france',], reference='fabien_model_2009', - effective_date=DateTime(2009, 07, 1), + effective_date=DateTime(2009, 7, 1), expiration_date=DateTime(2009, 12, 31)) model_line_3 = self.createModelLine(model_1) @@ -1676,8 +1676,8 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): paysheet = self.portal.accounting_module.newContent( portal_type='Pay Sheet Transaction', specialise_value=model_1, - start_date=DateTime(2009, 07, 1), - stop_date=DateTime(2009, 07, 31), + start_date=DateTime(2009, 7, 1), + stop_date=DateTime(2009, 7, 31), price_currency_value=eur) paysheet.PaySheetTransaction_applyModel() self.tic() @@ -1706,8 +1706,8 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): portal_type='Pay Sheet Model', variation_settings_category_list=['salary_range/france',], reference='fabien_model_2009', - effective_date=DateTime(2009, 01, 1), - expiration_date=DateTime(2009, 02, 28), + effective_date=DateTime(2009, 1, 1), + expiration_date=DateTime(2009, 2, 28), specialise_value=sequence.get('business_process')) # define two models with same references and same dates @@ -1716,7 +1716,7 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): portal_type='Pay Sheet Model', variation_settings_category_list=['salary_range/france',], reference='fabien_model_2009', - effective_date=DateTime(2009, 07, 1), + effective_date=DateTime(2009, 7, 1), expiration_date=DateTime(2009, 12, 31), version='002', specialise_value=sequence.get('business_process')) @@ -1725,7 +1725,7 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): portal_type='Pay Sheet Model', variation_settings_category_list=['salary_range/france',], reference='fabien_model_2009', - effective_date=DateTime(2009, 07, 1), + effective_date=DateTime(2009, 7, 1), expiration_date=DateTime(2009, 12, 31), version='001', specialise_value=sequence.get('business_process')) @@ -1735,8 +1735,8 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): paysheet = self.portal.accounting_module.newContent( portal_type='Pay Sheet Transaction', specialise_value=model_1, - start_date=DateTime(2009, 07, 1), - stop_date=DateTime(2009, 07, 31), + start_date=DateTime(2009, 7, 1), + stop_date=DateTime(2009, 7, 31), price_currency_value=eur) paysheet.PaySheetTransaction_applyModel() self.tic() @@ -1798,8 +1798,8 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): portal_type='Pay Sheet Model', specialise_value=sequence.get('business_process'), reference='fabien_model_2009', - effective_date=DateTime(2009, 01, 1), - expiration_date=DateTime(2009, 02, 28)) + effective_date=DateTime(2009, 1, 1), + expiration_date=DateTime(2009, 2, 28)) model_line_1 = self.createModelLine(model_1) model_line_1.edit( resource_value=labour, @@ -1813,7 +1813,7 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): portal_type='Pay Sheet Model', specialise_value=sequence.get('business_process'), reference='fabien_model_2009', - effective_date=DateTime(2009, 07, 1), + effective_date=DateTime(2009, 7, 1), expiration_date=DateTime(2009, 12, 31), version='002') model_line_2 = self.createModelLine(model_2) @@ -1827,7 +1827,7 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): portal_type='Pay Sheet Model', specialise_value=sequence.get('business_process'), reference='fabien_model_2009', - effective_date=DateTime(2009, 07, 1), + effective_date=DateTime(2009, 7, 1), expiration_date=DateTime(2009, 12, 31), version='001') model_line_3 = self.createModelLine(model_3) @@ -1843,8 +1843,8 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): portal_type='Pay Sheet Model', specialise_value=sequence.get('business_process'), reference='fabien_model_level_2_2009', - effective_date=DateTime(2009, 01, 1), - expiration_date=DateTime(2009, 06, 30), + effective_date=DateTime(2009, 1, 1), + expiration_date=DateTime(2009, 6, 30), version='002') model_line_4 = self.createModelLine(model_4) model_line_4.edit( @@ -1857,7 +1857,7 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): portal_type='Pay Sheet Model', specialise_value=sequence.get('business_process'), reference='fabien_model_level_2_2009', - effective_date=DateTime(2009, 07, 1), + effective_date=DateTime(2009, 7, 1), expiration_date=DateTime(2009, 12, 31), version='001') model_line_5 = self.createModelLine(model_5) @@ -1873,8 +1873,8 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): portal_type='Pay Sheet Model', specialise_value=sequence.get('business_process'), reference='fabien_model_level_3_2009', - effective_date=DateTime(2009, 01, 1), - expiration_date=DateTime(2009, 06, 30), + effective_date=DateTime(2009, 1, 1), + expiration_date=DateTime(2009, 6, 30), version='002') model_line_6 = self.createModelLine(model_6) model_line_6.edit( @@ -1887,7 +1887,7 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): portal_type='Pay Sheet Model', specialise_value=sequence.get('business_process'), reference='fabien_model_level_3_2009', - effective_date=DateTime(2009, 07, 1), + effective_date=DateTime(2009, 7, 1), expiration_date=DateTime(2009, 12, 31), version='001') model_line_7 = self.createModelLine(model_7) @@ -1903,8 +1903,8 @@ class TestPayrollMixin(TestTradeModelLineMixin, ERP5ReportTestCase): paysheet = self.portal.accounting_module.newContent( portal_type='Pay Sheet Transaction', specialise_value=model_1, - start_date=DateTime(2009, 07, 1), - stop_date=DateTime(2009, 07, 31), + start_date=DateTime(2009, 7, 1), + stop_date=DateTime(2009, 7, 31), price_currency_value=eur) specialise_value = paysheet.getSpecialiseValue() diff --git a/product/ERP5/tests/testProductionOrder.py b/product/ERP5/tests/testProductionOrder.py index 0fd950c14cf766b6a6001ecae7876cb196600595..473f6135f5b8e4d0418d6be0db904186a1602ca1 100644 --- a/product/ERP5/tests/testProductionOrder.py +++ b/product/ERP5/tests/testProductionOrder.py @@ -697,8 +697,8 @@ class TestProductionOrderMixin(TestOrderMixin): LOG('object.getDeliveryValue()', 0, delivery_value) if delivery_value is not None: LOG('object.getDeliveryValue().getQuantity()',0,delivery_value.getQuantity()) - raise AssertionError, "Attribute: %s, Value: %s, Result: %s" %\ - (attribute, value, getattr(object, attribute)()) + raise AssertionError("Attribute: %s, Value: %s, Result: %s" %\ + (attribute, value, getattr(object, attribute)())) def stepCheckProductionSimulation(self, sequence=None, sequence_list=None, **kw): diff --git a/product/ERP5/tests/testProductionOrderApparel.py b/product/ERP5/tests/testProductionOrderApparel.py index b58e8c86e96daa404fe3252661d485184c9b3fe5..7b24673cfd84db13cce203c18fddb8440a6abdf8 100644 --- a/product/ERP5/tests/testProductionOrderApparel.py +++ b/product/ERP5/tests/testProductionOrderApparel.py @@ -329,8 +329,8 @@ class TestProductionOrderApparelMixin(TestOrderMixin): LOG('object.getQuantity()',0,object.getQuantity()) LOG('object.__dict__',0,object.__dict__) LOG('object.getDeliveryValue().getQuantity()',0,object.getDeliveryValue().getQuantity()) - raise AssertionError, "Attribute: %s, Value: %s, Result: %s" %\ - (attribute, value, getattr(object, attribute)()) + raise AssertionError("Attribute: %s, Value: %s, Result: %s" %\ + (attribute, value, getattr(object, attribute)())) def stepCheckProductionSimulation(self, sequence=None, sequence_list=None, **kw): diff --git a/product/ERP5/tests/testReturnedSalePackingList.py b/product/ERP5/tests/testReturnedSalePackingList.py index 73ee9206cf7855d18e575339a8aef81d7a1baac4..b4ee7228b5697888d526b79b593b95f738a898c7 100644 --- a/product/ERP5/tests/testReturnedSalePackingList.py +++ b/product/ERP5/tests/testReturnedSalePackingList.py @@ -518,7 +518,7 @@ class TestReturnedSalePackingList(ReturnedSalePackingListMixin, ERP5TypeTestCase sequence_list.addSequenceString(sequence_string) try: sequence_list.play(self, quiet=quiet) - except UnsupportedWorkflowMethod, e: + except UnsupportedWorkflowMethod as e: self.assertTrue(True) def test_04_ReturnedSalePackingListCreating(self, quiet=quiet, diff --git a/product/ERP5/tests/testTradeCondition.py b/product/ERP5/tests/testTradeCondition.py index 07e1e967bb730a40ff1a2bf6e975a16f7d16507d..202010383ea1ac6bff49f6974540c8cb313e0588 100644 --- a/product/ERP5/tests/testTradeCondition.py +++ b/product/ERP5/tests/testTradeCondition.py @@ -162,10 +162,10 @@ class TestApplyTradeCondition(TradeConditionTestCase): def test_apply_trade_condition_with_payment_conditions(self): self.trade_condition.setPaymentConditionTradeDate('custom') - self.trade_condition.setPaymentConditionPaymentDate(DateTime(2001, 01, 01)) + self.trade_condition.setPaymentConditionPaymentDate(DateTime(2001, 1, 1)) self.order.setSpecialiseValue(self.trade_condition) self.assertEqual('custom', self.order.asComposedDocument().getProperty('payment_condition_trade_date')) - self.assertEqual(DateTime(2001, 01, 01), + self.assertEqual(DateTime(2001, 1, 1), self.order.asComposedDocument().getProperty('payment_condition_payment_date')) def test_apply_trade_condition_with_payment_conditions_with_hierarchy(self): @@ -174,12 +174,12 @@ class TestApplyTradeCondition(TradeConditionTestCase): title='Other Trade Condition') other_trade_condition.setPaymentConditionTradeDate('custom') other_trade_condition.setPaymentConditionPaymentDate( - DateTime(2001, 01, 01)) + DateTime(2001, 1, 1)) self.trade_condition.setSpecialiseValue(other_trade_condition) self.order.setSpecialiseValue(self.trade_condition) self.assertEqual('custom', self.order.asComposedDocument().getProperty('payment_condition_trade_date')) - self.assertEqual(DateTime(2001, 01, 01), + self.assertEqual(DateTime(2001, 1, 1), self.order.asComposedDocument().getProperty('payment_condition_payment_date')) def test_apply_trade_condition_twice_update_order(self): @@ -189,7 +189,7 @@ class TestApplyTradeCondition(TradeConditionTestCase): self.trade_condition.setDestinationValue(self.client) self.trade_condition.setPriceCurrencyValue(self.currency) self.trade_condition.setPaymentConditionTradeDate('custom') - self.trade_condition.setPaymentConditionPaymentDate(DateTime(2001, 01, 01)) + self.trade_condition.setPaymentConditionPaymentDate(DateTime(2001, 1, 1)) self.order.setSpecialiseValue(self.trade_condition) self.order.Order_applyTradeCondition(self.trade_condition, force=1) @@ -201,7 +201,7 @@ class TestApplyTradeCondition(TradeConditionTestCase): self.assertEqual(self.client, self.order.getDestinationValue()) self.assertEqual(self.currency, self.order.getPriceCurrencyValue()) self.assertEqual('custom', self.order.asComposedDocument().getProperty('payment_condition_trade_date')) - self.assertEqual(DateTime(2001, 01, 01), + self.assertEqual(DateTime(2001, 1, 1), self.order.asComposedDocument().getProperty('payment_condition_payment_date')) new_vendor = self.portal.organisation_module.newContent( @@ -221,7 +221,7 @@ class TestApplyTradeCondition(TradeConditionTestCase): self.assertEqual(self.client, self.order.getDestinationValue()) self.assertEqual(self.currency, self.order.getPriceCurrencyValue()) self.assertEqual('custom', self.order.asComposedDocument().getProperty('payment_condition_trade_date')) - self.assertEqual(DateTime(2002, 02, 02), + self.assertEqual(DateTime(2002, 2, 2), self.order.asComposedDocument().getProperty('payment_condition_payment_date')) diff --git a/product/ERP5/tests/testXHTML.py b/product/ERP5/tests/testXHTML.py index 8f3e7055421f4c3580c19a4726c0cc27588919a8..eff5db8739dd862f310dd2e976fd61cbab6aafb4 100644 --- a/product/ERP5/tests/testXHTML.py +++ b/product/ERP5/tests/testXHTML.py @@ -123,7 +123,7 @@ class TestXHTMLMixin(ERP5TypeTestCase): yield field except Exception: yield field - except AttributeError, e: + except AttributeError as e: ZopeTestCase._print("%s is broken: %s" % (form_path, e)) def test_deadProxyFields(self): @@ -236,8 +236,8 @@ class TestXHTMLMixin(ERP5TypeTestCase): try: stdout, stderr = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True).communicate(body) - except OSError, e: - raise OSError, '%r\n%r' % (os.environ, e) + except OSError as e: + raise OSError('%r\n%r' % (os.environ, e)) if stdout: error_list.append((check_path, stdout)) if error_list: diff --git a/product/ERP5Banking/tests/TestERP5BankingMixin.py b/product/ERP5Banking/tests/TestERP5BankingMixin.py index c10237a468e68128f4e788caf9a287f659e2ade8..dd106c7d6936516e994e77e32aaa8107b87c4073 100644 --- a/product/ERP5Banking/tests/TestERP5BankingMixin.py +++ b/product/ERP5Banking/tests/TestERP5BankingMixin.py @@ -1197,7 +1197,7 @@ class TestERP5BankingMixin(ERP5TypeTestCase): line.setVariationCategoryList(variation_category_list) line.updateCellRange(script_id='CashDetail_asCellRange', base_id=base_id) cell_range_key_list = line.getCellRangeKeyList(base_id=base_id) - if cell_range_key_list <> [[None, None]] : + if cell_range_key_list != [[None, None]] : for k in cell_range_key_list: category_list = filter(lambda k_item: k_item is not None, k) c = line.newCell(*k, **line_kwd) diff --git a/product/ERP5Catalog/CatalogTool.py b/product/ERP5Catalog/CatalogTool.py index 955d98d0f1d872d04b4bc7b8c6462da7b0b905fb..ada9b0fa9ab077e06a7fbbd9a9351d20030f2be1 100644 --- a/product/ERP5Catalog/CatalogTool.py +++ b/product/ERP5Catalog/CatalogTool.py @@ -971,10 +971,10 @@ class CatalogTool (UniqueObject, ZCatalog, CMFCoreCatalogTool, ActiveObject): """ if path is None and uid is None: if object is None: - raise TypeError, 'One of uid, path and object parameters must not be None' + raise TypeError('One of uid, path and object parameters must not be None') path = self.__url(object) if uid is None: - raise TypeError, "unindexObject supports only uid now" + raise TypeError("unindexObject supports only uid now") self.uncatalog_object(path=path, uid=uid, sql_catalog_id=sql_catalog_id) security.declarePrivate('beforeUnindexObject') diff --git a/product/ERP5Catalog/Tool/ArchiveTool.py b/product/ERP5Catalog/Tool/ArchiveTool.py index 46cbb83075a830e542b02308868f468528b4990c..5579063dc12fb58692b001c2f9dc52ca1349f0a3 100644 --- a/product/ERP5Catalog/Tool/ArchiveTool.py +++ b/product/ERP5Catalog/Tool/ArchiveTool.py @@ -121,7 +121,7 @@ class ArchiveTool(BaseTool): """ # First check parameter for destination catalog 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 # Guess connection id from current catalog source_catalog = portal_catalog.getSQLCatalog() @@ -131,7 +131,7 @@ class ArchiveTool(BaseTool): source_deferred_connection_id = source_catalog.getConnectionId(deferred=True) 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 destination_archive_id = destination_archive_id.split(' - ')[0] @@ -149,25 +149,25 @@ class ArchiveTool(BaseTool): # Check we don't use same connection id for source and destination 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: - 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: - 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 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: - 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: - 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 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: - 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: - 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 destination_sql_catalog = getattr(portal_catalog, destination_sql_catalog_id) diff --git a/product/ERP5Catalog/tests/testERP5Catalog.py b/product/ERP5Catalog/tests/testERP5Catalog.py index 31b5deed66ed0d836fbb14c20ae250134f79d9d9..e34b0e3f4f02f4b95c0669ad01cf03f213b0e021 100644 --- a/product/ERP5Catalog/tests/testERP5Catalog.py +++ b/product/ERP5Catalog/tests/testERP5Catalog.py @@ -63,7 +63,7 @@ class IndexableDocument(ObjectManager): if name.startswith('is') or \ name.startswith('provides'): return lambda: 0 - raise AttributeError, name + raise AttributeError(name) def getPath(self): return self._path @@ -1919,7 +1919,7 @@ class TestERP5Catalog(ERP5TypeTestCase, LogInterceptor): 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)) else: - raise Exception, 'Malformed allowedRolesAndUsers value: %r' % (line['allowedRolesAndUsers'], ) + raise Exception('Malformed allowedRolesAndUsers value: %r' % (line['allowedRolesAndUsers'], )) # Check that object that 'bar' can view because of 'Author' role can *not* # be found when searching for his other 'Whatever' role. diff --git a/product/ERP5Configurator/Document/WorkflowSecurityConfiguratorItem.py b/product/ERP5Configurator/Document/WorkflowSecurityConfiguratorItem.py index ca1959da68d4b46725871eb0f8c66ff24d84890c..7675cf974d150d3b119fef8b32e3cb9fde61aa13 100644 --- a/product/ERP5Configurator/Document/WorkflowSecurityConfiguratorItem.py +++ b/product/ERP5Configurator/Document/WorkflowSecurityConfiguratorItem.py @@ -66,7 +66,7 @@ class WorkflowSecurityConfiguratorItem(ConfiguratorItemMixin, XMLObject): if self.filename[-suffix_len:] == suffix: workflow_id = self.filename[:-suffix_len] else: - raise "NoValidName" + raise ValueError("NoValidName") # Configure state permission view_permission_list = ['View'] diff --git a/product/ERP5Configurator/Tool/ConfiguratorTool.py b/product/ERP5Configurator/Tool/ConfiguratorTool.py index e0e051c629e74927c49c22c472d4704dbd6f97f8..b53a061c367a05f56ac7f921e9bbc3fdd89e6e15 100644 --- a/product/ERP5Configurator/Tool/ConfiguratorTool.py +++ b/product/ERP5Configurator/Tool/ConfiguratorTool.py @@ -55,10 +55,10 @@ def _validateFormToRequest(form, REQUEST, **kw): form.validate_all_to_request(REQUEST) validation_status = 0 validation_errors = None - except FormValidationError, validation_errors: + except FormValidationError as validation_errors: ## not all fields valid validation_status = 1 - except Exception, validation_errors: + except Exception as validation_errors: ## missing fields validation_status = 2 ## extract form arguments and remove leading prefixes diff --git a/product/ERP5Configurator/tests/ConfiguratorTestMixin.py b/product/ERP5Configurator/tests/ConfiguratorTestMixin.py index 0494ebb7cc4755493785645601d87acdfb9143c5..bb2ac2217dae08927862a0ba58e7cdb56242212c 100644 --- a/product/ERP5Configurator/tests/ConfiguratorTestMixin.py +++ b/product/ERP5Configurator/tests/ConfiguratorTestMixin.py @@ -817,7 +817,7 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase): group='my_group') accounting_period = organisation.newContent( portal_type='Accounting Period', - start_date=DateTime(2001, 01, 01), + start_date=DateTime(2001, 1, 1), stop_date=DateTime(2002, 12, 31)) self.assertEqual(accounting_period.getSimulationState(), 'draft') @@ -1049,8 +1049,8 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase): def stepAccountingTransaction(self, sequence=None, sequence_list=None, **kw): transaction = self.portal.accounting_module.newContent( portal_type='Accounting Transaction', - start_date=DateTime(2001, 01, 01), - stop_date=DateTime(2001, 01, 01)) + start_date=DateTime(2001, 1, 1), + stop_date=DateTime(2001, 1, 1)) self.assertEqual('draft', transaction.getSimulationState()) for user_id in self._getUserIdList(self.all_username_list): self.assertUserCanViewDocument(user_id, transaction) @@ -1181,8 +1181,8 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase): def stepSaleInvoiceTransaction(self, sequence=None, sequence_list=None, **kw): transaction = self.portal.accounting_module.newContent( portal_type='Sale Invoice Transaction', - start_date=DateTime(2001, 01, 01), - stop_date=DateTime(2001, 01, 01)) + start_date=DateTime(2001, 1, 1), + stop_date=DateTime(2001, 1, 1)) self.assertEqual('draft', transaction.getSimulationState()) for user_id in self._getUserIdList(self.all_username_list): self.assertUserCanViewDocument(user_id, transaction) @@ -1324,8 +1324,8 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase): def stepPurchaseInvoiceTransaction(self, sequence=None, sequence_list=None, **kw): transaction = self.portal.accounting_module.newContent( portal_type='Purchase Invoice Transaction', - start_date=DateTime(2001, 01, 01), - stop_date=DateTime(2001, 01, 01)) + start_date=DateTime(2001, 1, 1), + stop_date=DateTime(2001, 1, 1)) self.assertEqual('draft', transaction.getSimulationState()) for user_id in self._getUserIdList(self.all_username_list): self.assertUserCanViewDocument(user_id, transaction) @@ -1471,8 +1471,8 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase): def stepPaymentTransaction(self, sequence=None, sequence_list=None, **kw): transaction = self.portal.accounting_module.newContent( portal_type='Payment Transaction', - start_date=DateTime(2001, 01, 01), - stop_date=DateTime(2001, 01, 01)) + start_date=DateTime(2001, 1, 1), + stop_date=DateTime(2001, 1, 1)) self.assertEqual('draft', transaction.getSimulationState()) for user_id in self._getUserIdList(self.all_username_list): self.assertUserCanViewDocument(user_id, transaction) @@ -1616,29 +1616,29 @@ class TestLiveConfiguratorWorkflowMixin(SecurityTestCase): accounting_transaction_x_related_to_a = self.portal.\ accounting_module.newContent( portal_type='Accounting Transaction', - start_date=DateTime(2010, 06, 01), - stop_date=DateTime(2010, 06, 01)) + start_date=DateTime(2010, 6, 1), + stop_date=DateTime(2010, 6, 1)) accounting_transaction_y_related_to_a = self.portal.\ accounting_module.newContent( portal_type='Accounting Transaction', - start_date=DateTime(2010, 06, 01), - stop_date=DateTime(2010, 06, 01)) + start_date=DateTime(2010, 6, 1), + stop_date=DateTime(2010, 6, 1)) accounting_transaction_a = self.portal.accounting_module.newContent( portal_type='Accounting Transaction', - start_date=DateTime(2010, 06, 01), - stop_date=DateTime(2010, 06, 01)) + start_date=DateTime(2010, 6, 1), + stop_date=DateTime(2010, 6, 1)) accounting_transaction_b = self.portal.accounting_module.newContent( portal_type='Accounting Transaction', - start_date=DateTime(2010, 06, 01), - stop_date=DateTime(2010, 06, 01)) + start_date=DateTime(2010, 6, 1), + stop_date=DateTime(2010, 6, 1)) accounting_transaction_c = self.portal.accounting_module.newContent( portal_type='Accounting Transaction', - start_date=DateTime(2010, 06, 01), - stop_date=DateTime(2010, 06, 01)) + start_date=DateTime(2010, 6, 1), + stop_date=DateTime(2010, 6, 1)) accounting_transaction_x_related_to_a.setCausalityValue(\ accounting_transaction_a) diff --git a/product/ERP5Form/CaptchaField.py b/product/ERP5Form/CaptchaField.py index 4b89f1f7c4d94bc3b1c43535dab75aa0ed920cfe..c11102ee88e1f2ebd00a619120fdf8b86f3ae698 100644 --- a/product/ERP5Form/CaptchaField.py +++ b/product/ERP5Form/CaptchaField.py @@ -262,7 +262,7 @@ class CaptchaField(ZMIField): try: # validate the form and get results result[field.get_real_field().id] = field.get_real_field().validate(REQUEST) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) @@ -278,7 +278,7 @@ class CaptchaField(ZMIField): try: # validate the form and get results result.update(self.form.validate(REQUEST)) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) @@ -328,7 +328,7 @@ class CaptchaField(ZMIField): try: # validate the form and get results result[field.id] = field.validate(REQUEST) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) @@ -341,7 +341,7 @@ class CaptchaField(ZMIField): try: # validate the form and get results result.update(self.tales_form.validate(REQUEST)) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) diff --git a/product/ERP5Form/Extensions/ERP5Site_updateModuleScribus.py b/product/ERP5Form/Extensions/ERP5Site_updateModuleScribus.py index 6776052d01d73a25fe1de8cd47b443cdcd37e435..f2b44d05854d0cbfaf6030c993dcc2648f15714c 100644 --- a/product/ERP5Form/Extensions/ERP5Site_updateModuleScribus.py +++ b/product/ERP5Form/Extensions/ERP5Site_updateModuleScribus.py @@ -97,11 +97,11 @@ def ERP5Site_updateModuleScribus(self, # We should have only one result if len(good_result) > 1: - raise ValueError, "Error: There is more than one result for the "\ - "view '%s_view' : %s" % (object_portal_type, good_result) + raise ValueError("Error: There is more than one result for the "\ + "view '%s_view' : %s" % (object_portal_type, good_result)) elif len(good_result) < 1: - raise ValueError, "Error: There is no result for the view "\ - "'%s_view'" % object_portal_type + raise ValueError("Error: There is no result for the view "\ + "'%s_view'" % object_portal_type) # use the result to get the object_title and portal_skin folder object_result = good_result.items()[0][1] @@ -119,8 +119,8 @@ def ERP5Site_updateModuleScribus(self, # get the skin_folder object if not portal_skins_folder in portal.portal_skins.objectIds(): # the skin folder should exists - raise ValueError, "Error: portal_skins %s not found" % \ - portal_skins_folder + raise ValueError("Error: portal_skins %s not found" % \ + portal_skins_folder) skin_folder = ManageModule.setSkinFolder(portal, portal_skins_folder) @@ -141,7 +141,7 @@ def ERP5Site_updateModuleScribus(self, # move the old objects in portal_trash trash = getToolByName(self.getPortalObject(), 'portal_trash', None) if trash is None: - raise AttributeError, 'Trash Tool is not installed' + raise AttributeError('Trash Tool is not installed') trashbin = trash.newTrashBin(bt_title='scribus_skin_folder_%s' % \ skin_folder.getId()) diff --git a/product/ERP5Form/Form.py b/product/ERP5Form/Form.py index aaad009984f24bd90831cb6402034ec5307af561..584ea4041fea6d627343feda5e08607fbd238474 100644 --- a/product/ERP5Form/Form.py +++ b/product/ERP5Form/Form.py @@ -128,7 +128,7 @@ def getFieldDict(field, value_type): elif value_type=='tales': get_method = getattr(field, 'get_recursive_tales') else: - raise ValueError, 'value_type must be values or tales' + raise ValueError('value_type must be values or tales') template_field = field.getRecursiveTemplateField() for ui_field_id in template_field.form.fields.keys(): result[ui_field_id] = get_method(ui_field_id) @@ -138,7 +138,7 @@ def getFieldDict(field, value_type): elif value_type=='tales': get_method = getattr(field, 'get_tales') else: - raise ValueError, 'value_type must be values or tales' + raise ValueError('value_type must be values or tales') for ui_field_id in field.form.fields.keys(): result[ui_field_id] = get_method(ui_field_id) return result @@ -755,12 +755,12 @@ class ERP5Form(Base, ZMIForm, ZopePageTemplate): alternate_name = field.get_value('alternate_name') if alternate_name: result[alternate_name] = value - except FormValidationError, e: # XXX JPS Patch for listbox + except FormValidationError as e: # XXX JPS Patch for listbox errors.extend(e.errors) result.update(e.result) - except ValidationError, err: + except ValidationError as err: errors.append(err) - except KeyError, err: + except KeyError as err: LOG('ERP5Form/Form.py:validate_all', 0, 'KeyError : %s' % (err, )) if len(errors) > 0: @@ -784,7 +784,7 @@ class ERP5Form(Base, ZMIForm, ZopePageTemplate): self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) if REQUEST.environ['REQUEST_METHOD'] != 'PUT': - raise Forbidden, 'REQUEST_METHOD should be PUT.' + raise Forbidden('REQUEST_METHOD should be PUT.') body=REQUEST.get('BODY', '') # Empty the form (XMLToForm is unable to empty things before reopening) for k in self.get_field_ids(): @@ -1308,9 +1308,9 @@ def get_field_meta_type_and_proxy_flag(field): try: return field.getRecursiveTemplateField().meta_type, True except AttributeError: - raise AttributeError, 'The proxy target of %s.%s field does not '\ + raise AttributeError('The proxy target of %s.%s field does not '\ 'exists. Please check the field setting.' % \ - (field.aq_parent.id, field.getId()) + (field.aq_parent.id, field.getId())) else: return field.meta_type, False diff --git a/product/ERP5Form/FormBox.py b/product/ERP5Form/FormBox.py index acd77575ec999d0c264932591e89711464416f74..f99bd44f63690f575ecde6fef3af7794ef050e71 100644 --- a/product/ERP5Form/FormBox.py +++ b/product/ERP5Form/FormBox.py @@ -213,7 +213,7 @@ class FormBoxValidator(Validator.Validator): REQUEST.set('field_errors', current_field_errors) getattr(here, formbox_target_id).validate_all_to_request(REQUEST, key_prefix=key) else: - raise NotImplementedError, result_type + raise NotImplementedError(result_type) FormBoxWidgetInstance = FormBoxWidget() FormBoxValidatorInstance = FormBoxValidator() diff --git a/product/ERP5Form/ListBox.py b/product/ERP5Form/ListBox.py index c21938868588b0ef3dd30d4076c6e98ca2b0b812..779a7773a7109ad8b135f2f3327fed52d7b652d2 100644 --- a/product/ERP5Form/ListBox.py +++ b/product/ERP5Form/ListBox.py @@ -529,7 +529,7 @@ class ListBoxRenderer: def getLineClass(self): """Return a class object for a line. This must be overridden. """ - raise NotImplementedError, "getLineClass must be overridden in a subclass" + raise NotImplementedError("getLineClass must be overridden in a subclass") # Here, define many getters which cache the results for better performance. @@ -672,7 +672,7 @@ class ListBoxRenderer: """Return the maximum number of lines shown in a page. This must be overridden in subclasses. """ - raise NotImplementedError, "getMaxLineNumber must be overridden in a subclass" + raise NotImplementedError("getMaxLineNumber must be overridden in a subclass") @lazyMethod def showSearchLine(self): @@ -1108,7 +1108,7 @@ class ListBoxRenderer: try: column_list.append(available_column_dict[id]) except KeyError: - raise AttributeError, "Column %s is not avaible" % id + raise AttributeError("Column %s is not avaible" % id) elif list_style_column_change_required and not dynamic_column_list_override: # no dynamically setting of columns happens , still we have different than default # listbox list style so try to get columns from 'More columns' @@ -1527,7 +1527,7 @@ class ListBoxRenderer: so the real value can be different from this. For example, if the value exceeds the total number of lines, the start number is forced to fit into somewhere. This must be overridden in subclasses. """ - raise NotImplementedError, "getLineStart must be overridden in a subclass" + raise NotImplementedError("getLineStart must be overridden in a subclass") @lazyMethod def getSelectedDomainPath(self): @@ -2037,7 +2037,7 @@ class ListBoxRenderer: def render(self, **kw): """Render the data. This must be overridden. """ - raise NotImplementedError, "render must be overridden in a subclass" + raise NotImplementedError("render must be overridden in a subclass") def __call__(self, **kw): """Render the ListBox. The real rendering must be done the method "render" which should @@ -2769,7 +2769,7 @@ class ListBoxValidator(Validator.Validator): value = editable_field._validate_helper(key, REQUEST) # We need cell # Here we set the property row_result[sql] = value - except ValidationError, err: + except ValidationError as err: pass except KeyError: pass @@ -2803,7 +2803,7 @@ class ListBoxValidator(Validator.Validator): try: row_result[sql] = editable_field._validate_helper( key, REQUEST) # We need cell - except ValidationError, err: + except ValidationError as err: #LOG("ListBox ValidationError",0,str(err)) err.field_id = error_result_key errors.append(err) @@ -2819,7 +2819,7 @@ class ListBoxValidator(Validator.Validator): # because sometimes, we can be provided bad uids try : o = here.portal_catalog.getObject(uid) - except (KeyError, NotFound, ValueError), err: + except (KeyError, NotFound, ValueError) as err: # It is possible that this object is not catalogged yet. So # the object must be obtained from ZODB. if object_list is None: @@ -2847,7 +2847,7 @@ class ListBoxValidator(Validator.Validator): try: row_result[sql] = error_result[error_result_key] = \ editable_field._validate_helper(key, REQUEST) - except ValidationError, err: + except ValidationError as err: err.field_id = error_result_key errors.append(err) except KeyError: diff --git a/product/ERP5Form/MatrixBox.py b/product/ERP5Form/MatrixBox.py index 9f0bfed115ea4fe9289620b744945464d45e7212..116c0175df7ac152610b50cb27619672754ace2d 100644 --- a/product/ERP5Form/MatrixBox.py +++ b/product/ERP5Form/MatrixBox.py @@ -600,7 +600,7 @@ class MatrixBoxValidator(Validator.Validator): external_validator = my_field.get_value('external_validator') if external_validator and not external_validator(value, REQUEST): my_field.validator.raise_error('external_validator_failed', my_field) - except ValidationError, err : + except ValidationError as err : err.field_id = my_field.id + '_cell_%s_%s_%s%s' % (i,j,k,extra_dimension_index) error_list.append(err) diff --git a/product/ERP5Form/OOoChart.py b/product/ERP5Form/OOoChart.py index 91052b4d5a72f570441527f30c01b0233cb89eac..fd33be414b14c5ca702738844e07aaefa22e947d 100644 --- a/product/ERP5Form/OOoChart.py +++ b/product/ERP5Form/OOoChart.py @@ -495,7 +495,7 @@ class OOoChartWidget(Widget.Widget): ''' % (url, UrlIconPdf) else: - raise NotImplementedError, 'Format: %s not handled' % format + raise NotImplementedError('Format: %s not handled' % format) extra_context = self.getArgumentDict(field, REQUEST) diff --git a/product/ERP5Form/PDFForm.py b/product/ERP5Form/PDFForm.py index 6da7958fd00f340f8e0da8a45bc7cf133262d714..571422b463441d2f14b210aafd159e54b8984979 100644 --- a/product/ERP5Form/PDFForm.py +++ b/product/ERP5Form/PDFForm.py @@ -127,15 +127,15 @@ class PDFTk: input = input.read() try : stdin.write(input) - except IOError, e: - raise IOError, str(e) + " ( make sure "\ - "%s exists and is in your $PATH )"%PDFTK_EXECUTABLE + except IOError as e: + raise IOError(str(e) + " ( make sure "\ + "%s exists and is in your $PATH )"%PDFTK_EXECUTABLE) stdin.close() ret = stdout.read() stdout.close() if assert_not_empty and len(ret) == 0 : - raise IOError, "Got no output from external program, make sure"\ - " %s exists and is in your $PATH"%PDFTK_EXECUTABLE + raise IOError("Got no output from external program, make sure"\ + " %s exists and is in your $PATH"%PDFTK_EXECUTABLE) return ret def _escapeString(self, value) : @@ -391,7 +391,7 @@ class PDFForm(File): for url in self.getProperty('download_url') : try : response = urllib.urlopen(url) - except IOError, e : + except IOError as e : LOG("PDFForm", WARNING, "Unable to download from %s" % url, e) continue if response.headers.getheader('Content-Type') != 'application/pdf': @@ -404,8 +404,8 @@ class PDFForm(File): "%s/manage_main?manage_tabs_message=Content+Downloaded" % self.absolute_url()) return - raise ValueError, "Unable to download from any url from the "\ - "`download_url` property." + raise ValueError("Unable to download from any url from the "\ + "`download_url` property.") security.declareProtected(Permissions.ManagePortal, 'deletePdfContent') @@ -445,7 +445,7 @@ class PDFForm(File): def doEditCells(self, REQUEST, RESPONSE=None): """ This is the action to the 'Edit Cell TALES' tab. """ if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): - raise ResourceLockedError, "File is locked via WebDAV" + raise ResourceLockedError("File is locked via WebDAV") for k, v in self.cells.items() : self.setCellTALES(k, REQUEST.get(str(k), v)) @@ -459,7 +459,7 @@ class PDFForm(File): def generatePDF(self, REQUEST=None, RESPONSE=None, *args, **kwargs) : """ generates the PDF with form filled in """ if not self.hasPdfContent() : - raise EmptyERP5PdfFormError, 'Pdf content must be downloaded first' + raise EmptyERP5PdfFormError('Pdf content must be downloaded first') values = self.calculateCellValues(REQUEST, *args, **kwargs) context = { 'here' : self.aq_parent, 'context' : self.aq_parent, @@ -557,7 +557,7 @@ class PDFForm(File): LOG("PDFForm", PROBLEM, 'TALES is not a string for cell "%s", it is = "%s"' %(cell_name, `TALES`)) - raise ValueError, 'TALES must be a string' + raise ValueError('TALES must be a string') self.all_cells[str(cell_name)] = self.cells[str(cell_name)] = TALES # invalidate for persistence self.all_cells = self.all_cells diff --git a/product/ERP5Form/PDFParser.py b/product/ERP5Form/PDFParser.py index 058ac73a1a6e19209dcb22e3cec93b84a3f1304b..0156d4ad4ff122a2433c11669ac1c6e5365812fc 100644 --- a/product/ERP5Form/PDFParser.py +++ b/product/ERP5Form/PDFParser.py @@ -53,7 +53,7 @@ class PDFParser: self.pages = None if pdf_file_descriptor is None: - raise ValueError, "No PDF file provided, please choose a pdf form " + raise ValueError("No PDF file provided, please choose a pdf form ") if type(pdf_file_descriptor) == 'str': @@ -80,8 +80,8 @@ class PDFParser: command_output = commands.getstatusoutput('pdfinfo %s' % \ temp_pdf_name) if command_output[0] != 0: - raise ValueError, 'Error: convert command failed with the following'\ - 'error message : \n%s' % command_output[1] + raise ValueError('Error: convert command failed with the following'\ + 'error message : \n%s' % command_output[1]) # get the pdf page size rawstr = r''' @@ -177,8 +177,8 @@ class PDFParser: command_output = commands.getstatusoutput('pdftk %s output %s flatten'\ % (temp_input_name, temp_output_name)) if command_output[0] != 0: - raise IOError, "pdftk failed with the following error %s"\ - % command_output[1] + raise IOError("pdftk failed with the following error %s"\ + % command_output[1]) temp_output = open(temp_output_name,'rb') temp_output.seek(0) datas = temp_output.read() diff --git a/product/ERP5Form/PDFTemplate.py b/product/ERP5Form/PDFTemplate.py index ab21db32c437228b6805348b9496384801793a12..97ce32a0565e51a75f2353e849b3195a9063084d 100644 --- a/product/ERP5Form/PDFTemplate.py +++ b/product/ERP5Form/PDFTemplate.py @@ -132,7 +132,7 @@ class PDFTemplate(ZopePageTemplate): Change title and pdf_stylesheet. """ if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): - raise ResourceLockedError, "File is locked via WebDAV" + raise ResourceLockedError("File is locked via WebDAV") self.pdf_stylesheet = pdf_stylesheet self.pt_setTitle(title) #REQUEST.set('text', self.read()) # May not equal 'text'! diff --git a/product/ERP5Form/PlanningBox.py b/product/ERP5Form/PlanningBox.py index 5606841494caacbe0a2efaa734a4de2898fd674c..f880d0b3aff625e5240156ad5efd7d10eeef400f 100644 --- a/product/ERP5Form/PlanningBox.py +++ b/product/ERP5Form/PlanningBox.py @@ -1777,14 +1777,14 @@ class BasicGroup: try: block_begin = obj.getProperty(object_property_begin, _marker) if block_begin is _marker: - raise AttributeError, object_property_begin + raise AttributeError(object_property_begin) except AttributeError: block_begin = getattr(obj, object_property_begin, None) try: block_end = obj.getProperty(object_property_end, _marker) if block_end is _marker: - raise AttributeError, object_property_end + raise AttributeError(object_property_end) except AttributeError: block_end = getattr(obj, object_property_end, None) diff --git a/product/ERP5Form/ProxyField.py b/product/ERP5Form/ProxyField.py index 240baa58f87ab86cc79f1981c586e0376545a889..d16fea2bd7981dc1addfeb119c9307c5b5ef585b 100644 --- a/product/ERP5Form/ProxyField.py +++ b/product/ERP5Form/ProxyField.py @@ -139,7 +139,7 @@ class ProxyValidator(Validator.Validator): proxy_field = field.getRecursiveTemplateField() try: result = proxy_field.validator.validate(field, key, REQUEST) - except ValidationError, error: + except ValidationError as error: error.field_id = field.id raise error return result @@ -195,7 +195,7 @@ class ProxyField(ZMIField): try: # validate the form and get results result = template_field.form.validate(REQUEST) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) @@ -213,7 +213,7 @@ class ProxyField(ZMIField): try: # validate the form and get results result = self.form.validate(REQUEST) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) @@ -305,7 +305,7 @@ class ProxyField(ZMIField): try: # validate the form and get results result = template_field.tales_form.validate(REQUEST) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) @@ -319,7 +319,7 @@ class ProxyField(ZMIField): try: # validate the form and get results result = self.tales_form.validate(REQUEST) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) @@ -638,7 +638,7 @@ class ProxyField(ZMIField): if proxied_field.__class__ == ProxyField: field = proxied_field elif proxied_field is None: - raise ValueError, "Can't find the template field of %s" % self.id + raise ValueError("Can't find the template field of %s" % self.id) else: tales = proxied_field.get_tales(id) if tales: diff --git a/product/ERP5Form/Report.py b/product/ERP5Form/Report.py index e66d8e2eb6e3d3de9dec032bc7bf85ef416924f0..30a791befb135161252553b29f811264270e9734 100644 --- a/product/ERP5Form/Report.py +++ b/product/ERP5Form/Report.py @@ -127,7 +127,7 @@ class ERP5Report(ERP5Form): def __call__(self, *args, **kwargs): warn("ERP5Report to be obsolete, please use ReportBox and normal ERP5Form instead.", DeprecationWarning) if not self.report_method: - raise KeyError, 'report method is not set on the report' + raise KeyError('report method is not set on the report') if not kwargs.has_key('args'): kwargs['args'] = args @@ -284,7 +284,7 @@ class ReportSection: def pushRequest(self): self = aq_base(self) if hasattr(self, '_REQUEST'): - raise ValueError, "can not replace the backupped REQUEST" + raise ValueError("can not replace the backupped REQUEST") self._REQUEST = {'form': {}, 'other': {},} REQUEST = get_request() self._REQUEST['form'].update(REQUEST.form) @@ -294,7 +294,7 @@ class ReportSection: def popRequest(self): self = aq_base(self) if not hasattr(self, '_REQUEST'): - raise ValueError, "no backupped REQUEST" + raise ValueError("no backupped REQUEST") REQUEST = get_request() REQUEST.form.clear() REQUEST.other.clear() diff --git a/product/ERP5Form/ScribusParser.py b/product/ERP5Form/ScribusParser.py index edcc32c54f515241a34386bf046ef2c95be84256..bba88cba756247e8cdc15d45c57f839f6cdcf436 100644 --- a/product/ERP5Form/ScribusParser.py +++ b/product/ERP5Form/ScribusParser.py @@ -44,7 +44,7 @@ class ScribusParser: or the content of the file """ if scribus_file_descriptor is None: - raise ValueError, "No Scribus file provided, please choose a Scibus Form" + raise ValueError("No Scribus file provided, please choose a Scibus Form") if type(scribus_file_descriptor) == 'str': data = scribus_file_descriptor diff --git a/product/ERP5Form/ScribusUtils.py b/product/ERP5Form/ScribusUtils.py index a623501e0e50ae69210378f541501086bf623a68..ec935d0ec981c563facab552415322b9ee05bd35 100644 --- a/product/ERP5Form/ScribusUtils.py +++ b/product/ERP5Form/ScribusUtils.py @@ -652,8 +652,8 @@ class ManageFiles: if os.path.exists(background_image): os.remove(background_image) - raise ValueError, 'Error: convert command failed with the following'\ - 'error message : \n%s' % result[1] + raise ValueError('Error: convert command failed with the following'\ + 'error message : \n%s' % result[1]) finally: temp_pdf.close() @@ -661,8 +661,8 @@ class ManageFiles: if not len(background_image_list): LOG('ScribusUtils.setBackgroundPictures :', ERROR, 'no background '\ 'image found') - raise ValueError, 'Error: ScribusUtils.setBackgroundPictures : '\ - 'no background' + raise ValueError('Error: ScribusUtils.setBackgroundPictures : '\ + 'no background') # get the real size of the first image # this could be usefull if the user only defined one dimention : @@ -736,8 +736,8 @@ class ManageFiles: if command_output[0] != 0: LOG('ScribusUtils.getPageAttributes :', ERROR, 'pdfinfo command'\ 'failed with the following error message : \n%s' % command_output[1]) - raise ValueError, 'Error: convert command failed with the following'\ - 'error message : \n%s' % command_output[1] + raise ValueError('Error: convert command failed with the following'\ + 'error message : \n%s' % command_output[1]) # get the pdf page size rawstr = r''' diff --git a/product/ERP5Form/Tool/SelectionTool.py b/product/ERP5Form/Tool/SelectionTool.py index 1a316d2f72337e837446188f552ddf0f1931075d..f4b25f6fd0a4cbe274f04587b60b5516edfc2477 100644 --- a/product/ERP5Form/Tool/SelectionTool.py +++ b/product/ERP5Form/Tool/SelectionTool.py @@ -161,13 +161,13 @@ class SelectionTool( BaseTool, SimpleItem ): self.storage = storage self.clearCachedContainer() else: - raise ValueError, 'Given storage type (%s) is now supported.' % (storage,) + raise ValueError('Given storage type (%s) is now supported.' % (storage,)) anonymous_storage = anonymous_storage or None if anonymous_storage in [item[1] for item in self.getStorageItemList()] + [None]: self.anonymous_storage = anonymous_storage self.clearCachedContainer(is_anonymous=True) else: - raise ValueError, 'Given storage type (%s) is now supported.' % (anonymous_storage,) + raise ValueError('Given storage type (%s) is now supported.' % (anonymous_storage,)) if RESPONSE is not None: RESPONSE.redirect('%s/manage_configure' % (self.absolute_url())) @@ -1232,8 +1232,8 @@ class SelectionTool( BaseTool, SimpleItem ): relation_index += 1 if not relation_field_found: # We didn't find the field... - raise SelectionError, "SelectionTool: can not find the relation" \ - " field %s" % index + raise SelectionError("SelectionTool: can not find the relation" \ + " field %s" % index) else: # Field found field_key = field.generate_field_key() diff --git a/product/ERP5Form/tests/testFields.py b/product/ERP5Form/tests/testFields.py index d7f54b728bb96537484d386755b87a879efd8437..3db161c54b7a564839415189dfd63cee350e4a1f 100644 --- a/product/ERP5Form/tests/testFields.py +++ b/product/ERP5Form/tests/testFields.py @@ -382,7 +382,7 @@ class TestDateTimeField(ERP5TypeTestCase): .xpath('%s/text()' % ODG_XML_WRAPPING_XPATH, namespaces=NSMAP)[0]) def test_render_odt_variable(self): - value = DateTime(2010, 12, 06, 10, 23, 32, 'GMT+5') + value = DateTime(2010, 12, 6, 10, 23, 32, 'GMT+5') self.field.values['default'] = value node = self.field.render_odt_variable(as_string=False) self.assertEqual(node.get('{%s}value-type' % NSMAP['office']), 'date') diff --git a/product/ERP5Form/tests/testListBox.py b/product/ERP5Form/tests/testListBox.py index ab20a97a95dcb028e417d5a44bb6d84580e69873..7d56989552d628dfc8c26e0488e65566cc07c92e 100644 --- a/product/ERP5Form/tests/testListBox.py +++ b/product/ERP5Form/tests/testListBox.py @@ -240,7 +240,7 @@ class TestListBox(ERP5TypeTestCase): request['here'] = portal.foo_module try: listbox.get_value('default', render_format='list', REQUEST=request) - except UnicodeError, e: + except UnicodeError as e: self.fail('Rendering failed: %s' % e) self.assertIn(u"\xe9lisa", listbox.render(REQUEST=request)) @@ -270,7 +270,7 @@ class TestListBox(ERP5TypeTestCase): request['here'] = portal.foo_module try: listbox.get_value('default', render_format='list', REQUEST=request) - except UnicodeError, e: + except UnicodeError as e: self.fail('Rendering failed: %s' % e) self.assertIn(u"\xe9lisa", listbox.render(REQUEST=request)) @@ -304,7 +304,7 @@ class TestListBox(ERP5TypeTestCase): request['here'] = portal.foo_module try: rendered = listbox.get_value('default', render_format='list', REQUEST=request) - except UnicodeError, e: + except UnicodeError as e: self.fail('Rendering failed: %s' % e) self.assertIn(u"http://example.com/?\xe9lisa", listbox.render(REQUEST=request)) @@ -338,7 +338,7 @@ class TestListBox(ERP5TypeTestCase): request['here'] = portal.foo_module try: rendered = listbox.get_value('default', render_format='list', REQUEST=request) - except UnicodeError, e: + except UnicodeError as e: self.fail('Rendering failed: %s' % e) self.assertIn(u"http://example.com/?\xe9lisa", listbox.render(REQUEST=request)) @@ -360,7 +360,7 @@ class TestListBox(ERP5TypeTestCase): listbox.get_value('default', render_format='list', REQUEST=request) try: self.commit() - except TypeError, e: + except TypeError as e: self.fail('Unable to commit transaction: %s' % e) def test_06_LineFields(self, quiet=0, run=run_all_test): diff --git a/product/ERP5Form/tests/testPreferences.py b/product/ERP5Form/tests/testPreferences.py index 62cac31b283e7611320813d6ad65857dd01dde59..c9925456a58048d1bccca5811c2b164dc3c5989c 100644 --- a/product/ERP5Form/tests/testPreferences.py +++ b/product/ERP5Form/tests/testPreferences.py @@ -275,7 +275,7 @@ class TestPreferences(PropertySheetTestCase): portal_workflow.doActionFor( person1, 'enable_action', wf_id='preference_workflow') self.assertEqual(person1.getPreferenceState(), 'enabled') - person1.setPreferredAccountingTransactionAtDate(DateTime(2005, 01, 01)) + person1.setPreferredAccountingTransactionAtDate(DateTime(2005, 1, 1)) pref_tool.setPreference( 'preferred_accounting_transaction_at_date', DateTime(2004, 12, 31)) self.tic() @@ -315,7 +315,7 @@ class TestPreferences(PropertySheetTestCase): # create a pref for user_b user_b_1 = portal_preferences.newContent( id='user_b_1', portal_type='Preference') - user_b_1.setPreferredAccountingTransactionAtDate(DateTime(2002, 02, 02)) + user_b_1.setPreferredAccountingTransactionAtDate(DateTime(2002, 2, 2)) self.tic() # enable this preference diff --git a/product/ERP5OOo/Document/OOoDocument.py b/product/ERP5OOo/Document/OOoDocument.py index e32f40943b65cf45aaed358589e818835f04630f..bd62f19e963b788c9d4af6fa1cdd28bd435d97e5 100644 --- a/product/ERP5OOo/Document/OOoDocument.py +++ b/product/ERP5OOo/Document/OOoDocument.py @@ -111,12 +111,12 @@ class OOoServerProxy(): # Cloudooo return result in (200 or 402, dict(), '') format or just based type # 402 for error and 200 for ok result_set = func(*args, **kw) - except SocketError, e: + except SocketError as e: message = 'Socket Error: %s' % (repr(e) or 'undefined.') socket_error_list.append(message) retry_server_list.append(server_proxy) continue - except ProtocolError, e: + except ProtocolError as e: # Network issue message = "%s: %s %s" % (e.url, e.errcode, e.errmsg) if e.errcode == -1: @@ -124,7 +124,7 @@ class OOoServerProxy(): protocol_error_list.append(message) retry_server_list.append(server_proxy) continue - except Fault, e: + except Fault as e: # Return not supported data types fault_error_list.append(e) continue @@ -279,7 +279,7 @@ class OOoDocument(OOoDocumentExtensibleTraversableMixin, BaseConvertableFileMixi " formats for conversion (Code %s: %s)" % ( response_code, response_message)) - except Fault, f: + except Fault as f: allowed = server_proxy.getAllowedTargets(content_type) warn('Your oood version is too old, using old method ' 'getAllowedTargets instead of getAllowedTargetList', diff --git a/product/ERP5OOo/FormPrintout.py b/product/ERP5OOo/FormPrintout.py index 8cca90f5654bae4c0eeba17e70aa5bf2df066a34..7f79456b8a984717e7f57f2d474e5319e6e7c742 100644 --- a/product/ERP5OOo/FormPrintout.py +++ b/product/ERP5OOo/FormPrintout.py @@ -220,7 +220,7 @@ class FormPrintout(Implicit, Persistent, RoleManager, Item, PropertyManager): elif self.template: printout_template = getattr(obj, self.template) else: - raise ValueError, 'Can not create a ODF Document without a printout template' + raise ValueError('Can not create a ODF Document without a printout template') report_method = None if hasattr(form, 'report_method'): @@ -248,7 +248,7 @@ class FormPrintout(Implicit, Persistent, RoleManager, Item, PropertyManager): def doSettings(self, REQUEST, title='', form_name='', template='', filename='object/title_or_id'): """Change title, form_name, template, filename.""" if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): - raise ResourceLockedError, "File is locked via WebDAV" + raise ResourceLockedError("File is locked via WebDAV") self.form_name = form_name self.template = template self.title = title @@ -264,7 +264,7 @@ class FormPrintout(Implicit, Persistent, RoleManager, Item, PropertyManager): return ODTStrategy() if guess_extension(content_type) == '.odg': return ODGStrategy() - raise ValueError, 'Template type: %s is not supported' % content_type + raise ValueError('Template type: %s is not supported' % content_type) def _oooConvertByFormat(self, printout, content_type, extra_context, REQUEST, format, batch_mode): @@ -337,11 +337,11 @@ class ODFStrategy(Implicit): """ here = extra_context['here'] if here is None: - raise ValueError, 'Can not create a ODF Document without a parent acquisition context' + raise ValueError('Can not create a ODF Document without a parent acquisition context') form = extra_context['form'] if not extra_context.has_key('printout_template') or \ extra_context['printout_template'] is None: - raise ValueError, 'Can not create a ODF Document without a printout template' + raise ValueError('Can not create a ODF Document without a printout template') odf_template = extra_context['printout_template'] diff --git a/product/ERP5OOo/OOoTemplate.py b/product/ERP5OOo/OOoTemplate.py index 6d8645087f7feb6b9f83f9cf21c049c6cb0455de..a2c8f97a3cba4e0b5daa457bb93e0b0240e6b046 100644 --- a/product/ERP5OOo/OOoTemplate.py +++ b/product/ERP5OOo/OOoTemplate.py @@ -206,10 +206,10 @@ class OOoTemplate(ZopePageTemplate): def pt_upload(self, REQUEST, file=''): """Replace the document with the text in file.""" if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): - raise ResourceLockedError, "File is locked via WebDAV" + raise ResourceLockedError("File is locked via WebDAV") if type(file) is not StringType: - if not file: raise ValueError, 'File not specified' + if not file: raise ValueError('File not specified') file = file.read() if file.startswith("PK") : # FIXME: this condition is probably not enough @@ -258,7 +258,7 @@ class OOoTemplate(ZopePageTemplate): Change title, xml_file_id and ooo_stylesheet. """ if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): - raise ResourceLockedError, "File is locked via WebDAV" + raise ResourceLockedError("File is locked via WebDAV") self.ooo_stylesheet = ooo_stylesheet self.ooo_script_name = script_name self.ooo_xml_file_id = xml_file_id @@ -452,7 +452,7 @@ class OOoTemplate(ZopePageTemplate): here = getattr(self, 'aq_parent', None) if here is None: # This is a system error - raise ValueError, 'Can not render a template without a parent acquisition context' + raise ValueError('Can not render a template without a parent acquisition context') # Retrieve master document ooo_document = None # If script is setting, call it diff --git a/product/ERP5OOo/OOoUtils.py b/product/ERP5OOo/OOoUtils.py index 420d37ce8924742f3364d7b026a63663006276e5..96ee648e59c89990d8f2140e1212063cf47f301f 100644 --- a/product/ERP5OOo/OOoUtils.py +++ b/product/ERP5OOo/OOoUtils.py @@ -242,7 +242,7 @@ class OOoParser(Implicit): # Try to unzip the Open Office doc try: oo_unzipped = ZipFile(file_descriptor, mode="r") - except Exception, e: + except Exception as e: LOG('ERP5OOo', DEBUG, 'Error in openFile', error=sys.exc_info()) raise CorruptedOOoFile(e) # Test the integrity of the file diff --git a/product/ERP5OOo/tests/testOOoImport.py b/product/ERP5OOo/tests/testOOoImport.py index 55d1cfd26d2828cf47ef7fad627735142422e290..a6b3692c5507f78ce22f705305fb42a8404a7b8c 100644 --- a/product/ERP5OOo/tests/testOOoImport.py +++ b/product/ERP5OOo/tests/testOOoImport.py @@ -789,7 +789,7 @@ class TestOOoImport(TestOOoImportMixin): try: self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping( import_file=import_file) - except ValueError, error: + except ValueError as error: # 'france' is the duplicate ID in this spreadsheet self.assertTrue('france' in str(error), str(error)) else: @@ -818,7 +818,7 @@ class TestOOoImport(TestOOoImportMixin): try: self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping( import_file=import_file) - except ValueError, error: + except ValueError as error: # 'wrong_hierarchy' is the ID of the category where the problem happens self.assertTrue('wrong_hierarchy' in str(error), str(error)) else: @@ -832,7 +832,7 @@ class TestOOoImport(TestOOoImportMixin): try: self.portal.portal_categories.Base_getCategoriesSpreadSheetMapping( import_file=import_file) - except ValueError, error: + except ValueError as error: self.assertTrue('More that one path is defined' in str(error), str(error)) else: self.fail('ValueError not raised') diff --git a/product/ERP5OOo/transforms/__init__.py b/product/ERP5OOo/transforms/__init__.py index d273b8f564aaf8a3b944351564d890416c53f420..40dc936abbee9ae0496a5810e2c19febecf43f04 100644 --- a/product/ERP5OOo/transforms/__init__.py +++ b/product/ERP5OOo/transforms/__init__.py @@ -26,12 +26,12 @@ for m in modules: try: ns = __import__(m, g, g, None) transforms.append(ns.register()) - except ImportError, e: + except ImportError as e: msg = "Problem importing module %s : %s" % (m, e) log(msg, severity=ERROR) - except MissingBinary, e: + except MissingBinary as e: log(str(e), severity=DEBUG) - except Exception, e: + except Exception as e: import traceback traceback.print_exc() log("Raised error %s for %s" % (e, m), severity=ERROR) diff --git a/product/ERP5SecurePayment/Tool/SecurePaymentTool.py b/product/ERP5SecurePayment/Tool/SecurePaymentTool.py index 6208d821a13e8b30246cec5477ea42e81cdaedcd..d3bfee8e3389da256c1488e85ed24ecc32e971c7 100644 --- a/product/ERP5SecurePayment/Tool/SecurePaymentTool.py +++ b/product/ERP5SecurePayment/Tool/SecurePaymentTool.py @@ -60,7 +60,7 @@ class SecurePaymentTool(BaseTool): if len(result) > 0: 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): user = getSecurityManager().getUser() diff --git a/product/ERP5Security/ERP5KeyAuthPlugin.py b/product/ERP5Security/ERP5KeyAuthPlugin.py index 0bc4cca575f1fe3ad5c5533312aaff36b345afeb..97edfc9e34eae87679db4345aa76826160e00d51 100644 --- a/product/ERP5Security/ERP5KeyAuthPlugin.py +++ b/product/ERP5Security/ERP5KeyAuthPlugin.py @@ -105,7 +105,7 @@ class CesarCipher: #check lenght of the string clogin_length = len(crypted_login) if clogin_length % self.block_length != 0: - raise ValueError, "Lenght is not good" + raise ValueError("Lenght is not good") #decrypt block per block position = 0 key_length = len(self.encrypted_key) @@ -196,7 +196,7 @@ class ERP5KeyAuthPlugin(ERP5UserManager, CookieAuthHelper): if encryption_key is None or encryption_key == '': encryption_key = id if "__ac_key" in [cookie_name, default_cookie_name]: - raise ValueError, "Cookie name must be different of __ac_key" + raise ValueError("Cookie name must be different of __ac_key") #Register value self._setId(id) @@ -277,7 +277,7 @@ class ERP5KeyAuthPlugin(ERP5UserManager, CookieAuthHelper): creds['remote_address'] = request.getClientAddr() except AttributeError: creds['remote_address'] = request.get('REMOTE_ADDR', '') - except StandardError, e: + except StandardError as e: #Log standard error to check error LOG('ERP5KeyAuthPlugin.extractCredentials', PROBLEM, str(e)) @@ -373,7 +373,7 @@ class ERP5KeyAuthPlugin(ERP5UserManager, CookieAuthHelper): return _authenticateCredentials(login=login) except _AuthenticationFailure: return None - except StandardError, e: + except StandardError as e: #Log standard error LOG('ERP5KeyAuthPlugin.authenticateCredentials', PROBLEM, str(e)) return None @@ -396,7 +396,7 @@ class ERP5KeyAuthPlugin(ERP5UserManager, CookieAuthHelper): #Test paramaeters if "__ac_key" in [cookie_name, default_cookie_name]: - raise ValueError, "Cookie name must be different of __ac_key" + raise ValueError("Cookie name must be different of __ac_key") #Save key if encryption_key == '' or encryption_key is None: diff --git a/product/ERP5ShortMessage/Document/EssendexGateway.py b/product/ERP5ShortMessage/Document/EssendexGateway.py index 089a2a7854d5ee5791a21407921e7b3aa769b51f..a664a820dc6e4e5d7eb4939bf4525f5a24c68734 100644 --- a/product/ERP5ShortMessage/Document/EssendexGateway.py +++ b/product/ERP5ShortMessage/Document/EssendexGateway.py @@ -173,7 +173,7 @@ class EssendexGateway(XMLObject): return message_ids.split(",") elif result['Result'] == "Error": #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": #just a test, no message id return None @@ -200,7 +200,7 @@ class EssendexGateway(XMLObject): return result.get('MessageStatus').lower() elif result['Result'] == "Error": #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') def receive(self,REQUEST): @@ -210,7 +210,7 @@ class EssendexGateway(XMLObject): datas = REQUEST['BODY'] if not datas: - raise SMSGatewayError, "Impossible to notify nothing" + raise SMSGatewayError("Impossible to notify nothing") #Get current user sm = getSecurityManager() @@ -232,18 +232,18 @@ class EssendexGateway(XMLObject): #Check Account id 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': self.notifyReception(xml) elif notification_type == 'MessageDelivered': self.notifyDelivery(xml) 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': - raise SMSGatewayError, "'MessageError' notification is not implemented (%s)" % str(kw) + raise SMSGatewayError("'MessageError' notification is not implemented (%s)" % str(kw)) else: - raise SMSGatewayError, "Unknow '%s' notification (%s)" % (notification_type, str(kw)) + raise SMSGatewayError("Unknow '%s' notification (%s)" % (notification_type, str(kw))) finally: #Restore orinal user setSecurityManager(sm) @@ -346,6 +346,6 @@ class EssendexGateway(XMLObject): LOG("EssendexGateway", INFO, result) elif result['Result'] == "Error": #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"))) diff --git a/product/ERP5ShortMessage/Document/MobytGateway.py b/product/ERP5ShortMessage/Document/MobytGateway.py index ba99f2ccae7a0098fb678931bb30e2df33fadac5..784ce98c2e54d52664733476326967834f2b6ec3 100644 --- a/product/ERP5ShortMessage/Document/MobytGateway.py +++ b/product/ERP5ShortMessage/Document/MobytGateway.py @@ -189,7 +189,7 @@ class MobytGateway(XMLObject): return [result.get('status_info', "")] #return message id (gateway side) elif result['status'] == "KO": #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": #just a test, no message id return None @@ -224,7 +224,7 @@ class MobytGateway(XMLObject): elif result['status'] == "KO": #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') def receive(self,REQUEST): diff --git a/product/ERP5SyncML/Document/SyncMLSubscription.py b/product/ERP5SyncML/Document/SyncMLSubscription.py index 76229b9339f431056ef35550fb0ff9c3c36cf08c..fc105aefd5a138e3ded5087f79d9fcd2f809c6c6 100644 --- a/product/ERP5SyncML/Document/SyncMLSubscription.py +++ b/product/ERP5SyncML/Document/SyncMLSubscription.py @@ -1036,11 +1036,11 @@ class SyncMLSubscription(XMLObject): else: result_list = query_method(**kw) else: - raise KeyError, 'This Subscriber %s provide no list method:%r'\ - % (self.getPath(), list_method_id) + raise KeyError('This Subscriber %s provide no list method:%r'\ + % (self.getPath(), list_method_id)) else: - raise KeyError, 'This Subscriber %s provide no list method with id:%r'\ - % (self.getPath(), list_method_id) + raise KeyError('This Subscriber %s provide no list method with id:%r'\ + % (self.getPath(), list_method_id)) return result_list security.declareProtected(Permissions.ModifyPortalContent, 'generateNewSessionId') @@ -1107,7 +1107,7 @@ class SyncMLSubscription(XMLObject): if id == document.getId(): return signature else: # XXX-Aurel : maybe none is expected - raise KeyError, id + raise KeyError(id) security.declareProtected(Permissions.AccessContentsInformation, 'getSignatureFromGid') diff --git a/product/ERP5SyncML/ERP5SyncMLMobileServer.py b/product/ERP5SyncML/ERP5SyncMLMobileServer.py index 395b3e927539d2bae4f74d9a23ac2a41499d1a90..bd4e637c8ac0d09de13a414986490821c3926634 100755 --- a/product/ERP5SyncML/ERP5SyncMLMobileServer.py +++ b/product/ERP5SyncML/ERP5SyncMLMobileServer.py @@ -172,9 +172,9 @@ def sendResponse(text, to_url, client_url): try: result = urllib2.urlopen(request).read() - except socket.error, msg: + except socket.error as msg: print 'error, url:%s ,data : %s'%(to_url, data) - except urllib2.URLError, msg: + except urllib2.URLError as msg: print "sendResponse, can't open url : %s" % to_url return result diff --git a/product/ERP5SyncML/Utils.py b/product/ERP5SyncML/Utils.py index 70bf1701d6b159fbd64011df44c3b32ae3df34c8..f587f755c8f04dc6c0486167bbc9b778ae63252d 100644 --- a/product/ERP5SyncML/Utils.py +++ b/product/ERP5SyncML/Utils.py @@ -77,7 +77,7 @@ class PdataHelper(persistent.Persistent): value = StringIO(value) if isinstance(value, FileUpload) and not value: - raise ValueError, 'File not specified' + raise ValueError('File not specified') if isinstance(value, Pdata): size = self._read_size_from_pdata(value) diff --git a/product/ERP5SyncML/XMLSyncUtils.py b/product/ERP5SyncML/XMLSyncUtils.py index 6b71138bc1c0eac692ab2bf1caa65b0af32571d7..ef04fb90f8013871f931b3bddd3532035b2bc8aa 100644 --- a/product/ERP5SyncML/XMLSyncUtils.py +++ b/product/ERP5SyncML/XMLSyncUtils.py @@ -62,8 +62,8 @@ def encode(format, string_to_encode): #elif format is .... put here the other formats else:#if there is no format corresponding with format, raise an error LOG('encode : unknown or not implemented format : ', INFO, format) - raise ValueError, "Sorry, the server ask for the format %s but \ - it's unknow or not implemented" % format + raise ValueError("Sorry, the server ask for the format %s but \ + it's unknow or not implemented" % format) def decode(format, string_to_decode): """ @@ -77,8 +77,8 @@ def decode(format, string_to_decode): #elif format is .... put here the other formats else:#if there is no format corresponding with format, raise an error LOG('decode : unknown or not implemented format :', INFO, format) - raise ValueError, "Sorry, the format %s is unknow or \ - not implemented" % format + raise ValueError("Sorry, the format %s is unknow or \ + not implemented" % format) def isDecodeEncodeTheSame(string_encoded, string_decoded, format): """ diff --git a/product/ERP5TioSafe/Conduit/AccountingERP5IntegrationConduit.py b/product/ERP5TioSafe/Conduit/AccountingERP5IntegrationConduit.py index 6a413a403081d4cf802f691bf318b0145b5a8ac9..07d03d90d6037943ba66162a3e7a7234572dba14 100644 --- a/product/ERP5TioSafe/Conduit/AccountingERP5IntegrationConduit.py +++ b/product/ERP5TioSafe/Conduit/AccountingERP5IntegrationConduit.py @@ -78,7 +78,7 @@ class AccountingERP5IntegrationConduit(TioSafeBaseConduit): 'PP', 'SA', 'SR', 'VP', 'VR'): return 'Payment Transaction' else: - raise "getObjectType: ERROR journal code unknow" + raise ValueError("getObjectType: ERROR journal code unknow") return def constructContent(self, object, object_id, portal_type): diff --git a/product/ERP5TioSafe/Conduit/ERP5NodeConduit.py b/product/ERP5TioSafe/Conduit/ERP5NodeConduit.py index 55617ead24e0bd07c4f6616be64f73804c469b04..a4d3c36c63531d9b12d56abcd6396e720e472e76 100644 --- a/product/ERP5TioSafe/Conduit/ERP5NodeConduit.py +++ b/product/ERP5TioSafe/Conduit/ERP5NodeConduit.py @@ -61,7 +61,7 @@ class ERP5NodeConduit(TioSafeBaseConduit): destination=object.getRelativeUrl(), destination_decision=object.getRelativeUrl(), destination_administration=object.getRelativeUrl(), - version=001) + version='001') stc.validate() def _updateSaleTradeCondition(self, object, **kw): @@ -76,8 +76,8 @@ class ERP5NodeConduit(TioSafeBaseConduit): if len(stc_list) == 0: self._createSaleTradeCondition(object, **kw) elif len(stc_list) > 1: - raise ValueError, "Multiple trade condition (%s) retrieved for %s" \ - % ([x.path for x in stc_list], object.getTitle()) + raise ValueError("Multiple trade condition (%s) retrieved for %s" \ + % ([x.path for x in stc_list], object.getTitle())) else: stc = stc_list[0].getObject() stc.edit( @@ -155,7 +155,7 @@ class ERP5NodeConduit(TioSafeBaseConduit): if link_object is not None: document.setCareerSubordinationValue(link_object) 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() return [] diff --git a/product/ERP5TioSafe/Conduit/ERP5PaymentTransactionConduit.py b/product/ERP5TioSafe/Conduit/ERP5PaymentTransactionConduit.py index 1c9e04efb32a0bb3c8ea0b49b36e64f8caafaa04..2164805ec4fa3a7a19f0a42d580005126817c07d 100644 --- a/product/ERP5TioSafe/Conduit/ERP5PaymentTransactionConduit.py +++ b/product/ERP5TioSafe/Conduit/ERP5PaymentTransactionConduit.py @@ -81,7 +81,7 @@ class ERP5PaymentTransactionConduit(TioSafeBaseConduit): # Create the STC stc = object.getPortalObject().sale_trade_condition_module.newContent(title=stc_title, specialise=default_stc, - version=001) + version='001') stc.validate() return stc @@ -156,7 +156,7 @@ class ERP5PaymentTransactionConduit(TioSafeBaseConduit): if tag in node_dict: node_dict[tag](document=sub_object, xml=node, **kw) 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']: if not node.text: node.text = None diff --git a/product/ERP5TioSafe/Conduit/ERP5ResourceConduit.py b/product/ERP5TioSafe/Conduit/ERP5ResourceConduit.py index 41a680cb9a6e1c4069c76fbe36c4344faa6fdda4..cc8d5a1e4e1cd4aedba7b593fb1720dad5365965 100644 --- a/product/ERP5TioSafe/Conduit/ERP5ResourceConduit.py +++ b/product/ERP5TioSafe/Conduit/ERP5ResourceConduit.py @@ -145,7 +145,7 @@ class ERP5ResourceConduit(TioSafeBaseConduit): conflict_list = self._createMapping(sub_object, mapping_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( object=sub_object, @@ -236,7 +236,7 @@ class ERP5ResourceConduit(TioSafeBaseConduit): ss_list = portal.sale_supply_module.searchFolder(title=name, validation_state='validated') 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: # Create a new one ss = portal.sale_supply_module.newContent(title=name) @@ -253,7 +253,7 @@ class ERP5ResourceConduit(TioSafeBaseConduit): pref_list = [x for x in portal.portal_preferences.objectValues(portal_type="System Preference")\ if x.getPreferenceState()=="global"] 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: pref = portal.portal_preferences.newContent(portal_type="System Preference", title="default system preference for TioSafe", @@ -380,9 +380,9 @@ class ERP5ResourceConduit(TioSafeBaseConduit): try: previous_value = previous_xml[0].text except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml, - ) + )) if isinstance(previous_value, unicode): previous_value = previous_value.encode('utf-8') @@ -549,9 +549,9 @@ class ERP5ResourceConduit(TioSafeBaseConduit): try: previous_value = previous_xml[0].text except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) if isinstance(previous_value, unicode): previous_value = previous_value.encode('utf-8') diff --git a/product/ERP5TioSafe/Conduit/ERP5TransactionConduit.py b/product/ERP5TioSafe/Conduit/ERP5TransactionConduit.py index 8165b8f00cbe77e565f27da8e99c231193ba9589..764848148a507bbfa8b12ef88eb3fd25a112e914 100644 --- a/product/ERP5TioSafe/Conduit/ERP5TransactionConduit.py +++ b/product/ERP5TioSafe/Conduit/ERP5TransactionConduit.py @@ -107,7 +107,7 @@ class ERP5TransactionConduit(TioSafeBaseConduit): if tag in node_dict: node_dict[tag](document=sub_object, xml=node, **kw) 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': link_object = object.portal_catalog.getResultValue( portal_type='Currency', @@ -290,7 +290,7 @@ class ERP5TransactionConduit(TioSafeBaseConduit): break # in the worse case save the line with the unknown product 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 movement_dict_value[tag] = link_object diff --git a/product/ERP5TioSafe/Conduit/TioSafeBaseConduit.py b/product/ERP5TioSafe/Conduit/TioSafeBaseConduit.py index a4accc3896e4a03f12f047a9045ed7da33d7b149..1a0633f331c22cf750652d19badcef985de0be7f 100644 --- a/product/ERP5TioSafe/Conduit/TioSafeBaseConduit.py +++ b/product/ERP5TioSafe/Conduit/TioSafeBaseConduit.py @@ -160,11 +160,11 @@ class TioSafeBaseConduit(ERP5Conduit): else: related_object_list = [x.getObject() for x in sync_object.Base_getRelatedObjectList()] 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() if integration_site.getPortalType() != "Integration Site": - raise ValueError, "Did not get an Integration Site object instead %s : %s" %(integration_site.getPortalType(), - integration_site.getPath()) + raise ValueError("Did not get an Integration Site object instead %s : %s" %(integration_site.getPortalType(), + integration_site.getPath())) self.integration_site = integration_site return self.integration_site @@ -187,7 +187,7 @@ class TioSafeBaseConduit(ERP5Conduit): elif synchronization_type == "subscription": result_list.append(module.getDestinationSectionValue()) else: - raise ValueError, 'Unknown type %s' %(synchronization_type,) + raise ValueError('Unknown type %s' %(synchronization_type,)) return result_list diff --git a/product/ERP5TioSafe/Conduit/TioSafeNodeConduit.py b/product/ERP5TioSafe/Conduit/TioSafeNodeConduit.py index 42995a85f0530d73a80893af6f519727d96e5e69..378613e282fa31478c5ae311627c8c13d1b0b5c6 100644 --- a/product/ERP5TioSafe/Conduit/TioSafeNodeConduit.py +++ b/product/ERP5TioSafe/Conduit/TioSafeNodeConduit.py @@ -104,9 +104,9 @@ class TioSafeNodeConduit(TioSafeBaseConduit): try: previous_value = previous_xml[0].text except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) # check if it'a work on person or on address if tag in ['street', 'zip', 'city', 'country']: diff --git a/product/ERP5TioSafe/Conduit/TioSafeResourceConduit.py b/product/ERP5TioSafe/Conduit/TioSafeResourceConduit.py index d02cd67fb4c5730d5c32910512180765d30b5a5e..ba0c3efe4e416f1330c6f6d978df61258a867875 100644 --- a/product/ERP5TioSafe/Conduit/TioSafeResourceConduit.py +++ b/product/ERP5TioSafe/Conduit/TioSafeResourceConduit.py @@ -81,7 +81,7 @@ class TioSafeResourceConduit(TioSafeBaseConduit): if create_method is not None: create_result = create_method(**keyword) 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): # We suppose the id of the object created was returned by the plugin new_id = create_result[0].getId() @@ -128,7 +128,7 @@ class TioSafeResourceConduit(TioSafeBaseConduit): if delete_method is not None: return delete_method(product_id=object_id) 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): @@ -147,9 +147,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit): try: previous_value = previous_xml[0].text except IndexError: - raise ValueError, 'Too little or too many value, only one is required for %s' % ( + raise ValueError('Too little or too many value, only one is required for %s' % ( previous_xml - ) + )) if isinstance(previous_value, unicode): previous_value = previous_value.encode('utf-8') @@ -208,9 +208,9 @@ class TioSafeResourceConduit(TioSafeBaseConduit): selected_previous_xml[0].text, ) except IndexError: - raise IndexError, 'Too little or too many value, only one is required for %s' % ( + raise IndexError('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)) # retrieve the current value to check if exists a conflict current_value = etree.XML(object_xml).xpath(tag)[0].text diff --git a/product/ERP5TioSafe/ConnectionPlugin/HTTPConnection.py b/product/ERP5TioSafe/ConnectionPlugin/HTTPConnection.py index f6cacbbfc8a808335861635739c2a0562f9ce5d4..2d3a4efa4e37debda09022f8552594915bed30bd 100644 --- a/product/ERP5TioSafe/ConnectionPlugin/HTTPConnection.py +++ b/product/ERP5TioSafe/ConnectionPlugin/HTTPConnection.py @@ -46,10 +46,10 @@ class MethodWrapper(object): try: response = urlopen(request) return url, response.read() - except HTTPError, msg: + except HTTPError as msg: error = "Impossible to access to the plugin, error code is %s - %s" %(msg.msg, msg.code,) raise ConnectionError(error) - except URLError, msg: + except URLError as msg: error = "Impossible to connect to the plugin, reason is %s" %(msg.reason,) raise ConnectionError(error) diff --git a/product/ERP5TioSafe/ConnectionPlugin/MagentoXMLRPCConnection.py b/product/ERP5TioSafe/ConnectionPlugin/MagentoXMLRPCConnection.py index b1e217c66d8514234898143449bbc92a1843281e..6d4fb8ef9b91052482501e73ad1312e8b32292e8 100644 --- a/product/ERP5TioSafe/ConnectionPlugin/MagentoXMLRPCConnection.py +++ b/product/ERP5TioSafe/ConnectionPlugin/MagentoXMLRPCConnection.py @@ -43,7 +43,7 @@ class MethodWrapper(object): else: return self._method, self._conn.server.call(self._conn.session, self._method, [args]) - except Fault, msg: + except Fault as msg: error = "XMLRPC error, reason is %s : %s" %(msg.faultCode, msg.faultString,) raise ConnectionError(error) diff --git a/product/ERP5TioSafe/ConnectionPlugin/OxatisConnection.py b/product/ERP5TioSafe/ConnectionPlugin/OxatisConnection.py index 2a738c922649a398abced96ae456175ce2d841c0..c4e252c01cbd4a7c6a6f0d2985b8f695a29520c2 100644 --- a/product/ERP5TioSafe/ConnectionPlugin/OxatisConnection.py +++ b/product/ERP5TioSafe/ConnectionPlugin/OxatisConnection.py @@ -99,7 +99,7 @@ class OxatisMethodWrapper(MethodWrapper): if sub_error_code == RECORD_NOT_FOUND: raise KeyError elif sub_error_code == INVALID_DATA: - raise TypeError, "Invalid data sent to WebService, url = %s, args =%s, kw = %s" %(url, args, kw) + raise TypeError("Invalid data sent to WebService, url = %s, args =%s, kw = %s" %(url, args, kw)) else: raise ValueError(error_message) else: diff --git a/product/ERP5TioSafe/ConnectionPlugin/RESTConnection.py b/product/ERP5TioSafe/ConnectionPlugin/RESTConnection.py index 1d2f7de662ac16ade2ff4a4e3d32be2ab4ba240c..a984ad5bbf71a0236c336826b29533f3fda73be8 100644 --- a/product/ERP5TioSafe/ConnectionPlugin/RESTConnection.py +++ b/product/ERP5TioSafe/ConnectionPlugin/RESTConnection.py @@ -46,10 +46,10 @@ class MethodWrapper(object): try: response = urlopen(request) return self._conn.url, response.read() - except HTTPError, msg: + except HTTPError as msg: error = "Impossible to access to the plugin, error code is %s - %s" %(msg.msg, msg.code,) raise ConnectionError(error) - except URLError, msg: + except URLError as msg: error = "Impossible to connect to the plugin, reason is %s" %(msg.reason,) raise ConnectionError(error) diff --git a/product/ERP5TioSafe/Document/IntegrationModule.py b/product/ERP5TioSafe/Document/IntegrationModule.py index d1f21ab235a71601d2e914497a199d04ac38cedd..3b7042e344f40616bb3229b98f00d8cefb40495e 100644 --- a/product/ERP5TioSafe/Document/IntegrationModule.py +++ b/product/ERP5TioSafe/Document/IntegrationModule.py @@ -95,8 +95,8 @@ class IntegrationModule(XMLObject): return self.getObjectList(id=item) else: return self.getObjectList[item] - except ValueError, msg: - raise KeyError, msg + except ValueError as msg: + raise KeyError(msg) security.declareProtected(Permissions.AccessContentsInformation, 'getGIDFor') diff --git a/product/ERP5TioSafe/Document/IntegrationSite.py b/product/ERP5TioSafe/Document/IntegrationSite.py index 10d9eeb6ee0cdd952f8a244122816296ec49cb4d..8da1dc22eb070017ff22756e1762a130aad53fdc 100644 --- a/product/ERP5TioSafe/Document/IntegrationSite.py +++ b/product/ERP5TioSafe/Document/IntegrationSite.py @@ -78,7 +78,7 @@ class IntegrationSite(Folder): """ if not category: 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 base_category, variation_category = category.split('/', 1) @@ -110,7 +110,7 @@ class IntegrationSite(Folder): # only the base category has to be mapped if missing_mapping or current_object.getDestinationReference() is None: # 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] else: # Create default line that has to be mapped by user later @@ -125,12 +125,12 @@ class IntegrationSite(Folder): missing_mapping = True else: 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() if mapped_category in ("", None) and cat_object.getPortalType() == "Integration Category Mapping": 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: mapped_base_category = mapped_category else: @@ -143,7 +143,7 @@ class IntegrationSite(Folder): ## category)) if missing_mapping: # 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] security.declareProtected(Permissions.AccessContentsInformation, @@ -165,7 +165,7 @@ class IntegrationSite(Folder): destination_reference=base_category, ) 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() # retrieve the corresponding category integration mapping @@ -174,7 +174,7 @@ class IntegrationSite(Folder): destination_reference=category, ) 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: # shared variation return '/'.join( @@ -204,7 +204,7 @@ class IntegrationSite(Folder): destination_reference=property_name, ) 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: return property_name else: diff --git a/product/ERP5TioSafe/Tool/OAuthTool.py b/product/ERP5TioSafe/Tool/OAuthTool.py index 697af6fc9ba15030029f87b3bde8dfebb00c21ec..7c4f4fc6fbadc28ba9edd304557260cec8155856 100644 --- a/product/ERP5TioSafe/Tool/OAuthTool.py +++ b/product/ERP5TioSafe/Tool/OAuthTool.py @@ -687,7 +687,7 @@ class OAuthTool(BaseTool): # self.end_headers() # # return the token # self.wfile.write(token.to_string()) - except OAuthError, err: + except OAuthError as err: raise LOG("Error returned %s" %(err,), 300, "") self.send_oauth_error(err, REQUEST) @@ -709,7 +709,7 @@ class OAuthTool(BaseTool): # self.end_headers() # # return the callback url (to show server has it) # self.wfile.write(token.get_callback_url()) - except OAuthError, err: + except OAuthError as err: self.send_oauth_error(err, REQUEST) return @@ -723,7 +723,7 @@ class OAuthTool(BaseTool): # send okay response LOG("calling the callback url %s" %(token.get_callback_url(),), 300, "") return REQUEST.RESPONSE.redirect(token.get_callback_url()) - except OAuthError, err: + except OAuthError as err: self.send_oauth_error(err, REQUEST) return @@ -739,7 +739,7 @@ class OAuthTool(BaseTool): # self.end_headers() # # return the token # self.wfile.write(token.to_string()) - except OAuthError, err: + except OAuthError as err: self.send_oauth_error(err, REQUEST) return @@ -754,7 +754,7 @@ class OAuthTool(BaseTool): # # return the extra parameters - just for something to return # self.wfile.write(str(params)) return str(params) - except OAuthError, err: + except OAuthError as err: self.send_oauth_error(err, REQUEST) return diff --git a/product/ERP5TioSafe/__init__.py b/product/ERP5TioSafe/__init__.py index 360e178f63c4db8c7faf3a54ff8b357f9d2ec585..e09238bd66a95b8d4941262a4c0cd46e146ccc01 100644 --- a/product/ERP5TioSafe/__init__.py +++ b/product/ERP5TioSafe/__init__.py @@ -78,7 +78,7 @@ for handler_id, module_id in handler_module_dict.iteritems(): else: try: registerConnectionPlugin(handler_id, getattr(module, module_id)) - except ValueError, msg: + except ValueError as msg: LOG('ERP5TioSafe.ConnectionPlugin.__init__', WARNING, 'Unable to register module %r. error is %r.' % \ (module_id, msg), diff --git a/product/ERP5TioSafe/tests/testPersonERP5Synchronization.py b/product/ERP5TioSafe/tests/testPersonERP5Synchronization.py index 4a984c4a3f7cd29be036775f2883fa225ef51e7c..acfe6567ad66592b05a51d21c4ccc8e710e414a8 100644 --- a/product/ERP5TioSafe/tests/testPersonERP5Synchronization.py +++ b/product/ERP5TioSafe/tests/testPersonERP5Synchronization.py @@ -155,8 +155,8 @@ class TestPersonERP5Synchronization(testPrestashopMixin): self.assertEqual(address.getCity(), 'Dortmund') self.assertEqual(address.getRegionTitle(), 'Allemagne') else: - raise ValueError, 'Can not check the address: %s of the person: %s' % \ - (address.getId(), person.getTitle()) + raise ValueError('Can not check the address: %s of the person: %s' % \ + (address.getId(), person.getTitle())) # Check the XML schema and the fixed point self.checkTioSafeXML( plugin_xml=self.root_xml % person.Node_asTioSafeXML(), @@ -336,8 +336,8 @@ class TestPersonERP5Synchronization(testPrestashopMixin): self.assertEqual(address.getCity(), 'Paris') self.assertEqual(address.getRegionTitle(), 'France') else: - raise ValueError, 'Can not check the address: %s of the person: %s' % \ - (index, person.getTitle()) + raise ValueError('Can not check the address: %s of the person: %s' % \ + (index, person.getTitle())) # The first update check remove of simple element, remove an address self.loadSQLDump( self.connection, @@ -389,8 +389,8 @@ class TestPersonERP5Synchronization(testPrestashopMixin): self.assertEqual(address.getCity(), 'Stuttgart') self.assertEqual(address.getRegionTitle(), 'Allemagne') else: - raise ValueError, 'Can not check the address: %s of the person: %s' % \ - (index, person.getTitle()) + raise ValueError('Can not check the address: %s of the person: %s' % \ + (index, person.getTitle())) # Check the XML schema and the fixed point self.checkTioSafeXML( plugin_xml=self.root_xml % person.Node_asTioSafeXML(), diff --git a/product/ERP5TioSafe/tests/testProductERP5Synchronization.py b/product/ERP5TioSafe/tests/testProductERP5Synchronization.py index d7001df2b9d5105033211b4e721bfd8061d6c8af..c31e71d281bed8ac18fd043170ee2631bc254772 100644 --- a/product/ERP5TioSafe/tests/testProductERP5Synchronization.py +++ b/product/ERP5TioSafe/tests/testProductERP5Synchronization.py @@ -131,8 +131,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): self.assertEqual(title, 'Noir') self.assertEqual(base_category_list, ['colour', ]) else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (index, product.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (index, product.getTitle())) # Check the XML schema and the fixed point self.checkTioSafeXML( plugin_xml= self.root_xml % product.Resource_asTioSafeXML(), @@ -178,8 +178,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): elif i == 3: self.assertEqual(variation, 'colour/white') else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (variation, product.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (variation, product.getTitle())) # Check the XML schema and the fixed point self.checkTioSafeXML( plugin_xml= self.root_xml % product.Resource_asTioSafeXML(), @@ -238,8 +238,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): elif i == 1: self.assertEqual(variation, 'colour/white') else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (variation, product.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (variation, product.getTitle())) individual_variation_list = product.searchFolder( portal_type='Product Individual Variation', sort_on=(['id', 'ASC'], ), @@ -259,8 +259,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): self.assertEqual(title, 's5') self.assertEqual(base_category_list, ['ball_size']) else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (index, product.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (index, product.getTitle())) # Check the XML schema and the fixed point self.checkTioSafeXML( plugin_xml= self.root_xml % product.Resource_asTioSafeXML(), @@ -340,8 +340,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): self.assertEqual(title, 's5') self.assertEqual(base_category_list, ['ball_size']) else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (index, product_2.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (index, product_2.getTitle())) # Check the product 'Ballon de foot' product_3 = self.product_module.searchFolder( portal_type='Product', @@ -364,8 +364,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): elif i == 1: self.assertEqual(variation, 'colour/white') else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (variation, product_3.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (variation, product_3.getTitle())) # Check the product 'Ballon de Basket' product_4 = self.product_module.searchFolder( portal_type='Product', @@ -384,8 +384,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): elif i == 1: self.assertEqual(variation, 'colour/white') else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (variation, product_4.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (variation, product_4.getTitle())) individual_variation_list = product_4.searchFolder( portal_type='Product Individual Variation', sort_on=(['id', 'ASC'], ), @@ -405,8 +405,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): self.assertEqual(title, 's5') self.assertEqual(base_category_list, ['ball_size']) else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (index, product_4.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (index, product_4.getTitle())) # Check the XML schema and the fixed point self.checkTioSafeXML( plugin_xml= self.root_xml % product_1.Resource_asTioSafeXML(), @@ -612,8 +612,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): self.assertEqual(title, 's5') self.assertEqual(base_category_list, ['ball_size']) else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (individual_variation.getId(), product.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (individual_variation.getId(), product.getTitle())) # The first update remove, add and update some elements but not realise an # hard work on variations self.loadSQLDump( @@ -656,8 +656,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): self.assertEqual(title, 's6') self.assertEqual(base_category_list, ['ball_size']) else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (index, product.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (index, product.getTitle())) # The second update remove variations (individuals and shareds) self.loadSQLDump( self.connection, @@ -721,8 +721,8 @@ class TestProductERP5Synchronization(testPrestashopMixin): self.assertEqual(title, 's6') self.assertEqual(base_category_list, ['ball_size']) else: - raise ValueError, 'Can not check variation: %s of the product: %s' % \ - (individual_variation.getId(), product.getTitle()) + raise ValueError('Can not check variation: %s of the product: %s' % \ + (individual_variation.getId(), product.getTitle())) # Check the XML schema and the fixed point self.checkTioSafeXML( plugin_xml= self.root_xml % product.Resource_asTioSafeXML(), diff --git a/product/ERP5TioSafe/tests/testProductPrestashopSynchronization.py b/product/ERP5TioSafe/tests/testProductPrestashopSynchronization.py index 715154d4aed2f32ccb404dcee96f1c3c2be66f0b..7d478d2a353718a15774ad03e9bde4e74cac0b77 100644 --- a/product/ERP5TioSafe/tests/testProductPrestashopSynchronization.py +++ b/product/ERP5TioSafe/tests/testProductPrestashopSynchronization.py @@ -438,7 +438,7 @@ class TestProductPrestashopSynchronization(testPrestashopMixin): pref_list = portal.portal_preferences.searchFolder(portal_type="System Preference", validation_state="enabled") 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: pref = portal.portal_preferences.newContent(portal_type="System Preference", title="default system preference for TioSafe", diff --git a/product/ERP5TioSafe/tests/testSaleOrderERP5Synchronization.py b/product/ERP5TioSafe/tests/testSaleOrderERP5Synchronization.py index 52c4cc9002a748d625d3e610ca3f395a13b9b9cb..a65c01356a4f2342175b541ba5bcfc45e3d9f56d 100644 --- a/product/ERP5TioSafe/tests/testSaleOrderERP5Synchronization.py +++ b/product/ERP5TioSafe/tests/testSaleOrderERP5Synchronization.py @@ -272,7 +272,7 @@ class TestSaleOrderERP5Synchronization(testPrestashopMixin): self.assertEqual(round(line.getPrice(), 6), 6.672241) self.assertEqual(line.getPriceCurrencyValue(), currency) else: - raise 'A line has not been checked' + self.fail('A line has not been checked') # Check the XML schema and the fixed point self.checkTioSafeXML( tiosafe_xml=self.root_xml % sale_order.Transaction_asTioSafeXML(context_document=self.portal.portal_synchronizations.ps_SaleOrder_pub.getPath()), @@ -373,7 +373,7 @@ class TestSaleOrderERP5Synchronization(testPrestashopMixin): self.assertEqual(round(line.getPrice(), 6), 6.672241) self.assertEqual(line.getPriceCurrencyValue(), currency) else: - raise 'A line has not been checked' + self.fail('A line has not been checked') # Check the XML schema and the fixed point self.checkTioSafeXML( tiosafe_xml=self.root_xml % sale_order.Transaction_asTioSafeXML(context_document=self.portal.portal_synchronizations.ps_SaleOrder_pub.getPath()), @@ -527,7 +527,7 @@ class TestSaleOrderERP5Synchronization(testPrestashopMixin): self.assertEqual(round(line.getPrice(), 6), 6.672241) self.assertEqual(line.getPriceCurrencyValue(), currency) else: - raise 'A line has not been checked' + self.fail('A line has not been checked') # Check the XML schema and the fixed point self.checkTioSafeXML( tiosafe_xml=self.root_xml % sale_order.Transaction_asTioSafeXML(context_document=self.portal.portal_synchronizations.ps_SaleOrder_pub.getPath()), @@ -810,7 +810,7 @@ class TestSaleOrderERP5Synchronization(testPrestashopMixin): self.assertEqual(round(line.getPrice(), 6), 6.672241) self.assertEqual(line.getPriceCurrencyValue(), currency) else: - raise 'A line has not been checked' + self.fail('A line has not been checked') # Check the XML schema and the fixed point self.checkTioSafeXML( tiosafe_xml=self.root_xml % sale_order.Transaction_asTioSafeXML(context_document=self.portal.portal_synchronizations.ps_SaleOrder_pub.getPath()), @@ -912,7 +912,7 @@ class TestSaleOrderERP5Synchronization(testPrestashopMixin): else: self.assertTrue(line.getTitle() in ['Delivery', 'Stylo']) - raise 'A line has not been checked' + self.fail('A line has not been checked') # Check the accounting sale_packing_list = sale_order.getCausalityRelatedValue( portal_type='Sale Packing List', @@ -959,7 +959,7 @@ class TestSaleOrderERP5Synchronization(testPrestashopMixin): self.assertEqual(line.getPrice(), 0.0) self.assertEqual(line.getTotalPrice(), 0.0) else: - raise 'The lines must contain VAT, Product or Delivery, nothing else.' + self.fail('The lines must contain VAT, Product or Delivery, nothing else.') # Check the XML schema and the fixed point self.checkTioSafeXML( tiosafe_xml=self.root_xml % sale_order.Transaction_asTioSafeXML(context_document=self.portal.portal_synchronizations.ps_SaleOrder_pub.getPath()), diff --git a/product/ERP5TioSafe/tests/testTioSafeMixin.py b/product/ERP5TioSafe/tests/testTioSafeMixin.py index 75133d63acbe405470903f857af47511e385a5cd..c05085449d4f5e602088d8266bb39a5e6032230a 100644 --- a/product/ERP5TioSafe/tests/testTioSafeMixin.py +++ b/product/ERP5TioSafe/tests/testTioSafeMixin.py @@ -317,7 +317,7 @@ class testTioSafeMixin(ERP5TypeTestCase): diff = "\n" for x in unified_diff(plugin_xml.split('\n'), tiosafe_xml.split('\n'), "plugin", "tiosafe", lineterm=''): diff += "%s\n" %(x) - raise AssertionError, diff + raise AssertionError(diff) def validateXMLSchema(self, xml, file_path): """ This method allows to check and validate the schema of an xml. """ diff --git a/product/ERP5Type/Base.py b/product/ERP5Type/Base.py index b6f536435a2fd1c5cee3a7b2ba5fc325160bb73e..ed9b96e9d36793baf0b2f77fc1fecd6995abfccb 100644 --- a/product/ERP5Type/Base.py +++ b/product/ERP5Type/Base.py @@ -239,7 +239,7 @@ class WorkflowMethod(Method): except ObjectDeleted: # Re-raise with a different result. raise ObjectDeleted(result) - except ObjectMoved, ex: + except ObjectMoved as ex: # Re-raise with a different result. raise ObjectMoved(ex.getNewObject(), result) @@ -1297,8 +1297,7 @@ class Base( CopyContainer, if value_len == 1: mono_value = value[0] return method(mono_value, **kw) - raise TypeError, \ - "A mono valued property must be set with a list of len 1" + raise TypeError("A mono valued property must be set with a list of len 1") # Finaly use standard PropertyManager #LOG("Changing attr: ",0, key) # If we are here, this means we do not use a property that @@ -3326,7 +3325,7 @@ class Base( CopyContainer, """ parent = self.getParentValue() if parent.getPortalType() != "Preference" and not parent.isTemplate: - raise ValueError, "Template documents can not be created outside Preferences" + raise ValueError("Template documents can not be created outside Preferences") self.isTemplate = ConstantGetter('isTemplate', value=True) # XXX reset security here @@ -3336,7 +3335,7 @@ class Base( CopyContainer, Make document behave as standard document (indexable) """ if self.getParentValue().getPortalType() == "Preference": - raise ValueError, "Template instances can not be created within Preferences" + raise ValueError("Template instances can not be created within Preferences") # We remove attributes from the instance # We do this rather than self.isIndexable = 0 because we want to # go back to previous situation (class based definition) @@ -3432,9 +3431,9 @@ class Base( CopyContainer, Use an Unrestricted method to edit related relations on other objects. """ if self.getPortalType() == portal_type: - raise TypeError, 'Can not migrate a document to same portal_type' + raise TypeError('Can not migrate a document to same portal_type') if not portal_type: - raise TypeError, 'Missing portal_type value' + raise TypeError('Missing portal_type value') # Reingestion requested with portal_type. input_kw = {} diff --git a/product/ERP5Type/Cache.py b/product/ERP5Type/Cache.py index 214c2491960815a5e21f48a5d15e46e3391c98d4..c974a398c3335d162581a08a46cad35615958ba5 100644 --- a/product/ERP5Type/Cache.py +++ b/product/ERP5Type/Cache.py @@ -246,10 +246,10 @@ class CachingMethod: cache_factory is the id of the cache_factory to use. """ if not callable(callable_object): - raise CachedMethodError, "callable_object %s is not callable" % str( - callable_object) + raise CachedMethodError("callable_object %s is not callable" % str( + callable_object)) if not id: - raise CachedMethodError, "id must be specified" + raise CachedMethodError("id must be specified") self.id = id self.callable_object = callable_object self.cache_duration = cache_duration diff --git a/product/ERP5Type/CachePlugins/RamCache.py b/product/ERP5Type/CachePlugins/RamCache.py index 61eeb7eae9af61eb6d72fc74280ee7690acb2e99..83642aa7ce00bf0db9344d79495915ebc2ab5716 100644 --- a/product/ERP5Type/CachePlugins/RamCache.py +++ b/product/ERP5Type/CachePlugins/RamCache.py @@ -81,7 +81,7 @@ class RamCache(BaseCache): #Delete expired CacheEntry self.delete(cache_id, scope) if default is _MARKER: - raise KeyError, 'CacheEntry for key %s not Found' % ((scope, cache_id),) + raise KeyError('CacheEntry for key %s not Found' % ((scope, cache_id),)) return default def set(self, cache_id, scope, value, cache_duration=None, calculation_time=0): diff --git a/product/ERP5Type/ConnectionPlugin/SFTPConnection.py b/product/ERP5Type/ConnectionPlugin/SFTPConnection.py index 91ce992264edc15532c14851abe9e530f40e81d1..38b6e6520b12853eaba39e667ffaa779234b2b60 100644 --- a/product/ERP5Type/ConnectionPlugin/SFTPConnection.py +++ b/product/ERP5Type/ConnectionPlugin/SFTPConnection.py @@ -94,14 +94,14 @@ class SFTPConnection: raise SFTPError("No password or private_key defined") # Connect self.conn = SFTPClient.from_transport(self.transport) - except (gaierror, error), msg: + except (gaierror, error) as msg: raise SFTPError(str(msg) + ' while establishing connection to %s' % (self.url,)) # Go to specified directory try: schema.path.rstrip('/') if len(schema.path): self.conn.chdir(schema.path) - except IOError, msg: + except IOError as msg: raise SFTPError(str(msg) + ' while changing to dir -%r-' % (schema.path,)) return self @@ -113,7 +113,7 @@ class SFTPConnection: serialized_data = Binary(str(data)) try: self.conn.putfo(StringIO(str(serialized_data)), filepath, confirm=confirm) - except error, msg: + except error as msg: raise SFTPError(str(msg) + ' while writing file %s on %s' % (filepath, path, self.url)) def _getFile(self, filepath): @@ -125,7 +125,7 @@ class SFTPConnection: tmp_file = self.conn.file(filepath, 'rb') tmp_file.seek(0) return tmp_file.read() - except error, msg: + except error as msg: raise SFTPError(str(msg) + ' while retrieving file %s from %s' % (filepath, self.url)) def readBinaryFile(self, filepath): @@ -149,7 +149,7 @@ class SFTPConnection: if sort_on: return [x.filename for x in sorted(self.conn.listdir_attr(path), key=operator.attrgetter(sort_on))] return self.conn.listdir(path) - except (EOFError, error), msg: + except (EOFError, error) as msg: raise SFTPError(str(msg) + ' while trying to list %s on %s' % (path, self.url)) def getDirectoryFileList(self, path): @@ -160,18 +160,18 @@ class SFTPConnection: """Delete the file""" try: self.conn.unlink(filepath) - except error, msg: + except error as msg: raise SFTPError(str(msg) + 'while trying to delete %s on %s' % (filepath, self.url)) def renameFile(self, old_path, new_path): """Rename a file""" try: self.conn.rename(old_path, new_path) - except error, msg: + except error as msg: raise SFTPError('%s while trying to rename "%s" to "%s" on %s.' % \ (str(msg), old_path, new_path, self.url)) - def createDirectory(self, path, mode=0777): + def createDirectory(self, path, mode=0o777): """Create a directory `path` with mode `mode`. """ return self.conn.mkdir(path, mode) diff --git a/product/ERP5Type/ConnectionPlugin/SOAPWSDLConnection.py b/product/ERP5Type/ConnectionPlugin/SOAPWSDLConnection.py index f8f38fd91ed3a4b0550f3e6f6ce994e4ed7f56a5..707a7a2075094eb309d9283dbdecd12db01166c6 100644 --- a/product/ERP5Type/ConnectionPlugin/SOAPWSDLConnection.py +++ b/product/ERP5Type/ConnectionPlugin/SOAPWSDLConnection.py @@ -156,7 +156,7 @@ class MethodWrapper(object): def __call__(self, *args, **kw): try: return self._method(*args, **kw) - except SOAPpy.Types.faultType, exception: + except SOAPpy.Types.faultType as exception: raise SOAPWSDLException(*exception()) # SOAPpy says nothing about thread-safeness of parsed WSDL. diff --git a/product/ERP5Type/ConnectionPlugin/TimeoutTransport.py b/product/ERP5Type/ConnectionPlugin/TimeoutTransport.py index 741f14d5ef4ef092da05c9d2d93c3c9e230e7a29..a23e03e33a839c925276fb73251db101bf1a5974 100644 --- a/product/ERP5Type/ConnectionPlugin/TimeoutTransport.py +++ b/product/ERP5Type/ConnectionPlugin/TimeoutTransport.py @@ -47,6 +47,6 @@ class TimeoutTransport(SafeTransport): def send_content(self, connection, request_body): try: return SafeTransport.send_content(self, connection, request_body) - except socket.error, e: + except socket.error as e: raise ProtocolError(connection.host, -1, "Could not connect to server", None) diff --git a/product/ERP5Type/Constraint/PropertyTypeValidity.py b/product/ERP5Type/Constraint/PropertyTypeValidity.py index a755f64e565d2e7d406be537652ad81ec6b51cc0..04c43d3d9d2e1df34d5ce91946588c0b9359881b 100644 --- a/product/ERP5Type/Constraint/PropertyTypeValidity.py +++ b/product/ERP5Type/Constraint/PropertyTypeValidity.py @@ -122,7 +122,7 @@ class PropertyTypeValidity(Constraint): if wrong_type: try: value = self._type_dict[property_type][0](value) - except (KeyError, ValueError), error: + except (KeyError, ValueError) as error: error_message = 'message_incorrect_type_fix_failed' mapping['type_cast_error'] = str(error) diff --git a/product/ERP5Type/Constraint/TALESConstraint.py b/product/ERP5Type/Constraint/TALESConstraint.py index 2b214bdcbe89c2a6ca29f897b28232289fae2150..0153998d170ba6e7ee4c674c2b0e13da2d45f40b 100644 --- a/product/ERP5Type/Constraint/TALESConstraint.py +++ b/product/ERP5Type/Constraint/TALESConstraint.py @@ -78,7 +78,7 @@ class TALESConstraint(Constraint): self._getMessage('message_expression_false'))) except (ConflictError, CompilerError): raise - except Exception, e: + except Exception as e: LOG('ERP5Type', PROBLEM, 'TALESConstraint error on "%s" on %s' % (self.constraint_definition['expression'], obj), error=sys.exc_info()) error_list.append(self._generateError(obj, diff --git a/product/ERP5Type/CopySupport.py b/product/ERP5Type/CopySupport.py index d9d9c7bbde535715c70e232fbd1f12ecea841544..b7e57df4c26ffbc743c6de08d2771d215f9b2a7e 100644 --- a/product/ERP5Type/CopySupport.py +++ b/product/ERP5Type/CopySupport.py @@ -72,7 +72,7 @@ class CopyContainer: if uids is None and REQUEST is not None: return eNoItemsSpecified elif uids is None: - raise ValueError, 'uids must be specified' + raise ValueError('uids must be specified') if isinstance(uids, (str, int)): ids=[uids] @@ -80,7 +80,7 @@ class CopyContainer: for uid in uids: ob=self.getPortalObject().portal_catalog.getObject(uid) if not ob.cb_isCopyable(): - raise CopyError, eNotSupported % uid + raise CopyError(eNotSupported % uid) m=Moniker.Moniker(ob) oblist.append(m.dump()) cp=(0, oblist) @@ -163,8 +163,8 @@ class CopyContainer: pass # There is no activity tool else: if portal_activities.countMessage(path=ob.getPath())>0: - raise ActivityPendingError, 'Sorry, pending activities prevent ' \ - + 'changing id at this current stage' + raise ActivityPendingError('Sorry, pending activities prevent ' \ + + 'changing id at this current stage') # Search for categories that have to be updated in sub objects. self._recursiveSetActivityAfterTag(ob) @@ -187,7 +187,7 @@ class CopyContainer: if uids is None and REQUEST is not None: return eNoItemsSpecified elif uids is None: - raise ValueError, 'uids must be specified' + raise ValueError('uids must be specified') if isinstance(uids, (str, int)): ids=[uids] @@ -195,7 +195,7 @@ class CopyContainer: for uid in uids: ob=self.getPortalObject().portal_catalog.getObject(uid) if not ob.cb_isMoveable(): - raise CopyError, eNotSupported % id + raise CopyError(eNotSupported % id) m=Moniker.Moniker(ob) oblist.append(m.dump()) cp=(1, oblist) # 0->1 This is the difference with manage_copyObject diff --git a/product/ERP5Type/Core/DynamicCategoryProperty.py b/product/ERP5Type/Core/DynamicCategoryProperty.py index d5e3cc4c9440aa31fa69a765626fbbd4b0c721c3..c6dab46262fb612ef5357c5ed39863864215a3db 100644 --- a/product/ERP5Type/Core/DynamicCategoryProperty.py +++ b/product/ERP5Type/Core/DynamicCategoryProperty.py @@ -74,7 +74,7 @@ class DynamicCategoryProperty(CategoryProperty): self.applyDefinitionOnAccessorHolder(accessor_holder, category_id, portal) - except ValueError, e: + except ValueError as e: # If one of the category defined is invalid, don't give up as # the other ones may be fine LOG("ERP5Type.Core.DynamicCategoryProperty", INFO, diff --git a/product/ERP5Type/Core/Folder.py b/product/ERP5Type/Core/Folder.py index 6ba2c89f206c7d2a2536bc3b7168d81b5fdfb78b..37e9bf4bea1dce41f2df64a88f3c50a489b7dce2 100644 --- a/product/ERP5Type/Core/Folder.py +++ b/product/ERP5Type/Core/Folder.py @@ -189,9 +189,9 @@ class FolderMixIn(ExtensionClass.Base): if isinstance(my_id, str): self._delObject(my_id) else: - raise TypeError, error_message + str(type(my_id)) + raise TypeError(error_message + str(type(my_id))) else: - raise TypeError, error_message + str(type(id)) + raise TypeError(error_message + str(type(id))) def _generatePerDayId(self): """ @@ -1575,12 +1575,12 @@ class Folder(CopyContainer, OFSFolder2, CMFBTreeFolder, CMFHBTreeFolder, Base, F add_permission = getattr(aq_base(subobject_type), 'permission', '') if add_permission: if not sm.checkPermission(add_permission, self): - raise AccessControl_Unauthorized, add_permission + raise AccessControl_Unauthorized(add_permission) # handle validate_src if validate_src: if not sm.validate(None, parent, None, object): - raise AccessControl_Unauthorized, object.getId() + raise AccessControl_Unauthorized(object.getId()) if validate_src > 1: if not sm.checkPermission(Permissions.DeleteObjects, parent): raise AccessControl_Unauthorized @@ -1618,7 +1618,7 @@ class NotImplementedClass(object): self.__name__ = method_id def __call__(self, *args, **kw): - raise NotImplementedError, str(self.__name__) + raise NotImplementedError(str(self.__name__)) for source_klass, destination_klass in \ ( diff --git a/product/ERP5Type/Core/PropertySheet.py b/product/ERP5Type/Core/PropertySheet.py index b94e274aecbc0c74bc2962ad62725ae3f2b9e3e0..e1eaaca5a32319963a33e49e0587639673386b49 100644 --- a/product/ERP5Type/Core/PropertySheet.py +++ b/product/ERP5Type/Core/PropertySheet.py @@ -192,7 +192,7 @@ class PropertySheet(Folder): property_definition.applyOnAccessorHolder(accessor_holder, expression_context, portal) - except ValueError, e: + except ValueError as e: LOG("ERP5Type.Core.PropertySheet", INFO, "Invalid property '%s' for Property Sheet '%s': %s" % \ (property_definition.getId(), self.getId(), str(e))) diff --git a/product/ERP5Type/Core/PropertyTypeValidityConstraint.py b/product/ERP5Type/Core/PropertyTypeValidityConstraint.py index 3f748771155262ebc84b8d2c05f5b004c593d5a7..7dbdc086f2a9a6ef6965157f38d91887f9d76cf7 100644 --- a/product/ERP5Type/Core/PropertyTypeValidityConstraint.py +++ b/product/ERP5Type/Core/PropertyTypeValidityConstraint.py @@ -117,7 +117,7 @@ class PropertyTypeValidityConstraint(ConstraintMixin): if wrong_type: try: value = self._type_dict[property_type][0](value) - except (KeyError, ValueError), error: + except (KeyError, ValueError) as error: error_message = 'message_incorrect_type_fix_failed' mapping['type_cast_error'] = str(error) diff --git a/product/ERP5Type/Core/TALESConstraint.py b/product/ERP5Type/Core/TALESConstraint.py index bc005d0eee5e7f6250325b0c5d1f94129775c9d9..6c050fa061c230575e32377a6943df83ecb8f3fc 100644 --- a/product/ERP5Type/Core/TALESConstraint.py +++ b/product/ERP5Type/Core/TALESConstraint.py @@ -77,7 +77,7 @@ class TALESConstraint(ConstraintMixin): self._getMessage('message_expression_false'))] except (ConflictError, CompilerError): raise - except Exception, e: + except Exception as e: LOG('ERP5Type', PROBLEM, 'TALESConstraint error on "%s" on %s' % (expression_text, obj), error=sys.exc_info()) diff --git a/product/ERP5Type/DateUtils.py b/product/ERP5Type/DateUtils.py index 6186db0216b5a0cdf0af2bf637936c843b54718b..695eeeb8f5239f9718800973929265602c6887c8 100644 --- a/product/ERP5Type/DateUtils.py +++ b/product/ERP5Type/DateUtils.py @@ -447,7 +447,7 @@ def convertDateToHour(date=None): # and this provides the use of toordinal method. formatted_creation_date = datetime(creation_date_dict['year'],creation_date_dict['month'],creation_date_dict['day']) # reference date which is the first day of creation date year - reference_date = datetime(creation_date_dict['year'], 01, 1) + reference_date = datetime(creation_date_dict['year'], 1, 1) # calculate the ordinal date of the creation date and the reference date ordinal_date = datetime.toordinal(formatted_creation_date) ordinal_reference_date = datetime.toordinal(reference_date) @@ -526,7 +526,7 @@ def atTheEndOfPeriod(date, period): end = atTheEndOfPeriod(date, 'day') end = addToDate(end, day=(1-end.dow()) % 7) else: - raise NotImplementedError, 'Period "%s" not Handled yet' % period + raise NotImplementedError('Period "%s" not Handled yet' % period) return end def copyDate(date, year=None, month=None, day=None, diff --git a/product/ERP5Type/ExtensibleTraversable.py b/product/ERP5Type/ExtensibleTraversable.py index 6ca24875fdb53e1a4682e2c12917730ade7eb1e4..ba1553c706619ba1b5c9cd0012fd93026e25630a 100644 --- a/product/ERP5Type/ExtensibleTraversable.py +++ b/product/ERP5Type/ExtensibleTraversable.py @@ -53,4 +53,4 @@ class ExtensibleTraversableMixIn: try: request.RESPONSE.notFoundError("%s\n%s" % (name, method)) except AttributeError: - raise KeyError, name + raise KeyError(name) diff --git a/product/ERP5Type/ImageUtil.py b/product/ERP5Type/ImageUtil.py index 7ccc785287ba199a23767bbee83bda8457ee2a99..28c43a8e22ea852d81fa8c56a17fd1e3e1bc1af1 100644 --- a/product/ERP5Type/ImageUtil.py +++ b/product/ERP5Type/ImageUtil.py @@ -35,7 +35,7 @@ SVG_DEFAULT_NAMESPACE = "http://www.w3.org/2000/svg" def getDataURI(url): try: data = urllib2.urlopen(url) - except Exception, e: + except Exception as e: raise ConversionError("Error to transform url (%s) into data uri. ERROR = %s" % (url, Exception(e))) return 'data:%s;base64,%s' % (data.info()["content-type"], data.read().encode("base64").replace('\n', "")) diff --git a/product/ERP5Type/ObjectMessage.py b/product/ERP5Type/ObjectMessage.py index 3f31bb7262726766bc3d5bdc171666e16ea1acb5..1fc2951035e3eb8fd5a35584a6229f296440f502 100644 --- a/product/ERP5Type/ObjectMessage.py +++ b/product/ERP5Type/ObjectMessage.py @@ -77,13 +77,13 @@ class ObjectMessage: Wrap the message with the object """ if name.startswith('__') : - raise AttributeError, name + raise AttributeError(name) else: obj = self.getObject() if obj is not None: return getattr(obj, name) else: - raise AttributeError, name + raise AttributeError(name) def getObject(self): """ diff --git a/product/ERP5Type/SSHConnection.py b/product/ERP5Type/SSHConnection.py index 3c9aae4f5a5d6f31435e1246e01ad43c9c3fce23..af724c0e160a8f280bc911616470963a4898d45b 100644 --- a/product/ERP5Type/SSHConnection.py +++ b/product/ERP5Type/SSHConnection.py @@ -52,7 +52,7 @@ class SSHConnection(object): if os.path.exists(key_path): self.key_path = key_path else: - raise ValueError, 'key_path does not exist: %s' % key_path + raise ValueError('key_path does not exist: %s' % key_path) security.declarePublic(Permissions.ManagePortal, 'connect') def connect(self): @@ -63,7 +63,7 @@ class SSHConnection(object): rsa_key = paramiko.RSAKey.from_private_key_file(self.key_path) try: self.transport.connect(username=self.username, pkey=rsa_key) - except SSHException, e: + except SSHException as e: self.transport.close() raise SSHConnectionError(str(e)) else: diff --git a/product/ERP5Type/Tool/MemcachedTool.py b/product/ERP5Type/Tool/MemcachedTool.py index 2a16f36de65682b28922ab993ebf5d0c4a41d60b..6bd41ef545ff06e82cc169e05b8e73477742ea0b 100644 --- a/product/ERP5Type/Tool/MemcachedTool.py +++ b/product/ERP5Type/Tool/MemcachedTool.py @@ -246,7 +246,7 @@ if memcache is not None: def _prefixKey(self, key): 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 %s is not a string. Only strings are supported as key in SharedDict' % (repr(key), )) return '%s_%s' % (self.prefix, key) def __getitem__(self, key): @@ -317,8 +317,8 @@ else: if this function is called and memcachedtool is disabled, fail loudly with a meaningfull message. """ - raise RuntimeError, 'MemcachedTool is disabled. You should ask the'\ - ' server administrator to enable it by installing python-memcached.' + raise RuntimeError('MemcachedTool is disabled. You should ask the'\ + ' server administrator to enable it by installing python-memcached.') memcached_tool_configure = failingMethod getMemcachedDict = failingMethod diff --git a/product/ERP5Type/Tool/SessionTool.py b/product/ERP5Type/Tool/SessionTool.py index 861e5a679c2a294790912bf78a887c2c8e2533c4..c636b564d0687f086bc3da9a8d997fe32359daf9 100644 --- a/product/ERP5Type/Tool/SessionTool.py +++ b/product/ERP5Type/Tool/SessionTool.py @@ -96,7 +96,7 @@ class RamSession(Session): # returned it wrapped in aquisition context value = value.__of__(self._aq_context) return value - raise KeyError, key + raise KeyError(key) def __setitem__(self, key, item): # save value without its acquisition context diff --git a/product/ERP5Type/Utils.py b/product/ERP5Type/Utils.py index 5074dee6e4a04b1382c8e3dfc888599418189254..22e732284c95a41e08108ead67c7707a0fd3260d 100644 --- a/product/ERP5Type/Utils.py +++ b/product/ERP5Type/Utils.py @@ -253,7 +253,7 @@ def convertToUpperCase(key): return _cached_convertToUpperCase[key] except KeyError: if not isinstance(key, basestring): - raise TypeError, '%s is not a string' % (key,) + raise TypeError('%s is not a string' % (key,)) _cached_convertToUpperCase[key] = ''.join([part.capitalize() for part in key.split('_')]) return _cached_convertToUpperCase[key] @@ -278,7 +278,7 @@ def convertToMixedCase(key): a method name according to the ERP5 naming conventions """ if not isinstance(key, basestring): - raise TypeError, '%s is not a string' % (key,) + raise TypeError('%s is not a string' % (key,)) parts = str(key).split('_', 1) if len(parts) == 2: parts[1] = convertToUpperCase(parts[1]) @@ -437,11 +437,11 @@ def checkPythonSourceCode(source_code_str, portal_type=None): try: from pylint.lint import Run from pylint.reporters.text import TextReporter - except ImportError, error: + except ImportError as error: try: compile(source_code_str, '', 'exec') return [] - except Exception, error: + except Exception as error: if isinstance(error, SyntaxError): message = {'type': 'F', 'row': error.lineno, @@ -672,7 +672,7 @@ def writeLocalPropertySheet(class_id, text, create=1, instance_home=None): path = os.path.join(path, "%s.py" % class_id) if create: if os.path.exists(path): - raise IOError, 'the file %s is already present' % path + raise IOError('the file %s is already present' % path) with open(path, 'w') as f: f.write(text) # load the file, so that an error is raised if file is invalid @@ -838,7 +838,7 @@ def writeLocalExtension(class_id, text, create=1, instance_home=None): path = os.path.join(path, "%s.py" % class_id) if create: if os.path.exists(path): - raise IOError, 'the file %s is already present' % path + raise IOError('the file %s is already present' % path) with open(path, 'w') as f: f.write(text) @@ -852,7 +852,7 @@ def writeLocalTest(class_id, text, create=1, instance_home=None): path = os.path.join(path, "%s.py" % class_id) if create: if os.path.exists(path): - raise IOError, 'the file %s is already present' % path + raise IOError('the file %s is already present' % path) with open(path, 'w') as f: f.write(text) @@ -866,7 +866,7 @@ def writeLocalConstraint(class_id, text, create=1, instance_home=None): path = os.path.join(path, "%s.py" % class_id) if create: if os.path.exists(path): - raise IOError, 'the file %s is already present' % path + raise IOError('the file %s is already present' % path) with open(path, 'w') as f: f.write(text) # load the file, so that an error is raised if file is invalid @@ -925,7 +925,7 @@ def writeLocalDocument(class_id, text, create=1, instance_home=None): path = os.path.join(path, "%s.py" % class_id) if create: if os.path.exists(path): - raise IOError, 'the file %s is already present' % path + raise IOError('the file %s is already present' % path) # check there is no syntax error (that's the most we can do at this time) compile(text, path, 'exec') with open(path, 'w') as f: @@ -1045,7 +1045,7 @@ def initializeLocalRegistry(directory_name, import_local_method): LOG('ERP5Type', BLATHER, 'Added local %s to ERP5Type repository: %s (%s)' % (directory_name, module_name, document_path)) - except Exception, e: + except Exception as e: if DevelopmentMode: raise LOG('E5RP5Type', PROBLEM, @@ -1319,7 +1319,7 @@ def evaluateExpressionFromString(expression_context, expression_string): # An AttributeError is raised when instanciating an Expression # class, and CompilerError and ValueError are raised in case of # error when evaluation the expression - except (AttributeError, CompilerError, ValueError), e: + except (AttributeError, CompilerError, ValueError) as e: raise ValueError("Error in TALES expression: '%s': %s" % (expression_string, str(e))) @@ -1334,7 +1334,7 @@ def isValidTALESExpression(value): """ try: ExpressionEngine.compile(value) - except CompilerError, message: + except CompilerError as message: return False, message else: return True, None @@ -1364,7 +1364,7 @@ def assertAttributePortalType(o, attribute_name, portal_type): portal_type = [portal_type] if getattr(o, attribute_name).portal_type not in portal_type: o._delObject(attribute_name) - except (KeyError, AttributeError), err: + except (KeyError, AttributeError) as err: LOG('ERP5Type', PROBLEM, "assertAttributePortalType failed on %s" % o, error=err) @@ -1732,7 +1732,7 @@ def guessEncodingFromText(data, content_type='text/html'): else: message = 'No suitable encoding detector found.'\ ' You must install python-magic' - raise NotImplementedError, message + raise NotImplementedError(message) _reencodeUrlEscapes_map = {chr(x): chr(x) if chr(x) in # safe diff --git a/product/ERP5Type/WebDAVSupport.py b/product/ERP5Type/WebDAVSupport.py index 69d782a33fd840a6b5610c7d50582bad0569dad1..67d54416821e5b87c716642d43d2be43c18cac90 100644 --- a/product/ERP5Type/WebDAVSupport.py +++ b/product/ERP5Type/WebDAVSupport.py @@ -119,7 +119,7 @@ class TextContent: self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) if REQUEST.environ['REQUEST_METHOD'] != 'PUT': - raise Forbidden, 'REQUEST_METHOD should be PUT.' + raise Forbidden('REQUEST_METHOD should be PUT.') body = REQUEST.get('BODY', '') try: @@ -128,14 +128,14 @@ class TextContent: headers.setdefault('content_type', content_type) headers['file'] = body self._edit(**headers) - except 'EditingConflict', msg: + except 'EditingConflict' as msg: # XXX Can we get an error msg through? Should we be raising an # exception, to be handled in the FTP mechanism? Inquiring # minds... transaction.abort() RESPONSE.setStatus(450) return RESPONSE - except ResourceLockedError, msg: + except ResourceLockedError as msg: transaction.abort() RESPONSE.setStatus(423) return RESPONSE @@ -212,7 +212,7 @@ def PUT(self, REQUEST, RESPONSE): self.dav__init(REQUEST, RESPONSE) if REQUEST.environ['REQUEST_METHOD'] != 'PUT': - raise Forbidden, 'REQUEST_METHOD should be PUT.' + raise Forbidden('REQUEST_METHOD should be PUT.') name = self.__name__ parent = self.__parent__ diff --git a/product/ERP5Type/dynamic/component_package.py b/product/ERP5Type/dynamic/component_package.py index bbc3bfbeec9e4c7e263abcc70d05f34385a56109..64ab5770dd208bcb26f947a3d625d8031a49b2dd 100644 --- a/product/ERP5Type/dynamic/component_package.py +++ b/product/ERP5Type/dynamic/component_package.py @@ -234,7 +234,7 @@ class ComponentDynamicPackage(ModuleType): try: version, name = name.split('.') version = version[:-self.__version_suffix_len] - except ValueError, error: + except ValueError as error: raise ImportError("%s: should be %s.VERSION.COMPONENT_REFERENCE (%s)" % \ (fullname, self._namespace, error)) @@ -300,7 +300,7 @@ class ComponentDynamicPackage(ModuleType): # in a deadlock source_code_obj = compile(source_code_str, module.__file__, 'exec') exec source_code_obj in module.__dict__ - except Exception, error: + except Exception as error: del sys.modules[module_fullname] if module_fullname_alias: del sys.modules[module_fullname_alias] diff --git a/product/ERP5Type/dynamic/lazy_class.py b/product/ERP5Type/dynamic/lazy_class.py index cddb6749b3e734d4ce0abc8c0f05b6064e09326c..d6b55880ad901c23709506b3695e0e9267e2c8d0 100644 --- a/product/ERP5Type/dynamic/lazy_class.py +++ b/product/ERP5Type/dynamic/lazy_class.py @@ -115,7 +115,7 @@ class GhostBaseMetaClass(ExtensionClass, AccessorHolderType): self.__class__.loadClass() except ConflictError: raise - except Exception, e: + except Exception as e: LOG('lazy_class.__getattribute__', WARNING, 'Failed to load class : %r' % (e,), error=sys.exc_info()) raise diff --git a/product/ERP5Type/mixin/component.py b/product/ERP5Type/mixin/component.py index 7f6183f4fad5426295da9a4f748d0bffe10aa4f4..21e1768dd70be2e6f3105241a344957e24700e72 100644 --- a/product/ERP5Type/mixin/component.py +++ b/product/ERP5Type/mixin/component.py @@ -317,7 +317,7 @@ class ComponentMixin(PropertyRecordableMixin, Base): self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) if REQUEST.environ['REQUEST_METHOD'] != 'PUT': - raise Forbidden, 'REQUEST_METHOD should be PUT.' + raise Forbidden('REQUEST_METHOD should be PUT.') text_content = REQUEST.get('BODY') if text_content is None: diff --git a/product/ERP5Type/mixin/matrix.py b/product/ERP5Type/mixin/matrix.py index 8101b17b760bbddfc7c331b5e04ce371851ee6b2..c9e7478e6cb0983220136fbba9de63d58001a8e4 100644 --- a/product/ERP5Type/mixin/matrix.py +++ b/product/ERP5Type/mixin/matrix.py @@ -200,9 +200,8 @@ class Matrix(object): """ script = self._getTypeBasedMethod('asCellRange', **kw) if script is None: - raise UnboundLocalError,\ - "Did not find cell range script for portal type: %r" %\ - self.getPortalType() + raise UnboundLocalError("Did not find cell range script for portal type: %r" %\ + self.getPortalType()) cell_range = script(base_id=base_id, matrixbox=0, **kw) self._setCellRange(base_id=base_id, *cell_range) @@ -336,7 +335,7 @@ class Matrix(object): cell_id = self.keyToId(kw, base_id = base_id) if cell_id is None: - raise KeyError, 'Invalid key: %s' % str(kw) + raise KeyError('Invalid key: %s' % str(kw)) cell = self.get(cell_id) if cell is not None: diff --git a/product/ERP5Type/patches/CMFBTreeFolder.py b/product/ERP5Type/patches/CMFBTreeFolder.py index 6162af7af66627bc42f8fdbd9c0767fa0a310708..481b33e000a93bb667c716c913a712d5530cbf8a 100644 --- a/product/ERP5Type/patches/CMFBTreeFolder.py +++ b/product/ERP5Type/patches/CMFBTreeFolder.py @@ -40,9 +40,9 @@ def CMFBTreeFolder_allowedContentTypes(self): for portal_type in myType.getTypeAllowedContentTypeList(): contentType = portal_types.getTypeInfo(portal_type) if contentType is None: - raise AttributeError, "Portal type '%s' does not exist " \ + raise AttributeError("Portal type '%s' does not exist " \ "and should not be allowed in '%s'" % \ - (portal_type, self.getPortalType()) + (portal_type, self.getPortalType())) result.append(contentType) else: for contentType in portal_types.listTypeInfo(self): diff --git a/product/ERP5Type/patches/CMFCoreSkinnable.py b/product/ERP5Type/patches/CMFCoreSkinnable.py index cdbba4af1ada0d9302ba031fe755b82b11175902..231b22df18d3bb5bd77d43623f551e0e4ad5d0cc 100644 --- a/product/ERP5Type/patches/CMFCoreSkinnable.py +++ b/product/ERP5Type/patches/CMFCoreSkinnable.py @@ -69,7 +69,7 @@ def skinResolve(self, selection, name): try: portal_skins = aq_base(self.portal_skins) except AttributeError: - raise AttributeError, name + raise AttributeError(name) try: portal_callables = aq_base(self.portal_callables) except AttributeError: @@ -163,7 +163,7 @@ def CMFCoreSkinnableSkinnableObjectManager_getSkin(self, name=None): calls. FIXME: Which exception should be raised here ? """ - raise Exception, 'This method must not be called when new caching system is applied.' + raise Exception('This method must not be called when new caching system is applied.') Skinnable.SkinnableObjectManager.__getattr__ = CMFCoreSkinnableSkinnableObjectManager___getattr__ Skinnable.SkinnableObjectManager.changeSkin = CMFCoreSkinnableSkinnableObjectManager_changeSkin diff --git a/product/ERP5Type/patches/CachingPolicyManager.py b/product/ERP5Type/patches/CachingPolicyManager.py index 30e847f27a23d52bfe8a4afc681d672edc806b71..a1885a872e3577c2657b3e1ee42df574bd4abad4 100644 --- a/product/ERP5Type/patches/CachingPolicyManager.py +++ b/product/ERP5Type/patches/CachingPolicyManager.py @@ -310,7 +310,7 @@ def _updatePolicy( self Update a policy in our registry. """ if policy_id not in self._policy_ids: - raise KeyError, "Policy %s does not exist!" % policy_id + raise KeyError("Policy %s does not exist!" % policy_id) self._policies[ policy_id ] = CachingPolicy( policy_id , predicate @@ -446,10 +446,10 @@ def _addPolicy( self policy_id = str( policy_id ).strip() if not policy_id: - raise ValueError, "Policy ID is required!" + raise ValueError("Policy ID is required!") if policy_id in self._policy_ids: - raise KeyError, "Policy %s already exists!" % policy_id + raise KeyError("Policy %s already exists!" % policy_id) self._policies[ policy_id ] = CachingPolicy( policy_id , predicate diff --git a/product/ERP5Type/patches/DA.py b/product/ERP5Type/patches/DA.py index 3b42902785045d12da0ca02f47ae78bc07f1ce3a..c9fcb0efe22a16549bdf65f8442fa885d5252929 100644 --- a/product/ERP5Type/patches/DA.py +++ b/product/ERP5Type/patches/DA.py @@ -187,12 +187,12 @@ def DA__call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw): #LOG("DA__call__ connection", 300, c) try: dbc=getattr(self, c) except AttributeError: - raise AttributeError, ( + raise AttributeError( "The database connection %s cannot be found." % ( c)) try: DB__=dbc() - except: raise DatabaseError, ( + except: raise DatabaseError( '%s is not connected to a database' % self.id) p = aq_parent(self) # None if no aq_parent @@ -205,7 +205,7 @@ def DA__call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw): security.addContext(self) try: query = self.template(p, **argdata) - except TypeError, msg: + except TypeError as msg: msg = str(msg) if 'client' in msg: raise NameError("'client' may not be used as an " diff --git a/product/ERP5Type/patches/DCWorkflow.py b/product/ERP5Type/patches/DCWorkflow.py index 94de021bccc46fc9a69be8c0988f9c813bb51504..09ec191615fc9c0b157c539e9182fc2b484ae466 100644 --- a/product/ERP5Type/patches/DCWorkflow.py +++ b/product/ERP5Type/patches/DCWorkflow.py @@ -415,11 +415,11 @@ def DCWorkflowDefinition_executeTransition(self, ob, tdef=None, kwargs=None): try: #LOG('_executeTransition', 0, "script = %s, sci = %s" % (repr(script), repr(sci))) script(sci) # May throw an exception. - except ValidationFailed, validation_exc: + except ValidationFailed as validation_exc: before_script_success = 0 before_script_error_message = deepcopy(validation_exc.msg) validation_exc_traceback = sys.exc_traceback - except ObjectMoved, moved_exc: + except ObjectMoved as moved_exc: ob = moved_exc.getNewObject() # Re-raise after transition @@ -533,7 +533,7 @@ def _executeMetaTransition(self, ob, new_state_id): new_sdef = self.states.get(new_state_id, None) if new_sdef is None: - raise WorkflowException, ('Destination state undefined: ' + new_state_id) + raise WorkflowException('Destination state undefined: ' + new_state_id) # Update variables. state_values = new_sdef.var_values @@ -587,12 +587,12 @@ def DCWorkflowDefinition_wrapWorkflowMethod(self, ob, method_id, func, args, kw) ''' sdef = self._getWorkflowStateOf(ob) if sdef is None: - raise WorkflowException, 'Object is in an undefined state' + raise WorkflowException('Object is in an undefined state') if method_id not in sdef.transitions: raise Unauthorized(method_id) tdef = self.transitions.get(method_id, None) if tdef is None or tdef.trigger_type != TRIGGER_WORKFLOW_METHOD: - raise WorkflowException, ( + raise WorkflowException( 'Transition %s is not triggered by a workflow method' % method_id) if not self._checkTransitionGuard(tdef, ob): @@ -603,7 +603,7 @@ def DCWorkflowDefinition_wrapWorkflowMethod(self, ob, method_id, func, args, kw) except ObjectDeleted: # Re-raise with a different result. raise ObjectDeleted(res) - except ObjectMoved, ex: + except ObjectMoved as ex: # Re-raise with a different result. raise ObjectMoved(ex.getNewObject(), res) return res diff --git a/product/ERP5Type/patches/DateTimePatch.py b/product/ERP5Type/patches/DateTimePatch.py index 5dea0db3d5490f9384837db24718a29f3ec8d1a7..e9eb1e5b4463dc3ed529d328501bb7460d7b7bed 100644 --- a/product/ERP5Type/patches/DateTimePatch.py +++ b/product/ERP5Type/patches/DateTimePatch.py @@ -130,18 +130,18 @@ def DateTime_parse(self, st, datefmt=getDefaultDateFormat()): if MonthNumbers.has_key(s): v=MonthNumbers[s] if month is None: month=v - else: raise SyntaxError, st + else: raise SyntaxError(st) continue # Check for time modifier: if s in TimeModifiers: if tm is None: tm=s - else: raise SyntaxError, st + else: raise SyntaxError(st) continue # Check for and skip day of week: if DayOfWeekNames.has_key(s): continue - raise SyntaxError, st + raise SyntaxError(st) day=None if ints[-1] > 60 and d not in ['.',':','/'] and len(ints) > 2: @@ -210,29 +210,29 @@ def DateTime_parse(self, st, datefmt=getDefaultDateFormat()): leap = year%4==0 and (year%100!=0 or year%400==0) try: if not day or day > self._month_len[leap][month]: - raise DateError, st + raise DateError(st) except IndexError: - raise DateError, st + raise DateError(st) tod=0 if ints: i=ints[0] # Modify hour to reflect am/pm if tm and (tm=='pm') and i<12: i=i+12 if tm and (tm=='am') and i==12: i=0 - if i > 24: raise TimeError, st + if i > 24: raise TimeError(st) tod = tod + int(i) * 3600 del ints[0] if ints: i=ints[0] - if i > 60: raise TimeError, st + if i > 60: raise TimeError(st) tod = tod + int(i) * 60 del ints[0] if ints: i=ints[0] - if i > 60: raise TimeError, st + if i > 60: raise TimeError(st) tod = tod + i del ints[0] - if ints: raise SyntaxError,st + if ints: raise SyntaxError(st) tod_int = int(math.floor(tod)) diff --git a/product/ERP5Type/patches/DemoStorage.py b/product/ERP5Type/patches/DemoStorage.py index 87ce80303f07974ff1dcdb699aa2c3c227b11f38..6d76f73adf43bc7dd01be7785521e3fb8f73b788 100644 --- a/product/ERP5Type/patches/DemoStorage.py +++ b/product/ERP5Type/patches/DemoStorage.py @@ -25,7 +25,7 @@ class DemoStorage(_DemoStorage.DemoStorage, ConflictResolvingStorage): try: return super(DemoStorage, self).store( oid, serial, data, version, transaction) - except ConflictError, e: + except ConflictError as e: old = e.serials[0] rdata = self.tryToResolveConflict(oid, old, serial, data) self.changes.store(oid, old, rdata, '', transaction) diff --git a/product/ERP5Type/patches/ExceptionFormatter.py b/product/ERP5Type/patches/ExceptionFormatter.py index 9931e103f80a5fe8bccd14682f493ee73a2dc05d..bc97df5fe6eb71fb104d53cea80c95c7371cfe28 100644 --- a/product/ERP5Type/patches/ExceptionFormatter.py +++ b/product/ERP5Type/patches/ExceptionFormatter.py @@ -90,7 +90,7 @@ def formatLine(self, tb, *args, **kwargs): line_str, flags=re.DOTALL) - except Exception, e: + except Exception as e: pass return line_str diff --git a/product/ERP5Type/patches/OFSImage.py b/product/ERP5Type/patches/OFSImage.py index aacfde27ceac2c087664ee2d94c9ba301ce92db5..416ba85bcc93ff9303f840dd914264f0bbbd022b 100644 --- a/product/ERP5Type/patches/OFSImage.py +++ b/product/ERP5Type/patches/OFSImage.py @@ -90,7 +90,7 @@ PUT_orig = OFS.Image.File.PUT def PUT(self, REQUEST, RESPONSE): """Handle HTTP PUT requests""" if REQUEST.environ['REQUEST_METHOD'] != 'PUT': - raise Forbidden, 'REQUEST_METHOD should be PUT.' + raise Forbidden('REQUEST_METHOD should be PUT.') return PUT_orig(self, REQUEST, RESPONSE) OFS.Image.File.PUT = PUT diff --git a/product/ERP5Type/patches/PropertyManager.py b/product/ERP5Type/patches/PropertyManager.py index 7ebc277480ca64db2d31b05d5030894d46d34198..3ea296d9428b07ce2aa68865df2e96ec39506bc2 100644 --- a/product/ERP5Type/patches/PropertyManager.py +++ b/product/ERP5Type/patches/PropertyManager.py @@ -41,7 +41,7 @@ def PropertyManager_updateProperty(self, id, value, local_properties=False): self._wrapperCheck(value) if not hasattr(self, 'isRADContent'): if not self.hasProperty(id): - raise BadRequest, 'The property %s does not exist' % escape(id) + raise BadRequest('The property %s does not exist' % escape(id)) if isinstance(value, str): proptype=self.getPropertyType(id, local_properties=local_properties) \ or 'string' @@ -110,11 +110,11 @@ def PropertyManager_setProperty(self, id, value, type=None): self._wrapperCheck(value) if not self.valid_property_id(id): - raise BadRequest, 'Invalid or duplicate property id: %s' % id + raise BadRequest('Invalid or duplicate property id: %s' % id) if type in ('selection', 'multiple selection'): if not hasattr(self, value): - raise BadRequest, 'No select variable %s' % value + raise BadRequest('No select variable %s' % value) self._local_properties=getattr(self, '_local_properties', ()) + ( {'id':id, 'type':type, 'select_variable':value},) if type=='selection': @@ -140,7 +140,7 @@ def PropertyManager_valid_property_id(self, id): def PropertyManager_delProperty(self, id): if not self.hasProperty(id): - raise ValueError, 'The property %s does not exist' % escape(id) + raise ValueError('The property %s does not exist' % escape(id)) self._delPropValue(id) self._local_properties=tuple(filter(lambda i, n=id: i['id'] != n, getattr(self, '_local_properties', ()))) diff --git a/product/ERP5Type/patches/WebDAV.py b/product/ERP5Type/patches/WebDAV.py index 67929105b8d56f9f76fd12c21332f7622999e30d..5d757860ab50e3ea73f79453996f8292cc06d0ec 100644 --- a/product/ERP5Type/patches/WebDAV.py +++ b/product/ERP5Type/patches/WebDAV.py @@ -27,15 +27,15 @@ def MKCOL(self, REQUEST, RESPONSE): """Create a new collection resource.""" self.dav__init(REQUEST, RESPONSE) if REQUEST.get('BODY', ''): - raise UnsupportedMediaType, 'Unknown request body.' + raise UnsupportedMediaType('Unknown request body.') name=self.__name__ parent = self.__parent__ if hasattr(aq_base(parent), name): - raise MethodNotAllowed, 'The name %s is in use.' % name + raise MethodNotAllowed('The name %s is in use.' % name) if not isDavCollection(parent): - raise Forbidden, 'Cannot create collection at this location.' + raise Forbidden('Cannot create collection at this location.') ifhdr = REQUEST.get_header('If', '') if IWriteLock.providedBy(parent) and parent.wl_isLocked(): diff --git a/product/ERP5Type/patches/WorkflowTool.py b/product/ERP5Type/patches/WorkflowTool.py index 9497854e894e9e357ee686fa43430f0bf59a8920..9dd1eef1b1a4937e9aab4e1e4d27a886c1d8f43a 100644 --- a/product/ERP5Type/patches/WorkflowTool.py +++ b/product/ERP5Type/patches/WorkflowTool.py @@ -57,12 +57,12 @@ def DCWorkflowDefinition_notifyWorkflowMethod(self, ob, transition_list, args=No raise ValueError('WorkflowMethod should be attached to exactly 1 transition per DCWorkflow instance.') sdef = self._getWorkflowStateOf(ob) if sdef is None: - raise WorkflowException, 'Object is in an undefined state' + raise WorkflowException('Object is in an undefined state') if method_id not in sdef.transitions: raise Unauthorized(method_id) tdef = self.transitions.get(method_id, None) if tdef is None or tdef.trigger_type != TRIGGER_WORKFLOW_METHOD: - raise WorkflowException, ( + raise WorkflowException( 'Transition %s is not triggered by a workflow method' % method_id) if not self._checkTransitionGuard(tdef, ob): @@ -567,13 +567,13 @@ def WorkflowTool_listActions(self, info=None, object=None, src__=False): % grouped_worklist_dict.keys(), error=sys.exc_info()) continue - except ProgrammingError, error_value: + except ProgrammingError as error_value: # 1146 = table does not exist if not use_cache or error_value[0] != 1146: raise try: self.Base_zCreateWorklistTable() - except ProgrammingError, error_value: + except ProgrammingError as error_value: # 1050 = table exists (alarm run just a bit too late) if error_value[0] != 1050: raise @@ -649,7 +649,7 @@ def WorkflowTool_refreshWorklistCache(self): else: try: self.Base_zClearWorklistTable() - except ProgrammingError, error_value: + except ProgrammingError as error_value: # 1146 = table does not exist if error_value[0] != 1146: raise @@ -709,7 +709,7 @@ def WorkflowTool_refreshWorklistCache(self): if len(value_column_dict[COUNT_COLUMN_TITLE]): try: Base_zInsertIntoWorklistTable(**value_column_dict) - except (ProgrammingError, OperationalError), error_value: + except (ProgrammingError, OperationalError) as error_value: # OperationalError 1054 = unknown column if isinstance(error_value, OperationalError) and error_value[0] != 1054: raise @@ -756,7 +756,7 @@ class WorkflowHistoryList(Persistent): return self.__class__((self[x] for x in xrange(*index.indices(len(self))))) else: - raise TypeError, 'tuple indices must be integers' + raise TypeError('tuple indices must be integers') def __getslice__(self, start, end): return self.__getitem__(slice(start, end)) @@ -898,7 +898,7 @@ class WorkflowMethod( Method ): # No workflow tool found. try: res = self._m(instance, *args, **kw) - except ObjectDeleted, ex: + except ObjectDeleted as ex: res = ex.getResult() else: if hasattr(aq_base(instance), 'reindexObject'): diff --git a/product/ERP5Type/patches/memcache_client.py b/product/ERP5Type/patches/memcache_client.py index d4cf6327abfdde8948cc06b4451cbd8f24f58ac6..9a808a259e71800723ba0960fbc332adfbb5a522 100644 --- a/product/ERP5Type/patches/memcache_client.py +++ b/product/ERP5Type/patches/memcache_client.py @@ -60,7 +60,7 @@ else: except TypeError: # BBB server.expect("END") - except (_Error, socket.error), msg: + except (_Error, socket.error) as msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) # (patch) @@ -79,7 +79,7 @@ else: # (patch) # return None raise _ConnectionDeadError - except (_ConnectionDeadError, socket.error), msg: + except (_ConnectionDeadError, socket.error) as msg: server.mark_dead(msg) # (patch) # return None diff --git a/product/ERP5Type/patches/pylint.py b/product/ERP5Type/patches/pylint.py index 459d8801a881c35f7053ebb0f945c4a47024a5d7..9f67560ec0fa126ae54fe347089232429444d9af 100644 --- a/product/ERP5Type/patches/pylint.py +++ b/product/ERP5Type/patches/pylint.py @@ -39,7 +39,7 @@ else: def _get_imported_module(self, importnode, modname): try: return importnode.do_import_module(modname) - except astroid.InferenceError, ex: + except astroid.InferenceError as ex: # BEGIN # XXX-arnau: Ignore ERP5 dynamic modules, hackish but required diff --git a/product/ERP5Type/patches/sqltest.py b/product/ERP5Type/patches/sqltest.py index 43e468fd5fe1686c6b838477301c958814c538b3..03dcc9e0752ca548e55bcdb62f23625b3fbef584 100644 --- a/product/ERP5Type/patches/sqltest.py +++ b/product/ERP5Type/patches/sqltest.py @@ -31,13 +31,13 @@ if 1: # For easy diff with original except (KeyError, NameError): if args.has_key('optional') and args['optional']: return '' - raise ValueError, 'Missing input variable, %s' % name + raise ValueError('Missing input variable, %s' % name) # PATCH: use isinstance instead of type comparison, to allow # subclassing. if isinstance(v, list_type_list): if len(v) > 1 and not self.multiple: - raise ValueError, ( + raise ValueError( 'multiple values are not allowed for %s' % name) else: v=[v] @@ -53,7 +53,7 @@ if 1: # For easy diff with original atoi(v) else: v=str(int(v)) except ValueError: - raise ValueError, ( + raise ValueError( 'Invalid integer value for %s' % name) elif t=='float': if not v and type(v) is StringType: continue @@ -61,7 +61,7 @@ if 1: # For easy diff with original if type(v) is StringType: atof(v) else: v=str(float(v)) except ValueError: - raise ValueError, ( + raise ValueError( 'Invalid floating-point value for %s' % name) elif t.startswith('datetime'): # For subsecond precision, use 'datetime(N)' MySQL type, @@ -84,12 +84,12 @@ if 1: # For easy diff with original return '' else: err = 'Invalid empty string value for %s' % name - raise ValueError, err + raise ValueError(err) if not vs: if self.optional: return '' - raise ValueError, ( + raise ValueError( 'No input was provided for %s' % name) if len(vs) > 1: diff --git a/product/ERP5Type/patches/unicodeconflictresolver.py b/product/ERP5Type/patches/unicodeconflictresolver.py index 1d12c5ef76d7008b49991eb5091aceaffc7e435f..1c2c7dd4154baa222ddab2e7651fb500a04915d8 100644 --- a/product/ERP5Type/patches/unicodeconflictresolver.py +++ b/product/ERP5Type/patches/unicodeconflictresolver.py @@ -32,7 +32,7 @@ def PreferredCharsetResolver_resolve(context, text, expression): # requests that do not contain Accept-Charset header. try: result = unicode(text, 'utf-8') - except UnicodeDecodeError, e: + except UnicodeDecodeError as e: tb_info = ''.join(traceback.format_stack()) logger.warn('UnicodeDecodeError(%s: %s): %s\ntext: %r\nat:\n%s' % (e.start, e.end, e.reason, repr(text), tb_info)) diff --git a/product/ERP5Type/tests/ERP5TypeFunctionalTestCase.py b/product/ERP5Type/tests/ERP5TypeFunctionalTestCase.py index a6af4e8095944510da51ebe46870167364054fb1..f2a7fdbd3625f21f47f9a3af503975918750b204 100644 --- a/product/ERP5Type/tests/ERP5TypeFunctionalTestCase.py +++ b/product/ERP5Type/tests/ERP5TypeFunctionalTestCase.py @@ -351,7 +351,7 @@ class ERP5TypeFunctionalTestCase(ERP5TypeTestCase): error = None try: iframe = self.runner.test(debug=debug) - except TimeoutError, e: + except TimeoutError as e: error = repr(e) self._verboseErrorLog(20) else: @@ -385,6 +385,6 @@ class ERP5TypeFunctionalTestCase(ERP5TypeTestCase): # authentication dialog in case of Unauthorized exception to prevent # blocking in functional tests. def _unauthorized(self): - raise RuntimeError, 'Unauthorized exception happens.' + raise RuntimeError('Unauthorized exception happens.') HTTPResponse._unauthorized = _unauthorized diff --git a/product/ERP5Type/tests/ERP5TypeTestCase.py b/product/ERP5Type/tests/ERP5TypeTestCase.py index 52807b52567df34e668068112c134c8574057456..1258f41122e9cc145fd12c641a844ed6f970a7f7 100644 --- a/product/ERP5Type/tests/ERP5TypeTestCase.py +++ b/product/ERP5Type/tests/ERP5TypeTestCase.py @@ -750,7 +750,7 @@ class ERP5TypeTestCaseMixin(ProcessingNodeTestCase, PortalTestCase): elif len(p) == 2: [env['PATH_INFO'], env['QUERY_STRING']] = p else: - raise TypeError, '' + raise TypeError('') if basic: assert not user, (basic, user) @@ -1412,7 +1412,7 @@ class ZEOServerTestCase(ERP5TypeTestCase): try: self.zeo_server = StorageServer(host_port, storage) break - except socket.error, e: + except socket.error as e: if e[0] != errno.EADDRINUSE: raise if zeo_client: diff --git a/product/ERP5Type/tests/ERP5TypeTestSuite.py b/product/ERP5Type/tests/ERP5TypeTestSuite.py index e5303c0946be91e5d51f4cbaf63fb6ea055c556e..84f1f5ee6da3ce5e3360a6219819ae3ad23170ae 100644 --- a/product/ERP5Type/tests/ERP5TypeTestSuite.py +++ b/product/ERP5Type/tests/ERP5TypeTestSuite.py @@ -48,7 +48,7 @@ class ERP5TypeTestSuite(TestSuite): + ('--verbose', '--erp5_sql_connection_string=' + mysql_db_list[0]) \ + args status_dict = self.spawn(*args, **kw) - except SubprocessError, e: + except SubprocessError as e: status_dict = e.status_dict test_log = status_dict['stderr'] search = self.RUN_RE.search(test_log) diff --git a/product/ERP5Type/tests/ProcessingNodeTestCase.py b/product/ERP5Type/tests/ProcessingNodeTestCase.py index 890a338898d230e944f007cf6a148005276f1c78..c041d0fd387635d4201df685ad0912a528347cd5 100644 --- a/product/ERP5Type/tests/ProcessingNodeTestCase.py +++ b/product/ERP5Type/tests/ProcessingNodeTestCase.py @@ -146,14 +146,14 @@ class ProcessingNodeTestCase(ZopeTestCase.TestCase): hs.server_protocol, hs.server_name, hs.server_port)) try: hs = createZServer(log) - except RuntimeError, e: + except RuntimeError as e: ZopeTestCase._print(str(e)) else: utils._Z2HOST, utils._Z2PORT = hs.server_name, hs.server_port _print(hs) try: _print(createZServer(log, zserver_type='webdav')) - except RuntimeError, e: + except RuntimeError as e: ZopeTestCase._print('Could not start webdav zserver: %s\n' % e) t = Thread(target=Lifetime.loop) t.setDaemon(1) @@ -251,7 +251,7 @@ class ProcessingNodeTestCase(ZopeTestCase.TestCase): error_message = 'tic is looping forever. ' try: self.assertNoPendingMessage() - except AssertionError, e: + except AssertionError as e: error_message += str(e) raise RuntimeError(error_message) # This give some time between messages diff --git a/product/ERP5Type/tests/runFunctionalTest.py b/product/ERP5Type/tests/runFunctionalTest.py index f090f599877555a562b4aeb058b20dc2e4b92656..f043afd1c0af15140ed94bcd3e835ba172779044 100644 --- a/product/ERP5Type/tests/runFunctionalTest.py +++ b/product/ERP5Type/tests/runFunctionalTest.py @@ -93,7 +93,7 @@ class FunctionalTestRunner: "portal_name=", "run_only=", "user=", "password=", "alarms=", "email_subject=", "smtp_host=", "xvfb_display="] ) - except getopt.GetoptError, msg: + except getopt.GetoptError as msg: self.usage(sys.stderr, msg) sys.exit(2) @@ -273,7 +273,7 @@ user_pref("capability.principal.codebase.p1.subjectName", "");""" % \ try: status = self.openUrl('%s/portal_tests/TestTool_getResults' % (self.portal_url)) - except urllib2.HTTPError, e: + except urllib2.HTTPError as e: if e.msg == "No Content" : status = "" else: diff --git a/product/ERP5Type/tests/runUnitTest.py b/product/ERP5Type/tests/runUnitTest.py index 3967f64fc3bbd5047ce719caa31cdee6803d3d5c..67e6a6e74cf1d80298cafdddbdd3337a01b8e6c8 100755 --- a/product/ERP5Type/tests/runUnitTest.py +++ b/product/ERP5Type/tests/runUnitTest.py @@ -740,7 +740,7 @@ def main(argument_list=None): "sys_path=", "instance_home=", ]) - except getopt.GetoptError, msg: + except getopt.GetoptError as msg: usage(sys.stderr, msg) sys.exit(2) diff --git a/product/ERP5Type/tests/utils.py b/product/ERP5Type/tests/utils.py index a41626d79dc2c3e97d1da9dc6b9f7985cc8de090..57f7f536c23bf43a96e21dfbe7385c893ec8c774 100644 --- a/product/ERP5Type/tests/utils.py +++ b/product/ERP5Type/tests/utils.py @@ -157,7 +157,7 @@ class DummyLocalizer: def __getitem__(self, key): if hasattr(self, key): return getattr(self, key) - raise KeyError, key + raise KeyError(key) def get_default_language(self): return self._default_language @@ -343,7 +343,7 @@ def createZServer(log=os.devnull, zserver_type='http'): hs.__init__(ip, port, resolver=None, logger_object=lg) hs.install_handler(zhandler_class(module='Zope2', uri_base='')) return hs - except socket.error, e: + except socket.error as e: if e[0] != errno.EADDRINUSE: raise hs.close() @@ -426,7 +426,7 @@ class LogInterceptor: def _catch_log_errors(self, ignored_level=zLOG.WARNING, subsystem=''): if subsystem in self.installed: - raise ValueError, 'Already installed filter!' + raise ValueError('Already installed filter!') root_logger = logging.getLogger(subsystem) self.installed += (subsystem,) @@ -583,7 +583,7 @@ def updateCellList(portal, line, cell_type, cell_range_method, cell_dict_list): elif isinstance(table[0][0], (tuple, list)): dimension = 3 else: - raise RuntimeError, "Unsupported table structure!" + raise RuntimeError("Unsupported table structure!") if dimension==1: for table_line in table: diff --git a/product/ERP5VCS/Git.py b/product/ERP5VCS/Git.py index 84605fd330e6303aff00dd90f7c05b9f46469cba..c7ca12c9cb1a2351ba0c89706dbabb5678d1d5ce 100644 --- a/product/ERP5VCS/Git.py +++ b/product/ERP5VCS/Git.py @@ -67,7 +67,7 @@ class Git(WorkingCopy): argv = ['git'] try: return subprocess.Popen(argv + list(args), **kw) - except OSError, e: + except OSError as e: import sys from zLOG import LOG, WARNING LOG('Git', WARNING, @@ -118,7 +118,7 @@ class Git(WorkingCopy): env.update(ERP5_GIT_USERNAME=userpwd[0], ERP5_GIT_PASSWORD=userpwd[1]) try: return self.git(*args, **kw) - except GitError, e: + except GitError as e: message = 'Authentication failed' if message in str(e): raise GitLoginError(userpwd and message or @@ -149,7 +149,7 @@ class Git(WorkingCopy): local, remote = self.git('rev-parse', '--symbolic-full-name', 'HEAD', '@{u}').splitlines() remote = remote[:13] == 'refs/remotes/' and remote[13:] or None - except GitError, e: + except GitError as e: local = e.stdout.splitlines()[0] remote = None if local != 'HEAD': @@ -294,7 +294,7 @@ class Git(WorkingCopy): try: return self.git('show', 'HEAD:' + self.prefix + path, strip=False, cwd=self.toplevel) - except GitError, e: + except GitError as e: err = e.args[0] if ' does not exist in ' in err or ' exists on disk, but not in ' in err: raise NotVersionedError(path) @@ -353,7 +353,7 @@ class Git(WorkingCopy): push_args = 'push', '--porcelain', remote, '%s:%s' % (src, dst) try: self.remote_git(*push_args) - except GitError, e: + except GitError as e: # first check why we could not push status = [x for x in e.stdout.splitlines() if x[:1] == '!'] if (len(status) != 1 or @@ -368,7 +368,7 @@ class Git(WorkingCopy): # TODO: solve conflicts on */bt/revision automatically try: self.git(merge, '@{u}', env=env) - except GitError, e: + except GitError as e: # XXX: how to know how it failed ? try: self.git(merge, '--abort') @@ -380,7 +380,7 @@ class Git(WorkingCopy): reset += 1 # retry to push everything self.remote_git(*push_args) - except (GitError, GitLoginError), e: + except (GitError, GitLoginError) as e: self.git('reset', '--soft', '@{%u}' % reset) if isinstance(e, GitLoginError): raise diff --git a/product/ERP5VCS/Subversion.py b/product/ERP5VCS/Subversion.py index 8bce310643e721e4a4882e89d1ea0a2f8b8fe32e..fb15cbf00d7e83b029e998573e7d00eaab124cf0 100644 --- a/product/ERP5VCS/Subversion.py +++ b/product/ERP5VCS/Subversion.py @@ -148,7 +148,7 @@ class Subversion(WorkingCopy): try: return self._getClient().cat(os.path.join(self.working_copy, path), Revision(opt_revision_kind.base)) - except ClientError, e: + except ClientError as e: if e.args[1][-1][1] in (errno.ENOENT, svn_err.entry_not_found): raise NotVersionedError(path) raise diff --git a/product/ERP5VCS/SubversionClient.py b/product/ERP5VCS/SubversionClient.py index a170b7a72f87e32aa290aaac8480ea9d5fd5ff4f..762d3a1312681b8ef116c6c262c5a404bde34bd5 100644 --- a/product/ERP5VCS/SubversionClient.py +++ b/product/ERP5VCS/SubversionClient.py @@ -124,7 +124,7 @@ try: def __call__(self): current_time = time.time() if current_time - self.client.creation_time > self.client.getTimeout(): - raise SubversionTimeoutError, 'too long transaction' + raise SubversionTimeoutError('too long transaction') #return True return False @@ -273,7 +273,7 @@ try: return Revision(self.client.checkin(path, log_message=log_message or 'none', recurse=recurse)) - except pysvn.ClientError, error: + except pysvn.ClientError as error: excep = self.getException() if excep: raise excep @@ -283,7 +283,7 @@ try: def update(self, path): try: return [Revision(x) for x in self.client.update(path)] - except pysvn.ClientError, error: + except pysvn.ClientError as error: excep = self.getException() if excep: raise excep @@ -295,7 +295,7 @@ try: # Zope, convert the objects. try: status_list = [Status(x) for x in self.client.status(path=path, **kw)] - except pysvn.ClientError, error: + except pysvn.ClientError as error: excep = self.getException() if excep: raise excep @@ -330,7 +330,7 @@ try: def log(self, path): try: log_list = self.client.log(path) - except pysvn.ClientError, error: + except pysvn.ClientError as error: if 'path not found' in error.args[0]: return excep = self.getException() @@ -357,20 +357,20 @@ try: def info(self, 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 if os.path.islink(path): path = os.path.realpath(path) try: entry = self.client.info(path=path) - except pysvn.ClientError, error: + except pysvn.ClientError as error: excep = self.getException() if excep: raise excep else: raise error 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 members_tuple = ('url', 'uuid', 'revision', 'kind', \ 'commit_author', 'commit_revision', 'commit_time',) @@ -383,7 +383,7 @@ try: def ls(self, path): try: dict_list = self.client.ls(url_or_path=path, recurse=False) - except pysvn.ClientError, error: + except pysvn.ClientError as error: if 'non-existent' in error.args[0]: return excep = self.getException() @@ -415,4 +415,4 @@ except ImportError: 'could not import pysvn; until pysvn is installed properly,' ' this tool will not work.', error=sys.exc_info()) def newSubversionClient(container, **kw): - raise SubversionInstallationError, 'pysvn library is not installed' + raise SubversionInstallationError('pysvn library is not installed') diff --git a/product/ERP5VCS/WorkingCopy.py b/product/ERP5VCS/WorkingCopy.py index f7dc72bc5c356e74b58c39bd99a245b39c7828d2..7252d284397a8511536ca39bb675a11c9388a916 100644 --- a/product/ERP5VCS/WorkingCopy.py +++ b/product/ERP5VCS/WorkingCopy.py @@ -269,7 +269,7 @@ class WorkingCopy(Implicit): try: with open(os.path.join(self.working_copy, path), 'rU') as f: text = f.read() - except IOError, e: + except IOError as e: if e.errno == errno.EISDIR: return '%s
%r is a folder!' % (head, path) if e.errno != errno.ENOENT: @@ -361,7 +361,7 @@ class BusinessTemplateWorkingCopy(BusinessTemplateFolder): try: try: file = open(path, 'r+b') - except IOError, e: + except IOError as e: if e.errno == errno.EISDIR: shutil.rmtree(path, ignore_errors=True) elif e.errno != errno.ENOENT: diff --git a/product/ERP5Wizard/Tool/WizardTool.py b/product/ERP5Wizard/Tool/WizardTool.py index 476a9cf9243e11c9c428c5789ed0669f3f111bb7..45ff6b07a03202ee85ee1a960c67482aad01b736 100644 --- a/product/ERP5Wizard/Tool/WizardTool.py +++ b/product/ERP5Wizard/Tool/WizardTool.py @@ -455,7 +455,7 @@ class WizardTool(BaseTool): try: method = getattr(witch_tool, distant_method) html = method(parameter_dict) - except socket.error, message: + except socket.error as message: html = _generateErrorXML("""Cannot contact the server: %s. Please check your network settings.""" % server_url) @@ -464,7 +464,7 @@ class WizardTool(BaseTool): "data": html, "next": None, "previous": None}) - except xmlrpclib.ProtocolError, message: + except xmlrpclib.ProtocolError as message: html = _generateErrorXML("""The server %s refused to reply. Please contact erp5-dev@erp5.org""" % server_url) @@ -473,7 +473,7 @@ class WizardTool(BaseTool): "data": html, "next": None, "previous": None}) - except xmlrpclib.Fault, message: + except xmlrpclib.Fault as message: html = _generateErrorXML("Error/bug inside the server: %s." %server_url) zLOG.LOG('Wizard Tool xmlrpc fault', zLOG.ERROR, message) result_call.update({"command": "show", diff --git a/product/ERP5eGovSecurity/EGOVGroupManager.py b/product/ERP5eGovSecurity/EGOVGroupManager.py index 8519f7be763cc5c946ee3f87237c63452ac7f6e7..9885287c3169e39fd3a150cbf62f27205ba23a30 100644 --- a/product/ERP5eGovSecurity/EGOVGroupManager.py +++ b/product/ERP5eGovSecurity/EGOVGroupManager.py @@ -130,9 +130,9 @@ class EGOVGroupManager(ERP5GroupManager): if len(catalog_result) != 1: # we won't proceed with groups if len(catalog_result) > 1: # configuration is screwed - raise ConsistencyError, 'There is more than one Person whose \ + raise ConsistencyError('There is more than one Person whose \ login is %s : %s' % (user_name, - repr([r.getObject() for r in catalog_result])) + repr([r.getObject() for r in catalog_result]))) else: # no person is linked to this user login portal = self.getPortalObject() diff --git a/product/Formulator/Field.py b/product/Formulator/Field.py index b3140fb675bbda60d0d9aacf10c376691b8b0191..6caa1d69fdbd72667f9f857a055792b9abb10c40 100644 --- a/product/Formulator/Field.py +++ b/product/Formulator/Field.py @@ -505,7 +505,7 @@ class ZMIField( try: # validate the form and get results result = self.form.validate(REQUEST) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) @@ -587,7 +587,7 @@ class ZMIField( try: # validate the form and get results result = self.override_form.validate(REQUEST) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) @@ -620,7 +620,7 @@ class ZMIField( try: # validate the form and get results result = self.tales_form.validate(REQUEST) - except ValidationError, err: + except ValidationError as err: if REQUEST: message = "Error: %s - %s" % (err.field.get_value('title'), err.error_text) diff --git a/product/Formulator/Form.py b/product/Formulator/Form.py index 36bee8d1cd25876a9ab07c66f042092d6ef2ba74..a568ace4a3b3980a3c606bc1734db0007edc1212 100644 --- a/product/Formulator/Form.py +++ b/product/Formulator/Form.py @@ -381,7 +381,7 @@ class Form: alternate_name = field.get_value('alternate_name') if alternate_name: result[alternate_name] = value - except ValidationError, err: + except ValidationError as err: errors.append(err) if len(errors) > 0: raise FormValidationError(errors, result) @@ -394,7 +394,7 @@ class Form: """ try: result = self.validate_all(REQUEST, key_prefix=key_prefix) - except FormValidationError, e: + except FormValidationError as e: # put whatever result we have in REQUEST for key, value in e.result.items(): REQUEST.set(key, value) @@ -681,19 +681,19 @@ class ZMIForm(ObjectManager, PropertyManager, RoleManager, Item, Form): FIXME: hack that could be removed once Zope 2.4.x goes back to a useful semantics...""" try: self._checkId(new_id) - except: raise CopyError, MessageDialog( + except: raise CopyError(MessageDialog( title='Invalid Id', message=sys.exc_info()[1], - action ='manage_main') + action ='manage_main')) ob=self._getOb(id) if not ob.cb_isMoveable(): - raise CopyError, eNotSupported % id + raise CopyError(eNotSupported % id) self._verifyObjectPaste(ob) try: ob._notifyOfCopyTo(self, op=1) - except: raise CopyError, MessageDialog( + except: raise CopyError(MessageDialog( title='Rename Error', message=sys.exc_info()[1], - action ='manage_main') + action ='manage_main')) self._delObject(id) ob = aq_base(ob) ob._setId(new_id) @@ -728,7 +728,7 @@ class ZMIForm(ObjectManager, PropertyManager, RoleManager, Item, Form): """ field = self._getOb(id, None) if field is None or not hasattr(aq_base(field), 'is_field'): - raise AttributeError, "No field %s" % id + raise AttributeError("No field %s" % id) if include_disabled or field.get_value('enabled'): return field raise FieldDisabledError("Field %s disabled" % id, field) @@ -783,7 +783,7 @@ class ZMIForm(ObjectManager, PropertyManager, RoleManager, Item, Form): """ try: result = self.settings_form.validate_all(REQUEST) - except FormValidationError, e: + except FormValidationError as e: message = "Validation error(s).
" + string.join( map(lambda error: "%s: %s" % (error.field.get_value('title'), error.error_text), e.errors), "
") diff --git a/product/Formulator/ProductForm.py b/product/Formulator/ProductForm.py index 35dc513e0662ad6cb8a23ba91ffb0dcda118d82c..0a149281289c4acca6de540cdcabd4610d755d78 100644 --- a/product/Formulator/ProductForm.py +++ b/product/Formulator/ProductForm.py @@ -114,7 +114,7 @@ class ProductForm(BasicForm): try: result=self.validate_all(REQUEST) - except FormValidationError, e: + except FormValidationError as e: for error in e.errors: errors[error.field.get_value('title')]=error.error_text diff --git a/product/Formulator/Validator.py b/product/Formulator/Validator.py index e87ceb899fd065607d9f0365594396eca1723543..15a6eea5320dd23dfca8ec452b0f20ef0e068b67 100644 --- a/product/Formulator/Validator.py +++ b/product/Formulator/Validator.py @@ -97,9 +97,9 @@ class StringBaseValidator(Validator): value = REQUEST.get(key, REQUEST.get('default_%s' % (key, ))) if value is None: 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 %s has not been transmitted. Check that all required fields are in visible groups.' % (repr(field.id), )) else: - raise KeyError, 'Field %s is not present in request object.' % (repr(field.id), ) + raise KeyError('Field %s is not present in request object.' % (repr(field.id), )) if isinstance(value, str): if field.has_value('whitespace_preserve'): if not field.get_value('whitespace_preserve'): @@ -537,7 +537,7 @@ class MultiSelectionValidator(Validator): def validate(self, field, key, REQUEST): 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 %s is not present in request object (marker field default_%s not found).' % (repr(field.id), key)) values = REQUEST.get(key, []) # NOTE: a hack to deal with single item selections if not isinstance(values, list): diff --git a/product/Formulator/tests/testFormValidator.py b/product/Formulator/tests/testFormValidator.py index 3e50fead47f42e2dcd926c311305fea351da49bb..259709511813728d9b7cea8e772abafde7c03cb8 100644 --- a/product/Formulator/tests/testFormValidator.py +++ b/product/Formulator/tests/testFormValidator.py @@ -28,7 +28,7 @@ class ValidatorTestCase(unittest.TestCase): def assertValidatorRaises(self, exception, error_key, f, *args, **kw): try: apply(f, args, kw) - except exception, e: + except exception as e: if hasattr(e, 'error_key') and e.error_key != error_key: self.fail('Got wrong error. Expected %s received %s' % (error_key, e)) diff --git a/product/Formulator/tests/testSerializeForm.py b/product/Formulator/tests/testSerializeForm.py index 1df549d5ddc1dd5d0d561914bf892f8af78278f4..c76b0eef04fa11b841157e4e1f61361f692d0489 100644 --- a/product/Formulator/tests/testSerializeForm.py +++ b/product/Formulator/tests/testSerializeForm.py @@ -210,14 +210,14 @@ class SerializeTestCase(unittest.TestCase): try: form.validate_all(request) self.fail('form should fail in validation') - except FormValidationError, e: + except FormValidationError as e: self.assertEqual(1, len(e.errors)) text1 = e.errors[0].error_text try: form2.validate_all(request) self.fail('form2 should fail in validation') - except FormValidationError, e: + except FormValidationError as e: self.assertEqual(1, len(e.errors)) text2 = e.errors[0].error_text @@ -343,7 +343,7 @@ class SerializeTestCase(unittest.TestCase): }) empty_field.manage_edit(REQUEST=request) - except ValidationError, e: + except ValidationError as e: self.fail('error when editing field %s; error message: %s' % (e.field_id, e.error_text) ) @@ -399,14 +399,14 @@ class SerializeTestCase(unittest.TestCase): request['field_empty_field'] = '' try: result1 = form.validate_all(request) - except FormValidationError, e: + except FormValidationError as e: # XXX only render first error ... self.fail('error when editing form1, field %s; error message: %s' % (e.errors[0].field_id, e.errors[0].error_text) ) try: result2 = form2.validate_all(request) - except FormValidationError, e: + except FormValidationError as e: # XXX only render first error ... self.fail('error when editing form1, field %s; error message: %s' % (e.errors[0].field_id, e.errors[0].error_text) ) diff --git a/product/HBTreeFolder2/HBTreeFolder2.py b/product/HBTreeFolder2/HBTreeFolder2.py index 0f03e4e5d895022eac3381445e368c275dcbbbdd..b85bff4bbde3caf65c89bfd0b46bf247fcbdb336 100644 --- a/product/HBTreeFolder2/HBTreeFolder2.py +++ b/product/HBTreeFolder2/HBTreeFolder2.py @@ -449,7 +449,7 @@ class HBTreeFolder2Base (Persistent): def _checkId(self, id, allow_dup=0): if not allow_dup and self.has_key(id): - raise BadRequestException, ('The id "%s" is invalid--' + raise BadRequestException('The id "%s" is invalid--' 'it is already in use.' % id) @@ -485,7 +485,7 @@ class HBTreeFolder2Base (Persistent): object = self._getOb(id) try: object.manage_beforeDelete(object, self) - except BeforeDeleteException, ob: + except BeforeDeleteException as ob: raise except ConflictError: raise diff --git a/product/Localizer/GettextTag.py b/product/Localizer/GettextTag.py index 89914bcc457ef259dfd973022153ad3092f4d2e1..1b70279f8ea132a2303d643a11cf9cf7fb2bd9b6 100644 --- a/product/Localizer/GettextTag.py +++ b/product/Localizer/GettextTag.py @@ -41,7 +41,7 @@ def name_or_expr(mapping, name_attr, expr_attr, default): return Eval(expr) if expr is None: return name - raise ParseError, ('%s and %s given' % (name_attr, expr_attr), 'calendar') + raise ParseError('%s and %s given' % (name_attr, expr_attr), 'calendar') diff --git a/product/Localizer/MessageCatalog.py b/product/Localizer/MessageCatalog.py index 360e7c28d1375b9e202ba1c84c41e3984d9085e9..db9c205f9e18319474dd0316771dffa6a4ffdc47 100644 --- a/product/Localizer/MessageCatalog.py +++ b/product/Localizer/MessageCatalog.py @@ -739,7 +739,7 @@ class POFile(SimpleItem): def PUT(self, REQUEST, RESPONSE): """ """ if REQUEST.environ['REQUEST_METHOD'] != 'PUT': - raise Forbidden, 'REQUEST_METHOD should be PUT.' + raise Forbidden('REQUEST_METHOD should be PUT.') body = REQUEST['BODY'] self.po_import(self.id, body) RESPONSE.setStatus(204) diff --git a/product/Localizer/__init__.py b/product/Localizer/__init__.py index d13417c44302bd8de4422960492a6c05efb02eb9..0edc7c8374830f4ea25571a840ed127eee9fd24e 100644 --- a/product/Localizer/__init__.py +++ b/product/Localizer/__init__.py @@ -44,7 +44,7 @@ def initialize(context): message = ( "The Localizer product must be installed within the 'Products'" " folder with the name 'Localizer' (not '%s').") % filename - raise RuntimeError, message + raise RuntimeError(message) # XXX This code has been written by Cornel Nitu, it may be a solution to # upgrade instances. diff --git a/product/MailTemplates/MailTemplate.py b/product/MailTemplates/MailTemplate.py index 076e33bd30eb77f2190227714198afe2142909f8..29c7c880b09866819fec7a12c90138398fb22430 100644 --- a/product/MailTemplates/MailTemplate.py +++ b/product/MailTemplates/MailTemplate.py @@ -40,7 +40,7 @@ class MailTemplate(BaseMailTemplate,ZopePageTemplate): def pt_editAction(self, REQUEST, mailhost, text, content_type, expand): """Change the mailhost and document.""" if self.wl_isLocked(): - raise ResourceLockedError, "File is locked via WebDAV" + raise ResourceLockedError("File is locked via WebDAV") self.expand=expand self._setPropValue('mailhost',mailhost) self.pt_edit(text, content_type) diff --git a/product/MailTemplates/tests/test_FSMailTemplate.py b/product/MailTemplates/tests/test_FSMailTemplate.py index e350f1a19b16c349221eb44350cf19dc91a6e56d..fffae00d25ec7ee1761eeb6ae35c889b0c7d5654 100644 --- a/product/MailTemplates/tests/test_FSMailTemplate.py +++ b/product/MailTemplates/tests/test_FSMailTemplate.py @@ -126,7 +126,7 @@ else: from zExceptions import Redirect try: self.assertRaises(self.ob.fake_skin.test.manage_workspace(self.r)) - except Redirect,r: + except Redirect as r: # this may appear to be incorrect, but http://foo/test_mt # is what we set as REQUEST['URL1'] self.assertEqual(r.args,('http://foo/test_mt/manage_main',)) diff --git a/product/MailTemplates/tests/test_MailTemplate.py b/product/MailTemplates/tests/test_MailTemplate.py index 1796481927f388d6b85b3111644eed338b0aaacc..279f2202578636a102d386626db9a52606544409 100644 --- a/product/MailTemplates/tests/test_MailTemplate.py +++ b/product/MailTemplates/tests/test_MailTemplate.py @@ -325,7 +325,7 @@ class TestMailTemplate(TestCase): from zExceptions import Redirect try: self.assertRaises(self.mt.manage_workspace(self.r)) - except Redirect,r: + except Redirect as r: # this may appear to be incorrect, but http://foo/test_mt # is what we set as REQUEST['URL1'] self.assertEqual(r.args,('http://foo/test_mt/pt_editForm',)) @@ -378,7 +378,7 @@ class TestMailTemplate(TestCase): self.test_add('Test Body') try: self.mt.send(**params) - except TypeError,e: + except TypeError as e: self.assertEqual(e.args[0],error) else: self.fail('Mail sent even though params missing') diff --git a/product/PortalTransforms/Transform.py b/product/PortalTransforms/Transform.py index 0552dd32a2411275b6c2abd3c5ae70f6ca527170..39aa71e0ca099ab83e3e71332b93c11291b18aee 100644 --- a/product/PortalTransforms/Transform.py +++ b/product/PortalTransforms/Transform.py @@ -26,7 +26,7 @@ def import_from_name(module_name): try: for sub in module_name.split('.')[1:]: m = getattr(m, sub) - except AttributeError, e: + except AttributeError as e: raise ImportError(str(e)) return m @@ -148,7 +148,7 @@ class Transform(SimpleItem): pass try: m = import_from_name(self.module) - except ImportError, err: + except ImportError as err: transform = BrokenTransform(self.id, self.module, err) msg = "Cannot register transform %s (ImportError), using BrokenTransform: Error\n %s" % (self.id, err) self.title = 'BROKEN' @@ -159,7 +159,7 @@ class Transform(SimpleItem): raise TransformException(msg) try: transform = m.register() - except Exception, err: + except Exception as err: transform = BrokenTransform(self.id, self.module, err) msg = "Cannot register transform %s, using BrokenTransform: Error\n %s" % (self.id, err) self.title = 'BROKEN' diff --git a/product/PortalTransforms/libtransforms/commandtransform.py b/product/PortalTransforms/libtransforms/commandtransform.py index 39da3f0c6645d6f5bfd98ef321e71c488ae4f7e8..45a225d23ac29625ac99b7a7baebb851ddbacc54 100644 --- a/product/PortalTransforms/libtransforms/commandtransform.py +++ b/product/PortalTransforms/libtransforms/commandtransform.py @@ -165,6 +165,6 @@ class subprocesstransform: stderr=PIPE, close_fds=True) data_out, data_err = process.communicate(input=data) if process.returncode: - raise OSError, data_err + raise OSError(data_err) cache.setData(data_out) return cache diff --git a/product/PortalTransforms/libtransforms/utils.py b/product/PortalTransforms/libtransforms/utils.py index f67aef9c39836a326182fb93f169e19d5cfcf545..2c24deaee12f405653e421cbbc5ee98a92769dec 100644 --- a/product/PortalTransforms/libtransforms/utils.py +++ b/product/PortalTransforms/libtransforms/utils.py @@ -182,10 +182,10 @@ class StrippingParser( SGMLParser ): for k, v in attrs: if k.lower().startswith( 'on' ): - raise IllegalHTML, 'Javascipt event "%s" not allowed.' % k + raise IllegalHTML('Javascipt event "%s" not allowed.' % k) if v.lower().startswith( 'javascript:' ): - raise IllegalHTML, 'Javascipt URI "%s" not allowed.' % v + raise IllegalHTML('Javascipt URI "%s" not allowed.' % v) self.result = '%s %s="%s"' % (self.result, k, v) @@ -196,7 +196,7 @@ class StrippingParser( SGMLParser ): self.result = self.result + ' />' elif NASTY_TAGS.get( tag ): - raise IllegalHTML, 'Dynamic tag "%s" not allowed.' % tag + raise IllegalHTML('Dynamic tag "%s" not allowed.' % tag) else: pass # omit tag diff --git a/product/PortalTransforms/libtransforms/zope27rest.py b/product/PortalTransforms/libtransforms/zope27rest.py index cd0175ab955f60a12597c3c0d9a6e36a26b28d73..52c18695713d5251640123651c0e78705ccf994a 100644 --- a/product/PortalTransforms/libtransforms/zope27rest.py +++ b/product/PortalTransforms/libtransforms/zope27rest.py @@ -20,15 +20,15 @@ Based on the new implementation of Zope 2.7.1 altered for PortalTransforms try: import docutils except ImportError: - raise ImportError, 'Please install docutils 0.3.3+ from http://docutils.sourceforge.net/#download.' + raise ImportError('Please install docutils 0.3.3+ from http://docutils.sourceforge.net/#download.') version = docutils.__version__.split('.') if version < ['0', '3', '3']: - raise ImportError, """Old version of docutils found: + raise ImportError("""Old version of docutils found: Got: %(version)s, required: 0.3.3+ Please remove docutils from %(path)s and replace it with a new version. You can download docutils at http://docutils.sourceforge.net/#download. -""" % {'version' : docutils.__version__, 'path' : docutils.__path__[0] } +""" % {'version' : docutils.__version__, 'path' : docutils.__path__[0] }) import sys, os, locale diff --git a/product/PortalTransforms/transforms/__init__.py b/product/PortalTransforms/transforms/__init__.py index c855f97ae76f7cb8610ff8dca2e85963920244b0..8145555c377a699e637c98bdba968a9be8f05729 100644 --- a/product/PortalTransforms/transforms/__init__.py +++ b/product/PortalTransforms/transforms/__init__.py @@ -54,12 +54,12 @@ for m in modules: try: ns = __import__(m, g, g, None) transforms.append(ns.register()) - except ImportError, e: + except ImportError as e: msg = "Problem importing module %s : %s" % (m, e) log(msg, severity=ERROR) - except MissingBinary, e: + except MissingBinary as e: log(str(e), severity=DEBUG) - except Exception, e: + except Exception as e: import traceback traceback.print_exc() log("Raised error %s for %s" % (e, m), severity=ERROR) diff --git a/product/PortalTransforms/transforms/python.py b/product/PortalTransforms/transforms/python.py index 8a8862fb8ac5eb15131a648052a53672583f39e2..75014b8b4891400af126595a4bd31193b539eae7 100644 --- a/product/PortalTransforms/transforms/python.py +++ b/product/PortalTransforms/transforms/python.py @@ -57,7 +57,7 @@ class Parser: self.out.write('
\n')
         try:
             tokenize.tokenize(text.readline, self)
-        except tokenize.TokenError, ex:
+        except tokenize.TokenError as ex:
             msg = ex[0]
             line = ex[1][0]
             self.out.write("
" % ( diff --git a/product/PortalTransforms/transforms/safe_html.py b/product/PortalTransforms/transforms/safe_html.py index 78fc000705ee27119a4e204c67f81e6e994283b6..b32705d339ebf7d60ebb7e393f06b78c4a43009e 100644 --- a/product/PortalTransforms/transforms/safe_html.py +++ b/product/PortalTransforms/transforms/safe_html.py @@ -214,13 +214,13 @@ class StrippingParser(HTMLParser): for k, v in attrs: if remove_script and k.strip().lower().startswith('on'): if not self.raise_error: continue - else: raise IllegalHTML, 'Script event "%s" not allowed.' % k + else: raise IllegalHTML('Script event "%s" not allowed.' % k) elif v is None: self.result.append(' %s' % k) elif remove_script and hasScript(v) and \ not (k.lower() == 'src' and tag.lower() == 'img'): if not self.raise_error: continue - else: raise IllegalHTML, 'Script URI "%s" not allowed.' % v + else: raise IllegalHTML('Script URI "%s" not allowed.' % v) else: if tag.lower() == 'meta' and k.lower() == 'content' and \ self.default_encoding and self.default_encoding not in v: @@ -246,7 +246,7 @@ class StrippingParser(HTMLParser): elif self.nasty.has_key(tag): self.suppress = True if self.raise_error: - raise IllegalHTML, 'Dynamic tag "%s" not allowed.' % tag + raise IllegalHTML('Dynamic tag "%s" not allowed.' % tag) else: # omit tag pass @@ -440,7 +440,7 @@ class SafeHTML: remove_javascript=self.config.get('remove_javascript', True), raise_error=False, default_encoding=self.config.get('default_encoding', 'utf-8')) - except IllegalHTML, inst: + except IllegalHTML as inst: data.setData(msg_pat % ("Error", str(inst))) break except (HTMLParseError, UnicodeDecodeError): diff --git a/product/ZLDAPConnection/Entry.py b/product/ZLDAPConnection/Entry.py index 684bc57919f88abd3c03b0235e43203a99e2cc9f..b41af766f78799541761b7246bc201041caa3e11 100644 --- a/product/ZLDAPConnection/Entry.py +++ b/product/ZLDAPConnection/Entry.py @@ -83,7 +83,7 @@ class GenericEntry(Acquisition.Implicit): def _connection(self): if self.__connection is None: - raise ConnectionError, 'No connection object for this entry' + raise ConnectionError('No connection object for this entry') else: return self.__connection @@ -99,20 +99,20 @@ class GenericEntry(Acquisition.Implicit): if conn.hasEntry(key): return conn.getEntry(key, self) else: - raise IndexError, key + raise IndexError(key) def __getattr__(self, attr): if self._data.has_key(attr): return AttrWrap(self._data[attr]) else: - raise AttributeError, attr + raise AttributeError(attr) #### Direct access for setting/getting/unsetting attributes def get(self, attr): if self._data.has_key(attr): return self._data[attr] else: - raise AttributeError, attr + raise AttributeError(attr) def set(self, key, value): """ Sets individual items """ @@ -169,7 +169,7 @@ class GenericEntry(Acquisition.Implicit): #### Get the ZLDAPConnection object. def _connection(self): if self.__connection is None: - raise ConnectionError, 'Cannot Get Connection' + raise ConnectionError('Cannot Get Connection') else: return self.__connection @@ -233,7 +233,7 @@ class GenericEntry(Acquisition.Implicit): # and verify that it doesn't already exist dn = "%s,%s" % (string.strip(rdn), self.dn) if conn.hasEntry(dn): # Check the LDAP server directly - raise KeyError, "DN '%s' already exists" % dn + raise KeyError("DN '%s' already exists" % dn) # Now split out the first attr based on the RDN (ie 'cn=bob') and # turn it into one of our attributes (ie attr[cn] = 'bob') @@ -395,7 +395,7 @@ class TransactionalEntry(GenericEntry): #Acquisition.Implicit #create the new full DN for new subentry and check its existance dn='%s,%s' % (string.strip(rdn), self.dn) if c.hasEntry(dn): - raise KeyError, "DN '%s' already exists" % dn + raise KeyError("DN '%s' already exists" % dn) # now split out the first attr based on the rdn (ie 'cn=bob', turns # into attr['cn'] = 'bob' diff --git a/product/ZLDAPConnection/ZLDAP.py b/product/ZLDAPConnection/ZLDAP.py index 0ffe451930678523d1d0918a7176e53ea822900e..37c34e53f5eb28ae7dac96e3f5f44fb048e8ec23 100644 --- a/product/ZLDAPConnection/ZLDAP.py +++ b/product/ZLDAPConnection/ZLDAP.py @@ -136,8 +136,7 @@ class ZLDAPConnection( def tpc_begin(self,*ignored): #make sure we're open! if not self.__ping(): #we're not open - raise (ConnectionError, - 'LDAP Connection is not open for commiting') + raise ConnectionError self._v_okobjects=[] def commit(self, o, *ignored): @@ -230,7 +229,7 @@ class ZLDAPConnection( if getattr(self, '_v_add',{}).has_key(dn): return (dn, self._v_add[dn]._data) elif dn in getattr(self,'_v_delete',()): - raise ldap.NO_SUCH_OBJECT, "Entry '%s' has been deleted" % dn + raise ldap.NO_SUCH_OBJECT("Entry '%s' has been deleted" % dn) try: e=self._connection().search_s( @@ -238,7 +237,7 @@ class ZLDAPConnection( ) if e: return e[0] except: - raise ldap.NO_SUCH_OBJECT, "Cannot retrieve entry '%s'" % dn + raise ldap.NO_SUCH_OBJECT("Cannot retrieve entry '%s'" % dn) def getEntry(self, dn, o=None): @@ -297,7 +296,7 @@ class ZLDAPConnection( ### modifying entries def _modifyEntry(self, dn, modlist): if not getattr(self,'_isCommitting',0): - raise AccessError, 'Cannot modify unless in a commit' + raise AccessError('Cannot modify unless in a commit') #someone's trying to be sneaky and modify an object #outside of a commit. We're not going to allow that! c=self._connection() @@ -321,7 +320,7 @@ class ZLDAPConnection( def _deleteEntry(self, dn): if not getattr(self, '_isCommitting',0): - raise AccessError, 'Cannot delete unless in a commit' + raise AccessError('Cannot delete unless in a commit') c=self._connection() c.delete_s(dn) @@ -342,7 +341,7 @@ class ZLDAPConnection( def _addEntry(self, dn, attrs): if not getattr(self, '_isCommitting',0): - raise AccessError, 'Cannot add unless in a commit' + raise AccessError('Cannot add unless in a commit') c=self._connection() c.add_s(dn, attrs) @@ -364,7 +363,7 @@ class ZLDAPConnection( if not self.isOpen(): self._open() return self._v_conn else: - raise ConnectionError, 'Connection Closed' + raise ConnectionError('Connection Closed') GetConnection=_connection @@ -373,7 +372,7 @@ class ZLDAPConnection( self._open() return self._v_conn else: - raise ConnectionError, 'Connection Closed' + raise ConnectionError('Connection Closed') def isOpen(self): " quickly checks to see if the connection's open " diff --git a/product/ZLDAPMethods/LM.py b/product/ZLDAPMethods/LM.py index 40bdbcbb29e62355d81df88f73b588bc9f6da23d..995304e7152914cb53b2880de87f87b806bf1c63 100644 --- a/product/ZLDAPMethods/LM.py +++ b/product/ZLDAPMethods/LM.py @@ -57,20 +57,20 @@ class ERP5LDIFRecordList(LDIFRecordList): if attr_type=='dn': # attr type and value pair was DN of LDIF record 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): - raise ValueError, 'No valid string-representation of distinguished name %s.' % (repr(attr_value)) + raise ValueError('No valid string-representation of distinguished name %s.' % (repr(attr_value))) dn = attr_value elif attr_type=='version' and dn is None: version = 1 elif attr_type=='changetype': # attr type and value pair was DN of LDIF record if dn is None: - raise ValueError, 'Read changetype: before getting valid dn: line.' + raise ValueError('Read changetype: before getting valid dn: line.') 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): - raise ValueError, 'changetype value %s is invalid.' % (repr(attr_value)) + raise ValueError('changetype value %s is invalid.' % (repr(attr_value))) changetype = attr_value attr_type, attr_value = self._parseAttrTypeandValue() modify_list = [] diff --git a/product/ZLDAPMethods/ldifvar.py b/product/ZLDAPMethods/ldifvar.py index 6b0ef0ee8de32c2062bd97cf93854b16a9b6b716..388127ae687e84db6c9fdad3b3ea4eaf8984d50b 100644 --- a/product/ZLDAPMethods/ldifvar.py +++ b/product/ZLDAPMethods/ldifvar.py @@ -77,10 +77,10 @@ class LDIFVar: self.args=args if not args.has_key('type'): - raise ParseError, ('the type attribute is required', 'dtvar') + raise ParseError('the type attribute is required', 'dtvar') t=args['type'] if not valid_type(t): - raise ParseError, ('invalid type, %s' % t, 'dtvar') + raise ParseError('invalid type, %s' % t, 'dtvar') def render(self, md): name=self.__name__ @@ -95,7 +95,7 @@ class LDIFVar: return if type(expr) is not type(''): raise - raise ValueError, 'Missing input variable, %s' % name + raise ValueError('Missing input variable, %s' % name) if v is None: return '' @@ -110,7 +110,7 @@ class LDIFVar: except: if not v and args.has_key('optional') and args['optional']: return - raise ValueError, ( + raise ValueError( 'Invalid integer value for %s' % name) elif t=='float': try: @@ -122,7 +122,7 @@ class LDIFVar: except: if not v and args.has_key('optional') and args['optional']: return - raise ValueError, ( + raise ValueError( 'Invalid floating-point value for %s' % name) else: @@ -132,7 +132,7 @@ class LDIFVar: if args.has_key('optional') and args['optional']: return else: - raise ValueError, ( + raise ValueError( 'Invalid empty string value for %s' % name) return v @@ -152,13 +152,13 @@ class LDIFLine: self.args=args if not args.has_key('type'): - raise ParseError, ('the type attribute is required', 'ldifattr') + raise ParseError('the type attribute is required', 'ldifattr') t=args['type'] if not valid_type(t): - raise ParseError, ('invalid type, %s' % t, 'dtvar') + raise ParseError('invalid type, %s' % t, 'dtvar') if not args.has_key('attr'): - raise ParseError, ('the attr attribute is required', 'ldifattr') + raise ParseError('the attr attribute is required', 'ldifattr') a=args['attr'] def render(self, md): @@ -176,13 +176,13 @@ class LDIFLine: return default if type(expr) is not type(''): raise - raise ValueError, 'Missing input variable, %s' % name + raise ValueError('Missing input variable, %s' % name) if v is None: if args.has_key('optional') and args['optional']: return default else: - raise ValueError, 'Missing input variable, %s' % name + raise ValueError('Missing input variable, %s' % name) if a in ['',None]: return default @@ -196,7 +196,7 @@ class LDIFLine: except: if not v and args.has_key('optional') and args['optional']: return default - raise ValueError, ( + raise ValueError( 'Invalid integer value for %s' % name) elif t=='float': try: @@ -208,7 +208,7 @@ class LDIFLine: except: if not v and args.has_key('optional') and args['optional']: return default - raise ValueError, ( + raise ValueError( 'Invalid floating-point value for %s' % name) else: @@ -218,7 +218,7 @@ class LDIFLine: if args.has_key('optional') and args['optional']: return default else: - raise ValueError, ( + raise ValueError( 'Invalid empty string value for %s' % name) return '%s: %s' % (a, v) diff --git a/product/ZMySQLDA/DABase.py b/product/ZMySQLDA/DABase.py index 1ecc6638cd8b270415ecea2ecbd0621662bf44e4..5194f1ba64178c1b2a444460f383490ae6648b53 100644 --- a/product/ZMySQLDA/DABase.py +++ b/product/ZMySQLDA/DABase.py @@ -135,7 +135,7 @@ class Connection(Shared.DC.ZRDB.Connection.Connection): if name=='tableNamed': if not hasattr(self, '_v_tables'): self.tpValues() return self._v_tables.__of__(self) - raise KeyError, name + raise KeyError(name) def manage_wizard(self, tables): " " @@ -155,7 +155,7 @@ class TableBrowserCollection(Acquisition.Implicit): class Browser(Base): def __getattr__(self, name): try: return self._d[name] - except KeyError: raise AttributeError, name + except KeyError: raise AttributeError(name) class values: @@ -225,7 +225,7 @@ class TableBrowser(Browser, Acquisition.Implicit): elif d: values.append(str(d)) else: - raise ValueError, ( + raise ValueError( 'no default was given for %s' % n) diff --git a/product/ZMySQLDA/db.py b/product/ZMySQLDA/db.py index b2f9e8e38774ce890a47a965331e88bb3332152a..8d2ada5742999548ace1b09deb835f6fd9286220 100644 --- a/product/ZMySQLDA/db.py +++ b/product/ZMySQLDA/db.py @@ -97,9 +97,8 @@ MySQLdb_version_required = (0,9,2) _v = getattr(_mysql, 'version_info', (0,0,0)) if _v < MySQLdb_version_required: - raise NotSupportedError, \ - "ZMySQLDA requires at least MySQLdb %s, %s found" % \ - (MySQLdb_version_required, _v) + raise NotSupportedError("ZMySQLDA requires at least MySQLdb %s, %s found" % \ + (MySQLdb_version_required, _v)) from MySQLdb.converters import conversions from MySQLdb.constants import FIELD_TYPE, CR, ER, CLIENT @@ -222,7 +221,7 @@ class DB(TM): if self._try_transactions == '-': transactional = 0 elif not transactional and self._try_transactions == '+': - raise NotSupportedError, "transactions not supported by this server" + raise NotSupportedError("transactions not supported by this server") self._transactions = transactional self._use_TM = transactional or self._mysql_lock @@ -353,7 +352,7 @@ class DB(TM): """ try: self.db.query(query) - except OperationalError, m: + except OperationalError as m: if m[0] in query_syntax_error: raise OperationalError(m[0], '%s: %s' % (m[1], query)) if m[0] in lock_error: @@ -365,7 +364,7 @@ class DB(TM): # Hm. maybe the db is hosed. Let's restart it. self._forceReconnection() self.db.query(query) - except ProgrammingError, exception: + except ProgrammingError as exception: LOG('ZMySQLDA', ERROR, 'query failed: %s' % (query,)) # XXX sometimes, after a programming error, the database object # gets fully broken and non-functional. So recover it by @@ -476,7 +475,7 @@ class DB(TM): self._query("ROLLBACK") else: LOG('ZMySQLDA', ERROR, "aborting when non-transactional") - except OperationalError, m: + except OperationalError as m: LOG('ZMySQLDA', ERROR, "exception during _abort", error=sys.exc_info()) if m[0] not in hosed_connection: @@ -531,7 +530,7 @@ class DB(TM): with (nested if src__ else self.lock)(): try: old_list, old_set, old_default = self._getTableSchema(name) - except ProgrammingError, e: + except ProgrammingError as e: if e[0] != ER.NO_SUCH_TABLE or not create_if_not_exists: raise if not src__: diff --git a/product/ZMySQLDA/tests/testDeferredConnection.py b/product/ZMySQLDA/tests/testDeferredConnection.py index 69f0e73cc7f37e7678804d0e3446be707c882287..a91de422254db21607543276abd57b48906cc5eb 100644 --- a/product/ZMySQLDA/tests/testDeferredConnection.py +++ b/product/ZMySQLDA/tests/testDeferredConnection.py @@ -55,7 +55,7 @@ def fake_db_query(self, *args, **kw): """ global GLOBAL_DB_CONNECTED_FLAG if GLOBAL_DB_CONNECTED_FLAG == UNCONNECTED_STATE: - raise OperationalError, (hosed_connection[0], 'dummy exception') + raise OperationalError(hosed_connection[0], 'dummy exception') return self.original_query(*args, **kw) class TestDeferredConnection(ERP5TypeTestCase): @@ -136,7 +136,7 @@ class TestDeferredConnection(ERP5TypeTestCase): try: try: self.commit() - except OperationalError, m: + except OperationalError as m: if m[0] not in hosed_connection: raise else: diff --git a/product/ZSQLCatalog/ColumnMap.py b/product/ZSQLCatalog/ColumnMap.py index 4f671a3f286b77af3f95c9d7842c824aca837faf..3c1027ea0cb42a7f239fc4630211b6dfa7b677f8 100644 --- a/product/ZSQLCatalog/ColumnMap.py +++ b/product/ZSQLCatalog/ColumnMap.py @@ -194,7 +194,7 @@ class ColumnMap(object): if alias is not None: self.resolveTable(table_name, alias, group=group) 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): mapping_dict = {} @@ -287,7 +287,7 @@ class ColumnMap(object): # Detect incomplete mappings if len(column_name_set): - raise ValueError, 'Could not map those columns: %r' % (column_name_set, ) + raise ValueError('Could not map those columns: %r' % (column_name_set, )) # Do the actual mapping for column_name, table_name in mapping_dict.iteritems(): @@ -506,7 +506,7 @@ class ColumnMap(object): if column == 'uid': LOG('ColumnMap', WARNING, 'Attempt to remap uid from %r to %r ignored.' % (previous_value, table_name)) else: - raise ValueError, 'Cannot remap a column to another table. column_map[%r] = %r, new = %r' % (column_map_key, column_map.get(column_map_key), table_name) + raise ValueError('Cannot remap a column to another table. column_map[%r] = %r, new = %r' % (column_map_key, column_map.get(column_map_key), table_name)) def resolveTable(self, table_name, alias, group=DEFAULT_GROUP_ID): table_alias_key = (group, table_name) diff --git a/product/ZSQLCatalog/Extensions/zsqlbrain.py b/product/ZSQLCatalog/Extensions/zsqlbrain.py index 325a1d5a06941a588f9484863e9c5e05f40d732c..f9f390219ad5357b8242b2246740f456895db956 100644 --- a/product/ZSQLCatalog/Extensions/zsqlbrain.py +++ b/product/ZSQLCatalog/Extensions/zsqlbrain.py @@ -52,8 +52,8 @@ class ZSQLBrain(Acquisition.Implicit): def getObject(self, REQUEST=None): """Try to return the object for this record""" if 'path' not in dir(self) and 'PATH' not in dir(self): - raise ValueError, "Unable to getObject from ZSQLBrain if ZSQL Method "\ - "does not retrieves the `path` column from catalog table." + raise ValueError("Unable to getObject from ZSQLBrain if ZSQL Method "\ + "does not retrieves the `path` column from catalog table.") obj = self.aq_parent.unrestrictedTraverse(self.getPath()) if obj is None: if REQUEST is None: diff --git a/product/ZSQLCatalog/Operator/ComparisonOperator.py b/product/ZSQLCatalog/Operator/ComparisonOperator.py index 30c76d98d43088ab1d6d56e2d1706f75fd0cfb17..262a1be9db12ab79907ced132114f6fb410e66cc 100644 --- a/product/ZSQLCatalog/Operator/ComparisonOperator.py +++ b/product/ZSQLCatalog/Operator/ComparisonOperator.py @@ -45,10 +45,10 @@ class ComparisonOperatorBase(OperatorBase): return SQLExpression(self, where_expression='%s %s %s' % (column, self.getOperator().upper(), value_list)) def render(self, column, value_list): - raise NotImplementedError, 'This method must be overloaded by a subclass.' + raise NotImplementedError('This method must be overloaded by a subclass.') def renderValue(self, value_list): - raise NotImplementedError, 'This method must be overloaded by a subclass.' + raise NotImplementedError('This method must be overloaded by a subclass.') verifyClass(IOperator, ComparisonOperatorBase) @@ -61,7 +61,7 @@ class MonovaluedComparisonOperator(ComparisonOperatorBase): try: value_list, = value_list except ValueError: - raise ValueError, '%r: value_list must not contain more than one item. Got %r' % (self, value_list) + raise ValueError('%r: value_list must not contain more than one item. Got %r' % (self, value_list)) return self._renderValue(value_list) def render(self, column, value_list): @@ -72,7 +72,7 @@ class MonovaluedComparisonOperator(ComparisonOperatorBase): try: value_list, = value_list except ValueError: - raise ValueError, '%r: value_list must not contain more than one item. Got %r' % (self, value_list) + raise ValueError('%r: value_list must not contain more than one item. Got %r' % (self, value_list)) return self._render(column, value_list) verifyClass(IOperator, MonovaluedComparisonOperator) @@ -83,7 +83,7 @@ class MultivaluedComparisonOperator(ComparisonOperatorBase): value_list must be a multi-value list (more than one item). """ if not isinstance(value_list, list_type_list) or len(value_list) < 2: - raise ValueError, '%r: value_list must be a list of more than one item. Got %r' % (self, value_list) + raise ValueError('%r: value_list must be a list of more than one item. Got %r' % (self, value_list)) return '(%s)' % ', '.join(map(self._renderValue, value_list)) def render(self, column, value_list): @@ -91,7 +91,7 @@ class MultivaluedComparisonOperator(ComparisonOperatorBase): value_list must be a multi-value list (more than one item). """ if not isinstance(value_list, list_type_list) or len(value_list) < 2: - raise ValueError, '%r: value_list must be a list of more than one item. Got %r' % (self, value_list) + raise ValueError('%r: value_list must be a list of more than one item. Got %r' % (self, value_list)) return column, '(%s)' % ', '.join(map(self._renderValue, value_list)) verifyClass(IOperator, MultivaluedComparisonOperator) @@ -153,7 +153,7 @@ class MroongaComparisonOperator(MatchComparisonOperator): try: value_list, = value_list except ValueError: - raise ValueError, '%r: value_list must not contain more than one item. Got %r' % (self, value_list) + raise ValueError('%r: value_list must not contain more than one item. Got %r' % (self, value_list)) if self.force_boolean: fulltext_query = '*D+ %s' % value_list @@ -192,7 +192,7 @@ class SphinxSEComparisonOperator(MonovaluedComparisonOperator): try: value_list, = value_list except ValueError: - raise ValueError, '%r: value_list must not contain more than one item. Got %r' % (self, value_list) + raise ValueError('%r: value_list must not contain more than one item. Got %r' % (self, value_list)) value_list = '%s;mode=extended2;limit=1000' % value_list return self._renderValue(value_list) diff --git a/product/ZSQLCatalog/Operator/OperatorBase.py b/product/ZSQLCatalog/Operator/OperatorBase.py index 66151d60988bc69d9ec46dfc93bc17bbefdd87b0..6a40352219ef04f6177b58ccba229feac16ab772 100644 --- a/product/ZSQLCatalog/Operator/OperatorBase.py +++ b/product/ZSQLCatalog/Operator/OperatorBase.py @@ -151,8 +151,8 @@ class OperatorBase(object): valueDefaultSearchTextRenderer)(value) def asSQLExpression(self, column, value_list, only_group_columns): - raise NotImplementedError, 'This method must be overloaded by a subclass ' \ - 'to be able to get an SQL representation of this operator.' + raise NotImplementedError('This method must be overloaded by a subclass ' \ + 'to be able to get an SQL representation of this operator.') def __repr__(self): return '<%s(%r) at %s>' % (self.__class__.__name__, self.getOperator(), id(self)) diff --git a/product/ZSQLCatalog/Query/AutoQuery.py b/product/ZSQLCatalog/Query/AutoQuery.py index 9dcb104d1ce907cda979f3321d5046fffb75a586..fe6b0011b9c089e60ad5df787745ac9cb275983d 100644 --- a/product/ZSQLCatalog/Query/AutoQuery.py +++ b/product/ZSQLCatalog/Query/AutoQuery.py @@ -59,7 +59,7 @@ class AutoQuery(Query): self.operator = operator self.ignore_empty_string = kw.pop('ignore_empty_string', True) 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=%r' % (kw['key'], )) self.search_key = kw.pop('key', None) def _createWrappedQuery(self, sql_catalog): @@ -106,7 +106,7 @@ class AutoQuery(Query): if self.table_alias_list is not None: query.setTableAliasList(self.table_alias_list) 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 def _asSearchTextExpression(self, sql_catalog, column=None): diff --git a/product/ZSQLCatalog/Query/ComplexQuery.py b/product/ZSQLCatalog/Query/ComplexQuery.py index be99d5d594e11b3a3c991303e010fcf58c16dd39..06b16b97bc4b6ab4b9a3c588c0cddc427ccb1419 100644 --- a/product/ZSQLCatalog/Query/ComplexQuery.py +++ b/product/ZSQLCatalog/Query/ComplexQuery.py @@ -158,7 +158,7 @@ class ComplexQuery(Query): assert len(search_text_list) == 1 result = 'NOT %s' % (search_text_list[0], ) else: - raise ValueError, 'Unknown operator %r' % (self.logical_operator, ) + raise ValueError('Unknown operator %r' % (self.logical_operator, )) if column not in (None, ''): if self_is_composed: result = '(%s)' % (result, ) diff --git a/product/ZSQLCatalog/Query/Query.py b/product/ZSQLCatalog/Query/Query.py index a63f5df79ed1c68fda6bdc0cb22ce956d3bf9f6b..c4e669af5e00324e8c674b9c87eacb2106aff506 100644 --- a/product/ZSQLCatalog/Query/Query.py +++ b/product/ZSQLCatalog/Query/Query.py @@ -45,13 +45,13 @@ class Query(object): """ 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): """ 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): return self._asSearchTextExpression(sql_catalog, column=column)[1] @@ -60,7 +60,7 @@ class Query(object): """ 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) diff --git a/product/ZSQLCatalog/Query/SQLQuery.py b/product/ZSQLCatalog/Query/SQLQuery.py index 9e30908a4bc6312c771b5fd03302744e7f84c929..5cc7bef35945482a8e7eebdd31621d0c2e7bfba4 100644 --- a/product/ZSQLCatalog/Query/SQLQuery.py +++ b/product/ZSQLCatalog/Query/SQLQuery.py @@ -45,7 +45,7 @@ class SQLQuery(Query): Raw SQL text. """ if not isinstance(payload, basestring): - raise TypeError, 'Payload must be a string, got a %r: %r' % (type(payload), payload) + raise TypeError('Payload must be a string, got a %r: %r' % (type(payload), payload)) assert len(payload) self.payload = '(' + payload + ')' diff --git a/product/ZSQLCatalog/Query/SimpleQuery.py b/product/ZSQLCatalog/Query/SimpleQuery.py index dae9d3a6cf3d8a5bf391b381bd1d0b513f2c2660..eeb750a2842ea67a0238f6f429c3778709a4bcd2 100644 --- a/product/ZSQLCatalog/Query/SimpleQuery.py +++ b/product/ZSQLCatalog/Query/SimpleQuery.py @@ -66,7 +66,7 @@ class SimpleQuery(Query): """ self.search_key = search_key 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() # Usability improvement code (those changes should not be needed when # this Query is instanciated by a SearchKey, as operator should be correct @@ -75,7 +75,7 @@ class SimpleQuery(Query): if comparison_operator == 'in': if isinstance(value, list_type_list): if len(value) == 0: - raise ValueError, 'Empty lists are not allowed.' + raise ValueError('Empty lists are not allowed.') elif len(value) == 1: value, = value comparison_operator = '=' @@ -84,7 +84,7 @@ class SimpleQuery(Query): elif comparison_operator == '=': if isinstance(value, list_type_list): if len(value) == 0: - raise ValueError, 'Empty lists are not allowed.' + raise ValueError('Empty lists are not allowed.') elif len(value) == 1: value, = value else: @@ -97,7 +97,7 @@ class SimpleQuery(Query): raise ValueError('Unexpected comparison_operator %r for None value.' % (comparison_operator, )) elif comparison_operator == 'is': - raise ValueError, 'Non-None value (%r) with "is" comparison_operator. Not sure what to do.' % (value, ) + raise ValueError('Non-None value (%r) with "is" comparison_operator. Not sure what to do.' % (value, )) self.value = value self.comparison_operator = comparison_operator self.group = group diff --git a/product/ZSQLCatalog/SQLExpression.py b/product/ZSQLCatalog/SQLExpression.py index a74f365c0e79485a23b194c88d013b45caadb632..1797903b6e5effe34af35cef1a98efc0aa4437e5 100644 --- a/product/ZSQLCatalog/SQLExpression.py +++ b/product/ZSQLCatalog/SQLExpression.py @@ -125,7 +125,7 @@ class SQLExpression(object): if len(limit) < 3: self.limit = limit else: - raise ValueError, 'Unrecognized "limit" value: %r' % (limit, ) + raise ValueError('Unrecognized "limit" value: %r' % (limit, )) else: self.limit = (limit, ) if from_expression is not None: @@ -188,7 +188,7 @@ class SQLExpression(object): sql_expression, sql_expression.query, ', '.join('%r (%r)' % (x, x.query) for x in self.sql_expression_list)) - raise ValueError, message + raise ValueError(message) result[alias] = table_name return result @@ -211,7 +211,7 @@ class SQLExpression(object): sql_expression, sql_expression.query, ', '.join('%r (%r)' % (x, x.query) for x in self.sql_expression_list)) - raise ValueError, message + raise ValueError(message) return result def getOrderByList(self): @@ -251,7 +251,7 @@ class SQLExpression(object): if delay_error: order_by_dict[key] = MergeConflict(message) else: - raise MergeConflictError, message + raise MergeConflictError(message) result_dict.update(order_by_dict) return result_dict @@ -317,7 +317,7 @@ class SQLExpression(object): sql_expression, sql_expression.query, ', '.join('%r (%r)' % (x, x.query) for x in self.sql_expression_list)) - raise ValueError, message + raise ValueError(message) return result def getLimitExpression(self): diff --git a/product/ZSQLCatalog/SearchKey/DateTimeKey.py b/product/ZSQLCatalog/SearchKey/DateTimeKey.py index 247cbf0bcd8b033e48504a3f69d7e3c456e2489e..09172aa80816349cc35a13fa8e06d600f0d05036 100644 --- a/product/ZSQLCatalog/SearchKey/DateTimeKey.py +++ b/product/ZSQLCatalog/SearchKey/DateTimeKey.py @@ -90,7 +90,7 @@ def castDate(value, change_timezone=True): else: raise else: - raise TypeError, 'Unknown date type: %r' % (value) + raise TypeError('Unknown date type: %r' % (value)) if change_timezone: return value.toZone('UTC') else: @@ -139,9 +139,9 @@ def getPeriodBoundaries(value): if isinstance(value, basestring): delimiter_count = countDelimiters(value) 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: - raise TypeError, 'Unknown date type: %r' % (value) + raise TypeError('Unknown date type: %r' % (value)) delta = delta_list[delimiter_count] if callable(delta): delta = delta(first_date) diff --git a/product/ZSQLCatalog/SearchKey/SearchKey.py b/product/ZSQLCatalog/SearchKey/SearchKey.py index 5a0fcf66ef93b4114eb76b79be1cf0298bd2515b..52e485f745b6670edcadc3c9a9eb1c78c6019991 100644 --- a/product/ZSQLCatalog/SearchKey/SearchKey.py +++ b/product/ZSQLCatalog/SearchKey/SearchKey.py @@ -243,24 +243,24 @@ class SearchKey(object): comparison_operator = single_operator_dict[value_range] elif value_range in dual_operator_dict: if not isinstance(actual_value, (tuple, list)): - raise TypeError, 'Operator %r requires value to be a '\ + raise TypeError('Operator %r requires value to be a '\ 'tuple/list. (%r)' % (value_range, - search_value) + search_value)) if len(actual_value) != 2: - raise TypeError, 'Operator %r requires value to have a length '\ + raise TypeError('Operator %r requires value to have a length '\ 'of 2. len(%r) = %i (%r)' % (value_range, - actual_value, len(actual_value), search_value) + actual_value, len(actual_value), search_value)) comparison_operator = dual_operator_dict[value_range] logical_operator = 'and' 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 not isinstance(value_operator, basestring): - raise TypeError, 'Operator must be of a string type. Got a %r' % \ - (type(value_operator), ) + raise TypeError('Operator must be of a string type. Got a %r' % \ + (type(value_operator), )) value_operator = value_operator.lower() 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.') if value_operator == 'in': comparison_operator = '=' logical_operator = 'or' diff --git a/product/ZSQLCatalog/SearchText/SearchTextParser.py b/product/ZSQLCatalog/SearchText/SearchTextParser.py index a20ff11963c1596ee4ffb73fd880d3a962988fcb..978e5ce9325c9bd48be60afc3c3a8ed6ce8267a6 100755 --- a/product/ZSQLCatalog/SearchText/SearchTextParser.py +++ b/product/ZSQLCatalog/SearchText/SearchTextParser.py @@ -51,7 +51,7 @@ class ParserPool(object): parser_registry = self.parser_registry name = '.'.join((parser.__module__, parser.__name__)) 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 return name @@ -306,7 +306,7 @@ if __name__ == '__main__': for input, expected in check_list: try: result = parse(input) - except ParserOrLexerError, message: + except ParserOrLexerError as message: print "ERROR when checking %r" % (input, ) print " crashed with: %s" % (message, ) print " instead of producing %r" % (expected, ) @@ -328,7 +328,7 @@ if __name__ == '__main__': try: detector_result = parser_pool.get(DETECTOR_ID)(input, isColumn) - except ParserOrLexerError, message: + except ParserOrLexerError as message: print ' Detector raise: %r' % (message, ) detector_result = False else: @@ -348,7 +348,7 @@ if __name__ == '__main__': print ' %r' % (parse(input, debug=2), ) else: print ' %r' % (input, ) - except ParserOrLexerError, message: + except ParserOrLexerError as message: print message print diff --git a/product/ZSQLCatalog/SearchText/lexer.py b/product/ZSQLCatalog/SearchText/lexer.py index 01b3b88fe2418de995c3be66261dbc60870f28e6..fbae816a85026ca3335a75ac564316346b301948 100644 --- a/product/ZSQLCatalog/SearchText/lexer.py +++ b/product/ZSQLCatalog/SearchText/lexer.py @@ -61,10 +61,10 @@ class lexer(object): LOG('lexer', 0, line) def t_error(self, t): - raise LexerError, 'ERROR: Invalid character %r' % (t.value[0], ) + raise LexerError('ERROR: Invalid character %r' % (t.value[0], )) def p_error(self, p): - raise ParserError, 'Syntax error in input: %r' % (p, ) + raise ParserError('Syntax error in input: %r' % (p, )) def input(self, string): self.lexer.input(string) diff --git a/product/ZSQLCatalog/ZSQLCatalog.py b/product/ZSQLCatalog/ZSQLCatalog.py index 564138b24be1b95645babd21ef4955253f39e3c8..64c23fdf1eeeda75c90e59bb0045901e39f195b2 100644 --- a/product/ZSQLCatalog/ZSQLCatalog.py +++ b/product/ZSQLCatalog/ZSQLCatalog.py @@ -259,7 +259,7 @@ class ZCatalog(Folder, Persistent, Implicit): self.destination_sql_catalog_id = destination_sql_catalog_id self.archive_path = archive_path else: - raise CatalogError, 'unknown hot reindexing state %s' % state + raise CatalogError('unknown hot reindexing state %s' % state) def _finishHotReindexing(self, source_sql_catalog_id, destination_sql_catalog_id, skin_selection_dict, @@ -293,8 +293,8 @@ class ZCatalog(Folder, Persistent, Implicit): ERP5Site_reindexAll. """ if self.getHotReindexingState() == HOT_REINDEXING_FINISHED_STATE: - raise Exception, 'cancelHotReindexing called while no Hot Reindexing '\ - 'was runing. Nothing done.' + raise Exception('cancelHotReindexing called while no Hot Reindexing '\ + 'was runing. Nothing done.') # Remove hot reindexing state self._setHotReindexingState(HOT_REINDEXING_FINISHED_STATE) portal_activities = getToolByName(self, 'portal_activities') @@ -323,9 +323,9 @@ class ZCatalog(Folder, Persistent, Implicit): transaction. """ 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_DOUBLE_INDEXING_STATE, ) + % (HOT_REINDEXING_DOUBLE_INDEXING_STATE, )) catalog_object = self.getSQLCatalog(sql_catalog_id) result = catalog_object.readRecordedObjectList(catalog=catalog) if len(result): @@ -337,7 +337,7 @@ class ZCatalog(Folder, Persistent, Implicit): if obj is not None: obj.reindexObject(sql_catalog_id=sql_catalog_id) else: - raise ValueError, '%s is not a valid value for "catalog".' % (catalog, ) + raise ValueError('%s is not a valid value for "catalog".' % (catalog, )) catalog_object.deleteRecordedObjectList(uid_list=[o.uid for o in result]) # Re-schedule the same action in case there are remaining rows in the # table. This can happen if the database connector limits the number @@ -428,13 +428,13 @@ class ZCatalog(Folder, Persistent, Implicit): """ # Hot reindexing can only be runing once at a time on a system. if self.hot_reindexing_state is not None: - 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: - raise CatalogError, 'Hot reindexing cannot be done with the same '\ + raise CatalogError('Hot reindexing cannot be done with the same '\ 'catalog as both source and destination. What'\ ' you want to do is a "clear catalog" and an '\ - '"ERP5Site_reindexAll".' + '"ERP5Site_reindexAll".') if source_sql_catalog_id != self.getDefaultSqlCatalogId(): LOG('ZSQLCatalog', 0, 'Warning : Hot reindexing is started with a '\ @@ -832,7 +832,7 @@ class ZCatalog(Folder, Persistent, Implicit): def uncatalog_object(self, uid=None,path=None, sql_catalog_id=None): """ wrapper around catalog """ if uid is None: - raise TypeError, "sorry uncatalog_object supports only uid" + raise TypeError("sorry uncatalog_object supports only uid") default_catalog = self.getSQLCatalog() if sql_catalog_id is None: @@ -1153,7 +1153,7 @@ class ZCatalog(Folder, Persistent, Implicit): try: add_result=result.append except AttributeError: - raise AttributeError, `result` + raise AttributeError(`result`) for id, ob in items: if pre: p="%s/%s" % (pre, id) diff --git a/product/ZSQLCatalog/tests/testSQLCatalog.py b/product/ZSQLCatalog/tests/testSQLCatalog.py index 553274ec67ea3372e9bdd09114814004e9924026..51c369c2ff13433ce446fd5cbe1682fa53946ff2 100644 --- a/product/ZSQLCatalog/tests/testSQLCatalog.py +++ b/product/ZSQLCatalog/tests/testSQLCatalog.py @@ -102,7 +102,7 @@ class ReferenceQuery: value = MatchList([value]) self.value = value 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): if isinstance(other, SimpleQuery): @@ -132,7 +132,7 @@ class ReferenceQuery: elif isinstance(other, Query): return self == other.wrapped_query else: - raise TypeError, 'Compared value is not a (known) Query instance: (%s) %r' % (other.__class__.__name__, other) + raise TypeError('Compared value is not a (known) Query instance: (%s) %r' % (other.__class__.__name__, other)) def __repr__(self): if self.args: diff --git a/product/Zelenium/generator.py b/product/Zelenium/generator.py index aff859ba4076fe08aec663030bb3a70d9b6439ea..4ee52b598915f2de5bd57eb60c650f276bc97dc1 100644 --- a/product/Zelenium/generator.py +++ b/product/Zelenium/generator.py @@ -181,7 +181,7 @@ class ScenarioGenerator: , 'test-case-title=' ] ) - except getopt.GetoptError, msg: + except getopt.GetoptError as msg: self.printUsage( msg=msg) for o, v in opts: diff --git a/product/Zelenium/tests/test_zuite.py b/product/Zelenium/tests/test_zuite.py index 8365a2a85a773be9b515a319c326cb8ad33578e3..4983f8e77baad9f40bbef4de541997d930e3ef14 100644 --- a/product/Zelenium/tests/test_zuite.py +++ b/product/Zelenium/tests/test_zuite.py @@ -131,11 +131,11 @@ class ZuiteTests( unittest.TestCase ): for name in names: if name not in contents: - raise AssertionError, 'Extra name in archive: %s' % name + raise AssertionError('Extra name in archive: %s' % name) for name in contents: if name not in names: - raise AssertionError, 'Missing name in archive: %s' % name + raise AssertionError('Missing name in archive: %s' % name) def _verifyManifest( self, bits, name, contents ): diff --git a/product/Zelenium/zuite.py b/product/Zelenium/zuite.py index c00f71927674788d86895170c6f735d1879ece91..f46ad5f542cedb881d2dc75ad75882cd2a683238 100644 --- a/product/Zelenium/zuite.py +++ b/product/Zelenium/zuite.py @@ -201,7 +201,7 @@ class Zuite( OrderedFolder ): if value is not _MARKER: return value - raise KeyError, key + raise KeyError(key) security.declareProtected( View, 'listTestCases' ) @@ -678,7 +678,7 @@ class ZuiteResults( Folder ): if default is not _MARKER: return default - raise KeyError, key + raise KeyError(key) InitializeClass( ZuiteResults ) @@ -718,7 +718,7 @@ class _FilesystemProxy( Folder ): if default is not _MARKER: return default - raise KeyError, key + raise KeyError(key) security.declareProtected( View, 'listTestCases' ) def listTestCases( self, prefix=() ):