Commit 61ed357f authored by Philippe Pepiot's avatar Philippe Pepiot
Browse files

Fix flake8 issues since release 3.6.0

Flake8 had a new release which raise new issues, namely:

W504: line break after binary operator
F841: local variable 'ex' is assigned to but never used
W605: invalid escape sequence
F821: undefined name 'buffer' (noqa seems the only way to avoid this false positive)

Also pin flake8>=3.6 in our tests and make explicit that we use python3 to run
flake8 tests.
parent e814f2e1059c
......@@ -80,7 +80,7 @@ def typed_eid(eid):
class Binary(BytesIO):
"""class to hold binary data. Use BytesIO to prevent use of unicode data"""
_allowed_types = (binary_type, bytearray, buffer if PY2 else memoryview)
_allowed_types = (binary_type, bytearray, buffer if PY2 else memoryview) # noqa: F405
def __init__(self, buf=b''):
assert isinstance(buf, self._allowed_types), \
......
......@@ -400,8 +400,8 @@ class ITreeAdapter(view.EntityAdapter):
path.append(entity.eid)
try:
# check we are not jumping to another tree
if (adapter.tree_relation != self.tree_relation or
adapter.child_role != self.child_role):
if (adapter.tree_relation != self.tree_relation
or adapter.child_role != self.child_role):
break
entity = adapter.parent()
adapter = entity.cw_adapt_to('ITree')
......
......@@ -3,6 +3,6 @@ from cubicweb.hooks import notification
class FolderUpdateHook(notification.EntityUpdateHook):
__select__ = (notification.EntityUpdateHook.__select__ &
is_instance('Folder'))
__select__ = (notification.EntityUpdateHook.__select__
& is_instance('Folder'))
order = 100 # late trigger so that metadata hooks come before.
......@@ -112,7 +112,7 @@ class CubicWebPyramidHandler(object):
# earlier in the controllers, not here. In the end, the
# ValidationError should never by handled here.
content = self.appli.validation_error_handler(req, ex)
except cubicweb.web.RemoteCallFailed as ex:
except cubicweb.web.RemoteCallFailed:
# XXX The default pyramid error handler (or one that we provide
# for this exception) should be enough
# content = self.appli.ajax_error_handler(req, ex)
......
......@@ -44,8 +44,8 @@ class CubicWebPyramidConfiguration(BaseWebConfiguration, ServerConfiguration):
cube_appobject_path = (BaseWebConfiguration.cube_appobject_path
| ServerConfiguration.cube_appobject_path)
options = merge_options(ServerConfiguration.options +
BaseWebConfiguration.options)
options = merge_options(ServerConfiguration.options
+ BaseWebConfiguration.options)
def init_log(self, *args, **kwargs):
"""Rely on logging configuration in Pyramid's .ini file, do nothing
......
......@@ -129,7 +129,7 @@ def cw_to_pyramid(request):
DeprecationWarning, stacklevel=2)
request.body = ex.content
request.status_int = ex.status
except cubicweb.web.Unauthorized as ex:
except cubicweb.web.Unauthorized:
raise httpexceptions.HTTPForbidden(
request.cw_request._(
'You\'re not authorized to access this page. '
......@@ -143,7 +143,7 @@ def cw_to_pyramid(request):
'If you think it should be allowed, please contact the site '
'administrator.'),
headers=cw_headers(request))
except (rql.BadRQLQuery, cubicweb.web.RequestError) as ex:
except (rql.BadRQLQuery, cubicweb.web.RequestError):
raise
......
......@@ -278,10 +278,10 @@ class RQLRewriter(object):
nbtrees = len(localchecks)
myunion = union = select.parent
# transform in subquery when len(localchecks)>1 and groups
if nbtrees > 1 and (select.orderby or select.groupby or
select.having or select.has_aggregat or
select.distinct or
select.limit or select.offset):
if nbtrees > 1 and (select.orderby or select.groupby
or select.having or select.has_aggregat
or select.distinct
or select.limit or select.offset):
newselect = stmts.Select()
# only select variables in subqueries
origselection = select.selection
......
......@@ -297,8 +297,8 @@ class RQLExpression(object):
prefix, action, suffix = rel.r_type.split('_')
except ValueError:
continue
if (prefix != 'has' or suffix != 'permission' or
action not in ('add', 'delete', 'update', 'read')):
if (prefix != 'has' or suffix != 'permission'
or action not in ('add', 'delete', 'update', 'read')):
continue
if found is None:
found = []
......@@ -696,8 +696,8 @@ def has_local_role(self, action):
@_override_method(PermissionMixIn)
def may_have_permission(self, action, req):
if action != 'read' and not (self.has_local_role('read') or
self.has_perm(req, 'read')):
if action != 'read' and not (self.has_local_role('read')
or self.has_perm(req, 'read')):
return False
return self.has_local_role(action) or self.has_perm(req, action)
......@@ -1188,8 +1188,8 @@ def name_for(self, rdef):
This name may be used as name for the constraint in the database.
"""
return 'cstr' + md5((rdef.subject.type + rdef.rtype.type + self.type() +
(self.serialize() or '')).encode('ascii')).hexdigest()
return 'cstr' + md5((rdef.subject.type + rdef.rtype.type + self.type()
+ (self.serialize() or '')).encode('ascii')).hexdigest()
class BaseRQLConstraint(RRQLExpression, BaseConstraint):
......@@ -1455,9 +1455,9 @@ def vocabulary(self, entity=None, form=None):
if cw is not None:
if hasattr(cw, 'write_security'): # test it's a session and not a request
# cw is a server session
hasperm = (not cw.write_security or
not cw.is_hook_category_activated('integrity') or
cw.user.matching_groups(MAY_USE_TEMPLATE_FORMAT))
hasperm = (not cw.write_security
or not cw.is_hook_category_activated('integrity')
or cw.user.matching_groups(MAY_USE_TEMPLATE_FORMAT))
else:
hasperm = cw.user.matching_groups(MAY_USE_TEMPLATE_FORMAT)
if hasperm:
......
......@@ -100,9 +100,9 @@ def _annotate_select(annotator, rqlst):
ostinfo = rhs.children[0].variable.stinfo
else:
ostinfo = lhs.variable.stinfo
if not (ostinfo.get('optcomparisons') or
any(orel for orel in ostinfo['relations']
if orel.optional and orel is not rel)):
if not (ostinfo.get('optcomparisons')
or any(orel for orel in ostinfo['relations']
if orel.optional and orel is not rel)):
break
if rschema.final or (onlhs and rschema.inlined):
if rschema.type != 'has_text':
......
......@@ -54,9 +54,8 @@ def build_index_name(table, columns, prefix='idx_'):
"""Return a predictable-but-size-constrained name for an index on `table(*columns)`, using an
md5 hash.
"""
return '%s%s' % (prefix, md5((table +
',' +
','.join(sorted(columns))).encode('ascii')).hexdigest())
return '%s%s' % (prefix, md5((
table + ',' + ','.join(sorted(columns))).encode('ascii')).hexdigest())
def rschema_has_table(rschema, skip_relations):
......
......@@ -693,7 +693,7 @@ class NativeSQLSource(SQLAdapterMixIn, AbstractSource):
cnx.cnxset.rollback()
if self.repo.config.mode != 'test':
self.debug('transaction has been rolled back')
except Exception as ex:
except Exception:
pass
if ex.__class__.__name__ == 'IntegrityError':
# need string comparison because of various backends
......
......@@ -59,7 +59,7 @@ class ChangeStateTextParser(TextParser):
:<transition name>: #?<eid>
"""
instr_rgx = re.compile(':(\w+):\s*#?(\d+)', re.U)
instr_rgx = re.compile(r':(\w+):\s*#?(\d+)', re.U)
def parse(self, caller, text):
for trname, eid in self.instr_rgx.findall(text):
......
......@@ -33,7 +33,7 @@ class BinaryTC(TestCase):
Binary(b'toto')
Binary(bytearray(b'toto'))
if PY2:
Binary(buffer('toto'))
Binary(buffer('toto')) # noqa: F821
else:
Binary(memoryview(b'toto'))
with self.assertRaises((AssertionError, TypeError)):
......@@ -45,7 +45,7 @@ class BinaryTC(TestCase):
b.write(b'toto')
b.write(bytearray(b'toto'))
if PY2:
b.write(buffer('toto'))
b.write(buffer('toto')) # noqa: F821
else:
b.write(memoryview(b'toto'))
with self.assertRaises((AssertionError, TypeError)):
......
......@@ -78,7 +78,7 @@ class StatsdTC(TestCase):
self.assertIn(value, DATA)
def check_received_ms(self, value):
value = re.compile(value.replace('?', '\d'))
value = re.compile(value.replace('?', r'\d'))
for i in range(10):
if [x for x in DATA if value.match(x)]:
break
......
......@@ -343,10 +343,10 @@ class ApplicationTC(CubicWebTC):
}
req.form.update(kwargs)
req.form['_cw_entity_fields:%s' % dir_eid] = ','.join(
['parent-%s' % role] +
[key.split(':')[0]
for key in kwargs.keys()
if not key.startswith('_')])
['parent-%s' % role]
+ [key.split(':')[0]
for key in kwargs.keys()
if not key.startswith('_')])
self.expect_redirect_handle_request(req)
def _edit_in_version(self, ticket_eid, version_eid, **kwargs):
......@@ -360,10 +360,10 @@ class ApplicationTC(CubicWebTC):
}
req.form.update(kwargs)
req.form['_cw_entity_fields:%s' % ticket_eid] = ','.join(
['in_version-subject'] +
[key.split(':')[0]
for key in kwargs.keys()
if not key.startswith('_')])
['in_version-subject']
+ [key.split(':')[0]
for key in kwargs.keys()
if not key.startswith('_')])
self.expect_redirect_handle_request(req)
def test_create_and_link_directories(self):
......
......@@ -43,8 +43,8 @@ _affk.tag_subject_of(('CWUser', 'in_group', 'CWGroup'),
class UserPreferencesEntityAction(action.Action):
__regid__ = 'prefs'
__select__ = (one_line_rset() & is_instance('CWUser') &
match_user_groups('owners', 'managers'))
__select__ = (one_line_rset() & is_instance('CWUser')
& match_user_groups('owners', 'managers'))
title = _('preferences')
category = 'mainactions'
......
......@@ -312,8 +312,7 @@ class EditController(basecontrollers.ViewController):
try:
for field, value in field.process_posted(form):
if not ((field.role == 'subject' and field.name in eschema.subjrels)
or
(field.role == 'object' and field.name in eschema.objrels)):
or (field.role == 'object' and field.name in eschema.objrels)):
continue
rschema = self._cw.vreg.schema.rschema(field.name)
......
......@@ -138,8 +138,8 @@ class JsonErrorView(JsonMixIn, management.ErrorView):
The returned json object will contain err / traceback informations.
"""
__select__ = (management.ErrorView.__select__ &
_requested_vid('jsonexport', 'ejsonexport'))
__select__ = (management.ErrorView.__select__
& _requested_vid('jsonexport', 'ejsonexport'))
def call(self):
errmsg, exclass, excinfo = self._excinfo()
......
......@@ -189,8 +189,8 @@ class InContextWithStateView(EntityView):
class WorkflowActions(action.Action):
"""fill 'workflow' sub-menu of the actions box"""
__regid__ = 'workflow'
__select__ = (action.Action.__select__ & one_line_rset() &
relation_possible('in_state'))
__select__ = (action.Action.__select__ & one_line_rset()
& relation_possible('in_state'))
submenu = _('workflow')
order = 10
......
......@@ -124,8 +124,8 @@ def setup_workflow(cnx, name, wfdef, cleanup=True):
wf.cw_set(initial_state=states[wfdef['initial_state']])
for trname, trdef in wfdef['transitions'].items():
tr = (wf.transition_by_name(trname) or
cnx.create_entity('Transition', name=trname))
tr = (wf.transition_by_name(trname)
or cnx.create_entity('Transition', name=trname))
tr.cw_set(transition_of=wf)
if trdef.get('tostate'):
tr.cw_set(destination_state=states[trdef['tostate']])
......
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