Commit 7b7c4723 authored by Jérome Perrin's avatar Jérome Perrin

core: pylint for py3

parent 4e9f8ce4
......@@ -195,7 +195,6 @@ class Amount(Base, VariatedMixin):
"""Do nothing in the case of an amount, because variation base category
list are set on the resource.
"""
pass
security.declareProtected(Permissions.AccessContentsInformation,
'getVariationBaseCategoryItemList')
......@@ -577,7 +576,7 @@ class Amount(Base, VariatedMixin):
if destination in (None, ''):
if quantity < 0:
return - quantity
return - quantity # pylint:disable=invalid-unary-operand-type
else:
return 0.0
......@@ -604,7 +603,7 @@ class Amount(Base, VariatedMixin):
if source in (None, ''):
if quantity < 0:
return - quantity
return - quantity # pylint:disable=invalid-unary-operand-type
else:
return 0.0
......
......@@ -317,7 +317,7 @@ class AppliedRule(XMLObject, ExplainableMixin):
try:
best_sm_list = best_dict[None]
except KeyError:
best_sm_list, = best_dict.values()
best_sm_list, = best_dict.values() # pylint:disable=unbalanced-dict-unpacking
if len(best_sm_list) < len(sm_list):
sm_dict[k] = list(set(sm_list).difference(best_sm_list))
sm_list = best_sm_list
......
......@@ -69,26 +69,26 @@ class ContributionPredicate(Predicate, XMLObject):
This method returns portal type name if test success, else returns False.
"""
self = self.asPredicate()
self_as_predicate = self.asPredicate()
result = 1
if getattr(aq_base(self), '_identity_criterion', None) is None:
self._identity_criterion = {}
self._range_criterion = {}
for property_, value in six.iteritems(self._identity_criterion):
if getattr(aq_base(self_as_predicate), '_identity_criterion', None) is None:
self_as_predicate._identity_criterion = {}
self_as_predicate._range_criterion = {}
for property_, value in six.iteritems(self_as_predicate._identity_criterion):
result = result and (context.getProperty(property_) in value)
for property_, (min_, max_) in six.iteritems(self._range_criterion):
for property_, (min_, max_) in six.iteritems(self_as_predicate._range_criterion):
value = context.getProperty(property_)
if min_ is not None:
result = result and (value >= min_)
if max_ is not None:
result = result and (value < max_)
multimembership_criterion_base_category_list = \
self.getMultimembershipCriterionBaseCategoryList()
self_as_predicate.getMultimembershipCriterionBaseCategoryList()
membership_criterion_base_category_list = \
self.getMembershipCriterionBaseCategoryList()
self_as_predicate.getMembershipCriterionBaseCategoryList()
tested_base_category = {}
membership_criterion_category_list = \
self.getMembershipCriterionCategoryList()
self_as_predicate.getMembershipCriterionCategoryList()
if tested_base_category_list is not None:
membership_criterion_category_list = [x for x in \
membership_criterion_category_list if x.split('/', 1)[0] in \
......@@ -115,14 +115,14 @@ class ContributionPredicate(Predicate, XMLObject):
result = result and (0 not in tested_base_category.values())
# Test method calls
test_method_id_list = self.getTestMethodIdList()
test_method_id_list = self_as_predicate.getTestMethodIdList()
if test_method_id_list:
for test_method_id in test_method_id_list:
if (test_method_id is not None) and result:
method = getattr(context, test_method_id)
result = result and method(self)
result = result and method(self_as_predicate)
else:
result = result and self.getDestinationPortalType()
result = result and self_as_predicate.getDestinationPortalType()
return result
def asQuery(self, *args, **kw):
......
......@@ -741,7 +741,6 @@ class Delivery(XMLObject, ImmobilisationDelivery, SimulableMixin,
"""
This is a hack
"""
pass
security.declareProtected( Permissions.AccessContentsInformation,
'getParentExplanationValue')
......@@ -761,7 +760,6 @@ class Delivery(XMLObject, ImmobilisationDelivery, SimulableMixin,
"""
This is a hack
"""
pass
security.declareProtected(Permissions.AccessContentsInformation,
'getBuilderList')
......
......@@ -309,7 +309,6 @@ class EmailDocument(TextDocument, MailMessageMixin):
to extract content information from this mail
message.
"""
pass
security.declareProtected(Permissions.View, 'index_html')
index_html = TextDocument.index_html
......
......@@ -153,7 +153,7 @@ class File(Document, OFS_File):
security.declarePrivate('update_data')
def update_data(self, *args, **kw):
super(File, self).update_data(*args, **kw)
if six.PY2 and isinstance(self.size, long): # pylint:disable=undefined-variable
if six.PY2 and isinstance(self.size, long): # pylint:disable=access-member-before-definition,undefined-variable
self.size = int(self.size)
security.declareProtected(Permissions.ModifyPortalContent,'setFile')
......
......@@ -119,7 +119,7 @@ class ImmobilisationDelivery(XMLObject):
sub_movement_list = self.contentValues()
for movement in self.getImmobilisationMovementList(**kw):
for item in movement.getAggregateValueList():
if IImmobilisationItem.providedBy(item):
if IImmobilisationItem.providedBy(item): # pylint:disable=no-value-for-parameter
future_movement_list = item.getFutureImmobilisationMovementValueList(
at_date = self.getStopDate(),
from_movement = self,
......
......@@ -142,7 +142,7 @@ class ImmobilisationMovement(Movement, XMLObject):
# Check if the date of this movement is unique
date_error = 0
for item in self.getAggregateValueList():
if IImmobilisationItem.providedBy(item):
if IImmobilisationItem.providedBy(item): # pylint:disable=no-value-for-parameter
same_date_list = item.getUnfilteredImmobilisationMovementValueList(
from_date = self.getStopDate(),
to_date = self.getStopDate(),
......@@ -200,7 +200,7 @@ class ImmobilisationMovement(Movement, XMLObject):
return checkPreviousMovementForItem(previous_movement, item)
return checkPreviousMovementForItem(previous_movement, item)
for item in self.getAggregateValueList():
if IImmobilisationItem.providedBy(item):
if IImmobilisationItem.providedBy(item): # pylint:disable=no-value-for-parameter
if not checkPreviousMovementForItem(self,item):
check_uncontinuous = 1
else:
......
......@@ -58,18 +58,6 @@ class Item(XMLObject, Amount):
, PropertySheet.Reference
)
if 0:
# The following code is disabled. The original intention was to generate
# an unique reference for each item. We now use reference instead of id,
# so this is not applicable any longer. We need something different for
# reference.
security.declareProtected(Permissions.ModifyPortalContent,'generateNewId')
def generateNewId(self, id_group='item_id_group', default=None, method=None):
"""
We want a different id for all Item
"""
return XMLObject.generateNewId(self, id_group=id_group, default=default, method=method)
security.declareProtected(Permissions.AccessContentsInformation, 'getPrice')
def getPrice(self,context=None,**kw):
"""
......
......@@ -80,43 +80,41 @@ class Order(Delivery):
# Call getAggregatedAmountList and sum all the amounts which
# base_contribution category is matched with.
raise NotImplementedError
"""
rounding = kw.get('rounding')
from Products.ERP5.PropertySheet.TradeModelLine import TARGET_LEVEL_MOVEMENT
trade_condition = self.getSpecialiseValue()
if trade_condition is None:
# We cannot find any amount so that the result is 0.
return 0
base_contribution = kw.get('base_contribution')
if isinstance(base_contribution, (tuple, list)):
base_contribution_list = base_contribution
else:
base_contribution_list = (base_contribution,)
base_contribution_value_list = []
portal_categories = self.portal_categories
for relative_url in base_contribution_list:
base_contribution_value = portal_categories.getCategoryValue(relative_url)
if base_contribution_value is not None:
base_contribution_value_list.append(base_contribution_value)
if not base_contribution_value_list:
# We cannot find any amount so that the result is 0.
return 0
current_aggregated_amount_list = trade_condition.getAggregatedAmountList(self, rounding=rounding, force_create_line=True)
trade_model_line = self.newContent(temp_object=True,
portal_type='Trade Model Line',
id='_temp_' + self.getId(), notify_workflow=False)
# prevent invoking interaction workflows.
trade_model_line.portal_type = ''
trade_model_line.edit(target_level=TARGET_LEVEL_MOVEMENT, price=1,
efficiency=1, quantity=None,
base_application_value_list=base_contribution_value_list)
aggregated_amount_list = trade_model_line._getAggregatedAmountList(
self,
movement_list=self.getMovementList(),
current_aggregated_amount_list=current_aggregated_amount_list,
rounding=rounding)
return aggregated_amount_list.getTotalPrice()
"""
# rounding = kw.get('rounding')
# from Products.ERP5.PropertySheet.TradeModelLine import TARGET_LEVEL_MOVEMENT
# trade_condition = self.getSpecialiseValue()
# if trade_condition is None:
# # We cannot find any amount so that the result is 0.
# return 0
# base_contribution = kw.get('base_contribution')
# if isinstance(base_contribution, (tuple, list)):
# base_contribution_list = base_contribution
# else:
# base_contribution_list = (base_contribution,)
# base_contribution_value_list = []
# portal_categories = self.portal_categories
# for relative_url in base_contribution_list:
# base_contribution_value = portal_categories.getCategoryValue(relative_url)
# if base_contribution_value is not None:
# base_contribution_value_list.append(base_contribution_value)
# if not base_contribution_value_list:
# # We cannot find any amount so that the result is 0.
# return 0
# current_aggregated_amount_list = trade_condition.getAggregatedAmountList(self, rounding=rounding, force_create_line=True)
# trade_model_line = self.newContent(temp_object=True,
# portal_type='Trade Model Line',
# id='_temp_' + self.getId(), notify_workflow=False)
# # prevent invoking interaction workflows.
# trade_model_line.portal_type = ''
# trade_model_line.edit(target_level=TARGET_LEVEL_MOVEMENT, price=1,
# efficiency=1, quantity=None,
# base_application_value_list=base_contribution_value_list)
# aggregated_amount_list = trade_model_line._getAggregatedAmountList(
# self,
# movement_list=self.getMovementList(),
# current_aggregated_amount_list=current_aggregated_amount_list,
# rounding=rounding)
# return aggregated_amount_list.getTotalPrice()
def getTotalQuantity(self, **kw) :
"""Returns the total quantity for this Order. """
......
......@@ -41,7 +41,7 @@ def toDateTime(time):
elif hasattr(time, 'timeTime'):
# assume that the time is persistent.TimeStamp
return DateTime(time.timeTime())
raise ValueError('do not know the time type :%r', time)
raise ValueError('do not know the time type :%r' % time)
def _getWorkflowHistory(document, initial_datetime):
history = []
......
......@@ -271,6 +271,7 @@ class AmountGeneratorMixin:
- is rounding really well supported (ie. before and after aggregation)
very likely not - proxying before or after must be decided
"""
# pylint:disable=self-cls-assignment
# It is the only place where we can import this
portal = self.getPortalObject()
getRoundingProxy = portal.portal_roundings.getRoundingProxy
......
......@@ -193,7 +193,7 @@ class CompositionMixin:
'asComposedDocument')
asComposedDocument = transactional_cached(
lambda self, portal_type_list=None: (self, portal_type_list)
)(asComposedDocument)
)(asComposedDocument) # pylint:disable=used-before-assignment
# XXX add accessors to get properties from '_effective_model_list' ?
# (cf PaySheetModel)
......@@ -226,7 +226,7 @@ class CompositionMixin:
model = _getEffectiveModel(model, start_date, stop_date)
if model not in effective_set:
effective_set.add(model)
if 1: #model.test(self): # XXX
if 1: #model.test(self): # XXX # pylint:disable=using-constant-test
effective_list.append(model)
return effective_list, specialise_value_list
......
......@@ -57,7 +57,7 @@ class DocumentExtensibleTraversableMixin(BaseExtensibleTraversableMixin):
# in some cases user (like Anonymous) can not view document according to portal catalog
# but we may ask him to login if such a document exists
isAuthorizationForced = getattr(self, 'isAuthorizationForced', None)
if isAuthorizationForced is not None and isAuthorizationForced():
if isAuthorizationForced is not None and isAuthorizationForced(): # pylint:disable=not-callable
if unrestricted_apply(self.getDocumentValue, (name, portal)) is not None:
# force user to login as specified in Web Section
raise Unauthorized
......@@ -43,7 +43,7 @@ try:
except ImportError:
# BBB backport https://github.com/zopefoundation/Zope/pull/893 with py2 support
def make_content_disposition(disposition, file_name):
if six.PY2 and not isinstance(file_name, unicode):
if six.PY2 and not isinstance(file_name, six.text_type):
file_name = file_name.decode('utf-8')
try:
file_name.encode('us-ascii')
......
......@@ -79,7 +79,8 @@ class RuleMixin(Predicate):
return context.newContent(portal_type='Applied Rule',
specialise_value=self, **kw)
if 0: # XXX-JPS - if people are stupid enough not to configfure predicates,
if 0: # pylint:disable=using-constant-test
# XXX-JPS - if people are stupid enough not to configfure predicates,
# it is not our role to be clever for them
# Rules have a workflow - make sure applicable rule system works
# if you wish, add a test here on workflow state to prevent using
......
......@@ -57,7 +57,7 @@ class VirtualFolderMixin:
if method is not None:
return method(name, typ, body)
return Folder.PUT_factory(self, name, typ, body)
return Folder.PUT_factory(self, name, typ, body) # pylint:disable=not-callable
security.declarePrivate('_setObject')
def _setObject(self, id, ob, **kw): # pylint: disable=redefined-builtin
......
......@@ -33,7 +33,6 @@ from zLOG import (
TRACE,
DEBUG,
BLATHER,
INFO,
PROBLEM,
WARNING,
ERROR,
......
......@@ -160,7 +160,8 @@ class MovementGroupNode:
movement, self._property_dict, property_list=property_list)
# The following check is partial because it does not check mutable values
# recursively.
if property_dict is self._property_dict != property_dict:
different_property_dict = self._property_dict != property_dict
if property_dict is different_property_dict:
raise ValueError(
"Movement Group must not modify the passed 'property_dict':"
" copy it, deeply if necessary, before editing properties")
......
......@@ -47,7 +47,7 @@ class TextContent:
try:
tree = html.fromstring(text)
if tree.tag != "html":
raise Exception
raise ValueError
except Exception:
# this is probably not html code, try rfc822 parsing
if six.PY3:
......
......@@ -104,9 +104,9 @@ for table_name in spreadsheet_list.keys():
# 1 table = 1 base category
base_category_name = table_name
base_category_id = getIDFromString(base_category_name)
if six.PY2 and isinstance(base_category_name, unicode):
if six.PY2 and isinstance(base_category_name, six.text_type):
base_category_name = base_category_name.encode('utf8')
if six.PY2 and isinstance(base_category_id, unicode):
if six.PY2 and isinstance(base_category_id, six.text_type):
base_category_id = base_category_id.encode('utf8')
category_list = category_list_spreadsheet_mapping.setdefault(base_category_id, [])
category_list.append({ 'path' : base_category_id
......
......@@ -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 RuntimeError('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
......
......@@ -3,16 +3,15 @@ from Products.CMFCore.WorkflowCore import WorkflowException
o = context.getObject()
if 1: # keep indentation
try :
context.portal_workflow.doActionFor( o,
workflow_action,
comment=comment,
**kw)
except WorkflowException:
pass
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 :
return context.Base_redirect(keep_items={'portal_status_message': str(message)})
try :
context.portal_workflow.doActionFor( o,
workflow_action,
comment=comment,
**kw)
except WorkflowException:
pass
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 :
return context.Base_redirect(keep_items={'portal_status_message': str(message)})
......@@ -29,5 +29,9 @@ for base_category_id in preferred_predicate_category_list:
uid_item_list_list = category_parent_uid_item_dict.values()
if uid_item_list_list:
return reduce(lambda a,b:a+b, uid_item_list_list)
result = []
for uid_item_list in uid_item_list_list:
result.extend(uid_item_list)
return result
return ()
......@@ -60,7 +60,7 @@ if detailed_report_result:
REQUEST.other['category_import_report'] = detailed_report_result
REQUEST.RESPONSE.setBody(portal_categories.CategoryTool_viewImportReport().encode('utf-8'), lock=True)
REQUEST.RESPONSE.setStatus(200, 'OK', lock=True)
raise Exception('Spreadsheet contains errors')
raise ValueError('Spreadsheet contains errors')
for base_category, category_list in six.iteritems(category_list_spreadsheet_dict):
total_category_counter += len(category_list)
......@@ -212,7 +212,10 @@ if detailed_report:
if simulation_mode:
REQUEST.RESPONSE.setBody(result, lock=True)
REQUEST.RESPONSE.setStatus(200, 'OK', lock=True)
raise Exception('Dry run')
class DryRun(Exception):
"""Exception raised to not commit transaction.
"""
raise DryRun()
return result
portal_categories.Base_redirect(
keep_items={
......
......@@ -97,7 +97,7 @@ def checkField(folder, form, field):
if a not in (None, "portal_catalog", "searchFolder", "objectValues",
"contentValues", "ListBox_initializeFastInput"):
if not a.endswith('List'):
if 0:
if 0: # pylint:disable=using-constant-test
error_message += "%s : %s : %r Bad Naming Convention\n" % (path, id_, a)
return error_message
......
......@@ -90,7 +90,7 @@ class ContributionTool(BaseTool):
security.declareProtected(Permissions.AddPortalContent, 'newContent')
@fill_args_from_request('data', 'filename', 'portal_type', 'container_path',
'discover_metadata', 'temp_object', 'reference')
def newContent(self, REQUEST=None, **kw):
def newContent(self, REQUEST=None, **kw): # pylint:disable=arguments-differ
"""
The newContent method is overriden to implement smart content
creation by detecting the portal type based on whatever information
......@@ -283,7 +283,6 @@ class ContributionTool(BaseTool):
Create a new content based on XML data. This is intended for contributing
to ERP5 from another application.
"""
pass
security.declareProtected(Permissions.ModifyPortalContent,
'getMatchedFilenamePatternDict')
......
......@@ -28,12 +28,12 @@
##############################################################################
import six
# pylint:disable=no-name-in-module,import-error
# pylint:disable=no-name-in-module,import-error,deprecated-class
if six.PY3:
from collections.abc import Set
else:
from collections import Set
# pylint:enable=no-name-in-module,import-error
# pylint:enable=no-name-in-module,import-error,deprecated-class
import difflib
import warnings
......
......@@ -349,7 +349,7 @@ class IntrospectionTool(LogMixin, BaseTool):
def cached_getSystemVersionDict():
import pkg_resources
version_dict = {}
for dist in pkg_resources.working_set:
for dist in pkg_resources.working_set: # pylint:disable=not-an-iterable
version_dict[dist.key] = dist.version
from Products import ERP5 as erp5_product
......
......@@ -2528,7 +2528,7 @@ class SimulationTool(BaseTool):
simulation_movement.expand(expand_policy='immediate')
# activate builder
movement_portal_type, = movement_portal_type_set
movement_portal_type, = movement_portal_type_set # pylint:disable=unbalanced-tuple-unpacking
merged_builder = self._findBuilderForDelivery(main_delivery, movement_portal_type)
if merged_builder is None:
error_list.append(translateString("Unable to find builder"))
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment