Commit b9f738c3 authored by Jérome Perrin's avatar Jérome Perrin Committed by Arnaud Fontaine

WIP: Fix pylint py3 warnings.

Also, remove `if True/1/False/0` statement raising pylint warnings.
Co-authored-by: Arnaud Fontaine's avatarArnaud Fontaine <arnaud.fontaine@nexedi.com>
parent d81c04b1
......@@ -28,14 +28,14 @@ for line in transaction_lines:
line.getDestinationSectionValue(portal_type=section_portal_type_list),
line.getSourcePaymentValue(portal_type=bank_account_portal_type),
lambda: (x[1] for x in getBankAccountItemList(
organisation=line.getSourceSection(portal_type=section_portal_type_list))),
organisation=line.getSourceSection(portal_type=section_portal_type_list))), # pylint:disable=cell-var-from-loop
),
(
line.getDestinationValue(portal_type='Account'),
line.getSourceSectionValue(portal_type=section_portal_type_list),
line.getDestinationPaymentValue(portal_type=bank_account_portal_type),
lambda: (x[1] for x in getBankAccountItemList(
organisation=line.getDestinationSection(portal_type=section_portal_type_list))),
organisation=line.getDestinationSection(portal_type=section_portal_type_list))), # pylint:disable=cell-var-from-loop
),
):
if account is not None and account.getValidationState() != 'validated':
......
......@@ -21,17 +21,14 @@ if accounting_module.getProperty('current_content_script',
'') == current_script_data_id:
return "Accounting Transactions Created."
# first, cleanup accounting module
# XXX should be done in an external script / tool, because we have to
# workaround some security checks
if 1:
for module_id in ['accounting_module',
'sale_packing_list_module',
'portal_simulation', ]:
module = portal[module_id]
if len(module) > 200:
raise ValueError("Do not run this on production !!!")
module.manage_delObjects(list(module.objectIds()))
# first, cleanup modules
for module_id in ['accounting_module',
'sale_packing_list_module',
'portal_simulation', ]:
module = portal[module_id]
if len(module) > 200:
raise ValueError("Do not run this on production !!!")
module.manage_delObjects(list(module.objectIds()))
# if `set_ledger`is true, allow all test ledgers in accounting types.
for accounting_type_id in portal.getPortalAccountingTransactionTypeList():
......
......@@ -16,10 +16,7 @@ if accounting_module.getProperty('current_content_script',
return "Accounting Transactions Created."
# first, cleanup accounting module
# XXX should be done in an external script / tool, because we have to
# workaround some security checks
if 1:
accounting_module.manage_delObjects(list(accounting_module.objectIds()))
accounting_module.manage_delObjects(list(accounting_module.objectIds()))
# XXX copy & paste
def getAccountByTitle(title):
......
......@@ -15,15 +15,12 @@ if accounting_module.getProperty('current_content_script',
return "Accounting Transactions Created."
# first, cleanup accounting module
# XXX should be done in an external script / tool, because we have to
# workaround some security checks
if 1:
for module_id in ['accounting_module',
'sale_packing_list_module',
'portal_simulation', ]:
module = portal[module_id]
module.manage_delObjects(list(module.objectIds()))
# first, cleanup modules
for module_id in ['accounting_module',
'sale_packing_list_module',
'portal_simulation', ]:
module = portal[module_id]
module.manage_delObjects(list(module.objectIds()))
# XXX copy & paste
def getAccountByTitle(title):
......
......@@ -47,4 +47,4 @@ else:
response.setHeader('content-type', content_type)
response.setHeader('content-disposition', 'attachment; filename="' + filename + '"')
response.write(data)
raise Exception('profiling')
raise RuntimeError('profiling')
\ No newline at end of file
......@@ -66,7 +66,7 @@ def unicodeDict(d):
return d
for k, v in six.iteritems(d):
if isinstance(v, str):
d.update({k:unicode(v, 'utf8')})
d.update({k: unicode(v, 'utf8')}) # pylint:disable=undefined-variable
return d
data_dict = {
......
......@@ -181,7 +181,6 @@ class Coordinate(Base):
"""
Returns the standard text formats for telephone numbers
"""
pass
security.declareProtected(Permissions.AccessContentsInformation, 'isDetailed')
def isDetailed(self):
......
......@@ -99,7 +99,6 @@ class SimulatedDeliveryBuilder(BuilderMixin):
Redefine this method, because it seems nothing interesting can be
done before building Delivery.
"""
pass
security.declarePrivate('searchMovementList')
@UnrestrictedMethod
......@@ -341,7 +340,7 @@ class SimulatedDeliveryBuilder(BuilderMixin):
'solveDivergence')
solveDivergence = UnrestrictedMethod(_solveDivergence)
def _createDelivery(self, delivery_module, movement_list, activate_kw): # pylint: disable=super-on-old-class
def _createDelivery(self, delivery_module, movement_list, activate_kw):
"""
Refer to the docstring in GeneratedDeliveryBuilder.
Unlike GeneratedDeliveryBuilder, SimulatedDeliveryBuilder needs to respect
......
......@@ -115,7 +115,7 @@ def unicodeDict(d):
return d
for k, v in six.iteritems(d):
if isinstance(v, str):
d.update({k:unicode(v, 'utf8')})
d.update({k: unicode(v, 'utf8')}) # pylint:disable=undefined-variable
return d
......
......@@ -1190,23 +1190,6 @@ class TestBudget(ERP5TypeTestCase):
self.assertEqual(default_cell_range,
budget_line.BudgetLine_asCellRange('available'))
if 0 :self.assertEqual(
dict(from_date=DateTime(2000, 1, 1),
at_date=DateTime(2000, 12, 31).latestTime(),
#node_category_strict_membership=['account_type/expense',
# 'account_type/asset'],
node_category_strict_membership='account_type',
section_category_strict_membership=['group/demo_group/sub1'],
group_by_node_category_strict_membership=True,
group_by_node=True,
node_uid=[self.portal.account_module.goods_purchase.getUid(),
self.portal.account_module.fixed_assets.getUid()],
group_by_section_category_strict_membership=True,
),
budget_model.getInventoryListQueryDict(budget_line))
atransaction = self.portal.accounting_module.newContent(
portal_type='Accounting Transaction',
resource_value=self.portal.currency_module.euro,
......
......@@ -60,11 +60,9 @@ def binary_search(binary):
class CertificateAuthorityBusy(Exception):
"""Exception raised when certificate authority is busy"""
pass
class CertificateAuthorityDamaged(Exception):
"""Exception raised when certificate authority is damaged"""
pass
class CertificateAuthorityTool(BaseTool):
"""CertificateAuthorityTool
......
......@@ -150,7 +150,6 @@ class StateError(Exception):
"""
Must call only an available transition
"""
pass
def executeTransition(state, transition, document, form_kw=None):
"""
Execute transition on the object.
......
......@@ -113,7 +113,7 @@ class TestAlarm(AlarmTestCase):
finally:
self.portal.portal_activities.manageClearActivities(keep=0)
else:
raise Exception('Tic did not raise though activity was supposed to fail')
self.fail('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()
......
......@@ -51,7 +51,9 @@ from zLOG import LOG
from six.moves import range
if six.PY3:
long = int # pylint:disable=redefined-builtin
long_type = int # pylint:disable=redefined-builtin
else:
long_type = long # pylint:disable=undefined-variable
def format_stack(thread=None):
frame_dict = sys._current_frames()
......@@ -105,8 +107,8 @@ class TransactionThread(threading.Thread):
# Login
newSecurityManager(None, portal_value.acl_users.getUser('ERP5TypeTestCase'))
self.payload(portal_value=portal_value)
except Exception as e: # pylint: disable=redefine-in-handler
self.exception = e # pylint: disable=redefine-in-handler
except Exception as e:
self.exception = e
if six.PY2:
self.exception.__traceback__ = sys.exc_info()[2]
......@@ -595,7 +597,7 @@ class TestERP5Catalog(ERP5TypeTestCase, LogInterceptor):
uid_dict = {}
for _ in range(UID_BUFFER_SIZE * 3):
uid = portal_catalog.newUid()
self.assertIsInstance(uid, long)
self.assertIsInstance(uid, long_type)
self.assertNotIn(uid, uid_dict)
uid_dict[uid] = None
......@@ -1671,7 +1673,7 @@ class TestERP5Catalog(ERP5TypeTestCase, LogInterceptor):
organisation = module.newContent(portal_type='Organisation',)
# Ensure that the new uid is long.
uid = organisation.uid
self.assertTrue(isinstance(uid, long))
self.assertTrue(isinstance(uid, long_type))
self.tic()
# Ensure that the uid did not change after the indexing.
......@@ -1683,7 +1685,7 @@ class TestERP5Catalog(ERP5TypeTestCase, LogInterceptor):
# After the indexing, the uid must be converted to long automatically,
# and the value must be equivalent.
self.assertTrue(isinstance(uid, long))
self.assertTrue(isinstance(uid, long_type))
self.assertEqual(organisation.uid, uid)
def test_55_FloatFormat(self):
......@@ -2175,7 +2177,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: %(allowedRolesAndUsers)r' % line)
raise ValueError('Malformed allowedRolesAndUsers value: %(allowedRolesAndUsers)r' % line)
# Check that object that 'bar' can view because of 'Author' role can *not*
# be found when searching for his other 'Whatever' role.
......
......@@ -41,58 +41,58 @@ from Products.ERP5Type.tests.utils import DummyTranslationService
from zExceptions import Unauthorized
if 1: # BBB
# Zope 2.12, simulate setting the globalTranslationService with
# zope.i18n utilities
import zope.interface
import zope.component
import Acquisition
global_translation_service = None
from zope.i18n.interfaces import ITranslationDomain, \
IFallbackTranslationDomainFactory
@zope.interface.implementer(ITranslationDomain)
@zope.interface.provider(IFallbackTranslationDomainFactory)
class DummyTranslationDomainFallback(object):
def __init__(self, domain):
self.domain = domain
def translate(self, msgid, mapping=None, *args, **kw):
return global_translation_service.translate(self.domain, msgid, mapping,
*args, **kw)
def setGlobalTranslationService(translation_service):
global global_translation_service # pylint:disable=global-statement
global_translation_service = translation_service
zope.component.provideUtility(DummyTranslationDomainFallback,
provides=IFallbackTranslationDomainFactory)
# disable translation for the 'ui' domain so it can use the fallback above.
# Save it on a portal attribute since we don't have access to the test
# class
sm = zope.component.getSiteManager()
portal = Acquisition.aq_parent(sm)
from zope.interface.interfaces import ComponentLookupError
try:
ui_domain = sm.getUtility(ITranslationDomain, name='ui')
except ComponentLookupError:
pass
else:
# store in a list to avoid acquisition wrapping
portal._save_ui_domain = [ui_domain]
sm.unregisterUtility(provided=ITranslationDomain, name='ui')
def unregister_translation_domain_fallback():
from zope.component.globalregistry import base
base.unregisterUtility(DummyTranslationDomainFallback)
sm = zope.component.getSiteManager()
portal = Acquisition.aq_parent(sm)
ui_domain = getattr(portal, '_save_ui_domain', [None]).pop()
if ui_domain is not None:
# aq_base() to remove acquisition wrapping
ui_domain = Acquisition.aq_base(ui_domain)
sm.registerUtility(ui_domain, ITranslationDomain, 'ui')
del portal._save_ui_domain
# Zope 2.12, simulate setting the globalTranslationService with
# zope.i18n utilities
import zope.interface
import zope.component
import Acquisition
global_translation_service = None
from zope.i18n.interfaces import ITranslationDomain, \
IFallbackTranslationDomainFactory
@zope.interface.implementer(ITranslationDomain)
@zope.interface.provider(IFallbackTranslationDomainFactory)
class DummyTranslationDomainFallback(object):
def __init__(self, domain):
self.domain = domain
def translate(self, msgid, mapping=None, *args, **kw):
return global_translation_service.translate(self.domain, msgid, mapping,
*args, **kw)
def setGlobalTranslationService(translation_service):
global global_translation_service # pylint:disable=global-statement
global_translation_service = translation_service
zope.component.provideUtility(DummyTranslationDomainFallback,
provides=IFallbackTranslationDomainFactory)
# disable translation for the 'ui' domain so it can use the fallback above.
# Save it on a portal attribute since we don't have access to the test
# class
sm = zope.component.getSiteManager()
portal = Acquisition.aq_parent(sm)
from zope.interface.interfaces import ComponentLookupError
try:
ui_domain = sm.getUtility(ITranslationDomain, name='ui')
except ComponentLookupError:
pass
else:
# store in a list to avoid acquisition wrapping
portal._save_ui_domain = [ui_domain]
sm.unregisterUtility(provided=ITranslationDomain, name='ui')
def unregister_translation_domain_fallback():
from zope.component.globalregistry import base
base.unregisterUtility(DummyTranslationDomainFallback)
sm = zope.component.getSiteManager()
portal = Acquisition.aq_parent(sm)
ui_domain = getattr(portal, '_save_ui_domain', [None]).pop()
if ui_domain is not None:
# aq_base() to remove acquisition wrapping
ui_domain = Acquisition.aq_base(ui_domain)
sm.registerUtility(ui_domain, ITranslationDomain, 'ui')
del portal._save_ui_domain
HTTP_OK = 200
HTTP_UNAUTHORIZED = 401
......@@ -587,26 +587,27 @@ class TestERP5Core(ERP5TypeTestCase, ZopeTestCase.Functional):
# now let's simulate a site just migrated from Zope 2.8 that's being
# accessed for the first time:
from Products.ERP5 import ERP5Site
if 1: # BBB
setSite()
# Sites from Zope2.8 don't have a site_manager yet.
del self.portal._components
self.assertIsNotNone(ERP5Site._missing_tools_registered)
ERP5Site._missing_tools_registered = None
self.commit()
# check that we can't get any translation utility
self.assertEqual(queryUtility(ITranslationDomain, 'erp5_ui'), None)
# Now simulate first access. Default behaviour from
# ObjectManager is to raise a ComponentLookupError here:
setSite(self.portal)
self.commit()
self.assertIsNotNone(ERP5Site._missing_tools_registered)
# This should have automatically reconstructed the i18n utility
# registrations:
self.assertEqual(queryUtility(ITranslationDomain, 'erp5_ui'),
erp5_ui_catalog)
self.assertEqual(queryUtility(ITranslationDomain, 'ui'), erp5_ui_catalog)
# BBB
setSite()
# Sites from Zope2.8 don't have a site_manager yet.
del self.portal._components
self.assertIsNotNone(ERP5Site._missing_tools_registered)
ERP5Site._missing_tools_registered = None
self.commit()
# check that we can't get any translation utility
self.assertEqual(queryUtility(ITranslationDomain, 'erp5_ui'), None)
# Now simulate first access. Default behaviour from
# ObjectManager is to raise a ComponentLookupError here:
setSite(self.portal)
self.commit()
self.assertIsNotNone(ERP5Site._missing_tools_registered)
# This should have automatically reconstructed the i18n utility
# registrations:
self.assertEqual(queryUtility(ITranslationDomain, 'erp5_ui'),
erp5_ui_catalog)
self.assertEqual(queryUtility(ITranslationDomain, 'ui'), erp5_ui_catalog)
def test_BasicAuthenticateDesactivated(self):
"""Make sure Unauthorized error does not lead to Basic auth popup in browser"""
......
......@@ -67,7 +67,7 @@ def old(items):
if len(whl._log) < 16:
whl._log.append(item)
else:
prev = whl.__new__(whl.__class__)
prev = whl.__new__(whl.__class__) # pylint:disable=no-value-for-parameter
prev._prev = whl._prev
prev._log = whl._log
whl._prev = prev
......@@ -91,7 +91,8 @@ class TestWorkflowHistoryList(TestCase):
self.assertEqual(ddl, new(type(ddl), EXPECTED))
class check(object):
def __getitem__(_, item): # pylint: disable=no-self-argument
def __getitem__(self_, item): # pylint: disable=no-self-argument
del self_
try:
a = EXPECTED[item]
except IndexError:
......
......@@ -78,7 +78,7 @@ class TestXMLPickle(unittest.TestCase):
reconstructed_obj = pickle.loads(reconstructed_pickled_data)
self.assertTrue(reconstructed_obj.__class__ is DummyClass)
self.assertTrue(type(getattr(reconstructed_obj, 'data', None)) is list) # pylint:disable=unidiomatic-typecheck
self.assertIs(type(getattr(reconstructed_obj, 'data', None)), list)
self.assertEqual(reconstructed_obj.data[0], 1)
self.assertTrue(reconstructed_obj.data[1] is reconstructed_obj)
self.assertTrue(reconstructed_obj.data[2] is reconstructed_obj.data)
......
......@@ -4,6 +4,6 @@ i=u.find('://')
if i>-1:
prot=u[:i]
if prot not in o.getProtocolList():
raise Exception("Protocol "+prot+" not supported")
raise ValueError("Protocol "+prot+" not supported")
o.setUrlString(u[i+3:])
o.setUrlProtocol(prot)
......@@ -41,7 +41,7 @@ GIT_ASKPASS = os.path.join(Products.ERP5.product_path, 'bin', 'git_askpass')
class GitInstallationError(EnvironmentError):
"""Raised when an installation is broken"""
pass
class GitError(EnvironmentError):
def __init__(self, err, out, returncode):
......@@ -239,7 +239,7 @@ class Git(WorkingCopy):
node_dict[parent] = [path]
path_dict[parent] = status
if parent:
path_list.append(parent)
path_list.append(parent) # pylint:disable=modified-iterating-list
else:
while path_dict.get(parent, status) != status:
path_dict[parent] = status = '*'
......@@ -264,7 +264,7 @@ class Git(WorkingCopy):
else:
child = Dir(basename, dir_status(status))
node.sub_dirs.append(child)
path_list.append((content, child))
path_list.append((content, child)) # pylint:disable=modified-iterating-list
return (root.sub_dirs or root.sub_files) and root
def update(self, keep=False):
......@@ -274,7 +274,7 @@ class Git(WorkingCopy):
if not keep:
self.clean()
self.remote_git('pull', '--ff-only')
elif 1: # elif local_changes:
elif 1: # elif local_changes: # pylint:disable=using-constant-test
raise NotImplementedError
# addremove
# write-tree | commit-tree -> A
......@@ -365,13 +365,13 @@ class Git(WorkingCopy):
# TODO: solve conflicts on */bt/revision automatically
try:
self.git(merge, '@{u}', env=env)
except GitError as e:
except GitError as e2:
# XXX: how to know how it failed ?
try:
self.git(merge, '--abort')
except GitError:
pass
raise e
raise e2
# no need to keep a merge commit if push fails again
if merge == 'merge':
reset += 1
......
......@@ -63,17 +63,14 @@ class getTransactionalDirectory(str):
class SubversionError(Exception):
"""The base exception class for the Subversion interface.
"""
pass
class SubversionInstallationError(SubversionError):
"""Raised when an installation is broken.
"""
pass
class SubversionTimeoutError(SubversionError):
"""Raised when a Subversion transaction is too long.
"""
pass
class SubversionLoginError(SubversionError):
"""Raised when an authentication is required.
......
......@@ -217,7 +217,7 @@ class WorkingCopy(Implicit):
hasDiff = lambda path: bool(getFilteredDiff(diff(path)))
else:
hasDiff = lambda path: True
self.__hasDiff = hasDiff
self.__hasDiff = hasDiff # pylint:disable=unused-private-member
return hasDiff(path)
def treeToXML(self, item) :
......
......@@ -154,7 +154,7 @@ class TestTemplateTool(ERP5TypeTestCase):
"""
self._svn_setup_ssl()
# we make this class a global so that it can be pickled
global PropertiesTool # pylint:disable=global-variable-not-assigned
global PropertiesTool # pylint:disable=global-variable-not-assigned,global-variable-undefined
class PropertiesTool(ActionsTool): # pylint:disable=redefined-outer-name
id = 'portal_properties'
cls = PropertiesTool
......
......@@ -216,7 +216,7 @@ if dialog_method != update_method and kw.get('deferred_style', 0):
# At this point the 'dialog_method' should point to a form (if we are in report)
# if we are not in Deferred mode - then it points to `Base_activateSimpleView`
if True:
if True: # pylint:disable=using-constant-test
if dialog_method != update_method:
# When we are not executing the update action, we have to change the skin
# manually,
......
......@@ -782,8 +782,9 @@ def renderField(traversed_document, field, form, value=MARKER, meta_type=None,
if list_method is not None:
selectKwargsForCallable(list_method, list_method_query_dict, REQUEST)
if (True): # editable_column_list (we need that template fields resolution
# (issued by existence of `form_relative_url`) always kicks in
if True: # pylint:disable=using-constant-test
# editable_column_list (we need that template fields resolution
# (issued by existence of `form_relative_url`) always kicks in
extra_param_dict = {
# in case of a dialog the form_id points to previous form, otherwise current form
"form_id": REQUEST.get('form_id', form.id)
......
"""
This script is called after successful data ingestion.
XXX: It's possible to hook here some asynchrounous
XXX: It's possible to hook here some asynchronous
notification for user that the ingestion was successful.
"""
pass
......@@ -121,7 +121,7 @@ def submitRequestWithFailure(**kw):
class ServiceWithException:
def submit(self, **kw):
raise Exception('exception')
raise RuntimeError('exception')
class ClientWithException:
def __init__(self):
......
......@@ -163,7 +163,7 @@ class TransformationRuleMovementGenerator(MovementGeneratorMixin):
# movement with an industrial_phase (other properties like reference
# starting with "pr/" is possible). The drawback with such filter is that
# Same Total Quantity check must be disabled.
if 1:
if 1: # pylint:disable=using-constant-test
cr_quantity = - parent_movement.getQuantity()
def newIntermediateMovement(reference_prefix, industrial_phase, **kw):
movement = newMovement(reference_prefix + phase, kw)
......
......@@ -2,7 +2,7 @@ simulation_method = getattr(delivery, 'getSimulationState', None)
if simulation_method is None:
return '#D1E8FF'
simulation_state = simulation_method()
simulation_state = simulation_method() # pylint:disable=not-callable
color_dict = {
'draft': '#a7d7ae',
......
......@@ -544,7 +544,7 @@ class _ERP5RequestValidator(RequestValidator):
return token_callable(**kw)
except jwt.InvalidTokenError:
pass
raise
raise # pylint:disable=misplaced-bare-raise
def client_authentication_required(self, request, *args, **kwargs):
# Use this method, which is called early on most endpoints, to setup request.client .
......@@ -1278,7 +1278,7 @@ class OAuth2AuthorisationServerConnector(XMLObject):
token_dict[JWT_PAYLOAD_KEY].encode('ascii'),
)
return token_dict
raise
raise # pylint:disable=misplaced-bare-raise
def _getRefreshTokenDict(self, value, request):
for _, algorithm, symetric_key in self.__getRefreshTokenKeyList():
......@@ -1300,7 +1300,7 @@ class OAuth2AuthorisationServerConnector(XMLObject):
continue
else:
return token_dict
raise
raise # pylint:disable=misplaced-bare-raise
def _checkCustomTokenPolicy(self, token, request):
"""
......@@ -1360,7 +1360,7 @@ class OAuth2AuthorisationServerConnector(XMLObject):
continue
else:
return token_dict['iss']
raise
raise # pylint:disable=misplaced-bare-raise
security.declarePrivate('getRefreshTokenClientId')
def getRefreshTokenClientId(self, value, request):
......@@ -1386,7 +1386,7 @@ class OAuth2AuthorisationServerConnector(XMLObject):
continue
else:
return token_dict['iss']
raise
raise # pylint:disable=misplaced-bare-raise
def _getSessionValueFromTokenDict(self, token_dict):
session_value = self._getSessionValue(
......
......@@ -84,6 +84,7 @@ class FormExtractor(HTMLParser):
self.__in_form = False
class TestOAuth2(ERP5TypeTestCase):
# pylint:disable=unused-private-member
__cleanup_list = None
__port = None
__query_trace = None
......
......@@ -97,7 +97,9 @@ def getReportSectionDictList(line_dict_list):
line_to_group_list = []
# add one line for gross salary
if previous_line_dict is not None and gross_category in previous_line_dict['base_contribution_list'] and gross_category not in current_line_dict['base_contribution_list']:
if (previous_line_dict is not None
and gross_category in previous_line_dict['base_contribution_list'] # pylint:disable=unsubscriptable-object
and gross_category not in current_line_dict['base_contribution_list']):
new_line_dict_list.append(
getFakeLineDictForNewSection(
context.Base_translateString("Gross Salary"),
......
......@@ -47,8 +47,6 @@ class TestHTMLPostLogic(ERP5TypeTestCase):
# here, you can create the categories and objects your test will depend on
"""
pass
def test_01_sampleTest(self):
"""
......
......@@ -6,7 +6,7 @@ simulation_method = getattr(task, 'getSimulationState', None)
if simulation_method is None:
return '#D1E8FF'
simulation_state = simulation_method()
simulation_state = simulation_method() # pylint:disable=not-callable
color_dict = {
'draft': '#a7d7ae',
......
......@@ -275,8 +275,6 @@ class ZoomifyBase:
def ZoomifyProcess(self, imageNames):
""" the method the client calls to generate zoomify metadata """
pass
return
def preProcess(self):
......
......@@ -105,7 +105,7 @@ class MovementSplitSolver(SolverMixin, ConfigurableMixin, XMLObject):
parent = obj.getParentValue()
parent.deleteContent(obj.getId())
if len(parent) == 0 and parent != parent.getRootDeliveryValue():
_delete(parent)
_delete(parent) # pylint:disable=cell-var-from-loop
for movement in delivery.getMovementList():
simulation_movement_list = movement.getDeliveryRelatedValueList()
......
......@@ -231,7 +231,7 @@ class SolverProcess(XMLObject, ActiveProcess):
movement_list = []
isMovement = IMovement.providedBy
for x in delivery_or_movement:
if isMovement(x):
if isMovement(x): # pylint:disable=no-value-for-parameter
movement_list.append(x)
else:
movement_list.extend(x.getMovementList())
......
......@@ -92,5 +92,4 @@ class BaseConduit(object):
Method called when update command is received
XXX It should returns the list of conflicts ?
"""
pass
......@@ -490,9 +490,8 @@ class ERP5Conduit(XMLSyncUtilsMixin):
first_object = False
elif sub_context is not None:
context = sub_context
else:
# else:
# Ignore non existing objects
pass
#LOG('ERP5Conduit', INFO, 'sub document of %s not found with id:%r'%\
#(context.getPath(), sub_context_id))
xpath = xpath.replace(object_block, '', 1)
......@@ -695,7 +694,6 @@ class ERP5Conduit(XMLSyncUtilsMixin):
def afterNewObject(self, object): # pylint: disable=redefined-builtin
"""Overloadable method
"""
pass
security.declareProtected(Permissions.AccessContentsInformation,
'getStatusFromXml')
......
......@@ -145,7 +145,7 @@ class SyncMLAsynchronousEngine(SyncMLEngineMixin):
"""
Process the package 4 of the SyncML DS exchange
"""
if False:
if False: # pylint:disable=using-constant-test
pass
# not subscriber.checkCorrectRemoteMessageId(
# syncml_request.header['message_id']):
......
......@@ -31,7 +31,7 @@ from requests import post
syncml_logger = getLogger('ERP5SyncML')
class ConnectionError(Exception):
class ConnectionError(Exception): # pylint:disable=redefined-builtin
pass
......
......@@ -141,7 +141,7 @@ class VCardConduit(ERP5Conduit):
property_value_list_well_incoded=[]
if encoding == 'QUOTED-PRINTABLE':
import mimify
import mimify # pylint:disable=import-error
for property_value in property_value_list:
property_value = mimify.mime_decode(property_value)
property_value_list_well_incoded.append(property_value)
......
......@@ -42,7 +42,6 @@ class CloudPerformanceUnitTestDistributor(ERP5ProjectUnitTestDistributor):
all test nodes runs all test suites, this is not a problem to keep
configuration
"""
pass
security.declarePublic("optimizeConfiguration")
def optimizeConfiguration(self):
......
......@@ -147,6 +147,7 @@ class TaskDistributionTestCase(ERP5TypeTestCase):
"""start_count: number of test line to start
stop_count: number of test line to stop
"""
# pylint:disable=possibly-used-before-assignment
status_dict = {}
test_result_path, revision = self._createTestResult(revision=revision,
test_list=['testFoo', 'testBar'], test_title=test_title, node_title=node_title)
......@@ -168,6 +169,7 @@ class TaskDistributionTestCase(ERP5TypeTestCase):
self.assertEqual(test_result.getSimulationState(), "stopped")
else:
self.assertEqual(test_result.getSimulationState(), "started")
# pylint:enable=possibly-used-before-assignment
def _cleanupTestResult(self):
self.tic()
......
......@@ -429,7 +429,7 @@ class TestInventory(TestOrderMixin, ERP5TypeTestCase):
sequence.edit(variation_2=cell_key)
quantity = 3
cell.edit(
quantity = quantity,
quantity = quantity, # pylint:disable=used-before-assignment
predicate_category_list = cell_key,
variation_category_list = cell_key,
mapped_value_property_list = ['quantity'],
......
......@@ -842,7 +842,7 @@ class TestResource(ERP5TypeTestCase):
destination_section_value=node)
supply.validate()
if 0:
if 0: # pylint:disable=using-constant-test
# XXX if both a supply line for the resource and a supply cell for
# the resource with the exact variation can be applied, one of them
# is choosen randomly. It looks like a bug, but I'm not sure we
......
......@@ -40,7 +40,7 @@ class SFTPError(Exception):
"""
Default exception for the connection
"""
pass
class SFTPConnection:
"""
......
......@@ -88,13 +88,13 @@ class AuthenticationBase(object):
This hook is called upon connection. It can be used to exchange
credentials with remote server.
"""
pass
class NullAuthentication(AuthenticationBase):
"""
NO-OP authentication.
"""
pass
class HeaderAuthentication(AuthenticationBase):
"""
......
......@@ -52,10 +52,6 @@ class SQLConnection:
"""
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, *args, **kw):
""" Do nothing """
pass
def connect(self):
"""Get a handle to a remote connection."""
return self
......
......@@ -114,8 +114,8 @@ class WechatService(XMLObject):
if result_msg=="ok":
sandbox_signkey = result_dict_content['sandbox_signkey']
return sandbox_signkey
raise Exception(result_dict_content['result_msg'].encode('utf-8'))
raise Exception("Get sanbox key failed: " + str(result_dict_content))
raise WechatException(result_dict_content['result_msg'].encode('utf-8'))
raise WechatException("Get sanbox key failed: " + str(result_dict_content))
def callWechatApi(self, URL, wechat_dict):
portal = self.getPortalObject()
......@@ -160,7 +160,7 @@ class WechatService(XMLObject):
if return_code=="SUCCESS":
return result_dict_content
else:
raise Exception(u"ERROR could not communicate with Wechat (return_code {}: {})".format(return_code, result_dict_content.get("return_msg")))
raise WechatException(u"ERROR could not communicate with Wechat (return_code {}: {})".format(return_code, result_dict_content.get("return_msg")))
def getWechatPaymentURL(self, wechat_dict):
portal = self.getPortalObject()
......@@ -173,7 +173,7 @@ class WechatService(XMLObject):
if result_code=="SUCCESS":
return wechat_answer['code_url']
else:
raise Exception(u"ERROR Wechat notified a problem (result_code {}: {})".format(result_code, wechat_answer.get("err_code_des")))
raise WechatException(u"ERROR Wechat notified a problem (result_code {}: {})".format(result_code, wechat_answer.get("err_code_des")))
def queryWechatOrderStatus(self, wechat_dict):
'''
......@@ -247,7 +247,6 @@ class WechatService(XMLObject):
def initialize(self, REQUEST=None, **kw):
"""See Payment Service Interface Documentation"""
pass
def navigate(self, wechat_dict, REQUEST=None, **kw):
"""Returns a redirection to the payment page"""
......
......@@ -1099,7 +1099,7 @@ class TemplateTool (BaseTool):
- 1.1 < 2.0
- 1.0.0 = 1.0
"""
r = re.compile('(\d+|[a-zA-Z])')
r = re.compile(r'(\d+|[a-zA-Z])')
v1 = r.findall(version1)
v2 = r.findall(version2)
......
......@@ -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
......
......@@ -319,7 +319,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
......
......@@ -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')
......
......@@ -300,7 +300,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):
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):
"""
......
......@@ -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
......@@ -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 configure 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
......
......@@ -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
message = email.message_from_string(text)
......
......@@ -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
......
......@@ -78,7 +78,7 @@ try:
if checkFieldType(my_field, 'MultiRelationStringField'):
# The checkProperty sometimes does not provide an
# acceptable value - XXXX - see vetement_id in Modele View
if old_value is '' or old_value is None:
if old_value == '' or old_value is None:
old_value = []
try:
old_value = list(old_value)
......
......@@ -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)})
......@@ -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
......
......@@ -89,7 +89,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
......@@ -282,7 +282,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=import-error,no-name-in-module
# pylint:disable=import-error,no-name-in-module,deprecated-class
if six.PY3:
from collections.abc import Set
else:
from collections import Set
# pylint:enable=import-error,no-name-in-module
# pylint:enable=import-error,no-name-in-module,deprecated-class
import difflib
import warnings
try:
......
......@@ -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
......
......@@ -1625,7 +1625,7 @@ class SimulationTool(BaseTool):
try:
result = cmp(line_a[key], line_b[key])
except KeyError:
raise Exception('Impossible to sort result since columns sort '
raise ValueError('Impossible to sort result since columns sort '
'happens on are not available in result: %r' % (key, ))
if result:
if not sort_direction.upper().startswith('A'):
......@@ -2523,7 +2523,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"))
......
......@@ -213,12 +213,12 @@ class Selection(Acquisition.Implicit, Traversable, Persistent):
kw.setdefault("ignore_unknown_columns", True)
# Always remove '-C'-named parameter.
kw.pop('-C', None)
if self.invert_mode is not 0:
if self.invert_mode:
kw['uid'] = self.uids
if method is None or isinstance(method, str):
method_path = method or self.method_path
method = context.unrestrictedTraverse(method_path)
if type(method) is type('a'):
if isinstance(method, str):
method = context.unrestrictedTraverse(self.method_path)
sort_on = getattr(self, 'sort_on', [])
if len(sort_on) == 0:
......@@ -338,7 +338,7 @@ class Selection(Acquisition.Implicit, Traversable, Persistent):
def getZoom(self):
try:
current_zoom=self.params['zoom']
if current_zoom != None:
if current_zoom is not None:
return current_zoom
else:
return 1
......
......@@ -617,8 +617,8 @@ class ODFStrategy(Implicit):
if svg_width is None or svg_height is None:
return ('0cm', '0cm')
# if not match causes exception
width_tuple = re.match("(\d[\d\.]*)(.*)", svg_width).groups()
height_tuple = re.match("(\d[\d\.]*)(.*)", svg_height).groups()
width_tuple = re.match(r"(\d[\d\.]*)(.*)", svg_width).groups()
height_tuple = re.match(r"(\d[\d\.]*)(.*)", svg_height).groups()
unit = width_tuple[1]
w = Decimal(width_tuple[0])
h = Decimal(height_tuple[0])
......
......@@ -278,7 +278,7 @@ class OOoTemplate(ZopePageTemplate):
def renderIncludes(self, here, text, extra_context, request, sub_document=None):
attached_files_dict = {}
arguments_re = re.compile('''(\S+?)\s*=\s*('|")(.*?)\\2\s*''',re.DOTALL)
arguments_re = re.compile(r'''(\S+?)\s*=\s*('|")(.*?)\2\s*''',re.DOTALL)
def getLengthInfos( opts_dict, opts_names ):
ret = []
for opt_name in opts_names:
......@@ -439,7 +439,7 @@ class OOoTemplate(ZopePageTemplate):
office_include.getparent().replace(office_include, draw_object)
text = bytes2str(etree.tostring(xml_doc, encoding='utf-8', xml_declaration=True,
pretty_print=False))
text = re.sub('<\s*office:include_img\s+(.*?)\s*/\s*>(?s)', replaceIncludesImg, text)
text = re.sub(r'<\s*office:include_img\s+(.*?)\s*/\s*>(?s)', replaceIncludesImg, text)
return (text, attached_files_dict)
# Proxy method to PageTemplate
......
......@@ -128,7 +128,7 @@ class PersistentContainer(Persistent):
self.value = state
global registered_workflow_method_set
wildcard_interaction_method_id_match = re.compile(r'[[.?*+{(\\]').search
wildcard_interaction_method_id_match = re.compile(r'[\[.?*+{(\\]').search
workflow_method_registry = [] # XXX A set() would be better but would require a hash in WorkflowMethod class
def resetRegisteredWorkflowMethod(portal_type=None):
......
......@@ -76,7 +76,7 @@ class ContentExistenceConstraint(ConstraintMixin):
# Otherwise, generate an error message
mapping = {}
if portal_type is ():
if not portal_type:
message_id = 'message_no_subobject'
else:
message_id = 'message_no_subobject_portal_type'
......
......@@ -730,7 +730,7 @@ from .Accessor.Base import func_code
from Products.CMFCore.utils import manage_addContentForm, manage_addContent
from AccessControl.PermissionRole import PermissionRole
python_file_parser = re.compile('^(.*)\.py$')
python_file_parser = re.compile(r'^(.*)\.py$')
def getLocalPropertySheetList():
if not getConfiguration:
......@@ -1711,12 +1711,12 @@ from six.moves.urllib.parse import urlsplit, urlunsplit, urljoin
# Regular expressions
re_cleanup_anchors = re.compile('#.*')
re_extract_port = re.compile(':(\d+)$')
re_extract_port = re.compile(r':(\d+)$')
def uppercaseLetter(matchobject):
return matchobject.group(0).upper()
re_cleanup_escaped_url = re.compile('%\w\d')
re_cleanup_escaped_url = re.compile(r'%\w\d')
re_cleanup_slashes = re.compile('/{2,}')
re_cleanup_tail = re.compile('\??$')
re_cleanup_tail = re.compile(r'\??$')
def legacyNormalizeUrl(url, base_url=None):
"""this method does normalisation itself.
......
......@@ -3219,13 +3219,11 @@ class Test(ERP5TypeTestCase):
"""
Dummy mail host has already been set up when running tests
"""
pass
def _restoreMailHost(self):
"""
Dummy mail host has already been set up when running tests
"""
pass
def test_01_sampleTest(self):
self.assertEqual(0, 0)
......@@ -3321,7 +3319,7 @@ class Test(ERP5TypeTestCase):
reset_portal_type_at_transaction_boundary=True)
output = runLiveTest('testRunLiveTest')
expected_msg_re = re.compile('Ran 2 tests.*FAILED \(failures=1\)', re.DOTALL)
expected_msg_re = re.compile(r'Ran 2 tests.*FAILED \(failures=1\)', re.DOTALL)
self.assertRegex(output, expected_msg_re)
# Now try addCleanup
......
......@@ -184,7 +184,7 @@ class EmailValidator(StringValidator):
# brackets around the address (we assume these would be added by
# some custom script if needed), and of course no characters that
# don't belong in an e-mail address.
pattern = re.compile('^[0-9a-zA-Z_\'&.%+-]+@([0-9a-zA-Z]([0-9a-zA-Z-]*[0-9a-zA-Z])?\.)+[a-zA-Z]{2,}$')
pattern = re.compile(r'^[0-9a-zA-Z_\'&.%+-]+@([0-9a-zA-Z]([0-9a-zA-Z-]*[0-9a-zA-Z])?\.)+[a-zA-Z]{2,}$')
def validate(self, field, key, REQUEST):
value = StringValidator.validate(self, field, key, REQUEST)
......
......@@ -175,7 +175,7 @@ def hasScript(s):
def decode_htmlentities(s):
""" XSS code can be hidden with htmlentities """
entity_pattern = re.compile("&#(?P<htmlentity>x?\w+)?;?")
entity_pattern = re.compile(r"&#(?P<htmlentity>x?\w+)?;?")
s = entity_pattern.sub(decode_htmlentity,s)
return s
......@@ -190,7 +190,7 @@ def decode_htmlentity(m):
except ValueError:
return entity_value
charset_parser = re.compile('charset="?(?P<charset>[^"]*)"?[\S/]?',
charset_parser = re.compile(r'charset="?(?P<charset>[^"]*)"?[\S/]?',
re.IGNORECASE)
class CharsetReplacer:
def __init__(self, encoding):
......
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