plone.api/fix_tests: make files more readable

Alexander Loechel <jenkins-z4DKO/[email protected]> Thu, 27 Jul 2017 15:24:48 -0700 (PDT)
Newsgroups gmane.comp.web.zope.plone.cvs
Message-ID <[email protected]>
Repository: plone.api
Branch: refs/heads/fix_tests
Date: 2017-07-28T00:24:33+02:00
Author: Alexander Loechel (loechel) <[email protected]>
Commit: https://github.com/plone/plone.api/commit/d3bc76102e57353c8ee54dee96b6a5ebcbdb2ad2

make files more readable

Files changed:
M src/plone/api/__init__.py
M src/plone/api/content.py
M src/plone/api/env.py
M src/plone/api/group.py
M src/plone/api/portal.py
M src/plone/api/user.py
M src/plone/api/validation.py

diff --git a/src/plone/api/__init__.py b/src/plone/api/__init__.py
index d0022a0..251c015 100644
--- a/src/plone/api/__init__.py
+++ b/src/plone/api/__init__.py
@@ -1,5 +1,6 @@
 # -*- coding: utf-8 -*-
-# flake8: noqa
+# flake8: NOQA: S401
+
 from plone.api import content
 from plone.api import env
 from plone.api import group
diff --git a/src/plone/api/content.py b/src/plone/api/content.py
index 529faa8..9ce9373 100644
--- a/src/plone/api/content.py
+++ b/src/plone/api/content.py
@@ -94,10 +94,14 @@ def create(
         types = [fti.getId() for fti in container.allowedContentTypes()]
 
         raise InvalidParameterError(
-            "Cannot add a '{0}' object to the container.\n"
+            "Cannot add a '{obj_type}' object to the container.\n"
             'Allowed types are:\n'
-            '{1}\n'
-            '{2}'.format(type, '\n'.join(sorted(types)), e.message),
+            '{allowed_types}\n'
+            '{message}'.format(
+                obj_type=type,
+                allowed_types='\n'.join(sorted(types)),
+                message=e.message,
+            ),
         )
 
     content = container[content_id]
@@ -143,8 +147,11 @@ def get(path=None, UID=None):
     if path:
         site = portal.get()
         site_absolute_path = '/'.join(site.getPhysicalPath())
-        if not path.startswith('{0}'.format(site_absolute_path)):
-            path = '{0}{1}'.format(site_absolute_path, path)
+        if not path.startswith('{path}'.format(path=site_absolute_path)):
+            path = '{site_path}{relative_path}'.format(
+                site_path=site_absolute_path,
+                relative_path=path,
+            )
 
         try:
             return site.restrictedTraverse(path)
@@ -349,6 +356,7 @@ def _find_path(maps, path, current_state, start_state):
     # transitions. i.e an initial state you are not able to return to.
     if current_state not in maps:
         return
+
     for new_transition, from_states in maps[current_state]:
         next_path = _copy(path)
         if new_transition in path:
@@ -388,9 +396,9 @@ def _wf_transitions_for(workflow, from_state, to_state):
     """
     exit_state_maps = {}
     for state in workflow.states.objectValues():
-        for t in state.getTransitions():
-            exit_state_maps.setdefault(t, [])
-            exit_state_maps[t].append(state.getId())
+        for transition in state.getTransitions():
+            exit_state_maps.setdefault(transition, [])
+            exit_state_maps[transition].append(state.getId())
 
     transition_maps = {}
     for transition in workflow.transitions.objectValues():
@@ -544,9 +552,12 @@ def get_view(name=None, context=None, request=None):
     # Raise an error if the requested view is not available.
     if name not in available_view_names:
         raise InvalidParameterError(
-            "Cannot find a view with name '{0}'.\n"
+            "Cannot find a view with name '{name}'.\n"
             'Available views are:\n'
-            '{1}'.format(name, '\n'.join(sorted(available_view_names))),
+            '{views}'.format(
+                name=name,
+                views='\n'.join(sorted(available_view_names)),
+            ),
         )
     return getMultiAdapter((context, request), name=name)
 
diff --git a/src/plone/api/env.py b/src/plone/api/env.py
index 8ac15ec..7d73086 100644
--- a/src/plone/api/env.py
+++ b/src/plone/api/env.py
@@ -3,6 +3,7 @@
 from AccessControl.SecurityManagement import newSecurityManager
 from AccessControl.SecurityManagement import setSecurityManager
 from App.config import getConfiguration
+from contextlib import closing
 from contextlib import contextmanager
 from pkg_resources import get_distribution
 from plone.api import portal
@@ -115,12 +116,12 @@ def _adopt_roles(roles):
     # If the stack is empty, the default security policy gets used.
     overriding_context = _GlobalRoleOverridingContext(roles)
 
-    sm = getSecurityManager()
-    sm.addContext(overriding_context)
+    security_manager = getSecurityManager()
+    security_manager.addContext(overriding_context)
 
     yield
 
-    sm.removeContext(overriding_context)
+    security_manager.removeContext(overriding_context)
 
 
 class _GlobalRoleOverridingContext(object):
@@ -208,13 +209,8 @@ def read_only_mode():
     :returns: bool isReadOnly True if ZODB is read-only
     :Example: :ref:`env_read_only_mode_example`
     """
-    isReadOnly = True
-    try:
-        conn = Globals.DB.open()
-        isReadOnly = conn.isReadOnly()
-    finally:
-        conn.close()
-    return isReadOnly
+    with closing(Globals.DB.open()) as connection:
+        return connection.isReadOnly()
 
 
 def plone_version():
diff --git a/src/plone/api/group.py b/src/plone/api/group.py
index 2fc650b..603d5a5 100644
--- a/src/plone/api/group.py
+++ b/src/plone/api/group.py
@@ -39,7 +39,9 @@ def create(
     """
     group_tool = portal.get_tool('portal_groups')
     group_tool.addGroup(
-        groupname, roles, groups,
+        groupname,
+        roles,
+        groups,
         title=title,
         description=description,
     )
@@ -241,8 +243,8 @@ def get_roles(groupname=None, group=None, obj=None, inherit=True):
         pas = portal.get_tool('acl_users')
         for _, lrmanager in pas.plugins.listPlugins(ILocalRolesPlugin):
             for adapter in lrmanager._getAdapters(obj):
-                for pid in principal_ids:
-                    roles.update(adapter.getRoles(pid))
+                for principal_id in principal_ids:
+                    roles.update(adapter.getRoles(principal_id))
         return list(roles)
 
 
@@ -278,10 +280,11 @@ def grant_roles(groupname=None, group=None, roles=None, obj=None):
         # only roles persistent on the object, not from other providers
         actual_roles = obj.get_local_roles_for_userid(group_id)
 
-    if actual_roles.count('Anonymous'):
-        actual_roles.remove('Anonymous')
-    if actual_roles.count('Authenticated'):
-        actual_roles.remove('Authenticated')
+    actual_roles = [
+        role
+        for role in actual_roles
+        if role not in ['Anonymous', 'Authenticated']
+    ]
 
     roles = list(set(actual_roles) | set(roles))
     portal_groups = portal.get_tool('portal_groups')
@@ -322,10 +325,12 @@ def revoke_roles(groupname=None, group=None, roles=None, obj=None):
         actual_roles = get_roles(groupname=group_id)
     else:
         actual_roles = get_roles(groupname=group_id, obj=obj, inherit=False)
-    if actual_roles.count('Anonymous'):
-        actual_roles.remove('Anonymous')
-    if actual_roles.count('Authenticated'):
-        actual_roles.remove('Authenticated')
+
+    actual_roles = [
+        role
+        for role in actual_roles
+        if role not in ['Anonymous', 'Authenticated']
+    ]
 
     roles = list(set(actual_roles) - set(roles))
     portal_groups = portal.get_tool('portal_groups')
diff --git a/src/plone/api/portal.py b/src/plone/api/portal.py
index 5d33645..85a515b 100644
--- a/src/plone/api/portal.py
+++ b/src/plone/api/portal.py
@@ -126,9 +126,9 @@ def get_tool(name=None):
                 tools.append(id)
 
         raise InvalidParameterError(
-            "Cannot find a tool with name '{0}'.\n"
+            "Cannot find a tool with name '{name}'.\n"
             'Available tools are:\n'
-            '{1}'.format(name, '\n'.join(tools)),
+            '{tools}'.format(name=name, tools='\n'.join(tools)),
         )
 
 
@@ -308,12 +308,13 @@ def get_registry_record(name=None, interface=None, default=MISSING):
         # Show all records on the interface.
         records = [key for key in interface.names()]
         msg = (
-            "Cannot find a record with name '{0}' on interface {1}.\n"
+            "Cannot find a record with name '{name}'"
+            " on interface {identifier}.\n"
             'Did you mean?\n'
-            '{2}'.format(
-                name,
-                interface.__identifier__,
-                '\n'.join(records),
+            '{records}'.format(
+                name=name,
+                identifier=interface.__identifier__,
+                records='\n'.join(records),
             )
         )
         raise InvalidParameterError(msg)
@@ -327,14 +328,14 @@ def get_registry_record(name=None, interface=None, default=MISSING):
     # Show all records that 'look like' name.
     # We don't dump the whole list, because it 1500+ items.
     msg = (
-        "Cannot find a record with name '{0}'".format(name)
+        "Cannot find a record with name '{name}'".format(name=name)
     )
     records = [key for key in registry.records.keys() if name in key]
     if records:
         msg = (
-            '{0}\n'
+            '{message}\n'
             'Did you mean?:\n'
-            '{1}'.format(msg, '\n'.join(records))
+            '{records}'.format(message=msg, records='\n'.join(records))
         )
     raise InvalidParameterError(msg)
 
@@ -369,19 +370,22 @@ def set_registry_record(name=None, value=None, interface=None):
 
         from zope.schema._bootstrapinterfaces import WrongType
         try:
-            registry['{0}.{1}'.format(interface.__identifier__, name)] = value
+            registry['{identifier}.{name}'.format(
+                identifier=interface.__identifier__,
+                name=name
+            )] = value
         except WrongType:
             field_type = [
-                f[1]
-                for f in interface.namesAndDescriptions()
-                if f[0] == 'field_one'
+                field[1]
+                for field in interface.namesAndDescriptions()
+                if field[0] == 'field_one'
             ][0]
             raise InvalidParameterError(
-                u'The value parameter for the field {0} needs to be {1}'
-                u'instead of {2}'.format(
-                    name,
-                    str(field_type.__class__),
-                    type(value),
+                u'The value parameter for the field {name} needs to be '
+                u'{of_class} instead of {of_type}'.format(
+                    name=name,
+                    of_class=str(field_type.__class__),
+                    of_type=type(value),
                 ),
             )
 
diff --git a/src/plone/api/user.py b/src/plone/api/user.py
index b306095..d08c97c 100644
--- a/src/plone/api/user.py
+++ b/src/plone/api/user.py
@@ -60,7 +60,8 @@ def create(
 
     try:
         use_email_as_username = portal.get_registry_record(
-            'plone.use_email_as_login')
+            'plone.use_email_as_login',
+        )
     except InvalidParameterError:
         site = portal.get()
         props = site.portal_properties
@@ -78,7 +79,7 @@ def create(
     # Generate a random 8-char password
     if not password:
         chars = string.ascii_letters + string.digits
-        password = ''.join(random.choice(chars) for x in range(8))
+        password = ''.join(random.choice(chars) for char in range(8))
 
     properties.update(username=user_id)
     properties.update(email=email)
@@ -250,12 +251,12 @@ def get_roles(username=None, user=None, obj=None, inherit=True):
             plone_user = user.getUser()
             principal_ids = list(plone_user.getGroups())
             principal_ids.insert(0, plone_user.getId())
-            roles = set([])
+            roles = set()
             pas = portal.get_tool('acl_users')
             for _, lrmanager in pas.plugins.listPlugins(ILocalRolesPlugin):
                 for adapter in lrmanager._getAdapters(obj):
-                    for pid in principal_ids:
-                        roles.update(adapter.getRoles(pid))
+                    for principal_id in principal_ids:
+                        roles.update(adapter.getRoles(principal_id))
             return list(roles)
     else:
         return user.getRoles()
@@ -298,7 +299,7 @@ def get_permissions(username=None, user=None, obj=None):
     result = {}
     with context:
         portal_membership = portal.get_tool('portal_membership')
-        permissions = (p[0] for p in getPermissions())
+        permissions = (permission[0] for permission in getPermissions())
         for permission in permissions:
             result[permission] = bool(
                 portal_membership.checkPermission(permission, obj),
@@ -420,23 +421,23 @@ def revoke_roles(username=None, user=None, obj=None, roles=None):
     if user is None:
         raise InvalidParameterError('User could not be found')
 
-    if isinstance(roles, tuple):
-        roles = list(roles)
+    roles = set(roles)
 
     if 'Anonymous' in roles or 'Authenticated' in roles:
         raise InvalidParameterError
+
     inherit = True
     if obj is not None:
         # if obj, get only a list of local roles, without inherited ones
         inherit = False
 
-    actual_roles = list(get_roles(user=user, obj=obj, inherit=inherit))
-    if actual_roles.count('Anonymous'):
-        actual_roles.remove('Anonymous')
-    if actual_roles.count('Authenticated'):
-        actual_roles.remove('Authenticated')
+    actual_roles = set([
+        role
+        for role in get_roles(user=user, obj=obj, inherit=inherit)
+        if role not in ['Anonymous', 'Authenticated']
+    ])
 
-    roles = list(set(actual_roles) - set(roles))
+    roles = list(actual_roles - roles)
 
     if obj is None:
         user.setSecurityProfile(roles=roles)
diff --git a/src/plone/api/validation.py b/src/plone/api/validation.py
index e14c7cc..afa9a91 100644
--- a/src/plone/api/validation.py
+++ b/src/plone/api/validation.py
@@ -17,9 +17,10 @@ def _get_arg_spec(func, validator_args):
     extra_args = set(validator_args) - set(signature_args)
     if extra_args:
         raise ValueError(
-            'Validator for {0} refers to parameters '
-            'that are not part of the function signature: {1}'.format(
-                func.__name__, ', '.join(extra_args),
+            'Validator for {name} refers to parameters '
+            'that are not part of the function signature: {signature}'.format(
+                name=func.__name__,
+                signature=', '.join(extra_args),
             ),
         )
 
@@ -31,13 +32,13 @@ def _get_supplied_args(signature_params, args, kwargs):
     either as positional or keyword arguments, and are not None.
     """
     supplied_args = []
-    for i in range(len(args)):
-        if args[i] is not None:
-            supplied_args.append(signature_params[i])
+    for index in range(len(args)):
+        if args[index] is not None:
+            supplied_args.append(signature_params[index])
 
-    for k in kwargs:
-        if kwargs[k] is not None:
-            supplied_args.append(k)
+    for keyword in kwargs:
+        if kwargs[keyword] is not None:
+            supplied_args.append(keyword)
 
     return supplied_args
 
@@ -57,19 +58,23 @@ def _required_parameters(func):
         """The actual decorator"""
         signature_params = _get_arg_spec(func, required_params)
 
-        def wrapped(f, *args, **kwargs):
+        def wrapped(function, *args, **kwargs):
             """The wrapped function (whose docstring will get replaced)"""
             supplied_args = _get_supplied_args(signature_params, args, kwargs)
 
-            missing = [p for p in required_params if p not in supplied_args]
+            missing = [
+                param
+                for param in required_params
+                if param not in supplied_args
+            ]
             if len(missing):
                 raise MissingParameterError(
-                    'Missing required parameter(s): {0}'.format(
-                        ', '.join(missing),
+                    'Missing required parameter(s): {params}'.format(
+                        params=', '.join(missing),
                     ),
                 )
 
-            return f(*args, **kwargs)
+            return function(*args, **kwargs)
 
         return decorator(wrapped, func)
 
@@ -89,18 +94,22 @@ def _mutually_exclusive_parameters(func):
         """The actual decorator."""
         signature_params = _get_arg_spec(func, exclusive_params)
 
-        def wrapped(f, *args, **kwargs):
+        def wrapped(function, *args, **kwargs):
             """The wrapped function (whose docstring will get replaced)."""
             supplied_args = _get_supplied_args(signature_params, args, kwargs)
-            clashes = [s for s in supplied_args if s in exclusive_params]
+            clashes = [
+                argument
+                for argument in supplied_args
+                if argument in exclusive_params
+            ]
             if len(clashes) > 1:
                 raise InvalidParameterError(
-                    'These parameters are mutually exclusive: {0}.'.format(
-                        ', '.join(supplied_args),
+                    'These parameters are mutually exclusive: {arg}.'.format(
+                        arg=', '.join(supplied_args),
                     ),
                 )
 
-            return f(*args, **kwargs)
+            return function(*args, **kwargs)
 
         return decorator(wrapped, func)
 
@@ -121,17 +130,23 @@ def _at_least_one_of(func):
         """The actual decorator."""
         signature_params = _get_arg_spec(func, candidate_params)
 
-        def wrapped(f, *args, **kwargs):
+        def wrapped(function, *args, **kwargs):
             """The wrapped function (whose docstring will get replaced)."""
             supplied_args = _get_supplied_args(signature_params, args, kwargs)
-            candidates = [s for s in supplied_args if s in candidate_params]
+            candidates = [
+                candidate
+                for candidate in supplied_args
+                if candidate in candidate_params
+            ]
             if len(candidates) < 1:
                 raise MissingParameterError(
                     'At least one of these parameters must be '
-                    'supplied: {0}.'.format(', '.join(candidate_params)),
+                    'supplied: {params}.'.format(
+                        params=', '.join(candidate_params),
+                    ),
                 )
 
-            return f(*args, **kwargs)
+            return function(*args, **kwargs)
 
         return decorator(wrapped, func)
 



------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot