diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4e6905e237..b817f1b821 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -22,16 +22,12 @@ repos: # rev: v1.1.1 # hooks: # - id: doc8 - - repo: https://github.com/asottile/pyupgrade - rev: v3.15.2 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.6.9 hooks: - - id: pyupgrade - args: ['--py38-plus'] - - repo: https://github.com/psf/black - rev: 24.4.0 - hooks: - - id: black - args: ['-S', '-l', '79'] + - id: ruff + args: ['--fix', '--unsafe-fixes'] + - id: ruff-format - repo: https://github.com/PyCQA/bandit rev: '1.7.9' hooks: diff --git a/api-ref/source/conf.py b/api-ref/source/conf.py index 1bbea93868..38a34b99d3 100644 --- a/api-ref/source/conf.py +++ b/api-ref/source/conf.py @@ -23,15 +23,9 @@ # serve to show the default. html_theme = 'openstackdocs' -html_theme_options = { - "sidebar_dropdown": "api_ref", - "sidebar_mode": "toc", -} +html_theme_options = {"sidebar_dropdown": "api_ref", "sidebar_mode": "toc"} -extensions = [ - 'os_api_ref', - 'openstackdocstheme', -] +extensions = ['os_api_ref', 'openstackdocstheme'] # If extensions (or modules to document with autodoc) are in another directory, diff --git a/devstack/tools/oidc/setup_keycloak_client.py b/devstack/tools/oidc/setup_keycloak_client.py index 406ad1f914..bd9f9239c8 100644 --- a/devstack/tools/oidc/setup_keycloak_client.py +++ b/devstack/tools/oidc/setup_keycloak_client.py @@ -29,7 +29,7 @@ class KeycloakClient: } r = requests.post(self.token_endpoint(realm), data=params).json() headers = { - 'Authorization': ("Bearer %s" % r['access_token']), + 'Authorization': f"Bearer {r['access_token']}", 'Content-Type': 'application/json', } self.session.headers.update(headers) diff --git a/doc/source/conf.py b/doc/source/conf.py index 213e7621b7..8ba1dadc51 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -285,7 +285,7 @@ texinfo_documents = [ 'keystone', 'One line description of project.', 'Miscellaneous', - ), + ) ] # Documents to append as an appendix to all manuals. diff --git a/keystone/api/_shared/EC2_S3_Resource.py b/keystone/api/_shared/EC2_S3_Resource.py index 7bb79683e0..767cb72e6b 100644 --- a/keystone/api/_shared/EC2_S3_Resource.py +++ b/keystone/api/_shared/EC2_S3_Resource.py @@ -110,15 +110,15 @@ class ResourceBase(ks_flask.ResourceBase): loaded = cred['blob'] # Convert to the legacy format - cred_data = dict( - user_id=cred.get('user_id'), - project_id=cred.get('project_id'), - access=loaded.get('access'), - secret=loaded.get('secret'), - trust_id=loaded.get('trust_id'), - app_cred_id=loaded.get('app_cred_id'), - access_token_id=loaded.get('access_token_id'), - ) + cred_data = { + 'user_id': cred.get('user_id'), + 'project_id': cred.get('project_id'), + 'access': loaded.get('access'), + 'secret': loaded.get('secret'), + 'trust_id': loaded.get('trust_id'), + 'app_cred_id': loaded.get('app_cred_id'), + 'access_token_id': loaded.get('access_token_id'), + } # validate the signature self._check_signature(cred_data, credentials) diff --git a/keystone/api/_shared/implied_roles.py b/keystone/api/_shared/implied_roles.py index 2b8f26164d..3130516135 100644 --- a/keystone/api/_shared/implied_roles.py +++ b/keystone/api/_shared/implied_roles.py @@ -24,7 +24,7 @@ PROVIDERS = provider_api.ProviderAPIs def build_prior_role_response_data(prior_role_id, prior_role_name): return { 'id': prior_role_id, - 'links': {'self': ks_flask.base_url(path='/roles/%s' % prior_role_id)}, + 'links': {'self': ks_flask.base_url(path=f'/roles/{prior_role_id}')}, 'name': prior_role_name, } @@ -33,7 +33,9 @@ def build_implied_role_response_data(implied_role): return { 'id': implied_role['id'], 'links': { - 'self': ks_flask.base_url(path='/roles/%s' % implied_role['id']) + 'self': ks_flask.base_url( + path='/roles/{}'.format(implied_role['id']) + ) }, 'name': implied_role['name'], } diff --git a/keystone/api/auth.py b/keystone/api/auth.py index abaaf26237..7881eb6263 100644 --- a/keystone/api/auth.py +++ b/keystone/api/auth.py @@ -466,15 +466,15 @@ class AuthAPI(ks_flask.APIBase): resource=AuthProjectsResource, url='/auth/projects', alternate_urls=[ - dict( - url='/OS-FEDERATION/projects', - json_home=ks_flask.construct_json_home_data( + { + 'url': '/OS-FEDERATION/projects', + 'json_home': ks_flask.construct_json_home_data( rel='projects', resource_relation_func=( json_home_relations.os_federation_resource_rel_func ), ), - ) + } ], rel='auth_projects', resource_kwargs={}, @@ -483,15 +483,15 @@ class AuthAPI(ks_flask.APIBase): resource=AuthDomainsResource, url='/auth/domains', alternate_urls=[ - dict( - url='/OS-FEDERATION/domains', - json_home=ks_flask.construct_json_home_data( + { + 'url': '/OS-FEDERATION/domains', + 'json_home': ks_flask.construct_json_home_data( rel='domains', resource_relation_func=( json_home_relations.os_federation_resource_rel_func ), ), - ) + } ], rel='auth_domains', resource_kwargs={}, @@ -590,7 +590,4 @@ class AuthFederationAPI(ks_flask.APIBase): ] -APIs = ( - AuthAPI, - AuthFederationAPI, -) +APIs = (AuthAPI, AuthFederationAPI) diff --git a/keystone/api/credentials.py b/keystone/api/credentials.py index 7f46e19299..9d1d777ad4 100644 --- a/keystone/api/credentials.py +++ b/keystone/api/credentials.py @@ -286,7 +286,6 @@ class CredentialResource(ks_flask.ResourceBase): class CredentialAPI(ks_flask.APIBase): - _name = 'credentials' _import_name = __name__ resource_mapping = [ diff --git a/keystone/api/discovery.py b/keystone/api/discovery.py index 4d3f5728e5..f265655e87 100644 --- a/keystone/api/discovery.py +++ b/keystone/api/discovery.py @@ -31,12 +31,7 @@ def _get_versions_list(identity_url): 'id': 'v3.14', 'status': 'stable', 'updated': '2020-04-07T00:00:00Z', - 'links': [ - { - 'rel': 'self', - 'href': identity_url, - } - ], + 'links': [{'rel': 'self', 'href': identity_url}], 'media-types': [ {'base': 'application/json', 'type': MEDIA_TYPE_JSON % 'v3'} ], @@ -70,7 +65,7 @@ def get_versions(): mimetype=MimeTypes.JSON_HOME, ) else: - identity_url = '%s/' % ks_flask.base_url() + identity_url = f'{ks_flask.base_url()}/' versions = _get_versions_list(identity_url) # Set the preferred version to the latest "stable" version. # TODO(morgan): If we ever have more API versions find the latest @@ -99,7 +94,7 @@ def get_version_v3(): response=jsonutils.dumps(content), mimetype=MimeTypes.JSON_HOME ) else: - identity_url = '%s/' % ks_flask.base_url() + identity_url = f'{ks_flask.base_url()}/' versions = _get_versions_list(identity_url) return flask.Response( response=jsonutils.dumps({'version': versions['v3']}), diff --git a/keystone/api/endpoints.py b/keystone/api/endpoints.py index b365fb7b2b..cab142ea0d 100644 --- a/keystone/api/endpoints.py +++ b/keystone/api/endpoints.py @@ -67,7 +67,7 @@ class EndpointResource(ks_flask.ResourceBase): try: PROVIDERS.catalog_api.get_region(endpoint['region_id']) except exception.RegionNotFound: - region = dict(id=endpoint['region_id']) + region = {'id': endpoint['region_id']} PROVIDERS.catalog_api.create_region( region, initiator=notifications.build_audit_initiator() ) diff --git a/keystone/api/os_ep_filter.py b/keystone/api/os_ep_filter.py index 8ab7acbaca..a1be593aca 100644 --- a/keystone/api/os_ep_filter.py +++ b/keystone/api/os_ep_filter.py @@ -235,12 +235,11 @@ class EPFilterGroupsProjectsResource(ks_flask.ResourceBase): @classmethod def _add_self_referential_link(cls, ref, collection_name=None): url = ( - '/OS-EP-FILTER/endpoint_groups/%(endpoint_group_id)s' - '/projects/%(project_id)s' - % { - 'endpoint_group_id': ref['endpoint_group_id'], - 'project_id': ref['project_id'], - } + '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' + '/projects/{project_id}'.format( + endpoint_group_id=ref['endpoint_group_id'], + project_id=ref['project_id'], + ) ) ref.setdefault('links', {}) ref['links']['self'] = url diff --git a/keystone/api/os_federation.py b/keystone/api/os_federation.py index 4200a26492..22abd1437a 100644 --- a/keystone/api/os_federation.py +++ b/keystone/api/os_federation.py @@ -99,7 +99,9 @@ class IdentityProvidersResource(_ResourceBase): """ base_path = ref['links'].get('self') if base_path is None: - base_path = '/'.join(ks_flask.base_url(path='/%s' % ref['id'])) + base_path = '/'.join( + ks_flask.base_url(path='/{}'.format(ref['id'])) + ) for name in ['protocols']: ref['links'][name] = '/'.join([base_path, name]) @@ -188,7 +190,6 @@ class _IdentityProvidersProtocolsResourceBase(_ResourceBase): class IDPProtocolsListResource(_IdentityProvidersProtocolsResourceBase): - def get(self, idp_id): """List protocols for an IDP. @@ -205,7 +206,6 @@ class IDPProtocolsListResource(_IdentityProvidersProtocolsResourceBase): class IDPProtocolsCRUDResource(_IdentityProvidersProtocolsResourceBase): - def get(self, idp_id, protocol_id): """Get protocols for an IDP. @@ -448,7 +448,6 @@ class SAML2MetadataResource(flask_restful.Resource): class OSFederationAuthResource(flask_restful.Resource): - @ks_flask.unenforced_api def get(self, idp_id, protocol_id): """Authenticate from dedicated uri endpoint. diff --git a/keystone/api/os_oauth1.py b/keystone/api/os_oauth1.py index a9cd52492e..cdf9826bc4 100644 --- a/keystone/api/os_oauth1.py +++ b/keystone/api/os_oauth1.py @@ -117,10 +117,10 @@ class ConsumerResource(ks_flask.ResourceBase): def delete(self, consumer_id): ENFORCER.enforce_call(action='identity:delete_consumer') reason = ( - 'Invalidating token cache because consumer %(consumer_id)s has ' + f'Invalidating token cache because consumer {consumer_id} has ' 'been deleted. Authorization for users with OAuth tokens will be ' 'recalculated and enforced accordingly the next time they ' - 'authenticate or validate a token.' % {'consumer_id': consumer_id} + 'authenticate or validate a token.' ) notifications.invalidate_token_cache_notification(reason) PROVIDERS.oauth_api.delete_consumer( @@ -191,12 +191,11 @@ class RequestTokenResource(_OAuth1ResourceBase): ) result = 'oauth_token={key}&oauth_token_secret={secret}'.format( - key=token_ref['id'], - secret=token_ref['request_secret'], + key=token_ref['id'], secret=token_ref['request_secret'] ) if CONF.oauth1.request_token_duration > 0: - expiry_bit = '&oauth_expires_at=%s' % token_ref['expires_at'] + expiry_bit = '&oauth_expires_at={}'.format(token_ref['expires_at']) result += expiry_bit resp = flask.make_response(result, http.client.CREATED) @@ -294,12 +293,11 @@ class AccessTokenResource(_OAuth1ResourceBase): ) result = 'oauth_token={key}&oauth_token_secret={secret}'.format( - key=token_ref['id'], - secret=token_ref['access_secret'], + key=token_ref['id'], secret=token_ref['access_secret'] ) if CONF.oauth1.access_token_duration > 0: - expiry_bit = '&oauth_expires_at=%s' % (token_ref['expires_at']) + expiry_bit = '&oauth_expires_at={}'.format(token_ref['expires_at']) result += expiry_bit resp = flask.make_response(result, http.client.CREATED) diff --git a/keystone/api/os_oauth2.py b/keystone/api/os_oauth2.py index a163fe8608..6885649d61 100644 --- a/keystone/api/os_oauth2.py +++ b/keystone/api/os_oauth2.py @@ -37,7 +37,6 @@ _build_resource_relation = json_home_relations.os_oauth2_resource_rel_func class AccessTokenResource(ks_flask.ResourceBase): - def _method_not_allowed(self): """Raise a method not allowed error.""" raise exception.OAuth2OtherError( @@ -361,11 +360,11 @@ class AccessTokenResource(ks_flask.ResourceBase): raise error client_cert_dn = {} for key in cert_subject_dn: - client_cert_dn['SSL_CLIENT_SUBJECT_DN_%s' % key.upper()] = ( + client_cert_dn[f'SSL_CLIENT_SUBJECT_DN_{key.upper()}'] = ( cert_subject_dn.get(key) ) for key in cert_issuer_dn: - client_cert_dn['SSL_CLIENT_ISSUER_DN_%s' % key.upper()] = ( + client_cert_dn[f'SSL_CLIENT_ISSUER_DN_{key.upper()}'] = ( cert_issuer_dn.get(key) ) diff --git a/keystone/api/policy.py b/keystone/api/policy.py index aaec219ff2..7e15c79b0c 100644 --- a/keystone/api/policy.py +++ b/keystone/api/policy.py @@ -102,7 +102,6 @@ class PolicyResource(ks_flask.ResourceBase): class EndpointPolicyResource(flask_restful.Resource): - def get(self, policy_id): ENFORCER.enforce_call(action='identity:list_endpoints_for_policy') PROVIDERS.policy_api.get_policy(policy_id) @@ -120,7 +119,6 @@ class EndpointPolicyResource(flask_restful.Resource): class EndpointPolicyAssociations(flask_restful.Resource): - def get(self, policy_id, endpoint_id): action = 'identity:check_policy_association_for_endpoint' ENFORCER.enforce_call(action=action) @@ -153,7 +151,6 @@ class EndpointPolicyAssociations(flask_restful.Resource): class ServicePolicyAssociations(flask_restful.Resource): - def get(self, policy_id, service_id): action = 'identity:check_policy_association_for_service' ENFORCER.enforce_call(action=action) @@ -186,7 +183,6 @@ class ServicePolicyAssociations(flask_restful.Resource): class ServiceRegionPolicyAssociations(flask_restful.Resource): - def get(self, policy_id, service_id, region_id): action = 'identity:check_policy_association_for_region_and_service' ENFORCER.enforce_call(action=action) diff --git a/keystone/api/role_assignments.py b/keystone/api/role_assignments.py index 0725e07de5..b5f850fd57 100644 --- a/keystone/api/role_assignments.py +++ b/keystone/api/role_assignments.py @@ -315,16 +315,16 @@ class RoleAssignmentsResource(ks_flask.ResourceBase): if 'domain_id' in entity.get('indirect', {}): inherited_assignment = True - formatted_link = ( - '/domains/%s' % entity['indirect']['domain_id'] + formatted_link = '/domains/{}'.format( + entity['indirect']['domain_id'] ) elif 'project_id' in entity.get('indirect', {}): inherited_assignment = True - formatted_link = ( - '/projects/%s' % entity['indirect']['project_id'] + formatted_link = '/projects/{}'.format( + entity['indirect']['project_id'] ) else: - formatted_link = '/projects/%s' % entity['project_id'] + formatted_link = '/projects/{}'.format(entity['project_id']) elif 'domain_id' in entity: if 'domain_name' in entity: formatted_entity['scope'] = { @@ -337,7 +337,7 @@ class RoleAssignmentsResource(ks_flask.ResourceBase): formatted_entity['scope'] = { 'domain': {'id': entity['domain_id']} } - formatted_link = '/domains/%s' % entity['domain_id'] + formatted_link = '/domains/{}'.format(entity['domain_id']) elif 'system' in entity: formatted_link = '/system' formatted_entity['scope'] = {'system': entity['system']} @@ -356,13 +356,16 @@ class RoleAssignmentsResource(ks_flask.ResourceBase): formatted_entity['user'] = {'id': entity['user_id']} if 'group_id' in entity.get('indirect', {}): membership_url = ks_flask.base_url( - path='/groups/%s/users/%s' - % (entity['indirect']['group_id'], entity['user_id']) + path='/groups/{}/users/{}'.format( + entity['indirect']['group_id'], entity['user_id'] + ) ) formatted_entity['links']['membership'] = membership_url - formatted_link += '/groups/%s' % entity['indirect']['group_id'] + formatted_link += '/groups/{}'.format( + entity['indirect']['group_id'] + ) else: - formatted_link += '/users/%s' % entity['user_id'] + formatted_link += '/users/{}'.format(entity['user_id']) elif 'group_id' in entity: if 'group_name' in entity: formatted_entity['group'] = { @@ -375,7 +378,7 @@ class RoleAssignmentsResource(ks_flask.ResourceBase): } else: formatted_entity['group'] = {'id': entity['group_id']} - formatted_link += '/groups/%s' % entity['group_id'] + formatted_link += '/groups/{}'.format(entity['group_id']) if 'role_name' in entity: formatted_entity['role'] = { @@ -395,18 +398,17 @@ class RoleAssignmentsResource(ks_flask.ResourceBase): formatted_entity['role'] = {'id': entity['role_id']} prior_role_link = '' if 'role_id' in entity.get('indirect', {}): - formatted_link += '/roles/%s' % entity['indirect']['role_id'] + formatted_link += '/roles/{}'.format(entity['indirect']['role_id']) prior_role_link = '/prior_role/{prior}/implies/{implied}'.format( - prior=entity['role_id'], - implied=entity['indirect']['role_id'], + prior=entity['role_id'], implied=entity['indirect']['role_id'] ) else: - formatted_link += '/roles/%s' % entity['role_id'] + formatted_link += '/roles/{}'.format(entity['role_id']) if inherited_assignment: formatted_entity['scope']['OS-INHERIT:inherited_to'] = 'projects' formatted_link = ( - '/OS-INHERIT%s/inherited_to_projects' % formatted_link + f'/OS-INHERIT{formatted_link}/inherited_to_projects' ) formatted_entity['links']['assignment'] = ks_flask.base_url( diff --git a/keystone/api/role_inferences.py b/keystone/api/role_inferences.py index 5412e3f8d2..b4ed9371fc 100644 --- a/keystone/api/role_inferences.py +++ b/keystone/api/role_inferences.py @@ -36,7 +36,7 @@ class RoleInferencesResource(flask_restful.Resource): for role_ref in PROVIDERS.role_api.list_roles() } - rules = dict() + rules = {} for ref in refs: implied_role_id = ref['implied_role_id'] prior_role_id = ref['prior_role_id'] @@ -49,10 +49,7 @@ class RoleInferencesResource(flask_restful.Resource): rules[prior_role_id] = implied inferences = [] - for ( - prior_id, - implied, - ) in rules.items(): + for prior_id, implied in rules.items(): prior_response = shared.build_prior_role_response_data( prior_id, role_dict[prior_id]['name'] ) diff --git a/keystone/api/roles.py b/keystone/api/roles.py index 9d9947731f..d45fba9c93 100644 --- a/keystone/api/roles.py +++ b/keystone/api/roles.py @@ -220,13 +220,12 @@ class RoleImplicationListResource(flask_restful.Resource): shared.build_implied_role_response_data(implied_role) ) response_json['links'] = { - 'self': ks_flask.base_url(path='/roles/%s/implies' % prior_role_id) + 'self': ks_flask.base_url(path=f'/roles/{prior_role_id}/implies') } return response_json class RoleImplicationResource(flask_restful.Resource): - def head(self, prior_role_id, implied_role_id=None): # TODO(morgan): deprecate "check_implied_role" policy, as a user must # have both check_implied_role and get_implied_role to use the head @@ -266,8 +265,7 @@ class RoleImplicationResource(flask_restful.Resource): ) response_json['links'] = { 'self': ks_flask.base_url( - path='/roles/%(prior)s/implies/%(implies)s' - % {'prior': prior_role_id, 'implies': implied_role_id} + path=f'/roles/{prior_role_id}/implies/{implied_role_id}' ) } return response_json diff --git a/keystone/api/trusts.py b/keystone/api/trusts.py index 165872364d..6e6bf44ca2 100644 --- a/keystone/api/trusts.py +++ b/keystone/api/trusts.py @@ -94,7 +94,7 @@ def _normalize_trust_roles(trust): trust['roles'] = trust_full_roles trust['roles_links'] = { - 'self': ks_flask.base_url(path='/%s/roles' % trust['id']), + 'self': ks_flask.base_url(path='/{}/roles'.format(trust['id'])), 'next': None, 'previous': None, } @@ -374,7 +374,6 @@ class TrustResource(ks_flask.ResourceBase): # URL additions and does not have a collection key/member_key, we use # the flask-restful Resource, not the keystone ResourceBase class RolesForTrustListResource(flask_restful.Resource): - @property def oslo_context(self): return flask.request.environ.get(context.REQUEST_CONTEXT_ENV, None) @@ -429,7 +428,6 @@ class RolesForTrustListResource(flask_restful.Resource): # URL additions and does not have a collection key/member_key, we use # the flask-restful Resource, not the keystone ResourceBase class RoleForTrustResource(flask_restful.Resource): - @property def oslo_context(self): return flask.request.environ.get(context.REQUEST_CONTEXT_ENV, None) diff --git a/keystone/api/users.py b/keystone/api/users.py index c9970663e7..50a0d360f8 100644 --- a/keystone/api/users.py +++ b/keystone/api/users.py @@ -66,7 +66,6 @@ def _convert_v3_to_ec2_credential(credential): def _format_token_entity(entity): - formatted_entity = entity.copy() access_token_id = formatted_entity['id'] user_id = formatted_entity.get('authorizing_user_id', '') @@ -76,8 +75,7 @@ def _format_token_entity(entity): formatted_entity.pop('access_secret') url = ( - '/users/%(user_id)s/OS-OAUTH1/access_tokens/%(access_token_id)s' - '/roles' % {'user_id': user_id, 'access_token_id': access_token_id} + f'/users/{user_id}/OS-OAUTH1/access_tokens/{access_token_id}' '/roles' ) formatted_entity.setdefault('links', {}) @@ -418,19 +416,19 @@ class UserOSEC2CredentialsResourceListCreate(_UserOSEC2CredBaseResource): PROVIDERS.identity_api.get_user(user_id) tenant_id = self.request_body_json.get('tenant_id') PROVIDERS.resource_api.get_project(tenant_id) - blob = dict( - access=uuid.uuid4().hex, - secret=uuid.uuid4().hex, - trust_id=self.oslo_context.trust_id, - ) + blob = { + 'access': uuid.uuid4().hex, + 'secret': uuid.uuid4().hex, + 'trust_id': self.oslo_context.trust_id, + } credential_id = utils.hash_access_key(blob['access']) - cred_data = dict( - user_id=user_id, - project_id=tenant_id, - blob=jsonutils.dumps(blob), - id=credential_id, - type=CRED_TYPE_EC2, - ) + cred_data = { + 'user_id': user_id, + 'project_id': tenant_id, + 'blob': jsonutils.dumps(blob), + 'id': credential_id, + 'type': CRED_TYPE_EC2, + } PROVIDERS.credential_api.create_credential(credential_id, cred_data) ref = _convert_v3_to_ec2_credential(cred_data) return self.wrap_member(ref), http.client.CREATED @@ -537,10 +535,10 @@ class OAuth1AccessTokenCRUDResource(_OAuth1ResourceBase): access_token = PROVIDERS.oauth_api.get_access_token(access_token_id) reason = ( 'Invalidating the token cache because an access token for ' - 'consumer %(consumer_id)s has been deleted. Authorization for ' + 'consumer {consumer_id} has been deleted. Authorization for ' 'users with OAuth tokens will be recalculated and enforced ' 'accordingly the next time they authenticate or validate a ' - 'token.' % {'consumer_id': access_token['consumer_id']} + 'token.'.format(consumer_id=access_token['consumer_id']) ) notifications.invalidate_token_cache_notification(reason) PROVIDERS.oauth_api.delete_access_token( @@ -752,8 +750,7 @@ class UserAppCredGetDeleteResource(ks_flask.ResourceBase): """ target = _update_request_user_id_attribute() ENFORCER.enforce_call( - action='identity:get_application_credential', - target_attr=target, + action='identity:get_application_credential', target_attr=target ) ref = PROVIDERS.application_credential_api.get_application_credential( application_credential_id @@ -787,11 +784,7 @@ class UserAccessRuleListResource(ks_flask.ResourceBase): GET/HEAD /v3/users/{user_id}/access_rules """ - filters = ( - 'service', - 'path', - 'method', - ) + filters = ('service', 'path', 'method') ENFORCER.enforce_call( action='identity:list_access_rules', filters=filters, diff --git a/keystone/api/validation/__init__.py b/keystone/api/validation/__init__.py index 305762aad9..7b39ac2f99 100644 --- a/keystone/api/validation/__init__.py +++ b/keystone/api/validation/__init__.py @@ -52,9 +52,7 @@ def _schema_validator( schema_validator.validate(target) -def request_body_schema( - schema: ty.Optional[ty.Dict[str, ty.Any]] = None, -): +def request_body_schema(schema: ty.Optional[ty.Dict[str, ty.Any]] = None): """Register a schema to validate request body. ``schema`` will be used for validating the request body just before the API @@ -88,9 +86,7 @@ def request_body_schema( return add_validator -def request_query_schema( - schema: ty.Optional[ty.Dict[str, ty.Any]] = None, -): +def request_query_schema(schema: ty.Optional[ty.Dict[str, ty.Any]] = None): """Register a schema to validate request query string parameters. ``schema`` will be used for validating request query strings just before @@ -113,13 +109,7 @@ def request_query_schema( else: req = flask.request.args - _schema_validator( - schema, - req, - args, - kwargs, - is_body=True, - ) + _schema_validator(schema, req, args, kwargs, is_body=True) return func(*args, **kwargs) wrapper._request_query_schema = schema @@ -129,9 +119,7 @@ def request_query_schema( return add_validator -def response_body_schema( - schema: ty.Optional[ty.Dict[str, ty.Any]] = None, -): +def response_body_schema(schema: ty.Optional[ty.Dict[str, ty.Any]] = None): """Register a schema to validate response body. ``schema`` will be used for validating the response body just after the API @@ -169,13 +157,7 @@ def response_body_schema( else: body = jsonutils.loads(_body) - _schema_validator( - schema, - body, - args, - kwargs, - is_body=True, - ) + _schema_validator(schema, body, args, kwargs, is_body=True) return response wrapper._response_body_schema = schema diff --git a/keystone/api/validation/parameter_types.py b/keystone/api/validation/parameter_types.py index 5da1c6448a..b85bc89273 100644 --- a/keystone/api/validation/parameter_types.py +++ b/keystone/api/validation/parameter_types.py @@ -11,6 +11,7 @@ # under the License. """Common parameter types for validating API requests.""" + from typing import Any empty: dict[str, Any] = {"type": "null"} @@ -24,22 +25,11 @@ name: dict[str, Any] = { boolean = { "type": ["boolean", "string"], - "enum": [ - True, - "True", - "TRUE", - "true", - False, - "False", - "FALSE", - "false", - ], + "enum": [True, "True", "TRUE", "true", False, "False", "FALSE", "false"], } -domain_id: dict[str, str] = { - "type": "string", -} +domain_id: dict[str, str] = {"type": "string"} parent_id: dict[str, str] = {"type": "string", "format": "uuid"} @@ -60,10 +50,7 @@ tags: dict[str, Any] = { # As OpenAPI request parameters this is an array of string serialized # as csv "openapi": { - "schema": { - "type": "array", - "items": _tag_name_property, - }, + "schema": {"type": "array", "items": _tag_name_property}, "style": "form", "explode": False, } diff --git a/keystone/api/validation/response_types.py b/keystone/api/validation/response_types.py index 6732f8895d..edd8afae33 100644 --- a/keystone/api/validation/response_types.py +++ b/keystone/api/validation/response_types.py @@ -11,6 +11,7 @@ # under the License. """Common field types for validating API responses.""" + from typing import Any # Common schema for resource `link` attribute diff --git a/keystone/api/validation/validators.py b/keystone/api/validation/validators.py index f9df03ce69..9367af20e3 100644 --- a/keystone/api/validation/validators.py +++ b/keystone/api/validation/validators.py @@ -26,10 +26,7 @@ from keystone.i18n import _ def _soft_validate_additional_properties( - validator, - additional_properties_value, - param_value, - schema, + validator, additional_properties_value, param_value, schema ): """Validator function. diff --git a/keystone/application_credential/backends/base.py b/keystone/application_credential/backends/base.py index 68c3f731ed..e947301a2b 100644 --- a/keystone/application_credential/backends/base.py +++ b/keystone/application_credential/backends/base.py @@ -18,7 +18,6 @@ from keystone import exception class ApplicationCredentialDriverBase(metaclass=abc.ABCMeta): - @abc.abstractmethod def authenticate(self, application_credential_id, secret): """Validate an application credential. diff --git a/keystone/application_credential/backends/sql.py b/keystone/application_credential/backends/sql.py index f3b02182c6..6d9dd567db 100644 --- a/keystone/application_credential/backends/sql.py +++ b/keystone/application_credential/backends/sql.py @@ -125,7 +125,6 @@ class ApplicationCredentialAccessRuleModel(sql.ModelBase, sql.ModelDictMixin): class ApplicationCredential(base.ApplicationCredentialDriverBase): - def _check_secret(self, secret, app_cred_ref): secret_hash = app_cred_ref['secret_hash'] return password_hashing.check_password(secret, secret_hash) diff --git a/keystone/assignment/backends/base.py b/keystone/assignment/backends/base.py index 6640537316..23d22cb3a7 100644 --- a/keystone/assignment/backends/base.py +++ b/keystone/assignment/backends/base.py @@ -21,7 +21,6 @@ CONF = keystone.conf.CONF class AssignmentDriverBase(metaclass=abc.ABCMeta): - def _get_list_limit(self): return CONF.assignment.list_limit or CONF.list_limit diff --git a/keystone/assignment/backends/sql.py b/keystone/assignment/backends/sql.py index cf480fd294..a9e7122cd8 100644 --- a/keystone/assignment/backends/sql.py +++ b/keystone/assignment/backends/sql.py @@ -41,7 +41,6 @@ class AssignmentType: class Assignment(base.AssignmentDriverBase): - @classmethod def default_role_driver(cls): return 'sql' @@ -55,7 +54,6 @@ class Assignment(base.AssignmentDriverBase): project_id=None, inherited_to_projects=False, ): - assignment_type = AssignmentType.calculate_type( user_id, group_id, project_id, domain_id ) @@ -182,11 +180,7 @@ class Assignment(base.AssignmentDriverBase): ) ) except sql.DBDuplicateEntry: - msg = 'User {} already has role {} in tenant {}'.format( - user_id, - role_id, - project_id, - ) + msg = f'User {user_id} already has role {role_id} in tenant {project_id}' raise exception.Conflict(type='role grant', details=msg) def remove_role_from_user_and_project(self, user_id, project_id, role_id): @@ -264,7 +258,6 @@ class Assignment(base.AssignmentDriverBase): project_ids=None, inherited_to_projects=None, ): - def denormalize_role(ref): assignment = {} if ref.type == AssignmentType.USER_PROJECT: diff --git a/keystone/assignment/core.py b/keystone/assignment/core.py index 32a3b61251..6fa4c9c971 100644 --- a/keystone/assignment/core.py +++ b/keystone/assignment/core.py @@ -71,8 +71,8 @@ class Manager(manager.Manager): self.event_callbacks = { notifications.ACTIONS.deleted: { - 'domain': [self._delete_domain_assignments], - }, + 'domain': [self._delete_domain_assignments] + } } def _delete_domain_assignments( @@ -209,7 +209,6 @@ class Manager(manager.Manager): inherited_to_projects=False, context=None, ): - # The parameters for this method must match the parameters for # create_grant so that the notifications.role_assignment decorator # will work. @@ -286,7 +285,6 @@ class Manager(manager.Manager): inherited_to_projects=False, context=None, ): - # The parameters for this method must match the parameters for # delete_grant so that the notifications.role_assignment decorator # will work. @@ -326,16 +324,9 @@ class Manager(manager.Manager): target_id = project_id reason = ( - 'Invalidating the token cache because role %(role_id)s was ' - 'removed from %(actor_type)s %(actor_id)s on %(target_type)s ' - '%(target_id)s.' - % { - 'role_id': role_id, - 'actor_type': actor_type, - 'actor_id': actor_id, - 'target_type': target_type, - 'target_id': target_id, - } + f'Invalidating the token cache because role {role_id} was ' + f'removed from {actor_type} {actor_id} on {target_type} ' + f'{target_id}.' ) notifications.invalidate_token_cache_notification(reason) @@ -429,7 +420,6 @@ class Manager(manager.Manager): inherited_to_projects=False, initiator=None, ): - # check if role exist before any processing PROVIDERS.role_api.get_role(role_id) @@ -760,7 +750,7 @@ class Manager(manager.Manager): implied_roles_cache = {} role_refs_to_check = list(role_refs) ref_results = list(role_refs) - checked_role_refs = list() + checked_role_refs = [] while role_refs_to_check: next_ref = role_refs_to_check.pop() checked_role_refs.append(next_ref) @@ -1348,9 +1338,8 @@ class Manager(manager.Manager): role = PROVIDERS.role_api.get_role(role_id) if role.get('domain_id'): raise exception.ValidationError( - 'Role %(role_id)s is a domain-specific role. Unable to use ' + f'Role {role_id} is a domain-specific role. Unable to use ' 'a domain-specific role in a system assignment.' - % {'role_id': role_id} ) target_id = self._SYSTEM_SCOPE_TOKEN assignment_type = self._USER_SYSTEM @@ -1420,9 +1409,8 @@ class Manager(manager.Manager): role = PROVIDERS.role_api.get_role(role_id) if role.get('domain_id'): raise exception.ValidationError( - 'Role %(role_id)s is a domain-specific role. Unable to use ' + f'Role {role_id} is a domain-specific role. Unable to use ' 'a domain-specific role in a system assignment.' - % {'role_id': role_id} ) target_id = self._SYSTEM_SCOPE_TOKEN assignment_type = self._GROUP_SYSTEM @@ -1556,10 +1544,10 @@ class RoleManager(manager.Manager): notifications.Audit.deleted(self._ROLE, role_id, initiator) self.get_role.invalidate(self, role_id) reason = ( - 'Invalidating the token cache because role %(role_id)s has been ' + f'Invalidating the token cache because role {role_id} has been ' 'removed. Role assignments for users will be recalculated and ' 'enforced accordingly the next time they authenticate or validate ' - 'a token' % {'role_id': role_id} + 'a token' ) notifications.invalidate_token_cache_notification(reason) COMPUTED_ASSIGNMENTS_REGION.invalidate() diff --git a/keystone/assignment/role_backends/base.py b/keystone/assignment/role_backends/base.py index 26dc0f1cfc..ada9d8ddf0 100644 --- a/keystone/assignment/role_backends/base.py +++ b/keystone/assignment/role_backends/base.py @@ -29,7 +29,6 @@ CONF = keystone.conf.CONF class RoleDriverBase(metaclass=abc.ABCMeta): - def _get_list_limit(self): return CONF.role.list_limit or CONF.list_limit diff --git a/keystone/assignment/role_backends/resource_options.py b/keystone/assignment/role_backends/resource_options.py index 0b022942b8..85943091f6 100644 --- a/keystone/assignment/role_backends/resource_options.py +++ b/keystone/assignment/role_backends/resource_options.py @@ -19,9 +19,7 @@ ROLE_OPTIONS_REGISTRY = resource_options.ResourceOptionRegistry('ROLE') # NOTE(morgan): wrap this in a function for testing purposes. # This is called on import by design. def register_role_options(): - for opt in [ - ro_opt.IMMUTABLE_OPT, - ]: + for opt in [ro_opt.IMMUTABLE_OPT]: ROLE_OPTIONS_REGISTRY.register_option(opt) diff --git a/keystone/assignment/role_backends/sql.py b/keystone/assignment/role_backends/sql.py index c050bf3aa3..e1083a7630 100644 --- a/keystone/assignment/role_backends/sql.py +++ b/keystone/assignment/role_backends/sql.py @@ -20,7 +20,6 @@ from keystone import exception class Role(base.RoleDriverBase): - @sql.handle_conflicts(conflict_type='role') def create_role(self, role_id, role): with sql.session_for_write() as session: diff --git a/keystone/assignment/role_backends/sql_model.py b/keystone/assignment/role_backends/sql_model.py index 602b2c8ad7..bc14fe5043 100644 --- a/keystone/assignment/role_backends/sql_model.py +++ b/keystone/assignment/role_backends/sql_model.py @@ -19,7 +19,6 @@ from keystone.common import sql class RoleTable(sql.ModelBase, sql.ModelDictMixinWithExtras): - def to_dict(self, include_extra_dict=False): d = super().to_dict(include_extra_dict=include_extra_dict) if d['domain_id'] == base.NULL_DOMAIN_ID: @@ -96,7 +95,7 @@ class ImpliedRoleTable(sql.ModelBase, sql.ModelDictMixin): overrides the `to_dict` function from the base class to avoid having an `extra` field. """ - d = dict() + d = {} for attr in self.__class__.attributes: d[attr] = getattr(self, attr) return d diff --git a/keystone/auth/core.py b/keystone/auth/core.py index bc70cb3a7e..b063ebf4d2 100644 --- a/keystone/auth/core.py +++ b/keystone/auth/core.py @@ -38,7 +38,7 @@ def _get_auth_driver_manager(namespace, plugin_name): def load_auth_method(method): plugin_name = CONF.auth.get(method) or 'default' - namespace = 'keystone.auth.%s' % method + namespace = f'keystone.auth.{method}' driver_manager = _get_auth_driver_manager(namespace, plugin_name) return driver_manager.driver @@ -261,7 +261,7 @@ class AuthInfo(provider_api.ProviderAPIMixin): app_cred_api = PROVIDERS.application_credential_api app_creds = app_cred_api.list_application_credentials(user_id, hints) if len(app_creds) != 1: - message = "Could not find application credential: %s" % name + message = f"Could not find application credential: {name}" tr_message = _("Could not find application credential: %s") % name LOG.warning(message) raise exception.Unauthorized(tr_message) diff --git a/keystone/auth/plugins/base.py b/keystone/auth/plugins/base.py index 0d8d2bb96d..928af409d4 100644 --- a/keystone/auth/plugins/base.py +++ b/keystone/auth/plugins/base.py @@ -45,13 +45,7 @@ class AuthMethodHandler(provider_api.ProviderAPIMixin, metaclass=abc.ABCMeta): to the re-scope type action. Here's an example of ``response_data`` on successful authentication:: - { - "methods": [ - "password", - "token" - ], - "user_id": "abc123" - } + {"methods": ["password", "token"], "user_id": "abc123"} Plugins are invoked in the order in which they are specified in the ``methods`` attribute of the ``identity`` object. For example, @@ -61,23 +55,12 @@ class AuthMethodHandler(provider_api.ProviderAPIMixin, metaclass=abc.ABCMeta): { "auth": { "identity": { - "custom-plugin": { - "custom-data": "sdfdfsfsfsdfsf" - }, - "methods": [ - "custom-plugin", - "password", - "token" - ], + "custom-plugin": {"custom-data": "sdfdfsfsfsdfsf"}, + "methods": ["custom-plugin", "password", "token"], "password": { - "user": { - "id": "s23sfad1", - "password": "secret" - } + "user": {"id": "s23sfad1", "password": "secret"} }, - "token": { - "id": "sdfafasdfsfasfasdfds" - } + "token": {"id": "sdfafasdfsfasfasdfds"}, } } } diff --git a/keystone/auth/plugins/core.py b/keystone/auth/plugins/core.py index 92e84e7bfe..0513db88dd 100644 --- a/keystone/auth/plugins/core.py +++ b/keystone/auth/plugins/core.py @@ -27,9 +27,7 @@ CONF = keystone.conf.CONF LOG = log.getLogger(__name__) PROVIDERS = provider_api.ProviderAPIs _NOTIFY_OP = 'authenticate' -_NOTIFY_EVENT = '{service}.{event}'.format( - service=notifications.SERVICE, event=_NOTIFY_OP -) +_NOTIFY_EVENT = f'{notifications.SERVICE}.{_NOTIFY_OP}' def construct_method_map_from_config(): @@ -38,7 +36,7 @@ def construct_method_map_from_config(): :returns: a dictionary containing the methods and their indexes """ - method_map = dict() + method_map = {} method_index = 1 for method in CONF.auth.methods: method_map[method_index] = method @@ -99,7 +97,6 @@ def convert_integer_to_method_list(method_int): class BaseUserInfo(provider_api.ProviderAPIMixin): - @classmethod def create(cls, auth_payload, method_name): user_auth_info = cls() @@ -213,7 +210,6 @@ class BaseUserInfo(provider_api.ProviderAPIMixin): class UserAuthInfo(BaseUserInfo): - def __init__(self): super().__init__() self.password = None @@ -225,7 +221,6 @@ class UserAuthInfo(BaseUserInfo): class TOTPUserInfo(BaseUserInfo): - def __init__(self): super().__init__() self.passcode = None diff --git a/keystone/auth/plugins/mapped.py b/keystone/auth/plugins/mapped.py index bfc1cb4fc5..236905b2eb 100644 --- a/keystone/auth/plugins/mapped.py +++ b/keystone/auth/plugins/mapped.py @@ -34,7 +34,6 @@ PROVIDERS = provider_api.ProviderAPIs class Mapped(base.AuthMethodHandler): - def _get_token_ref(self, auth_payload): token_id = auth_payload['id'] return PROVIDERS.token_provider_api.validate_token(token_id) @@ -184,7 +183,6 @@ def handle_unscoped_token( assignment_api, role_api, ): - def validate_shadow_mapping( shadow_projects, existing_roles, user_domain_id, idp_id ): @@ -300,7 +298,6 @@ def handle_unscoped_token( ) if 'projects' in mapped_properties: - existing_roles = { role['name']: role for role in role_api.list_roles() } diff --git a/keystone/auth/plugins/password.py b/keystone/auth/plugins/password.py index 394bdb19e1..a82c326d07 100644 --- a/keystone/auth/plugins/password.py +++ b/keystone/auth/plugins/password.py @@ -23,7 +23,6 @@ PROVIDERS = provider_api.ProviderAPIs class Password(base.AuthMethodHandler): - def authenticate(self, auth_payload): """Try to authenticate against the identity backend.""" response_data = {} diff --git a/keystone/auth/plugins/token.py b/keystone/auth/plugins/token.py index 560be75b33..31675e1952 100644 --- a/keystone/auth/plugins/token.py +++ b/keystone/auth/plugins/token.py @@ -29,7 +29,6 @@ PROVIDERS = provider_api.ProviderAPIs class Token(base.AuthMethodHandler): - def _get_token_ref(self, auth_payload): token_id = auth_payload['id'] return PROVIDERS.token_provider_api.validate_token(token_id) @@ -59,7 +58,6 @@ class Token(base.AuthMethodHandler): def token_authenticate(token): response_data = {} try: - # Do not allow tokens used for delegation to # create another token, or perform any changes of # state in Keystone. To do so is to invite elevation of diff --git a/keystone/auth/plugins/totp.py b/keystone/auth/plugins/totp.py index 15606b6a7f..0327b01175 100644 --- a/keystone/auth/plugins/totp.py +++ b/keystone/auth/plugins/totp.py @@ -90,7 +90,6 @@ def _generate_totp_passcodes(secret, included_previous_windows=0): class TOTP(base.AuthMethodHandler): - def authenticate(self, auth_payload): """Try to authenticate using TOTP.""" response_data = {} diff --git a/keystone/auth/schema.py b/keystone/auth/schema.py index 17fe2be380..0e075727be 100644 --- a/keystone/auth/schema.py +++ b/keystone/auth/schema.py @@ -21,57 +21,34 @@ token_issue = { 'identity': { 'type': 'object', 'properties': { - 'methods': { - 'type': 'array', - 'items': { - 'type': 'string', - }, - }, + 'methods': {'type': 'array', 'items': {'type': 'string'}}, 'password': { 'type': 'object', 'properties': { 'user': { 'type': 'object', 'properties': { - 'id': { - 'type': 'string', - }, - 'name': { - 'type': 'string', - }, - 'password': { - 'type': 'string', - }, + 'id': {'type': 'string'}, + 'name': {'type': 'string'}, + 'password': {'type': 'string'}, 'domain': { 'type': 'object', 'properties': { - 'id': { - 'type': 'string', - }, - 'name': { - 'type': 'string', - }, + 'id': {'type': 'string'}, + 'name': {'type': 'string'}, }, }, }, - }, + } }, }, 'token': { 'type': 'object', - 'properties': { - 'id': { - 'type': 'string', - }, - }, - 'required': [ - 'id', - ], + 'properties': {'id': {'type': 'string'}}, + 'required': ['id'], }, }, - 'required': [ - 'methods', - ], + 'required': ['methods'], }, 'scope': { # For explicit unscoped authentication the type should not be @@ -85,21 +62,13 @@ token_issue = { 'project': { 'type': 'object', 'properties': { - 'name': { - 'type': 'string', - }, - 'id': { - 'type': 'string', - }, + 'name': {'type': 'string'}, + 'id': {'type': 'string'}, 'domain': { 'type': 'object', 'properties': { - 'id': { - 'type': 'string', - }, - 'name': { - 'type': 'string', - }, + 'id': {'type': 'string'}, + 'name': {'type': 'string'}, }, }, }, @@ -107,21 +76,13 @@ token_issue = { 'domain': { 'type': 'object', 'properties': { - 'id': { - 'type': 'string', - }, - 'name': { - 'type': 'string', - }, + 'id': {'type': 'string'}, + 'name': {'type': 'string'}, }, }, 'OS-TRUST:trust': { 'type': 'object', - 'properties': { - 'id': { - 'type': 'string', - }, - }, + 'properties': {'id': {'type': 'string'}}, }, 'system': { 'type': 'object', @@ -130,9 +91,7 @@ token_issue = { }, }, }, - 'required': [ - 'identity', - ], + 'required': ['identity'], } diff --git a/keystone/catalog/backends/base.py b/keystone/catalog/backends/base.py index b3562c2ee2..b1a9c8ac12 100644 --- a/keystone/catalog/backends/base.py +++ b/keystone/catalog/backends/base.py @@ -242,21 +242,23 @@ class CatalogDriverBase(provider_api.ProviderAPIMixin, metaclass=abc.ABCMeta): [ { "endpoints": [ - { - "interface": "public", - "id": "--endpoint-id--", - "region": "RegionOne", - "url": "http://external:8776/v1/--project-id--" - }, - { - "interface": "internal", - "id": "--endpoint-id--", - "region": "RegionOne", - "url": "http://internal:8776/v1/--project-id--" - }], - "id": "--service-id--", - "type": "volume" - }] + { + "interface": "public", + "id": "--endpoint-id--", + "region": "RegionOne", + "url": "http://external:8776/v1/--project-id--", + }, + { + "interface": "internal", + "id": "--endpoint-id--", + "region": "RegionOne", + "url": "http://internal:8776/v1/--project-id--", + }, + ], + "id": "--service-id--", + "type": "volume", + } + ] :returns: A list representing the service catalog or an empty list :raises keystone.exception.NotFound: If the endpoint doesn't exist. diff --git a/keystone/catalog/backends/sql.py b/keystone/catalog/backends/sql.py index 9ae94c99e6..2dd8aa73f8 100644 --- a/keystone/catalog/backends/sql.py +++ b/keystone/catalog/backends/sql.py @@ -333,7 +333,7 @@ class Catalog(base.CatalogDriverBase): } catalog.setdefault(region, {}) catalog[region].setdefault(service_type, default_service) - interface_url = '%sURL' % endpoint['interface'] + interface_url = '{}URL'.format(endpoint['interface']) catalog[region][service_type][interface_url] = url return catalog @@ -355,12 +355,7 @@ class Catalog(base.CatalogDriverBase): d.update({'user_id': user_id}) silent_keyerror_failures = [] if project_id: - d.update( - { - 'tenant_id': project_id, - 'project_id': project_id, - } - ) + d.update({'tenant_id': project_id, 'project_id': project_id}) else: silent_keyerror_failures = ['tenant_id', 'project_id'] @@ -463,8 +458,7 @@ class Catalog(base.CatalogDriverBase): def _get_project_endpoint_ref(self, session, endpoint_id, project_id): endpoint_filter_ref = session.get( - ProjectEndpoint, - (endpoint_id, project_id), + ProjectEndpoint, (endpoint_id, project_id) ) if endpoint_filter_ref is None: msg = _( @@ -576,8 +570,7 @@ class Catalog(base.CatalogDriverBase): self, session, endpoint_group_id, project_id ): endpoint_group_project_ref = session.get( - ProjectEndpointGroupMembership, - (endpoint_group_id, project_id), + ProjectEndpointGroupMembership, (endpoint_group_id, project_id) ) if endpoint_group_project_ref is None: msg = _('Endpoint Group Project Association not found') diff --git a/keystone/catalog/backends/templated.py b/keystone/catalog/backends/templated.py index 5285523d01..a4f508e0ae 100644 --- a/keystone/catalog/backends/templated.py +++ b/keystone/catalog/backends/templated.py @@ -166,11 +166,7 @@ class Catalog(base.CatalogDriverBase): for key in service_ref: if key.endswith('URL'): interface = key[:-3] - endpoint_id = '{}-{}-{}'.format( - region_id, - service_type, - interface, - ) + endpoint_id = f'{region_id}-{service_type}-{interface}' yield { 'id': endpoint_id, 'service_id': service_type, @@ -215,16 +211,10 @@ class Catalog(base.CatalogDriverBase): silent_keyerror_failures = [] if project_id: substitutions.update( - { - 'tenant_id': project_id, - 'project_id': project_id, - } + {'tenant_id': project_id, 'project_id': project_id} ) else: - silent_keyerror_failures = [ - 'tenant_id', - 'project_id', - ] + silent_keyerror_failures = ['tenant_id', 'project_id'] catalog = {} # TODO(davechen): If there is service with no endpoints, we should diff --git a/keystone/cmd/bootstrap.py b/keystone/cmd/bootstrap.py index 6c596bbe12..9ac166e103 100644 --- a/keystone/cmd/bootstrap.py +++ b/keystone/cmd/bootstrap.py @@ -26,7 +26,6 @@ PROVIDERS = provider_api.ProviderAPIs class Bootstrapper: - def __init__(self): backends.load_backends() diff --git a/keystone/cmd/cli.py b/keystone/cmd/cli.py index 622fde22c4..93bf024144 100644 --- a/keystone/cmd/cli.py +++ b/keystone/cmd/cli.py @@ -52,7 +52,6 @@ LOG = log.getLogger(__name__) class BaseApp: - name: str @classmethod @@ -536,8 +535,7 @@ class ResetLastActive(BaseApp): raise SystemExit('reset_last_active aborted.') LOG.debug( - "Resetting null values to current time %s", - timeutils.utcnow(), + "Resetting null values to current time %s", timeutils.utcnow() ) drivers = backends.load_backends() identity_api = drivers['identity_api'] @@ -565,14 +563,14 @@ class BasePermissionsSetup(BaseApp): if a: keystone_user_id = utils.get_unix_user(a)[0] except KeyError: - raise ValueError("Unknown user '%s' in --keystone-user" % a) + raise ValueError(f"Unknown user '{a}' in --keystone-user") try: a = CONF.command.keystone_group if a: keystone_group_id = utils.get_unix_group(a)[0] except KeyError: - raise ValueError("Unknown group '%s' in --keystone-group" % a) + raise ValueError(f"Unknown group '{a}' in --keystone-group") return keystone_user_id, keystone_group_id @@ -1180,7 +1178,6 @@ def _domain_config_finder(conf_dir): class DomainConfigUploadFiles: - def __init__(self, domain_config_finder=_domain_config_finder): super().__init__() self.load_backends() @@ -1518,12 +1515,9 @@ class MappingEngineTester(BaseApp): tester.normalize_assertion() if CONF.command.engine_debug: + print(f"Using Rules:\n{jsonutils.dumps(tester.rules, indent=2)}") print( - "Using Rules:\n%s" % (jsonutils.dumps(tester.rules, indent=2)) - ) - print( - "Using Assertion:\n%s" - % (jsonutils.dumps(tester.assertion, indent=2)) + f"Using Assertion:\n{jsonutils.dumps(tester.assertion, indent=2)}" ) rp = mapping_engine.RuleProcessor( diff --git a/keystone/cmd/doctor/__init__.py b/keystone/cmd/doctor/__init__.py index 11974aca0d..690d252c05 100644 --- a/keystone/cmd/doctor/__init__.py +++ b/keystone/cmd/doctor/__init__.py @@ -50,8 +50,9 @@ def diagnose(): # Some symptoms may take a long time to check, so let's keep # curious users posted on our progress as we go. print( - 'Checking for %s...' - % symptom.__name__[len(SYMPTOM_PREFIX) :].replace('_', ' ') + 'Checking for {}...'.format( + symptom.__name__[len(SYMPTOM_PREFIX) :].replace('_', ' ') + ) ) # All symptoms are just callables that return true when they match the @@ -65,9 +66,7 @@ def diagnose(): # passing a string here. Also, we include a line break here to # visually separate the symptom's description from any other # checks -- it provides a better user experience. - print( - _('\nWARNING: %s') % _(symptom.__doc__) - ) # noqa: See comment above. + print(_('\nWARNING: %s') % _(symptom.__doc__)) # noqa: See comment above. return symptoms_found diff --git a/keystone/cmd/doctor/ldap.py b/keystone/cmd/doctor/ldap.py index 3406369111..56949cec90 100644 --- a/keystone/cmd/doctor/ldap.py +++ b/keystone/cmd/doctor/ldap.py @@ -85,10 +85,10 @@ def symptom_LDAP_file_based_domain_specific_configs(): if invalid_files: invalid_str = ', '.join(invalid_files) print( - 'Warning: The following non-config files were found: %s\n' + f'Warning: The following non-config files were found: {invalid_str}\n' 'If they are intended to be config files then rename them ' 'to the form of `keystone..conf`. ' - 'Otherwise, ignore this warning' % invalid_str + 'Otherwise, ignore this warning' ) return True else: diff --git a/keystone/cmd/idutils.py b/keystone/cmd/idutils.py index 2ed18306b3..ee33083608 100644 --- a/keystone/cmd/idutils.py +++ b/keystone/cmd/idutils.py @@ -28,7 +28,6 @@ PROVIDERS = provider_api.ProviderAPIs class Identity: - def __init__(self): backends.load_backends() diff --git a/keystone/cmd/status.py b/keystone/cmd/status.py index d21af98ce6..70ac422b19 100644 --- a/keystone/cmd/status.py +++ b/keystone/cmd/status.py @@ -54,13 +54,14 @@ class Checks(upgradecheck.UpgradeCommands): if any(failed_rules): return upgradecheck.Result( upgradecheck.Code.FAILURE, - "Policy check string for rules \"%s\" are overridden to " + "Policy check string for rules \"{}\" are overridden to " "\"\", \"@\", or []. In the next release, this will cause " "these rules to be fully permissive as hardcoded enforcement " "will be removed. To correct this issue, either stop " "overriding these rules in config to accept the defaults, or " - "explicitly set check strings that are not empty." - % "\", \"".join(failed_rules), + "explicitly set check strings that are not empty.".format( + "\", \"".join(failed_rules) + ), ) return upgradecheck.Result( upgradecheck.Code.SUCCESS, 'Trust policies are safe.' @@ -70,11 +71,7 @@ class Checks(upgradecheck.UpgradeCommands): hints = driver_hints.Hints() hints.add_filter('domain_id', None) # Only check global roles roles = PROVIDERS.role_api.list_roles(hints=hints) - default_roles = ( - 'admin', - 'member', - 'reader', - ) + default_roles = ('admin', 'member', 'reader') failed_roles = [] for role in [r for r in roles if r['name'] in default_roles]: if not role.get('options', {}).get('immutable'): @@ -82,7 +79,7 @@ class Checks(upgradecheck.UpgradeCommands): if any(failed_roles): return upgradecheck.Result( upgradecheck.Code.FAILURE, - "Roles are not immutable: %s" % ", ".join(failed_roles), + "Roles are not immutable: {}".format(", ".join(failed_roles)), ) return upgradecheck.Result( upgradecheck.Code.SUCCESS, "Default roles are immutable." diff --git a/keystone/common/cache/_context_cache.py b/keystone/common/cache/_context_cache.py index 5def5e05af..5e17ed2a36 100644 --- a/keystone/common/cache/_context_cache.py +++ b/keystone/common/cache/_context_cache.py @@ -11,6 +11,7 @@ # under the License. """A dogpile.cache proxy that caches objects in the request local cache.""" + from dogpile.cache import api from dogpile.cache import proxy from oslo_context import context as oslo_context @@ -28,7 +29,6 @@ def _register_model_handler(handler_class): class _ResponseCacheProxy(proxy.ProxyBackend): - __key_pfx = '_request_cache_%s' def _get_request_context(self): diff --git a/keystone/common/cache/core.py b/keystone/common/cache/core.py index 6a968956b4..5a6dad6e79 100644 --- a/keystone/common/cache/core.py +++ b/keystone/common/cache/core.py @@ -27,7 +27,6 @@ CONF = keystone.conf.CONF class RegionInvalidationManager: - REGION_KEY_PREFIX = '<<>>:' def __init__(self, invalidation_region, region_name): @@ -53,7 +52,6 @@ class RegionInvalidationManager: class DistributedInvalidationStrategy(region.RegionInvalidationStrategy): - def __init__(self, region_manager): self._region_manager = region_manager @@ -165,7 +163,7 @@ def configure_invalidation_region(): config_dict['expiration_time'] = None # we don't want an expiration CACHE_INVALIDATION_REGION.configure_from_config( - config_dict, '%s.' % CONF.cache.config_prefix + config_dict, f'{CONF.cache.config_prefix}.' ) # NOTE(breton): Wrap the cache invalidation region to avoid excessive diff --git a/keystone/common/context.py b/keystone/common/context.py index f42166ee06..f4518e46c1 100644 --- a/keystone/common/context.py +++ b/keystone/common/context.py @@ -22,7 +22,6 @@ def _prop(name): class RequestContext(oslo_context.RequestContext): - def __init__(self, **kwargs): self.username = kwargs.pop('username', None) self.project_tag_name = kwargs.pop('project_tag_name', None) diff --git a/keystone/common/driver_hints.py b/keystone/common/driver_hints.py index d270e0e65d..29dcb1add0 100644 --- a/keystone/common/driver_hints.py +++ b/keystone/common/driver_hints.py @@ -96,7 +96,7 @@ class Hints: def __init__(self): self.limit = None - self.filters = list() + self.filters = [] self.cannot_match = False def add_filter( diff --git a/keystone/common/fernet_utils.py b/keystone/common/fernet_utils.py index 66a15ff663..36dd70671b 100644 --- a/keystone/common/fernet_utils.py +++ b/keystone/common/fernet_utils.py @@ -34,7 +34,6 @@ NULL_KEY = base64.urlsafe_b64encode(b'\x00' * 32) class FernetUtils: - def __init__(self, key_repository, max_active_keys, config_group): self.key_repository = key_repository self.max_active_keys = max_active_keys @@ -157,8 +156,8 @@ class FernetUtils: LOG.info('Become a valid new key: %s', valid_key_file) def _get_key_files(self, key_repo): - key_files = dict() - keys = dict() + key_files = {} + keys = {} for filename in os.listdir(key_repo): path = os.path.join(key_repo, str(filename)) if os.path.isfile(path): diff --git a/keystone/common/json_home.py b/keystone/common/json_home.py index b3371c1091..fe4f2fdb0f 100644 --- a/keystone/common/json_home.py +++ b/keystone/common/json_home.py @@ -20,34 +20,28 @@ from keystone.i18n import _ def build_v3_resource_relation(resource_name): - return ( - 'https://docs.openstack.org/api/openstack-identity/3/rel/%s' - % resource_name - ) + return f'https://docs.openstack.org/api/openstack-identity/3/rel/{resource_name}' def build_v3_extension_resource_relation( extension_name, extension_version, resource_name ): return ( - 'https://docs.openstack.org/api/openstack-identity/3/ext/%s/%s/rel/' - '%s' % (extension_name, extension_version, resource_name) + f'https://docs.openstack.org/api/openstack-identity/3/ext/{extension_name}/{extension_version}/rel/' + f'{resource_name}' ) def build_v3_parameter_relation(parameter_name): - return ( - 'https://docs.openstack.org/api/openstack-identity/3/param/%s' - % parameter_name - ) + return f'https://docs.openstack.org/api/openstack-identity/3/param/{parameter_name}' def build_v3_extension_parameter_relation( extension_name, extension_version, parameter_name ): return ( - 'https://docs.openstack.org/api/openstack-identity/3/ext/%s/%s/param/' - '%s' % (extension_name, extension_version, parameter_name) + f'https://docs.openstack.org/api/openstack-identity/3/ext/{extension_name}/{extension_version}/param/' + f'{parameter_name}' ) diff --git a/keystone/common/manager.py b/keystone/common/manager.py index aeffe8c79b..eef40bb953 100644 --- a/keystone/common/manager.py +++ b/keystone/common/manager.py @@ -86,10 +86,8 @@ class _TraceMeta(type): @staticmethod def wrapper(__f, __classname): __argspec = inspect.getfullargspec(__f) - __fn_info = '{module}.{classname}.{funcname}'.format( - module=inspect.getmodule(__f).__name__, - classname=__classname, - funcname=__f.__name__, + __fn_info = ( + f'{inspect.getmodule(__f).__name__}.{__classname}.{__f.__name__}' ) # NOTE(morganfainberg): Omit "cls" and "self" when printing trace logs # the index can be calculated at wrap time rather than at runtime. diff --git a/keystone/common/password_hashers/bcrypt.py b/keystone/common/password_hashers/bcrypt.py index 037538d8d8..3d18b14076 100644 --- a/keystone/common/password_hashers/bcrypt.py +++ b/keystone/common/password_hashers/bcrypt.py @@ -26,11 +26,7 @@ class Bcrypt(password_hashers.PasswordHasher): ident_values: set[str] = {"$2$", "$2a$", "$2b$", "$2x$", "$2y$"} @staticmethod - def hash( - password: bytes, - rounds: int = 12, - **kwargs, - ) -> str: + def hash(password: bytes, rounds: int = 12, **kwargs) -> str: """Generate password hash string with ident and params https://pypi.org/project/bcrypt/ @@ -66,11 +62,7 @@ class Bcrypt_sha256(password_hashers.PasswordHasher): prefix: str = "$bcrypt-sha256$" @staticmethod - def hash( - password: bytes, - rounds: int = 12, - **kwargs, - ) -> str: + def hash(password: bytes, rounds: int = 12, **kwargs) -> str: """Generate password hash string with ident and params https://pypi.org/project/bcrypt/ diff --git a/keystone/common/password_hashers/pbkdf2.py b/keystone/common/password_hashers/pbkdf2.py index 98794ce1b3..07629fc415 100644 --- a/keystone/common/password_hashers/pbkdf2.py +++ b/keystone/common/password_hashers/pbkdf2.py @@ -29,11 +29,7 @@ class Sha512(password_hashers.PasswordHasher): hash_algo = hashes.SHA512() @staticmethod - def hash( - password: bytes, - salt_size: int = 16, - rounds: int = 25000, - ) -> str: + def hash(password: bytes, salt_size: int = 16, rounds: int = 25000) -> str: """Generate password hash string with ident and params https://cryptography.io/en/stable/hazmat/primitives/key-derivation-functions/#pbkdf2 @@ -49,10 +45,7 @@ class Sha512(password_hashers.PasswordHasher): # Prepave the kdf function with params kdf = PBKDF2HMAC( - algorithm=Sha512.hash_algo, - length=64, - salt=salt, - iterations=rounds, + algorithm=Sha512.hash_algo, length=64, salt=salt, iterations=rounds ) # derive - create a digest @@ -101,10 +94,7 @@ class Sha512(password_hashers.PasswordHasher): # Prepave the kdf function with params kdf = PBKDF2HMAC( - algorithm=Sha512.hash_algo, - length=64, - salt=salt, - iterations=rounds, + algorithm=Sha512.hash_algo, length=64, salt=salt, iterations=rounds ) # Verify the key. diff --git a/keystone/common/policies/base.py b/keystone/common/policies/base.py index 6de301c5d3..97970e4e03 100644 --- a/keystone/common/policies/base.py +++ b/keystone/common/policies/base.py @@ -28,9 +28,7 @@ RULE_ADMIN_OR_TARGET_PROJECT = ( ) RULE_ADMIN_OR_TOKEN_SUBJECT = 'rule:admin_or_token_subject' # nosec RULE_REVOKE_EVENT_OR_ADMIN = 'rule:revoke_event_or_admin' -RULE_SERVICE_ADMIN_OR_TOKEN_SUBJECT = ( - 'rule:service_admin_or_token_subject' # nosec -) +RULE_SERVICE_ADMIN_OR_TOKEN_SUBJECT = 'rule:service_admin_or_token_subject' # nosec RULE_SERVICE_OR_ADMIN = 'rule:service_or_admin' RULE_TRUST_OWNER = 'user_id:%(trust.trustor_user_id)s' diff --git a/keystone/common/policies/project.py b/keystone/common/policies/project.py index b65a877a13..0125bfa96d 100644 --- a/keystone/common/policies/project.py +++ b/keystone/common/policies/project.py @@ -40,9 +40,7 @@ SYSTEM_ADMIN_OR_DOMAIN_ADMIN_OR_PROJECT_ADMIN = ( # /v3/users/{user_id}/project path. SYSTEM_READER_OR_DOMAIN_READER_OR_OWNER = ( # System reader policy - '(' - + base.SYSTEM_READER - + ') or ' + '(' + base.SYSTEM_READER + ') or ' # Domain reader policy '(role:reader and domain_id:%(target.user.domain_id)s) or ' # User accessing the API with a token they've obtained, matching diff --git a/keystone/common/provider_api.py b/keystone/common/provider_api.py index 02a54f2f0f..75d74c8614 100644 --- a/keystone/common/provider_api.py +++ b/keystone/common/provider_api.py @@ -35,7 +35,7 @@ class ProviderAPIRegistry: try: return self.__registry[item] except KeyError: - raise AttributeError("'ProviderAPIs' has no attribute %s" % item) + raise AttributeError(f"'ProviderAPIs' has no attribute {item}") def __setattr__(self, key, value): """Do not allow setting values on the registry object.""" @@ -58,9 +58,8 @@ class ProviderAPIRegistry: if name in self.__registry: raise DuplicateProviderError( - '`%(name)s` has already been registered as an api ' - 'provider by `%(prov)r`' - % {'name': name, 'prov': self.__registry[name]} + f'`{name}` has already been registered as an api ' + f'provider by `{self.__registry[name]!r}`' ) self.__registry[name] = obj diff --git a/keystone/common/rbac_enforcer/enforcer.py b/keystone/common/rbac_enforcer/enforcer.py index 5d9489fb78..87253e458e 100644 --- a/keystone/common/rbac_enforcer/enforcer.py +++ b/keystone/common/rbac_enforcer/enforcer.py @@ -242,7 +242,7 @@ class RBACEnforcer: member_name = None func = getattr(resource, 'get_member_from_driver', None) if member_name is not None and callable(func): - key = '%s_id' % member_name + key = f'{member_name}_id' if key in (flask.request.view_args or {}): # NOTE(morgan): For most correct setup, instantiate the # view_class. There is no current support for passing diff --git a/keystone/common/render_token.py b/keystone/common/render_token.py index bef49b0fc1..dbaab32c4b 100644 --- a/keystone/common/render_token.py +++ b/keystone/common/render_token.py @@ -107,11 +107,11 @@ def render_token_response_from_model(token, include_catalog=True): token_reference['token']['service_providers'] = sps if token.is_federated: PROVIDERS.federation_api.get_idp(token.identity_provider_id) - federated_dict = dict( - groups=token.federated_groups, - identity_provider={'id': token.identity_provider_id}, - protocol={'id': token.protocol_id}, - ) + federated_dict = { + 'groups': token.federated_groups, + 'identity_provider': {'id': token.identity_provider_id}, + 'protocol': {'id': token.protocol_id}, + } token_reference['token']['user']['OS-FEDERATION'] = federated_dict del token_reference['token']['user']['password_expires_at'] if token.access_token_id: diff --git a/keystone/common/resource_options/core.py b/keystone/common/resource_options/core.py index 7333a628bd..0604cc9dbb 100644 --- a/keystone/common/resource_options/core.py +++ b/keystone/common/resource_options/core.py @@ -183,7 +183,6 @@ class ResourceOptionRegistry: class ResourceOption: - def __init__( self, option_id, diff --git a/keystone/common/sql/core.py b/keystone/common/sql/core.py index fbbff4d5ea..3d30a26356 100644 --- a/keystone/common/sql/core.py +++ b/keystone/common/sql/core.py @@ -18,6 +18,7 @@ Before using this module, call initialize(). This has to be done before CONF() because it sets up configuration options. """ + import datetime import functools @@ -117,7 +118,6 @@ ModelBase.__init__ = initialize_decorator(ModelBase.__init__) # Special Fields class JsonBlob(sql_types.TypeDecorator): - impl = sql.Text # NOTE(ralonsoh): set to True as any other TypeDecorator in SQLAlchemy # https://docs.sqlalchemy.org/en/14/core/custom_types.html# \ @@ -256,7 +256,6 @@ class ModelDictMixinWithExtras(models.ModelBase): class ModelDictMixin(models.ModelBase): - @classmethod def from_dict(cls, d): """Return a model instance from a dictionary.""" @@ -413,13 +412,13 @@ def _filter(model, query, hints): if filter_['comparator'] == 'contains': _WontMatch.check(filter_['value'], column_attr) - query_term = column_attr.ilike('%%%s%%' % filter_['value']) + query_term = column_attr.ilike('%{}%'.format(filter_['value'])) elif filter_['comparator'] == 'startswith': _WontMatch.check(filter_['value'], column_attr) - query_term = column_attr.ilike('%s%%' % filter_['value']) + query_term = column_attr.ilike('{}%'.format(filter_['value'])) elif filter_['comparator'] == 'endswith': _WontMatch.check(filter_['value'], column_attr) - query_term = column_attr.ilike('%%%s' % filter_['value']) + query_term = column_attr.ilike('%{}'.format(filter_['value'])) else: # It's a filter we don't understand, so let the caller # work out if they need to do something with it. diff --git a/keystone/common/sql/migrations/autogen.py b/keystone/common/sql/migrations/autogen.py index d0f1e34b75..1c158d4cc8 100644 --- a/keystone/common/sql/migrations/autogen.py +++ b/keystone/common/sql/migrations/autogen.py @@ -51,8 +51,7 @@ def _migration_script_ops(context, directive, phase): """ autogen_kwargs = {} version_path = upgrades.get_version_branch_path( - release=upgrades.CURRENT_RELEASE, - branch=phase, + release=upgrades.CURRENT_RELEASE, branch=phase ) upgrades.check_bootstrap_new_branch(phase, version_path, autogen_kwargs) @@ -65,7 +64,7 @@ def _migration_script_ops(context, directive, phase): ), ops.DowngradeOps(ops=[]), message=directive.message, - **autogen_kwargs + **autogen_kwargs, ) if not op.upgrade_ops.is_empty(): diff --git a/keystone/common/sql/migrations/manage.py b/keystone/common/sql/migrations/manage.py index 6e71d4a45e..22af6160eb 100644 --- a/keystone/common/sql/migrations/manage.py +++ b/keystone/common/sql/migrations/manage.py @@ -134,14 +134,10 @@ def do_upgrade(config, cmd): if revision in upgrades.MILESTONES: expand_revisions = _find_milestone_revisions( - config, - revision, - upgrades.EXPAND_BRANCH, + config, revision, upgrades.EXPAND_BRANCH ) contract_revisions = _find_milestone_revisions( - config, - revision, - upgrades.CONTRACT_BRANCH, + config, revision, upgrades.CONTRACT_BRANCH ) # Expand revisions must be run before contract revisions revisions = expand_revisions + contract_revisions @@ -152,10 +148,7 @@ def do_upgrade(config, cmd): # if not CONF.command.sql: # run_sanity_checks(config, revision) do_alembic_command( - config, - cmd, - revision=revision, - sql=CONF.command.sql, + config, cmd, revision=revision, sql=CONF.command.sql ) @@ -179,8 +172,7 @@ def do_revision(config, cmd): for branch in branches: args = copy.copy(kwargs) version_path = upgrades.get_version_branch_path( - release=upgrades.CURRENT_RELEASE, - branch=branch, + release=upgrades.CURRENT_RELEASE, branch=branch ) upgrades.check_bootstrap_new_branch(branch, version_path, args) do_alembic_command(config, cmd, **args) diff --git a/keystone/common/sql/migrations/versions/27e647c0fad4_initial_version.py b/keystone/common/sql/migrations/versions/27e647c0fad4_initial_version.py index 03e0438d68..cb9e6c80c3 100644 --- a/keystone/common/sql/migrations/versions/27e647c0fad4_initial_version.py +++ b/keystone/common/sql/migrations/versions/27e647c0fad4_initial_version.py @@ -46,8 +46,7 @@ def upgrade(): if bind.engine.name == 'mysql': # Set default DB charset to UTF8. op.execute( - 'ALTER DATABASE %s DEFAULT CHARACTER SET utf8' - % bind.engine.url.database + f'ALTER DATABASE {bind.engine.url.database} DEFAULT CHARACTER SET utf8' ) op.create_table( @@ -89,11 +88,7 @@ def upgrade(): sql.Column('role_id', sql.String(64), nullable=False), sql.Column('inherited', sql.Boolean, default=False, nullable=False), sql.PrimaryKeyConstraint( - 'type', - 'actor_id', - 'target_id', - 'role_id', - 'inherited', + 'type', 'actor_id', 'target_id', 'role_id', 'inherited' ), sql.Index('ix_actor_id', 'actor_id'), mysql_engine='InnoDB', @@ -109,8 +104,7 @@ def upgrade(): sql.Column('external_id', sql.String(64)), sql.Column('user_id', sql.String(64)), sql.UniqueConstraint( - 'external_id', - name='access_rule_external_id_key', + 'external_id', name='access_rule_external_id_key' ), sql.UniqueConstraint( 'user_id', @@ -149,11 +143,7 @@ def upgrade(): sql.Column('type', sql.String(length=255), nullable=False), sql.Column('extra', ks_sql.JsonBlob.impl), sql.Column('key_hash', sql.String(64), nullable=False), - sql.Column( - 'encrypted_blob', - ks_sql.Text, - nullable=False, - ), + sql.Column('encrypted_blob', ks_sql.Text, nullable=False), mysql_engine='InnoDB', mysql_charset='utf8', ) @@ -166,9 +156,7 @@ def upgrade(): sql.Column('description', sql.Text), sql.Column('extra', ks_sql.JsonBlob.impl), sql.UniqueConstraint( - 'domain_id', - 'name', - name='ixu_group_name_domain_id', + 'domain_id', 'name', name='ixu_group_name_domain_id' ), mysql_engine='InnoDB', mysql_charset='utf8', @@ -189,10 +177,7 @@ def upgrade(): nullable=False, ), sql.UniqueConstraint( - 'domain_id', - 'local_id', - 'entity_type', - name='domain_id', + 'domain_id', 'local_id', 'entity_type', name='domain_id' ), mysql_engine='InnoDB', mysql_charset='utf8', @@ -261,19 +246,13 @@ def upgrade(): sql.Column( 'domain_id', sql.String(length=64), - sql.ForeignKey( - 'project.id', - name='project_domain_id_fkey', - ), + sql.ForeignKey('project.id', name='project_domain_id_fkey'), nullable=False, ), sql.Column( 'parent_id', sql.String(64), - sql.ForeignKey( - 'project.id', - name='project_parent_id_fkey', - ), + sql.ForeignKey('project.id', name='project_parent_id_fkey'), nullable=True, ), sql.Column( @@ -284,9 +263,7 @@ def upgrade(): default=False, ), sql.UniqueConstraint( - 'domain_id', - 'name', - name='ixu_project_name_domain_id', + 'domain_id', 'name', name='ixu_project_name_domain_id' ), mysql_engine='InnoDB', mysql_charset='utf8', @@ -439,9 +416,7 @@ def upgrade(): ), sql.Column('description', sql.String(255), nullable=True), sql.UniqueConstraint( - 'name', - 'domain_id', - name='ixu_role_name_domain_id', + 'name', 'domain_id', name='ixu_role_name_domain_id' ), mysql_engine='InnoDB', mysql_charset='utf8', @@ -558,16 +533,8 @@ def upgrade(): 'expires_at_int', name='duplicate_trust_constraint_expanded', ), - sql.Column( - 'redelegated_trust_id', - sql.String(64), - nullable=True, - ), - sql.Column( - 'redelegation_count', - sql.Integer, - nullable=True, - ), + sql.Column('redelegated_trust_id', sql.String(64), nullable=True), + sql.Column('redelegation_count', sql.Integer, nullable=True), mysql_engine='InnoDB', mysql_charset='utf8', ) @@ -604,18 +571,14 @@ def upgrade(): sql.Column( 'user_id', sql.String(length=64), - sql.ForeignKey( - 'user.id', - name='fk_user_group_membership_user_id', - ), + sql.ForeignKey('user.id', name='fk_user_group_membership_user_id'), primary_key=True, ), sql.Column( 'group_id', sql.String(length=64), sql.ForeignKey( - 'group.id', - name='fk_user_group_membership_group_id', + 'group.id', name='fk_user_group_membership_group_id' ), primary_key=True, ), @@ -720,10 +683,7 @@ def upgrade(): sql.Column( 'service_id', sql.String(length=64), - sql.ForeignKey( - 'service.id', - name='endpoint_service_id_fkey', - ), + sql.ForeignKey('service.id', name='endpoint_service_id_fkey'), nullable=False, ), sql.Column('url', sql.Text, nullable=False), @@ -738,10 +698,7 @@ def upgrade(): sql.Column( 'region_id', sql.String(length=255), - sql.ForeignKey( - 'region.id', - name='fk_endpoint_region_id', - ), + sql.ForeignKey('region.id', name='fk_endpoint_region_id'), nullable=True, ), # NOTE(stevemar): The index was named 'service_id' in @@ -835,10 +792,7 @@ def upgrade(): # FIXME(stephenfin): This should have a foreign key constraint on # registered_limit.id, but sqlalchemy-migrate clearly didn't handle # creating a column with embedded FK info as was attempted in 048 - sql.Column( - 'registered_limit_id', - sql.String(64), - ), + sql.Column('registered_limit_id', sql.String(64)), sql.Column('domain_id', sql.String(64), nullable=True), # NOTE(stephenfin): Name chosen to preserve backwards compatibility # with names used for primary key unique constraints @@ -850,12 +804,7 @@ def upgrade(): op.create_table( 'local_user', sql.Column('id', sql.Integer, primary_key=True, nullable=False), - sql.Column( - 'user_id', - sql.String(64), - nullable=False, - unique=True, - ), + sql.Column('user_id', sql.String(64), nullable=False, unique=True), sql.Column('domain_id', sql.String(64), nullable=False), sql.Column('name', sql.String(255), nullable=False), sql.Column('failed_auth_count', sql.Integer, nullable=True), @@ -874,11 +823,7 @@ def upgrade(): 'nonlocal_user', sql.Column('domain_id', sql.String(64), primary_key=True), sql.Column('name', sql.String(255), primary_key=True), - sql.Column( - 'user_id', - sql.String(64), - nullable=False, - ), + sql.Column('user_id', sql.String(64), nullable=False), sql.ForeignKeyConstraint( ['user_id', 'domain_id'], ['user.id', 'user.domain_id'], @@ -974,10 +919,7 @@ def upgrade(): # only for sqlite, once we collapse 073 we can remove this constraint with op.batch_alter_table('assignment') as batch_op: batch_op.create_foreign_key( - 'fk_assignment_role_id', - 'role', - ['role_id'], - ['id'], + 'fk_assignment_role_id', 'role', ['role_id'], ['id'] ) # TODO(stephenfin): Remove these procedures in a future contract migration @@ -1064,9 +1006,7 @@ def upgrade(): # FIXME(stephenfin): This should be dropped when we add the FK # constraint to this column op.create_index( - 'registered_limit_id', - 'limit', - ['registered_limit_id'], + 'registered_limit_id', 'limit', ['registered_limit_id'] ) # FIXME(stephenfin): These are leftover from when we removed a FK diff --git a/keystone/common/sql/migrations/versions/bobcat/expand/11c3b243b4cb_remove_service_provider_relay_state_server_default.py b/keystone/common/sql/migrations/versions/bobcat/expand/11c3b243b4cb_remove_service_provider_relay_state_server_default.py index 5bcc2e32d3..b7ea7709bb 100644 --- a/keystone/common/sql/migrations/versions/bobcat/expand/11c3b243b4cb_remove_service_provider_relay_state_server_default.py +++ b/keystone/common/sql/migrations/versions/bobcat/expand/11c3b243b4cb_remove_service_provider_relay_state_server_default.py @@ -28,7 +28,4 @@ depends_on = None def upgrade(): with op.batch_alter_table('service_provider', schema=None) as batch_op: - batch_op.alter_column( - 'relay_state_prefix', - server_default=None, - ) + batch_op.alter_column('relay_state_prefix', server_default=None) diff --git a/keystone/common/sql/upgrades.py b/keystone/common/sql/upgrades.py index 409611926d..acfb5b7af3 100644 --- a/keystone/common/sql/upgrades.py +++ b/keystone/common/sql/upgrades.py @@ -36,11 +36,7 @@ EXPAND_BRANCH = 'expand' DATA_MIGRATION_BRANCH = 'data_migration' CONTRACT_BRANCH = 'contract' -RELEASES = ( - 'yoga', - 'bobcat', - '2024.01', -) +RELEASES = ('yoga', 'bobcat', '2024.01') MILESTONES = ( 'yoga', # Do not add the milestone until the end of the release @@ -48,9 +44,7 @@ MILESTONES = ( CURRENT_RELEASE = RELEASES[-1] MIGRATION_BRANCHES = (EXPAND_BRANCH, CONTRACT_BRANCH) VERSIONS_PATH = os.path.join( - os.path.dirname(sql.__file__), - 'migrations', - 'versions', + os.path.dirname(sql.__file__), 'migrations', 'versions' ) @@ -77,8 +71,7 @@ def _find_alembic_conf(): :returns: An instance of ``alembic.config.Config`` """ path = os.path.join( - os.path.abspath(os.path.dirname(__file__)), - 'alembic.ini', + os.path.abspath(os.path.dirname(__file__)), 'alembic.ini' ) config = alembic_config.Config(os.path.abspath(path)) diff --git a/keystone/common/utils.py b/keystone/common/utils.py index 18804ef815..64aa5921d8 100644 --- a/keystone/common/utils.py +++ b/keystone/common/utils.py @@ -66,9 +66,7 @@ check_password = password_hashing.check_password # NOTE(hiromu): This dict defines alternative DN string for X.509. When # retriving DN from X.509, converting attributes types that are not listed # in the RFC4514 to a corresponding alternative DN string. -ATTR_NAME_OVERRIDES = { - x509.NameOID.EMAIL_ADDRESS: "emailAddress", -} +ATTR_NAME_OVERRIDES = {x509.NameOID.EMAIL_ADDRESS: "emailAddress"} def resource_uuid(value): @@ -217,7 +215,7 @@ def get_unix_user(user=None): try: i = int(user) except ValueError: - raise KeyError("user name '%s' not found" % user) + raise KeyError(f"user name '{user}' not found") try: user_info = pwd.getpwuid(i) except KeyError: @@ -232,8 +230,7 @@ def get_unix_user(user=None): else: user_cls_name = reflection.get_class_name(user, fully_qualified=False) raise TypeError( - 'user must be string, int or None; not %s (%r)' - % (user_cls_name, user) + f'user must be string, int or None; not {user_cls_name} ({user!r})' ) return user_info.pw_uid, user_info.pw_name @@ -278,7 +275,7 @@ def get_unix_group(group=None): try: i = int(group) except ValueError: - raise KeyError("group name '%s' not found" % group) + raise KeyError(f"group name '{group}' not found") try: group_info = grp.getgrgid(i) except KeyError: @@ -295,15 +292,13 @@ def get_unix_group(group=None): group, fully_qualified=False ) raise TypeError( - 'group must be string, int or None; not %s (%r)' - % (group_cls_name, group) + f'group must be string, int or None; not {group_cls_name} ({group!r})' ) return group_info.gr_gid, group_info.gr_name class WhiteListedItemFilter: - def __init__(self, whitelist, data): self._whitelist = set(whitelist or []) self._data = data diff --git a/keystone/conf/__init__.py b/keystone/conf/__init__.py index 53ece0e0cb..4ce87f6a2b 100644 --- a/keystone/conf/__init__.py +++ b/keystone/conf/__init__.py @@ -105,10 +105,7 @@ def set_default_for_default_log_levels(): This function needs to be called before CONF(). """ - extra_log_level_defaults = [ - 'dogpile=INFO', - 'routes=INFO', - ] + extra_log_level_defaults = ['dogpile=INFO', 'routes=INFO'] log.register_options(CONF) log.set_defaults( diff --git a/keystone/conf/application_credential.py b/keystone/conf/application_credential.py index 0e20234acb..0785e671bf 100644 --- a/keystone/conf/application_credential.py +++ b/keystone/conf/application_credential.py @@ -63,12 +63,7 @@ keystone database or open keystone to a DoS attack. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - driver, - caching, - cache_time, - user_limit, -] +ALL_OPTS = [driver, caching, cache_time, user_limit] def register_opts(conf): diff --git a/keystone/conf/catalog.py b/keystone/conf/catalog.py index 1ee6babe82..d4f304f70f 100644 --- a/keystone/conf/catalog.py +++ b/keystone/conf/catalog.py @@ -75,13 +75,7 @@ have enough services or endpoints to exceed a reasonable limit. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - template_file, - driver, - caching, - cache_time, - list_limit, -] +ALL_OPTS = [template_file, driver, caching, cache_time, list_limit] def register_opts(conf): diff --git a/keystone/conf/constants.py b/keystone/conf/constants.py index 7b9923e37f..e60e5d31c2 100644 --- a/keystone/conf/constants.py +++ b/keystone/conf/constants.py @@ -16,7 +16,6 @@ package. """ - _DEFAULT_AUTH_METHODS = [ 'external', 'password', diff --git a/keystone/conf/endpoint_filter.py b/keystone/conf/endpoint_filter.py index 836f2a7b6a..1a36be2f4c 100644 --- a/keystone/conf/endpoint_filter.py +++ b/keystone/conf/endpoint_filter.py @@ -42,10 +42,7 @@ catalog. If set to false, keystone will return an empty service catalog. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - driver, - return_all_endpoints_if_no_filter, -] +ALL_OPTS = [driver, return_all_endpoints_if_no_filter] def register_opts(conf): diff --git a/keystone/conf/endpoint_policy.py b/keystone/conf/endpoint_policy.py index ad64fbe972..044644b50d 100644 --- a/keystone/conf/endpoint_policy.py +++ b/keystone/conf/endpoint_policy.py @@ -28,9 +28,7 @@ to set this unless you are providing a custom entry point. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - driver, -] +ALL_OPTS = [driver] def register_opts(conf): diff --git a/keystone/conf/fernet_receipts.py b/keystone/conf/fernet_receipts.py index b6c3b746dd..f50ae6d349 100644 --- a/keystone/conf/fernet_receipts.py +++ b/keystone/conf/fernet_receipts.py @@ -62,10 +62,7 @@ this value means that additional secondary keys will be kept in the rotation. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - key_repository, - max_active_keys, -] +ALL_OPTS = [key_repository, max_active_keys] def register_opts(conf): diff --git a/keystone/conf/fernet_tokens.py b/keystone/conf/fernet_tokens.py index bfd166640e..bcaacb893b 100644 --- a/keystone/conf/fernet_tokens.py +++ b/keystone/conf/fernet_tokens.py @@ -60,10 +60,7 @@ this value means that additional secondary keys will be kept in the rotation. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - key_repository, - max_active_keys, -] +ALL_OPTS = [key_repository, max_active_keys] def register_opts(conf): diff --git a/keystone/conf/identity_mapping.py b/keystone/conf/identity_mapping.py index 23e745a8f4..62e642638b 100644 --- a/keystone/conf/identity_mapping.py +++ b/keystone/conf/identity_mapping.py @@ -67,11 +67,7 @@ recommended value. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - driver, - generator, - backward_compatible_ids, -] +ALL_OPTS = [driver, generator, backward_compatible_ids] def register_opts(conf): diff --git a/keystone/conf/oauth1.py b/keystone/conf/oauth1.py index 58b1f94ab4..e8932a5c01 100644 --- a/keystone/conf/oauth1.py +++ b/keystone/conf/oauth1.py @@ -55,11 +55,7 @@ means that access tokens will last forever. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - driver, - request_token_duration, - access_token_duration, -] +ALL_OPTS = [driver, request_token_duration, access_token_duration] def register_opts(conf): diff --git a/keystone/conf/opts.py b/keystone/conf/opts.py index f0bc8a3f51..e96b4ead90 100644 --- a/keystone/conf/opts.py +++ b/keystone/conf/opts.py @@ -47,7 +47,7 @@ def list_opts(): def _tupleize(d): """Convert a dict of options to the 2-tuple format.""" - return [(key, value) for key, value in d.items()] + return list(d.items()) def _list_module_names(): @@ -69,9 +69,8 @@ def _import_modules(module_names): module = importlib.import_module(full_module_path) if not hasattr(module, LIST_OPTS_FUNC_NAME): raise Exception( - "The module '%s' should have a '%s' function which " + f"The module '{full_module_path}' should have a '{LIST_OPTS_FUNC_NAME}' function which " "returns the config options." - % (full_module_path, LIST_OPTS_FUNC_NAME) ) else: imported_modules.append(module) diff --git a/keystone/conf/policy.py b/keystone/conf/policy.py index 39c7a9b914..6b9bf206ce 100644 --- a/keystone/conf/policy.py +++ b/keystone/conf/policy.py @@ -38,10 +38,7 @@ Maximum number of entities that will be returned in a policy collection. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - driver, - list_limit, -] +ALL_OPTS = [driver, list_limit] def register_opts(conf): diff --git a/keystone/conf/receipt.py b/keystone/conf/receipt.py index 0d70195bc5..ee5d9974a3 100644 --- a/keystone/conf/receipt.py +++ b/keystone/conf/receipt.py @@ -83,13 +83,7 @@ has no effect unless global caching and receipt caching are enabled. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - expiration, - provider, - caching, - cache_time, - cache_on_issue, -] +ALL_OPTS = [expiration, provider, caching, cache_time, cache_on_issue] def register_opts(conf): diff --git a/keystone/conf/revoke.py b/keystone/conf/revoke.py index 1e075379ce..bdaab1af14 100644 --- a/keystone/conf/revoke.py +++ b/keystone/conf/revoke.py @@ -65,12 +65,7 @@ has no effect unless global and `[revoke] caching` are both enabled. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - driver, - expiration_buffer, - caching, - cache_time, -] +ALL_OPTS = [driver, expiration_buffer, caching, cache_time] def register_opts(conf): diff --git a/keystone/conf/role.py b/keystone/conf/role.py index 76ba38e237..2c54e5eb6b 100644 --- a/keystone/conf/role.py +++ b/keystone/conf/role.py @@ -61,12 +61,7 @@ deployment. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - driver, - caching, - cache_time, - list_limit, -] +ALL_OPTS = [driver, caching, cache_time, list_limit] def register_opts(conf): diff --git a/keystone/conf/shadow_users.py b/keystone/conf/shadow_users.py index b6953c4679..60306ab69c 100644 --- a/keystone/conf/shadow_users.py +++ b/keystone/conf/shadow_users.py @@ -30,9 +30,7 @@ this option unless you are providing a custom entry point. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - driver, -] +ALL_OPTS = [driver] def register_opts(conf): diff --git a/keystone/conf/tokenless_auth.py b/keystone/conf/tokenless_auth.py index f334d8e60d..05089e3af5 100644 --- a/keystone/conf/tokenless_auth.py +++ b/keystone/conf/tokenless_auth.py @@ -61,11 +61,7 @@ this value. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - trusted_issuer, - protocol, - issuer_attribute, -] +ALL_OPTS = [trusted_issuer, protocol, issuer_attribute] def register_opts(conf): diff --git a/keystone/conf/totp.py b/keystone/conf/totp.py index 668a29d9eb..1317d0fdc5 100644 --- a/keystone/conf/totp.py +++ b/keystone/conf/totp.py @@ -28,9 +28,7 @@ The number of previous windows to check when processing TOTP passcodes. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - included_previous_windows, -] +ALL_OPTS = [included_previous_windows] def register_opts(conf): diff --git a/keystone/conf/trust.py b/keystone/conf/trust.py index 36646dadc3..e189a85c0a 100644 --- a/keystone/conf/trust.py +++ b/keystone/conf/trust.py @@ -52,11 +52,7 @@ unless you are providing a custom entry point. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - allow_redelegation, - max_redelegation_count, - driver, -] +ALL_OPTS = [allow_redelegation, max_redelegation_count, driver] def register_opts(conf): diff --git a/keystone/conf/unified_limit.py b/keystone/conf/unified_limit.py index ecf1587fd7..462816e1fc 100644 --- a/keystone/conf/unified_limit.py +++ b/keystone/conf/unified_limit.py @@ -74,13 +74,7 @@ running deployment. GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - driver, - caching, - cache_time, - list_limit, - enforcement_model, -] +ALL_OPTS = [driver, caching, cache_time, list_limit, enforcement_model] def register_opts(conf): diff --git a/keystone/conf/wsgi.py b/keystone/conf/wsgi.py index a8c5f67eb2..84d277467f 100644 --- a/keystone/conf/wsgi.py +++ b/keystone/conf/wsgi.py @@ -39,9 +39,7 @@ SENSITIVE/PRIVILEGED DATA. ) GROUP_NAME = __name__.split('.')[-1] -ALL_OPTS = [ - debug_middleware, -] +ALL_OPTS = [debug_middleware] def register_opts(conf): diff --git a/keystone/credential/backends/sql.py b/keystone/credential/backends/sql.py index 8f9954a438..7a88ee2757 100644 --- a/keystone/credential/backends/sql.py +++ b/keystone/credential/backends/sql.py @@ -54,7 +54,6 @@ class CredentialModel(sql.ModelBase, sql.ModelDictMixinWithExtras): class Credential(base.CredentialDriverBase): - # credential crud @sql.handle_conflicts(conflict_type='credential') diff --git a/keystone/credential/core.py b/keystone/credential/core.py index 13b90e379f..82b52207b2 100644 --- a/keystone/credential/core.py +++ b/keystone/credential/core.py @@ -50,7 +50,7 @@ class Manager(manager.Manager): if credential['type'] == 'ec2': decrypted_blob = json.loads( PROVIDERS.credential_provider_api.decrypt( - credential['encrypted_blob'], + credential['encrypted_blob'] ) ) else: diff --git a/keystone/credential/provider.py b/keystone/credential/provider.py index 52ededcd1c..89c6465517 100644 --- a/keystone/credential/provider.py +++ b/keystone/credential/provider.py @@ -17,7 +17,6 @@ CONF = keystone.conf.CONF class Manager(manager.Manager): - driver_namespace = 'keystone.credential.provider' _provides_api = 'credential_provider_api' diff --git a/keystone/credential/providers/fernet/core.py b/keystone/credential/providers/fernet/core.py index f2f35ae928..6544c51dc8 100644 --- a/keystone/credential/providers/fernet/core.py +++ b/keystone/credential/providers/fernet/core.py @@ -85,7 +85,7 @@ class Provider(core.Provider): primary_key_hash(keys), ) except (TypeError, ValueError) as e: - msg = 'Credential could not be encrypted: %s' % str(e) + msg = f'Credential could not be encrypted: {str(e)}' tr_msg = _('Credential could not be encrypted: %s') % str(e) LOG.error(msg) raise exception.CredentialEncryptionError(tr_msg) diff --git a/keystone/credential/schema.py b/keystone/credential/schema.py index 1cd17d01d1..274fa57cda 100644 --- a/keystone/credential/schema.py +++ b/keystone/credential/schema.py @@ -135,7 +135,7 @@ update_request_body: dict[str, Any] = { "properties": _credential_properties, "additionalProperties": True, "minProperties": 1, - }, + } }, "required": ["credential"], } diff --git a/keystone/endpoint_policy/backends/sql.py b/keystone/endpoint_policy/backends/sql.py index a18d624a17..cee49f8c99 100644 --- a/keystone/endpoint_policy/backends/sql.py +++ b/keystone/endpoint_policy/backends/sql.py @@ -50,7 +50,6 @@ class PolicyAssociation(sql.ModelBase, sql.ModelDictMixin): class EndpointPolicy(base.EndpointPolicyDriverBase): - def create_policy_association( self, policy_id, endpoint_id=None, service_id=None, region_id=None ): diff --git a/keystone/endpoint_policy/core.py b/keystone/endpoint_policy/core.py index 69314d8f99..f09d4bd7a3 100644 --- a/keystone/endpoint_policy/core.py +++ b/keystone/endpoint_policy/core.py @@ -97,7 +97,6 @@ class Manager(manager.Manager): ) def list_endpoints_for_policy(self, policy_id): - def _get_endpoint(endpoint_id, policy_id): try: return PROVIDERS.catalog_api.get_endpoint(endpoint_id) @@ -235,7 +234,6 @@ class Manager(manager.Manager): return matching_endpoints def get_policy_for_endpoint(self, endpoint_id): - def _get_policy(policy_id, endpoint_id): try: return PROVIDERS.policy_api.get_policy(policy_id) diff --git a/keystone/exception.py b/keystone/exception.py index 09b7473274..5e1ee3f250 100644 --- a/keystone/exception.py +++ b/keystone/exception.py @@ -328,7 +328,7 @@ class InsufficientAuthMethods(Error): title = 'Unauthorized' def __init__(self, message=None, user_id=None, methods=None): - methods_str = '[%s]' % ','.join(methods) + methods_str = '[{}]'.format(','.join(methods)) super().__init__(message, user_id=user_id, methods=methods_str) self.user_id = user_id @@ -639,7 +639,6 @@ class UnexpectedError(SecurityError): ) def _build_message(self, message, **kwargs): - # Ensure that exception has a value to be extra defensive for # substitutions and make sure the exception doesn't raise an # exception. @@ -801,7 +800,6 @@ class LDAPSizeLimitExceeded(UnexpectedError): class CacheDeserializationError(Exception): - def __init__(self, obj, data): super().__init__( _('Failed to deserialize %(obj)s. Data is %(data)s') @@ -826,7 +824,6 @@ class ResourceDeleteForbidden(ForbiddenNotSecurity): class OAuth2Error(Error): - def __init__(self, code, title, error_title, message): self.code = code self.title = title diff --git a/keystone/federation/backends/base.py b/keystone/federation/backends/base.py index 7f608a2c39..799be6bb47 100644 --- a/keystone/federation/backends/base.py +++ b/keystone/federation/backends/base.py @@ -18,7 +18,6 @@ from keystone import exception class FederationDriverBase(metaclass=abc.ABCMeta): - @abc.abstractmethod def create_idp(self, idp_id, idp): """Create an identity provider. diff --git a/keystone/federation/backends/sql.py b/keystone/federation/backends/sql.py index d293b9429b..b138baa130 100644 --- a/keystone/federation/backends/sql.py +++ b/keystone/federation/backends/sql.py @@ -47,7 +47,7 @@ class FederationProtocolModel(sql.ModelBase, sql.ModelDictMixin): def to_dict(self): """Return a dictionary with model's attributes.""" - d = dict() + d = {} for attr in self.__class__.attributes: d[attr] = getattr(self, attr) return d @@ -102,7 +102,7 @@ class IdentityProviderModel(sql.ModelBase, sql.ModelDictMixin): def to_dict(self): """Return a dictionary with model's attributes.""" - d = dict() + d = {} for attr in self.__class__.attributes: d[attr] = getattr(self, attr) d['remote_ids'] = [] @@ -129,7 +129,7 @@ class IdPRemoteIdsModel(sql.ModelBase, sql.ModelDictMixin): def to_dict(self): """Return a dictionary with model's attributes.""" - d = dict() + d = {} for attr in self.__class__.attributes: d[attr] = getattr(self, attr) return d @@ -153,7 +153,7 @@ class MappingModel(sql.ModelBase, sql.ModelDictMixin): def to_dict(self): """Return a dictionary with model's attributes.""" - d = dict() + d = {} for attr in self.__class__.attributes: d[attr] = getattr(self, attr) d['rules'] = jsonutils.loads(d['rules']) @@ -188,14 +188,13 @@ class ServiceProviderModel(sql.ModelBase, sql.ModelDictMixin): def to_dict(self): """Return a dictionary with model's attributes.""" - d = dict() + d = {} for attr in self.__class__.attributes: d[attr] = getattr(self, attr) return d class Federation(base.FederationDriverBase): - _CONFLICT_LOG_MSG = 'Conflict %(conflict_type)s: %(details)s' def _handle_idp_conflict(self, e): diff --git a/keystone/federation/core.py b/keystone/federation/core.py index 4fab7f6121..446de57d3b 100644 --- a/keystone/federation/core.py +++ b/keystone/federation/core.py @@ -100,9 +100,9 @@ class Manager(manager.Manager): # provider removes a federated identity provider resource. reason = ( 'The token cache is being invalidated because identity provider ' - '%(idp_id)s has been deleted. Authorization for federated users ' + f'{idp_id} has been deleted. Authorization for federated users ' 'will be recalculated and enforced accordingly the next time ' - 'they authenticate or validate a token.' % {'idp_id': idp_id} + 'they authenticate or validate a token.' ) notifications.invalidate_token_cache_notification(reason) diff --git a/keystone/federation/idp.py b/keystone/federation/idp.py index 7f45b21bf3..13b482f053 100644 --- a/keystone/federation/idp.py +++ b/keystone/federation/idp.py @@ -456,9 +456,9 @@ def _verify_assertion_binary_is_installed(): ) except subprocess.CalledProcessError: msg = ( - 'Unable to locate %(binary)s binary on the system. Check to make ' + f'Unable to locate {CONF.saml.xmlsec1_binary} binary on the system. Check to make ' 'sure it is installed.' - ) % {'binary': CONF.saml.xmlsec1_binary} + ) tr_msg = _( 'Unable to locate %(binary)s binary on the system. Check to ' 'make sure it is installed.' @@ -491,16 +491,12 @@ def _sign_assertion(assertion): for option in ('keyfile', 'certfile'): if ',' in getattr(CONF.saml, option, ''): raise exception.UnexpectedError( - 'The configuration value in `keystone.conf [saml] %s` cannot ' + f'The configuration value in `keystone.conf [saml] {option}` cannot ' 'contain a comma (`,`). Please fix your configuration.' - % option ) # xmlsec1 --sign --privkey-pem privkey,cert --id-attr:ID - certificates = '{idp_private_key},{idp_public_key}'.format( - idp_public_key=CONF.saml.certfile, - idp_private_key=CONF.saml.keyfile, - ) + certificates = f'{CONF.saml.keyfile},{CONF.saml.certfile}' # Verify that the binary used to create the assertion actually exists on # the system. If it doesn't, log a warning for operators to go and install @@ -589,15 +585,14 @@ class MetadataGenerator: return ed def _create_idp_sso_descriptor(self): - def get_cert(): try: return sigver.read_cert_from_file(CONF.saml.certfile, 'pem') except (OSError, sigver.CertificateError) as e: msg = ( - 'Cannot open certificate %(cert_file)s.' - 'Reason: %(reason)s' - ) % {'cert_file': CONF.saml.certfile, 'reason': e} + f'Cannot open certificate {CONF.saml.certfile}.' + f'Reason: {e}' + ) tr_msg = _( 'Cannot open certificate %(cert_file)s.' 'Reason: %(reason)s' diff --git a/keystone/federation/schema.py b/keystone/federation/schema.py index 48c92a6775..6dced4f7d5 100644 --- a/keystone/federation/schema.py +++ b/keystone/federation/schema.py @@ -106,10 +106,7 @@ identity_provider_update = { 'additionalProperties': False, } -_remote_id_attribute_properties = { - 'type': 'string', - 'maxLength': 64, -} +_remote_id_attribute_properties = {'type': 'string', 'maxLength': 64} _protocol_properties = { 'mapping_id': parameter_types.mapping_id_string, diff --git a/keystone/federation/utils.py b/keystone/federation/utils.py index 8179b89106..f0cf7c6fe3 100644 --- a/keystone/federation/utils.py +++ b/keystone/federation/utils.py @@ -45,9 +45,7 @@ ROLE_PROPERTIES = { "items": { "type": "object", "required": ["name"], - "properties": { - "name": {"type": "string"}, - }, + "properties": {"name": {"type": "string"}}, "additionalProperties": False, }, } @@ -138,9 +136,7 @@ IDP_ATTRIBUTE_MAPPING_SCHEMA_1_0 = { "empty": { "type": "object", "required": ['type'], - "properties": { - "type": {"type": "string"}, - }, + "properties": {"type": {"type": "string"}}, "additionalProperties": False, }, "any_one_of": { @@ -222,13 +218,7 @@ PROJECTS_SCHEMA_2_0["items"]["properties"]["domain"] = { # type: ignore[index] IDP_ATTRIBUTE_MAPPING_SCHEMA_2_0['properties']['rules']['items']['properties'][ # type: ignore[index] 'local' -][ - 'items' -][ - 'properties' -][ - 'projects' -] = PROJECTS_SCHEMA_2_0 +]['items']['properties']['projects'] = PROJECTS_SCHEMA_2_0 def get_default_attribute_mapping_schema_version(): @@ -246,7 +236,7 @@ class DirectMaps: def __str__(self): """Return the direct map array as a string.""" - return '%s' % self._matches + return f'{self._matches}' def add(self, values): """Add a matched value to the list of matches. @@ -395,18 +385,8 @@ def transform_to_group_ids( Example of group_names parameter:: [ - { - "name": "group_name", - "domain": { - "id": "domain_id" - }, - }, - { - "name": "group_name_2", - "domain": { - "name": "domain_name" - } - } + {"name": "group_name", "domain": {"id": "domain_id"}}, + {"name": "group_name_2", "domain": {"name": "domain_name"}}, ] :param group_names: list of group identified by name and its domain. @@ -508,7 +488,7 @@ class RuleProcessor: 'UserName': 'testacct', 'FirstName': 'Test', 'LastName': 'Account', - 'orgPersonType': 'Tester' + 'orgPersonType': 'Tester', } :returns: dictionary with user and group_ids @@ -519,25 +499,10 @@ class RuleProcessor: 'name': 'foobar', 'group_ids': ['abc123', 'def456'], 'group_names': [ - { - 'name': 'group_name_1', - 'domain': { - 'name': 'domain1' - } - }, - { - 'name': 'group_name_1_1', - 'domain': { - 'name': 'domain1' - } - }, - { - 'name': 'group_name_2', - 'domain': { - 'id': 'xyz132' - } - } - ] + {'name': 'group_name_1', 'domain': {'name': 'domain1'}}, + {'name': 'group_name_1_1', 'domain': {'name': 'domain1'}}, + {'name': 'group_name_2', 'domain': {'id': 'xyz132'}}, + ], } """ @@ -680,8 +645,8 @@ class RuleProcessor: # initialize the group_ids as a set to eliminate duplicates user = {} group_ids = set() - group_names = list() - groups_by_domain = dict() + group_names = [] + groups_by_domain = {} projects = [] # if mapping yield no valid identity values, we should bail right away @@ -746,7 +711,7 @@ class RuleProcessor: def process_group_by_name(self, group, groups_by_domain): domain = group['domain'].get('name') or group['domain'].get('id') - groups_by_domain.setdefault(domain, list()).append(group) + groups_by_domain.setdefault(domain, []).append(group) return self.extract_groups(groups_by_domain) def extract_projects(self, identity_value): @@ -816,21 +781,9 @@ class RuleProcessor: Example requirements:: [ - { - "type": "UserName" - }, - { - "type": "orgPersonType", - "any_one_of": [ - "Customer" - ] - }, - { - "type": "ADFS_GROUPS", - "whitelist": [ - "g1", "g2", "g3", "g4" - ] - } + {"type": "UserName"}, + {"type": "orgPersonType", "any_one_of": ["Customer"]}, + {"type": "ADFS_GROUPS", "whitelist": ["g1", "g2", "g3", "g4"]}, ] :param assertion: dict of attributes from an IdP @@ -844,7 +797,7 @@ class RuleProcessor: 'orgPersonType': ['Tester'], 'Email': ['testacct@example.com'], 'FirstName': ['Test'], - 'ADFS_GROUPS': ['g1', 'g2'] + 'ADFS_GROUPS': ['g1', 'g2'], } :returns: identity values used to update local @@ -918,7 +871,7 @@ class RuleProcessor: return [ assertion for assertion in assertion_values - if any([re.search(regex, assertion) for regex in values]) + if any(re.search(regex, assertion) for regex in values) ] def _evaluate_requirement( diff --git a/keystone/identity/backends/ldap/common.py b/keystone/identity/backends/ldap/common.py index 5a203fdc3d..2212543872 100644 --- a/keystone/identity/backends/ldap/common.py +++ b/keystone/identity/backends/ldap/common.py @@ -80,7 +80,7 @@ def utf8_encode(value): value_cls_name = reflection.get_class_name( value, fully_qualified=False ) - raise TypeError("value must be basestring, not %s" % value_cls_name) + raise TypeError(f"value must be basestring, not {value_cls_name}") _utf8_decoder = codecs.getdecoder('utf-8') @@ -217,10 +217,7 @@ def parse_deref(opt): 'Invalid LDAP deref option: %(option)s. ' 'Choose one of: %(options)s' ) - % { - 'option': opt, - 'options': ', '.join(LDAP_DEREF.keys()), - } + % {'option': opt, 'options': ', '.join(LDAP_DEREF.keys())} ) @@ -569,7 +566,6 @@ class PythonLDAPHandler(LDAPHandler): pool_conn_timeout=None, pool_conn_lifetime=None, ): - _common_ldap_initialization( url=url, use_tls=use_tls, @@ -850,7 +846,6 @@ class PooledLDAPHandler(LDAPHandler): pool_conn_timeout=None, pool_conn_lifetime=None, ): - _common_ldap_initialization( url=url, use_tls=use_tls, @@ -1423,14 +1418,14 @@ class BaseLdap: if self.options_name is not None: self.tree_dn = ( - getattr(conf.ldap, '%s_tree_dn' % self.options_name) + getattr(conf.ldap, f'{self.options_name}_tree_dn') or f'{self.DEFAULT_OU},{conf.ldap.suffix}' ) - idatt = '%s_id_attribute' % self.options_name + idatt = f'{self.options_name}_id_attribute' self.id_attr = getattr(conf.ldap, idatt) or self.DEFAULT_ID_ATTR - objclass = '%s_objectclass' % self.options_name + objclass = f'{self.options_name}_objectclass' self.object_class = ( getattr(conf.ldap, objclass) or self.DEFAULT_OBJECTCLASS ) @@ -1440,7 +1435,7 @@ class BaseLdap: self.attribute_mapping[k] = getattr(conf.ldap, v) attr_mapping_opt = ( - '%s_additional_attribute_mapping' % self.options_name + f'{self.options_name}_additional_attribute_mapping' ) attr_mapping = ( getattr(conf.ldap, attr_mapping_opt) @@ -1448,12 +1443,12 @@ class BaseLdap: ) self.extra_attr_mapping = self._parse_extra_attrs(attr_mapping) - ldap_filter = '%s_filter' % self.options_name + ldap_filter = f'{self.options_name}_filter' self.ldap_filter = ( getattr(conf.ldap, ldap_filter) or self.DEFAULT_FILTER ) - member_attribute = '%s_member_attribute' % self.options_name + member_attribute = f'{self.options_name}_member_attribute' self.member_attribute = getattr(conf.ldap, member_attribute, None) self.structural_classes = self.DEFAULT_STRUCTURAL_CLASSES @@ -1461,7 +1456,7 @@ class BaseLdap: if self.notfound_arg is None: self.notfound_arg = self.options_name + '_id' - attribute_ignore = '%s_attribute_ignore' % self.options_name + attribute_ignore = f'{self.options_name}_attribute_ignore' self.attribute_ignore = getattr(conf.ldap, attribute_ignore) def _not_found(self, object_id): @@ -1547,11 +1542,7 @@ class BaseLdap: raise exception.LDAPServerConnectionError(url=self.LDAP_URL) def _id_to_dn_string(self, object_id): - return '{}={},{}'.format( - self.id_attr, - ldap.dn.escape_dn_chars(str(object_id)), - self.tree_dn, - ) + return f'{self.id_attr}={ldap.dn.escape_dn_chars(str(object_id))},{self.tree_dn}' def _id_to_dn(self, object_id): if self.LDAP_SCOPE == ldap.SCOPE_ONELEVEL: @@ -1560,12 +1551,7 @@ class BaseLdap: search_result = conn.search_s( self.tree_dn, self.LDAP_SCOPE, - '(&(%(id_attr)s=%(id)s)(objectclass=%(objclass)s))' - % { - 'id_attr': self.id_attr, - 'id': ldap.filter.escape_filter_chars(str(object_id)), - 'objclass': self.object_class, - }, + f'(&({self.id_attr}={ldap.filter.escape_filter_chars(str(object_id))})(objectclass={self.object_class}))', attrlist=DN_ONLY, ) if search_result: @@ -1590,18 +1576,18 @@ class BaseLdap: id_list = search_result[0][1][self.id_attr] except KeyError: message = ( - 'ID attribute %(id_attr)s not found in LDAP ' - 'object %(dn)s.' - ) % ({'id_attr': self.id_attr, 'dn': search_result}) + f'ID attribute {self.id_attr} not found in LDAP ' + f'object {search_result}.' + ) LOG.warning(message) raise exception.NotFound(message=message) if len(id_list) > 1: message = ( 'In order to keep backward compatibility, in ' 'the case of multivalued ids, we are ' - 'returning the first id %(id_attr)s in the ' + f'returning the first id {id_list[0]} in the ' 'DN.' - ) % ({'id_attr': id_list[0]}) + ) LOG.warning(message) return id_list[0] else: @@ -1631,10 +1617,10 @@ class BaseLdap: # deployments. We need to fix our read-write LDAP logic so # it does not get the ID from DN. message = ( - 'ID attribute %(id_attr)s for LDAP object %(dn)s ' + f'ID attribute {self.id_attr} for LDAP object {res[0]} ' 'has multiple values and therefore cannot be used ' 'as an ID. Will get the ID from DN instead' - ) % ({'id_attr': self.id_attr, 'dn': res[0]}) + ) LOG.warning(message) id_val = self._dn_to_id(res[0]) else: @@ -1744,13 +1730,9 @@ class BaseLdap: # To ensure that ldap attribute value is not empty in ldap config. if not attr: - attr_name = '{}_{}_attribute'.format( - self.options_name, - self.attribute_options_names[ldap_attr_name], - ) + attr_name = f'{self.options_name}_{self.attribute_options_names[ldap_attr_name]}_attribute' raise ValueError( - '"%(attr)s" is not a valid value for' - ' "%(attr_name)s"' % {'attr': attr, 'attr_name': attr_name} + f'"{attr}" is not a valid value for' f' "{attr_name}"' ) # consider attr = "cn" and @@ -1784,15 +1766,14 @@ class BaseLdap: def _ldap_get(self, object_id, ldap_filter=None): query = ( - '(&(%(id_attr)s=%(id)s)' - '%(filter)s' - '(objectClass=%(object_class)s))' - % { - 'id_attr': self.id_attr, - 'id': ldap.filter.escape_filter_chars(str(object_id)), - 'filter': (ldap_filter or self.ldap_filter or ''), - 'object_class': self.object_class, - } + '(&({id_attr}={id})' + '{filter}' + '(objectClass={object_class}))'.format( + id_attr=self.id_attr, + id=ldap.filter.escape_filter_chars(str(object_id)), + filter=ldap_filter or self.ldap_filter or '', + object_class=self.object_class, + ) ) with self.get_connection() as conn: try: @@ -1875,7 +1856,7 @@ class BaseLdap: def _ldap_get_list( self, search_base, scope, query_params=None, attrlist=None ): - query = '(objectClass=%s)' % self.object_class + query = f'(objectClass={self.object_class})' if query_params: def calc_filter(attrname, value): @@ -1925,7 +1906,6 @@ class BaseLdap: continue if k in self.attribute_ignore: - # Handle 'enabled' specially since can't disable if ignored. if k == 'enabled' and (not v): action = _( @@ -2050,25 +2030,13 @@ class BaseLdap: # booleans (this is related to bug #1411478). if filter_['comparator'] == 'equals': - query_term = '({attr}={val})'.format( - attr=ldap_attr, - val=val_esc, - ) + query_term = f'({ldap_attr}={val_esc})' elif filter_['comparator'] == 'contains': - query_term = '({attr}=*{val}*)'.format( - attr=ldap_attr, - val=val_esc, - ) + query_term = f'({ldap_attr}=*{val_esc}*)' elif filter_['comparator'] == 'startswith': - query_term = '({attr}={val}*)'.format( - attr=ldap_attr, - val=val_esc, - ) + query_term = f'({ldap_attr}={val_esc}*)' elif filter_['comparator'] == 'endswith': - query_term = '({attr}=*{val})'.format( - attr=ldap_attr, - val=val_esc, - ) + query_term = f'({ldap_attr}=*{val_esc})' else: # It's a filter we don't understand, so let the caller # work out if they need to do something with it. @@ -2128,14 +2096,14 @@ class EnabledEmuMixIn(BaseLdap): def __init__(self, conf): super().__init__(conf) - enabled_emulation = '%s_enabled_emulation' % self.options_name + enabled_emulation = f'{self.options_name}_enabled_emulation' self.enabled_emulation = getattr(conf.ldap, enabled_emulation) - enabled_emulation_dn = '%s_enabled_emulation_dn' % self.options_name + enabled_emulation_dn = f'{self.options_name}_enabled_emulation_dn' self.enabled_emulation_dn = getattr(conf.ldap, enabled_emulation_dn) use_group_config = ( - '%s_enabled_emulation_use_group_config' % self.options_name + f'{self.options_name}_enabled_emulation_use_group_config' ) self.use_group_config = getattr(conf.ldap, use_group_config) @@ -2150,9 +2118,9 @@ class EnabledEmuMixIn(BaseLdap): if not self.enabled_emulation_dn: naming_attr_name = 'cn' - naming_attr_value = 'enabled_%ss' % self.options_name + naming_attr_value = f'enabled_{self.options_name}s' sub_vals = (naming_attr_name, naming_attr_value, self.tree_dn) - self.enabled_emulation_dn = '%s=%s,%s' % sub_vals + self.enabled_emulation_dn = '{}={},{}'.format(*sub_vals) naming_attr = (naming_attr_name, [naming_attr_value]) else: # Extract the attribute name and value from the configured DN. @@ -2172,10 +2140,7 @@ class EnabledEmuMixIn(BaseLdap): return self._is_member_enabled(member_attr_val, conn) def _is_member_enabled(self, member_attr_val, conn): - query = '({}={})'.format( - self.member_attribute, - ldap.filter.escape_filter_chars(member_attr_val), - ) + query = f'({self.member_attribute}={ldap.filter.escape_filter_chars(member_attr_val)})' try: enabled_value = conn.search_s( self.enabled_emulation_dn, diff --git a/keystone/identity/backends/ldap/core.py b/keystone/identity/backends/ldap/core.py index b0d6d4cd4c..75251234ba 100644 --- a/keystone/identity/backends/ldap/core.py +++ b/keystone/identity/backends/ldap/core.py @@ -135,7 +135,7 @@ class Identity(base.IdentityDriverBase): ' not found in the directory. The user should be' ' removed from the group. The user will be ignored.' ) - LOG.debug(msg, dict(user_id=user_id, group_id=group_id)) + LOG.debug(msg, {'user_id': user_id, 'group_id': group_id}) return users def check_user_in_group(self, user_id, group_id): @@ -413,11 +413,7 @@ class GroupApi(common_ldap.BaseLdap): """Return a list of groups for which the user is a member.""" user_dn_esc = ldap.filter.escape_filter_chars(user_dn) if self.group_ad_nesting: - query = '({}:{}:={})'.format( - self.member_attribute, - LDAP_MATCHING_RULE_IN_CHAIN, - user_dn_esc, - ) + query = f'({self.member_attribute}:{LDAP_MATCHING_RULE_IN_CHAIN}:={user_dn_esc})' else: query = f'({self.member_attribute}={user_dn_esc})' return self.get_all(query) @@ -429,10 +425,7 @@ class GroupApi(common_ldap.BaseLdap): # Hardcoded to member as that is how the Matching Rule in Chain # Mechanisms expects it. The member_attribute might actually be # member_of elsewhere, so they are not the same. - query = '(member:{}:={})'.format( - LDAP_MATCHING_RULE_IN_CHAIN, - user_dn_esc, - ) + query = f'(member:{LDAP_MATCHING_RULE_IN_CHAIN}:={user_dn_esc})' else: query = f'({self.member_attribute}={user_dn_esc})' return self.get_all_filtered(hints, query) @@ -451,7 +444,7 @@ class GroupApi(common_ldap.BaseLdap): self.tree_dn, self.LDAP_SCOPE, query_params={ - "member:%s:" % LDAP_MATCHING_RULE_IN_CHAIN: group_dn + f"member:{LDAP_MATCHING_RULE_IN_CHAIN}:": group_dn }, attrlist=[self.member_attribute], ) diff --git a/keystone/identity/backends/resource_options.py b/keystone/identity/backends/resource_options.py index 92c8933812..cae390eb70 100644 --- a/keystone/identity/backends/resource_options.py +++ b/keystone/identity/backends/resource_options.py @@ -101,7 +101,7 @@ MFA_RULES_OPT = resource_options.ResourceOption( 'items': { # Of Strings, each string must be unique, minimum 1 # element - 'type': 'string', + 'type': 'string' }, 'minItems': 1, 'uniqueItems': True, diff --git a/keystone/identity/backends/sql_model.py b/keystone/identity/backends/sql_model.py index 9a1a6fdcc3..4f202369d5 100644 --- a/keystone/identity/backends/sql_model.py +++ b/keystone/identity/backends/sql_model.py @@ -87,10 +87,7 @@ class User(sql.ModelBase, sql.ModelDictMixinWithExtras): created_at = sql.Column(sql.DateTime, nullable=True) last_active_at = sql.Column(sql.Date, nullable=True) # unique constraint needed here to support composite fk constraints - __table_args__: ty.Any = ( - sql.UniqueConstraint('id', 'domain_id'), - {}, - ) + __table_args__: ty.Any = (sql.UniqueConstraint('id', 'domain_id'), {}) # NOTE(stevemar): we use a hybrid property here because we leverage the # expression method, see `@name.expression` and `LocalUser.name` below. @@ -353,25 +350,16 @@ class Password(sql.ModelBase, sql.ModelDictMixin): # in the model are no longer required. # created_at default set here to safe guard in case it gets missed _created_at = sql.Column( - 'created_at', - sql.DateTime, - nullable=False, - default=timeutils.utcnow, + 'created_at', sql.DateTime, nullable=False, default=timeutils.utcnow ) _expires_at = sql.Column('expires_at', sql.DateTime, nullable=True) # set the default to 0, a 0 indicates it is unset. created_at_int = sql.Column( - sql.DateTimeInt(), - nullable=False, - default=0, - server_default='0', + sql.DateTimeInt(), nullable=False, default=0, server_default='0' ) expires_at_int = sql.Column(sql.DateTimeInt(), nullable=True) self_service = sql.Column( - sql.Boolean, - default=False, - nullable=False, - server_default='0', + sql.Boolean, default=False, nullable=False, server_default='0' ) @hybrid_property diff --git a/keystone/identity/core.py b/keystone/identity/core.py index 9efd19dbde..fd1b114902 100644 --- a/keystone/identity/core.py +++ b/keystone/identity/core.py @@ -111,7 +111,6 @@ class DomainConfigs(provider_api.ProviderAPIMixin, dict): ) def _load_config_from_file(self, resource_api, file_list, domain_name): - def _assert_no_more_than_one_sql_driver(new_config, config_file): """Ensure there is no more than one sql driver. @@ -202,7 +201,6 @@ class DomainConfigs(provider_api.ProviderAPIMixin, dict): ) def _load_config_from_database(self, domain_id, specific_config): - def _assert_no_more_than_one_sql_driver(domain_id, new_config): """Ensure adding driver doesn't push us over the limit of 1. @@ -613,8 +611,8 @@ class Manager(manager.Manager): ) self.event_callbacks = { notifications.ACTIONS.deleted: { - 'project': [self._unset_default_project], - }, + 'project': [self._unset_default_project] + } } def _domain_deleted(self, service, resource_type, operation, payload): @@ -1374,10 +1372,10 @@ class Manager(manager.Manager): if enabled_change or user.get('password') is not None: self._persist_revocation_event_for_user(user_id) reason = ( - 'Invalidating the token cache because user %(user_id)s was ' + f'Invalidating the token cache because user {user_id} was ' 'enabled or disabled. Authorization will be calculated and ' 'enforced accordingly the next time they authenticate or ' - 'validate a token.' % {'user_id': user_id} + 'validate a token.' ) notifications.invalidate_token_cache_notification(reason) @@ -1501,8 +1499,8 @@ class Manager(manager.Manager): self._persist_revocation_event_for_user(user_id) reason_s = ( - 'Invalidating the token cache because group %(group_id)s ' - 'has been deleted.' % {'group_id': group_id} + f'Invalidating the token cache because group {group_id} ' + 'has been deleted.' ) notifications.invalidate_token_cache_notification(reason_s) @@ -1566,14 +1564,10 @@ class Manager(manager.Manager): # role assignments expanded from this group to this user assignment.COMPUTED_ASSIGNMENTS_REGION.invalidate() reason = ( - 'Invalidating the token cache because user %(user_id)s was ' - 'removed from group %(group_id)s. Authorization will be ' + f'Invalidating the token cache because user {user_id} was ' + f'removed from group {group_id}. Authorization will be ' 'calculated and enforced accordingly the next time they ' 'authenticate or validate a token.' - % { - 'user_id': user_id, - 'group_id': group_id, - } ) notifications.invalidate_token_cache_notification(reason) notifications.Audit.removed_from( @@ -1678,7 +1672,6 @@ class Manager(manager.Manager): def change_password( self, user_id, original_password, new_password, initiator=None ): - # authenticate() will raise an AssertionError if authentication fails try: self.authenticate(user_id, original_password) @@ -1702,10 +1695,10 @@ class Manager(manager.Manager): notifications.Audit.updated(self._USER, user_id, initiator) self._persist_revocation_event_for_user(user_id) reason_s = ( - 'Invalidating the token cache because user %(user_id)s changed ' + f'Invalidating the token cache because user {user_id} changed ' 'the password. Authorization will be calculated and enforced ' 'accordingly the next time they authenticate or validate a ' - 'token.' % {'user_id': user_id} + 'token.' ) notifications.invalidate_token_cache_notification(reason_s) diff --git a/keystone/identity/id_generators/sha256.py b/keystone/identity/id_generators/sha256.py index 170c2616ef..4597e622c9 100644 --- a/keystone/identity/id_generators/sha256.py +++ b/keystone/identity/id_generators/sha256.py @@ -18,7 +18,6 @@ from keystone.identity import generator class Generator(generator.IDGenerator): - def generate_public_ID(self, mapping): m = hashlib.sha256() for key in sorted(mapping.keys()): diff --git a/keystone/identity/mapping_backends/sql.py b/keystone/identity/mapping_backends/sql.py index 65e1529f3c..6fc4e6c186 100644 --- a/keystone/identity/mapping_backends/sql.py +++ b/keystone/identity/mapping_backends/sql.py @@ -39,7 +39,6 @@ class IDMapping(sql.ModelBase, sql.ModelDictMixin): class Mapping(base.MappingDriverBase): - def get_public_id(self, local_entity): # NOTE(henry-nash): Since the Public ID is regeneratable, rather # than search for the entry using the local entity values, we diff --git a/keystone/identity/schema.py b/keystone/identity/schema.py index 23bee9bcc8..e8b1597ea0 100644 --- a/keystone/identity/schema.py +++ b/keystone/identity/schema.py @@ -102,15 +102,15 @@ _password_change_properties = { 'password': {'type': 'string'}, } if getattr(CONF, 'strict_password_check', None): - _password_change_properties['password'][ - 'maxLength' - ] = CONF.identity.max_password_length + _password_change_properties['password']['maxLength'] = ( + CONF.identity.max_password_length + ) if getattr(CONF, 'security_compliance', None): if getattr(CONF.security_compliance, 'password_regex', None): - _password_change_properties['password'][ - 'pattern' - ] = CONF.security_compliance.password_regex + _password_change_properties['password']['pattern'] = ( + CONF.security_compliance.password_regex + ) password_change = { 'type': 'object', diff --git a/keystone/identity/shadow_backends/sql.py b/keystone/identity/shadow_backends/sql.py index 8c5c6ef2a8..a79c0687e1 100644 --- a/keystone/identity/shadow_backends/sql.py +++ b/keystone/identity/shadow_backends/sql.py @@ -31,7 +31,6 @@ PROVIDERS = provider_api.ProviderAPIs class ShadowUsers(base.ShadowUsersDriverBase): @sql.handle_conflicts(conflict_type='federated_user') def create_federated_user(self, domain_id, federated_dict, email=None): - local_entity = { 'domain_id': domain_id, 'local_id': federated_dict['unique_id'], diff --git a/keystone/limit/backends/base.py b/keystone/limit/backends/base.py index 4b7ea03c07..0574d6804a 100644 --- a/keystone/limit/backends/base.py +++ b/keystone/limit/backends/base.py @@ -22,7 +22,6 @@ CONF = keystone.conf.CONF class UnifiedLimitDriverBase(metaclass=abc.ABCMeta): - def _get_list_limit(self): return CONF.unified_limit.list_limit or CONF.list_limit diff --git a/keystone/limit/backends/sql.py b/keystone/limit/backends/sql.py index 99fe1dbf38..e435383fe7 100644 --- a/keystone/limit/backends/sql.py +++ b/keystone/limit/backends/sql.py @@ -123,7 +123,6 @@ class LimitModel(sql.ModelBase, sql.ModelDictMixin): class UnifiedLimit(base.UnifiedLimitDriverBase): - def _check_unified_limit_unique( self, unified_limit, is_registered_limit=True ): diff --git a/keystone/limit/core.py b/keystone/limit/core.py index 3e760c9632..309c1da7f1 100644 --- a/keystone/limit/core.py +++ b/keystone/limit/core.py @@ -28,7 +28,6 @@ MEMOIZE = cache.get_memoization_decorator(group='unified_limit') class Manager(manager.Manager): - driver_namespace = 'keystone.unified_limit' _provides_api = 'unified_limit_api' diff --git a/keystone/limit/models/flat.py b/keystone/limit/models/flat.py index c20516059a..3ed57c82eb 100644 --- a/keystone/limit/models/flat.py +++ b/keystone/limit/models/flat.py @@ -14,7 +14,6 @@ from keystone.limit.models import base class FlatModel(base.ModelBase): - NAME = 'flat' DESCRIPTION = ( 'Limit enforcement and validation does not take project hierarchy ' diff --git a/keystone/limit/models/strict_two_level.py b/keystone/limit/models/strict_two_level.py index adff9b5468..ffc5f734ca 100644 --- a/keystone/limit/models/strict_two_level.py +++ b/keystone/limit/models/strict_two_level.py @@ -166,20 +166,20 @@ class StrictTwoLevelModel(base.ModelBase): ) except exception.InvalidLimit: error = ( - "The resource limit (%(level)s: %(id)s, " - "resource_name: %(resource_name)s, " - "resource_limit: %(resource_limit)s, " - "service_id: %(service_id)s, " - "region_id: %(region_id)s) doesn't satisfy " + "The resource limit ({level}: {id}, " + "resource_name: {resource_name}, " + "resource_limit: {resource_limit}, " + "service_id: {service_id}, " + "region_id: {region_id}) doesn't satisfy " "current hierarchy model." - ) % { - 'level': 'project_id' if project_id else 'domain_id', - 'id': project_id or domain_id, - 'resource_name': resource_name, - 'resource_limit': resource_limit, - 'service_id': service_id, - 'region_id': region_id, - } + ).format( + level='project_id' if project_id else 'domain_id', + id=project_id or domain_id, + resource_name=resource_name, + resource_limit=resource_limit, + service_id=service_id, + region_id=region_id, + ) tr_error = _( "The resource limit (%(level)s: %(id)s, " "resource_name: %(resource_name)s, " diff --git a/keystone/models/revoke_model.py b/keystone/models/revoke_model.py index 19f84b15f1..ce003264a9 100644 --- a/keystone/models/revoke_model.py +++ b/keystone/models/revoke_model.py @@ -59,9 +59,7 @@ ALTERNATIVES = { 'user_id': ['user_id', 'trustor_id', 'trustee_id'], 'domain_id': ['identity_domain_id', 'assignment_domain_id'], # For a domain-scoped token, the domain is in assignment_domain_id. - 'domain_scope_id': [ - 'assignment_domain_id', - ], + 'domain_scope_id': ['assignment_domain_id'], } @@ -69,7 +67,7 @@ REVOKE_KEYS = _NAMES + _EVENT_ARGS def blank_token_data(issued_at): - token_data = dict() + token_data = {} for name in _NAMES: token_data[name] = None for name in _TOKEN_KEYS: @@ -156,7 +154,7 @@ def is_revoked(events, token_data): match any revocation events, meaning the token is considered valid by the revocation API. """ - return any([matches(e, token_data) for e in events]) + return any(matches(e, token_data) for e in events) def matches(event, token_values): @@ -214,8 +212,9 @@ def matches(event, token_values): ): return False - if event.role_id is not None and event.role_id not in ( - token_values['roles'] + if ( + event.role_id is not None + and event.role_id not in (token_values['roles']) ): return False @@ -223,7 +222,6 @@ def matches(event, token_values): def build_token_values(token): - token_expires_at = timeutils.parse_isotime(token.expires_at) # Trim off the microseconds because the revocation event only has diff --git a/keystone/models/token_model.py b/keystone/models/token_model.py index 68bcdfc1e5..fd2fe045c8 100644 --- a/keystone/models/token_model.py +++ b/keystone/models/token_model.py @@ -470,9 +470,9 @@ class TokenModel: def _validate_token_resources(self): if self.project and not self.project.get('enabled'): msg = ( - 'Unable to validate token because project %(id)s is ' + f'Unable to validate token because project {self.project_id} is ' 'disabled' - ) % {'id': self.project_id} + ) tr_msg = _( 'Unable to validate token because project %(id)s is ' 'disabled' @@ -481,8 +481,8 @@ class TokenModel: raise exception.ProjectNotFound(tr_msg) if self.project and not self.project_domain.get('enabled'): msg = ( - 'Unable to validate token because domain %(id)s is disabled' - ) % {'id': self.project_domain['id']} + 'Unable to validate token because domain {id} is disabled' + ).format(id=self.project_domain['id']) tr_msg = _( 'Unable to validate token because domain %(id)s is disabled' ) % {'id': self.project_domain['id']} @@ -513,8 +513,8 @@ class TokenModel: if not self.user_domain.get('enabled'): msg = ( - 'Unable to validate token because domain %(id)s is disabled' - ) % {'id': self.user_domain['id']} + 'Unable to validate token because domain {id} is disabled' + ).format(id=self.user_domain['id']) tr_msg = _( 'Unable to validate token because domain %(id)s is disabled' ) % {'id': self.user_domain['id']} @@ -523,9 +523,7 @@ class TokenModel: def _validate_system_scope(self): if self.system_scoped and not self.roles: - msg = ('User %(user_id)s has no access to the system') % { - 'user_id': self.user_id - } + msg = f'User {self.user_id} has no access to the system' tr_msg = _('User %(user_id)s has no access to the system') % { 'user_id': self.user_id } @@ -535,8 +533,8 @@ class TokenModel: def _validate_domain_scope(self): if self.domain_scoped and not self.roles: msg = ( - 'User %(user_id)s has no access to domain %(domain_id)s' - ) % {'user_id': self.user_id, 'domain_id': self.domain_id} + f'User {self.user_id} has no access to domain {self.domain_id}' + ) tr_msg = _( 'User %(user_id)s has no access to domain %(domain_id)s' ) % {'user_id': self.user_id, 'domain_id': self.domain_id} @@ -545,9 +543,7 @@ class TokenModel: def _validate_project_scope(self): if self.project_scoped and not self.roles: - msg = ( - 'User %(user_id)s has no access to project %(project_id)s' - ) % {'user_id': self.user_id, 'project_id': self.project_id} + msg = f'User {self.user_id} has no access to project {self.project_id}' tr_msg = _( 'User %(user_id)s has no access to project %(project_id)s' ) % {'user_id': self.user_id, 'project_id': self.project_id} diff --git a/keystone/notifications.py b/keystone/notifications.py index 0acfdbebfc..1df7e1569c 100644 --- a/keystone/notifications.py +++ b/keystone/notifications.py @@ -397,7 +397,7 @@ def register_event_callback(event, resource_type, callbacks): for callback in callbacks: if not callable(callback): - msg = 'Method not callable: %s' % callback + msg = f'Method not callable: {callback}' tr_msg = _('Method not callable: %s') % callback LOG.error(msg) raise TypeError(tr_msg) @@ -429,11 +429,10 @@ def listener(cls): @listener class Something(object): - def __init__(self): self.event_callbacks = { notifications.ACTIONS.created: { - 'user': self._user_created_callback, + 'user': self._user_created_callback }, notifications.ACTIONS.deleted: { 'project': [ @@ -497,9 +496,7 @@ def _get_notifier(): host = CONF.default_publisher_id or socket.gethostname() try: transport = oslo_messaging.get_notification_transport(CONF) - _notifier = oslo_messaging.Notifier( - transport, "identity.%s" % host - ) + _notifier = oslo_messaging.Notifier(transport, f"identity.{host}") except Exception: LOG.exception("Failed to construct notifier") _notifier = False @@ -624,11 +621,7 @@ def _send_notification( notifier = _get_notifier() if notifier: context = {} - event_type = '{service}.{resource_type}.{operation}'.format( - service=SERVICE, - resource_type=resource_type, - operation=operation, - ) + event_type = f'{SERVICE}.{resource_type}.{operation}' if _check_notification_opt_out(event_type, outcome=None): return try: @@ -773,11 +766,7 @@ class CadfRoleAssignmentNotificationWrapper: def __init__(self, operation): self.action = f'{operation}.{self.ROLE_ASSIGNMENT}' - self.event_type = '{}.{}.{}'.format( - SERVICE, - self.ROLE_ASSIGNMENT, - operation, - ) + self.event_type = f'{SERVICE}.{self.ROLE_ASSIGNMENT}.{operation}' def __call__(self, f): @functools.wraps(f) @@ -790,8 +779,9 @@ class CadfRoleAssignmentNotificationWrapper: differently in various tests. Using named arguments, i.e.:: - create_grant(user_id=user['id'], domain_id=domain['id'], - role_id=role['id']) + create_grant( + user_id=user['id'], domain_id=domain['id'], role_id=role['id'] + ) Or, using positional arguments, i.e.:: @@ -800,8 +790,9 @@ class CadfRoleAssignmentNotificationWrapper: Or, both, i.e.:: - create_grant(role_id['id'], user_id=user['id'], - domain_id=domain['id']) + create_grant( + role_id['id'], user_id=user['id'], domain_id=domain['id'] + ) Checking the values for kwargs is easy enough, since it comes in as a dictionary @@ -810,9 +801,14 @@ class CadfRoleAssignmentNotificationWrapper: :: - create_grant(role_id, user_id=None, group_id=None, - domain_id=None, project_id=None, - inherited_to_projects=False) + create_grant( + role_id, + user_id=None, + group_id=None, + domain_id=None, + project_id=None, + inherited_to_projects=False, + ) So, if the values of actor or target are still None after checking kwargs, we can check the positional arguments, diff --git a/keystone/oauth1/core.py b/keystone/oauth1/core.py index e0ec7d1691..119159e7a8 100644 --- a/keystone/oauth1/core.py +++ b/keystone/oauth1/core.py @@ -87,12 +87,12 @@ def validate_oauth_params(query_string): if params_fitered: if 'error' in params_fitered: msg = ( - 'Validation failed with errors: %(error)s, detail ' - 'message is: %(desc)s.' - ) % { - 'error': params_fitered['error'], - 'desc': params_fitered['error_description'], - } + 'Validation failed with errors: {error}, detail ' + 'message is: {desc}.' + ).format( + error=params_fitered['error'], + desc=params_fitered['error_description'], + ) tr_msg = _( 'Validation failed with errors: %(error)s, detail ' 'message is: %(desc)s.' diff --git a/keystone/oauth1/validator.py b/keystone/oauth1/validator.py index 6a7d36220d..cd68026af6 100644 --- a/keystone/oauth1/validator.py +++ b/keystone/oauth1/validator.py @@ -24,7 +24,6 @@ PROVIDERS = provider_api.ProviderAPIs class OAuthValidator(provider_api.ProviderAPIMixin, oauth1.RequestValidator): - # TODO(mhu) set as option probably? @property def enforce_ssl(self): diff --git a/keystone/oauth2/handlers.py b/keystone/oauth2/handlers.py index 87d0b52739..bf287e2c69 100644 --- a/keystone/oauth2/handlers.py +++ b/keystone/oauth2/handlers.py @@ -30,6 +30,6 @@ def build_response(error): if error.code == 401: response.headers['WWW-Authenticate'] = ( - 'Keystone uri="%s"' % ks_flask.base_url() + f'Keystone uri="{ks_flask.base_url()}"' ) return response diff --git a/keystone/policy/backends/base.py b/keystone/policy/backends/base.py index 8eac86973c..1f12aaa6d8 100644 --- a/keystone/policy/backends/base.py +++ b/keystone/policy/backends/base.py @@ -19,7 +19,6 @@ CONF = keystone.conf.CONF class PolicyDriverBase(metaclass=abc.ABCMeta): - def _get_list_limit(self): return CONF.policy.list_limit or CONF.list_limit diff --git a/keystone/policy/backends/sql.py b/keystone/policy/backends/sql.py index 3461405896..4cb0bbc15c 100644 --- a/keystone/policy/backends/sql.py +++ b/keystone/policy/backends/sql.py @@ -27,7 +27,6 @@ class PolicyModel(sql.ModelBase, sql.ModelDictMixinWithExtras): class Policy(rules.Policy): - @sql.handle_conflicts(conflict_type='policy') def create_policy(self, policy_id, policy): with sql.session_for_write() as session: diff --git a/keystone/receipt/handlers.py b/keystone/receipt/handlers.py index ad30259c46..2b2ebcb0ee 100644 --- a/keystone/receipt/handlers.py +++ b/keystone/receipt/handlers.py @@ -33,9 +33,10 @@ def extract_receipt(auth_context): if auth_context['user_id'] != receipt.user_id: raise exception.ReceiptNotFound( - "AuthContext user_id: %s does not match " - "user_id for supplied auth receipt: %s" - % (auth_context['user_id'], receipt.user_id), + "AuthContext user_id: {} does not match " + "user_id for supplied auth receipt: {}".format( + auth_context['user_id'], receipt.user_id + ), receipt_id=receipt_id, ) else: diff --git a/keystone/receipt/provider.py b/keystone/receipt/provider.py index 78908fc51a..8be12f2b47 100644 --- a/keystone/receipt/provider.py +++ b/keystone/receipt/provider.py @@ -84,7 +84,7 @@ class Manager(manager.Manager): [ notifications.INVALIDATE_TOKEN_CACHE, self._drop_receipt_cache, - ], + ] ], } @@ -160,7 +160,6 @@ class Manager(manager.Manager): ) def issue_receipt(self, user_id, method_names, expires_at=None): - receipt = receipt_model.ReceiptModel() receipt.user_id = user_id receipt.methods = method_names diff --git a/keystone/receipt/providers/fernet/core.py b/keystone/receipt/providers/fernet/core.py index 734f13dc79..bb7f30edab 100644 --- a/keystone/receipt/providers/fernet/core.py +++ b/keystone/receipt/providers/fernet/core.py @@ -57,9 +57,7 @@ class Provider(base.Provider): def generate_id_and_issued_at(self, receipt): receipt_id = self.receipt_formatter.create_receipt( - receipt.user_id, - receipt.methods, - receipt.expires_at, + receipt.user_id, receipt.methods, receipt.expires_at ) creation_datetime_obj = self.receipt_formatter.creation_time( receipt_id diff --git a/keystone/receipt/receipt_formatters.py b/keystone/receipt/receipt_formatters.py index 2ebd14ff88..204a3c5277 100644 --- a/keystone/receipt/receipt_formatters.py +++ b/keystone/receipt/receipt_formatters.py @@ -183,7 +183,6 @@ class ReceiptFormatter: class ReceiptPayload: - @classmethod def assemble(cls, user_id, methods, expires_at): """Assemble the payload of a receipt. diff --git a/keystone/resource/backends/base.py b/keystone/resource/backends/base.py index f7aa846750..d05f3fae76 100644 --- a/keystone/resource/backends/base.py +++ b/keystone/resource/backends/base.py @@ -37,7 +37,6 @@ NULL_DOMAIN_ID = '<>' class ResourceDriverBase(metaclass=abc.ABCMeta): - def _get_list_limit(self): return CONF.resource.list_limit or CONF.list_limit diff --git a/keystone/resource/backends/resource_options.py b/keystone/resource/backends/resource_options.py index 2ecfacebc1..93c05fdd66 100644 --- a/keystone/resource/backends/resource_options.py +++ b/keystone/resource/backends/resource_options.py @@ -19,9 +19,7 @@ PROJECT_OPTIONS_REGISTRY = resource_options.ResourceOptionRegistry('PROJECT') # NOTE(morgan): wrap this in a function for testing purposes. # This is called on import by design. def register_role_options(): - for opt in [ - ro_opt.IMMUTABLE_OPT, - ]: + for opt in [ro_opt.IMMUTABLE_OPT]: PROJECT_OPTIONS_REGISTRY.register_option(opt) diff --git a/keystone/resource/backends/sql.py b/keystone/resource/backends/sql.py index 0cdeb34695..7e8b7d90dd 100644 --- a/keystone/resource/backends/sql.py +++ b/keystone/resource/backends/sql.py @@ -25,7 +25,6 @@ LOG = log.getLogger(__name__) class Resource(base.ResourceDriverBase): - def _encode_domain_id(self, ref): if 'domain_id' in ref and ref['domain_id'] is None: new_ref = ref.copy() @@ -231,7 +230,7 @@ class Resource(base.ResourceDriverBase): subq_tags = query.filter( sql_model.ProjectTag.project_id == ptag['project_id'] ) - result = map(lambda x: x['name'], subq_tags.all()) + result = (x['name'] for x in subq_tags.all()) if set(tags) <= set(result): filtered_ids.append(ptag['project_id']) return filtered_ids diff --git a/keystone/resource/backends/sql_model.py b/keystone/resource/backends/sql_model.py index d341181d59..f9603e7a37 100644 --- a/keystone/resource/backends/sql_model.py +++ b/keystone/resource/backends/sql_model.py @@ -116,7 +116,6 @@ class Project(sql.ModelBase, sql.ModelDictMixinWithExtras): class ProjectTag(sql.ModelBase, sql.ModelDictMixin): - def to_dict(self): d = super().to_dict() return d diff --git a/keystone/resource/config_backends/sql.py b/keystone/resource/config_backends/sql.py index facc25cd9d..caece09ec1 100644 --- a/keystone/resource/config_backends/sql.py +++ b/keystone/resource/config_backends/sql.py @@ -49,7 +49,6 @@ class ConfigRegister(sql.ModelBase, sql.ModelDictMixin): class DomainConfig(base.DomainConfigDriverBase): - def choose_table(self, sensitive): if sensitive: return SensitiveConfig diff --git a/keystone/resource/core.py b/keystone/resource/core.py index cf3985f443..0d554310c1 100644 --- a/keystone/resource/core.py +++ b/keystone/resource/core.py @@ -612,9 +612,9 @@ class Manager(manager.Manager): reason = ( 'The token cache is being invalidate because project ' - '%(project_id)s was deleted. Authorization will be recalculated ' + f'{project_id} was deleted. Authorization will be recalculated ' 'and enforced accordingly the next time users authenticate or ' - 'validate a token.' % {'project_id': project_id} + 'validate a token.' ) notifications.invalidate_token_cache_notification(reason) return ret diff --git a/keystone/revoke/backends/sql.py b/keystone/revoke/backends/sql.py index 4e0a9c5f77..699452747d 100644 --- a/keystone/revoke/backends/sql.py +++ b/keystone/revoke/backends/sql.py @@ -151,7 +151,7 @@ class Revoke(base.RevokeDriverBase): @oslo_db_api.wrap_db_retry(retry_on_deadlock=True) def revoke(self, event): - kwargs = dict() + kwargs = {} for attr in revoke_model.REVOKE_KEYS: kwargs[attr] = getattr(event, attr) record = RevocationEvent(**kwargs) diff --git a/keystone/revoke/core.py b/keystone/revoke/core.py index 77425f643a..ab86e4b8eb 100644 --- a/keystone/revoke/core.py +++ b/keystone/revoke/core.py @@ -85,7 +85,7 @@ class Manager(manager.Manager): [ notifications.PERSIST_REVOCATION_EVENT_FOR_USER, self._user_callback, - ], + ] ], } @@ -115,7 +115,6 @@ class Manager(manager.Manager): def revoke_by_audit_chain_id( self, audit_chain_id, project_id=None, domain_id=None ): - self._assert_not_domain_and_project_scoped( domain_id=domain_id, project_id=project_id ) diff --git a/keystone/server/backends.py b/keystone/server/backends.py index 388ea867be..f8a29067fa 100644 --- a/keystone/server/backends.py +++ b/keystone/server/backends.py @@ -37,7 +37,6 @@ LOG = log.getLogger(__name__) def load_backends(): - # Configure and build the cache cache.configure_cache() cache.configure_cache(region=catalog.COMPUTED_CATALOG_REGION) diff --git a/keystone/server/flask/application.py b/keystone/server/flask/application.py index b720855778..ddde080cfa 100644 --- a/keystone/server/flask/application.py +++ b/keystone/server/flask/application.py @@ -161,9 +161,9 @@ def _handle_keystone_exception(error): # convert to a string. message = str(message) - body = dict( - error={'code': error.code, 'title': error.title, 'message': message} - ) + body = { + 'error': {'code': error.code, 'title': error.title, 'message': message} + } if isinstance(error, exception.AuthPluginException): body['error']['identity'] = error.authentication @@ -175,7 +175,7 @@ def _handle_keystone_exception(error): # Add the appropriate WWW-Authenticate header for Unauthorized if isinstance(error, exception.Unauthorized): url = ks_flask.base_url() - response.headers['WWW-Authenticate'] = 'Keystone uri="%s"' % url + response.headers['WWW-Authenticate'] = f'Keystone uri="{url}"' return response diff --git a/keystone/server/flask/common.py b/keystone/server/flask/common.py index 7cf4d37b6e..e4cbacf66a 100644 --- a/keystone/server/flask/common.py +++ b/keystone/server/flask/common.py @@ -132,7 +132,7 @@ def construct_resource_map( else: jh_data = None if not url.startswith('/'): - url = '/%s' % url + url = f'/{url}' return ResourceMap( resource=resource, url=url, @@ -186,7 +186,6 @@ def _remove_content_type_on_204(resp): class APIBase(metaclass=abc.ABCMeta): - @property @abc.abstractmethod def _name(self): @@ -281,7 +280,7 @@ class APIBase(metaclass=abc.ABCMeta): api_url_prefix = api_url_prefix.rstrip('/') if api_url_prefix and not api_url_prefix.startswith('/'): - self._api_url_prefix = '/%s' % api_url_prefix + self._api_url_prefix = f'/{api_url_prefix}' else: # NOTE(morgan): If the api_url_prefix is empty fall back on the # class-level defined `_api_url_prefix` if it is set. @@ -291,7 +290,7 @@ class APIBase(metaclass=abc.ABCMeta): if blueprint_url_prefix and not blueprint_url_prefix.startswith('/'): self._blueprint_url_prefix = self._build_bp_url_prefix( - '/%s' % blueprint_url_prefix + f'/{blueprint_url_prefix}' ) else: self._blueprint_url_prefix = self._build_bp_url_prefix( @@ -372,7 +371,7 @@ class APIBase(metaclass=abc.ABCMeta): # NOTE(morgan): The Prefix is automatically added by the API, so # we do not add it to the paths here. - collection_path = '/%s' % c_key + collection_path = f'/{c_key}' if getattr(r, '_id_path_param_name_override', None): # The member_key doesn't match the "id" key in the url, make # sure to use the correct path-key for ID. @@ -380,19 +379,14 @@ class APIBase(metaclass=abc.ABCMeta): else: member_id_key = f'{m_key}_id' - entity_path = '/{collection}/'.format( - collection=c_key, - member=member_id_key, - ) + entity_path = f'/{c_key}/' # NOTE(morgan): The json-home form of the entity path is different # from the flask-url routing form. Must also include the prefix jh_e_path = _URL_SUBST.sub( '{\\1}', - '%(pfx)s/%(e_path)s' - % { - 'pfx': self._api_url_prefix, - 'e_path': entity_path.lstrip('/'), - }, + '{pfx}/{e_path}'.format( + pfx=self._api_url_prefix, e_path=entity_path.lstrip('/') + ), ) LOG.debug( @@ -424,10 +418,7 @@ class APIBase(metaclass=abc.ABCMeta): ) # NOTE(morgan): Add the prefix explicitly for JSON Home documents # to the collection path. - href_val = '{pfx}{collection_path}'.format( - pfx=self._api_url_prefix, - collection_path=collection_path, - ) + href_val = f'{self._api_url_prefix}{collection_path}' # If additional parameters exist in the URL, add them to the # href-vars dict. @@ -440,7 +431,7 @@ class APIBase(metaclass=abc.ABCMeta): # means we know the params are in the "prefix". This guarantees # the correct data in the json_home document with href-template # and href-vars even on the "collection" entry - rel_data = dict() + rel_data = {} rel_data['href-template'] = _URL_SUBST.sub('{\\1}', href_val) rel_data['href-vars'] = additional_params else: @@ -683,7 +674,7 @@ class ResourceBase(flask_restful.Resource): """Ensure the value matches the reference's ID, if any.""" id_arg = None if cls.member_key is not None: - id_arg = flask.request.view_args.get('%s_id' % cls.member_key) + id_arg = flask.request.view_args.get(f'{cls.member_key}_id') if ref.get('id') is not None and id_arg != ref['id']: raise exception.ValidationError('Cannot change ID') @@ -1108,8 +1099,8 @@ def full_url(path=''): subs = {'url': base_url(path), 'query_string': ''} qs = flask.request.environ.get('QUERY_STRING') if qs: - subs['query_string'] = '?%s' % qs - return '%(url)s%(query_string)s' % subs + subs['query_string'] = f'?{qs}' + return '{url}{query_string}'.format(**subs) def set_unenforced_ok(): diff --git a/keystone/server/flask/request_processing/middleware/auth_context.py b/keystone/server/flask/request_processing/middleware/auth_context.py index da7cee3fce..61c3a1907b 100644 --- a/keystone/server/flask/request_processing/middleware/auth_context.py +++ b/keystone/server/flask/request_processing/middleware/auth_context.py @@ -87,7 +87,6 @@ def base_url(context): def middleware_exceptions(method): - @functools.wraps(method) def _inner(self, request): try: @@ -206,11 +205,7 @@ def render_exception(error, context=None, request=None, user_locale=None): message = str(message) body = { - 'error': { - 'code': error.code, - 'title': error.title, - 'message': message, - } + 'error': {'code': error.code, 'title': error.title, 'message': message} } headers = [] if isinstance(error, exception.AuthPluginException): @@ -226,7 +221,7 @@ def render_exception(error, context=None, request=None, user_locale=None): local_context = {'environment': context['environment']} url = base_url(local_context) - headers.append(('WWW-Authenticate', 'Keystone uri="%s"' % url)) + headers.append(('WWW-Authenticate', f'Keystone uri="{url}"')) return render_response( status=(error.code, error.title), body=body, headers=headers ) diff --git a/keystone/tests/common/auth.py b/keystone/tests/common/auth.py index be7ef1e499..64500d3675 100644 --- a/keystone/tests/common/auth.py +++ b/keystone/tests/common/auth.py @@ -91,9 +91,8 @@ class AuthTestMixin: username=None, user_domain_id=None, user_domain_name=None, - **kwargs + **kwargs, ): - # NOTE(dstanek): just to ensure sanity in the tests self.assertEqual( 1, @@ -161,7 +160,7 @@ class AuthTestMixin: app_cred_id=None, app_cred_name=None, secret=None, - **kwargs + **kwargs, ): """Build auth dictionary. diff --git a/keystone/tests/functional/core.py b/keystone/tests/functional/core.py index 26b75ece0d..5984a18e32 100644 --- a/keystone/tests/functional/core.py +++ b/keystone/tests/functional/core.py @@ -19,7 +19,6 @@ from keystone.tests.common import auth as common_auth class BaseTestCase(testtools.TestCase, common_auth.AuthTestMixin): - request_headers = {'content-type': 'application/json'} def setUp(self): diff --git a/keystone/tests/functional/shared/test_running.py b/keystone/tests/functional/shared/test_running.py index 86a1e3f800..0f75dcb4de 100644 --- a/keystone/tests/functional/shared/test_running.py +++ b/keystone/tests/functional/shared/test_running.py @@ -24,7 +24,6 @@ versions = ['v3'] class TestServerRunning(functests.BaseTestCase): - def test_admin_responds_with_multiple_choices(self): resp = requests.get(self.ADMIN_URL) self.assertThat(resp.status_code, is_multiple_choices) @@ -35,7 +34,7 @@ class TestServerRunning(functests.BaseTestCase): self.assertThat( resp.status_code, testtools.matchers.Annotate( - 'failed for version %s' % version, is_ok + f'failed for version {version}', is_ok ), ) @@ -49,7 +48,7 @@ class TestServerRunning(functests.BaseTestCase): self.assertThat( resp.status_code, testtools.matchers.Annotate( - 'failed for version %s' % version, is_ok + f'failed for version {version}', is_ok ), ) diff --git a/keystone/tests/hacking/checks.py b/keystone/tests/hacking/checks.py index 8deaf4f7e5..c800062d79 100644 --- a/keystone/tests/hacking/checks.py +++ b/keystone/tests/hacking/checks.py @@ -123,7 +123,6 @@ def block_comments_begin_with_a_space(physical_line, line_number): class CheckForTranslationIssues(BaseASTChecker): - name = "check_for_translation_issues" version = "1.0" LOGGING_CHECK_DESC = 'K005 Using translated string in logging' diff --git a/keystone/tests/protection/v3/test_access_rules.py b/keystone/tests/protection/v3/test_access_rules.py index 4855967b6e..232cf70775 100644 --- a/keystone/tests/protection/v3/test_access_rules.py +++ b/keystone/tests/protection/v3/test_access_rules.py @@ -50,8 +50,7 @@ class _UserAccessRuleTests: ) with self.test_client() as c: path = '/v3/users/{}/access_rules/{}'.format( - self.user_id, - app_cred['access_rules'][0]['id'], + self.user_id, app_cred['access_rules'][0]['id'] ) c.get(path, headers=self.headers) @@ -76,8 +75,7 @@ class _UserAccessRuleTests: ) with self.test_client() as c: r = c.get( - '/v3/users/%s/access_rules' % self.user_id, - headers=self.headers, + f'/v3/users/{self.user_id}/access_rules', headers=self.headers ) self.assertEqual(len(r.json['access_rules']), 1) @@ -105,10 +103,7 @@ class _UserAccessRuleTests: app_cred['id'] ) with self.test_client() as c: - path = '/v3/users/{}/access_rules/{}'.format( - self.user_id, - access_rule_id, - ) + path = f'/v3/users/{self.user_id}/access_rules/{access_rule_id}' c.delete(path, headers=self.headers) @@ -149,8 +144,7 @@ class _ProjectUsersTests: ) with self.test_client() as c: path = '/v3/users/{}/access_rules/{}'.format( - user['id'], - access_rule_id, + user['id'], access_rule_id ) c.get( path, @@ -161,8 +155,7 @@ class _ProjectUsersTests: def test_user_cannot_get_own_non_existent_access_rule_not_found(self): with self.test_client() as c: c.get( - '/v3/users/%s/access_rules/%s' - % (self.user_id, uuid.uuid4().hex), + f'/v3/users/{self.user_id}/access_rules/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -172,8 +165,9 @@ class _ProjectUsersTests: user = PROVIDERS.identity_api.create_user(user) with self.test_client() as c: c.get( - '/v3/users/%s/access_rules/%s' - % (user['id'], uuid.uuid4().hex), + '/v3/users/{}/access_rules/{}'.format( + user['id'], uuid.uuid4().hex + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -210,7 +204,7 @@ class _ProjectUsersTests: ) with self.test_client() as c: - path = '/v3/users/%s/access_rules' % user['id'] + path = '/v3/users/{}/access_rules'.format(user['id']) c.get( path, headers=self.headers, @@ -253,8 +247,7 @@ class _ProjectUsersTests: ) with self.test_client() as c: path = '/v3/users/{}/access_rules/{}'.format( - user['id'], - access_rule_id, + user['id'], access_rule_id ) c.delete( path, @@ -267,8 +260,9 @@ class _ProjectUsersTests: user = PROVIDERS.identity_api.create_user(user) with self.test_client() as c: c.delete( - '/v3/users/%s/access_rules/%s' - % (user['id'], uuid.uuid4().hex), + '/v3/users/{}/access_rules/{}'.format( + user['id'], uuid.uuid4().hex + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -311,7 +305,8 @@ class _SystemUserAccessRuleTests: with self.test_client() as c: r = c.get( - '/v3/users/%s/access_rules' % user['id'], headers=self.headers + '/v3/users/{}/access_rules'.format(user['id']), + headers=self.headers, ) self.assertEqual(1, len(r.json['access_rules'])) @@ -320,8 +315,9 @@ class _SystemUserAccessRuleTests: user = PROVIDERS.identity_api.create_user(user) with self.test_client() as c: c.get( - '/v3/users/%s/access_rules/%s' - % (user['id'], uuid.uuid4().hex), + '/v3/users/{}/access_rules/{}'.format( + user['id'], uuid.uuid4().hex + ), headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -332,7 +328,6 @@ class SystemReaderTests( common_auth.AuthTestMixin, _SystemUserAccessRuleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -397,8 +392,7 @@ class SystemReaderTests( ) with self.test_client() as c: path = '/v3/users/{}/access_rules/{}'.format( - user['id'], - access_rule_id, + user['id'], access_rule_id ) c.delete( path, @@ -411,8 +405,9 @@ class SystemReaderTests( user = PROVIDERS.identity_api.create_user(user) with self.test_client() as c: c.delete( - '/v3/users/%s/access_rules/%s' - % (user['id'], uuid.uuid4().hex), + '/v3/users/{}/access_rules/{}'.format( + user['id'], uuid.uuid4().hex + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -423,7 +418,6 @@ class SystemMemberTests( common_auth.AuthTestMixin, _SystemUserAccessRuleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -488,8 +482,7 @@ class SystemMemberTests( ) with self.test_client() as c: path = '/v3/users/{}/access_rules/{}'.format( - user['id'], - access_rule_id, + user['id'], access_rule_id ) c.delete( path, @@ -499,8 +492,7 @@ class SystemMemberTests( with self.test_client() as c: path = '/v3/users/{}/access_rules/{}'.format( - user['id'], - access_rule_id, + user['id'], access_rule_id ) c.delete( path, @@ -513,8 +505,9 @@ class SystemMemberTests( user = PROVIDERS.identity_api.create_user(user) with self.test_client() as c: c.delete( - '/v3/users/%s/access_rules/%s' - % (user['id'], uuid.uuid4().hex), + '/v3/users/{}/access_rules/{}'.format( + user['id'], uuid.uuid4().hex + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -525,7 +518,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserAccessRuleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -585,8 +577,7 @@ class SystemAdminTests( with self.test_client() as c: path = '/v3/users/{}/access_rules/{}'.format( - user['id'], - access_rule_id, + user['id'], access_rule_id ) c.delete(path, headers=self.headers) @@ -595,8 +586,9 @@ class SystemAdminTests( user = PROVIDERS.identity_api.create_user(user) with self.test_client() as c: c.delete( - '/v3/users/%s/access_rules/%s' - % (user['id'], uuid.uuid4().hex), + '/v3/users/{}/access_rules/{}'.format( + user['id'], uuid.uuid4().hex + ), headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -608,7 +600,6 @@ class ProjectReaderTests( _UserAccessRuleTests, _ProjectUsersTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -651,7 +642,6 @@ class ProjectMemberTests( _UserAccessRuleTests, _ProjectUsersTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -694,7 +684,6 @@ class ProjectAdminTests( _UserAccessRuleTests, _ProjectUsersTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_application_credential.py b/keystone/tests/protection/v3/test_application_credential.py index d09cbe9710..697bc5a0d3 100644 --- a/keystone/tests/protection/v3/test_application_credential.py +++ b/keystone/tests/protection/v3/test_application_credential.py @@ -59,9 +59,7 @@ class _TestAppCredBase(base_classes.TestCaseWithBootstrap): 'project_id': project_id, 'system': system, 'expires_at': expires, - 'roles': [ - {'id': self.bootstrapper.member_role_id}, - ], + 'roles': [{'id': self.bootstrapper.member_role_id}], 'secret': uuid.uuid4().hex, 'unrestricted': False, } @@ -137,8 +135,7 @@ class _DomainAndProjectUserTests: with self.test_client() as c: c.get( - '/v3/users/%s/application_credentials' - % (self.app_cred_user_id), + f'/v3/users/{self.app_cred_user_id}/application_credentials', expected_status_code=http.client.FORBIDDEN, headers=self.headers, ) @@ -148,8 +145,9 @@ class _DomainAndProjectUserTests: with self.test_client() as c: c.get( - '/v3/users/%s/application_credentials/%s' - % (self.app_cred_user_id, app_cred['id']), + '/v3/users/{}/application_credentials/{}'.format( + self.app_cred_user_id, app_cred['id'] + ), expected_status_code=http.client.FORBIDDEN, headers=self.headers, ) @@ -159,8 +157,9 @@ class _DomainAndProjectUserTests: with self.test_client() as c: c.get( - '/v3/users/%s/application_credentials?name=%s' - % (self.app_cred_user_id, app_cred['name']), + '/v3/users/{}/application_credentials?name={}'.format( + self.app_cred_user_id, app_cred['name'] + ), expected_status_code=http.client.FORBIDDEN, headers=self.headers, ) @@ -170,8 +169,9 @@ class _DomainAndProjectUserTests: with self.test_client() as c: c.delete( - '/v3/users/%s/application_credentials/%s' - % (self.app_cred_user_id, app_cred['id']), + '/v3/users/{}/application_credentials/{}'.format( + self.app_cred_user_id, app_cred['id'] + ), expected_status_code=http.client.FORBIDDEN, headers=self.headers, ) @@ -179,8 +179,7 @@ class _DomainAndProjectUserTests: def test_user_cannot_lookup_non_existent_application_credential(self): with self.test_client() as c: c.get( - '/v3/users/%s/application_credentials?name=%s' - % (self.app_cred_user_id, uuid.uuid4().hex), + f'/v3/users/{self.app_cred_user_id}/application_credentials?name={uuid.uuid4().hex}', expected_status_code=http.client.FORBIDDEN, headers=self.headers, ) @@ -202,7 +201,7 @@ class _DomainAndProjectUserTests: with self.test_client() as c: c.post( - '/v3/users/%s/application_credentials' % another_user_id, + f'/v3/users/{another_user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.FORBIDDEN, headers=self.headers, @@ -219,8 +218,7 @@ class _SystemUserAndOwnerTests: with self.test_client() as c: r = c.get( - '/v3/users/%s/application_credentials' - % (self.app_cred_user_id), + f'/v3/users/{self.app_cred_user_id}/application_credentials', headers=self.headers, ) self.assertEqual(2, len(r.json['application_credentials'])) @@ -230,8 +228,9 @@ class _SystemUserAndOwnerTests: with self.test_client() as c: r = c.get( - '/v3/users/%s/application_credentials/%s' - % (self.app_cred_user_id, app_cred['id']), + '/v3/users/{}/application_credentials/{}'.format( + self.app_cred_user_id, app_cred['id'] + ), headers=self.headers, ) actual_app_cred = r.json['application_credential'] @@ -242,8 +241,9 @@ class _SystemUserAndOwnerTests: with self.test_client() as c: r = c.get( - '/v3/users/%s/application_credentials?name=%s' - % (self.app_cred_user_id, app_cred['name']), + '/v3/users/{}/application_credentials?name={}'.format( + self.app_cred_user_id, app_cred['name'] + ), headers=self.headers, ) self.assertEqual(1, len(r.json['application_credentials'])) @@ -257,8 +257,9 @@ class _SystemUserAndOwnerTests: with self.test_client() as c: c.delete( - '/v3/users/%s/application_credentials/%s' - % (self.app_cred_user_id, app_cred['id']), + '/v3/users/{}/application_credentials/{}'.format( + self.app_cred_user_id, app_cred['id'] + ), expected_status_code=expected_status_code, headers=self.headers, ) @@ -280,7 +281,7 @@ class _SystemUserAndOwnerTests: with self.test_client() as c: c.post( - '/v3/users/%s/application_credentials' % another_user_id, + f'/v3/users/{another_user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.FORBIDDEN, headers=self.headers, @@ -290,7 +291,6 @@ class _SystemUserAndOwnerTests: class SystemReaderTests( _TestAppCredBase, common_auth.AuthTestMixin, _SystemUserAndOwnerTests ): - def setUp(self): super().setUp() self.loadapp() @@ -327,7 +327,6 @@ class SystemReaderTests( class SystemMemberTests( _TestAppCredBase, common_auth.AuthTestMixin, _SystemUserAndOwnerTests ): - def setUp(self): super().setUp() self.loadapp() @@ -364,7 +363,6 @@ class SystemMemberTests( class SystemAdminTests( _TestAppCredBase, common_auth.AuthTestMixin, _SystemUserAndOwnerTests ): - def setUp(self): super().setUp() self.loadapp() @@ -392,7 +390,6 @@ class SystemAdminTests( class OwnerTests( _TestAppCredBase, common_auth.AuthTestMixin, _SystemUserAndOwnerTests ): - def setUp(self): super().setUp() self.loadapp() @@ -431,7 +428,7 @@ class OwnerTests( with self.test_client() as c: c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers=self.headers, @@ -466,8 +463,9 @@ class OwnerTests( # attempt to lookup the application credential as another user with self.test_client() as c: c.get( - '/v3/users/%s/application_credentials/%s' - % (another_user_id, app_cred['id']), + '/v3/users/{}/application_credentials/{}'.format( + another_user_id, app_cred['id'] + ), expected_status_code=http.client.FORBIDDEN, headers={'X-Auth-Token': another_user_token}, ) @@ -498,8 +496,9 @@ class OwnerTests( # attempt to delete the application credential as another user with self.test_client() as c: c.delete( - '/v3/users/%s/application_credentials/%s' - % (another_user_id, app_cred['id']), + '/v3/users/{}/application_credentials/{}'.format( + another_user_id, app_cred['id'] + ), expected_status_code=http.client.FORBIDDEN, headers={'X-Auth-Token': another_user_token}, ) @@ -508,7 +507,6 @@ class OwnerTests( class DomainAdminTests( _TestAppCredBase, common_auth.AuthTestMixin, _DomainAndProjectUserTests ): - def setUp(self): super().setUp() self.loadapp() @@ -551,7 +549,6 @@ class DomainAdminTests( class DomainReaderTests( _TestAppCredBase, common_auth.AuthTestMixin, _DomainAndProjectUserTests ): - def setUp(self): super().setUp() self.loadapp() @@ -594,7 +591,6 @@ class DomainReaderTests( class DomainMemberTests( _TestAppCredBase, common_auth.AuthTestMixin, _DomainAndProjectUserTests ): - def setUp(self): super().setUp() self.loadapp() @@ -637,7 +633,6 @@ class DomainMemberTests( class ProjectAdminTests( _TestAppCredBase, common_auth.AuthTestMixin, _DomainAndProjectUserTests ): - def setUp(self): super().setUp() self.loadapp() @@ -681,7 +676,6 @@ class ProjectAdminTests( class ProjectReaderTests( _TestAppCredBase, common_auth.AuthTestMixin, _DomainAndProjectUserTests ): - def setUp(self): super().setUp() self.loadapp() @@ -725,7 +719,6 @@ class ProjectReaderTests( class ProjectMemberTests( _TestAppCredBase, common_auth.AuthTestMixin, _DomainAndProjectUserTests ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_assignment.py b/keystone/tests/protection/v3/test_assignment.py index cbb36911f8..8c5fdc4869 100644 --- a/keystone/tests/protection/v3/test_assignment.py +++ b/keystone/tests/protection/v3/test_assignment.py @@ -286,7 +286,7 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.project.id=%s' % project_id, + f'/v3/role_assignments?scope.project.id={project_id}', headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -312,7 +312,7 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.domain.id=%s' % domain_id, + f'/v3/role_assignments?scope.domain.id={domain_id}', headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -381,8 +381,7 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?user.id=%s' % user_id, - headers=self.headers, + f'/v3/role_assignments?user.id={user_id}', headers=self.headers ) self.assertEqual(len(expected), len(r.json['role_assignments'])) actual = self._extract_role_assignments_from_response_body(r) @@ -412,7 +411,7 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?group.id=%s' % group_id, + f'/v3/role_assignments?group.id={group_id}', headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -474,7 +473,7 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?role.id=%s&include_names=True' % role_id, + f'/v3/role_assignments?role.id={role_id}&include_names=True', headers=self.headers, ) self.assertEqual( @@ -502,7 +501,9 @@ class _SystemUserTests: with self.test_client() as c: qs = (assignments['project_id'], assignments['role_id']) r = c.get( - '/v3/role_assignments?scope.project.id=%s&role.id=%s' % qs, + '/v3/role_assignments?scope.project.id={}&role.id={}'.format( + *qs + ), headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -528,7 +529,9 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.domain.id=%s&role.id=%s' % qs, + '/v3/role_assignments?scope.domain.id={}&role.id={}'.format( + *qs + ), headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -561,7 +564,7 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.system=all&role.id=%s' % role_id, + f'/v3/role_assignments?scope.system=all&role.id={role_id}', headers=self.headers, ) self.assertEqual( @@ -594,7 +597,7 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?user.id=%s&role.id=%s' % qs, + '/v3/role_assignments?user.id={}&role.id={}'.format(*qs), headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -625,7 +628,7 @@ class _SystemUserTests: with self.test_client() as c: qs = (assignments['group_id'], assignments['role_id']) r = c.get( - '/v3/role_assignments?group.id=%s&role.id=%s' % qs, + '/v3/role_assignments?group.id={}&role.id={}'.format(*qs), headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -646,7 +649,9 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.project.id=%s&user.id=%s' % qs, + '/v3/role_assignments?scope.project.id={}&user.id={}'.format( + *qs + ), headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -667,7 +672,9 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.project.id=%s&group.id=%s' % qs, + '/v3/role_assignments?scope.project.id={}&group.id={}'.format( + *qs + ), headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -688,7 +695,9 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.domain.id=%s&user.id=%s' % qs, + '/v3/role_assignments?scope.domain.id={}&user.id={}'.format( + *qs + ), headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -709,7 +718,9 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.domain.id=%s&group.id=%s' % qs, + '/v3/role_assignments?scope.domain.id={}&group.id={}'.format( + *qs + ), headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -754,8 +765,9 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( ( - '/v3/role_assignments?scope.project.id=%s&include_subtree' - % assignments['project_id'] + '/v3/role_assignments?scope.project.id={}&include_subtree'.format( + assignments['project_id'] + ) ), headers=self.headers, ) @@ -876,7 +888,7 @@ class _DomainUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.project.id=%s' % project_id, + f'/v3/role_assignments?scope.project.id={project_id}', headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -908,7 +920,7 @@ class _DomainUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.domain.id=%s' % self.domain_id, + f'/v3/role_assignments?scope.domain.id={self.domain_id}', headers=self.headers, ) self.assertEqual( @@ -939,8 +951,7 @@ class _DomainUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?user.id=%s' % user_id, - headers=self.headers, + f'/v3/role_assignments?user.id={user_id}', headers=self.headers ) self.assertEqual(len(expected), len(r.json['role_assignments'])) actual = self._extract_role_assignments_from_response_body(r) @@ -968,7 +979,7 @@ class _DomainUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?group.id=%s' % group_id, + f'/v3/role_assignments?group.id={group_id}', headers=self.headers, ) self.assertEqual(len(expected), len(r.json['role_assignments'])) @@ -991,7 +1002,7 @@ class _DomainUserTests: domain = assignments['domain_id'] with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.domain.id=%s' % domain, + f'/v3/role_assignments?scope.domain.id={domain}', headers=self.headers, ) self.assertEqual([], r.json['role_assignments']) @@ -1006,7 +1017,7 @@ class _DomainUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?scope.project.id=%s' % project_id, + f'/v3/role_assignments?scope.project.id={project_id}', headers=self.headers, ) self.assertEqual(0, len(r.json['role_assignments'])) @@ -1022,8 +1033,7 @@ class _DomainUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?user.id=%s' % user_id, - headers=self.headers, + f'/v3/role_assignments?user.id={user_id}', headers=self.headers ) self.assertEqual(0, len(r.json['role_assignments'])) @@ -1038,7 +1048,7 @@ class _DomainUserTests: with self.test_client() as c: r = c.get( - '/v3/role_assignments?group.id=%s' % group_id, + f'/v3/role_assignments?group.id={group_id}', headers=self.headers, ) self.assertEqual(0, len(r.json['role_assignments'])) @@ -1081,8 +1091,9 @@ class _DomainUserTests: with self.test_client() as c: r = c.get( ( - '/v3/role_assignments?scope.project.id=%s&include_subtree' - % domain_assignments['project_id'] + '/v3/role_assignments?scope.project.id={}&include_subtree'.format( + domain_assignments['project_id'] + ) ), headers=self.headers, ) @@ -1096,8 +1107,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( ( - '/v3/role_assignments?scope.project.id=%s&include_subtree' - % assignments['project_id'] + '/v3/role_assignments?scope.project.id={}&include_subtree'.format( + assignments['project_id'] + ) ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -1105,7 +1117,6 @@ class _DomainUserTests: class _ProjectUserTests: - def test_user_cannot_list_all_assignments_in_their_project(self): with self.test_client() as c: c.get( @@ -1120,7 +1131,7 @@ class _ProjectUserTests: with self.test_client() as c: c.get( - '/v3/role_assignments?user.id=%s' % user_id, + f'/v3/role_assignments?user.id={user_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1131,7 +1142,7 @@ class _ProjectUserTests: with self.test_client() as c: c.get( - '/v3/role_assignments?group.id=%s' % group_id, + f'/v3/role_assignments?group.id={group_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1147,7 +1158,7 @@ class _ProjectUserTests: def test_user_cannot_filter_role_assignments_by_domain(self): with self.test_client() as c: c.get( - '/v3/role_assignments?scope.domain.id=%s' % self.domain_id, + f'/v3/role_assignments?scope.domain.id={self.domain_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1159,7 +1170,7 @@ class _ProjectUserTests: with self.test_client() as c: c.get( - '/v3/role_assignments?scope.project.id=%s' % project1, + f'/v3/role_assignments?scope.project.id={project1}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1174,7 +1185,7 @@ class _ProjectUserTests: with self.test_client() as c: c.get( - '/v3/role_assignments?user.id=%s' % user_id, + f'/v3/role_assignments?user.id={user_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1189,7 +1200,7 @@ class _ProjectUserTests: with self.test_client() as c: c.get( - '/v3/role_assignments?group.id=%s' % group_id, + f'/v3/role_assignments?group.id={group_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1214,8 +1225,7 @@ class _ProjectReaderMemberTests: with self.test_client() as c: c.get( ( - '/v3/role_assignments?scope.project.id=%s&include_subtree' - % self.project_id + f'/v3/role_assignments?scope.project.id={self.project_id}&include_subtree' ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -1228,7 +1238,6 @@ class SystemReaderTests( _AssignmentTestUtilities, _SystemUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1271,7 +1280,6 @@ class SystemMemberTests( _AssignmentTestUtilities, _SystemUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1314,7 +1322,6 @@ class SystemAdminTests( _AssignmentTestUtilities, _SystemUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1344,7 +1351,6 @@ class DomainReaderTests( _AssignmentTestUtilities, _DomainUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1391,7 +1397,6 @@ class DomainMemberTests( _AssignmentTestUtilities, _DomainUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1438,7 +1443,6 @@ class DomainAdminTests( _AssignmentTestUtilities, _DomainUserTests, ): - def _override_policy(self): # TODO(lbragstad): Remove this once the deprecated policies in # keystone.common.policies.role_assignment have been removed. This is @@ -1513,7 +1517,6 @@ class ProjectReaderTests( _ProjectUserTests, _ProjectReaderMemberTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1567,7 +1570,6 @@ class ProjectMemberTests( _ProjectUserTests, _ProjectReaderMemberTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1620,7 +1622,6 @@ class ProjectAdminTests( _AssignmentTestUtilities, _ProjectUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1719,8 +1720,7 @@ class ProjectAdminTests( with self.test_client() as c: r = c.get( ( - '/v3/role_assignments?scope.project.id=%s&include_subtree' - % self.project_id + f'/v3/role_assignments?scope.project.id={self.project_id}&include_subtree' ), headers=self.headers, ) @@ -1744,8 +1744,9 @@ class ProjectAdminTests( with self.test_client() as c: c.get( ( - '/v3/role_assignments?scope.project.id=%s&include_subtree' - % project['id'] + '/v3/role_assignments?scope.project.id={}&include_subtree'.format( + project['id'] + ) ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, diff --git a/keystone/tests/protection/v3/test_consumer.py b/keystone/tests/protection/v3/test_consumer.py index 7212189002..bfa177cc22 100644 --- a/keystone/tests/protection/v3/test_consumer.py +++ b/keystone/tests/protection/v3/test_consumer.py @@ -31,7 +31,8 @@ class _SystemUserOauth1ConsumerTests: ref = PROVIDERS.oauth_api.create_consumer({'id': uuid.uuid4().hex}) with self.test_client() as c: c.get( - '/v3/OS-OAUTH1/consumers/%s' % ref['id'], headers=self.headers + '/v3/OS-OAUTH1/consumers/{}'.format(ref['id']), + headers=self.headers, ) def test_user_can_list_consumers(self): @@ -41,7 +42,6 @@ class _SystemUserOauth1ConsumerTests: class _SystemReaderAndMemberOauth1ConsumerTests: - def test_user_cannot_create_consumer(self): with self.test_client() as c: c.post( @@ -55,7 +55,7 @@ class _SystemReaderAndMemberOauth1ConsumerTests: ref = PROVIDERS.oauth_api.create_consumer({'id': uuid.uuid4().hex}) with self.test_client() as c: c.patch( - '/v3/OS-OAUTH1/consumers/%s' % ref['id'], + '/v3/OS-OAUTH1/consumers/{}'.format(ref['id']), json={'consumer': {'description': uuid.uuid4().hex}}, expected_status_code=http.client.FORBIDDEN, headers=self.headers, @@ -65,7 +65,7 @@ class _SystemReaderAndMemberOauth1ConsumerTests: ref = PROVIDERS.oauth_api.create_consumer({'id': uuid.uuid4().hex}) with self.test_client() as c: c.delete( - '/v3/OS-OAUTH1/consumers/%s' % ref['id'], + '/v3/OS-OAUTH1/consumers/{}'.format(ref['id']), expected_status_code=http.client.FORBIDDEN, headers=self.headers, ) @@ -77,7 +77,6 @@ class SystemReaderTests( _SystemUserOauth1ConsumerTests, _SystemReaderAndMemberOauth1ConsumerTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -112,7 +111,6 @@ class SystemMemberTests( _SystemUserOauth1ConsumerTests, _SystemReaderAndMemberOauth1ConsumerTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -146,7 +144,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserOauth1ConsumerTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -181,7 +178,7 @@ class SystemAdminTests( ref = PROVIDERS.oauth_api.create_consumer({'id': uuid.uuid4().hex}) with self.test_client() as c: c.patch( - '/v3/OS-OAUTH1/consumers/%s' % ref['id'], + '/v3/OS-OAUTH1/consumers/{}'.format(ref['id']), json={'consumer': {'description': uuid.uuid4().hex}}, headers=self.headers, ) @@ -190,5 +187,6 @@ class SystemAdminTests( ref = PROVIDERS.oauth_api.create_consumer({'id': uuid.uuid4().hex}) with self.test_client() as c: c.delete( - '/v3/OS-OAUTH1/consumers/%s' % ref['id'], headers=self.headers + '/v3/OS-OAUTH1/consumers/{}'.format(ref['id']), + headers=self.headers, ) diff --git a/keystone/tests/protection/v3/test_credentials.py b/keystone/tests/protection/v3/test_credentials.py index 6991062762..fc45a1ea6d 100644 --- a/keystone/tests/protection/v3/test_credentials.py +++ b/keystone/tests/protection/v3/test_credentials.py @@ -54,7 +54,7 @@ class _UserCredentialTests: r = c.post('/v3/credentials', json=create, headers=self.headers) credential_id = r.json['credential']['id'] - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' r = c.get(path, headers=self.headers) self.assertEqual(self.user_id, r.json['credential']['user_id']) @@ -100,13 +100,13 @@ class _UserCredentialTests: } r = c.post('/v3/credentials', json=create, headers=self.headers) - path = '/v3/credentials?type=%s' % credential_type + path = f'/v3/credentials?type={credential_type}' r = c.get(path, headers=self.headers) self.assertEqual( expected_credential_id, r.json['credentials'][0]['id'] ) - path = '/v3/credentials?user=%s' % self.user_id + path = f'/v3/credentials?user={self.user_id}' r = c.get(path, headers=self.headers) self.assertEqual( expected_credential_id, r.json['credentials'][0]['id'] @@ -127,7 +127,7 @@ class _UserCredentialTests: updated_blob = uuid.uuid4().hex update = {'credential': {'blob': updated_blob}} - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' r = c.patch(path, json=update, headers=self.headers) self.assertEqual(updated_blob, r.json['credential']['blob']) @@ -143,7 +143,7 @@ class _UserCredentialTests: r = c.post('/v3/credentials', json=create, headers=self.headers) credential_id = r.json['credential']['id'] - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' c.delete(path, headers=self.headers) @@ -185,7 +185,7 @@ class _ProjectUsersTests: credential_id = r.json['credential']['id'] with self.test_client() as c: - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' c.get( path, headers=self.headers, @@ -195,7 +195,7 @@ class _ProjectUsersTests: def test_user_cannot_get_non_existant_credential_forbidden(self): with self.test_client() as c: c.get( - '/v3/credentials/%s' % uuid.uuid4().hex, + f'/v3/credentials/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -234,7 +234,7 @@ class _ProjectUsersTests: c.post('/v3/credentials', json=create, headers=headers) with self.test_client() as c: - path = '/v3/credentials?user_id=%s' % user['id'] + path = '/v3/credentials?user_id={}'.format(user['id']) r = c.get(path, headers=self.headers) self.assertEqual([], r.json['credentials']) @@ -273,7 +273,7 @@ class _ProjectUsersTests: c.post('/v3/credentials', json=create, headers=headers) with self.test_client() as c: - path = '/v3/credentials?type=%s' % credential_type + path = f'/v3/credentials?type={credential_type}' r = c.get(path, headers=self.headers) self.assertEqual(0, len(r.json['credentials'])) @@ -314,7 +314,7 @@ class _ProjectUsersTests: expected_cred_ids.append(r.json['credential']['id']) with self.test_client() as c: - path = '/v3/credentials?user_id=%s' % user['id'] + path = '/v3/credentials?user_id={}'.format(user['id']) r = c.get(path, headers=self.headers) self.assertEqual([], r.json['credentials']) @@ -354,7 +354,7 @@ class _ProjectUsersTests: with self.test_client() as c: update = {'credential': {'blob': uuid.uuid4().hex}} - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' c.patch( path, json=update, @@ -367,7 +367,7 @@ class _ProjectUsersTests: update = {'credential': {'blob': uuid.uuid4().hex}} c.patch( - '/v3/credentials/%s' % uuid.uuid4().hex, + f'/v3/credentials/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -428,7 +428,7 @@ class _ProjectUsersTests: credential_id = r.json['credential']['id'] with self.test_client() as c: - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' c.delete( path, headers=self.headers, @@ -438,7 +438,7 @@ class _ProjectUsersTests: def test_user_cannot_delete_non_existant_credential_forbidden(self): with self.test_client() as c: c.delete( - '/v3/credentials/%s' % uuid.uuid4().hex, + f'/v3/credentials/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -490,7 +490,7 @@ class _SystemUserCredentialTests: def test_user_cannot_get_non_existant_credential_not_found(self): with self.test_client() as c: c.get( - '/v3/credentials/%s' % uuid.uuid4().hex, + f'/v3/credentials/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -540,7 +540,7 @@ class _SystemUserCredentialTests: c.post('/v3/credentials', json=create, headers=headers) with self.test_client() as c: - path = '/v3/credentials?type=%s' % credential_type + path = f'/v3/credentials?type={credential_type}' r = c.get(path, headers=self.headers) self.assertEqual(1, len(r.json['credentials'])) self.assertEqual(credential_id, r.json['credentials'][0]['id']) @@ -583,7 +583,7 @@ class _SystemUserCredentialTests: expected_cred_ids.append(r.json['credential']['id']) with self.test_client() as c: - path = '/v3/credentials?user_id=%s' % user['id'] + path = '/v3/credentials?user_id={}'.format(user['id']) r = c.get(path, headers=self.headers) self.assertEqual(2, len(r.json['credentials'])) for credential in r.json['credentials']: @@ -597,7 +597,6 @@ class SystemReaderTests( _UserCredentialTests, _SystemUserCredentialTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -681,7 +680,7 @@ class SystemReaderTests( with self.test_client() as c: update = {'credential': {'blob': uuid.uuid4().hex}} - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' c.patch( path, json=update, @@ -694,7 +693,7 @@ class SystemReaderTests( update = {'credential': {'blob': uuid.uuid4().hex}} c.patch( - '/v3/credentials/%s' % uuid.uuid4().hex, + f'/v3/credentials/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -735,7 +734,7 @@ class SystemReaderTests( credential_id = r.json['credential']['id'] with self.test_client() as c: - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' c.delete( path, headers=self.headers, @@ -745,7 +744,7 @@ class SystemReaderTests( def test_user_cannot_delete_non_existant_credential_forbidden(self): with self.test_client() as c: c.delete( - '/v3/credentials/%s' % uuid.uuid4().hex, + f'/v3/credentials/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -757,7 +756,6 @@ class SystemMemberTests( _UserCredentialTests, _SystemUserCredentialTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -841,7 +839,7 @@ class SystemMemberTests( with self.test_client() as c: update = {'credential': {'blob': uuid.uuid4().hex}} - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' c.patch( path, json=update, @@ -854,7 +852,7 @@ class SystemMemberTests( update = {'credential': {'blob': uuid.uuid4().hex}} c.patch( - '/v3/credentials/%s' % uuid.uuid4().hex, + f'/v3/credentials/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -895,7 +893,7 @@ class SystemMemberTests( credential_id = r.json['credential']['id'] with self.test_client() as c: - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' c.delete( path, headers=self.headers, @@ -905,7 +903,7 @@ class SystemMemberTests( def test_user_cannot_delete_non_existant_credential_forbidden(self): with self.test_client() as c: c.delete( - '/v3/credentials/%s' % uuid.uuid4().hex, + f'/v3/credentials/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -917,7 +915,6 @@ class SystemAdminTests( _UserCredentialTests, _SystemUserCredentialTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -990,7 +987,7 @@ class SystemAdminTests( credential_id = r.json['credential']['id'] with self.test_client() as c: - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' updated_blob = uuid.uuid4().hex update = {'credential': {'blob': updated_blob}} r = c.patch(path, json=update, headers=self.headers) @@ -1002,7 +999,7 @@ class SystemAdminTests( update = {'credential': {'blob': uuid.uuid4().hex}} c.patch( - '/v3/credentials/%s' % uuid.uuid4().hex, + f'/v3/credentials/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.NOT_FOUND, @@ -1043,13 +1040,13 @@ class SystemAdminTests( credential_id = r.json['credential']['id'] with self.test_client() as c: - path = '/v3/credentials/%s' % credential_id + path = f'/v3/credentials/{credential_id}' c.delete(path, headers=self.headers) def test_user_cannot_delete_non_existant_credential_not_found(self): with self.test_client() as c: c.delete( - '/v3/credentials/%s' % uuid.uuid4().hex, + f'/v3/credentials/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -1061,7 +1058,6 @@ class ProjectReaderTests( _UserCredentialTests, _ProjectUsersTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1104,7 +1100,6 @@ class ProjectMemberTests( _UserCredentialTests, _ProjectUsersTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1147,7 +1142,6 @@ class ProjectAdminTests( _UserCredentialTests, _ProjectUsersTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1204,7 +1198,6 @@ class ProjectReaderTestsEnforceScopeFalse( _UserCredentialTests, _ProjectUsersTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1247,7 +1240,6 @@ class ProjectMemberTestsEnforceScopeFalse( _UserCredentialTests, _ProjectUsersTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1290,7 +1282,6 @@ class ProjectAdminTestsEnforceScopeFalse( _UserCredentialTests, _SystemUserCredentialTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_domain_config.py b/keystone/tests/protection/v3/test_domain_config.py index 819ccbad1f..4b0d3222c6 100644 --- a/keystone/tests/protection/v3/test_domain_config.py +++ b/keystone/tests/protection/v3/test_domain_config.py @@ -25,7 +25,6 @@ PROVIDERS = provider_api.ProviderAPIs class _SystemDomainAndProjectUserDomainConfigTests: - def test_user_can_get_security_compliance_domain_config(self): # Set the security compliance configuration options password_regex = uuid.uuid4().hex @@ -39,8 +38,7 @@ class _SystemDomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config/security_compliance' - % CONF.identity.default_domain_id, + f'/v3/domains/{CONF.identity.default_domain_id}/config/security_compliance', headers=self.headers, ) @@ -52,9 +50,8 @@ class _SystemDomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config/security_compliance' - '/password_regex_description' - % CONF.identity.default_domain_id, + f'/v3/domains/{CONF.identity.default_domain_id}/config/security_compliance' + '/password_regex_description', headers=self.headers, ) @@ -87,14 +84,12 @@ class _SystemDomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config/security_compliance' - % CONF.identity.default_domain_id, + f'/v3/domains/{CONF.identity.default_domain_id}/config/security_compliance', headers=self.headers, ) class _SystemUserDomainConfigTests: - def test_user_can_get_domain_config(self): domain = PROVIDERS.resource_api.create_domain( uuid.uuid4().hex, unit.new_domain_ref() @@ -103,7 +98,10 @@ class _SystemUserDomainConfigTests: domain['id'], unit.new_domain_config_ref() ) with self.test_client() as c: - c.get('/v3/domains/%s/config' % domain['id'], headers=self.headers) + c.get( + '/v3/domains/{}/config'.format(domain['id']), + headers=self.headers, + ) def test_user_can_get_domain_group_config(self): domain = PROVIDERS.resource_api.create_domain( @@ -114,7 +112,7 @@ class _SystemUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config/ldap' % domain['id'], + '/v3/domains/{}/config/ldap'.format(domain['id']), headers=self.headers, ) @@ -128,7 +126,7 @@ class _SystemUserDomainConfigTests: invalid_domain_id = uuid.uuid4().hex with self.test_client() as c: c.get( - '/v3/domains/%s/config/ldap' % invalid_domain_id, + f'/v3/domains/{invalid_domain_id}/config/ldap', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -139,7 +137,7 @@ class _SystemUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config' % domain['id'], + '/v3/domains/{}/config'.format(domain['id']), headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -153,7 +151,7 @@ class _SystemUserDomainConfigTests: invalid_domain_id = uuid.uuid4().hex with self.test_client() as c: c.get( - '/v3/domains/%s/config/ldap' % invalid_domain_id, + f'/v3/domains/{invalid_domain_id}/config/ldap', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -167,7 +165,7 @@ class _SystemUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config/ldap/url' % domain['id'], + '/v3/domains/{}/config/ldap/url'.format(domain['id']), headers=self.headers, ) @@ -179,7 +177,7 @@ class _SystemUserDomainConfigTests: PROVIDERS.domain_config_api.create_config(domain['id'], config) with self.test_client() as c: c.get( - '/v3/domains/%s/config/ldap/user_tree_dn' % domain['id'], + '/v3/domains/{}/config/ldap/user_tree_dn'.format(domain['id']), headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -193,7 +191,7 @@ class _SystemUserDomainConfigTests: invalid_domain_id = uuid.uuid4().hex with self.test_client() as c: c.get( - '/v3/domains/%s/config/ldap/user_tree_dn' % invalid_domain_id, + f'/v3/domains/{invalid_domain_id}/config/ldap/user_tree_dn', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -211,8 +209,7 @@ class _SystemUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config/security_compliance' - % CONF.identity.default_domain_id, + f'/v3/domains/{CONF.identity.default_domain_id}/config/security_compliance', headers=self.headers, ) @@ -224,9 +221,8 @@ class _SystemUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config/security_compliance' - '/password_regex_description' - % CONF.identity.default_domain_id, + f'/v3/domains/{CONF.identity.default_domain_id}/config/security_compliance' + '/password_regex_description', headers=self.headers, ) @@ -245,8 +241,7 @@ class _SystemUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config/security_compliance' - % CONF.identity.default_domain_id, + f'/v3/domains/{CONF.identity.default_domain_id}/config/security_compliance', headers=self.headers, ) @@ -264,14 +259,13 @@ class _SystemUserDomainConfigTests: class _SystemReaderMemberDomainAndProjectUserDomainConfigTests: - def test_user_cannot_create_domain_config(self): domain = PROVIDERS.resource_api.create_domain( uuid.uuid4().hex, unit.new_domain_ref() ) with self.test_client() as c: c.put( - '/v3/domains/%s/config' % domain['id'], + '/v3/domains/{}/config'.format(domain['id']), json={'config': unit.new_domain_config_ref()}, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -290,7 +284,7 @@ class _SystemReaderMemberDomainAndProjectUserDomainConfigTests: } with self.test_client() as c: c.patch( - '/v3/domains/%s/config' % domain['id'], + '/v3/domains/{}/config'.format(domain['id']), json={'config': new_config}, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -308,7 +302,7 @@ class _SystemReaderMemberDomainAndProjectUserDomainConfigTests: } with self.test_client() as c: c.patch( - '/v3/domains/%s/config/ldap' % domain['id'], + '/v3/domains/{}/config/ldap'.format(domain['id']), json={'config': new_config}, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -324,7 +318,7 @@ class _SystemReaderMemberDomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.patch( - '/v3/domains/%s/config/ldap/url' % domain['id'], + '/v3/domains/{}/config/ldap/url'.format(domain['id']), json={'config': new_config}, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -339,7 +333,7 @@ class _SystemReaderMemberDomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.delete( - '/v3/domains/%s/config' % domain['id'], + '/v3/domains/{}/config'.format(domain['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -353,7 +347,7 @@ class _SystemReaderMemberDomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.delete( - '/v3/domains/%s/config/ldap' % domain['id'], + '/v3/domains/{}/config/ldap'.format(domain['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -367,14 +361,13 @@ class _SystemReaderMemberDomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.delete( - '/v3/domains/%s/config/ldap/url' % domain['id'], + '/v3/domains/{}/config/ldap/url'.format(domain['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainAndProjectUserDomainConfigTests: - def test_user_cannot_get_domain_config(self): domain = PROVIDERS.resource_api.create_domain( uuid.uuid4().hex, unit.new_domain_ref() @@ -384,7 +377,7 @@ class _DomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config' % domain['id'], + '/v3/domains/{}/config'.format(domain['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -398,7 +391,7 @@ class _DomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config/ldap' % domain['id'], + '/v3/domains/{}/config/ldap'.format(domain['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -409,7 +402,7 @@ class _DomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config' % domain['id'], + '/v3/domains/{}/config'.format(domain['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -423,7 +416,7 @@ class _DomainAndProjectUserDomainConfigTests: ) with self.test_client() as c: c.get( - '/v3/domains/%s/config/ldap/url' % domain['id'], + '/v3/domains/{}/config/ldap/url'.format(domain['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -460,7 +453,6 @@ class SystemReaderTests( _SystemReaderMemberDomainAndProjectUserDomainConfigTests, _SystemDomainAndProjectUserDomainConfigTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -496,7 +488,6 @@ class SystemMemberTests( _SystemReaderMemberDomainAndProjectUserDomainConfigTests, _SystemDomainAndProjectUserDomainConfigTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -531,7 +522,6 @@ class SystemAdminTests( _SystemUserDomainConfigTests, _SystemDomainAndProjectUserDomainConfigTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -560,7 +550,7 @@ class SystemAdminTests( ) with self.test_client() as c: c.put( - '/v3/domains/%s/config' % domain['id'], + '/v3/domains/{}/config'.format(domain['id']), json={'config': unit.new_domain_config_ref()}, headers=self.headers, expected_status_code=http.client.CREATED, @@ -570,7 +560,7 @@ class SystemAdminTests( invalid_domain_id = uuid.uuid4().hex with self.test_client() as c: c.put( - '/v3/domains/%s/config' % invalid_domain_id, + f'/v3/domains/{invalid_domain_id}/config', json={'config': unit.new_domain_config_ref()}, headers=self.headers, expected_status_code=http.client.NOT_FOUND, @@ -589,7 +579,7 @@ class SystemAdminTests( ) with self.test_client() as c: c.patch( - '/v3/domains/%s/config' % domain['id'], + '/v3/domains/{}/config'.format(domain['id']), json={'config': new_config}, headers=self.headers, ) @@ -606,7 +596,7 @@ class SystemAdminTests( ) with self.test_client() as c: c.patch( - '/v3/domains/%s/config/ldap' % domain['id'], + '/v3/domains/{}/config/ldap'.format(domain['id']), json={'config': new_config}, headers=self.headers, ) @@ -621,7 +611,7 @@ class SystemAdminTests( ) with self.test_client() as c: c.patch( - '/v3/domains/%s/config/ldap/url' % domain['id'], + '/v3/domains/{}/config/ldap/url'.format(domain['id']), json={'config': new_config}, headers=self.headers, ) @@ -635,7 +625,8 @@ class SystemAdminTests( ) with self.test_client() as c: c.delete( - '/v3/domains/%s/config' % domain['id'], headers=self.headers + '/v3/domains/{}/config'.format(domain['id']), + headers=self.headers, ) def test_user_can_delete_domain_group_config(self): @@ -647,7 +638,7 @@ class SystemAdminTests( ) with self.test_client() as c: c.delete( - '/v3/domains/%s/config/ldap' % domain['id'], + '/v3/domains/{}/config/ldap'.format(domain['id']), headers=self.headers, ) @@ -660,7 +651,7 @@ class SystemAdminTests( ) with self.test_client() as c: c.delete( - '/v3/domains/%s/config/ldap/url' % domain['id'], + '/v3/domains/{}/config/ldap/url'.format(domain['id']), headers=self.headers, ) @@ -674,7 +665,7 @@ class SystemAdminTests( invalid_domain_id = uuid.uuid4().hex with self.test_client() as c: c.delete( - '/v3/domains/%s/config' % invalid_domain_id, + f'/v3/domains/{invalid_domain_id}/config', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -687,7 +678,6 @@ class DomainUserTests( _DomainAndProjectUserDomainConfigTests, _SystemReaderMemberDomainAndProjectUserDomainConfigTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -727,7 +717,6 @@ class ProjectUserTests( _DomainAndProjectUserDomainConfigTests, _SystemReaderMemberDomainAndProjectUserDomainConfigTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -756,7 +745,6 @@ class ProjectUserTestsWithoutEnforceScope( _DomainAndProjectUserDomainConfigTests, _SystemReaderMemberDomainAndProjectUserDomainConfigTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_domain_roles.py b/keystone/tests/protection/v3/test_domain_roles.py index 6e32936c2e..3828a24915 100644 --- a/keystone/tests/protection/v3/test_domain_roles.py +++ b/keystone/tests/protection/v3/test_domain_roles.py @@ -35,7 +35,7 @@ class _SystemUserDomainRoleTests: with self.test_client() as c: r = c.get( - '/v3/roles?domain_id=%s' % CONF.identity.default_domain_id, + f'/v3/roles?domain_id={CONF.identity.default_domain_id}', headers=self.headers, ) self.assertEqual(1, len(r.json['roles'])) @@ -47,7 +47,7 @@ class _SystemUserDomainRoleTests: ) with self.test_client() as c: - r = c.get('/v3/roles/%s' % role['id'], headers=self.headers) + r = c.get('/v3/roles/{}'.format(role['id']), headers=self.headers) self.assertEqual(role['id'], r.json['role']['id']) @@ -79,7 +79,7 @@ class _SystemReaderAndMemberDomainRoleTests: with self.test_client() as c: c.patch( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -93,7 +93,7 @@ class _SystemReaderAndMemberDomainRoleTests: with self.test_client() as c: c.delete( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -123,7 +123,7 @@ class _DomainAndProjectUserDomainRoleTests: with self.test_client() as c: c.get( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -153,7 +153,7 @@ class _DomainAndProjectUserDomainRoleTests: with self.test_client() as c: c.patch( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -167,7 +167,7 @@ class _DomainAndProjectUserDomainRoleTests: with self.test_client() as c: c.delete( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -179,7 +179,6 @@ class SystemReaderTests( _SystemUserDomainRoleTests, _SystemReaderAndMemberDomainRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -214,7 +213,6 @@ class SystemMemberTests( _SystemUserDomainRoleTests, _SystemReaderAndMemberDomainRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -248,7 +246,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserDomainRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -291,7 +288,7 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), json=update, headers=self.headers, ) @@ -303,7 +300,7 @@ class SystemAdminTests( ) with self.test_client() as c: - c.delete('/v3/roles/%s' % role['id'], headers=self.headers) + c.delete('/v3/roles/{}'.format(role['id']), headers=self.headers) class DomainUserTests( @@ -311,7 +308,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserDomainRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -349,7 +345,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserDomainRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -376,7 +371,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _DomainAndProjectUserDomainRoleTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_domains.py b/keystone/tests/protection/v3/test_domains.py index ae1c2e5e53..ac5863db91 100644 --- a/keystone/tests/protection/v3/test_domains.py +++ b/keystone/tests/protection/v3/test_domains.py @@ -29,7 +29,6 @@ PROVIDERS = provider_api.ProviderAPIs class _SystemUserDomainTests: - def test_user_can_list_domains(self): domain = PROVIDERS.resource_api.create_domain( uuid.uuid4().hex, unit.new_domain_ref() @@ -52,9 +51,7 @@ class _SystemUserDomainTests: ) with self.test_client() as c: - r = c.get( - '/v3/domains?name=%s' % domain_name, headers=self.headers - ) + r = c.get(f'/v3/domains?name={domain_name}', headers=self.headers) self.assertEqual(1, len(r.json['domains'])) self.assertEqual(domain['id'], r.json['domains'][0]['id']) @@ -87,12 +84,13 @@ class _SystemUserDomainTests: ) with self.test_client() as c: - r = c.get('/v3/domains/%s' % domain['id'], headers=self.headers) + r = c.get( + '/v3/domains/{}'.format(domain['id']), headers=self.headers + ) self.assertEqual(domain['id'], r.json['domain']['id']) class _SystemMemberAndReaderDomainTests: - def test_user_cannot_create_a_domain(self): create = {'domain': {'name': uuid.uuid4().hex}} @@ -112,7 +110,7 @@ class _SystemMemberAndReaderDomainTests: update = {'domain': {'description': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/domains/%s' % domain['id'], + '/v3/domains/{}'.format(domain['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -125,14 +123,13 @@ class _SystemMemberAndReaderDomainTests: with self.test_client() as c: c.delete( - '/v3/domains/%s' % domain['id'], + '/v3/domains/{}'.format(domain['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainReaderDomainTests: - def test_user_can_list_domains(self): # second domain, should be invisible to scoped reader second_domain = PROVIDERS.resource_api.create_domain( @@ -157,7 +154,7 @@ class _DomainReaderDomainTests: with self.test_client() as c: # filtering for own domain should succeed r = c.get( - '/v3/domains?name=%s' % self.domain['name'], + '/v3/domains?name={}'.format(self.domain['name']), headers=self.headers, ) self.assertEqual(1, len(r.json['domains'])) @@ -168,7 +165,7 @@ class _DomainReaderDomainTests: # filtering for the second domain should yield no results r = c.get( - '/v3/domains?name=%s' % second_domain['name'], + '/v3/domains?name={}'.format(second_domain['name']), headers=self.headers, ) self.assertEqual(0, len(r.json['domains'])) @@ -199,10 +196,9 @@ class _DomainReaderDomainTests: class _ProjectUserDomainTests: - def test_user_can_get_a_domain(self): with self.test_client() as c: - r = c.get('/v3/domains/%s' % self.domain_id, headers=self.headers) + r = c.get(f'/v3/domains/{self.domain_id}', headers=self.headers) self.assertEqual(self.domain_id, r.json['domain']['id']) def test_user_cannot_get_a_domain_they_are_not_authorized_to_access(self): @@ -212,7 +208,7 @@ class _ProjectUserDomainTests: with self.test_client() as c: c.get( - '/v3/domains/%s' % domain['id'], + '/v3/domains/{}'.format(domain['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -236,7 +232,7 @@ class _ProjectUserDomainTests: with self.test_client() as c: c.get( - '/v3/domains?name=%s' % domain_name, + f'/v3/domains?name={domain_name}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -262,7 +258,7 @@ class _ProjectUserDomainTests: update = {'domain': {'description': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/domains/%s' % domain['id'], + '/v3/domains/{}'.format(domain['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -286,7 +282,7 @@ class _ProjectUserDomainTests: with self.test_client() as c: update = {'domain': {'enabled': False}} - path = '/v3/domains/%s' % domain['id'] + path = '/v3/domains/{}'.format(domain['id']) c.patch( path, json=update, @@ -300,10 +296,9 @@ class _ProjectUserDomainTests: ) def test_user_cannot_get_non_existant_domain_forbidden(self): - with self.test_client() as c: c.get( - '/v3/domains/%s' % uuid.uuid4().hex, + f'/v3/domains/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -315,7 +310,6 @@ class SystemReaderTests( _SystemUserDomainTests, _SystemMemberAndReaderDomainTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -352,7 +346,6 @@ class SystemMemberTests( _SystemUserDomainTests, _SystemMemberAndReaderDomainTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -388,7 +381,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserDomainTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -417,7 +409,7 @@ class SystemAdminTests( update = {'domain': {'description': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/domains/%s' % domain['id'], + '/v3/domains/{}'.format(domain['id']), json=update, headers=self.headers, ) @@ -435,7 +427,7 @@ class SystemAdminTests( with self.test_client() as c: update = {'domain': {'enabled': False}} - path = '/v3/domains/%s' % domain['id'] + path = '/v3/domains/{}'.format(domain['id']) c.patch(path, json=update, headers=self.headers) c.delete(path, headers=self.headers) @@ -445,7 +437,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainReaderDomainTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -485,7 +476,6 @@ class ProjectReaderTests( common_auth.AuthTestMixin, _ProjectUserDomainTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -531,7 +521,6 @@ class ProjectMemberTests( common_auth.AuthTestMixin, _ProjectUserDomainTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -577,7 +566,6 @@ class ProjectAdminTests( common_auth.AuthTestMixin, _ProjectUserDomainTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_ec2_credential.py b/keystone/tests/protection/v3/test_ec2_credential.py index 7ab097beb1..2b6a15ea9a 100644 --- a/keystone/tests/protection/v3/test_ec2_credential.py +++ b/keystone/tests/protection/v3/test_ec2_credential.py @@ -28,7 +28,6 @@ PROVIDERS = provider_api.ProviderAPIs class _UserEC2CredentialTests: - def test_user_can_get_their_ec2_credentials(self): project = unit.new_project_ref( domain_id=CONF.identity.default_domain_id @@ -42,16 +41,15 @@ class _UserEC2CredentialTests: with self.test_client() as c: r = c.post( - '/v3/users/%s/credentials/OS-EC2' % self.user_id, + f'/v3/users/{self.user_id}/credentials/OS-EC2', json={'tenant_id': project['id']}, headers=self.headers, ) credential_id = r.json['credential']['access'] - path = '/v3/users/{}/credentials/OS-EC2/{}'.format( - self.user_id, - credential_id, + path = ( + f'/v3/users/{self.user_id}/credentials/OS-EC2/{credential_id}' ) r = c.get(path, headers=self.headers) self.assertEqual(self.user_id, r.json['credential']['user_id']) @@ -69,12 +67,12 @@ class _UserEC2CredentialTests: with self.test_client() as c: c.post( - '/v3/users/%s/credentials/OS-EC2' % self.user_id, + f'/v3/users/{self.user_id}/credentials/OS-EC2', json={'tenant_id': project['id']}, headers=self.headers, ) - path = '/v3/users/%s/credentials/OS-EC2' % self.user_id + path = f'/v3/users/{self.user_id}/credentials/OS-EC2' r = c.get(path, headers=self.headers) for credential in r.json['credentials']: self.assertEqual(self.user_id, credential['user_id']) @@ -92,7 +90,7 @@ class _UserEC2CredentialTests: with self.test_client() as c: c.post( - '/v3/users/%s/credentials/OS-EC2' % self.user_id, + f'/v3/users/{self.user_id}/credentials/OS-EC2', json={'tenant_id': project['id']}, headers=self.headers, expected_status_code=http.client.CREATED, @@ -111,15 +109,14 @@ class _UserEC2CredentialTests: with self.test_client() as c: r = c.post( - '/v3/users/%s/credentials/OS-EC2' % self.user_id, + f'/v3/users/{self.user_id}/credentials/OS-EC2', json={'tenant_id': project['id']}, headers=self.headers, ) credential_id = r.json['credential']['access'] c.delete( - '/v3/users/%s/credentials/OS-EC2/%s' - % (self.user_id, credential_id), + f'/v3/users/{self.user_id}/credentials/OS-EC2/{credential_id}', headers=self.headers, ) @@ -139,7 +136,7 @@ class _UserEC2CredentialTests: with self.test_client() as c: c.post( - '/v3/users/%s/credentials/OS-EC2' % user['id'], + '/v3/users/{}/credentials/OS-EC2'.format(user['id']), json={'tenant_id': project['id']}, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -169,22 +166,20 @@ class _UserEC2CredentialTests: headers = {'X-Auth-Token': token_id} r = c.post( - '/v3/users/%s/credentials/OS-EC2' % user['id'], + '/v3/users/{}/credentials/OS-EC2'.format(user['id']), json={'tenant_id': project['id']}, headers=headers, ) credential_id = r.json['credential']['access'] c.delete( - '/v3/users/%s/credentials/OS-EC2/%s' - % (self.user_id, credential_id), + f'/v3/users/{self.user_id}/credentials/OS-EC2/{credential_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _SystemUserTests: - def test_user_can_get_ec2_credentials_for_others(self): user = unit.new_user_ref(domain_id=CONF.identity.default_domain_id) user_password = user['password'] @@ -209,15 +204,14 @@ class _SystemUserTests: headers = {'X-Auth-Token': token_id} r = c.post( - '/v3/users/%s/credentials/OS-EC2' % user['id'], + '/v3/users/{}/credentials/OS-EC2'.format(user['id']), json={'tenant_id': project['id']}, headers=headers, ) credential_id = r.json['credential']['access'] - path = '/v3/users/{}/credentials/OS-EC2/{}'.format( - self.user_id, - credential_id, + path = ( + f'/v3/users/{self.user_id}/credentials/OS-EC2/{credential_id}' ) c.get( path, headers=self.headers, expected_status_code=http.client.OK @@ -225,7 +219,6 @@ class _SystemUserTests: class _SystemReaderAndMemberTests: - def test_user_cannot_list_ec2_credentials_for_others(self): user = unit.new_user_ref(domain_id=CONF.identity.default_domain_id) user_password = user['password'] @@ -250,12 +243,12 @@ class _SystemReaderAndMemberTests: headers = {'X-Auth-Token': token_id} c.post( - '/v3/users/%s/credentials/OS-EC2' % user['id'], + '/v3/users/{}/credentials/OS-EC2'.format(user['id']), json={'tenant_id': project['id']}, headers=headers, ) - path = '/v3/users/%s/credentials/OS-EC2' % self.user_id + path = f'/v3/users/{self.user_id}/credentials/OS-EC2' r = c.get(path, headers=self.headers) self.assertEqual([], r.json['credentials']) @@ -266,7 +259,6 @@ class SystemReaderTests( _SystemUserTests, _SystemReaderAndMemberTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -301,7 +293,6 @@ class SystemMemberTests( _SystemUserTests, _SystemReaderAndMemberTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -335,7 +326,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -382,12 +372,12 @@ class SystemAdminTests( headers = {'X-Auth-Token': token_id} c.post( - '/v3/users/%s/credentials/OS-EC2' % user['id'], + '/v3/users/{}/credentials/OS-EC2'.format(user['id']), json={'tenant_id': project['id']}, headers=headers, ) - path = '/v3/users/%s/credentials/OS-EC2' % self.user_id + path = f'/v3/users/{self.user_id}/credentials/OS-EC2' r = c.get(path, headers=self.headers) self.assertEqual([], r.json['credentials']) @@ -407,7 +397,7 @@ class SystemAdminTests( with self.test_client() as c: c.post( - '/v3/users/%s/credentials/OS-EC2' % user['id'], + '/v3/users/{}/credentials/OS-EC2'.format(user['id']), json={'tenant_id': project['id']}, headers=self.headers, ) @@ -436,15 +426,14 @@ class SystemAdminTests( headers = {'X-Auth-Token': token_id} r = c.post( - '/v3/users/%s/credentials/OS-EC2' % user['id'], + '/v3/users/{}/credentials/OS-EC2'.format(user['id']), json={'tenant_id': project['id']}, headers=headers, ) credential_id = r.json['credential']['access'] c.delete( - '/v3/users/%s/credentials/OS-EC2/%s' - % (self.user_id, credential_id), + f'/v3/users/{self.user_id}/credentials/OS-EC2/{credential_id}', headers=self.headers, ) @@ -455,7 +444,6 @@ class ProjectAdminTests( _UserEC2CredentialTests, _SystemReaderAndMemberTests, ): - def _override_policy(self): # TODO(cmurphy): Remove this once the deprecated policies in # keystone.common.policies.ec2_credential have been removed. This is diff --git a/keystone/tests/protection/v3/test_endpoint_group.py b/keystone/tests/protection/v3/test_endpoint_group.py index a913bc37ed..f2fafc1964 100644 --- a/keystone/tests/protection/v3/test_endpoint_group.py +++ b/keystone/tests/protection/v3/test_endpoint_group.py @@ -52,7 +52,9 @@ class _SystemUserEndpointGroupsTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/endpoint_groups/%s' % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}'.format( + endpoint_group['id'] + ), headers=self.headers, ) @@ -72,8 +74,9 @@ class _SystemUserEndpointGroupsTests: ) with self.test_client() as c: r = c.get( - '/v3/OS-EP-FILTER/endpoint_groups/%s/projects' - % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}/projects'.format( + endpoint_group['id'] + ), headers=self.headers, ) projects = [] @@ -97,8 +100,9 @@ class _SystemUserEndpointGroupsTests: ) with self.test_client() as c: r = c.get( - '/v3/OS-EP-FILTER/endpoint_groups/%s/endpoints' - % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}/endpoints'.format( + endpoint_group['id'] + ), headers=self.headers, ) endpoints = [] @@ -122,8 +126,9 @@ class _SystemUserEndpointGroupsTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/endpoint_groups/%s/projects/%s' - % (endpoint_group['id'], project['id']), + '/v3/OS-EP-FILTER/endpoint_groups/{}/projects/{}'.format( + endpoint_group['id'], project['id'] + ), headers=self.headers, ) @@ -143,7 +148,9 @@ class _SystemUserEndpointGroupsTests: ) with self.test_client() as c: r = c.get( - '/v3/OS-EP-FILTER/projects/%s/endpoint_groups' % project['id'], + '/v3/OS-EP-FILTER/projects/{}/endpoint_groups'.format( + project['id'] + ), headers=self.headers, ) endpoint_groups = [] @@ -184,7 +191,9 @@ class _SystemReaderAndMemberUserEndpointGroupsTests: with self.test_client() as c: c.patch( - '/v3/OS-EP-FILTER/endpoint_groups/%s' % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}'.format( + endpoint_group['id'] + ), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -200,7 +209,9 @@ class _SystemReaderAndMemberUserEndpointGroupsTests: with self.test_client() as c: c.delete( - '/v3/OS-EP-FILTER/endpoint_groups/%s' % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}'.format( + endpoint_group['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -218,8 +229,9 @@ class _SystemReaderAndMemberUserEndpointGroupsTests: ) with self.test_client() as c: c.put( - '/v3/OS-EP-FILTER/endpoint_groups/%s/projects/%s' - % (endpoint_group['id'], project['id']), + '/v3/OS-EP-FILTER/endpoint_groups/{}/projects/{}'.format( + endpoint_group['id'], project['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -237,15 +249,15 @@ class _SystemReaderAndMemberUserEndpointGroupsTests: ) with self.test_client() as c: c.delete( - '/v3/OS-EP-FILTER/endpoint_groups/%s/projects/%s' - % (endpoint_group['id'], project['id']), + '/v3/OS-EP-FILTER/endpoint_groups/{}/projects/{}'.format( + endpoint_group['id'], project['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainAndProjectUserEndpointGroupTests: - def test_user_cannot_list_endpoint_groups(self): endpoint_group = unit.new_endpoint_group_ref( filters={'interface': 'public'} @@ -270,7 +282,9 @@ class _DomainAndProjectUserEndpointGroupTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/endpoint_groups/%s' % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}'.format( + endpoint_group['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -291,8 +305,9 @@ class _DomainAndProjectUserEndpointGroupTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/endpoint_groups/%s/projects' - % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}/projects'.format( + endpoint_group['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -313,8 +328,9 @@ class _DomainAndProjectUserEndpointGroupTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/endpoint_groups/%s/endpoints' - % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}/endpoints'.format( + endpoint_group['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -335,8 +351,9 @@ class _DomainAndProjectUserEndpointGroupTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/endpoint_groups/%s/projects/%s' - % (endpoint_group['id'], project['id']), + '/v3/OS-EP-FILTER/endpoint_groups/{}/projects/{}'.format( + endpoint_group['id'], project['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -357,7 +374,9 @@ class _DomainAndProjectUserEndpointGroupTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/projects/%s/endpoint_groups' % project['id'], + '/v3/OS-EP-FILTER/projects/{}/endpoint_groups'.format( + project['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -392,7 +411,9 @@ class _DomainAndProjectUserEndpointGroupTests: with self.test_client() as c: c.patch( - '/v3/OS-EP-FILTER/endpoint_groups/%s' % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}'.format( + endpoint_group['id'] + ), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -408,7 +429,9 @@ class _DomainAndProjectUserEndpointGroupTests: with self.test_client() as c: c.delete( - '/v3/OS-EP-FILTER/endpoint_groups/%s' % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}'.format( + endpoint_group['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -426,8 +449,9 @@ class _DomainAndProjectUserEndpointGroupTests: ) with self.test_client() as c: c.put( - '/v3/OS-EP-FILTER/endpoint_groups/%s/projects/%s' - % (endpoint_group['id'], project['id']), + '/v3/OS-EP-FILTER/endpoint_groups/{}/projects/{}'.format( + endpoint_group['id'], project['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -445,8 +469,9 @@ class _DomainAndProjectUserEndpointGroupTests: ) with self.test_client() as c: c.delete( - '/v3/OS-EP-FILTER/endpoint_groups/%s/projects/%s' - % (endpoint_group['id'], project['id']), + '/v3/OS-EP-FILTER/endpoint_groups/{}/projects/{}'.format( + endpoint_group['id'], project['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -458,7 +483,6 @@ class SystemReaderTests( _SystemUserEndpointGroupsTests, _SystemReaderAndMemberUserEndpointGroupsTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -493,7 +517,6 @@ class SystemMemberTests( _SystemUserEndpointGroupsTests, _SystemReaderAndMemberUserEndpointGroupsTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -527,7 +550,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserEndpointGroupsTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -579,7 +601,9 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/OS-EP-FILTER/endpoint_groups/%s' % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}'.format( + endpoint_group['id'] + ), json=update, headers=self.headers, ) @@ -594,7 +618,9 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/OS-EP-FILTER/endpoint_groups/%s' % endpoint_group['id'], + '/v3/OS-EP-FILTER/endpoint_groups/{}'.format( + endpoint_group['id'] + ), headers=self.headers, ) @@ -611,8 +637,9 @@ class SystemAdminTests( ) with self.test_client() as c: c.put( - '/v3/OS-EP-FILTER/endpoint_groups/%s/projects/%s' - % (endpoint_group['id'], project['id']), + '/v3/OS-EP-FILTER/endpoint_groups/{}/projects/{}'.format( + endpoint_group['id'], project['id'] + ), headers=self.headers, ) @@ -632,8 +659,9 @@ class SystemAdminTests( ) with self.test_client() as c: c.delete( - '/v3/OS-EP-FILTER/endpoint_groups/%s/projects/%s' - % (endpoint_group['id'], project['id']), + '/v3/OS-EP-FILTER/endpoint_groups/{}/projects/{}'.format( + endpoint_group['id'], project['id'] + ), headers=self.headers, ) @@ -643,7 +671,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserEndpointGroupTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -681,7 +708,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserEndpointGroupTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -708,7 +734,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _DomainAndProjectUserEndpointGroupTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_endpoints.py b/keystone/tests/protection/v3/test_endpoints.py index 0edd0811ee..356f508b51 100644 --- a/keystone/tests/protection/v3/test_endpoints.py +++ b/keystone/tests/protection/v3/test_endpoints.py @@ -55,7 +55,9 @@ class _SystemUserEndpointTests: ) with self.test_client() as c: - c.get('/v3/endpoints/%s' % endpoint['id'], headers=self.headers) + c.get( + '/v3/endpoints/{}'.format(endpoint['id']), headers=self.headers + ) class _SystemReaderAndMemberUserEndpointTests: @@ -91,7 +93,7 @@ class _SystemReaderAndMemberUserEndpointTests: with self.test_client() as c: c.patch( - '/v3/endpoints/%s' % endpoint['id'], + '/v3/endpoints/{}'.format(endpoint['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -108,14 +110,13 @@ class _SystemReaderAndMemberUserEndpointTests: with self.test_client() as c: c.delete( - '/v3/endpoints/%s' % endpoint['id'], + '/v3/endpoints/{}'.format(endpoint['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainAndProjectUserEndpointTests: - def test_user_cannot_create_endpoints(self): create = { 'endpoint': { @@ -163,7 +164,7 @@ class _DomainAndProjectUserEndpointTests: with self.test_client() as c: c.get( - '/v3/endpoints/%s' % endpoint['id'], + '/v3/endpoints/{}'.format(endpoint['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -181,7 +182,7 @@ class _DomainAndProjectUserEndpointTests: with self.test_client() as c: c.patch( - '/v3/endpoints/%s' % endpoint['id'], + '/v3/endpoints/{}'.format(endpoint['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -198,7 +199,7 @@ class _DomainAndProjectUserEndpointTests: with self.test_client() as c: c.delete( - '/v3/endpoints/%s' % endpoint['id'], + '/v3/endpoints/{}'.format(endpoint['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -210,7 +211,6 @@ class SystemReaderTests( _SystemUserEndpointTests, _SystemReaderAndMemberUserEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -245,7 +245,6 @@ class SystemMemberTests( _SystemUserEndpointTests, _SystemReaderAndMemberUserEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -279,7 +278,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -330,7 +328,7 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/endpoints/%s' % endpoint['id'], + '/v3/endpoints/{}'.format(endpoint['id']), json=update, headers=self.headers, ) @@ -346,8 +344,7 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/endpoints/%s' % endpoint['id'], - headers=self.headers, + '/v3/endpoints/{}'.format(endpoint['id']), headers=self.headers ) @@ -356,7 +353,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -394,7 +390,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -421,7 +416,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _DomainAndProjectUserEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_grants.py b/keystone/tests/protection/v3/test_grants.py index 70e30fe8d2..2ac3c29b33 100644 --- a/keystone/tests/protection/v3/test_grants.py +++ b/keystone/tests/protection/v3/test_grants.py @@ -29,7 +29,6 @@ PROVIDERS = provider_api.ProviderAPIs class _SystemUserGrantTests: - def test_can_list_grants_for_user_on_project(self): user = PROVIDERS.identity_api.create_user( unit.new_user_ref(domain_id=CONF.identity.default_domain_id) @@ -97,8 +96,9 @@ class _SystemUserGrantTests: with self.test_client() as c: r = c.get( - '/v3/projects/%s/groups/%s/roles' - % (project['id'], group['id']), + '/v3/projects/{}/groups/{}/roles'.format( + project['id'], group['id'] + ), headers=self.headers, ) self.assertEqual(1, len(r.json['roles'])) @@ -145,11 +145,8 @@ class _SystemUserGrantTests: with self.test_client() as c: c.get( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, @@ -172,8 +169,9 @@ class _SystemUserGrantTests: with self.test_client() as c: c.get( - '/v3/domains/%s/users/%s/roles/%s' - % (domain['id'], user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain['id'], user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -196,8 +194,7 @@ class _SystemUserGrantTests: with self.test_client() as c: c.get( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -223,11 +220,8 @@ class _SystemUserGrantTests: with self.test_client() as c: c.get( - '/v3/domains/%s/groups/%s/roles/%s' - % ( - domain['id'], - group['id'], - self.bootstrapper.reader_role_id, + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain['id'], group['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, @@ -235,7 +229,6 @@ class _SystemUserGrantTests: class _SystemMemberAndReaderGrantTests: - def test_cannot_create_grant_for_user_on_project(self): user = PROVIDERS.identity_api.create_user( unit.new_user_ref(domain_id=CONF.identity.default_domain_id) @@ -248,11 +241,8 @@ class _SystemMemberAndReaderGrantTests: with self.test_client() as c: c.put( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -269,8 +259,9 @@ class _SystemMemberAndReaderGrantTests: with self.test_client() as c: c.put( - '/v3/domains/%s/users/%s/roles/%s' - % (domain['id'], user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain['id'], user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -287,8 +278,7 @@ class _SystemMemberAndReaderGrantTests: with self.test_client() as c: c.put( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -308,11 +298,8 @@ class _SystemMemberAndReaderGrantTests: with self.test_client() as c: c.put( - '/v3/domains/%s/groups/%s/roles/%s' - % ( - domain['id'], - group['id'], - self.bootstrapper.reader_role_id, + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain['id'], group['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -336,11 +323,8 @@ class _SystemMemberAndReaderGrantTests: with self.test_client() as c: c.delete( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -363,8 +347,9 @@ class _SystemMemberAndReaderGrantTests: with self.test_client() as c: c.delete( - '/v3/domains/%s/users/%s/roles/%s' - % (domain['id'], user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain['id'], user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -387,8 +372,7 @@ class _SystemMemberAndReaderGrantTests: with self.test_client() as c: c.delete( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -414,11 +398,8 @@ class _SystemMemberAndReaderGrantTests: with self.test_client() as c: c.delete( - '/v3/domains/%s/groups/%s/roles/%s' - % ( - domain['id'], - group['id'], - self.bootstrapper.reader_role_id, + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain['id'], group['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -426,7 +407,6 @@ class _SystemMemberAndReaderGrantTests: class _DomainUserTests: - def test_can_list_grants_for_user_on_project(self): user = PROVIDERS.identity_api.create_user( unit.new_user_ref(domain_id=self.domain_id) @@ -488,8 +468,9 @@ class _DomainUserTests: with self.test_client() as c: r = c.get( - '/v3/projects/%s/groups/%s/roles' - % (project['id'], group['id']), + '/v3/projects/{}/groups/{}/roles'.format( + project['id'], group['id'] + ), headers=self.headers, ) self.assertEqual(1, len(r.json['roles'])) @@ -507,8 +488,9 @@ class _DomainUserTests: with self.test_client() as c: r = c.get( - '/v3/domains/%s/groups/%s/roles' - % (self.domain_id, group['id']), + '/v3/domains/{}/groups/{}/roles'.format( + self.domain_id, group['id'] + ), headers=self.headers, ) self.assertEqual(1, len(r.json['roles'])) @@ -530,11 +512,8 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, @@ -553,8 +532,7 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/domains/%s/users/%s/roles/%s' - % ( + '/v3/domains/{}/users/{}/roles/{}'.format( self.domain_id, user['id'], self.bootstrapper.reader_role_id, @@ -580,8 +558,7 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -603,8 +580,7 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/domains/%s/groups/%s/roles/%s' - % ( + '/v3/domains/{}/groups/{}/roles/{}'.format( self.domain_id, group['id'], self.bootstrapper.reader_role_id, @@ -735,8 +711,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/projects/%s/groups/%s/roles' - % (project['id'], group['id']), + '/v3/projects/{}/groups/{}/roles'.format( + project['id'], group['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -763,8 +740,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/projects/%s/groups/%s/roles' - % (project['id'], group['id']), + '/v3/projects/{}/groups/{}/roles'.format( + project['id'], group['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -837,11 +815,8 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -869,11 +844,8 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -905,8 +877,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/projects/%s/users/%s/roles/%s' - % (project['id'], user['id'], role['id']), + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], role['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -927,8 +900,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/domains/%s/users/%s/roles/%s' - % (domain_id, user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain_id, user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -949,8 +923,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/domains/%s/users/%s/roles/%s' - % (domain_id, user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain_id, user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -977,8 +952,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/domains/%s/users/%s/roles/%s' - % (domain_id, user['id'], role['id']), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain_id, user['id'], role['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1005,8 +981,7 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -1037,8 +1012,7 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -1073,8 +1047,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/projects/%s/groups/%s/roles/%s' - % (project['id'], group['id'], role['id']), + '/v3/projects/{}/groups/{}/roles/{}'.format( + project['id'], group['id'], role['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1095,8 +1070,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/domains/%s/groups/%s/roles/%s' - % (domain_id, group['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain_id, group['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1117,8 +1093,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/domains/%s/groups/%s/roles/%s' - % (domain_id, group['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain_id, group['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1145,8 +1122,9 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/domains/%s/groups/%s/roles/%s' - % (domain_id, group['id'], role['id']), + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain_id, group['id'], role['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1167,11 +1145,8 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -1193,11 +1168,8 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -1223,8 +1195,9 @@ class _DomainUserTests: ) with self.test_client() as c: c.put( - '/v3/projects/%s/users/%s/roles/%s' - % (project['id'], user['id'], role['id']), + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], role['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1239,8 +1212,9 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/domains/%s/users/%s/roles/%s' - % (domain_id, user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain_id, user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1255,8 +1229,9 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/domains/%s/users/%s/roles/%s' - % (domain_id, user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain_id, user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1278,8 +1253,9 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/domains/%s/users/%s/roles/%s' - % (domain_id, user['id'], role['id']), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain_id, user['id'], role['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1300,8 +1276,7 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -1326,8 +1301,7 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -1357,8 +1331,9 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/projects/%s/groups/%s/roles/%s' - % (project['id'], group['id'], role['id']), + '/v3/projects/{}/groups/{}/roles/{}'.format( + project['id'], group['id'], role['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1373,8 +1348,9 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/domains/%s/groups/%s/roles/%s' - % (domain_id, group['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain_id, group['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1389,8 +1365,9 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/domains/%s/groups/%s/roles/%s' - % (domain_id, group['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain_id, group['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1412,8 +1389,9 @@ class _DomainUserTests: with self.test_client() as c: c.put( - '/v3/domains/%s/groups/%s/roles/%s' - % (domain_id, group['id'], role['id']), + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain_id, group['id'], role['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1440,11 +1418,8 @@ class _DomainUserTests: with self.test_client() as c: c.delete( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -1472,11 +1447,8 @@ class _DomainUserTests: with self.test_client() as c: c.delete( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -1498,8 +1470,9 @@ class _DomainUserTests: with self.test_client() as c: c.delete( - '/v3/domains/%s/users/%s/roles/%s' - % (domain_id, user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain_id, user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1520,8 +1493,9 @@ class _DomainUserTests: with self.test_client() as c: c.delete( - '/v3/domains/%s/users/%s/roles/%s' - % (domain_id, user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain_id, user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1547,8 +1521,9 @@ class _DomainUserTests: with self.test_client() as c: c.delete( - '/v3/domains/%s/users/%s/roles/%s' - % (domain_id, user['id'], role['id']), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain_id, user['id'], role['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1575,8 +1550,7 @@ class _DomainUserTests: with self.test_client() as c: c.delete( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -1607,8 +1581,7 @@ class _DomainUserTests: with self.test_client() as c: c.delete( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -1633,8 +1606,9 @@ class _DomainUserTests: with self.test_client() as c: c.delete( - '/v3/domains/%s/groups/%s/roles/%s' - % (domain_id, group['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain_id, group['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1655,8 +1629,9 @@ class _DomainUserTests: with self.test_client() as c: c.delete( - '/v3/domains/%s/groups/%s/roles/%s' - % (domain_id, group['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain_id, group['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1682,8 +1657,9 @@ class _DomainUserTests: with self.test_client() as c: c.delete( - '/v3/domains/%s/groups/%s/roles/%s' - % (domain_id, group['id'], role['id']), + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain_id, group['id'], role['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1695,7 +1671,6 @@ class SystemReaderTests( _SystemUserGrantTests, _SystemMemberAndReaderGrantTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1730,7 +1705,6 @@ class SystemMemberTests( _SystemUserGrantTests, _SystemMemberAndReaderGrantTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1764,7 +1738,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserGrantTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1797,11 +1770,8 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, ) @@ -1817,8 +1787,9 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/domains/%s/users/%s/roles/%s' - % (domain['id'], user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain['id'], user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, ) @@ -1834,8 +1805,7 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -1854,11 +1824,8 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/domains/%s/groups/%s/roles/%s' - % ( - domain['id'], - group['id'], - self.bootstrapper.reader_role_id, + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain['id'], group['id'], self.bootstrapper.reader_role_id ), headers=self.headers, ) @@ -1881,11 +1848,8 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, ) @@ -1907,8 +1871,9 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/domains/%s/users/%s/roles/%s' - % (domain['id'], user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain['id'], user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, ) @@ -1930,8 +1895,7 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -1956,18 +1920,14 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/domains/%s/groups/%s/roles/%s' - % ( - domain['id'], - group['id'], - self.bootstrapper.reader_role_id, + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain['id'], group['id'], self.bootstrapper.reader_role_id ), headers=self.headers, ) class _DomainMemberAndReaderTests: - def test_cannot_create_grant_for_user_on_project(self): user = PROVIDERS.identity_api.create_user( unit.new_user_ref(domain_id=self.domain_id) @@ -1980,11 +1940,8 @@ class _DomainMemberAndReaderTests: with self.test_client() as c: c.put( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -2001,8 +1958,9 @@ class _DomainMemberAndReaderTests: with self.test_client() as c: c.put( - '/v3/domains/%s/users/%s/roles/%s' - % (domain['id'], user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain['id'], user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -2018,8 +1976,7 @@ class _DomainMemberAndReaderTests: with self.test_client() as c: c.put( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -2039,11 +1996,8 @@ class _DomainMemberAndReaderTests: with self.test_client() as c: c.put( - '/v3/domains/%s/groups/%s/roles/%s' - % ( - domain['id'], - group['id'], - self.bootstrapper.reader_role_id, + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain['id'], group['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -2066,11 +2020,8 @@ class _DomainMemberAndReaderTests: with self.test_client() as c: c.delete( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -2093,8 +2044,9 @@ class _DomainMemberAndReaderTests: with self.test_client() as c: c.delete( - '/v3/domains/%s/users/%s/roles/%s' - % (domain['id'], user['id'], self.bootstrapper.reader_role_id), + '/v3/domains/{}/users/{}/roles/{}'.format( + domain['id'], user['id'], self.bootstrapper.reader_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -2117,8 +2069,7 @@ class _DomainMemberAndReaderTests: with self.test_client() as c: c.delete( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -2144,11 +2095,8 @@ class _DomainMemberAndReaderTests: with self.test_client() as c: c.delete( - '/v3/domains/%s/groups/%s/roles/%s' - % ( - domain['id'], - group['id'], - self.bootstrapper.reader_role_id, + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain['id'], group['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -2161,7 +2109,6 @@ class DomainReaderTests( _DomainUserTests, _DomainMemberAndReaderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -2200,7 +2147,6 @@ class DomainMemberTests( _DomainUserTests, _DomainMemberAndReaderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -2237,7 +2183,6 @@ class DomainAdminTests( common_auth.AuthTestMixin, _DomainUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -2305,11 +2250,8 @@ class DomainAdminTests( with self.test_client() as c: c.put( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, ) @@ -2321,8 +2263,7 @@ class DomainAdminTests( with self.test_client() as c: c.put( - '/v3/domains/%s/users/%s/roles/%s' - % ( + '/v3/domains/{}/users/{}/roles/{}'.format( self.domain_id, user['id'], self.bootstrapper.reader_role_id, @@ -2341,8 +2282,7 @@ class DomainAdminTests( with self.test_client() as c: c.put( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -2357,8 +2297,7 @@ class DomainAdminTests( with self.test_client() as c: c.put( - '/v3/domains/%s/groups/%s/roles/%s' - % ( + '/v3/domains/{}/groups/{}/roles/{}'.format( self.domain_id, group['id'], self.bootstrapper.reader_role_id, @@ -2383,11 +2322,8 @@ class DomainAdminTests( with self.test_client() as c: c.delete( - '/v3/projects/%s/users/%s/roles/%s' - % ( - project['id'], - user['id'], - self.bootstrapper.reader_role_id, + '/v3/projects/{}/users/{}/roles/{}'.format( + project['id'], user['id'], self.bootstrapper.reader_role_id ), headers=self.headers, ) @@ -2409,8 +2345,7 @@ class DomainAdminTests( with self.test_client() as c: c.delete( - '/v3/projects/%s/groups/%s/roles/%s' - % ( + '/v3/projects/{}/groups/{}/roles/{}'.format( project['id'], group['id'], self.bootstrapper.reader_role_id, @@ -2435,11 +2370,8 @@ class DomainAdminTests( with self.test_client() as c: c.delete( - '/v3/domains/%s/groups/%s/roles/%s' - % ( - domain['id'], - group['id'], - self.bootstrapper.reader_role_id, + '/v3/domains/{}/groups/{}/roles/{}'.format( + domain['id'], group['id'], self.bootstrapper.reader_role_id ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, diff --git a/keystone/tests/protection/v3/test_groups.py b/keystone/tests/protection/v3/test_groups.py index 0fb36eadee..c21c245b9d 100644 --- a/keystone/tests/protection/v3/test_groups.py +++ b/keystone/tests/protection/v3/test_groups.py @@ -53,7 +53,9 @@ class _SystemUserGroupTests: ) with self.test_client() as c: - r = c.get('/v3/groups/%s' % group['id'], headers=self.headers) + r = c.get( + '/v3/groups/{}'.format(group['id']), headers=self.headers + ) self.assertEqual(group['id'], r.json['group']['id']) def test_user_can_list_group_members(self): @@ -71,7 +73,7 @@ class _SystemUserGroupTests: with self.test_client() as c: r = c.get( - '/v3/groups/%s/users' % group['id'], headers=self.headers + '/v3/groups/{}/users'.format(group['id']), headers=self.headers ) self.assertEqual(1, len(r.json['users'])) self.assertEqual(user['id'], r.json['users'][0]['id']) @@ -90,7 +92,9 @@ class _SystemUserGroupTests: PROVIDERS.identity_api.add_user_to_group(user['id'], group['id']) with self.test_client() as c: - r = c.get('/v3/users/%s/groups' % user['id'], headers=self.headers) + r = c.get( + '/v3/users/{}/groups'.format(user['id']), headers=self.headers + ) self.assertEqual(1, len(r.json['groups'])) self.assertEqual(group['id'], r.json['groups'][0]['id']) @@ -117,7 +121,7 @@ class _SystemUserGroupTests: def test_user_cannot_get_non_existent_group_not_found(self): with self.test_client() as c: c.get( - '/v3/groups/%s' % uuid.uuid4().hex, + f'/v3/groups/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -155,7 +159,7 @@ class _SystemAndDomainMemberAndReaderGroupTests: with self.test_client() as c: c.patch( - '/v3/groups/%s' % group['id'], + '/v3/groups/{}'.format(group['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -171,7 +175,7 @@ class _SystemAndDomainMemberAndReaderGroupTests: with self.test_client() as c: c.delete( - '/v3/groups/%s' % group['id'], + '/v3/groups/{}'.format(group['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -221,7 +225,6 @@ class SystemReaderTests( _SystemUserGroupTests, _SystemAndDomainMemberAndReaderGroupTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -256,7 +259,6 @@ class SystemMemberTests( _SystemUserGroupTests, _SystemAndDomainMemberAndReaderGroupTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -290,7 +292,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserGroupTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -335,7 +336,7 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/groups/%s' % group['id'], + '/v3/groups/{}'.format(group['id']), json=update, headers=self.headers, ) @@ -349,7 +350,7 @@ class SystemAdminTests( ) with self.test_client() as c: - c.delete('/v3/groups/%s' % group['id'], headers=self.headers) + c.delete('/v3/groups/{}'.format(group['id']), headers=self.headers) def test_user_can_add_users_to_group(self): domain = PROVIDERS.resource_api.create_domain( @@ -389,7 +390,6 @@ class SystemAdminTests( class _DomainUserGroupTests: - def test_user_can_list_groups_in_domain(self): # second domain domain = PROVIDERS.resource_api.create_domain( @@ -420,7 +420,8 @@ class _DomainUserGroupTests: ) with self.test_client() as c: r = c.get( - '/v3/groups?domain_id=%s' % domain['id'], headers=self.headers + '/v3/groups?domain_id={}'.format(domain['id']), + headers=self.headers, ) self.assertEqual(0, len(r.json['groups'])) @@ -429,7 +430,9 @@ class _DomainUserGroupTests: unit.new_group_ref(domain_id=self.domain_id) ) with self.test_client() as c: - r = c.get('/v3/groups/%s' % group['id'], headers=self.headers) + r = c.get( + '/v3/groups/{}'.format(group['id']), headers=self.headers + ) self.assertEqual(group['id'], r.json['group']['id']) def test_user_cannot_get_group_in_other_domain(self): @@ -441,7 +444,7 @@ class _DomainUserGroupTests: ) with self.test_client() as c: c.get( - '/v3/groups/%s' % group['id'], + '/v3/groups/{}'.format(group['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -449,7 +452,7 @@ class _DomainUserGroupTests: def test_user_cannot_get_non_existent_group_forbidden(self): with self.test_client() as c: c.get( - '/v3/groups/%s' % uuid.uuid4().hex, + f'/v3/groups/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -463,7 +466,9 @@ class _DomainUserGroupTests: ) PROVIDERS.identity_api.add_user_to_group(user['id'], group['id']) with self.test_client() as c: - r = c.get('/v3/users/%s/groups' % user['id'], headers=self.headers) + r = c.get( + '/v3/users/{}/groups'.format(user['id']), headers=self.headers + ) self.assertEqual(1, len(r.json['groups'])) self.assertEqual(group['id'], r.json['groups'][0]['id']) @@ -480,7 +485,7 @@ class _DomainUserGroupTests: PROVIDERS.identity_api.add_user_to_group(user['id'], group['id']) with self.test_client() as c: c.get( - '/v3/users/%s/groups' % user['id'], + '/v3/users/{}/groups'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -488,7 +493,7 @@ class _DomainUserGroupTests: def test_user_cannot_list_groups_for_non_existent_user_forbidden(self): with self.test_client() as c: c.get( - '/v3/users/%s/groups' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}/groups', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -511,7 +516,9 @@ class _DomainUserGroupTests: PROVIDERS.identity_api.add_user_to_group(user['id'], group1['id']) PROVIDERS.identity_api.add_user_to_group(user['id'], group2['id']) with self.test_client() as c: - r = c.get('/v3/users/%s/groups' % user['id'], headers=self.headers) + r = c.get( + '/v3/users/{}/groups'.format(user['id']), headers=self.headers + ) # only one group should be visible self.assertEqual(1, len(r.json['groups'])) self.assertEqual(group2['id'], r.json['groups'][0]['id']) @@ -526,7 +533,7 @@ class _DomainUserGroupTests: PROVIDERS.identity_api.add_user_to_group(user['id'], group['id']) with self.test_client() as c: r = c.get( - '/v3/groups/%s/users' % group['id'], headers=self.headers + '/v3/groups/{}/users'.format(group['id']), headers=self.headers ) self.assertEqual(1, len(r.json['users'])) self.assertEqual(user['id'], r.json['users'][0]['id']) @@ -550,7 +557,7 @@ class _DomainUserGroupTests: PROVIDERS.identity_api.add_user_to_group(user2['id'], group['id']) with self.test_client() as c: r = c.get( - '/v3/groups/%s/users' % group['id'], headers=self.headers + '/v3/groups/{}/users'.format(group['id']), headers=self.headers ) # only one user should be visible self.assertEqual(1, len(r.json['users'])) @@ -569,7 +576,7 @@ class _DomainUserGroupTests: PROVIDERS.identity_api.add_user_to_group(user['id'], group['id']) with self.test_client() as c: c.get( - '/v3/groups/%s/users' % group['id'], + '/v3/groups/{}/users'.format(group['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -577,7 +584,7 @@ class _DomainUserGroupTests: def test_user_cannot_list_users_in_non_existent_group_forbidden(self): with self.test_client() as c: c.get( - '/v3/groups/%s/users' % uuid.uuid4().hex, + f'/v3/groups/{uuid.uuid4().hex}/users', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -592,14 +599,16 @@ class _DomainUserGroupTests: PROVIDERS.identity_api.add_user_to_group(user['id'], group['id']) with self.test_client() as c: c.head( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=user['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) c.get( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=user['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -617,14 +626,16 @@ class _DomainUserGroupTests: PROVIDERS.identity_api.add_user_to_group(user['id'], group['id']) with self.test_client() as c: c.head( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=user['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) c.get( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=user['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -636,7 +647,6 @@ class DomainReaderTests( _DomainUserGroupTests, _SystemAndDomainMemberAndReaderGroupTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -701,7 +711,6 @@ class DomainMemberTests( _DomainUserGroupTests, _SystemAndDomainMemberAndReaderGroupTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -765,7 +774,6 @@ class DomainAdminTests( common_auth.AuthTestMixin, _DomainUserGroupTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -861,7 +869,7 @@ class DomainAdminTests( update = {'group': {'description': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/groups/%s' % group['id'], + '/v3/groups/{}'.format(group['id']), json=update, headers=self.headers, ) @@ -877,7 +885,7 @@ class DomainAdminTests( update = {'group': {'description': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/groups/%s' % group['id'], + '/v3/groups/{}'.format(group['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -888,7 +896,7 @@ class DomainAdminTests( unit.new_group_ref(domain_id=self.domain_id) ) with self.test_client() as c: - c.delete('/v3/groups/%s' % group['id'], headers=self.headers) + c.delete('/v3/groups/{}'.format(group['id']), headers=self.headers) def test_user_cannot_delete_group_in_other_domain(self): domain = PROVIDERS.resource_api.create_domain( @@ -899,7 +907,7 @@ class DomainAdminTests( ) with self.test_client() as c: c.delete( - '/v3/groups/%s' % group['id'], + '/v3/groups/{}'.format(group['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -914,8 +922,9 @@ class DomainAdminTests( PROVIDERS.identity_api.add_user_to_group(user['id'], group['id']) with self.test_client() as c: c.delete( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=user['id'] + ), headers=self.headers, ) @@ -932,8 +941,9 @@ class DomainAdminTests( PROVIDERS.identity_api.add_user_to_group(user['id'], group['id']) with self.test_client() as c: c.delete( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=user['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -951,8 +961,9 @@ class DomainAdminTests( PROVIDERS.identity_api.add_user_to_group(user['id'], group['id']) with self.test_client() as c: c.delete( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=user['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -963,8 +974,9 @@ class DomainAdminTests( ) with self.test_client() as c: c.delete( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': uuid.uuid4().hex}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=uuid.uuid4().hex + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -975,8 +987,9 @@ class DomainAdminTests( ) with self.test_client() as c: c.delete( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': uuid.uuid4().hex, 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=uuid.uuid4().hex, user=user['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -990,8 +1003,9 @@ class DomainAdminTests( ) with self.test_client() as c: c.put( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=user['id'] + ), headers=self.headers, ) @@ -1007,8 +1021,9 @@ class DomainAdminTests( ) with self.test_client() as c: c.put( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=user['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1025,8 +1040,9 @@ class DomainAdminTests( ) with self.test_client() as c: c.put( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=user['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1037,8 +1053,9 @@ class DomainAdminTests( ) with self.test_client() as c: c.put( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': group['id'], 'user': uuid.uuid4().hex}, + '/v3/groups/{group}/users/{user}'.format( + group=group['id'], user=uuid.uuid4().hex + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1049,8 +1066,9 @@ class DomainAdminTests( ) with self.test_client() as c: c.put( - '/v3/groups/%(group)s/users/%(user)s' - % {'group': uuid.uuid4().hex, 'user': user['id']}, + '/v3/groups/{group}/users/{user}'.format( + group=uuid.uuid4().hex, user=user['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1059,7 +1077,6 @@ class DomainAdminTests( class ProjectUserTests( base_classes.TestCaseWithBootstrap, common_auth.AuthTestMixin ): - def setUp(self): super().setUp() self.loadapp() @@ -1104,9 +1121,7 @@ class ProjectUserTests( PROVIDERS.identity_api.add_user_to_group(self.user_id, group['id']) with self.test_client() as c: - r = c.get( - '/v3/users/%s/groups' % self.user_id, headers=self.headers - ) + r = c.get(f'/v3/users/{self.user_id}/groups', headers=self.headers) self.assertEqual(1, len(r.json['groups'])) self.assertEqual(group['id'], r.json['groups'][0]['id']) @@ -1125,7 +1140,7 @@ class ProjectUserTests( with self.test_client() as c: c.get( - '/v3/users/%s/groups' % user['id'], + '/v3/users/{}/groups'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1155,7 +1170,7 @@ class ProjectUserTests( with self.test_client() as c: c.get( - '/v3/groups/%s' % group['id'], + '/v3/groups/{}'.format(group['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1175,7 +1190,7 @@ class ProjectUserTests( with self.test_client() as c: c.get( - '/v3/groups/%s/users' % group['id'], + '/v3/groups/{}/users'.format(group['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1203,7 +1218,7 @@ class ProjectUserTests( def test_user_cannot_get_non_existent_group_forbidden(self): with self.test_client() as c: c.get( - '/v3/groups/%s' % uuid.uuid4().hex, + f'/v3/groups/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) diff --git a/keystone/tests/protection/v3/test_identity_providers.py b/keystone/tests/protection/v3/test_identity_providers.py index e3f985c98f..79fd4b8429 100644 --- a/keystone/tests/protection/v3/test_identity_providers.py +++ b/keystone/tests/protection/v3/test_identity_providers.py @@ -49,7 +49,7 @@ class _SystemUserIdentityProviderTests: with self.test_client() as c: c.get( - '/v3/OS-FEDERATION/identity_providers/%s' % idp['id'], + '/v3/OS-FEDERATION/identity_providers/{}'.format(idp['id']), headers=self.headers, ) @@ -62,7 +62,7 @@ class _SystemReaderAndMemberIdentityProviderTests: with self.test_client() as c: c.put( - '/v3/OS-FEDERATION/identity_providers/%s' % uuid.uuid4().hex, + f'/v3/OS-FEDERATION/identity_providers/{uuid.uuid4().hex}', json=create, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -77,7 +77,7 @@ class _SystemReaderAndMemberIdentityProviderTests: with self.test_client() as c: c.patch( - '/v3/OS-FEDERATION/identity_providers/%s' % idp['id'], + '/v3/OS-FEDERATION/identity_providers/{}'.format(idp['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -90,7 +90,7 @@ class _SystemReaderAndMemberIdentityProviderTests: with self.test_client() as c: c.delete( - '/v3/OS-FEDERATION/identity_providers/%s' % idp['id'], + '/v3/OS-FEDERATION/identity_providers/{}'.format(idp['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -104,7 +104,7 @@ class _DomainAndProjectUserIdentityProviderTests: with self.test_client() as c: c.put( - '/v3/OS-FEDERATION/identity_providers/%s' % uuid.uuid4().hex, + f'/v3/OS-FEDERATION/identity_providers/{uuid.uuid4().hex}', json=create, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -119,7 +119,7 @@ class _DomainAndProjectUserIdentityProviderTests: with self.test_client() as c: c.patch( - '/v3/OS-FEDERATION/identity_providers/%s' % idp['id'], + '/v3/OS-FEDERATION/identity_providers/{}'.format(idp['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -144,7 +144,7 @@ class _DomainAndProjectUserIdentityProviderTests: with self.test_client() as c: c.get( - '/v3/OS-FEDERATION/identity_providers/%s' % idp['id'], + '/v3/OS-FEDERATION/identity_providers/{}'.format(idp['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -156,7 +156,7 @@ class _DomainAndProjectUserIdentityProviderTests: with self.test_client() as c: c.delete( - '/v3/OS-FEDERATION/identity_providers/%s' % idp['id'], + '/v3/OS-FEDERATION/identity_providers/{}'.format(idp['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -168,7 +168,6 @@ class SystemReaderTests( _SystemUserIdentityProviderTests, _SystemReaderAndMemberIdentityProviderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -203,7 +202,6 @@ class SystemMemberTests( _SystemUserIdentityProviderTests, _SystemReaderAndMemberIdentityProviderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -237,7 +235,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserIdentityProviderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -265,7 +262,7 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/OS-FEDERATION/identity_providers/%s' % uuid.uuid4().hex, + f'/v3/OS-FEDERATION/identity_providers/{uuid.uuid4().hex}', json=create, headers=self.headers, expected_status_code=http.client.CREATED, @@ -280,7 +277,7 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/OS-FEDERATION/identity_providers/%s' % idp['id'], + '/v3/OS-FEDERATION/identity_providers/{}'.format(idp['id']), json=update, headers=self.headers, ) @@ -292,7 +289,7 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/OS-FEDERATION/identity_providers/%s' % idp['id'], + '/v3/OS-FEDERATION/identity_providers/{}'.format(idp['id']), headers=self.headers, ) @@ -302,7 +299,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserIdentityProviderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -340,7 +336,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserIdentityProviderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -367,7 +362,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _DomainAndProjectUserIdentityProviderTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_implied_roles.py b/keystone/tests/protection/v3/test_implied_roles.py index bcbd0c332d..eda371d144 100644 --- a/keystone/tests/protection/v3/test_implied_roles.py +++ b/keystone/tests/protection/v3/test_implied_roles.py @@ -43,8 +43,7 @@ class _SystemUserImpliedRoleTests: with self.test_client() as c: r = c.get( - '/v3/roles/%s/implies' % self.prior_role_id, - headers=self.headers, + f'/v3/roles/{self.prior_role_id}/implies', headers=self.headers ) self.assertEqual(1, len(r.json['role_inference']['implies'])) @@ -55,13 +54,11 @@ class _SystemUserImpliedRoleTests: with self.test_client() as c: c.get( - '/v3/roles/%s/implies/%s' - % (self.prior_role_id, self.implied_role_id), + f'/v3/roles/{self.prior_role_id}/implies/{self.implied_role_id}', headers=self.headers, ) c.head( - '/v3/roles/%s/implies/%s' - % (self.prior_role_id, self.implied_role_id), + f'/v3/roles/{self.prior_role_id}/implies/{self.implied_role_id}', headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -84,8 +81,7 @@ class _SystemReaderAndMemberImpliedRoleTests: def test_user_cannot_create_implied_roles(self): with self.test_client() as c: c.put( - '/v3/roles/%s/implies/%s' - % (self.prior_role_id, self.implied_role_id), + f'/v3/roles/{self.prior_role_id}/implies/{self.implied_role_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -97,8 +93,7 @@ class _SystemReaderAndMemberImpliedRoleTests: with self.test_client() as c: c.delete( - '/v3/roles/%s/implies/%s' - % (self.prior_role_id, self.implied_role_id), + f'/v3/roles/{self.prior_role_id}/implies/{self.implied_role_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -111,7 +106,6 @@ class SystemReaderTests( _SystemUserImpliedRoleTests, _SystemReaderAndMemberImpliedRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -149,7 +143,6 @@ class SystemMemberTests( _SystemUserImpliedRoleTests, _SystemReaderAndMemberImpliedRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -186,7 +179,6 @@ class SystemAdminTests( _ImpliedRolesSetupMixin, _SystemUserImpliedRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -214,8 +206,7 @@ class SystemAdminTests( def test_user_can_create_implied_roles(self): with self.test_client() as c: c.put( - '/v3/roles/%s/implies/%s' - % (self.prior_role_id, self.implied_role_id), + f'/v3/roles/{self.prior_role_id}/implies/{self.implied_role_id}', headers=self.headers, expected_status_code=http.client.CREATED, ) @@ -227,7 +218,6 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/roles/%s/implies/%s' - % (self.prior_role_id, self.implied_role_id), + f'/v3/roles/{self.prior_role_id}/implies/{self.implied_role_id}', headers=self.headers, ) diff --git a/keystone/tests/protection/v3/test_limits.py b/keystone/tests/protection/v3/test_limits.py index 41bbdb20d1..18febfbadb 100644 --- a/keystone/tests/protection/v3/test_limits.py +++ b/keystone/tests/protection/v3/test_limits.py @@ -86,7 +86,7 @@ class _UserLimitTests: limit_id, _ = _create_limits_and_dependencies() with self.test_client() as c: - r = c.get('/v3/limits/%s' % limit_id, headers=self.headers) + r = c.get(f'/v3/limits/{limit_id}', headers=self.headers) self.assertEqual(limit_id, r.json['limit']['id']) def test_user_can_list_limits(self): @@ -148,7 +148,7 @@ class _UserLimitTests: with self.test_client() as c: c.patch( - '/v3/limits/%s' % limit_id, + f'/v3/limits/{limit_id}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -159,7 +159,7 @@ class _UserLimitTests: with self.test_client() as c: c.delete( - '/v3/limits/%s' % limit_id, + f'/v3/limits/{limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -203,7 +203,6 @@ class SystemMemberTests( common_auth.AuthTestMixin, _UserLimitTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -235,7 +234,6 @@ class SystemMemberTests( class SystemAdminTests( base_classes.TestCaseWithBootstrap, common_auth.AuthTestMixin ): - def setUp(self): super().setUp() self.loadapp() @@ -262,7 +260,7 @@ class SystemAdminTests( limit_id, _ = _create_limits_and_dependencies() with self.test_client() as c: - r = c.get('/v3/limits/%s' % limit_id, headers=self.headers) + r = c.get(f'/v3/limits/{limit_id}', headers=self.headers) self.assertEqual(limit_id, r.json['limit']['id']) def test_user_can_list_limits(self): @@ -319,20 +317,19 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/limits/%s' % limit_id, json=update, headers=self.headers + f'/v3/limits/{limit_id}', json=update, headers=self.headers ) def test_user_can_delete_limits(self): limit_id, _ = _create_limits_and_dependencies() with self.test_client() as c: - c.delete('/v3/limits/%s' % limit_id, headers=self.headers) + c.delete(f'/v3/limits/{limit_id}', headers=self.headers) class DomainUserTests( base_classes.TestCaseWithBootstrap, common_auth.AuthTestMixin ): - def setUp(self): super().setUp() self.loadapp() @@ -370,7 +367,7 @@ class DomainUserTests( ) with self.test_client() as c: - c.get('/v3/limits/%s' % project_limit_id, headers=self.headers) + c.get(f'/v3/limits/{project_limit_id}', headers=self.headers) def test_user_can_get_domain_limits(self): _, domain_limit_id = _create_limits_and_dependencies( @@ -378,7 +375,7 @@ class DomainUserTests( ) with self.test_client() as c: - r = c.get('/v3/limits/%s' % domain_limit_id, headers=self.headers) + r = c.get(f'/v3/limits/{domain_limit_id}', headers=self.headers) self.assertEqual(self.domain_id, r.json['limit']['domain_id']) def test_user_cannot_get_project_limit_outside_domain(self): @@ -386,7 +383,7 @@ class DomainUserTests( with self.test_client() as c: c.get( - '/v3/limits/%s' % project_limit_id, + f'/v3/limits/{project_limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -396,7 +393,7 @@ class DomainUserTests( with self.test_client() as c: c.get( - '/v3/limits/%s' % domain_limit_id, + f'/v3/limits/{domain_limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -577,7 +574,7 @@ class DomainUserTests( with self.test_client() as c: c.patch( - '/v3/limits/%s' % domain_limit_id, + f'/v3/limits/{domain_limit_id}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -590,7 +587,7 @@ class DomainUserTests( with self.test_client() as c: c.patch( - '/v3/limits/%s' % domain_limit_id, + f'/v3/limits/{domain_limit_id}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -605,7 +602,7 @@ class DomainUserTests( with self.test_client() as c: c.patch( - '/v3/limits/%s' % project_limit_id, + f'/v3/limits/{project_limit_id}', headers=self.headers, json=update, expected_status_code=http.client.FORBIDDEN, @@ -618,7 +615,7 @@ class DomainUserTests( with self.test_client() as c: c.patch( - '/v3/limits/%s' % project_limit_id, + f'/v3/limits/{project_limit_id}', headers=self.headers, json=update, expected_status_code=http.client.FORBIDDEN, @@ -631,7 +628,7 @@ class DomainUserTests( with self.test_client() as c: c.delete( - '/v3/limits/%s' % domain_limit_id, + f'/v3/limits/{domain_limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -641,7 +638,7 @@ class DomainUserTests( with self.test_client() as c: c.delete( - '/v3/limits/%s' % domain_limit_id, + f'/v3/limits/{domain_limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -653,7 +650,7 @@ class DomainUserTests( with self.test_client() as c: c.delete( - '/v3/limits/%s' % project_limit_id, + f'/v3/limits/{project_limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -663,7 +660,7 @@ class DomainUserTests( with self.test_client() as c: c.delete( - '/v3/limits/%s' % project_limit_id, + f'/v3/limits/{project_limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -672,7 +669,6 @@ class DomainUserTests( class ProjectUserTests( base_classes.TestCaseWithBootstrap, common_auth.AuthTestMixin ): - def setUp(self): super().setUp() self.loadapp() @@ -718,14 +714,14 @@ class ProjectUserTests( headers = {'X-Auth-Token': token_id} with self.test_client() as c: - r = c.get('/v3/limits/%s' % project_limit_id, headers=headers) + r = c.get(f'/v3/limits/{project_limit_id}', headers=headers) def test_user_cannot_get_project_limit_without_role_assignment(self): project_limit_id, _ = _create_limits_and_dependencies() with self.test_client() as c: c.get( - '/v3/limits/%s' % project_limit_id, + f'/v3/limits/{project_limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -735,7 +731,7 @@ class ProjectUserTests( with self.test_client() as c: c.get( - '/v3/limits/%s' % domain_limit_id, + f'/v3/limits/{domain_limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -824,7 +820,7 @@ class ProjectUserTests( with self.test_client() as c: c.patch( - '/v3/limits/%s' % limit_id, + f'/v3/limits/{limit_id}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -835,14 +831,13 @@ class ProjectUserTests( with self.test_client() as c: c.delete( - '/v3/limits/%s' % limit_id, + f'/v3/limits/{limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class ProjectUserTestsWithoutEnforceScope(ProjectUserTests): - def setUp(self): super().setUp() self.config_fixture.config(group='oslo_policy', enforce_scope=False) diff --git a/keystone/tests/protection/v3/test_mappings.py b/keystone/tests/protection/v3/test_mappings.py index 6785d96869..9c5d7696d3 100644 --- a/keystone/tests/protection/v3/test_mappings.py +++ b/keystone/tests/protection/v3/test_mappings.py @@ -46,7 +46,7 @@ class _SystemUserMappingTests: with self.test_client() as c: c.get( - '/v3/OS-FEDERATION/mappings/%s' % mapping['id'], + '/v3/OS-FEDERATION/mappings/{}'.format(mapping['id']), headers=self.headers, ) @@ -70,7 +70,7 @@ class _SystemReaderAndMemberUserMappingTests: with self.test_client() as c: c.put( - '/v3/OS-FEDERATION/mappings/%s' % mapping_id, + f'/v3/OS-FEDERATION/mappings/{mapping_id}', json=create, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -95,7 +95,7 @@ class _SystemReaderAndMemberUserMappingTests: with self.test_client() as c: c.patch( - '/v3/OS-FEDERATION/mappings/%s' % mapping['id'], + '/v3/OS-FEDERATION/mappings/{}'.format(mapping['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -109,14 +109,13 @@ class _SystemReaderAndMemberUserMappingTests: with self.test_client() as c: c.delete( - '/v3/OS-FEDERATION/mappings/%s' % mapping['id'], + '/v3/OS-FEDERATION/mappings/{}'.format(mapping['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainAndProjectUserMappingTests: - def test_user_cannot_create_mappings(self): create = { 'mapping': { @@ -133,7 +132,7 @@ class _DomainAndProjectUserMappingTests: with self.test_client() as c: c.put( - '/v3/OS-FEDERATION/mappings/%s' % mapping_id, + f'/v3/OS-FEDERATION/mappings/{mapping_id}', json=create, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -160,7 +159,7 @@ class _DomainAndProjectUserMappingTests: with self.test_client() as c: c.get( - '/v3/OS-FEDERATION/mappings/%s' % mapping['id'], + '/v3/OS-FEDERATION/mappings/{}'.format(mapping['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -184,7 +183,7 @@ class _DomainAndProjectUserMappingTests: with self.test_client() as c: c.patch( - '/v3/OS-FEDERATION/mappings/%s' % mapping['id'], + '/v3/OS-FEDERATION/mappings/{}'.format(mapping['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -198,7 +197,7 @@ class _DomainAndProjectUserMappingTests: with self.test_client() as c: c.delete( - '/v3/OS-FEDERATION/mappings/%s' % mapping['id'], + '/v3/OS-FEDERATION/mappings/{}'.format(mapping['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -210,7 +209,6 @@ class SystemReaderTests( _SystemUserMappingTests, _SystemReaderAndMemberUserMappingTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -254,7 +252,7 @@ class SystemReaderTests( with self.test_client() as c: c.put( - '/v3/OS-FEDERATION/mappings/%s' % mapping_id, + f'/v3/OS-FEDERATION/mappings/{mapping_id}', json=create, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -279,7 +277,7 @@ class SystemReaderTests( with self.test_client() as c: c.patch( - '/v3/OS-FEDERATION/mappings/%s' % mapping['id'], + '/v3/OS-FEDERATION/mappings/{}'.format(mapping['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -293,7 +291,7 @@ class SystemReaderTests( with self.test_client() as c: c.delete( - '/v3/OS-FEDERATION/mappings/%s' % mapping['id'], + '/v3/OS-FEDERATION/mappings/{}'.format(mapping['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -305,7 +303,6 @@ class SystemMemberTests( _SystemUserMappingTests, _SystemReaderAndMemberUserMappingTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -339,7 +336,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserMappingTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -378,7 +374,7 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/OS-FEDERATION/mappings/%s' % mapping_id, + f'/v3/OS-FEDERATION/mappings/{mapping_id}', json=create, headers=self.headers, expected_status_code=http.client.CREATED, @@ -403,7 +399,7 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/OS-FEDERATION/mappings/%s' % mapping['id'], + '/v3/OS-FEDERATION/mappings/{}'.format(mapping['id']), json=update, headers=self.headers, ) @@ -416,7 +412,7 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/OS-FEDERATION/mappings/%s' % mapping['id'], + '/v3/OS-FEDERATION/mappings/{}'.format(mapping['id']), headers=self.headers, ) @@ -426,7 +422,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserMappingTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -464,7 +459,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserMappingTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -491,7 +485,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _DomainAndProjectUserMappingTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_policy.py b/keystone/tests/protection/v3/test_policy.py index 637956d24d..1bd23fb8cf 100644 --- a/keystone/tests/protection/v3/test_policy.py +++ b/keystone/tests/protection/v3/test_policy.py @@ -45,7 +45,7 @@ class _SystemUserPoliciesTests: policy = PROVIDERS.policy_api.create_policy(policy['id'], policy) with self.test_client() as c: - c.get('/v3/policies/%s' % policy['id'], headers=self.headers) + c.get('/v3/policies/{}'.format(policy['id']), headers=self.headers) class _SystemReaderAndMemberPoliciesTests: @@ -58,11 +58,7 @@ class _SystemReaderAndMemberPoliciesTests: 'description': uuid.uuid4().hex, 'enabled': True, # Store serialized JSON data as the blob to mimic real world usage. - 'blob': json.dumps( - { - 'data': uuid.uuid4().hex, - } - ), + 'blob': json.dumps({'data': uuid.uuid4().hex}), 'type': uuid.uuid4().hex, } with self.test_client() as c: @@ -81,7 +77,7 @@ class _SystemReaderAndMemberPoliciesTests: with self.test_client() as c: c.patch( - '/v3/policies/%s' % policy['id'], + '/v3/policies/{}'.format(policy['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -93,14 +89,13 @@ class _SystemReaderAndMemberPoliciesTests: with self.test_client() as c: c.delete( - '/v3/policies/%s' % policy['id'], + '/v3/policies/{}'.format(policy['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainAndProjectUserPolicyTests: - def test_user_cannot_list_policies(self): policy = unit.new_policy_ref() policy = PROVIDERS.policy_api.create_policy(policy['id'], policy) @@ -118,7 +113,7 @@ class _DomainAndProjectUserPolicyTests: with self.test_client() as c: c.get( - '/v3/policies/%s' % policy['id'], + '/v3/policies/{}'.format(policy['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -130,11 +125,7 @@ class _DomainAndProjectUserPolicyTests: 'description': uuid.uuid4().hex, 'enabled': True, # Store serialized JSON data as the blob to mimic real world usage. - 'blob': json.dumps( - { - 'data': uuid.uuid4().hex, - } - ), + 'blob': json.dumps({'data': uuid.uuid4().hex}), 'type': uuid.uuid4().hex, } with self.test_client() as c: @@ -153,7 +144,7 @@ class _DomainAndProjectUserPolicyTests: with self.test_client() as c: c.patch( - '/v3/policies/%s' % policy['id'], + '/v3/policies/{}'.format(policy['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -165,7 +156,7 @@ class _DomainAndProjectUserPolicyTests: with self.test_client() as c: c.delete( - '/v3/policies/%s' % policy['id'], + '/v3/policies/{}'.format(policy['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -177,7 +168,6 @@ class SystemReaderTests( _SystemUserPoliciesTests, _SystemReaderAndMemberPoliciesTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -212,7 +202,6 @@ class SystemMemberTests( _SystemUserPoliciesTests, _SystemReaderAndMemberPoliciesTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -246,7 +235,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserPoliciesTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -278,11 +266,7 @@ class SystemAdminTests( 'enabled': True, # Store serialized JSON data as the blob to mimic real world # usage. - 'blob': json.dumps( - { - 'data': uuid.uuid4().hex, - } - ), + 'blob': json.dumps({'data': uuid.uuid4().hex}), 'type': uuid.uuid4().hex, } } @@ -297,7 +281,7 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/policies/%s' % policy['id'], + '/v3/policies/{}'.format(policy['id']), json=update, headers=self.headers, ) @@ -307,7 +291,9 @@ class SystemAdminTests( policy = PROVIDERS.policy_api.create_policy(policy['id'], policy) with self.test_client() as c: - c.delete('/v3/policies/%s' % policy['id'], headers=self.headers) + c.delete( + '/v3/policies/{}'.format(policy['id']), headers=self.headers + ) class DomainUserTests( @@ -315,7 +301,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserPolicyTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -353,7 +338,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserPolicyTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -380,7 +364,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _DomainAndProjectUserPolicyTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_policy_association.py b/keystone/tests/protection/v3/test_policy_association.py index 31b772384a..a62b498bea 100644 --- a/keystone/tests/protection/v3/test_policy_association.py +++ b/keystone/tests/protection/v3/test_policy_association.py @@ -45,8 +45,9 @@ class _SystemUserPoliciesAssociationTests: with self.test_client() as c: c.get( - '/v3/policies/%s/OS-ENDPOINT-POLICY/endpoints/%s' - % (policy['id'], endpoint['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/endpoints/{}'.format( + policy['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -65,8 +66,9 @@ class _SystemUserPoliciesAssociationTests: with self.test_client() as c: c.get( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s' - % (policy['id'], service['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}'.format( + policy['id'], service['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -87,8 +89,9 @@ class _SystemUserPoliciesAssociationTests: with self.test_client() as c: c.get( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s/regions/%s' - % (policy['id'], service['id'], region['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}/regions/{}'.format( + policy['id'], service['id'], region['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -108,8 +111,9 @@ class _SystemUserPoliciesAssociationTests: ) with self.test_client() as c: c.get( - '/v3/endpoints/%s/OS-ENDPOINT-POLICY/policy' - % (endpoint['id']), + '/v3/endpoints/{}/OS-ENDPOINT-POLICY/policy'.format( + endpoint['id'] + ), headers=self.headers, ) @@ -128,8 +132,9 @@ class _SystemUserPoliciesAssociationTests: ) with self.test_client() as c: r = c.get( - '/v3/policies/%s/OS-ENDPOINT-POLICY/endpoints' - % (policy['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/endpoints'.format( + policy['id'] + ), headers=self.headers, ) for endpoint_itr in r.json['endpoints']: @@ -137,7 +142,6 @@ class _SystemUserPoliciesAssociationTests: class _SystemReaderAndMemberPoliciesAssociationTests: - def test_user_cannot_create_policy_association_for_endpoint(self): policy = unit.new_policy_ref() policy = PROVIDERS.policy_api.create_policy(policy['id'], policy) @@ -151,8 +155,9 @@ class _SystemReaderAndMemberPoliciesAssociationTests: with self.test_client() as c: c.put( - '/v3/policies/%s/OS-ENDPOINT-POLICY/endpoints/%s' - % (policy['id'], endpoint['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/endpoints/{}'.format( + policy['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -170,8 +175,9 @@ class _SystemReaderAndMemberPoliciesAssociationTests: with self.test_client() as c: c.delete( - '/v3/policies/%s/OS-ENDPOINT-POLICY/endpoints/%s' - % (policy['id'], endpoint['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/endpoints/{}'.format( + policy['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -184,8 +190,9 @@ class _SystemReaderAndMemberPoliciesAssociationTests: ) with self.test_client() as c: c.put( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s' - % (policy['id'], service['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}'.format( + policy['id'], service['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -199,8 +206,9 @@ class _SystemReaderAndMemberPoliciesAssociationTests: with self.test_client() as c: c.delete( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s' - % (policy['id'], service['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}'.format( + policy['id'], service['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -215,8 +223,9 @@ class _SystemReaderAndMemberPoliciesAssociationTests: with self.test_client() as c: c.put( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s/regions/%s' - % (policy['id'], service['id'], region['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}/regions/{}'.format( + policy['id'], service['id'], region['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -231,15 +240,15 @@ class _SystemReaderAndMemberPoliciesAssociationTests: with self.test_client() as c: c.delete( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s/regions/%s' - % (policy['id'], service['id'], region['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}/regions/{}'.format( + policy['id'], service['id'], region['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainAndProjectUserPolicyAssociationsTests: - def test_user_cannot_check_policy_association_for_endpoint(self): policy = unit.new_policy_ref() policy = PROVIDERS.policy_api.create_policy(policy['id'], policy) @@ -258,8 +267,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: with self.test_client() as c: c.get( - '/v3/policies/%s/OS-ENDPOINT-POLICY/endpoints/%s' - % (policy['id'], endpoint['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/endpoints/{}'.format( + policy['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -278,8 +288,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: with self.test_client() as c: c.get( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s' - % (policy['id'], service['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}'.format( + policy['id'], service['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -300,8 +311,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: with self.test_client() as c: c.get( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s/regions/%s' - % (policy['id'], service['id'], region['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}/regions/{}'.format( + policy['id'], service['id'], region['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -321,8 +333,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: ) with self.test_client() as c: c.get( - '/v3/endpoints/%s/OS-ENDPOINT-POLICY/policy' - % (endpoint['id']), + '/v3/endpoints/{}/OS-ENDPOINT-POLICY/policy'.format( + endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -342,8 +355,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: ) with self.test_client() as c: c.get( - '/v3/policies/%s/OS-ENDPOINT-POLICY/endpoints' - % (policy['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/endpoints'.format( + policy['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -361,8 +375,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: with self.test_client() as c: c.put( - '/v3/policies/%s/OS-ENDPOINT-POLICY/endpoints/%s' - % (policy['id'], endpoint['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/endpoints/{}'.format( + policy['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -380,8 +395,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: with self.test_client() as c: c.delete( - '/v3/policies/%s/OS-ENDPOINT-POLICY/endpoints/%s' - % (policy['id'], endpoint['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/endpoints/{}'.format( + policy['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -394,8 +410,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: ) with self.test_client() as c: c.put( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s' - % (policy['id'], service['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}'.format( + policy['id'], service['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -409,8 +426,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: with self.test_client() as c: c.delete( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s' - % (policy['id'], service['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}'.format( + policy['id'], service['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -425,8 +443,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: with self.test_client() as c: c.put( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s/regions/%s' - % (policy['id'], service['id'], region['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}/regions/{}'.format( + policy['id'], service['id'], region['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -441,8 +460,9 @@ class _DomainAndProjectUserPolicyAssociationsTests: with self.test_client() as c: c.delete( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s/regions/%s' - % (policy['id'], service['id'], region['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}/regions/{}'.format( + policy['id'], service['id'], region['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -454,7 +474,6 @@ class SystemReaderTests( _SystemUserPoliciesAssociationTests, _SystemReaderAndMemberPoliciesAssociationTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -489,7 +508,6 @@ class SystemMemberTests( _SystemUserPoliciesAssociationTests, _SystemReaderAndMemberPoliciesAssociationTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -523,7 +541,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserPoliciesAssociationTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -559,8 +576,9 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/policies/%s/OS-ENDPOINT-POLICY/endpoints/%s' - % (policy['id'], endpoint['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/endpoints/{}'.format( + policy['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -578,8 +596,9 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/policies/%s/OS-ENDPOINT-POLICY/endpoints/%s' - % (policy['id'], endpoint['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/endpoints/{}'.format( + policy['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -592,8 +611,9 @@ class SystemAdminTests( ) with self.test_client() as c: c.put( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s' - % (policy['id'], service['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}'.format( + policy['id'], service['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -607,8 +627,9 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s' - % (policy['id'], service['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}'.format( + policy['id'], service['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -623,8 +644,9 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s/regions/%s' - % (policy['id'], service['id'], region['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}/regions/{}'.format( + policy['id'], service['id'], region['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -639,8 +661,9 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/policies/%s/OS-ENDPOINT-POLICY/services/%s/regions/%s' - % (policy['id'], service['id'], region['id']), + '/v3/policies/{}/OS-ENDPOINT-POLICY/services/{}/regions/{}'.format( + policy['id'], service['id'], region['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -651,7 +674,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserPolicyAssociationsTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -689,7 +711,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserPolicyAssociationsTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -716,7 +737,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _DomainAndProjectUserPolicyAssociationsTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_project_endpoint.py b/keystone/tests/protection/v3/test_project_endpoint.py index 6108a05fda..5bf0df7112 100644 --- a/keystone/tests/protection/v3/test_project_endpoint.py +++ b/keystone/tests/protection/v3/test_project_endpoint.py @@ -50,7 +50,9 @@ class _SystemUserProjectEndpointTests: ) with self.test_client() as c: r = c.get( - '/v3/OS-EP-FILTER/endpoints/%s/projects' % endpoint['id'], + '/v3/OS-EP-FILTER/endpoints/{}/projects'.format( + endpoint['id'] + ), headers=self.headers, ) for project_itr in r.json['projects']: @@ -75,8 +77,9 @@ class _SystemUserProjectEndpointTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/projects/%s/endpoints/%s' - % (project['id'], endpoint['id']), + '/v3/OS-EP-FILTER/projects/{}/endpoints/{}'.format( + project['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -100,7 +103,7 @@ class _SystemUserProjectEndpointTests: ) with self.test_client() as c: r = c.get( - '/v3/OS-EP-FILTER/projects/%s/endpoints' % project['id'], + '/v3/OS-EP-FILTER/projects/{}/endpoints'.format(project['id']), headers=self.headers, ) for endpoint_itr in r.json['endpoints']: @@ -108,7 +111,6 @@ class _SystemUserProjectEndpointTests: class _SystemReaderAndMemberProjectEndpointTests: - def test_user_cannot_add_endpoint_to_project(self): project = PROVIDERS.resource_api.create_project( uuid.uuid4().hex, @@ -124,8 +126,9 @@ class _SystemReaderAndMemberProjectEndpointTests: ) with self.test_client() as c: c.put( - '/v3/OS-EP-FILTER/projects/%s/endpoints/%s' - % (project['id'], endpoint['id']), + '/v3/OS-EP-FILTER/projects/{}/endpoints/{}'.format( + project['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -145,15 +148,15 @@ class _SystemReaderAndMemberProjectEndpointTests: ) with self.test_client() as c: c.delete( - '/v3/OS-EP-FILTER/projects/%s/endpoints/%s' - % (project['id'], endpoint['id']), + '/v3/OS-EP-FILTER/projects/{}/endpoints/{}'.format( + project['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainAndProjectUserProjectEndpointTests: - def test_user_cannot_list_projects_for_endpoint(self): project = PROVIDERS.resource_api.create_project( uuid.uuid4().hex, @@ -173,7 +176,9 @@ class _DomainAndProjectUserProjectEndpointTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/endpoints/%s/projects' % endpoint['id'], + '/v3/OS-EP-FILTER/endpoints/{}/projects'.format( + endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -197,8 +202,9 @@ class _DomainAndProjectUserProjectEndpointTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/projects/%s/endpoints/%s' - % (project['id'], endpoint['id']), + '/v3/OS-EP-FILTER/projects/{}/endpoints/{}'.format( + project['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -222,7 +228,7 @@ class _DomainAndProjectUserProjectEndpointTests: ) with self.test_client() as c: c.get( - '/v3/OS-EP-FILTER/projects/%s/endpoints' % project['id'], + '/v3/OS-EP-FILTER/projects/{}/endpoints'.format(project['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -234,7 +240,6 @@ class SystemReaderTests( _SystemUserProjectEndpointTests, _SystemReaderAndMemberProjectEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -269,7 +274,6 @@ class SystemMemberTests( _SystemUserProjectEndpointTests, _SystemReaderAndMemberProjectEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -303,7 +307,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserProjectEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -341,8 +344,9 @@ class SystemAdminTests( ) with self.test_client() as c: c.put( - '/v3/OS-EP-FILTER/projects/%s/endpoints/%s' - % (project['id'], endpoint['id']), + '/v3/OS-EP-FILTER/projects/{}/endpoints/{}'.format( + project['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -365,8 +369,9 @@ class SystemAdminTests( ) with self.test_client() as c: c.delete( - '/v3/OS-EP-FILTER/projects/%s/endpoints/%s' - % (project['id'], endpoint['id']), + '/v3/OS-EP-FILTER/projects/{}/endpoints/{}'.format( + project['id'], endpoint['id'] + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -378,7 +383,6 @@ class DomainUserTests( _DomainAndProjectUserProjectEndpointTests, _SystemReaderAndMemberProjectEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -417,7 +421,6 @@ class ProjectUserTests( _DomainAndProjectUserProjectEndpointTests, _SystemReaderAndMemberProjectEndpointTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -445,7 +448,6 @@ class ProjectUserTestsWithoutEnforceScope( _DomainAndProjectUserProjectEndpointTests, _SystemReaderAndMemberProjectEndpointTests, ): - def _override_policy(self): # TODO(cmurphy): Remove this once the deprecated policies in # keystone.common.policies.project_endpoint have been removed. This is diff --git a/keystone/tests/protection/v3/test_project_tags.py b/keystone/tests/protection/v3/test_project_tags.py index d8bcb3a0d7..1570fa84fd 100644 --- a/keystone/tests/protection/v3/test_project_tags.py +++ b/keystone/tests/protection/v3/test_project_tags.py @@ -89,14 +89,14 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/projects/%s/tags' % project['id'], headers=self.headers + '/v3/projects/{}/tags'.format(project['id']), + headers=self.headers, ) self.assertTrue(len(r.json['tags']) == 1) self.assertEqual(tag, r.json['tags'][0]) class _SystemMemberAndReaderTagTests: - def test_user_cannot_create_project_tag(self): project = PROVIDERS.resource_api.create_project( uuid.uuid4().hex, @@ -125,7 +125,7 @@ class _SystemMemberAndReaderTagTests: with self.test_client() as c: c.put( - '/v3/projects/%s/tags' % project['id'], + '/v3/projects/{}/tags'.format(project['id']), headers=self.headers, json=update, expected_status_code=http.client.FORBIDDEN, @@ -149,7 +149,6 @@ class _SystemMemberAndReaderTagTests: class _DomainAndProjectUserTagTests: - def test_user_cannot_create_project_tag(self): project = PROVIDERS.resource_api.create_project( uuid.uuid4().hex, @@ -178,7 +177,7 @@ class _DomainAndProjectUserTagTests: with self.test_client() as c: c.put( - '/v3/projects/%s/tags' % project['id'], + '/v3/projects/{}/tags'.format(project['id']), headers=self.headers, json=update, expected_status_code=http.client.FORBIDDEN, @@ -207,7 +206,6 @@ class SystemReaderTests( _SystemUserTests, _SystemMemberAndReaderTagTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -242,7 +240,6 @@ class SystemMemberTests( _SystemUserTests, _SystemMemberAndReaderTagTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -276,7 +273,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -325,7 +321,7 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/projects/%s/tags' % project['id'], + '/v3/projects/{}/tags'.format(project['id']), headers=self.headers, json=update, expected_status_code=http.client.OK, @@ -348,7 +344,6 @@ class SystemAdminTests( class _DomainUserTagTests: - def test_user_can_get_tag_for_project_in_domain(self): project = PROVIDERS.resource_api.create_project( uuid.uuid4().hex, unit.new_project_ref(domain_id=self.domain_id) @@ -374,7 +369,8 @@ class _DomainUserTagTests: with self.test_client() as c: r = c.get( - '/v3/projects/%s/tags' % project['id'], headers=self.headers + '/v3/projects/{}/tags'.format(project['id']), + headers=self.headers, ) self.assertTrue(len(r.json['tags']) == 1) self.assertEqual(tag, r.json['tags'][0]) @@ -408,7 +404,7 @@ class _DomainUserTagTests: with self.test_client() as c: c.put( - '/v3/projects/%s/tags' % project['id'], + '/v3/projects/{}/tags'.format(project['id']), headers=self.headers, json=update, expected_status_code=http.client.FORBIDDEN, @@ -457,14 +453,13 @@ class _DomainUserTagTests: with self.test_client() as c: c.get( - '/v3/projects/%s/tags' % project['id'], + '/v3/projects/{}/tags'.format(project['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainMemberAndReaderTagTests: - def test_user_cannot_create_project_tag_in_domain(self): project = PROVIDERS.resource_api.create_project( uuid.uuid4().hex, unit.new_project_ref(domain_id=self.domain_id) @@ -492,7 +487,7 @@ class _DomainMemberAndReaderTagTests: with self.test_client() as c: c.put( - '/v3/projects/%s/tags' % project['id'], + '/v3/projects/{}/tags'.format(project['id']), headers=self.headers, json=update, expected_status_code=http.client.FORBIDDEN, @@ -519,7 +514,6 @@ class DomainAdminUserTests( common_auth.AuthTestMixin, _DomainUserTagTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -587,7 +581,7 @@ class DomainAdminUserTests( with self.test_client() as c: r = c.put( - '/v3/projects/%s/tags' % project['id'], + '/v3/projects/{}/tags'.format(project['id']), headers=self.headers, json=update, expected_status_code=http.client.OK, @@ -616,7 +610,6 @@ class DomainMemberUserTests( _DomainUserTagTests, _DomainMemberAndReaderTagTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -664,7 +657,6 @@ class DomainReaderUserTests( _DomainUserTagTests, _DomainMemberAndReaderTagTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -707,7 +699,6 @@ class DomainReaderUserTests( class _ProjectUserTagTests: - def test_user_can_get_tag_for_project(self): tag = uuid.uuid4().hex PROVIDERS.resource_api.create_project_tag(self.project_id, tag) @@ -725,7 +716,7 @@ class _ProjectUserTagTests: with self.test_client() as c: r = c.get( - '/v3/projects/%s/tags' % self.project_id, headers=self.headers + f'/v3/projects/{self.project_id}/tags', headers=self.headers ) self.assertTrue(len(r.json['tags']) == 1) self.assertEqual(tag, r.json['tags'][0]) @@ -758,7 +749,7 @@ class _ProjectUserTagTests: with self.test_client() as c: c.put( - '/v3/projects/%s/tags' % project['id'], + '/v3/projects/{}/tags'.format(project['id']), headers=self.headers, json=update, expected_status_code=http.client.FORBIDDEN, @@ -807,14 +798,13 @@ class _ProjectUserTagTests: with self.test_client() as c: c.get( - '/v3/projects/%s/tags' % project['id'], + '/v3/projects/{}/tags'.format(project['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _ProjectMemberAndReaderTagTests: - def test_user_cannot_create_project_tag(self): tag = uuid.uuid4().hex with self.test_client() as c: @@ -832,7 +822,7 @@ class _ProjectMemberAndReaderTagTests: with self.test_client() as c: c.put( - '/v3/projects/%s/tags' % self.project_id, + f'/v3/projects/{self.project_id}/tags', headers=self.headers, json=update, expected_status_code=http.client.FORBIDDEN, @@ -855,7 +845,6 @@ class ProjectAdminTests( common_auth.AuthTestMixin, _ProjectUserTagTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -908,7 +897,7 @@ class ProjectAdminTests( with self.test_client() as c: c.put( - '/v3/projects/%s/tags' % self.project_id, + f'/v3/projects/{self.project_id}/tags', headers=self.headers, json=update, expected_status_code=http.client.OK, @@ -931,7 +920,6 @@ class ProjectMemberTests( _ProjectUserTagTests, _ProjectMemberAndReaderTagTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -979,7 +967,6 @@ class ProjectReaderTests( _ProjectUserTagTests, _ProjectMemberAndReaderTagTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_projects.py b/keystone/tests/protection/v3/test_projects.py index 0a2b365d12..a5661a274d 100644 --- a/keystone/tests/protection/v3/test_projects.py +++ b/keystone/tests/protection/v3/test_projects.py @@ -61,7 +61,7 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/users/%s/projects' % user['id'], + '/v3/users/{}/projects'.format(user['id']), headers=self.headers, ) self.assertEqual(1, len(r.json['projects'])) @@ -74,13 +74,15 @@ class _SystemUserTests: ) with self.test_client() as c: - r = c.get('/v3/projects/%s' % project['id'], headers=self.headers) + r = c.get( + '/v3/projects/{}'.format(project['id']), headers=self.headers + ) self.assertEqual(project['id'], r.json['project']['id']) def test_user_cannot_get_non_existent_project_not_found(self): with self.test_client() as c: c.get( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -114,7 +116,7 @@ class _SystemMemberAndReaderProjectTests: with self.test_client() as c: c.patch( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -125,7 +127,7 @@ class _SystemMemberAndReaderProjectTests: with self.test_client() as c: c.patch( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -139,7 +141,7 @@ class _SystemMemberAndReaderProjectTests: with self.test_client() as c: c.delete( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -147,7 +149,7 @@ class _SystemMemberAndReaderProjectTests: def test_user_cannot_delete_non_existent_project_forbidden(self): with self.test_client() as c: c.delete( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -182,7 +184,9 @@ class _DomainUsersTests: ) with self.test_client() as c: - r = c.get('/v3/projects/%s' % project['id'], headers=self.headers) + r = c.get( + '/v3/projects/{}'.format(project['id']), headers=self.headers + ) self.assertEqual(project['id'], r.json['project']['id']) def test_user_cannot_get_a_project_in_other_domain(self): @@ -193,7 +197,7 @@ class _DomainUsersTests: with self.test_client() as c: c.get( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -215,7 +219,8 @@ class _DomainUsersTests: with self.test_client() as c: r = c.get( - '/v3/users/%s/projects' % user['id'], headers=self.headers + '/v3/users/{}/projects'.format(user['id']), + headers=self.headers, ) self.assertEqual(1, len(r.json['projects'])) self.assertEqual(project['id'], r.json['projects'][0]['id']) @@ -240,7 +245,7 @@ class _DomainUsersTests: with self.test_client() as c: c.get( - '/v3/users/%s/projects' % user['id'], + '/v3/users/{}/projects'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -284,7 +289,7 @@ class _DomainMemberAndReaderProjectTests: with self.test_client() as c: c.patch( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -300,7 +305,7 @@ class _DomainMemberAndReaderProjectTests: with self.test_client() as c: c.patch( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -311,7 +316,7 @@ class _DomainMemberAndReaderProjectTests: with self.test_client() as c: c.patch( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -324,7 +329,7 @@ class _DomainMemberAndReaderProjectTests: with self.test_client() as c: c.delete( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -337,7 +342,7 @@ class _DomainMemberAndReaderProjectTests: with self.test_client() as c: c.delete( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -345,7 +350,7 @@ class _DomainMemberAndReaderProjectTests: def test_user_cannot_delete_non_existent_projects_forbidden(self): with self.test_client() as c: c.delete( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -357,7 +362,6 @@ class SystemReaderTests( _SystemUserTests, _SystemMemberAndReaderProjectTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -392,7 +396,6 @@ class SystemMemberTests( _SystemUserTests, _SystemMemberAndReaderProjectTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -426,7 +429,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -467,7 +469,7 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), json=update, headers=self.headers, ) @@ -477,7 +479,7 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.NOT_FOUND, @@ -490,12 +492,14 @@ class SystemAdminTests( ) with self.test_client() as c: - c.delete('/v3/projects/%s' % project['id'], headers=self.headers) + c.delete( + '/v3/projects/{}'.format(project['id']), headers=self.headers + ) def test_user_can_delete_non_existent_project_not_found(self): with self.test_client() as c: c.delete( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -519,8 +523,7 @@ class SystemAdminTests( with self.test_client() as c: r = c.get( - '/v3/users/%s/projects' % self.user_id, - headers=self.headers, + f'/v3/users/{self.user_id}/projects', headers=self.headers ) self.assertEqual(2, len(r.json['projects'])) project_ids = [] @@ -538,7 +541,6 @@ class DomainReaderTests( _DomainUsersTests, _DomainMemberAndReaderProjectTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -577,7 +579,6 @@ class DomainMemberTests( _DomainUsersTests, _DomainMemberAndReaderProjectTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -615,7 +616,6 @@ class DomainAdminTests( common_auth.AuthTestMixin, _DomainUsersTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -710,7 +710,7 @@ class DomainAdminTests( with self.test_client() as c: c.patch( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), json=update, headers=self.headers, ) @@ -725,7 +725,7 @@ class DomainAdminTests( with self.test_client() as c: c.patch( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -742,7 +742,7 @@ class DomainAdminTests( with self.test_client() as c: c.patch( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -754,7 +754,9 @@ class DomainAdminTests( ) with self.test_client() as c: - c.delete('/v3/projects/%s' % project['id'], headers=self.headers) + c.delete( + '/v3/projects/{}'.format(project['id']), headers=self.headers + ) def test_user_cannot_delete_projects_in_other_domain(self): project = PROVIDERS.resource_api.create_project( @@ -764,7 +766,7 @@ class DomainAdminTests( with self.test_client() as c: c.delete( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -778,7 +780,7 @@ class DomainAdminTests( # a 403 instead of a 404. with self.test_client() as c: c.delete( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -787,7 +789,6 @@ class DomainAdminTests( class ProjectUserTests( base_classes.TestCaseWithBootstrap, common_auth.AuthTestMixin ): - def setUp(self): super().setUp() self.loadapp() @@ -877,7 +878,7 @@ class ProjectUserTests( with self.test_client() as c: c.get( - '/v3/users/%s/projects' % user['id'], + '/v3/users/{}/projects'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -888,15 +889,14 @@ class ProjectUserTests( # administrative, reserved for system and domain users. with self.test_client() as c: r = c.get( - '/v3/users/%s/projects' % self.user_id, - headers=self.headers, + f'/v3/users/{self.user_id}/projects', headers=self.headers ) self.assertEqual(1, len(r.json['projects'])) self.assertEqual(self.project_id, r.json['projects'][0]['id']) def test_user_can_get_their_project(self): with self.test_client() as c: - c.get('/v3/projects/%s' % self.project_id, headers=self.headers) + c.get(f'/v3/projects/{self.project_id}', headers=self.headers) def test_user_cannot_get_other_projects(self): project = PROVIDERS.resource_api.create_project( @@ -906,7 +906,7 @@ class ProjectUserTests( with self.test_client() as c: c.get( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -936,7 +936,7 @@ class ProjectUserTests( with self.test_client() as c: c.patch( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -947,7 +947,7 @@ class ProjectUserTests( with self.test_client() as c: c.patch( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -961,7 +961,7 @@ class ProjectUserTests( with self.test_client() as c: c.delete( - '/v3/projects/%s' % project['id'], + '/v3/projects/{}'.format(project['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -969,7 +969,7 @@ class ProjectUserTests( def test_user_cannot_delete_non_existent_project_forbidden(self): with self.test_client() as c: c.delete( - '/v3/projects/%s' % uuid.uuid4().hex, + f'/v3/projects/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) diff --git a/keystone/tests/protection/v3/test_protocols.py b/keystone/tests/protection/v3/test_protocols.py index 019748f72b..660703ed18 100644 --- a/keystone/tests/protection/v3/test_protocols.py +++ b/keystone/tests/protection/v3/test_protocols.py @@ -25,7 +25,6 @@ PROVIDERS = provider_api.ProviderAPIs class _CommonUtilities: - def _create_protocol_and_deps(self): identity_provider = unit.new_identity_provider_ref() identity_provider = PROVIDERS.federation_api.create_idp( @@ -49,9 +48,8 @@ class _SystemUserProtocolTests: protocol, mapping, identity_provider = self._create_protocol_and_deps() with self.test_client() as c: - path = ( - '/v3/OS-FEDERATION/identity_providers/%s/protocols' - % identity_provider['id'] + path = '/v3/OS-FEDERATION/identity_providers/{}/protocols'.format( + identity_provider['id'] ) r = c.get(path, headers=self.headers) self.assertEqual(1, len(r.json['protocols'])) @@ -63,15 +61,13 @@ class _SystemUserProtocolTests: with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol['id'], + identity_provider['id'], protocol['id'] ) ) c.get(path, headers=self.headers) class _SystemReaderAndMemberProtocolTests: - def test_user_cannot_create_protocols(self): identity_provider = unit.new_identity_provider_ref() identity_provider = PROVIDERS.federation_api.create_idp( @@ -88,8 +84,7 @@ class _SystemReaderAndMemberProtocolTests: with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol_id, + identity_provider['id'], protocol_id ) ) c.put( @@ -110,8 +105,7 @@ class _SystemReaderAndMemberProtocolTests: with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol['id'], + identity_provider['id'], protocol['id'] ) ) c.patch( @@ -127,8 +121,7 @@ class _SystemReaderAndMemberProtocolTests: with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol['id'], + identity_provider['id'], protocol['id'] ) ) c.delete( @@ -139,7 +132,6 @@ class _SystemReaderAndMemberProtocolTests: class _DomainAndProjectUserProtocolTests: - def test_user_cannot_create_protocols(self): identity_provider = unit.new_identity_provider_ref() identity_provider = PROVIDERS.federation_api.create_idp( @@ -156,8 +148,7 @@ class _DomainAndProjectUserProtocolTests: with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol_id, + identity_provider['id'], protocol_id ) ) c.put( @@ -178,8 +169,7 @@ class _DomainAndProjectUserProtocolTests: with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol['id'], + identity_provider['id'], protocol['id'] ) ) c.patch( @@ -195,8 +185,7 @@ class _DomainAndProjectUserProtocolTests: with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol['id'], + identity_provider['id'], protocol['id'] ) ) c.delete( @@ -209,9 +198,8 @@ class _DomainAndProjectUserProtocolTests: protocol, mapping, identity_provider = self._create_protocol_and_deps() with self.test_client() as c: - path = ( - '/v3/OS-FEDERATION/identity_providers/%s/protocols' - % identity_provider['id'] + path = '/v3/OS-FEDERATION/identity_providers/{}/protocols'.format( + identity_provider['id'] ) c.get( path, @@ -225,8 +213,7 @@ class _DomainAndProjectUserProtocolTests: with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol['id'], + identity_provider['id'], protocol['id'] ) ) c.get( @@ -243,7 +230,6 @@ class SystemReaderTests( _SystemUserProtocolTests, _SystemReaderAndMemberProtocolTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -279,7 +265,6 @@ class SystemMemberTests( _SystemUserProtocolTests, _SystemReaderAndMemberProtocolTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -314,7 +299,6 @@ class SystemAdminTests( _CommonUtilities, _SystemUserProtocolTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -353,8 +337,7 @@ class SystemAdminTests( with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol_id, + identity_provider['id'], protocol_id ) ) c.put( @@ -375,8 +358,7 @@ class SystemAdminTests( with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol['id'], + identity_provider['id'], protocol['id'] ) ) c.patch(path, json=update, headers=self.headers) @@ -387,8 +369,7 @@ class SystemAdminTests( with self.test_client() as c: path = ( '/v3/OS-FEDERATION/identity_providers/{}/protocols/{}'.format( - identity_provider['id'], - protocol['id'], + identity_provider['id'], protocol['id'] ) ) c.delete(path, headers=self.headers) @@ -400,7 +381,6 @@ class DomainUserTests( _CommonUtilities, _DomainAndProjectUserProtocolTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -439,7 +419,6 @@ class ProjectUserTests( _CommonUtilities, _DomainAndProjectUserProtocolTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -467,7 +446,6 @@ class ProjectUserTestsWithoutEnforceScope( _CommonUtilities, _DomainAndProjectUserProtocolTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_regions.py b/keystone/tests/protection/v3/test_regions.py index 29071ba4bb..d720776bed 100644 --- a/keystone/tests/protection/v3/test_regions.py +++ b/keystone/tests/protection/v3/test_regions.py @@ -31,7 +31,7 @@ class _UserRegionTests: region = PROVIDERS.catalog_api.create_region(unit.new_region_ref()) with self.test_client() as c: - c.get('/v3/regions/%s' % region['id'], headers=self.headers) + c.get('/v3/regions/{}'.format(region['id']), headers=self.headers) def test_user_can_list_regions(self): expected_regions = [] @@ -65,7 +65,7 @@ class _SystemReaderAndMemberUserRegionTests: with self.test_client() as c: update = {'region': {'description': uuid.uuid4().hex}} c.patch( - '/v3/regions/%s' % region['id'], + '/v3/regions/{}'.format(region['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -76,7 +76,7 @@ class _SystemReaderAndMemberUserRegionTests: with self.test_client() as c: c.delete( - '/v3/regions/%s' % region['id'], + '/v3/regions/{}'.format(region['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -102,7 +102,7 @@ class _DomainAndProjectUserRegionTests: with self.test_client() as c: update = {'region': {'description': uuid.uuid4().hex}} c.patch( - '/v3/regions/%s' % region['id'], + '/v3/regions/{}'.format(region['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -113,7 +113,7 @@ class _DomainAndProjectUserRegionTests: with self.test_client() as c: c.delete( - '/v3/regions/%s' % region['id'], + '/v3/regions/{}'.format(region['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -125,7 +125,6 @@ class SystemReaderTests( _UserRegionTests, _SystemReaderAndMemberUserRegionTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -160,7 +159,6 @@ class SystemMemberTests( _UserRegionTests, _SystemReaderAndMemberUserRegionTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -194,7 +192,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _UserRegionTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -229,7 +226,7 @@ class SystemAdminTests( with self.test_client() as c: update = {'region': {'description': uuid.uuid4().hex}} c.patch( - '/v3/regions/%s' % region['id'], + '/v3/regions/{}'.format(region['id']), json=update, headers=self.headers, ) @@ -238,7 +235,9 @@ class SystemAdminTests( region = PROVIDERS.catalog_api.create_region(unit.new_region_ref()) with self.test_client() as c: - c.delete('/v3/regions/%s' % region['id'], headers=self.headers) + c.delete( + '/v3/regions/{}'.format(region['id']), headers=self.headers + ) class DomainUserTests( @@ -247,7 +246,6 @@ class DomainUserTests( _UserRegionTests, _DomainAndProjectUserRegionTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -286,7 +284,6 @@ class ProjectUserTests( _UserRegionTests, _DomainAndProjectUserRegionTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -316,7 +313,6 @@ class ProjectUserTestsWithoutEnforceScope( _UserRegionTests, _DomainAndProjectUserRegionTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_registered_limits.py b/keystone/tests/protection/v3/test_registered_limits.py index e59ea2d98a..48fdb6986a 100644 --- a/keystone/tests/protection/v3/test_registered_limits.py +++ b/keystone/tests/protection/v3/test_registered_limits.py @@ -42,7 +42,7 @@ class _UserRegisteredLimitTests: with self.test_client() as c: r = c.get( - '/v3/registered_limits/%s' % limit_id, headers=self.headers + f'/v3/registered_limits/{limit_id}', headers=self.headers ) self.assertEqual(limit_id, r.json['registered_limit']['id']) @@ -100,7 +100,7 @@ class _UserRegisteredLimitTests: update = {'registered_limit': {'default_limit': 5}} c.patch( - '/v3/registered_limits/%s' % limit_id, + f'/v3/registered_limits/{limit_id}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -121,7 +121,7 @@ class _UserRegisteredLimitTests: with self.test_client() as c: c.delete( - '/v3/registered_limits/%s' % limit_id, + f'/v3/registered_limits/{limit_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -165,7 +165,6 @@ class SystemMemberTests( common_auth.AuthTestMixin, _UserRegisteredLimitTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -197,7 +196,6 @@ class SystemMemberTests( class SystemAdminTests( base_classes.TestCaseWithBootstrap, common_auth.AuthTestMixin ): - def setUp(self): super().setUp() self.loadapp() @@ -235,7 +233,7 @@ class SystemAdminTests( with self.test_client() as c: r = c.get( - '/v3/registered_limits/%s' % limit_id, headers=self.headers + f'/v3/registered_limits/{limit_id}', headers=self.headers ) self.assertEqual(limit_id, r.json['registered_limit']['id']) @@ -288,7 +286,7 @@ class SystemAdminTests( update = {'registered_limit': {'default_limit': 5}} c.patch( - '/v3/registered_limits/%s' % limit_id, + f'/v3/registered_limits/{limit_id}', json=update, headers=self.headers, ) @@ -307,9 +305,7 @@ class SystemAdminTests( limit_id = limits[0]['id'] with self.test_client() as c: - c.delete( - '/v3/registered_limits/%s' % limit_id, headers=self.headers - ) + c.delete(f'/v3/registered_limits/{limit_id}', headers=self.headers) class DomainUserTests( @@ -317,7 +313,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _UserRegisteredLimitTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -355,7 +350,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _UserRegisteredLimitTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -384,7 +378,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _UserRegisteredLimitTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_roles.py b/keystone/tests/protection/v3/test_roles.py index 11a57827ad..dcf229f2f8 100644 --- a/keystone/tests/protection/v3/test_roles.py +++ b/keystone/tests/protection/v3/test_roles.py @@ -43,7 +43,7 @@ class _SystemUserRoleTests: ) with self.test_client() as c: - r = c.get('/v3/roles/%s' % role['id'], headers=self.headers) + r = c.get('/v3/roles/{}'.format(role['id']), headers=self.headers) self.assertEqual(role['id'], r.json['role']['id']) @@ -70,7 +70,7 @@ class _SystemReaderAndMemberRoleTests: with self.test_client() as c: c.patch( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -83,7 +83,7 @@ class _SystemReaderAndMemberRoleTests: with self.test_client() as c: c.delete( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -109,7 +109,7 @@ class _DomainAndProjectUserRoleTests: with self.test_client() as c: c.get( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -134,7 +134,7 @@ class _DomainAndProjectUserRoleTests: with self.test_client() as c: c.patch( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -147,7 +147,7 @@ class _DomainAndProjectUserRoleTests: with self.test_client() as c: c.delete( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -159,7 +159,6 @@ class SystemReaderTests( _SystemUserRoleTests, _SystemReaderAndMemberRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -194,7 +193,6 @@ class SystemMemberTests( _SystemUserRoleTests, _SystemReaderAndMemberRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -228,7 +226,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -266,7 +263,7 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/roles/%s' % role['id'], + '/v3/roles/{}'.format(role['id']), json=update, headers=self.headers, ) @@ -277,7 +274,7 @@ class SystemAdminTests( ) with self.test_client() as c: - c.delete('/v3/roles/%s' % role['id'], headers=self.headers) + c.delete('/v3/roles/{}'.format(role['id']), headers=self.headers) class DomainUserTests( @@ -285,7 +282,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -323,7 +319,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserRoleTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -350,7 +345,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _DomainAndProjectUserRoleTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_service_providers.py b/keystone/tests/protection/v3/test_service_providers.py index 7ff88a4fea..fb13217d45 100644 --- a/keystone/tests/protection/v3/test_service_providers.py +++ b/keystone/tests/protection/v3/test_service_providers.py @@ -48,8 +48,9 @@ class _SystemUserServiceProviderTests: with self.test_client() as c: r = c.get( - '/v3/OS-FEDERATION/service_providers/%s' - % service_provider['id'], + '/v3/OS-FEDERATION/service_providers/{}'.format( + service_provider['id'] + ), headers=self.headers, ) self.assertEqual( @@ -70,7 +71,7 @@ class _SystemReaderAndMemberUserServiceProviderTests: with self.test_client() as c: c.put( - '/v3/OS-FEDERATION/service_providers/%s' % uuid.uuid4().hex, + f'/v3/OS-FEDERATION/service_providers/{uuid.uuid4().hex}', headers=self.headers, json=create, expected_status_code=http.client.FORBIDDEN, @@ -85,8 +86,9 @@ class _SystemReaderAndMemberUserServiceProviderTests: with self.test_client() as c: c.patch( - '/v3/OS-FEDERATION/service_providers/%s' - % service_provider['id'], + '/v3/OS-FEDERATION/service_providers/{}'.format( + service_provider['id'] + ), headers=self.headers, json=update, expected_status_code=http.client.FORBIDDEN, @@ -99,8 +101,9 @@ class _SystemReaderAndMemberUserServiceProviderTests: with self.test_client() as c: c.delete( - '/v3/OS-FEDERATION/service_providers/%s' - % service_provider['id'], + '/v3/OS-FEDERATION/service_providers/{}'.format( + service_provider['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -119,7 +122,7 @@ class _DomainAndProjectUserServiceProviderTests: with self.test_client() as c: c.put( - '/v3/OS-FEDERATION/service_providers/%s' % uuid.uuid4().hex, + f'/v3/OS-FEDERATION/service_providers/{uuid.uuid4().hex}', headers=self.headers, json=create, expected_status_code=http.client.FORBIDDEN, @@ -134,8 +137,9 @@ class _DomainAndProjectUserServiceProviderTests: with self.test_client() as c: c.patch( - '/v3/OS-FEDERATION/service_providers/%s' - % service_provider['id'], + '/v3/OS-FEDERATION/service_providers/{}'.format( + service_provider['id'] + ), headers=self.headers, json=update, expected_status_code=http.client.FORBIDDEN, @@ -160,8 +164,9 @@ class _DomainAndProjectUserServiceProviderTests: with self.test_client() as c: c.get( - '/v3/OS-FEDERATION/service_providers/%s' - % service_provider['id'], + '/v3/OS-FEDERATION/service_providers/{}'.format( + service_provider['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -173,8 +178,9 @@ class _DomainAndProjectUserServiceProviderTests: with self.test_client() as c: c.delete( - '/v3/OS-FEDERATION/service_providers/%s' - % service_provider['id'], + '/v3/OS-FEDERATION/service_providers/{}'.format( + service_provider['id'] + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -186,7 +192,6 @@ class SystemReaderTests( _SystemUserServiceProviderTests, _SystemReaderAndMemberUserServiceProviderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -221,7 +226,6 @@ class SystemMemberTests( _SystemUserServiceProviderTests, _SystemReaderAndMemberUserServiceProviderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -255,7 +259,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserServiceProviderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -288,7 +291,7 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/OS-FEDERATION/service_providers/%s' % uuid.uuid4().hex, + f'/v3/OS-FEDERATION/service_providers/{uuid.uuid4().hex}', headers=self.headers, json=create, expected_status_code=http.client.CREATED, @@ -303,8 +306,9 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/OS-FEDERATION/service_providers/%s' - % service_provider['id'], + '/v3/OS-FEDERATION/service_providers/{}'.format( + service_provider['id'] + ), headers=self.headers, json=update, ) @@ -316,8 +320,9 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/OS-FEDERATION/service_providers/%s' - % service_provider['id'], + '/v3/OS-FEDERATION/service_providers/{}'.format( + service_provider['id'] + ), headers=self.headers, ) @@ -327,7 +332,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserServiceProviderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -365,7 +369,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserServiceProviderTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -392,7 +395,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _DomainAndProjectUserServiceProviderTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_services.py b/keystone/tests/protection/v3/test_services.py index 181e19224f..ae9e6487d9 100644 --- a/keystone/tests/protection/v3/test_services.py +++ b/keystone/tests/protection/v3/test_services.py @@ -49,7 +49,9 @@ class _SystemUserServiceTests: service = PROVIDERS.catalog_api.create_service(service['id'], service) with self.test_client() as c: - r = c.get('/v3/services/%s' % service['id'], headers=self.headers) + r = c.get( + '/v3/services/{}'.format(service['id']), headers=self.headers + ) self.assertEqual(r.json['service']['id'], service['id']) @@ -58,10 +60,7 @@ class _SystemReaderAndMemberUserServiceTests: def test_user_cannot_create_services(self): create = { - 'service': { - 'type': uuid.uuid4().hex, - 'name': uuid.uuid4().hex, - } + 'service': {'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex} } with self.test_client() as c: @@ -80,7 +79,7 @@ class _SystemReaderAndMemberUserServiceTests: with self.test_client() as c: c.patch( - '/v3/services/%s' % service['id'], + '/v3/services/{}'.format(service['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -92,20 +91,16 @@ class _SystemReaderAndMemberUserServiceTests: with self.test_client() as c: c.delete( - '/v3/services/%s' % service['id'], + '/v3/services/{}'.format(service['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainAndProjectUserServiceTests: - def test_user_cannot_create_services(self): create = { - 'service': { - 'type': uuid.uuid4().hex, - 'name': uuid.uuid4().hex, - } + 'service': {'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex} } with self.test_client() as c: @@ -133,7 +128,7 @@ class _DomainAndProjectUserServiceTests: with self.test_client() as c: c.get( - '/v3/services/%s' % service['id'], + '/v3/services/{}'.format(service['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -146,7 +141,7 @@ class _DomainAndProjectUserServiceTests: with self.test_client() as c: c.patch( - '/v3/services/%s' % service['id'], + '/v3/services/{}'.format(service['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -158,7 +153,7 @@ class _DomainAndProjectUserServiceTests: with self.test_client() as c: c.delete( - '/v3/services/%s' % service['id'], + '/v3/services/{}'.format(service['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -170,7 +165,6 @@ class SystemReaderTests( _SystemUserServiceTests, _SystemReaderAndMemberUserServiceTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -205,7 +199,6 @@ class SystemMemberTests( _SystemUserServiceTests, _SystemReaderAndMemberUserServiceTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -239,7 +232,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserServiceTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -264,10 +256,7 @@ class SystemAdminTests( def test_user_can_create_services(self): create = { - 'service': { - 'type': uuid.uuid4().hex, - 'name': uuid.uuid4().hex, - } + 'service': {'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex} } with self.test_client() as c: @@ -281,7 +270,7 @@ class SystemAdminTests( with self.test_client() as c: c.patch( - '/v3/services/%s' % service['id'], + '/v3/services/{}'.format(service['id']), json=update, headers=self.headers, ) @@ -291,7 +280,9 @@ class SystemAdminTests( service = PROVIDERS.catalog_api.create_service(service['id'], service) with self.test_client() as c: - c.delete('/v3/services/%s' % service['id'], headers=self.headers) + c.delete( + '/v3/services/{}'.format(service['id']), headers=self.headers + ) class DomainUserTests( @@ -299,7 +290,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserServiceTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -337,7 +327,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserServiceTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -364,7 +353,6 @@ class ProjectUserTestsWithoutEnforceScope( common_auth.AuthTestMixin, _DomainAndProjectUserServiceTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_system_assignments.py b/keystone/tests/protection/v3/test_system_assignments.py index ea9f4c0477..2271a598dd 100644 --- a/keystone/tests/protection/v3/test_system_assignments.py +++ b/keystone/tests/protection/v3/test_system_assignments.py @@ -29,7 +29,6 @@ PROVIDERS = provider_api.ProviderAPIs class _SystemUserSystemAssignmentTests: - def test_user_can_list_user_system_role_assignments(self): user = PROVIDERS.identity_api.create_user( unit.new_user_ref(CONF.identity.default_domain_id) @@ -41,7 +40,8 @@ class _SystemUserSystemAssignmentTests: with self.test_client() as c: r = c.get( - '/v3/system/users/%s/roles' % user['id'], headers=self.headers + '/v3/system/users/{}/roles'.format(user['id']), + headers=self.headers, ) self.assertEqual(1, len(r.json['roles'])) self.assertEqual( @@ -59,8 +59,9 @@ class _SystemUserSystemAssignmentTests: with self.test_client() as c: c.get( - '/v3/system/users/%s/roles/%s' - % (user['id'], self.bootstrapper.member_role_id), + '/v3/system/users/{}/roles/{}'.format( + user['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -76,7 +77,7 @@ class _SystemUserSystemAssignmentTests: with self.test_client() as c: r = c.get( - '/v3/system/groups/%s/roles' % group['id'], + '/v3/system/groups/{}/roles'.format(group['id']), headers=self.headers, ) self.assertEqual(1, len(r.json['roles'])) @@ -95,15 +96,15 @@ class _SystemUserSystemAssignmentTests: with self.test_client() as c: c.get( - '/v3/system/groups/%s/roles/%s' - % (group['id'], self.bootstrapper.member_role_id), + '/v3/system/groups/{}/roles/{}'.format( + group['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) class _SystemMemberAndReaderSystemAssignmentTests: - def test_user_cannot_grant_system_assignments(self): user = PROVIDERS.identity_api.create_user( unit.new_user_ref(CONF.identity.default_domain_id) @@ -111,8 +112,9 @@ class _SystemMemberAndReaderSystemAssignmentTests: with self.test_client() as c: c.put( - '/v3/system/users/%s/roles/%s' - % (user['id'], self.bootstrapper.member_role_id), + '/v3/system/users/{}/roles/{}'.format( + user['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -128,8 +130,9 @@ class _SystemMemberAndReaderSystemAssignmentTests: with self.test_client() as c: c.delete( - '/v3/system/users/%s/roles/%s' - % (user['id'], self.bootstrapper.member_role_id), + '/v3/system/users/{}/roles/{}'.format( + user['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -141,8 +144,9 @@ class _SystemMemberAndReaderSystemAssignmentTests: with self.test_client() as c: c.put( - '/v3/system/groups/%s/roles/%s' - % (group['id'], self.bootstrapper.member_role_id), + '/v3/system/groups/{}/roles/{}'.format( + group['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -158,15 +162,15 @@ class _SystemMemberAndReaderSystemAssignmentTests: with self.test_client() as c: c.delete( - '/v3/system/groups/%s/roles/%s' - % (group['id'], self.bootstrapper.member_role_id), + '/v3/system/groups/{}/roles/{}'.format( + group['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) class _DomainAndProjectUserSystemAssignmentTests: - def test_user_cannot_list_system_role_assignments(self): user = PROVIDERS.identity_api.create_user( unit.new_user_ref(CONF.identity.default_domain_id) @@ -178,7 +182,7 @@ class _DomainAndProjectUserSystemAssignmentTests: with self.test_client() as c: c.get( - '/v3/system/users/%s/roles' % user['id'], + '/v3/system/users/{}/roles'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -194,8 +198,9 @@ class _DomainAndProjectUserSystemAssignmentTests: with self.test_client() as c: c.get( - '/v3/system/users/%s/roles/%s' - % (user['id'], self.bootstrapper.member_role_id), + '/v3/system/users/{}/roles/{}'.format( + user['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -207,8 +212,9 @@ class _DomainAndProjectUserSystemAssignmentTests: with self.test_client() as c: c.put( - '/v3/system/users/%s/roles/%s' - % (user['id'], self.bootstrapper.member_role_id), + '/v3/system/users/{}/roles/{}'.format( + user['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -224,8 +230,9 @@ class _DomainAndProjectUserSystemAssignmentTests: with self.test_client() as c: c.delete( - '/v3/system/users/%s/roles/%s' - % (user['id'], self.bootstrapper.member_role_id), + '/v3/system/users/{}/roles/{}'.format( + user['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -241,7 +248,7 @@ class _DomainAndProjectUserSystemAssignmentTests: with self.test_client() as c: c.get( - '/v3/system/groups/%s/roles' % group['id'], + '/v3/system/groups/{}/roles'.format(group['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -257,8 +264,9 @@ class _DomainAndProjectUserSystemAssignmentTests: with self.test_client() as c: c.get( - '/v3/system/groups/%s/roles/%s' - % (group['id'], self.bootstrapper.member_role_id), + '/v3/system/groups/{}/roles/{}'.format( + group['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -270,8 +278,9 @@ class _DomainAndProjectUserSystemAssignmentTests: with self.test_client() as c: c.put( - '/v3/system/groups/%s/roles/%s' - % (group['id'], self.bootstrapper.member_role_id), + '/v3/system/groups/{}/roles/{}'.format( + group['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -287,8 +296,9 @@ class _DomainAndProjectUserSystemAssignmentTests: with self.test_client() as c: c.delete( - '/v3/system/groups/%s/roles/%s' - % (group['id'], self.bootstrapper.member_role_id), + '/v3/system/groups/{}/roles/{}'.format( + group['id'], self.bootstrapper.member_role_id + ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -300,7 +310,6 @@ class SystemReaderTests( _SystemUserSystemAssignmentTests, _SystemMemberAndReaderSystemAssignmentTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -335,7 +344,6 @@ class SystemMemberTests( _SystemUserSystemAssignmentTests, _SystemMemberAndReaderSystemAssignmentTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -377,7 +385,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserSystemAssignmentTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -407,8 +414,9 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/system/users/%s/roles/%s' - % (user['id'], self.bootstrapper.member_role_id), + '/v3/system/users/{}/roles/{}'.format( + user['id'], self.bootstrapper.member_role_id + ), headers=self.headers, ) @@ -423,8 +431,9 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/system/users/%s/roles/%s' - % (user['id'], self.bootstrapper.member_role_id), + '/v3/system/users/{}/roles/{}'.format( + user['id'], self.bootstrapper.member_role_id + ), headers=self.headers, ) @@ -435,8 +444,9 @@ class SystemAdminTests( with self.test_client() as c: c.put( - '/v3/system/groups/%s/roles/%s' - % (group['id'], self.bootstrapper.member_role_id), + '/v3/system/groups/{}/roles/{}'.format( + group['id'], self.bootstrapper.member_role_id + ), headers=self.headers, ) @@ -451,8 +461,9 @@ class SystemAdminTests( with self.test_client() as c: c.delete( - '/v3/system/groups/%s/roles/%s' - % (group['id'], self.bootstrapper.member_role_id), + '/v3/system/groups/{}/roles/{}'.format( + group['id'], self.bootstrapper.member_role_id + ), headers=self.headers, ) @@ -462,7 +473,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserSystemAssignmentTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -502,7 +512,6 @@ class ProjectReaderTests( common_auth.AuthTestMixin, _DomainAndProjectUserSystemAssignmentTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -548,7 +557,6 @@ class ProjectMemberTests( common_auth.AuthTestMixin, _DomainAndProjectUserSystemAssignmentTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -594,7 +602,6 @@ class ProjectAdminTests( common_auth.AuthTestMixin, _DomainAndProjectUserSystemAssignmentTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_tokens.py b/keystone/tests/protection/v3/test_tokens.py index 17e6f5a375..2cb85efe08 100644 --- a/keystone/tests/protection/v3/test_tokens.py +++ b/keystone/tests/protection/v3/test_tokens.py @@ -25,7 +25,6 @@ PROVIDERS = provider_api.ProviderAPIs class _SystemUserTokenTests: - def test_user_can_validate_system_scoped_token(self): user = unit.new_user_ref(domain_id=CONF.identity.default_domain_id) user['id'] = PROVIDERS.identity_api.create_user(user)['id'] @@ -105,7 +104,6 @@ class _SystemUserTokenTests: class _SystemMemberAndReaderTokenTests: - def test_user_cannot_revoke_a_system_scoped_token(self): user = unit.new_user_ref(domain_id=CONF.identity.default_domain_id) user['id'] = PROVIDERS.identity_api.create_user(user)['id'] @@ -202,7 +200,6 @@ class SystemReaderTests( _SystemUserTokenTests, _SystemMemberAndReaderTokenTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -237,7 +234,6 @@ class SystemMemberTests( _SystemUserTokenTests, _SystemMemberAndReaderTokenTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -271,7 +267,6 @@ class SystemAdminTests( common_auth.AuthTestMixin, _SystemUserTokenTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -371,7 +366,6 @@ class SystemAdminTests( class _DomainAndProjectUserTests: - def test_user_can_validate_their_own_tokens(self): with self.test_client() as c: self.headers['X-Subject-Token'] = self.token_id @@ -566,7 +560,6 @@ class DomainUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -606,7 +599,6 @@ class ProjectUserTests( common_auth.AuthTestMixin, _DomainAndProjectUserTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/protection/v3/test_trusts.py b/keystone/tests/protection/v3/test_trusts.py index 16c4056506..0ab1a0dda6 100644 --- a/keystone/tests/protection/v3/test_trusts.py +++ b/keystone/tests/protection/v3/test_trusts.py @@ -170,7 +170,7 @@ class AdminTokenTests(TrustTests, _AdminTestsMixin): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.headers, expected_status_code=http.client.NO_CONTENT, ) @@ -179,7 +179,7 @@ class AdminTokenTests(TrustTests, _AdminTestsMixin): trust_id = uuid.uuid4().hex with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s' % trust_id, + f'/v3/OS-TRUST/trusts/{trust_id}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -189,7 +189,7 @@ class AdminTokenTests(TrustTests, _AdminTestsMixin): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -199,7 +199,7 @@ class AdminTokenTests(TrustTests, _AdminTestsMixin): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s/roles' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -210,8 +210,7 @@ class AdminTokenTests(TrustTests, _AdminTestsMixin): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts/%s/roles/%s' - % (self.trust_id, self.bootstrapper.member_role_id) + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles/{self.bootstrapper.member_role_id}' ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -225,7 +224,7 @@ class _SystemUserTests: trust_id = uuid.uuid4().hex with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s' % trust_id, + f'/v3/OS-TRUST/trusts/{trust_id}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -235,7 +234,7 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/OS-TRUST/trusts/%s' % self.trust_id, headers=self.headers + f'/v3/OS-TRUST/trusts/{self.trust_id}', headers=self.headers ) self.assertEqual(r.json['trust']['id'], self.trust_id) @@ -245,8 +244,7 @@ class _SystemUserTests: with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustee_user_id=%s' - % self.trustee_user_id + f'/v3/OS-TRUST/trusts?trustee_user_id={self.trustee_user_id}' ), headers=self.headers, ) @@ -257,8 +255,7 @@ class _SystemUserTests: with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustor_user_id=%s' - % self.trustor_user_id + f'/v3/OS-TRUST/trusts?trustor_user_id={self.trustor_user_id}' ), headers=self.headers, ) @@ -268,7 +265,7 @@ class _SystemUserTests: with self.test_client() as c: r = c.get( - '/v3/OS-TRUST/trusts/%s/roles' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles', headers=self.headers, ) self.assertEqual( @@ -281,8 +278,7 @@ class _SystemUserTests: with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts/%s/roles/%s' - % (self.trust_id, self.bootstrapper.member_role_id) + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles/{self.bootstrapper.member_role_id}' ), headers=self.headers, ) @@ -310,7 +306,7 @@ class _SystemReaderMemberTests(_SystemUserTests): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -402,7 +398,8 @@ class SystemAdminTests(TrustTests, _AdminTestsMixin, _SystemUserTests): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], headers=self.headers + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), + headers=self.headers, ) def test_admin_cannot_delete_trust_for_user_overridden_defaults(self): @@ -414,7 +411,7 @@ class SystemAdminTests(TrustTests, _AdminTestsMixin, _SystemUserTests): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -425,7 +422,7 @@ class SystemAdminTests(TrustTests, _AdminTestsMixin, _SystemUserTests): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -436,7 +433,7 @@ class SystemAdminTests(TrustTests, _AdminTestsMixin, _SystemUserTests): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s/roles' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -448,8 +445,7 @@ class SystemAdminTests(TrustTests, _AdminTestsMixin, _SystemUserTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts/%s/roles/%s' - % (self.trust_id, self.bootstrapper.member_role_id) + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles/{self.bootstrapper.member_role_id}' ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -497,8 +493,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: r = c.get( ( - '/v3/OS-TRUST/trusts?trustor_user_id=%s' - % self.trustor_user_id + f'/v3/OS-TRUST/trusts?trustor_user_id={self.trustor_user_id}' ), headers=self.trustor_headers, ) @@ -511,8 +506,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: r = c.get( ( - '/v3/OS-TRUST/trusts?trustee_user_id=%s' - % self.trustee_user_id + f'/v3/OS-TRUST/trusts?trustee_user_id={self.trustee_user_id}' ), headers=self.trustee_headers, ) @@ -525,8 +519,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustee_user_id=%s' - % self.trustee_user_id + f'/v3/OS-TRUST/trusts?trustee_user_id={self.trustee_user_id}' ), headers=self.trustor_headers, expected_status_code=http.client.FORBIDDEN, @@ -538,8 +531,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustor_user_id=%s' - % self.trustor_user_id + f'/v3/OS-TRUST/trusts?trustor_user_id={self.trustor_user_id}' ), headers=self.trustee_headers, expected_status_code=http.client.FORBIDDEN, @@ -551,8 +543,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustor_user_id=%s' - % self.trustor_user_id + f'/v3/OS-TRUST/trusts?trustor_user_id={self.trustor_user_id}' ), headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, @@ -564,8 +555,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustee_user_id=%s' - % self.trustee_user_id + f'/v3/OS-TRUST/trusts?trustee_user_id={self.trustee_user_id}' ), headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, @@ -588,7 +578,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, ) @@ -597,7 +587,7 @@ class ProjectUserTests(TrustTests): trust_id = uuid.uuid4().hex with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s' % trust_id, + f'/v3/OS-TRUST/trusts/{trust_id}', headers=self.other_headers, expected_status_code=http.client.NOT_FOUND, ) @@ -609,7 +599,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.trustor_headers, ) @@ -620,7 +610,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: r = c.get( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.trustee_headers, ) self.assertEqual(r.json['trust']['id'], self.trust_id) @@ -653,7 +643,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.trustor_headers, ) @@ -664,7 +654,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.trustee_headers, expected_status_code=http.client.FORBIDDEN, ) @@ -676,7 +666,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, ) @@ -686,7 +676,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: r = c.get( - '/v3/OS-TRUST/trusts/%s/roles' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles', headers=self.trustor_headers, ) self.assertEqual( @@ -698,7 +688,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: r = c.get( - '/v3/OS-TRUST/trusts/%s/roles' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles', headers=self.trustee_headers, ) self.assertEqual( @@ -710,7 +700,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s/roles' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles', headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, ) @@ -721,8 +711,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.head( ( - '/v3/OS-TRUST/trusts/%s/roles/%s' - % (self.trust_id, self.bootstrapper.member_role_id) + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles/{self.bootstrapper.member_role_id}' ), headers=self.trustor_headers, ) @@ -733,8 +722,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.head( ( - '/v3/OS-TRUST/trusts/%s/roles/%s' - % (self.trust_id, self.bootstrapper.member_role_id) + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles/{self.bootstrapper.member_role_id}' ), headers=self.trustee_headers, ) @@ -745,8 +733,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.head( ( - '/v3/OS-TRUST/trusts/%s/roles/%s' - % (self.trust_id, self.bootstrapper.member_role_id) + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles/{self.bootstrapper.member_role_id}' ), headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, @@ -759,8 +746,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustee_user_id=%s' - % self.trustee_user_id + f'/v3/OS-TRUST/trusts?trustee_user_id={self.trustee_user_id}' ), headers=self.trustor_headers, expected_status_code=http.client.FORBIDDEN, @@ -773,8 +759,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustor_user_id=%s' - % self.trustor_user_id + f'/v3/OS-TRUST/trusts?trustor_user_id={self.trustor_user_id}' ), headers=self.trustee_headers, expected_status_code=http.client.FORBIDDEN, @@ -787,8 +772,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustor_user_id=%s' - % self.trustor_user_id + f'/v3/OS-TRUST/trusts?trustor_user_id={self.trustor_user_id}' ), headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, @@ -801,8 +785,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustee_user_id=%s' - % self.trustee_user_id + f'/v3/OS-TRUST/trusts?trustee_user_id={self.trustee_user_id}' ), headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, @@ -827,7 +810,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.trustor_headers, ) @@ -839,7 +822,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.trustee_headers, expected_status_code=http.client.FORBIDDEN, ) @@ -852,7 +835,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, ) @@ -865,7 +848,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.trustor_headers, ) @@ -877,7 +860,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: r = c.get( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.trustee_headers, ) self.assertEqual(r.json['trust']['id'], self.trust_id) @@ -888,7 +871,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: r = c.get( - '/v3/OS-TRUST/trusts/%s/roles' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles', headers=self.trustor_headers, ) self.assertEqual( @@ -901,7 +884,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: r = c.get( - '/v3/OS-TRUST/trusts/%s/roles' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles', headers=self.trustee_headers, ) self.assertEqual( @@ -914,7 +897,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s/roles' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles', headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, ) @@ -926,8 +909,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.head( ( - '/v3/OS-TRUST/trusts/%s/roles/%s' - % (self.trust_id, self.bootstrapper.member_role_id) + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles/{self.bootstrapper.member_role_id}' ), headers=self.trustor_headers, ) @@ -939,8 +921,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.head( ( - '/v3/OS-TRUST/trusts/%s/roles/%s' - % (self.trust_id, self.bootstrapper.member_role_id) + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles/{self.bootstrapper.member_role_id}' ), headers=self.trustee_headers, ) @@ -952,8 +933,7 @@ class ProjectUserTests(TrustTests): with self.test_client() as c: c.head( ( - '/v3/OS-TRUST/trusts/%s/roles/%s' - % (self.trust_id, self.bootstrapper.member_role_id) + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles/{self.bootstrapper.member_role_id}' ), headers=self.other_headers, expected_status_code=http.client.FORBIDDEN, @@ -995,8 +975,7 @@ class DomainUserTests(TrustTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustee_user_id=%s' - % self.trustee_user_id + f'/v3/OS-TRUST/trusts?trustee_user_id={self.trustee_user_id}' ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -1008,8 +987,7 @@ class DomainUserTests(TrustTests): with self.test_client() as c: c.get( ( - '/v3/OS-TRUST/trusts?trustor_user_id=%s' - % self.trustor_user_id + f'/v3/OS-TRUST/trusts?trustor_user_id={self.trustor_user_id}' ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -1032,7 +1010,7 @@ class DomainUserTests(TrustTests): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1041,7 +1019,7 @@ class DomainUserTests(TrustTests): trust_id = uuid.uuid4().hex with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s' % trust_id, + f'/v3/OS-TRUST/trusts/{trust_id}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -1067,7 +1045,7 @@ class DomainUserTests(TrustTests): with self.test_client() as c: c.delete( - '/v3/OS-TRUST/trusts/%s' % ref['id'], + '/v3/OS-TRUST/trusts/{}'.format(ref['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1077,7 +1055,7 @@ class DomainUserTests(TrustTests): with self.test_client() as c: c.get( - '/v3/OS-TRUST/trusts/%s/roles' % self.trust_id, + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -1088,8 +1066,7 @@ class DomainUserTests(TrustTests): with self.test_client() as c: c.head( ( - '/v3/OS-TRUST/trusts/%s/roles/%s' - % (self.trust_id, self.bootstrapper.member_role_id) + f'/v3/OS-TRUST/trusts/{self.trust_id}/roles/{self.bootstrapper.member_role_id}' ), headers=self.headers, expected_status_code=http.client.FORBIDDEN, diff --git a/keystone/tests/protection/v3/test_users.py b/keystone/tests/protection/v3/test_users.py index 9a5b348104..1931e73118 100644 --- a/keystone/tests/protection/v3/test_users.py +++ b/keystone/tests/protection/v3/test_users.py @@ -33,7 +33,7 @@ class _CommonUserTests: def test_user_can_get_their_own_user_reference(self): with self.test_client() as c: - r = c.get('/v3/users/%s' % self.user_id, headers=self.headers) + r = c.get(f'/v3/users/{self.user_id}', headers=self.headers) self.assertEqual(self.user_id, r.json['user']['id']) @@ -46,13 +46,13 @@ class _SystemUserTests: ) with self.test_client() as c: - r = c.get('/v3/users/%s' % user['id'], headers=self.headers) + r = c.get('/v3/users/{}'.format(user['id']), headers=self.headers) self.assertEqual(user['id'], r.json['user']['id']) def test_user_cannot_get_non_existent_user_not_found(self): with self.test_client() as c: c.get( - '/v3/users/%s' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -103,7 +103,7 @@ class _SystemMemberAndReaderUserTests: update = {'user': {'email': uuid.uuid4().hex}} c.patch( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -117,7 +117,7 @@ class _SystemMemberAndReaderUserTests: update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -130,7 +130,7 @@ class _SystemMemberAndReaderUserTests: with self.test_client() as c: c.delete( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -138,7 +138,7 @@ class _SystemMemberAndReaderUserTests: def test_user_cannot_delete_non_existent_user_forbidden(self): with self.test_client() as c: c.delete( - '/v3/users/%s' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -153,7 +153,7 @@ class _DomainUserTests: ) with self.test_client() as c: - r = c.get('/v3/users/%s' % user['id'], headers=self.headers) + r = c.get('/v3/users/{}'.format(user['id']), headers=self.headers) self.assertEqual(user['id'], r.json['user']['id']) def test_user_cannot_get_user_in_other_domain(self): @@ -167,7 +167,7 @@ class _DomainUserTests: with self.test_client() as c: c.get( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -244,7 +244,7 @@ class _DomainMemberAndReaderUserTests: update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -261,7 +261,7 @@ class _DomainMemberAndReaderUserTests: update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -275,7 +275,7 @@ class _DomainMemberAndReaderUserTests: update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -288,7 +288,7 @@ class _DomainMemberAndReaderUserTests: with self.test_client() as c: c.delete( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -303,7 +303,7 @@ class _DomainMemberAndReaderUserTests: with self.test_client() as c: c.delete( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -311,7 +311,7 @@ class _DomainMemberAndReaderUserTests: def test_user_cannot_delete_non_existent_user_forbidden(self): with self.test_client() as c: c.delete( - '/v3/users/%s' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -327,7 +327,7 @@ class _ProjectUserTests: with self.test_client() as c: c.get( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -342,7 +342,7 @@ class _ProjectUserTests: with self.test_client() as c: c.get( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -350,7 +350,7 @@ class _ProjectUserTests: def test_user_cannot_get_non_existent_user_forbidden(self): with self.test_client() as c: c.get( - '/v3/users/%s' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -358,7 +358,7 @@ class _ProjectUserTests: def test_user_cannot_list_users_within_domain(self): with self.test_client() as c: c.get( - '/v3/users?domain_id=%s' % self.domain_id, + f'/v3/users?domain_id={self.domain_id}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -373,7 +373,7 @@ class _ProjectUserTests: with self.test_client() as c: c.get( - '/v3/users?domain_id=%s' % domain['id'], + '/v3/users?domain_id={}'.format(domain['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -416,7 +416,7 @@ class _ProjectUserTests: update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -433,7 +433,7 @@ class _ProjectUserTests: update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -443,7 +443,7 @@ class _ProjectUserTests: update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -456,7 +456,7 @@ class _ProjectUserTests: with self.test_client() as c: c.delete( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -471,7 +471,7 @@ class _ProjectUserTests: with self.test_client() as c: c.delete( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -479,7 +479,7 @@ class _ProjectUserTests: def test_user_cannot_delete_non_existent_user_forbidden(self): with self.test_client() as c: c.delete( - '/v3/users/%s' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -492,7 +492,6 @@ class SystemReaderTests( _SystemUserTests, _SystemMemberAndReaderUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -528,7 +527,6 @@ class SystemMemberTests( _SystemUserTests, _SystemMemberAndReaderUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -563,7 +561,6 @@ class SystemAdminTests( _CommonUserTests, _SystemUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -603,14 +600,16 @@ class SystemAdminTests( update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % user['id'], json=update, headers=self.headers + '/v3/users/{}'.format(user['id']), + json=update, + headers=self.headers, ) def test_user_cannot_update_non_existent_user_not_found(self): update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.NOT_FOUND, @@ -622,12 +621,12 @@ class SystemAdminTests( ) with self.test_client() as c: - c.delete('/v3/users/%s' % user['id'], headers=self.headers) + c.delete('/v3/users/{}'.format(user['id']), headers=self.headers) def test_user_cannot_delete_non_existent_user_not_found(self): with self.test_client() as c: c.delete( - '/v3/users/%s' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.NOT_FOUND, ) @@ -640,7 +639,6 @@ class DomainReaderTests( _DomainUserTests, _DomainMemberAndReaderUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -680,7 +678,6 @@ class DomainMemberTests( _DomainUserTests, _DomainMemberAndReaderUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -719,7 +716,6 @@ class DomainAdminTests( _CommonUserTests, _DomainUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -833,7 +829,9 @@ class DomainAdminTests( update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % user['id'], json=update, headers=self.headers + '/v3/users/{}'.format(user['id']), + json=update, + headers=self.headers, ) def test_user_can_update_users_within_domain_hyphened_domain_id(self): @@ -851,7 +849,9 @@ class DomainAdminTests( update = {'user': {'domain-id': domain['id']}} with self.test_client() as c: r = c.patch( - '/v3/users/%s' % user['id'], json=update, headers=self.headers + '/v3/users/{}'.format(user['id']), + json=update, + headers=self.headers, ) self.assertEqual(domain['id'], r.json['user']['domain-id']) self.assertEqual(self.domain_id, r.json['user']['domain_id']) @@ -867,7 +867,7 @@ class DomainAdminTests( update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -877,7 +877,7 @@ class DomainAdminTests( update = {'user': {'email': uuid.uuid4().hex}} with self.test_client() as c: c.patch( - '/v3/users/%s' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}', json=update, headers=self.headers, expected_status_code=http.client.FORBIDDEN, @@ -889,7 +889,7 @@ class DomainAdminTests( ) with self.test_client() as c: - c.delete('/v3/users/%s' % user['id'], headers=self.headers) + c.delete('/v3/users/{}'.format(user['id']), headers=self.headers) def test_user_cannot_delete_users_in_other_domain(self): domain = PROVIDERS.resource_api.create_domain( @@ -901,7 +901,7 @@ class DomainAdminTests( with self.test_client() as c: c.delete( - '/v3/users/%s' % user['id'], + '/v3/users/{}'.format(user['id']), headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -909,7 +909,7 @@ class DomainAdminTests( def test_user_cannot_delete_non_existent_user_forbidden(self): with self.test_client() as c: c.delete( - '/v3/users/%s' % uuid.uuid4().hex, + f'/v3/users/{uuid.uuid4().hex}', headers=self.headers, expected_status_code=http.client.FORBIDDEN, ) @@ -921,7 +921,6 @@ class ProjectReaderTests( _CommonUserTests, _ProjectUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -965,7 +964,6 @@ class ProjectMemberTests( _CommonUserTests, _ProjectUserTests, ): - def setUp(self): super().setUp() self.loadapp() @@ -1009,7 +1007,6 @@ class ProjectAdminTests( _CommonUserTests, _ProjectUserTests, ): - def setUp(self): super().setUp() self.loadapp() diff --git a/keystone/tests/unit/application_credential/test_backends.py b/keystone/tests/unit/application_credential/test_backends.py index c4d6751cb1..9c8737ce70 100644 --- a/keystone/tests/unit/application_credential/test_backends.py +++ b/keystone/tests/unit/application_credential/test_backends.py @@ -26,7 +26,6 @@ PROVIDERS = provider_api.ProviderAPIs class ApplicationCredentialTests: - def _new_app_cred_data( self, user_id, project_id=None, name=None, expires=None, system=None ): @@ -46,9 +45,7 @@ class ApplicationCredentialTests: 'project_id': project_id, 'system': system, 'expires_at': expires, - 'roles': [ - {'id': self.role__member_['id']}, - ], + 'roles': [{'id': self.role__member_['id']}], 'secret': uuid.uuid4().hex, 'unrestricted': False, } diff --git a/keystone/tests/unit/assignment/role_backends/test_sql.py b/keystone/tests/unit/assignment/role_backends/test_sql.py index ba2ff61eb0..436d0a0ad1 100644 --- a/keystone/tests/unit/assignment/role_backends/test_sql.py +++ b/keystone/tests/unit/assignment/role_backends/test_sql.py @@ -23,7 +23,6 @@ PROVIDERS = provider_api.ProviderAPIs class SqlRoleModels(core_sql.BaseBackendSqlModels): - def test_role_model(self): cols = ( ('id', sql.String, 64), @@ -34,7 +33,6 @@ class SqlRoleModels(core_sql.BaseBackendSqlModels): class SqlRole(core_sql.BaseBackendSqlTests, test_core.RoleTests): - def test_create_null_role_name(self): role = unit.new_role_ref(name=None) self.assertRaises( diff --git a/keystone/tests/unit/assignment/test_backends.py b/keystone/tests/unit/assignment/test_backends.py index c0df09f7d1..dbb59cebe3 100644 --- a/keystone/tests/unit/assignment/test_backends.py +++ b/keystone/tests/unit/assignment/test_backends.py @@ -295,8 +295,8 @@ class AssignmentTestHelperMixin: This method converts the shorthand version into the full reference. """ - expanded_key = '%s_id' % key - reference_index = '%ss' % key + expanded_key = f'{key}_id' + reference_index = f'{key}s' index_value = reference_data[reference_index][shorthand_data[key]][ 'id' ] @@ -471,7 +471,6 @@ class AssignmentTestHelperMixin: class AssignmentTests(AssignmentTestHelperMixin): - def _get_domain_fixture(self): domain = unit.new_domain_ref() PROVIDERS.resource_api.create_domain(domain['id'], domain) @@ -2130,9 +2129,7 @@ class AssignmentTests(AssignmentTestHelperMixin): 'role': 1, 'effective': True, }, - 'results': [ - {'group': 0, 'role': 1, 'domain': 1}, - ], + 'results': [{'group': 0, 'role': 1, 'domain': 1}], }, ], } @@ -3036,7 +3033,6 @@ class AssignmentTests(AssignmentTestHelperMixin): class InheritanceTests(AssignmentTestHelperMixin): - def test_role_assignments_user_domain_to_project_inheritance(self): test_plan = { 'entities': {'domains': {'users': 2, 'projects': 1}, 'roles': 3}, @@ -4377,14 +4373,13 @@ class InheritanceTests(AssignmentTestHelperMixin): }, {'group': 1, 'role': 2, 'project': 1}, ], - }, + } ], } self.execute_assignment_plan(test_plan) class ImpliedRoleTests(AssignmentTestHelperMixin): - def test_implied_role_crd(self): prior_role_ref = unit.new_role_ref() PROVIDERS.role_api.create_role(prior_role_ref['id'], prior_role_ref) @@ -4581,7 +4576,7 @@ class ImpliedRoleTests(AssignmentTestHelperMixin): 'indirect': {'role': 5}, }, ], - }, + } ], } test_data = self.execute_assignment_plan(test_plan) @@ -4627,7 +4622,7 @@ class ImpliedRoleTests(AssignmentTestHelperMixin): }, {'user': 0, 'role': 3, 'project': 1}, ], - }, + } ], } self.execute_assignment_plan(test_plan) diff --git a/keystone/tests/unit/assignment/test_core.py b/keystone/tests/unit/assignment/test_core.py index 6497125114..5f16b2f7eb 100644 --- a/keystone/tests/unit/assignment/test_core.py +++ b/keystone/tests/unit/assignment/test_core.py @@ -25,7 +25,6 @@ PROVIDERS = provider_api.ProviderAPIs class RoleTests: - def test_get_role_returns_not_found(self): self.assertRaises( exception.RoleNotFound, diff --git a/keystone/tests/unit/auth/plugins/test_core.py b/keystone/tests/unit/auth/plugins/test_core.py index f0d90de075..81a4779bd5 100644 --- a/keystone/tests/unit/auth/plugins/test_core.py +++ b/keystone/tests/unit/auth/plugins/test_core.py @@ -15,7 +15,6 @@ from keystone.tests import unit class TestPluginCore(unit.TestCase): - def test_construct_method_map_with_one_methods(self): auth_methods = ['password'] self.config_fixture.config(group='auth', methods=auth_methods) diff --git a/keystone/tests/unit/auth/test_controllers.py b/keystone/tests/unit/auth/test_controllers.py index c26e0f1c71..9c4c5e5fd3 100644 --- a/keystone/tests/unit/auth/test_controllers.py +++ b/keystone/tests/unit/auth/test_controllers.py @@ -42,7 +42,7 @@ class TestLoadAuthMethod(unit.BaseTestCase): plugin=mock.sentinel.plugin, obj=mock.sentinel.driver, ) - auth_plugin_namespace = 'keystone.auth.%s' % method + auth_plugin_namespace = f'keystone.auth.{method}' fake_driver_manager = stevedore.DriverManager.make_test_instance( extension_, namespace=auth_plugin_namespace ) diff --git a/keystone/tests/unit/auth/test_schema.py b/keystone/tests/unit/auth/test_schema.py index d9880ccf5b..2ad2255d82 100644 --- a/keystone/tests/unit/auth/test_schema.py +++ b/keystone/tests/unit/auth/test_schema.py @@ -46,21 +46,12 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): def test_no_auth_plugin_parameters(self): # auth plugin (password / token) may not be present. - post_data = { - 'identity': { - 'methods': ['password'], - }, - } + post_data = {'identity': {'methods': ['password']}} schema.validate_issue_token_auth(post_data) def test_password_not_object_ex(self): # if password is present, it must be an object. - p = { - 'identity': { - 'methods': ['password'], - 'password': 'something', - }, - } + p = {'identity': {'methods': ['password'], 'password': 'something'}} self._expect_failure(p) def test_password_user_not_object_ex(self): @@ -68,10 +59,8 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): p = { 'identity': { 'methods': ['password'], - 'password': { - 'user': 'something', - }, - }, + 'password': {'user': 'something'}, + } } self._expect_failure(p) @@ -80,12 +69,8 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): p = { 'identity': { 'methods': ['password'], - 'password': { - 'user': { - 'name': 1, - }, - }, - }, + 'password': {'user': {'name': 1}}, + } } self._expect_failure(p) @@ -94,25 +79,14 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): p = { 'identity': { 'methods': ['password'], - 'password': { - 'user': { - 'id': {}, - }, - }, - }, + 'password': {'user': {'id': {}}}, + } } self._expect_failure(p) def test_password_no_user_id_or_name_ex(self): # either user id or name must be present. - p = { - 'identity': { - 'methods': ['password'], - 'password': { - 'user': {}, - }, - }, - } + p = {'identity': {'methods': ['password'], 'password': {'user': {}}}} self._expect_failure(p) def test_password_user_password_not_string_ex(self): @@ -120,13 +94,8 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): p = { 'identity': { 'methods': ['password'], - 'password': { - 'user': { - 'id': 'something', - 'password': {}, - }, - }, - }, + 'password': {'user': {'id': 'something', 'password': {}}}, + } } self._expect_failure(p) @@ -136,12 +105,9 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): 'identity': { 'methods': ['password'], 'password': { - 'user': { - 'id': 'something', - 'domain': 'something', - }, + 'user': {'id': 'something', 'domain': 'something'} }, - }, + } } self._expect_failure(p) @@ -150,13 +116,8 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): p = { 'identity': { 'methods': ['password'], - 'password': { - 'user': { - 'id': 'something', - 'domain': {}, - }, - }, - }, + 'password': {'user': {'id': 'something', 'domain': {}}}, + } } self._expect_failure(p) @@ -166,12 +127,9 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): 'identity': { 'methods': ['password'], 'password': { - 'user': { - 'id': 'something', - 'domain': {'name': {}}, - }, + 'user': {'id': 'something', 'domain': {'name': {}}} }, - }, + } } self._expect_failure(p) @@ -181,232 +139,100 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): 'identity': { 'methods': ['password'], 'password': { - 'user': { - 'id': 'something', - 'domain': {'id': {}}, - }, + 'user': {'id': 'something', 'domain': {'id': {}}} }, - }, + } } self._expect_failure(p) def test_token(self): # valid token auth plugin data is supported. - p = { - 'identity': { - 'methods': ['token'], - 'token': { - 'id': 'something', - }, - }, - } + p = {'identity': {'methods': ['token'], 'token': {'id': 'something'}}} schema.validate_issue_token_auth(p) def test_token_not_object_ex(self): # if token auth plugin data is present, it must be an object. - p = { - 'identity': { - 'methods': ['token'], - 'token': '', - }, - } + p = {'identity': {'methods': ['token'], 'token': ''}} self._expect_failure(p) def test_token_no_id_ex(self): # if token auth plugin data is present, id must be present. - p = { - 'identity': { - 'methods': ['token'], - 'token': {}, - }, - } + p = {'identity': {'methods': ['token'], 'token': {}}} self._expect_failure(p) def test_token_id_not_string_ex(self): # if token auth plugin data is present, id must be a string. - p = { - 'identity': { - 'methods': ['token'], - 'token': { - 'id': 123, - }, - }, - } + p = {'identity': {'methods': ['token'], 'token': {'id': 123}}} self._expect_failure(p) def test_scope_not_object_or_string_ex(self): - p = { - 'identity': { - 'methods': [], - }, - 'scope': 1, - } + p = {'identity': {'methods': []}, 'scope': 1} self._expect_failure(p) def test_project_not_object_ex(self): - p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'project': 'something', - }, - } + p = {'identity': {'methods': []}, 'scope': {'project': 'something'}} self._expect_failure(p) def test_project_name_not_string_ex(self): - p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'project': { - 'name': {}, - }, - }, - } + p = {'identity': {'methods': []}, 'scope': {'project': {'name': {}}}} self._expect_failure(p) def test_project_id_not_string_ex(self): - p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'project': { - 'id': {}, - }, - }, - } + p = {'identity': {'methods': []}, 'scope': {'project': {'id': {}}}} self._expect_failure(p) def test_project_no_id_or_name_ex(self): - p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'project': {}, - }, - } + p = {'identity': {'methods': []}, 'scope': {'project': {}}} self._expect_failure(p) def test_project_domain_not_object_ex(self): p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'project': { - 'id': 'something', - 'domain': 'something', - }, - }, + 'identity': {'methods': []}, + 'scope': {'project': {'id': 'something', 'domain': 'something'}}, } self._expect_failure(p) def test_project_domain_name_not_string_ex(self): p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'project': { - 'id': 'something', - 'domain': { - 'name': {}, - }, - }, - }, + 'identity': {'methods': []}, + 'scope': {'project': {'id': 'something', 'domain': {'name': {}}}}, } self._expect_failure(p) def test_project_domain_id_not_string_ex(self): p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'project': { - 'id': 'something', - 'domain': { - 'id': {}, - }, - }, - }, + 'identity': {'methods': []}, + 'scope': {'project': {'id': 'something', 'domain': {'id': {}}}}, } self._expect_failure(p) def test_project_domain_no_id_or_name_ex(self): p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'project': { - 'id': 'something', - 'domain': {}, - }, - }, + 'identity': {'methods': []}, + 'scope': {'project': {'id': 'something', 'domain': {}}}, } self._expect_failure(p) def test_domain_not_object_ex(self): - p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'domain': 'something', - }, - } + p = {'identity': {'methods': []}, 'scope': {'domain': 'something'}} self._expect_failure(p) def test_domain_id_not_string_ex(self): - p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'domain': { - 'id': {}, - }, - }, - } + p = {'identity': {'methods': []}, 'scope': {'domain': {'id': {}}}} self._expect_failure(p) def test_domain_name_not_string_ex(self): - p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'domain': { - 'name': {}, - }, - }, - } + p = {'identity': {'methods': []}, 'scope': {'domain': {'name': {}}}} self._expect_failure(p) def test_domain_no_id_or_name_ex(self): - p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'domain': {}, - }, - } + p = {'identity': {'methods': []}, 'scope': {'domain': {}}} self._expect_failure(p) def test_trust_not_object_ex(self): p = { - 'identity': { - 'methods': [], - }, - 'scope': { - 'OS-TRUST:trust': 'something', - }, + 'identity': {'methods': []}, + 'scope': {'OS-TRUST:trust': 'something'}, } self._expect_failure(p) @@ -417,13 +243,11 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): 'password': { 'user': { 'name': 'admin', - 'domain': { - 'name': 'Default', - }, + 'domain': {'name': 'Default'}, 'password': 'devstacker', - }, + } }, - }, + } } schema.validate_issue_token_auth(post_data) @@ -434,13 +258,11 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): 'password': { 'user': { 'name': 'admin', - 'domain': { - 'id': 'default', - }, + 'domain': {'id': 'default'}, 'password': 'devstacker', - }, + } }, - }, + } } schema.validate_issue_token_auth(post_data) @@ -451,13 +273,11 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): 'password': { 'user': { 'name': 'admin', - 'domain': { - 'name': 'Default', - }, + 'domain': {'name': 'Default'}, 'password': 'devstacker', - }, + } }, - }, + } } schema.validate_issue_token_auth(post_data) @@ -468,20 +288,13 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): 'password': { 'user': { 'name': 'admin', - 'domain': { - 'name': 'Default', - }, + 'domain': {'name': 'Default'}, 'password': 'devstacker', - }, + } }, }, 'scope': { - 'project': { - 'name': 'demo', - 'domain': { - 'name': 'Default', - }, - }, + 'project': {'name': 'demo', 'domain': {'name': 'Default'}} }, } schema.validate_issue_token_auth(post_data) @@ -493,18 +306,12 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): 'password': { 'user': { 'name': 'admin', - 'domain': { - 'name': 'Default', - }, + 'domain': {'name': 'Default'}, 'password': 'devstacker', - }, - }, - }, - 'scope': { - 'domain': { - 'name': 'Default', + } }, }, + 'scope': {'domain': {'name': 'Default'}}, } schema.validate_issue_token_auth(post_data) @@ -515,11 +322,9 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): 'password': { 'user': { 'name': 'admin', - 'domain': { - 'name': 'Default', - }, + 'domain': {'name': 'Default'}, 'password': 'devstacker', - }, + } }, }, 'scope': 'unscoped', @@ -535,32 +340,20 @@ class TestValidateIssueTokenAuth(unit.BaseTestCase): 'user': { 'id': 'whatever', 'extra4': 'whatever4', - 'domain': { - 'id': 'whatever', - 'extra5': 'whatever5', - }, + 'domain': {'id': 'whatever', 'extra5': 'whatever5'}, }, 'extra3': 'whatever3', }, - 'token': { - 'id': 'something', - 'extra9': 'whatever9', - }, + 'token': {'id': 'something', 'extra9': 'whatever9'}, 'extra4': 'whatever4', }, 'scope': { 'project': { 'id': 'something', - 'domain': { - 'id': 'something', - 'extra8': 'whatever8', - }, + 'domain': {'id': 'something', 'extra8': 'whatever8'}, 'extra7': 'whatever7', }, - 'domain': { - 'id': 'something', - 'extra9': 'whatever9', - }, + 'domain': {'id': 'something', 'extra9': 'whatever9'}, 'extra6': 'whatever6', }, 'extra2': 'whatever2', diff --git a/keystone/tests/unit/backend/core_ldap.py b/keystone/tests/unit/backend/core_ldap.py index b82e10a0f2..9dc8df9c5f 100644 --- a/keystone/tests/unit/backend/core_ldap.py +++ b/keystone/tests/unit/backend/core_ldap.py @@ -71,7 +71,7 @@ class BaseBackendLdapCommon: ldap_ = PROVIDERS.identity_api.driver.user.get_connection() res = ldap_.search_s( - user_dn, ldap.SCOPE_BASE, '(sn=%s)' % user['name'] + user_dn, ldap.SCOPE_BASE, '(sn={})'.format(user['name']) ) if enabled_attr_name in res[0][1]: return res[0][1][enabled_attr_name] diff --git a/keystone/tests/unit/backend/core_sql.py b/keystone/tests/unit/backend/core_sql.py index 008528fbeb..3e511c1259 100644 --- a/keystone/tests/unit/backend/core_sql.py +++ b/keystone/tests/unit/backend/core_sql.py @@ -19,7 +19,6 @@ from keystone.tests.unit.ksfixtures import database class BaseBackendSqlTests(unit.SQLDriverOverrides, unit.TestCase): - def setUp(self): super().setUp() self.database_fixture = self.useFixture(database.Database()) @@ -37,7 +36,6 @@ class BaseBackendSqlTests(unit.SQLDriverOverrides, unit.TestCase): class BaseBackendSqlModels(BaseBackendSqlTests): - def load_table(self, name): table = sqlalchemy.Table( name, diff --git a/keystone/tests/unit/catalog/test_backends.py b/keystone/tests/unit/catalog/test_backends.py index 64c8f0e067..88616837d5 100644 --- a/keystone/tests/unit/catalog/test_backends.py +++ b/keystone/tests/unit/catalog/test_backends.py @@ -26,7 +26,6 @@ PROVIDERS = provider_api.ProviderAPIs class CatalogTests: - _legacy_endpoint_id_in_endpoint = True _enabled_default_to_true_when_creating_endpoint = False @@ -630,8 +629,8 @@ class CatalogTests: ref = unit.new_endpoint_ref( service_id=service_id, region_id=region, - url='http://localhost/%s' % uuid.uuid4().hex, - **kwargs + url=f'http://localhost/{uuid.uuid4().hex}', + **kwargs, ) PROVIDERS.catalog_api.create_endpoint(ref['id'], ref) diff --git a/keystone/tests/unit/catalog/test_core.py b/keystone/tests/unit/catalog/test_core.py index 8ad88a7a43..c4f71c5e73 100644 --- a/keystone/tests/unit/catalog/test_core.py +++ b/keystone/tests/unit/catalog/test_core.py @@ -18,7 +18,6 @@ from keystone.tests import unit class FormatUrlTests(unit.BaseTestCase): - def test_successful_formatting(self): url_template = ( 'http://server:9090/$(tenant_id)s/$(user_id)s/$(project_id)s' diff --git a/keystone/tests/unit/common/test_cache.py b/keystone/tests/unit/common/test_cache.py index 784a691f43..1fcc471160 100644 --- a/keystone/tests/unit/common/test_cache.py +++ b/keystone/tests/unit/common/test_cache.py @@ -24,7 +24,6 @@ CONF = keystone.conf.CONF class TestCacheRegion(unit.BaseTestCase): - def setUp(self): super().setUp() self.config_fixture = self.useFixture(config_fixture.Config(CONF)) diff --git a/keystone/tests/unit/common/test_database_conflicts.py b/keystone/tests/unit/common/test_database_conflicts.py index 775ca584c7..3a9f7aaa59 100644 --- a/keystone/tests/unit/common/test_database_conflicts.py +++ b/keystone/tests/unit/common/test_database_conflicts.py @@ -40,7 +40,7 @@ class DuplicateTestCase(test_v3.RestfulTestCase): try: PROVIDERS.resource_api.create_domain(domain['id'], domain) except exception.Conflict as e: - self.assertIn("%s" % domain['name'], repr(e)) + self.assertIn("{}".format(domain['name']), repr(e)) else: self.fail("Creating duplicate domain did not raise a conflict") @@ -51,7 +51,7 @@ class DuplicateTestCase(test_v3.RestfulTestCase): try: PROVIDERS.resource_api.create_project(project['id'], project) except exception.Conflict as e: - self.assertIn("%s" % project['name'], repr(e)) + self.assertIn("{}".format(project['name']), repr(e)) else: self.fail("Creating duplicate project did not raise a conflict") @@ -63,7 +63,8 @@ class DuplicateTestCase(test_v3.RestfulTestCase): PROVIDERS.identity_api.create_user(user) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with name %s" % user['name'], repr(e) + "Duplicate entry found with name {}".format(user['name']), + repr(e), ) else: self.fail("Create duplicate user did not raise a conflict") @@ -76,7 +77,8 @@ class DuplicateTestCase(test_v3.RestfulTestCase): PROVIDERS.role_api.create_role(role['id'], role) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with name %s" % role['name'], repr(e) + "Duplicate entry found with name {}".format(role['name']), + repr(e), ) else: self.fail("Create duplicate role did not raise a conflict") @@ -88,7 +90,8 @@ class DuplicateTestCase(test_v3.RestfulTestCase): PROVIDERS.identity_api.create_group(group) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with name %s" % group['name'], repr(e) + "Duplicate entry found with name {}".format(group['name']), + repr(e), ) else: self.fail("Create duplicate group did not raise a conflict") @@ -100,7 +103,9 @@ class DuplicateTestCase(test_v3.RestfulTestCase): PROVIDERS.policy_api.create_policy(policy_ref['id'], policy_ref) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with name %s" % policy_ref['name'], + "Duplicate entry found with name {}".format( + policy_ref['name'] + ), repr(e), ) else: @@ -118,7 +123,8 @@ class DuplicateTestCase(test_v3.RestfulTestCase): ) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with ID %s" % credential['id'], repr(e) + "Duplicate entry found with ID {}".format(credential['id']), + repr(e), ) else: self.fail("Create duplicate credential did not raise a conflict") @@ -140,7 +146,8 @@ class DuplicateTestCase(test_v3.RestfulTestCase): ) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with ID %s" % trust_ref['id'], repr(e) + "Duplicate entry found with ID {}".format(trust_ref['id']), + repr(e), ) else: self.fail("Create duplicate trust did not raise a conflict") @@ -157,7 +164,7 @@ class DuplicateTestCase(test_v3.RestfulTestCase): ) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with ID %s" % self.mapping['id'], + "Duplicate entry found with ID {}".format(self.mapping['id']), repr(e), ) else: @@ -175,7 +182,7 @@ class DuplicateTestCase(test_v3.RestfulTestCase): ) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with ID %s" % self.mapping['id'], + "Duplicate entry found with ID {}".format(self.mapping['id']), repr(e), ) # Any other exception will cause the test to fail @@ -186,7 +193,7 @@ class DuplicateTestCase(test_v3.RestfulTestCase): try: PROVIDERS.catalog_api.create_region(region_ref) except exception.Conflict as e: - self.assertIn("Duplicate ID, %s" % region_ref['id'], repr(e)) + self.assertIn("Duplicate ID, {}".format(region_ref['id']), repr(e)) else: self.fail("Create duplicate region did not raise a conflict") @@ -212,7 +219,7 @@ class DuplicateTestCase(test_v3.RestfulTestCase): ) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with ID %s" % protocol_ret['id'], + "Duplicate entry found with ID {}".format(protocol_ret['id']), repr(e), ) else: @@ -246,7 +253,7 @@ class DuplicateTestCase(test_v3.RestfulTestCase): ) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with ID %s" % protocol_ret['id'], + "Duplicate entry found with ID {}".format(protocol_ret['id']), repr(e), ) # Any other exception will fail the test @@ -273,7 +280,7 @@ class DuplicateTestCase(test_v3.RestfulTestCase): ) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with ID %s" % protocol_ret['id'], + "Duplicate entry found with ID {}".format(protocol_ret['id']), repr(e), ) # Any other exception will fail the test @@ -291,7 +298,8 @@ class DuplicateTestCase(test_v3.RestfulTestCase): PROVIDERS.federation_api.create_sp('SP1', sp) except exception.Conflict as e: self.assertIn( - "Duplicate entry found with ID %s" % service_ref['id'], repr(e) + "Duplicate entry found with ID {}".format(service_ref['id']), + repr(e), ) else: self.fail("Create duplicate sp did not raise a conflict") diff --git a/keystone/tests/unit/common/test_json_home.py b/keystone/tests/unit/common/test_json_home.py index edbe20499d..ee53e4022a 100644 --- a/keystone/tests/unit/common/test_json_home.py +++ b/keystone/tests/unit/common/test_json_home.py @@ -25,10 +25,7 @@ class JsonHomeTest(unit.BaseTestCase): def test_build_v3_resource_relation(self): resource_name = self.getUniqueString() relation = json_home.build_v3_resource_relation(resource_name) - exp_relation = ( - 'https://docs.openstack.org/api/openstack-identity/3/rel/%s' - % resource_name - ) + exp_relation = f'https://docs.openstack.org/api/openstack-identity/3/rel/{resource_name}' self.assertThat(relation, matchers.Equals(exp_relation)) def test_build_v3_extension_resource_relation(self): @@ -39,18 +36,15 @@ class JsonHomeTest(unit.BaseTestCase): extension_name, extension_version, resource_name ) exp_relation = ( - 'https://docs.openstack.org/api/openstack-identity/3/ext/%s/%s/rel' - '/%s' % (extension_name, extension_version, resource_name) + f'https://docs.openstack.org/api/openstack-identity/3/ext/{extension_name}/{extension_version}/rel' + f'/{resource_name}' ) self.assertThat(relation, matchers.Equals(exp_relation)) def test_build_v3_parameter_relation(self): parameter_name = self.getUniqueString() relation = json_home.build_v3_parameter_relation(parameter_name) - exp_relation = ( - 'https://docs.openstack.org/api/openstack-identity/3/param/%s' - % parameter_name - ) + exp_relation = f'https://docs.openstack.org/api/openstack-identity/3/param/{parameter_name}' self.assertThat(relation, matchers.Equals(exp_relation)) def test_build_v3_extension_parameter_relation(self): @@ -61,8 +55,8 @@ class JsonHomeTest(unit.BaseTestCase): extension_name, extension_version, parameter_name ) exp_relation = ( - 'https://docs.openstack.org/api/openstack-identity/3/ext/%s/%s/' - 'param/%s' % (extension_name, extension_version, parameter_name) + f'https://docs.openstack.org/api/openstack-identity/3/ext/{extension_name}/{extension_version}/' + f'param/{parameter_name}' ) self.assertThat(relation, matchers.Equals(exp_relation)) diff --git a/keystone/tests/unit/common/test_notifications.py b/keystone/tests/unit/common/test_notifications.py index d3f642535b..65fa13b1b1 100644 --- a/keystone/tests/unit/common/test_notifications.py +++ b/keystone/tests/unit/common/test_notifications.py @@ -141,7 +141,6 @@ class AuditNotificationsTestCase(unit.BaseTestCase): class NotificationsTestCase(unit.BaseTestCase): - def setUp(self): super().setUp() self.config_fixture = self.useFixture(config_fixture.Config(CONF)) @@ -172,7 +171,7 @@ class NotificationsTestCase(unit.BaseTestCase): # ensures and maintains these conditions. expected_args = [ {}, # empty context - 'identity.%s.created' % resource_type, # event_type + f'identity.{resource_type}.created', # event_type {'resource_info': resource}, # payload ] @@ -193,7 +192,7 @@ class NotificationsTestCase(unit.BaseTestCase): resource = uuid.uuid4().hex resource_type = EXP_RESOURCE_TYPE operation = CREATED_OPERATION - event_type = 'identity.%s.created' % resource_type + event_type = f'identity.{resource_type}.created' # NOTE(diazjf): Here we add notification_opt_out to the # configuration so that we should return before _get_notifer is @@ -205,7 +204,6 @@ class NotificationsTestCase(unit.BaseTestCase): with mock.patch.object( notifications._get_notifier(), 'info' ) as mocked: - notifications._send_notification( operation, resource_type, resource ) @@ -223,7 +221,7 @@ class NotificationsTestCase(unit.BaseTestCase): initiator = mock target = mock outcome = 'success' - event_type = 'identity.%s.created' % resource_type + event_type = f'identity.{resource_type}.created' conf = self.useFixture(config_fixture.Config(CONF)) conf.config(notification_opt_out=[event_type]) @@ -231,7 +229,6 @@ class NotificationsTestCase(unit.BaseTestCase): with mock.patch.object( notifications._get_notifier(), 'info' ) as mocked: - notifications._send_audit_notification( action, initiator, outcome, target, event_type ) @@ -254,7 +251,6 @@ class NotificationsTestCase(unit.BaseTestCase): with mock.patch.object( notifications._get_notifier(), 'info' ) as mocked: - notifications._send_audit_notification( action, initiator, outcome, target, event_type ) @@ -262,7 +258,6 @@ class NotificationsTestCase(unit.BaseTestCase): class BaseNotificationTest(test_v3.RestfulTestCase): - def setUp(self): super().setUp() @@ -433,7 +428,6 @@ class BaseNotificationTest(test_v3.RestfulTestCase): class NotificationsForEntities(BaseNotificationTest): - def test_create_group(self): group_ref = unit.new_group_ref(domain_id=self.domain_id) group_ref = PROVIDERS.identity_api.create_group(group_ref) @@ -923,7 +917,7 @@ class NotificationsForEntities(BaseNotificationTest): self.assertIsNotNone(initiator.request_id) def test_initiator_global_request_id(self): - global_request_id = 'req-%s' % uuid.uuid4() + global_request_id = f'req-{uuid.uuid4()}' ref = unit.new_domain_ref() self.post( '/domains', @@ -943,7 +937,6 @@ class NotificationsForEntities(BaseNotificationTest): class CADFNotificationsForPCIDSSEvents(BaseNotificationTest): - def setUp(self): super().setUp() conf = self.useFixture(config_fixture.Config(CONF)) @@ -1151,7 +1144,6 @@ class CADFNotificationsForPCIDSSEvents(BaseNotificationTest): class CADFNotificationsForEntities(NotificationsForEntities): - def setUp(self): super().setUp() self.config_fixture.config(notification_format='cadf') @@ -1180,7 +1172,7 @@ class CADFNotificationsForEntities(NotificationsForEntities): self.assertIn('request_id', initiator) def test_initiator_global_request_id(self): - global_request_id = 'req-%s' % uuid.uuid4() + global_request_id = f'req-{uuid.uuid4()}' data = self.build_authentication_request( user_id=self.user_id, password=self.user['password'] ) @@ -1204,9 +1196,7 @@ class CADFNotificationsForEntities(NotificationsForEntities): class TestEventCallbacks(test_v3.RestfulTestCase): - class FakeManager: - def _project_deleted_callback( self, service, resource_type, operation, payload ): @@ -1347,7 +1337,6 @@ class TestEventCallbacks(test_v3.RestfulTestCase): class CadfNotificationsWrapperTestCase(test_v3.RestfulTestCase): - LOCAL_HOST = 'localhost' ACTION = 'authenticate' ROLE_ASSIGNMENT = 'role_assignment' @@ -1564,29 +1553,17 @@ class CadfNotificationsWrapperTestCase(test_v3.RestfulTestCase): ): self.put(url) action = f"{CREATED_OPERATION}.{self.ROLE_ASSIGNMENT}" - event_type = '{}.{}.{}'.format( - notifications.SERVICE, - self.ROLE_ASSIGNMENT, - CREATED_OPERATION, - ) + event_type = f'{notifications.SERVICE}.{self.ROLE_ASSIGNMENT}.{CREATED_OPERATION}' self._assert_last_note(action, self.user_id, event_type) self._assert_event(role, project, domain, user, group) self.delete(url) action = f"{DELETED_OPERATION}.{self.ROLE_ASSIGNMENT}" - event_type = '{}.{}.{}'.format( - notifications.SERVICE, - self.ROLE_ASSIGNMENT, - DELETED_OPERATION, - ) + event_type = f'{notifications.SERVICE}.{self.ROLE_ASSIGNMENT}.{DELETED_OPERATION}' self._assert_last_note(action, self.user_id, event_type) self._assert_event(role, project, domain, user, None) def test_user_project_grant(self): - url = '/projects/{}/users/{}/roles/{}'.format( - self.project_id, - self.user_id, - self.role_id, - ) + url = f'/projects/{self.project_id}/users/{self.user_id}/roles/{self.role_id}' self._test_role_assignment( url, self.role_id, project=self.project_id, user=self.user_id ) @@ -1596,9 +1573,7 @@ class CadfNotificationsWrapperTestCase(test_v3.RestfulTestCase): group = PROVIDERS.identity_api.create_group(group_ref) PROVIDERS.identity_api.add_user_to_group(self.user_id, group['id']) url = '/domains/{}/groups/{}/roles/{}'.format( - self.domain_id, - group['id'], - self.role_id, + self.domain_id, group['id'], self.role_id ) self._test_role_assignment( url, self.role_id, domain=self.domain_id, group=group['id'] @@ -1677,7 +1652,7 @@ class TestCallbackRegistration(unit.BaseTestCase): callback = 'keystone.tests.unit.common.test_notifications.callback' expected_log_data = { 'callback': callback, - 'event': 'identity.%s.created' % resource_type, + 'event': f'identity.{resource_type}.created', } self.verify_log_message([expected_log_data]) @@ -1740,7 +1715,6 @@ class TestCallbackRegistration(unit.BaseTestCase): class CADFNotificationsDataTestCase(test_v3.RestfulTestCase): - def config_overrides(self): super().config_overrides() # NOTE(lbragstad): This is a workaround since oslo.messaging version @@ -1780,7 +1754,6 @@ class CADFNotificationsDataTestCase(test_v3.RestfulTestCase): with mock.patch.object( notifications._get_notifier(), 'info' ) as mocked: - notifications._send_audit_notification( action, initiator, outcome, target, event_type ) diff --git a/keystone/tests/unit/common/test_provider_api.py b/keystone/tests/unit/common/test_provider_api.py index e1e4623c5a..11b463f964 100644 --- a/keystone/tests/unit/common/test_provider_api.py +++ b/keystone/tests/unit/common/test_provider_api.py @@ -26,7 +26,7 @@ class TestProviderAPIRegistry(unit.BaseTestCase): self.addCleanup(provider_api.ProviderAPIs._clear_registry_instances) def _create_manager_instance(self, provides_api=None): - provides_api = provides_api or '%s_api' % uuid.uuid4().hex + provides_api = provides_api or f'{uuid.uuid4().hex}_api' class TestManager(manager.Manager): _provides_api = provides_api @@ -38,7 +38,7 @@ class TestProviderAPIRegistry(unit.BaseTestCase): return TestManager(driver_name=None) def test_deferred_gettr(self): - api_name = '%s_api' % uuid.uuid4().hex + api_name = f'{uuid.uuid4().hex}_api' class TestClass: descriptor = provider_api.ProviderAPIs.deferred_provider_lookup( diff --git a/keystone/tests/unit/common/test_rbac_enforcer.py b/keystone/tests/unit/common/test_rbac_enforcer.py index 5700308314..2424a0fece 100644 --- a/keystone/tests/unit/common/test_rbac_enforcer.py +++ b/keystone/tests/unit/common/test_rbac_enforcer.py @@ -31,7 +31,6 @@ PROVIDER_APIS = provider_api.ProviderAPIs class TestRBACEnforcer(unit.TestCase): - def test_enforcer_shared_state(self): enforcer = rbac_enforcer.enforcer.RBACEnforcer() enforcer2 = rbac_enforcer.enforcer.RBACEnforcer() @@ -51,7 +50,6 @@ class TestRBACEnforcer(unit.TestCase): class _TestRBACEnforcerBase(rest.RestfulTestCase): - def setUp(self): super().setUp() self._setup_enforcer_object() @@ -93,7 +91,7 @@ class _TestRBACEnforcerBase(rest.RestfulTestCase): def _setup_dynamic_flask_blueprint_api(self): # Create a dynamic flask blueprint with a known prefix api = uuid.uuid4().hex - url_prefix = '/_%s_TEST' % api + url_prefix = f'/_{api}_TEST' blueprint = blueprints.Blueprint(api, __name__, url_prefix=url_prefix) self.url_prefix = url_prefix self.flask_blueprint = blueprint @@ -104,7 +102,7 @@ class _TestRBACEnforcerBase(rest.RestfulTestCase): return {'id': argument_id, 'value': 'TEST', 'owner_id': user['id']} def _setup_flask_restful_api(self): - self.restful_api_url_prefix = '/_%s_TEST' % uuid.uuid4().hex + self.restful_api_url_prefix = f'/_{uuid.uuid4().hex}_TEST' self.restful_api = flask_restful.Api( self.public_app.app, self.restful_api_url_prefix ) @@ -113,7 +111,6 @@ class _TestRBACEnforcerBase(rest.RestfulTestCase): # Very Basic Restful Resource class RestfulResource(flask_restful.Resource): - def get(self, argument_id=None): if argument_id is not None: return self._get_argument(argument_id) @@ -181,9 +178,7 @@ class _TestRBACEnforcerBase(rest.RestfulTestCase): scope_types=['project'], ), policy.RuleDefault( - name='example:allowed', - check_str='', - scope_types=['project'], + name='example:allowed', check_str='', scope_types=['project'] ), policy.RuleDefault( name='example:denied', @@ -195,7 +190,6 @@ class _TestRBACEnforcerBase(rest.RestfulTestCase): class TestRBACEnforcerRestAdminAuthToken(_TestRBACEnforcerBase): - def config_overrides(self): super().config_overrides() self.config_fixture.config(admin_token='ADMIN') @@ -204,8 +198,7 @@ class TestRBACEnforcerRestAdminAuthToken(_TestRBACEnforcerBase): # Admin-shared token passed and valid, "is_admin" should be true. with self.test_client() as c: c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={authorization.AUTH_TOKEN_HEADER: 'ADMIN'}, ) self.assertTrue(self.enforcer._shared_admin_auth_token_set()) @@ -214,24 +207,19 @@ class TestRBACEnforcerRestAdminAuthToken(_TestRBACEnforcerBase): with self.test_client() as c: # Admin-shared token passed and invalid, "is_admin" should be false c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={authorization.AUTH_TOKEN_HEADER: 'BOGUS'}, ) self.assertFalse(self.enforcer._shared_admin_auth_token_set()) # Admin-shared token not passed, "is_admin" should be false - c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex) - ) + c.get(f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}') self.assertFalse(self.enforcer._shared_admin_auth_token_set()) def test_enforce_call_is_admin(self): with self.test_client() as c: c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={authorization.AUTH_TOKEN_HEADER: 'ADMIN'}, ) with mock.patch.object(self.enforcer, '_enforce') as mock_method: @@ -240,7 +228,6 @@ class TestRBACEnforcerRestAdminAuthToken(_TestRBACEnforcerBase): class TestRBACEnforcerRest(_TestRBACEnforcerBase): - def test_extract_subject_token_target_data(self): path = '/v3/auth/tokens' body = self._auth_json() @@ -283,7 +270,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): path = uuid.uuid4().hex - @self.flask_blueprint.route('/%s' % path) + @self.flask_blueprint.route(f'/{path}') def return_nothing_interesting(): return 'OK', 200 @@ -296,10 +283,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): # Populate the query-string with two params, one that should # exist and one that should not in the resulting policy # dict. - qs = '{expected}=EXPECTED&{unexpected}=UNEXPECTED'.format( - expected=expected_param, - unexpected=unexpected_param, - ) + qs = f'{expected_param}=EXPECTED&{unexpected_param}=UNEXPECTED' # Perform the get with the query-string c.get(f'{get_path}?{qs}') # Extract the filter values. @@ -318,10 +302,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): # from the environ as expected. The only way to really test is an # instance check. with self.test_client() as c: - c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex) - ) + c.get(f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}') oslo_req_context = self.enforcer._get_oslo_req_context() self.assertIsInstance(oslo_req_context, context.RequestContext) @@ -333,8 +314,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): r = c.post(token_path, json=auth_json, expected_status_code=201) token_id = r.headers.get('X-Subject-Token') c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={'X-Auth-Token': token_id}, ) self.enforcer._assert_is_authenticated() @@ -358,8 +338,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): r = c.post(token_path, json=auth_json, expected_status_code=201) token_id = r.headers.get('X-Subject-Token') c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={'X-Auth-Token': token_id}, ) extracted_creds = self.enforcer._extract_policy_check_credentials() @@ -384,11 +363,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): argument_id = uuid.uuid4().hex with self.test_client() as c: - c.get( - '{}/argument/{}'.format( - self.restful_api_url_prefix, argument_id - ) - ) + c.get(f'{self.restful_api_url_prefix}/argument/{argument_id}') extracted = self.enforcer._extract_member_target_data( member_target_type=None, member_target=None ) @@ -431,16 +406,14 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): token_id = r.headers['X-Subject-Token'] c.get( - '{}/argument/{}'.format( - self.restful_api_url_prefix, argument_id - ), + f'{self.restful_api_url_prefix}/argument/{argument_id}', headers={'X-Auth-Token': token_id}, ) # Use any valid policy as _enforce is mockpatched out self.enforcer.enforce_call(action='example:allowed') c.get( - '%s/argument' % self.restful_api_url_prefix, + f'{self.restful_api_url_prefix}/argument', headers={'X-Auth-Token': token_id}, ) self.assertRaises( @@ -511,9 +484,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): token_id = r.headers['X-Subject-Token'] c.get( - '{}/argument/{}'.format( - self.restful_api_url_prefix, argument_id - ), + f'{self.restful_api_url_prefix}/argument/{argument_id}', headers={'X-Auth-Token': token_id}, ) self.enforcer.enforce_call( @@ -533,7 +504,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): self._register_blueprint_to_app() with self.test_client() as c: - c.get('%s' % self.url_prefix) + c.get(f'{self.url_prefix}') self.assertEqual( action, getattr(flask.g, self.enforcer.ACTION_STORE_ATTR) ) @@ -562,10 +533,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): def test_enforce_call_not_is_authenticated(self): with self.test_client() as c: - c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex) - ) + c.get(f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}') # Patch the enforcer to return an empty oslo context. with mock.patch.object( self.enforcer, '_get_oslo_req_context', return_value=None @@ -597,8 +565,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): # TODO(morgan): confirm if subject-token-processing can/should # occur in this form without causing issues. c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={ 'X-Auth-Token': token_id, 'X-Subject-Token': token_id, @@ -626,8 +593,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): # user_id are the same. example:deprecated should also pass # since it is open enforcement. c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={ 'X-Auth-Token': token_id, 'X-Subject-Token': token_id, @@ -645,8 +611,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): # and member_target. This form still extracts data from the subject # token. c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={ 'X-Auth-Token': token_id, 'X-Subject-Token': token_id, @@ -678,8 +643,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): # check the enforcer properly handles inferred member data get # This form still extracts data from the subject token. c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={ 'X-Auth-Token': token_id, 'X-Subject-Token': token_id, @@ -698,8 +662,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): # Check that the enforcer passes if a filter is supplied *and* # the filter name is passed to enforce_call c.get( - '%s/argument/%s?user=%s' - % ( + '{}/argument/{}?user={}'.format( self.restful_api_url_prefix, uuid.uuid4().hex, self.user_req_admin['id'], @@ -719,8 +682,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): # With No Filters in the PATH c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={'X-Auth-Token': token_id}, ) self.assertRaises( @@ -732,8 +694,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): # With no filters in the path and no filters passed to enforce_call c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={'X-Auth-Token': token_id}, ) self.assertRaises( @@ -752,8 +713,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): # Check the enforcer behaves as expected with a pre-instantiated # enforcer passed into .enforce_call() c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={'X-Auth-Token': token_id}, ) self.enforcer.enforce_call( @@ -777,8 +737,7 @@ class TestRBACEnforcerRest(_TestRBACEnforcerBase): r = c.post(token_path, json=auth_json, expected_status_code=201) token_id = r.headers.get('X-Subject-Token') c.get( - '%s/argument/%s' - % (self.restful_api_url_prefix, uuid.uuid4().hex), + f'{self.restful_api_url_prefix}/argument/{uuid.uuid4().hex}', headers={'X-Auth-Token': token_id}, ) diff --git a/keystone/tests/unit/common/test_sql_core.py b/keystone/tests/unit/common/test_sql_core.py index 80b7d37059..92ae092cc6 100644 --- a/keystone/tests/unit/common/test_sql_core.py +++ b/keystone/tests/unit/common/test_sql_core.py @@ -27,7 +27,6 @@ class TestModel(ModelBase, sql.ModelDictMixin): # type: ignore class TestModelDictMixin(unit.BaseTestCase): - def test_creating_a_model_instance_from_a_dict(self): d = {'id': utils.new_uuid(), 'text': utils.new_uuid()} m = TestModel.from_dict(d) diff --git a/keystone/tests/unit/common/test_utils.py b/keystone/tests/unit/common/test_utils.py index 50f7d04f84..adf395ca92 100644 --- a/keystone/tests/unit/common/test_utils.py +++ b/keystone/tests/unit/common/test_utils.py @@ -361,7 +361,6 @@ class UtilsTestCase(unit.BaseTestCase): class ServiceHelperTests(unit.BaseTestCase): - @application.fail_gracefully def _do_test(self): raise Exception("Test Exc") @@ -371,7 +370,6 @@ class ServiceHelperTests(unit.BaseTestCase): class FernetUtilsTestCase(unit.BaseTestCase): - def setUp(self): super().setUp() self.config_fixture = self.useFixture(config_fixture.Config(CONF)) diff --git a/keystone/tests/unit/contrib/federation/test_utils.py b/keystone/tests/unit/contrib/federation/test_utils.py index 90b32e1c3b..0b6e97e9d0 100644 --- a/keystone/tests/unit/contrib/federation/test_utils.py +++ b/keystone/tests/unit/contrib/federation/test_utils.py @@ -159,10 +159,7 @@ class MappingRuleEngineTests(unit.BaseTestCase): name = values.get('user', {}).get('name') self.assertEqual(user_name, name) - self.assertEqual( - [], - group_ids, - ) + self.assertEqual([], group_ids) def test_rule_engine_not_any_of_many_rules(self): """Should return group EMPLOYEE_GROUP_ID. @@ -630,7 +627,6 @@ class MappingRuleEngineTests(unit.BaseTestCase): ) def test_get_user_unique_id_and_display_name(self): - mapping = mapping_fixtures.MAPPING_USER_IDS assertion = mapping_fixtures.ADMIN_ASSERTION FAKE_MAPPING_ID = uuid.uuid4().hex @@ -915,7 +911,7 @@ class MappingRuleEngineTests(unit.BaseTestCase): {"name": "Production", "roles": [{"name": "observer"}]}, {"name": "Staging", "roles": [{"name": "member"}]}, { - "name": "Project for %s" % expected_username, + "name": f"Project for {expected_username}", "roles": [{"name": "admin"}], }, ] @@ -944,10 +940,7 @@ class MappingRuleEngineTests(unit.BaseTestCase): self.assertEqual(user_name, name) self.assertEqual(user_groups, group_list) - self.assertEqual( - [], - group_ids, - ) + self.assertEqual([], group_ids) class TestUnicodeAssertionData(unit.BaseTestCase): @@ -1009,9 +1002,7 @@ class TestMappingLocals(unit.BaseTestCase): 'rules': [ { 'local': [ - { - 'user': {'name': '{0}'}, - }, + {'user': {'name': '{0}'}}, {'group': {'id': 'd34db33f'}}, ], 'remote': [{'type': 'idp_username'}], diff --git a/keystone/tests/unit/core.py b/keystone/tests/unit/core.py index 62be0a228a..2f8380e3fa 100644 --- a/keystone/tests/unit/core.py +++ b/keystone/tests/unit/core.py @@ -133,8 +133,7 @@ def skip_if_cache_disabled(*sections): In the code fragment:: @skip_if_cache_is_disabled('assignment', 'token') - def test_method(*args): - ... + def test_method(*args): ... The method test_method would be skipped if caching is disabled globally via the `enabled` option in the `cache` section of the configuration or if @@ -157,7 +156,7 @@ def skip_if_cache_disabled(*sections): conf_sec = getattr(CONF, s, None) if conf_sec is not None: if not getattr(conf_sec, 'caching', True): - raise unittest.SkipTest('%s caching disabled.' % s) + raise unittest.SkipTest(f'{s} caching disabled.') return f(*args, **kwargs) return inner @@ -174,7 +173,7 @@ def skip_if_cache_is_enabled(*sections): conf_sec = getattr(CONF, s, None) if conf_sec is not None: if getattr(conf_sec, 'caching', True): - raise unittest.SkipTest('%s caching enabled.' % s) + raise unittest.SkipTest(f'{s} caching enabled.') return f(*args, **kwargs) return inner @@ -228,7 +227,6 @@ NEEDS_REGION_ID = object() def new_endpoint_ref( service_id, interface='public', region_id=NEEDS_REGION_ID, **kwargs ): - ref = { 'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, @@ -349,11 +347,7 @@ def new_protocol_ref(protocol_id=None, idp_id=None, mapping_id=None, **kwargs): def new_identity_provider_ref(idp_id=None, **kwargs): - ref = { - 'id': idp_id or 'ORG_IDP', - 'enabled': True, - 'description': '', - } + ref = {'id': idp_id or 'ORG_IDP', 'enabled': True, 'description': ''} ref.update(kwargs) return ref @@ -382,11 +376,7 @@ def new_group_ref(domain_id, **kwargs): def new_credential_ref(user_id, project_id=None, type='cert', **kwargs): - ref = { - 'id': uuid.uuid4().hex, - 'user_id': user_id, - 'type': type, - } + ref = {'id': uuid.uuid4().hex, 'user_id': user_id, 'type': type} if project_id: ref['project_id'] = project_id @@ -486,13 +476,12 @@ def update_dn(dn1, dn2): dn1_attrs = {attr.oid: attr for attr in dn1} dn2_attrs = {attr.oid: attr for attr in dn2} dn1_attrs.update(dn2_attrs) - return x509.Name([attr for attr in dn1_attrs.values()]) + return x509.Name(list(dn1_attrs.values())) def create_certificate(subject_dn, ca=None, ca_key=None): private_key = rsa.generate_private_key( - public_exponent=65537, - key_size=2048, + public_exponent=65537, key_size=2048 ) issuer = ca.subject if ca else subject_dn if not ca_key: @@ -561,11 +550,7 @@ def new_policy_ref(**kwargs): 'description': uuid.uuid4().hex, 'enabled': True, # Store serialized JSON data as the blob to mimic real world usage. - 'blob': json.dumps( - { - 'data': uuid.uuid4().hex, - } - ), + 'blob': json.dumps({'data': uuid.uuid4().hex}), 'type': uuid.uuid4().hex, } @@ -708,17 +693,12 @@ def _assert_expected_status(f): # an un-routed HTTP call was made. This allows us to avoid # misinterpreting HTTP 404 from Flask and HTTP 404 from a # resource that is not found (e.g. USER NOT FOUND) programmatically - raise AssertionError("I AM A TEAPOT(418): %s" % response.data) + raise AssertionError(f"I AM A TEAPOT(418): {response.data}") if response.status_code != expected_status_code: raise AssertionError( 'Expected HTTP Status does not match observed HTTP ' - 'Status: %(expected)s != %(observed)s (%(data)s)' - % { - 'expected': expected_status_code, - 'observed': response.status_code, - 'data': response.data, - } + f'Status: {expected_status_code} != {response.status_code} ({response.data})' ) # return the original response object @@ -828,13 +808,13 @@ class BaseTestCase(testtools.TestCase): def skip_if_env_not_set(self, env_var): if not os.environ.get(env_var): - self.skipTest('Env variable %s is not set.' % env_var) + self.skipTest(f'Env variable {env_var} is not set.') def skip_test_overrides(self, *args, **kwargs): if self._check_for_method_in_parents(self._testMethodName): return super().skipTest(*args, **kwargs) raise Exception( - '%r is not a previously defined test method' % self._testMethodName + f'{self._testMethodName!r} is not a previously defined test method' ) def _check_for_method_in_parents(self, name): @@ -853,10 +833,9 @@ class BaseTestCase(testtools.TestCase): # is a hard error and should not pass testing. def page_not_found_teapot(e): content = ( - 'TEST PROGRAMMING ERROR - Reached a 404 from an unrouted (`%s`' + f'TEST PROGRAMMING ERROR - Reached a 404 from an unrouted (`{flask.request.url}`' ') path. Be sure the test is requesting the right resource ' 'and that all blueprints are registered with the flask app.' - % flask.request.url ) return content, 418 @@ -870,7 +849,6 @@ class BaseTestCase(testtools.TestCase): class TestCase(BaseTestCase): - def config_files(self): return [] @@ -1062,12 +1040,14 @@ class TestCase(BaseTestCase): pass for domain in fixtures.DOMAINS: rv = PROVIDERS.resource_api.create_domain(domain['id'], domain) - attrname = 'domain_%s' % domain['id'] + attrname = 'domain_{}'.format(domain['id']) setattr(self, attrname, rv) fixtures_to_cleanup.append(attrname) for project in fixtures.PROJECTS: - project_attr_name = 'project_%s' % project['name'].lower() + project_attr_name = 'project_{}'.format( + project['name'].lower() + ) rv = PROVIDERS.resource_api.create_project( project['id'], project ) @@ -1076,7 +1056,7 @@ class TestCase(BaseTestCase): for role in fixtures.ROLES: rv = PROVIDERS.role_api.create_role(role['id'], role) - attrname = 'role_%s' % role['name'] + attrname = 'role_{}'.format(role['name']) setattr(self, attrname, rv) fixtures_to_cleanup.append(attrname) @@ -1100,7 +1080,7 @@ class TestCase(BaseTestCase): # Use the ID from the fixture as the attribute name, so # that our tests can easily reference each user dict, while # the ID in the dict will be the real public ID. - attrname = 'user_%s' % user['name'] + attrname = 'user_{}'.format(user['name']) setattr(self, attrname, user_copy) fixtures_to_cleanup.append(attrname) @@ -1108,7 +1088,7 @@ class TestCase(BaseTestCase): role_id = role_assignment['role_id'] user = role_assignment['user'] project_id = role_assignment['project_id'] - user_id = getattr(self, 'user_%s' % user)['id'] + user_id = getattr(self, f'user_{user}')['id'] PROVIDERS.assignment_api.add_role_to_user_and_project( user_id, project_id, role_id ) diff --git a/keystone/tests/unit/credential/test_backend_sql.py b/keystone/tests/unit/credential/test_backend_sql.py index e293e3dc57..378fbdb05c 100644 --- a/keystone/tests/unit/credential/test_backend_sql.py +++ b/keystone/tests/unit/credential/test_backend_sql.py @@ -27,7 +27,6 @@ PROVIDERS = provider_api.ProviderAPIs class SqlTests(unit.SQLDriverOverrides, unit.TestCase): - def setUp(self): super().setUp() self.useFixture(database.Database()) @@ -44,7 +43,6 @@ class SqlTests(unit.SQLDriverOverrides, unit.TestCase): class SqlCredential(SqlTests): - def _create_credential_with_user_id(self, user_id=None): if not user_id: user_id = uuid.uuid4().hex diff --git a/keystone/tests/unit/default_fixtures.py b/keystone/tests/unit/default_fixtures.py index e4ceb9d22d..571bcb48ab 100644 --- a/keystone/tests/unit/default_fixtures.py +++ b/keystone/tests/unit/default_fixtures.py @@ -129,41 +129,17 @@ USERS = [ ] ROLES = [ - { - 'id': ADMIN_ROLE_ID, - 'name': 'admin', - 'domain_id': None, - }, - { - 'id': MEMBER_ROLE_ID, - 'name': 'member', - 'domain_id': None, - }, + {'id': ADMIN_ROLE_ID, 'name': 'admin', 'domain_id': None}, + {'id': MEMBER_ROLE_ID, 'name': 'member', 'domain_id': None}, { 'id': '9fe2ff9ee4384b1894a90878d3e92bab', 'name': '_member_', 'domain_id': None, }, - { - 'id': OTHER_ROLE_ID, - 'name': 'other', - 'domain_id': None, - }, - { - 'id': uuid.uuid4().hex, - 'name': 'browser', - 'domain_id': None, - }, - { - 'id': uuid.uuid4().hex, - 'name': 'writer', - 'domain_id': None, - }, - { - 'id': uuid.uuid4().hex, - 'name': 'service', - 'domain_id': None, - }, + {'id': OTHER_ROLE_ID, 'name': 'other', 'domain_id': None}, + {'id': uuid.uuid4().hex, 'name': 'browser', 'domain_id': None}, + {'id': uuid.uuid4().hex, 'name': 'writer', 'domain_id': None}, + {'id': uuid.uuid4().hex, 'name': 'service', 'domain_id': None}, ] # NOTE(morganfainberg): Admin assignment for replacing admin_token_auth @@ -172,7 +148,7 @@ ROLE_ASSIGNMENTS = [ 'user': 'req_admin', 'project_id': SERVICE_PROJECT_ID, 'role_id': ADMIN_ROLE_ID, - }, + } ] # TODO(wxy): We should add the root domain ``<>`` as well diff --git a/keystone/tests/unit/endpoint_policy/backends/test_base.py b/keystone/tests/unit/endpoint_policy/backends/test_base.py index b3e5316cde..da555272e6 100644 --- a/keystone/tests/unit/endpoint_policy/backends/test_base.py +++ b/keystone/tests/unit/endpoint_policy/backends/test_base.py @@ -60,7 +60,7 @@ class DriverTestCase: self.assertRaises( exception.PolicyAssociationNotFound, self.driver.check_policy_association, - **original_association + **original_association, ) def test_check_policy_association(self): @@ -76,7 +76,7 @@ class DriverTestCase: self.assertRaises( exception.PolicyAssociationNotFound, self.driver.check_policy_association, - **association + **association, ) def test_delete_policy_association(self): @@ -86,7 +86,7 @@ class DriverTestCase: self.assertRaises( exception.PolicyAssociationNotFound, self.driver.check_policy_association, - **association + **association, ) def test_get_policy_association(self): @@ -123,7 +123,7 @@ class DriverTestCase: self.assertRaises( exception.PolicyAssociationNotFound, self.driver.check_policy_association, - **association + **association, ) def test_delete_association_by_service(self): @@ -139,7 +139,7 @@ class DriverTestCase: self.assertRaises( exception.PolicyAssociationNotFound, self.driver.check_policy_association, - **association + **association, ) def test_delete_association_by_region(self): @@ -157,7 +157,7 @@ class DriverTestCase: self.assertRaises( exception.PolicyAssociationNotFound, self.driver.check_policy_association, - **association + **association, ) def test_delete_association_by_policy(self): @@ -175,5 +175,5 @@ class DriverTestCase: self.assertRaises( exception.PolicyAssociationNotFound, self.driver.check_policy_association, - **association + **association, ) diff --git a/keystone/tests/unit/endpoint_policy/backends/test_sql.py b/keystone/tests/unit/endpoint_policy/backends/test_sql.py index 5dc5e0e8c1..049716aa45 100644 --- a/keystone/tests/unit/endpoint_policy/backends/test_sql.py +++ b/keystone/tests/unit/endpoint_policy/backends/test_sql.py @@ -34,7 +34,6 @@ class SQLModelTestCase(core_sql.BaseBackendSqlModels): class SQLDriverTestCase(test_base.DriverTestCase, unit.TestCase): - def setUp(self): super().setUp() self.useFixture(database.Database()) diff --git a/keystone/tests/unit/external/test_timeutils.py b/keystone/tests/unit/external/test_timeutils.py index fca5ca5b87..fa5c48b686 100644 --- a/keystone/tests/unit/external/test_timeutils.py +++ b/keystone/tests/unit/external/test_timeutils.py @@ -16,7 +16,6 @@ import keystone.tests.unit as tests class TestTimeUtils(tests.BaseTestCase): - def test_parsing_date_strings_returns_a_datetime(self): example_date_str = '2015-09-23T04:45:37.196621Z' dt = datetime.datetime.strptime(example_date_str, tests.TIME_FORMAT) diff --git a/keystone/tests/unit/fakeldap.py b/keystone/tests/unit/fakeldap.py index fcc86e46ed..3dc42f9ac2 100644 --- a/keystone/tests/unit/fakeldap.py +++ b/keystone/tests/unit/fakeldap.py @@ -171,9 +171,7 @@ def _match(key, value, attrs): return str(value) in str_sids if key != 'objectclass': check_value = _internal_attr(key, value)[0].lower() - norm_values = list( - _internal_attr(key, x)[0].lower() for x in attrs[key] - ) + norm_values = [_internal_attr(key, x)[0].lower() for x in attrs[key]] return match_with_wildcards(check_value, norm_values) # It is an objectclass check, so check subclasses values = _subs(value) @@ -207,7 +205,6 @@ server_fail = False class FakeShelve(dict): - def sync(self): pass @@ -357,9 +354,7 @@ class FakeLdap(common.LDAPHandler): # The LDAP API raises a TypeError if attr name is None. for k, dummy_v in modlist: if k is None: - raise TypeError( - 'must be string, not None. modlist=%s' % modlist - ) + raise TypeError(f'must be string, not None. modlist={modlist}') if k == id_attr: for val in dummy_v: @@ -465,7 +460,7 @@ class FakeLdap(common.LDAPHandler): else: LOG.debug('modify item failed: unknown command %s', cmd) raise NotImplementedError( - 'modify_s action %s not implemented' % cmd + f'modify_s action {cmd} not implemented' ) self.db[key] = entry self.db.sync() @@ -520,10 +515,7 @@ class FakeLdap(common.LDAPHandler): (k[len(self.__prefix) :], v) for k, v in self.db.items() if re.match( - '{}.*,{}'.format( - re.escape(self.__prefix), re.escape(base) - ), - k, + f'{re.escape(self.__prefix)}.*,{re.escape(base)}', k ) ] results.extend(extraresults) diff --git a/keystone/tests/unit/federation/test_core.py b/keystone/tests/unit/federation/test_core.py index 8c2b397644..eabeeeca52 100644 --- a/keystone/tests/unit/federation/test_core.py +++ b/keystone/tests/unit/federation/test_core.py @@ -23,7 +23,6 @@ PROVIDERS = provider_api.ProviderAPIs class TestFederationProtocol(unit.TestCase): - def setUp(self): super().setUp() self.useFixture(database.Database()) diff --git a/keystone/tests/unit/federation/test_utils.py b/keystone/tests/unit/federation/test_utils.py index d0ceab42d9..eae2f71f9b 100644 --- a/keystone/tests/unit/federation/test_utils.py +++ b/keystone/tests/unit/federation/test_utils.py @@ -18,7 +18,6 @@ from keystone.tests import unit class TestFederationUtils(unit.TestCase): - def setUp(self): super().setUp() self.mapping_id_mock = uuid.uuid4().hex diff --git a/keystone/tests/unit/filtering.py b/keystone/tests/unit/filtering.py index e70dbdd7ee..8dd42f455f 100644 --- a/keystone/tests/unit/filtering.py +++ b/keystone/tests/unit/filtering.py @@ -23,7 +23,6 @@ CONF = keystone.conf.CONF class FilterTests: - # Provide support for checking if a batch of list items all # exist within a contiguous range in a total list def _match_with_list( @@ -55,13 +54,11 @@ class FilterTests: one. """ - f = getattr(PROVIDERS.identity_api, 'create_%s' % entity_type, None) + f = getattr(PROVIDERS.identity_api, f'create_{entity_type}', None) if f is None: - f = getattr( - PROVIDERS.resource_api, 'create_%s' % entity_type, None - ) + f = getattr(PROVIDERS.resource_api, f'create_{entity_type}', None) if f is None: - f = getattr(PROVIDERS.assignment_api, 'create_%s' % entity_type) + f = getattr(PROVIDERS.assignment_api, f'create_{entity_type}') return f def _delete_entity(self, entity_type): @@ -72,13 +69,11 @@ class FilterTests: one. """ - f = getattr(PROVIDERS.identity_api, 'delete_%s' % entity_type, None) + f = getattr(PROVIDERS.identity_api, f'delete_{entity_type}', None) if f is None: - f = getattr( - PROVIDERS.resource_api, 'delete_%s' % entity_type, None - ) + f = getattr(PROVIDERS.resource_api, f'delete_{entity_type}', None) if f is None: - f = getattr(PROVIDERS.assignment_api, 'delete_%s' % entity_type) + f = getattr(PROVIDERS.assignment_api, f'delete_{entity_type}') return f def _list_entities(self, entity_type): @@ -89,11 +84,11 @@ class FilterTests: one. """ - f = getattr(PROVIDERS.identity_api, 'list_%ss' % entity_type, None) + f = getattr(PROVIDERS.identity_api, f'list_{entity_type}s', None) if f is None: - f = getattr(PROVIDERS.resource_api, 'list_%ss' % entity_type, None) + f = getattr(PROVIDERS.resource_api, f'list_{entity_type}s', None) if f is None: - f = getattr(PROVIDERS.assignment_api, 'list_%ss' % entity_type) + f = getattr(PROVIDERS.assignment_api, f'list_{entity_type}s') return f def _create_one_entity(self, entity_type, domain_id, name): diff --git a/keystone/tests/unit/identity/backends/test_base.py b/keystone/tests/unit/identity/backends/test_base.py index 59044e525b..c259296375 100644 --- a/keystone/tests/unit/identity/backends/test_base.py +++ b/keystone/tests/unit/identity/backends/test_base.py @@ -49,11 +49,7 @@ class IdentityDriverTests: maybe it gets a user from a set of pre-created users. """ user_id = uuid.uuid4().hex - user = { - 'id': user_id, - 'name': uuid.uuid4().hex, - 'enabled': True, - } + user = {'id': user_id, 'name': uuid.uuid4().hex, 'enabled': True} if self.driver.is_domain_aware(): user['domain_id'] = domain_id or uuid.uuid4().hex user.update(kwargs) @@ -66,10 +62,7 @@ class IdentityDriverTests: provide their own way to provide a group for the test. """ group_id = uuid.uuid4().hex - group = { - 'id': group_id, - 'name': uuid.uuid4().hex, - } + group = {'id': group_id, 'name': uuid.uuid4().hex} if self.driver.is_domain_aware(): group['domain_id'] = domain_id or uuid.uuid4().hex return self.driver.create_group(group_id, group) @@ -117,11 +110,7 @@ class IdentityDriverTests: def test_create_user_same_id_exc(self): user_id = uuid.uuid4().hex - user = { - 'id': user_id, - 'name': uuid.uuid4().hex, - 'enabled': True, - } + user = {'id': user_id, 'name': uuid.uuid4().hex, 'enabled': True} if self.driver.is_domain_aware(): user['domain_id'] = uuid.uuid4().hex self.driver.create_user(user_id, user) @@ -133,21 +122,13 @@ class IdentityDriverTests: user1_id = uuid.uuid4().hex name = uuid.uuid4().hex domain_id = uuid.uuid4().hex - user = { - 'id': user1_id, - 'name': name, - 'enabled': True, - } + user = {'id': user1_id, 'name': name, 'enabled': True} if self.driver.is_domain_aware(): user['domain_id'] = domain_id self.driver.create_user(user1_id, user) user2_id = uuid.uuid4().hex - user = { - 'id': user2_id, - 'name': name, - 'enabled': True, - } + user = {'id': user2_id, 'name': name, 'enabled': True} if self.driver.is_domain_aware(): user['domain_id'] = domain_id self.assertRaises( @@ -275,10 +256,7 @@ class IdentityDriverTests: def test_create_group(self): group_id = uuid.uuid4().hex - group = { - 'id': group_id, - 'name': uuid.uuid4().hex, - } + group = {'id': group_id, 'name': uuid.uuid4().hex} if self.driver.is_domain_aware(): group['domain_id'] = uuid.uuid4().hex new_group = self.driver.create_group(group_id, group) @@ -300,19 +278,13 @@ class IdentityDriverTests: group1_id = uuid.uuid4().hex name = uuid.uuid4().hex domain = uuid.uuid4().hex - group1 = { - 'id': group1_id, - 'name': name, - } + group1 = {'id': group1_id, 'name': name} if self.driver.is_domain_aware(): group1['domain_id'] = domain self.driver.create_group(group1_id, group1) group2_id = uuid.uuid4().hex - group2 = { - 'id': group2_id, - 'name': name, - } + group2 = {'id': group2_id, 'name': name} if self.driver.is_domain_aware(): group2['domain_id'] = domain self.assertRaises( diff --git a/keystone/tests/unit/identity/backends/test_ldap.py b/keystone/tests/unit/identity/backends/test_ldap.py index fed139bafb..0fa61c1756 100644 --- a/keystone/tests/unit/identity/backends/test_ldap.py +++ b/keystone/tests/unit/identity/backends/test_ldap.py @@ -19,7 +19,6 @@ from keystone.tests.unit.ksfixtures import ldapdb class TestIdentityDriver(core.BaseTestCase, test_base.IdentityDriverTests): - allows_name_update = False allows_self_service_change_password = False expected_is_domain_aware = False diff --git a/keystone/tests/unit/identity/backends/test_ldap_common.py b/keystone/tests/unit/identity/backends/test_ldap_common.py index 9b43226320..a2906c4cb2 100644 --- a/keystone/tests/unit/identity/backends/test_ldap_common.py +++ b/keystone/tests/unit/identity/backends/test_ldap_common.py @@ -203,7 +203,6 @@ class DnCompareTest(unit.BaseTestCase): class LDAPDeleteTreeTest(unit.TestCase): - def setUp(self): super().setUp() @@ -473,9 +472,9 @@ class CommonLdapTestCase(unit.BaseTestCase): 'cn': ['junk'], 'sn': [uuid.uuid4().hex], 'mail': [uuid.uuid4().hex], - 'binary_attr': [b'\x00\xFF\x00\xFF'], + 'binary_attr': [b'\x00\xff\x00\xff'], }, - ), + ) ] py_result = common_ldap.convert_ldap_result(result) # The attribute containing the binary value should @@ -509,7 +508,7 @@ class CommonLdapTestCase(unit.BaseTestCase): ( 'cn=dummy,dc=example,dc=com', {'user_id': [user_id], 'enabled': ['TRUE']}, - ), + ) ] py_result = common_ldap.convert_ldap_result(result) # The user id should be 0123456, and the enabled @@ -525,7 +524,7 @@ class CommonLdapTestCase(unit.BaseTestCase): ( 'cn=dummy,dc=example,dc=com', {'user_id': [user_id], 'enabled': [bitmask]}, - ), + ) ] py_result = common_ldap.convert_ldap_result(result) # The user id should be 0123456, and the enabled @@ -541,7 +540,7 @@ class CommonLdapTestCase(unit.BaseTestCase): ( 'cn=dummy,dc=example,dc=com', {'user_id': [user_id], 'enabled': [bitmask]}, - ), + ) ] py_result = common_ldap.convert_ldap_result(result) # The user id should be 0123456, and the enabled @@ -566,7 +565,7 @@ class CommonLdapTestCase(unit.BaseTestCase): ( 'cn=dummy,dc=example,dc=com', {'user_id': [user_id], 'user_name': [user_name]}, - ), + ) ] py_result = common_ldap.convert_ldap_result(result) # The user name should still be a string value. @@ -628,10 +627,7 @@ class LDAPFilterQueryCompositionTest(unit.BaseTestCase): comparator='equals', case_sensitive=False, ) - expected_ldap_filter = '(&({}={}))'.format( - self.filter_attribute_name, - username, - ) + expected_ldap_filter = f'(&({self.filter_attribute_name}={username}))' self.assertEqual( expected_ldap_filter, self.base_ldap.filter_query(hints=hints) ) @@ -642,12 +638,8 @@ class LDAPFilterQueryCompositionTest(unit.BaseTestCase): # filter string is concatenated correctly query = uuid.uuid4().hex username = uuid.uuid4().hex - expected_result = '(&%(query)s(%(user_name_attr)s=%(username)s))' % ( - { - 'query': query, - 'user_name_attr': self.filter_attribute_name, - 'username': username, - } + expected_result = ( + f'(&{query}({self.filter_attribute_name}={username}))' ) hints.add_filter(self.attribute_name, username) self.assertEqual( @@ -664,10 +656,7 @@ class LDAPFilterQueryCompositionTest(unit.BaseTestCase): comparator='equals', case_sensitive=False, ) - expected_ldap_filter = '(&({}={}))'.format( - self.filter_attribute_name, - username, - ) + expected_ldap_filter = f'(&({self.filter_attribute_name}={username}))' self.assertEqual( expected_ldap_filter, self.base_ldap.filter_query(hints=hints, query=None), diff --git a/keystone/tests/unit/identity/backends/test_sql.py b/keystone/tests/unit/identity/backends/test_sql.py index 3f3b068c5f..e3bcb285a3 100644 --- a/keystone/tests/unit/identity/backends/test_sql.py +++ b/keystone/tests/unit/identity/backends/test_sql.py @@ -25,7 +25,6 @@ class TestIdentityDriver( test_base.BaseTestCase, id_test_base.IdentityDriverTests, ): - expected_is_domain_aware = True expected_default_assignment_driver = 'sql' expected_is_sql = True diff --git a/keystone/tests/unit/identity/test_backends.py b/keystone/tests/unit/identity/test_backends.py index cc68ccc4c1..24f7c43856 100644 --- a/keystone/tests/unit/identity/test_backends.py +++ b/keystone/tests/unit/identity/test_backends.py @@ -29,7 +29,6 @@ PROVIDERS = provider_api.ProviderAPIs class IdentityTests: - def _get_domain_fixture(self): domain = unit.new_domain_ref() PROVIDERS.resource_api.create_domain(domain['id'], domain) @@ -471,7 +470,7 @@ class IdentityTests: self.assertEqual(len(default_fixtures.USERS), len(users)) user_ids = {user['id'] for user in users} expected_user_ids = { - getattr(self, 'user_%s' % user['name'])['id'] + getattr(self, 'user_{}'.format(user['name']))['id'] for user in default_fixtures.USERS } for user_ref in users: @@ -1139,9 +1138,7 @@ class IdentityTests: # The test is designed for multiple domains only def create_domains(domain_count, domain_name_prefix): for _ in range(domain_count): - domain_name = '{}-{}'.format( - domain_name_prefix, uuid.uuid4().hex - ) + domain_name = f'{domain_name_prefix}-{uuid.uuid4().hex}' domain = unit.new_domain_ref(name=domain_name) self.domain_list[domain_name] = ( PROVIDERS.resource_api.create_domain(domain['id'], domain) diff --git a/keystone/tests/unit/identity/test_core.py b/keystone/tests/unit/identity/test_core.py index 29e97bf61a..e5af04df15 100644 --- a/keystone/tests/unit/identity/test_core.py +++ b/keystone/tests/unit/identity/test_core.py @@ -35,7 +35,6 @@ PROVIDERS = provider_api.ProviderAPIs class TestDomainConfigs(unit.BaseTestCase): - def setUp(self): super().setUp() self.addCleanup(CONF.reset) @@ -57,7 +56,7 @@ class TestDomainConfigs(unit.BaseTestCase): """ domain_id = uuid.uuid4().hex domain_config_filename = os.path.join( - self.tmp_dir, 'keystone.%s.conf' % domain_id + self.tmp_dir, f'keystone.{domain_id}.conf' ) self.addCleanup(lambda: os.remove(domain_config_filename)) with open(domain_config_filename, 'w'): @@ -147,7 +146,6 @@ class TestDomainConfigs(unit.BaseTestCase): class TestDatabaseDomainConfigs(unit.TestCase): - def setUp(self): super().setUp() self.useFixture(database.Database()) diff --git a/keystone/tests/unit/ksfixtures/__init__.py b/keystone/tests/unit/ksfixtures/__init__.py index f848233d0b..1b06aabfaf 100644 --- a/keystone/tests/unit/ksfixtures/__init__.py +++ b/keystone/tests/unit/ksfixtures/__init__.py @@ -11,12 +11,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from keystone.tests.unit.ksfixtures.auth_plugins import ( - ConfigAuthPlugins, -) # noqa -from keystone.tests.unit.ksfixtures.jws_key_repository import ( - JWSKeyRepository, -) # noqa +from keystone.tests.unit.ksfixtures.auth_plugins import ConfigAuthPlugins # noqa +from keystone.tests.unit.ksfixtures.jws_key_repository import JWSKeyRepository # noqa from keystone.tests.unit.ksfixtures.backendloader import BackendLoader # noqa from keystone.tests.unit.ksfixtures.cache import Cache # noqa diff --git a/keystone/tests/unit/ksfixtures/auth_plugins.py b/keystone/tests/unit/ksfixtures/auth_plugins.py index 301dd01522..49cef7fd42 100644 --- a/keystone/tests/unit/ksfixtures/auth_plugins.py +++ b/keystone/tests/unit/ksfixtures/auth_plugins.py @@ -36,7 +36,6 @@ class ConfigAuthPlugins(fixtures.Fixture): class LoadAuthPlugins(fixtures.Fixture): - def __init__(self, *method_names): super().__init__() self.method_names = method_names diff --git a/keystone/tests/unit/ksfixtures/database.py b/keystone/tests/unit/ksfixtures/database.py index 1476add7a5..d402fd5e76 100644 --- a/keystone/tests/unit/ksfixtures/database.py +++ b/keystone/tests/unit/ksfixtures/database.py @@ -89,7 +89,9 @@ def _load_sqlalchemy_models(): # The root will be prefixed with an instance of os.sep, which will # make the root after replacement '.', the 'keystone' part # of the module path is always added to the front - module_root = 'keystone.%s' % root.replace(os.sep, '.').lstrip('.') + module_root = 'keystone.{}'.format( + root.replace(os.sep, '.').lstrip('.') + ) module_components = module_root.split('.') module_without_backends = '' for x in range(0, len(module_components) - 1): diff --git a/keystone/tests/unit/ksfixtures/hacking.py b/keystone/tests/unit/ksfixtures/hacking.py index 0bf07372a0..33c9973f18 100644 --- a/keystone/tests/unit/ksfixtures/hacking.py +++ b/keystone/tests/unit/ksfixtures/hacking.py @@ -104,9 +104,7 @@ class HackingCode(fixtures.Fixture): # be continued with extra indentation # if that's what the developer wants. """, - 'expected_errors': [ - (3, 0, 'K002'), - ], + 'expected_errors': [(3, 0, 'K002')], } asserting_none_equality = { @@ -139,11 +137,7 @@ class HackingCode(fixtures.Fixture): dict([[i,i] for i in range(3)]) dict(({1:2})) """, - 'expected_errors': [ - (3, 0, 'K008'), - (4, 0, 'K008'), - (5, 0, 'K008'), - ], + 'expected_errors': [(3, 0, 'K008'), (4, 0, 'K008'), (5, 0, 'K008')], } @@ -175,10 +169,7 @@ class HackingTranslations(fixtures.Fixture): def __init__(self): LOG.warning(oslo_i18n('text', {})) """, - 'expected_errors': [ - (3, 9, 'K005'), - (6, 20, 'K005'), - ], + 'expected_errors': [(3, 9, 'K005'), (6, 20, 'K005')], }, { 'code': """ @@ -191,9 +182,7 @@ class HackingTranslations(fixtures.Fixture): _('text'), {} ) """, - 'expected_errors': [ - (7, 12, 'K005'), - ], + 'expected_errors': [(7, 12, 'K005')], }, { 'code': """ @@ -201,9 +190,7 @@ class HackingTranslations(fixtures.Fixture): L = log.getLogger(__name__) L.error(oslo_i18n('text')) """, - 'expected_errors': [ - (3, 8, 'K005'), - ], + 'expected_errors': [(3, 8, 'K005')], }, { 'code': """ @@ -213,9 +200,7 @@ class HackingTranslations(fixtures.Fixture): self.LOG = oslo_logging.getLogger() self.LOG.critical(_('text')) """, - 'expected_errors': [ - (5, 26, 'K005'), - ], + 'expected_errors': [(5, 26, 'K005')], }, { 'code': """ @@ -224,9 +209,7 @@ class HackingTranslations(fixtures.Fixture): msg = _('text') LOG.exception(msg) """, - 'expected_errors': [ - (4, 14, 'K005'), - ], + 'expected_errors': [(4, 14, 'K005')], }, { 'code': """ @@ -236,9 +219,7 @@ class HackingTranslations(fixtures.Fixture): L.warning(msg) raise Exception(msg) """, - 'expected_errors': [ - (4, 10, 'K005'), - ], + 'expected_errors': [(4, 10, 'K005')], }, { 'code': """ @@ -249,9 +230,7 @@ class HackingTranslations(fixtures.Fixture): something = True # add an extra statement here raise Exception(msg) """, - 'expected_errors': [ - (4, 14, 'K005'), - ], + 'expected_errors': [(4, 14, 'K005')], }, { 'code': """ @@ -261,9 +240,7 @@ class HackingTranslations(fixtures.Fixture): LOG.warning(msg) raise Exception('some other message') """, - 'expected_errors': [ - (4, 16, 'K005'), - ], + 'expected_errors': [(4, 16, 'K005')], }, { 'code': """ @@ -275,9 +252,7 @@ class HackingTranslations(fixtures.Fixture): LOG.warning(msg) raise Exception(msg) """, - 'expected_errors': [ - (6, 12, 'K005'), - ], + 'expected_errors': [(6, 12, 'K005')], }, { 'code': """ @@ -288,9 +263,7 @@ class HackingTranslations(fixtures.Fixture): msg = _('text') LOG.warning(msg) """, - 'expected_errors': [ - (6, 12, 'K005'), - ], + 'expected_errors': [(6, 12, 'K005')], }, { 'code': """ @@ -308,9 +281,7 @@ class HackingTranslations(fixtures.Fixture): msg = _('hello %s') % 'world' LOG.warning(msg) """, - 'expected_errors': [ - (3, 12, 'K005'), - ], + 'expected_errors': [(3, 12, 'K005')], }, { 'code': """ @@ -335,8 +306,6 @@ class HackingTranslations(fixtures.Fixture): LOG.warning(msg) raise exception.Unauthorized(message=msg) """, - 'expected_errors': [ - (7, 16, 'K005'), - ], + 'expected_errors': [(7, 16, 'K005')], }, ] diff --git a/keystone/tests/unit/ksfixtures/warnings.py b/keystone/tests/unit/ksfixtures/warnings.py index f02580b7bf..2cae34b843 100644 --- a/keystone/tests/unit/ksfixtures/warnings.py +++ b/keystone/tests/unit/ksfixtures/warnings.py @@ -30,9 +30,7 @@ class WarningsFixture(fixtures.Fixture): warnings.simplefilter('once', DeprecationWarning) warnings.filterwarnings( - 'error', - module='keystone', - category=DeprecationWarning, + 'error', module='keystone', category=DeprecationWarning ) warnings.filterwarnings( @@ -60,23 +58,18 @@ class WarningsFixture(fixtures.Fixture): ) warnings.filterwarnings( - 'error', - module='keystone', - category=sqla_exc.SAWarning, + 'error', module='keystone', category=sqla_exc.SAWarning ) warnings.filterwarnings( - 'ignore', - category=sqla_exc.SADeprecationWarning, + 'ignore', category=sqla_exc.SADeprecationWarning ) # Enable deprecation warnings for keystone itself to capture upcoming # SQLALchemy changes warnings.filterwarnings( - 'error', - module='keystone', - category=sqla_exc.SADeprecationWarning, + 'error', module='keystone', category=sqla_exc.SADeprecationWarning ) self.addCleanup(self._reset_warning_filters) diff --git a/keystone/tests/unit/limit/test_backends.py b/keystone/tests/unit/limit/test_backends.py index 4dcc780bab..1ff20364a8 100644 --- a/keystone/tests/unit/limit/test_backends.py +++ b/keystone/tests/unit/limit/test_backends.py @@ -21,7 +21,6 @@ PROVIDERS = provider_api.ProviderAPIs class RegisteredLimitTests: - def test_create_registered_limit_crud(self): # create one, return it. registered_limit_1 = unit.new_registered_limit_ref( @@ -563,7 +562,6 @@ class RegisteredLimitTests: class LimitTests: - def test_default_enforcement_model_is_flat(self): expected = { 'description': ( diff --git a/keystone/tests/unit/mapping_fixtures.py b/keystone/tests/unit/mapping_fixtures.py index 70132e36cd..47e3f4e962 100644 --- a/keystone/tests/unit/mapping_fixtures.py +++ b/keystone/tests/unit/mapping_fixtures.py @@ -12,7 +12,6 @@ """Fixtures for Federation Mapping.""" - EMPLOYEE_GROUP_ID = "0cd5e9" CONTRACTOR_GROUP_ID = "85a868" TESTER_GROUP_ID = "123" @@ -205,9 +204,7 @@ MAPPING_EXTRA_RULES_PROPS = { "rules": [ { "local": [{"group": {"id": "0cd5e9"}}, {"user": {"name": "{0}"}}], - "invalid_type": { - "id": "xyz", - }, + "invalid_type": {"id": "xyz"}, "remote": [ {"type": "UserName"}, {"type": "orgPersonType", "not_any_of": ["SubContractor"]}, @@ -219,13 +216,7 @@ MAPPING_EXTRA_RULES_PROPS = { MAPPING_TESTER_REGEX = { "rules": [ { - "local": [ - { - "user": { - "name": "{0}", - } - } - ], + "local": [{"user": {"name": "{0}"}}], "remote": [{"type": "UserName"}], }, { @@ -246,11 +237,7 @@ MAPPING_DIRECT_MAPPING_THROUGH_KEYWORD = { "rules": [ { "local": [ - { - "user": { - "name": "{0}", - } - }, + {"user": {"name": "{0}"}}, {"group": {"id": TESTER_GROUP_ID}}, ], "remote": [{"type": "UserName", "any_one_of": ["bwilliams"]}], @@ -262,19 +249,11 @@ MAPPING_DEVELOPER_REGEX = { "rules": [ { "local": [ - { - "user": { - "name": "{0}", - }, - "group": {"id": DEVELOPER_GROUP_ID}, - } + {"user": {"name": "{0}"}, "group": {"id": DEVELOPER_GROUP_ID}} ], "remote": [ {"type": "UserName"}, - { - "type": "orgPersonType", - "any_one_of": ["Developer"], - }, + {"type": "orgPersonType", "any_one_of": ["Developer"]}, { "type": "Email", "not_any_of": [".*@example.org$"], @@ -288,13 +267,7 @@ MAPPING_DEVELOPER_REGEX = { MAPPING_GROUP_NAMES = { "rules": [ { - "local": [ - { - "user": { - "name": "{0}", - } - } - ], + "local": [{"user": {"name": "{0}"}}], "remote": [{"type": "UserName"}], }, { @@ -306,12 +279,7 @@ MAPPING_GROUP_NAMES = { } } ], - "remote": [ - { - "type": "orgPersonType", - "any_one_of": ["Employee"], - } - ], + "remote": [{"type": "orgPersonType", "any_one_of": ["Employee"]}], }, { "local": [ @@ -330,20 +298,9 @@ MAPPING_GROUP_NAMES = { MAPPING_GROUP_NAME_WITHOUT_DOMAIN = { "rules": [ { - "local": [ - { - "group": { - "name": DEVELOPER_GROUP_NAME, - } - } - ], - "remote": [ - { - "type": "orgPersonType", - "any_one_of": ["Employee"], - } - ], - }, + "local": [{"group": {"name": DEVELOPER_GROUP_NAME}}], + "remote": [{"type": "orgPersonType", "any_one_of": ["Employee"]}], + } ] } @@ -358,13 +315,8 @@ MAPPING_GROUP_ID_WITH_DOMAIN = { } } ], - "remote": [ - { - "type": "orgPersonType", - "any_one_of": ["Employee"], - } - ], - }, + "remote": [{"type": "orgPersonType", "any_one_of": ["Employee"]}], + } ] } @@ -372,13 +324,8 @@ MAPPING_BAD_GROUP = { "rules": [ { "local": [{"group": {}}], - "remote": [ - { - "type": "orgPersonType", - "any_one_of": ["Employee"], - } - ], - }, + "remote": [{"type": "orgPersonType", "any_one_of": ["Employee"]}], + } ] } @@ -396,13 +343,8 @@ MAPPING_BAD_DOMAIN = { } } ], - "remote": [ - { - "type": "orgPersonType", - "any_one_of": ["Employee"], - } - ], - }, + "remote": [{"type": "orgPersonType", "any_one_of": ["Employee"]}], + } ] } @@ -491,13 +433,9 @@ MAPPING_GROUPS_WHITELIST_MISSING_DOMAIN = { { "type": "orgPersonType", "whitelist": ["Developer", "Contractor"], - }, - ], - "local": [ - { - "groups": "{0}", } ], + "local": [{"groups": "{0}"}], } ] } @@ -535,11 +473,7 @@ MAPPING_GROUPS_BLACKLIST_MULTIPLES = { ], "local": [ {"groups": "{0}", "domain": {"id": DEVELOPER_GROUP_DOMAIN_ID}}, - { - "user": { - "name": "{2}", - } - }, + {"user": {"name": "{2}"}}, ], } ] @@ -570,11 +504,9 @@ MAPPING_GROUPS_BLACKLIST_REGEX = { "type": "orgPersonType", "blacklist": [".*Employee$"], "regex": True, - }, - ], - "local": [ - {"groups": "{0}", "domain": {"id": FEDERATED_DOMAIN}}, + } ], + "local": [{"groups": "{0}", "domain": {"id": FEDERATED_DOMAIN}}], } ] } @@ -587,11 +519,9 @@ MAPPING_GROUPS_WHITELIST_REGEX = { "type": "orgPersonType", "whitelist": [".*Employee$"], "regex": True, - }, - ], - "local": [ - {"groups": "{0}", "domain": {"id": FEDERATED_DOMAIN}}, + } ], + "local": [{"groups": "{0}", "domain": {"id": FEDERATED_DOMAIN}}], } ] } @@ -654,13 +584,9 @@ MAPPING_GROUPS_BLACKLIST_MISSING_DOMAIN = { { "type": "orgPersonType", "blacklist": ["Developer", "Manager"], - }, - ], - "local": [ - { - "groups": "{0}", - }, + } ], + "local": [{"groups": "{0}"}], } ] } @@ -673,10 +599,10 @@ MAPPING_GROUPS_WHITELIST_AND_BLACKLIST = { "type": "orgPersonType", "blacklist": ["Employee"], "whitelist": ["Contractor"], - }, + } ], "local": [ - {"groups": "{0}", "domain": {"id": DEVELOPER_GROUP_DOMAIN_ID}}, + {"groups": "{0}", "domain": {"id": DEVELOPER_GROUP_DOMAIN_ID}} ], } ] @@ -929,7 +855,7 @@ MAPPING_BAD_LOCAL_TYPE_USER_IN_ASSERTION = { {"type": "openstack_groups"}, {"type": "openstack_roles", "any_one_of": ["Admin"]}, ], - }, + } ] } @@ -937,12 +863,8 @@ MAPPING_GROUPS_WITH_EMAIL = { "rules": [ { "remote": [ - { - "type": "groups", - }, - { - "type": "userEmail", - }, + {"type": "groups"}, + {"type": "userEmail"}, {"type": "UserName"}, ], "local": [ @@ -1166,8 +1088,8 @@ MAPPING_UNICODE = { "any_one_of": ["Admin", "Big Cheese"], }, ], - }, - ], + } + ] } MAPPING_PROJECTS = { @@ -1186,14 +1108,12 @@ MAPPING_PROJECTS = { "name": "Project for {0}", "roles": [{"name": "admin"}], }, - ], + ] }, ], "remote": [ {"type": "UserName"}, - { - "type": "Email", - }, + {"type": "Email"}, {"type": "orgPersonType", "any_one_of": ["Employee"]}, ], } @@ -1214,7 +1134,7 @@ MAPPING_PROJECTS_WITHOUT_ROLES = { } ], "remote": [{"type": "UserName"}], - }, + } ] } @@ -1235,6 +1155,6 @@ MAPPING_PROJECTS_WITHOUT_NAME = { } ], "remote": [{"type": "UserName"}], - }, + } ] } diff --git a/keystone/tests/unit/policy/backends/test_sql.py b/keystone/tests/unit/policy/backends/test_sql.py index e4ecff0e7e..a6acca655d 100644 --- a/keystone/tests/unit/policy/backends/test_sql.py +++ b/keystone/tests/unit/policy/backends/test_sql.py @@ -33,7 +33,6 @@ class SQLModelTestCase(core_sql.BaseBackendSqlModels): class SQLDriverTestCase(test_base.DriverTestCase, unit.TestCase): - def setUp(self): # Load database first since parent's setUp will use it self.useFixture(database.Database()) diff --git a/keystone/tests/unit/receipt/test_fernet_provider.py b/keystone/tests/unit/receipt/test_fernet_provider.py index 01151bad3c..13ef3a18da 100644 --- a/keystone/tests/unit/receipt/test_fernet_provider.py +++ b/keystone/tests/unit/receipt/test_fernet_provider.py @@ -49,7 +49,7 @@ class TestFernetReceiptProvider(unit.TestCase): self.provider.validate_receipt, receipt_id, ) - self.assertIn(receipt_id, '%s' % e) + self.assertIn(receipt_id, f'{e}') class TestValidate(unit.TestCase): @@ -79,10 +79,7 @@ class TestValidate(unit.TestCase): domain_ref['id'], domain_ref ) - rule_list = [ - ['password', 'totp'], - ['password', 'totp', 'token'], - ] + rule_list = [['password', 'totp'], ['password', 'totp', 'token']] user_ref = unit.new_user_ref(domain_ref['id']) user_ref = PROVIDERS.identity_api.create_user(user_ref) @@ -140,7 +137,6 @@ class TestReceiptFormatter(unit.TestCase): class TestPayloads(unit.TestCase): - def setUp(self): super().setUp() self.useFixture( @@ -394,7 +390,7 @@ class TestFernetKeyRotation(unit.TestCase): # Simulate the disk full situation mock_open = mock.mock_open() file_handle = mock_open() - file_handle.flush.side_effect = IOError('disk full') + file_handle.flush.side_effect = OSError('disk full') with mock.patch('keystone.common.fernet_utils.open', mock_open): self.assertRaises(IOError, key_utils.rotate_keys) @@ -454,7 +450,6 @@ class TestFernetKeyRotation(unit.TestCase): class TestLoadKeys(unit.TestCase): - def assertValidFernetKeys(self, keys): # Make sure each key is a non-empty string for key in keys: diff --git a/keystone/tests/unit/receipt/test_receipt_serialization.py b/keystone/tests/unit/receipt/test_receipt_serialization.py index 7b8703e506..d4a6dc900b 100644 --- a/keystone/tests/unit/receipt/test_receipt_serialization.py +++ b/keystone/tests/unit/receipt/test_receipt_serialization.py @@ -23,7 +23,6 @@ from keystone.tests.unit import base_classes class TestReceiptSerialization(base_classes.TestCaseWithBootstrap): - def setUp(self): super().setUp() self.admin_user_id = self.bootstrapper.admin_user_id diff --git a/keystone/tests/unit/resource/config_backends/test_sql.py b/keystone/tests/unit/resource/config_backends/test_sql.py index ef74694e9f..0c2cbcfccc 100644 --- a/keystone/tests/unit/resource/config_backends/test_sql.py +++ b/keystone/tests/unit/resource/config_backends/test_sql.py @@ -20,7 +20,6 @@ from keystone.tests.unit.resource import test_core class SqlDomainConfigModels(core_sql.BaseBackendSqlModels): - def test_whitelisted_model(self): cols = ( ('domain_id', sql.String, 64), diff --git a/keystone/tests/unit/resource/test_backends.py b/keystone/tests/unit/resource/test_backends.py index a66971f813..811a5d5d42 100644 --- a/keystone/tests/unit/resource/test_backends.py +++ b/keystone/tests/unit/resource/test_backends.py @@ -31,7 +31,6 @@ PROVIDERS = provider_api.ProviderAPIs class ResourceTests: - domain_count = len(default_fixtures.DOMAINS) def test_get_project(self): @@ -200,7 +199,7 @@ class ResourceTests: exception.ProjectNotFound, PROVIDERS.resource_api.update_project, uuid.uuid4().hex, - dict(), + {}, ) def test_delete_project_returns_not_found(self): @@ -1430,7 +1429,6 @@ class ResourceTests: with mock.patch.object( resource_sql.Resource, "get_project" ) as mock_get_project: - mock_get_project.return_value = domain_ref # Delete the domain PROVIDERS.resource_api.delete_domain(domain['id']) @@ -2136,11 +2134,7 @@ class ResourceTests: def test_cannot_delete_disabled_domain_with_immutable_project(self): domain_id = uuid.uuid4().hex - domain = { - 'name': uuid.uuid4().hex, - 'id': domain_id, - 'is_domain': True, - } + domain = {'name': uuid.uuid4().hex, 'id': domain_id, 'is_domain': True} PROVIDERS.resource_api.create_domain(domain_id, domain) project = unit.new_project_ref(domain_id) @@ -2161,11 +2155,7 @@ class ResourceTests: # domains are projects, this should be the same as the project version domain_id = uuid.uuid4().hex - domain = { - 'name': uuid.uuid4().hex, - 'id': domain_id, - 'is_domain': True, - } + domain = {'name': uuid.uuid4().hex, 'id': domain_id, 'is_domain': True} PROVIDERS.resource_api.create_domain(domain_id, domain) domain_via_manager = PROVIDERS.resource_api.get_domain(domain_id) @@ -2194,11 +2184,7 @@ class ResourceTests: # domains are projects, this should be the same as the project version domain_id = uuid.uuid4().hex - domain = { - 'name': uuid.uuid4().hex, - 'id': domain_id, - 'is_domain': True, - } + domain = {'name': uuid.uuid4().hex, 'id': domain_id, 'is_domain': True} PROVIDERS.resource_api.create_domain(domain_id, domain) domain_via_manager = PROVIDERS.resource_api.get_domain(domain_id) @@ -2299,19 +2285,11 @@ class ResourceDriverTests: domain_id = default_fixtures.ROOT_DOMAIN['id'] project_id = uuid.uuid4().hex - project = { - 'name': name, - 'id': project_id, - 'domain_id': domain_id, - } + project = {'name': name, 'id': project_id, 'domain_id': domain_id} self.driver.create_project(project_id, project) project_id = uuid.uuid4().hex - project = { - 'name': name, - 'id': project_id, - 'domain_id': domain_id, - } + project = {'name': name, 'id': project_id, 'domain_id': domain_id} self.assertRaises( exception.Conflict, self.driver.create_project, project_id, project ) diff --git a/keystone/tests/unit/resource/test_core.py b/keystone/tests/unit/resource/test_core.py index ff50112336..f66a2755da 100644 --- a/keystone/tests/unit/resource/test_core.py +++ b/keystone/tests/unit/resource/test_core.py @@ -29,7 +29,6 @@ PROVIDERS = provider_api.ProviderAPIs class TestResourceManagerNoFixtures(unit.SQLDriverOverrides, unit.TestCase): - def setUp(self): super().setUp() self.useFixture(database.Database()) @@ -69,7 +68,6 @@ class TestResourceManagerNoFixtures(unit.SQLDriverOverrides, unit.TestCase): class DomainConfigDriverTests: - def _domain_config_crud(self, sensitive): domain = uuid.uuid4().hex group = uuid.uuid4().hex @@ -262,7 +260,6 @@ class DomainConfigDriverTests: class DomainConfigTests: - def setUp(self): self.domain = unit.new_domain_ref() PROVIDERS.resource_api.create_domain(self.domain['id'], self.domain) diff --git a/keystone/tests/unit/rest.py b/keystone/tests/unit/rest.py index 0e48f1f5bd..26bf00a968 100644 --- a/keystone/tests/unit/rest.py +++ b/keystone/tests/unit/rest.py @@ -80,7 +80,7 @@ class RestfulTestCase(unit.TestCase): headers=None, token=None, expected_status=None, - **kwargs + **kwargs, ): if headers: headers = {str(k): str(v) for k, v in headers.items()} @@ -128,8 +128,7 @@ class RestfulTestCase(unit.TestCase): self.assertEqual( expected_status, response.status_code, - 'Status code %s is not %s, as expected\n\n%s' - % (response.status_code, expected_status, response.body), + f'Status code {response.status_code} is not {expected_status}, as expected\n\n{response.body}', ) def assertValidResponseHeaders(self, response): @@ -184,7 +183,7 @@ class RestfulTestCase(unit.TestCase): body=None, content_type=None, response_content_type=None, - **kwargs + **kwargs, ): """Serialize/deserialize json as request/response body. diff --git a/keystone/tests/unit/server/test_keystone_flask.py b/keystone/tests/unit/server/test_keystone_flask.py index 6d9cff9732..6d3a6dc0a9 100644 --- a/keystone/tests/unit/server/test_keystone_flask.py +++ b/keystone/tests/unit/server/test_keystone_flask.py @@ -131,7 +131,6 @@ class _TestRestfulAPI(flask_common.APIBase): class TestKeystoneFlaskCommon(rest.RestfulTestCase): - _policy_rules = [ policy.RuleDefault(name='example:allowed', check_str=''), policy.RuleDefault(name='example:deny', check_str='false:false'), @@ -182,7 +181,6 @@ class TestKeystoneFlaskCommon(rest.RestfulTestCase): ) def _setup_flask_restful_api(self, **options): - self.restful_api_opts = options.copy() orig_value = _TestResourceWithCollectionInfo.api_prefix setattr( @@ -335,12 +333,12 @@ class TestKeystoneFlaskCommon(rest.RestfulTestCase): ) def test_api_url_prefix(self): - url_prefix = '/%s' % uuid.uuid4().hex + url_prefix = f'/{uuid.uuid4().hex}' self._setup_flask_restful_api(api_url_prefix=url_prefix) self._make_requests() def test_blueprint_url_prefix(self): - url_prefix = '/%s' % uuid.uuid4().hex + url_prefix = f'/{uuid.uuid4().hex}' self._setup_flask_restful_api(blueprint_url_prefix=url_prefix) self._make_requests() @@ -349,7 +347,6 @@ class TestKeystoneFlaskCommon(rest.RestfulTestCase): self._make_requests() def test_cannot_add_before_request_functions_twice(self): - class TestAPIDuplicateBefore(_TestRestfulAPI): def __init__(self): super().__init__() @@ -358,7 +355,6 @@ class TestKeystoneFlaskCommon(rest.RestfulTestCase): self.assertRaises(AssertionError, TestAPIDuplicateBefore) def test_cannot_add_after_request_functions_twice(self): - class TestAPIDuplicateAfter(_TestRestfulAPI): def __init__(self): super().__init__() @@ -367,7 +363,6 @@ class TestKeystoneFlaskCommon(rest.RestfulTestCase): self.assertRaises(AssertionError, TestAPIDuplicateAfter) def test_after_request_functions_must_be_added(self): - class TestAPINoAfter(_TestRestfulAPI): def _register_after_request_functions(self, functions=None): pass @@ -375,7 +370,6 @@ class TestKeystoneFlaskCommon(rest.RestfulTestCase): self.assertRaises(AssertionError, TestAPINoAfter) def test_before_request_functions_must_be_added(self): - class TestAPINoBefore(_TestRestfulAPI): def _register_before_request_functions(self, functions=None): pass @@ -438,12 +432,12 @@ class TestKeystoneFlaskCommon(rest.RestfulTestCase): ) url = '/v3/arguments/' old_url = [ - dict( - url='/v3/old_arguments/', - json_home=flask_common.construct_json_home_data( + { + 'url': '/v3/old_arguments/', + 'json_home': flask_common.construct_json_home_data( rel='arguments', resource_relation_func=alt_rel_func ), - ) + } ] mapping = flask_common.construct_resource_map( @@ -713,7 +707,6 @@ class TestKeystoneFlaskCommon(rest.RestfulTestCase): ) def test_api_prefix_self_referential_link_substitution(self): - view_arg = uuid.uuid4().hex class TestResource(flask_common.ResourceBase): @@ -723,7 +716,7 @@ class TestKeystoneFlaskCommon(rest.RestfulTestCase): # therefore we don't need the heavy lifting of a full request # run. with self.test_request_context( - path='/%s/nothing/values' % view_arg, base_url='https://localhost/' + path=f'/{view_arg}/nothing/values', base_url='https://localhost/' ): # explicitly set the view_args, this is a special case # for a synthetic test case, usually one would rely on @@ -742,7 +735,7 @@ class TestKeystoneFlaskCommon(rest.RestfulTestCase): # including the explicit view arg. self.assertTrue( ref['links']['self'].startswith( - 'https://localhost/v3/%s' % view_arg + f'https://localhost/v3/{view_arg}' ) ) diff --git a/keystone/tests/unit/test_associate_project_endpoint_extension.py b/keystone/tests/unit/test_associate_project_endpoint_extension.py index a88599ff0f..a527b3e373 100644 --- a/keystone/tests/unit/test_associate_project_endpoint_extension.py +++ b/keystone/tests/unit/test_associate_project_endpoint_extension.py @@ -26,21 +26,15 @@ PROVIDERS = provider_api.ProviderAPIs class EndpointFilterTestCase(test_v3.RestfulTestCase): - def setUp(self): super().setUp() self.default_request_url = ( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': self.endpoint_id, - } + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{self.endpoint_id}' ) class EndpointFilterCRUDTestCase(EndpointFilterTestCase): - def test_create_endpoint_project_association(self): """PUT /OS-EP-FILTER/projects/{project_id}/endpoints/{endpoint_id}. @@ -56,12 +50,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': uuid.uuid4().hex, - 'endpoint_id': self.endpoint_id, - }, + f'/OS-EP-FILTER/projects/{uuid.uuid4().hex}' + f'/endpoints/{self.endpoint_id}', expected_status=http.client.NOT_FOUND, ) @@ -72,12 +62,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': uuid.uuid4().hex, - }, + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{uuid.uuid4().hex}', expected_status=http.client.NOT_FOUND, ) @@ -100,12 +86,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) self.head( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': self.endpoint_id, - }, + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{self.endpoint_id}', expected_status=http.client.NO_CONTENT, ) @@ -117,12 +99,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) self.head( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': uuid.uuid4().hex, - 'endpoint_id': self.endpoint_id, - }, + f'/OS-EP-FILTER/projects/{uuid.uuid4().hex}' + f'/endpoints/{self.endpoint_id}', expected_status=http.client.NOT_FOUND, ) @@ -134,12 +112,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) self.head( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': uuid.uuid4().hex, - }, + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{uuid.uuid4().hex}', expected_status=http.client.NOT_FOUND, ) @@ -151,12 +125,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) self.get( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': self.endpoint_id, - }, + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{self.endpoint_id}', expected_status=http.client.NO_CONTENT, ) @@ -168,12 +138,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) self.get( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': uuid.uuid4().hex, - 'endpoint_id': self.endpoint_id, - }, + f'/OS-EP-FILTER/projects/{uuid.uuid4().hex}' + f'/endpoints/{self.endpoint_id}', expected_status=http.client.NOT_FOUND, ) @@ -185,12 +151,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) self.get( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': uuid.uuid4().hex, - }, + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{uuid.uuid4().hex}', expected_status=http.client.NOT_FOUND, ) @@ -201,9 +163,7 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) - resource_url = '/OS-EP-FILTER/projects/{project_id}/endpoints'.format( - project_id=self.default_domain_project_id - ) + resource_url = f'/OS-EP-FILTER/projects/{self.default_domain_project_id}/endpoints' r = self.get(resource_url) self.assertValidEndpointListResponse( r, self.endpoint, resource_url=resource_url @@ -217,9 +177,7 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) - url = '/OS-EP-FILTER/projects/{project_id}/endpoints'.format( - project_id=uuid.uuid4().hex - ) + url = f'/OS-EP-FILTER/projects/{uuid.uuid4().hex}/endpoints' self.get(url, expected_status=http.client.NOT_FOUND) self.head(url, expected_status=http.client.NOT_FOUND) @@ -230,9 +188,7 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) - resource_url = '/OS-EP-FILTER/endpoints/{endpoint_id}/projects'.format( - endpoint_id=self.endpoint_id - ) + resource_url = f'/OS-EP-FILTER/endpoints/{self.endpoint_id}/projects' r = self.get(resource_url, expected_status=http.client.OK) self.assertValidProjectListResponse( r, self.default_domain_project, resource_url=resource_url @@ -245,9 +201,7 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): Valid endpoint id but no endpoint-project associations test case. """ - url = '/OS-EP-FILTER/endpoints/{endpoint_id}/projects'.format( - endpoint_id=self.endpoint_id - ) + url = f'/OS-EP-FILTER/endpoints/{self.endpoint_id}/projects' r = self.get(url, expected_status=http.client.OK) self.assertValidProjectListResponse(r, expected_length=0) self.head(url, expected_status=http.client.OK) @@ -258,9 +212,7 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): Invalid endpoint id test case. """ - url = '/OS-EP-FILTER/endpoints/{endpoint_id}/projects'.format( - endpoint_id=uuid.uuid4().hex - ) + url = f'/OS-EP-FILTER/endpoints/{uuid.uuid4().hex}/projects' self.get(url, expected_status=http.client.NOT_FOUND) self.head(url, expected_status=http.client.NOT_FOUND) @@ -272,12 +224,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) self.delete( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': self.endpoint_id, - } + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{self.endpoint_id}' ) def test_remove_endpoint_project_association_with_invalid_project(self): @@ -288,12 +236,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) self.delete( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': uuid.uuid4().hex, - 'endpoint_id': self.endpoint_id, - }, + f'/OS-EP-FILTER/projects/{uuid.uuid4().hex}' + f'/endpoints/{self.endpoint_id}', expected_status=http.client.NOT_FOUND, ) @@ -305,39 +249,27 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): """ self.put(self.default_request_url) self.delete( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': uuid.uuid4().hex, - }, + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{uuid.uuid4().hex}', expected_status=http.client.NOT_FOUND, ) def test_endpoint_project_association_cleanup_when_project_deleted(self): self.put(self.default_request_url) association_url = ( - '/OS-EP-FILTER/endpoints/%(endpoint_id)s/projects' - % {'endpoint_id': self.endpoint_id} + f'/OS-EP-FILTER/endpoints/{self.endpoint_id}/projects' ) r = self.get(association_url) self.assertValidProjectListResponse(r, expected_length=1) - self.delete( - '/projects/%(project_id)s' - % {'project_id': self.default_domain_project_id} - ) + self.delete(f'/projects/{self.default_domain_project_id}') r = self.get(association_url) self.assertValidProjectListResponse(r, expected_length=0) def test_endpoint_project_association_cleanup_when_endpoint_deleted(self): self.put(self.default_request_url) - association_url = ( - '/OS-EP-FILTER/projects/{project_id}/endpoints'.format( - project_id=self.default_domain_project_id - ) - ) + association_url = f'/OS-EP-FILTER/projects/{self.default_domain_project_id}/endpoints' r = self.get(association_url) self.assertValidEndpointListResponse(r, expected_length=1) @@ -397,12 +329,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): # the catalog_api API manager directly but call the REST API # instead for consistency. self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': endpoint_id2, - } + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{endpoint_id2}' ) # should get back two endpoints since the cache has been @@ -434,12 +362,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): # add second endpoint to default project. self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': endpoint_id2, - } + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{endpoint_id2}' ) # should get back only one endpoint that was just created. @@ -481,12 +405,8 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): # by calling the catalog_api API manager directly but call # the REST API instead for consistency. self.delete( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.default_domain_project_id, - 'endpoint_id': endpoint_id2, - } + f'/OS-EP-FILTER/projects/{self.default_domain_project_id}' + f'/endpoints/{endpoint_id2}' ) # should only get back one endpoint since the cache has been @@ -500,7 +420,6 @@ class EndpointFilterCRUDTestCase(EndpointFilterTestCase): class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): - def test_project_scoped_token_using_endpoint_filter(self): """Verify endpoints from project scoped token filtered.""" # create a project to work with @@ -510,12 +429,11 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): # grant the user a role on the project self.put( - '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' - % { - 'user_id': self.user['id'], - 'project_id': project['id'], - 'role_id': self.role['id'], - } + '/projects/{project_id}/users/{user_id}/roles/{role_id}'.format( + user_id=self.user['id'], + project_id=project['id'], + role_id=self.role['id'], + ) ) # set the user's preferred project @@ -527,9 +445,10 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): # add one endpoint to the project self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % {'project_id': project['id'], 'endpoint_id': self.endpoint_id} + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=project['id'], endpoint_id=self.endpoint_id + ) ) # attempt to authenticate without requesting a project @@ -546,12 +465,10 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): """Verify endpoints from default scoped token filtered.""" # add one endpoint to default project self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.project['id'], - 'endpoint_id': self.endpoint_id, - } + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=self.project['id'], endpoint_id=self.endpoint_id + ) ) auth_data = self.build_authentication_request( @@ -579,12 +496,10 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): def test_scoped_token_with_no_catalog_using_endpoint_filter(self): """Verify endpoint filter does not affect no catalog.""" self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.project['id'], - 'endpoint_id': self.endpoint_id, - } + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=self.project['id'], endpoint_id=self.endpoint_id + ) ) auth_data = self.build_authentication_request( @@ -602,12 +517,10 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): """Verify an invalid endpoint-project association is handled.""" # add first endpoint to default project self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.project['id'], - 'endpoint_id': self.endpoint_id, - } + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=self.project['id'], endpoint_id=self.endpoint_id + ) ) # create a second temporary endpoint @@ -622,9 +535,10 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): # add second endpoint to default project self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % {'project_id': self.project['id'], 'endpoint_id': endpoint_id2} + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=self.project['id'], endpoint_id=endpoint_id2 + ) ) # remove the temporary reference @@ -649,12 +563,10 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): """Test that a disabled endpoint is handled.""" # Add an enabled endpoint to the default project self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.project['id'], - 'endpoint_id': self.endpoint_id, - } + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=self.project['id'], endpoint_id=self.endpoint_id + ) ) # Add a disabled endpoint to the default project. @@ -674,12 +586,10 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): ) self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.project['id'], - 'endpoint_id': disabled_endpoint_id, - } + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=self.project['id'], endpoint_id=disabled_endpoint_id + ) ) # Authenticate to get token with catalog @@ -695,7 +605,6 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): self.assertEqual([self.endpoint_id], endpoint_ids) def test_multiple_endpoint_project_associations(self): - def _create_an_endpoint(): endpoint_ref = unit.new_endpoint_ref( service_id=self.service_id, @@ -712,14 +621,16 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): # only associate two endpoints with project self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % {'project_id': self.project['id'], 'endpoint_id': endpoint_id1} + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=self.project['id'], endpoint_id=endpoint_id1 + ) ) self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % {'project_id': self.project['id'], 'endpoint_id': endpoint_id2} + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=self.project['id'], endpoint_id=endpoint_id2 + ) ) # there should be only two endpoints in token catalog @@ -736,12 +647,10 @@ class EndpointFilterTokenRequestTestCase(EndpointFilterTestCase): def test_get_auth_catalog_using_endpoint_filter(self): # add one endpoint to default project self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % { - 'project_id': self.project['id'], - 'endpoint_id': self.endpoint_id, - } + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=self.project['id'], endpoint_id=self.endpoint_id + ) ) auth_data = self.build_authentication_request( @@ -773,20 +682,18 @@ class JsonHomeTests(EndpointFilterTestCase, test_v3.JsonHomeTestMixin): 'href-template': '/OS-EP-FILTER/endpoints/{endpoint_id}/projects', 'href-vars': { 'endpoint_id': 'https://docs.openstack.org/api/openstack-identity/3/param/' - 'endpoint_id', + 'endpoint_id' }, }, 'https://docs.openstack.org/api/openstack-identity/3/ext/OS-EP-FILTER/' - '1.0/rel/endpoint_groups': { - 'href': '/OS-EP-FILTER/endpoint_groups', - }, + '1.0/rel/endpoint_groups': {'href': '/OS-EP-FILTER/endpoint_groups'}, 'https://docs.openstack.org/api/openstack-identity/3/ext/OS-EP-FILTER/' '1.0/rel/endpoint_group': { 'href-template': '/OS-EP-FILTER/endpoint_groups/' '{endpoint_group_id}', 'href-vars': { 'endpoint_group_id': 'https://docs.openstack.org/api/openstack-identity/3/' - 'ext/OS-EP-FILTER/1.0/param/endpoint_group_id', + 'ext/OS-EP-FILTER/1.0/param/endpoint_group_id' }, }, 'https://docs.openstack.org/api/openstack-identity/3/ext/OS-EP-FILTER/' @@ -806,7 +713,7 @@ class JsonHomeTests(EndpointFilterTestCase, test_v3.JsonHomeTestMixin): '{endpoint_group_id}/projects', 'href-vars': { 'endpoint_group_id': 'https://docs.openstack.org/api/openstack-identity/3/' - 'ext/OS-EP-FILTER/1.0/param/endpoint_group_id', + 'ext/OS-EP-FILTER/1.0/param/endpoint_group_id' }, }, 'https://docs.openstack.org/api/openstack-identity/3/ext/OS-EP-FILTER/' @@ -815,7 +722,7 @@ class JsonHomeTests(EndpointFilterTestCase, test_v3.JsonHomeTestMixin): '{endpoint_group_id}/endpoints', 'href-vars': { 'endpoint_group_id': 'https://docs.openstack.org/api/openstack-identity/3/' - 'ext/OS-EP-FILTER/1.0/param/endpoint_group_id', + 'ext/OS-EP-FILTER/1.0/param/endpoint_group_id' }, }, 'https://docs.openstack.org/api/openstack-identity/3/ext/OS-EP-FILTER/' @@ -824,14 +731,13 @@ class JsonHomeTests(EndpointFilterTestCase, test_v3.JsonHomeTestMixin): 'endpoint_groups', 'href-vars': { 'project_id': 'https://docs.openstack.org/api/openstack-identity/3/param/' - 'project_id', + 'project_id' }, }, } class EndpointGroupCRUDTestCase(EndpointFilterTestCase): - DEFAULT_ENDPOINT_GROUP_BODY = { 'endpoint_group': { 'description': 'endpoint group description', @@ -865,8 +771,9 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): self.assertThat( r.result['endpoint_group']['links']['self'], matchers.EndsWith( - '/OS-EP-FILTER/endpoint_groups/%(endpoint_group_id)s' - % {'endpoint_group_id': r.result['endpoint_group']['id']} + '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( + endpoint_group_id=r.result['endpoint_group']['id'] + ) ), ) @@ -898,9 +805,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): endpoint_group_id = response.result['endpoint_group']['id'] endpoint_group_filters = response.result['endpoint_group']['filters'] endpoint_group_name = response.result['endpoint_group']['name'] - url = '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( - endpoint_group_id=endpoint_group_id - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' self.get(url) self.assertEqual( endpoint_group_id, response.result['endpoint_group']['id'] @@ -924,9 +829,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): """ endpoint_group_id = 'foobar' - url = '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( - endpoint_group_id=endpoint_group_id - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' self.get(url, expected_status=http.client.NOT_FOUND) def test_check_endpoint_group(self): @@ -939,9 +842,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): endpoint_group_id = self._create_valid_endpoint_group( self.DEFAULT_ENDPOINT_GROUP_URL, self.DEFAULT_ENDPOINT_GROUP_BODY ) - url = '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( - endpoint_group_id=endpoint_group_id - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' self.head(url, expected_status=http.client.OK) def test_check_invalid_endpoint_group(self): @@ -951,9 +852,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): """ endpoint_group_id = 'foobar' - url = '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( - endpoint_group_id=endpoint_group_id - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' self.head(url, expected_status=http.client.NOT_FOUND) def test_patch_endpoint_group(self): @@ -969,9 +868,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): endpoint_group_id = self._create_valid_endpoint_group( self.DEFAULT_ENDPOINT_GROUP_URL, self.DEFAULT_ENDPOINT_GROUP_BODY ) - url = '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( - endpoint_group_id=endpoint_group_id - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' r = self.patch(url, body=body) self.assertEqual(endpoint_group_id, r.result['endpoint_group']['id']) self.assertEqual( @@ -1011,17 +908,13 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): endpoint_group_id = self._create_valid_endpoint_group( self.DEFAULT_ENDPOINT_GROUP_URL, self.DEFAULT_ENDPOINT_GROUP_BODY ) - url = '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( - endpoint_group_id=endpoint_group_id - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' self.patch(url, body=body, expected_status=http.client.BAD_REQUEST) # Perform a GET call to ensure that the content remains # the same (as DEFAULT_ENDPOINT_GROUP_BODY) after attempting to update # with an invalid filter - url = '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( - endpoint_group_id=endpoint_group_id - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' r = self.get(url) del r.result['endpoint_group']['id'] del r.result['endpoint_group']['links'] @@ -1037,9 +930,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): endpoint_group_id = self._create_valid_endpoint_group( self.DEFAULT_ENDPOINT_GROUP_URL, self.DEFAULT_ENDPOINT_GROUP_BODY ) - url = '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( - endpoint_group_id=endpoint_group_id - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' self.delete(url) self.get(url, expected_status=http.client.NOT_FOUND) @@ -1050,9 +941,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): """ endpoint_group_id = 'foobar' - url = '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( - endpoint_group_id=endpoint_group_id - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' self.delete(url, expected_status=http.client.NOT_FOUND) def test_add_endpoint_group_to_project(self): @@ -1122,9 +1011,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): ) self.put(url) - url = '/OS-EP-FILTER/projects/{project_id}/endpoint_groups'.format( - project_id=self.project_id - ) + url = f'/OS-EP-FILTER/projects/{self.project_id}/endpoint_groups' response = self.get(url, expected_status=http.client.OK) self.assertEqual( @@ -1136,17 +1023,13 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): def test_list_endpoint_groups_in_invalid_project(self): """Test retrieving from invalid project.""" project_id = uuid.uuid4().hex - url = '/OS-EP-FILTER/projects/{project_id}/endpoint_groups'.format( - project_id=project_id - ) + url = f'/OS-EP-FILTER/projects/{project_id}/endpoint_groups' self.get(url, expected_status=http.client.NOT_FOUND) self.head(url, expected_status=http.client.NOT_FOUND) def test_empty_endpoint_groups_in_project(self): """Test when no endpoint groups associated with the project.""" - url = '/OS-EP-FILTER/projects/{project_id}/endpoint_groups'.format( - project_id=self.project_id - ) + url = f'/OS-EP-FILTER/projects/{self.project_id}/endpoint_groups' response = self.get(url, expected_status=http.client.OK) self.assertEqual(0, len(response.result['endpoint_groups'])) @@ -1245,10 +1128,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): ) # recover list of projects associated with endpoint group - url = ( - '/OS-EP-FILTER/endpoint_groups/%(endpoint_group_id)s' - '/projects' % {'endpoint_group_id': endpoint_group_id} - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' '/projects' self.get(url, expected_status=http.client.OK) self.head(url, expected_status=http.client.OK) @@ -1284,10 +1164,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): ) # recover list of endpoints associated with endpoint group - url = ( - '/OS-EP-FILTER/endpoint_groups/%(endpoint_group_id)s' - '/endpoints' % {'endpoint_group_id': endpoint_group_id} - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' '/endpoints' r = self.get(url, expected_status=http.client.OK) self.assertNotEmpty(r.result['endpoints']) self.assertEqual(endpoint_id, r.result['endpoints'][0].get('id')) @@ -1326,9 +1203,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): ) # Now get a list of the filtered endpoints - endpoints_url = '/OS-EP-FILTER/projects/{project_id}/endpoints'.format( - project_id=self.default_domain_project_id - ) + endpoints_url = f'/OS-EP-FILTER/projects/{self.default_domain_project_id}/endpoints' r = self.get(endpoints_url, expected_status=http.client.OK) endpoints = self.assertValidEndpointListResponse(r) self.assertEqual(2, len(endpoints)) @@ -1350,9 +1225,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): self.delete(url) # Now remove endpoint group - url = '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}'.format( - endpoint_group_id=endpoint_group_id - ) + url = f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' self.delete(url) r = self.get(endpoints_url) @@ -1442,8 +1315,7 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): # remove endpoint group, the associated endpoint_group project will # be removed as well. endpoint_group_url = ( - '/OS-EP-FILTER/endpoint_groups/' - '%(endpoint_group_id)s' % {'endpoint_group_id': endpoint_group_id} + '/OS-EP-FILTER/endpoint_groups/' f'{endpoint_group_id}' ) self.delete(endpoint_group_url) self.get(endpoint_group_url, expected_status=http.client.NOT_FOUND) @@ -1620,12 +1492,8 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): def _get_project_endpoint_group_url(self, endpoint_group_id, project_id): return ( - '/OS-EP-FILTER/endpoint_groups/%(endpoint_group_id)s' - '/projects/%(project_id)s' - % { - 'endpoint_group_id': endpoint_group_id, - 'project_id': project_id, - } + f'/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}' + f'/projects/{project_id}' ) def _create_endpoint_and_associations(self, project_id, service_id=None): @@ -1645,8 +1513,9 @@ class EndpointGroupCRUDTestCase(EndpointFilterTestCase): # now add endpoint to project self.put( - '/OS-EP-FILTER/projects/%(project_id)s' - '/endpoints/%(endpoint_id)s' - % {'project_id': self.project['id'], 'endpoint_id': endpoint['id']} + '/OS-EP-FILTER/projects/{project_id}' + '/endpoints/{endpoint_id}'.format( + project_id=self.project['id'], endpoint_id=endpoint['id'] + ) ) return endpoint diff --git a/keystone/tests/unit/test_auth_plugin.py b/keystone/tests/unit/test_auth_plugin.py index 32834060fe..917127ead8 100644 --- a/keystone/tests/unit/test_auth_plugin.py +++ b/keystone/tests/unit/test_auth_plugin.py @@ -53,7 +53,6 @@ class SimpleChallengeResponse(base.AuthMethodHandler): class TestAuthPlugin(unit.SQLDriverOverrides, unit.TestCase): - def test_unsupported_auth_method(self): method_name = uuid.uuid4().hex auth_data = {'methods': [method_name]} @@ -147,7 +146,6 @@ class TestAuthPluginDynamicOptions(TestAuthPlugin): class TestMapped(unit.TestCase): - def config_files(self): config_files = super().config_files() config_files.append(unit.dirs.tests_conf('test_auth_plugin.conf')) diff --git a/keystone/tests/unit/test_backend_endpoint_policy.py b/keystone/tests/unit/test_backend_endpoint_policy.py index 79fc483441..1374f7988c 100644 --- a/keystone/tests/unit/test_backend_endpoint_policy.py +++ b/keystone/tests/unit/test_backend_endpoint_policy.py @@ -24,7 +24,6 @@ PROVIDERS = provider_api.ProviderAPIs class PolicyAssociationTests: - def _assert_correct_policy(self, endpoint, policy): ref = PROVIDERS.endpoint_policy_api.get_policy_for_endpoint( endpoint['id'] diff --git a/keystone/tests/unit/test_backend_endpoint_policy_sql.py b/keystone/tests/unit/test_backend_endpoint_policy_sql.py index 20e93d06e0..d85150b314 100644 --- a/keystone/tests/unit/test_backend_endpoint_policy_sql.py +++ b/keystone/tests/unit/test_backend_endpoint_policy_sql.py @@ -35,7 +35,6 @@ class SqlPolicyAssociationTests( test_backend_sql.SqlTests, test_backend_endpoint_policy.PolicyAssociationTests, ): - def load_fixtures(self, fixtures): super().load_fixtures(fixtures) self.load_sample_data() diff --git a/keystone/tests/unit/test_backend_id_mapping_sql.py b/keystone/tests/unit/test_backend_id_mapping_sql.py index 52c542fdfd..24cc62a030 100644 --- a/keystone/tests/unit/test_backend_id_mapping_sql.py +++ b/keystone/tests/unit/test_backend_id_mapping_sql.py @@ -40,7 +40,6 @@ class SqlIDMappingTable(test_backend_sql.SqlModels): class SqlIDMapping(test_backend_sql.SqlTests): - def setUp(self): super().setUp() self.load_sample_data() diff --git a/keystone/tests/unit/test_backend_ldap.py b/keystone/tests/unit/test_backend_ldap.py index 4dbeafaec6..946fa18100 100644 --- a/keystone/tests/unit/test_backend_ldap.py +++ b/keystone/tests/unit/test_backend_ldap.py @@ -48,7 +48,6 @@ PROVIDERS = provider_api.ProviderAPIs def _assert_backends(testcase, **kwargs): - def _get_backend_cls(testcase, subsystem): observed_backend = getattr(testcase, subsystem + '_api').driver return observed_backend.__class__ @@ -114,13 +113,11 @@ def _assert_backends(testcase, **kwargs): else: raise ValueError( - '%r is not an expected value for entrypoint name' - % entrypoint_name + f'{entrypoint_name!r} is not an expected value for entrypoint name' ) class IdentityTests(identity_tests.IdentityTests): - def test_update_domain_set_immutable(self): self.skip_test_overrides('N/A: LDAP does not support multiple domains') @@ -183,7 +180,6 @@ class IdentityTests(identity_tests.IdentityTests): class AssignmentTests(assignment_tests.AssignmentTests): - def test_get_role_assignment_by_domain_not_found(self): self.skip_test_overrides('N/A: LDAP does not support multiple domains') @@ -264,7 +260,6 @@ class AssignmentTests(assignment_tests.AssignmentTests): class ResourceTests(resource_tests.ResourceTests): - def test_create_duplicate_project_name_in_different_domains(self): self.skip_test_overrides('Domains are read-only against LDAP') @@ -366,7 +361,6 @@ class LDAPTestSetup: class BaseLDAPIdentity( LDAPTestSetup, IdentityTests, AssignmentTests, ResourceTests ): - def _get_domain_fixture(self): """Return the static domain, since domains in LDAP are read-only.""" return PROVIDERS.resource_api.get_domain( @@ -402,7 +396,7 @@ class BaseLDAPIdentity( ldap_ = PROVIDERS.identity_api.driver.user.get_connection() res = ldap_.search_s( - user_dn, ldap.SCOPE_BASE, '(sn=%s)' % user['name'] + user_dn, ldap.SCOPE_BASE, '(sn={})'.format(user['name']) ) if enabled_attr_name in res[0][1]: return res[0][1][enabled_attr_name] @@ -413,7 +407,7 @@ class BaseLDAPIdentity( """Regression test for building the tree names.""" user_api = identity.backends.ldap.UserApi(CONF) self.assertTrue(user_api) - self.assertEqual("ou=Users,%s" % CONF.ldap.suffix, user_api.tree_dn) + self.assertEqual(f"ou=Users,{CONF.ldap.suffix}", user_api.tree_dn) def test_configurable_allowed_user_actions(self): user = self.new_user_ref(domain_id=CONF.identity.default_domain_id) @@ -454,8 +448,7 @@ class BaseLDAPIdentity( domain_id = self.user_foo['domain_id'] driver = PROVIDERS.identity_api._select_identity_driver(domain_id) driver.user.ldap_filter = '(|(cn={})(cn={}))'.format( - self.user_sna['id'], - self.user_two['id'], + self.user_sna['id'], self.user_two['id'] ) users = PROVIDERS.identity_api.list_users( domain_scope=self._set_domain_scope(domain_id), hints=hints @@ -478,7 +471,9 @@ class BaseLDAPIdentity( self.assertEqual(numgroups, len(groups)) # configure the group filter driver = PROVIDERS.identity_api._select_identity_driver(domain['id']) - driver.group.ldap_filter = '(|(ou=%s)(ou=%s))' % tuple(group_names[:2]) + driver.group.ldap_filter = '(|(ou={})(ou={}))'.format( + *tuple(group_names[:2]) + ) # confirm that the group filter is working groups = PROVIDERS.identity_api.list_groups( domain_scope=self._set_domain_scope(domain['id']) @@ -571,9 +566,7 @@ class BaseLDAPIdentity( # domains are sourced from, so that we would not need to override such # tests here. This is raised as bug 1373865. new_domain = self._get_domain_fixture() - new_group = unit.new_group_ref( - domain_id=new_domain['id'], - ) + new_group = unit.new_group_ref(domain_id=new_domain['id']) new_group = PROVIDERS.identity_api.create_group(new_group) new_user = self.new_user_ref(domain_id=new_domain['id']) new_user = PROVIDERS.identity_api.create_user(new_user) @@ -1004,10 +997,7 @@ class BaseLDAPIdentity( def test_update_user_name(self): """A user's name cannot be changed through the LDAP driver.""" - self.assertRaises( - exception.Conflict, - super().test_update_user_name, - ) + self.assertRaises(exception.Conflict, super().test_update_user_name) def test_user_id_comma(self): """Even if the user has a , in their ID, groups can be listed.""" @@ -1205,7 +1195,6 @@ class BaseLDAPIdentity( class LDAPIdentity(BaseLDAPIdentity): - def assert_backends(self): _assert_backends( self, assignment='sql', identity='ldap', resource='sql' @@ -1381,7 +1370,6 @@ class LDAPIdentity(BaseLDAPIdentity): def test_filter_ldap_result_by_attr( self, mock_simple_bind_s, mock_search_s, mock_connect ): - # Mock the ldap search results to return user entries with # user_name_attribute('sn') value has emptyspaces, emptystring # and attibute itself is not set. @@ -1394,13 +1382,7 @@ class LDAPIdentity(BaseLDAPIdentity): 'sn': ['junk1'], }, ), - ( - '', - { - 'cn': [uuid.uuid4().hex], - 'email': [uuid.uuid4().hex], - }, - ), + ('', {'cn': [uuid.uuid4().hex], 'email': [uuid.uuid4().hex]}), ( 'sn=,dc=example,dc=com', { @@ -1634,10 +1616,7 @@ class LDAPIdentity(BaseLDAPIdentity): # the live tests. ldap_id_field = 'sn' ldap_id_value = uuid.uuid4().hex - dn = '{}={},ou=Users,cn=example,cn=com'.format( - ldap_id_field, - ldap_id_value, - ) + dn = f'{ldap_id_field}={ldap_id_value},ou=Users,cn=example,cn=com' modlist = [ ('objectClass', ['person', 'inetOrgPerson']), (ldap_id_field, [ldap_id_value]), @@ -1920,7 +1899,7 @@ class LDAPIdentity(BaseLDAPIdentity): self.assertEqual(len(default_fixtures.USERS), len(users)) user_ids = {user['id'] for user in users} expected_user_ids = { - getattr(self, 'user_%s' % user['name'])['id'] + getattr(self, 'user_{}'.format(user['name']))['id'] for user in default_fixtures.USERS } for user_ref in users: @@ -2005,9 +1984,7 @@ class LDAPIdentity(BaseLDAPIdentity): # and attibute itself is not set. mock_ldap_get.return_value = ( 'cn=users,dc=example,dc=com', - { - 'mail': [email1, email2], - }, + {'mail': [email1, email2]}, ) # This is not a valid scenario, since we do not support multiple value @@ -2066,9 +2043,7 @@ class LDAPIdentity(BaseLDAPIdentity): def test_id_attribute_not_found(self, mock_ldap_get): mock_ldap_get.return_value = ( 'cn=nobodycares,dc=example,dc=com', - { - 'sn': [uuid.uuid4().hex], - }, + {'sn': [uuid.uuid4().hex]}, ) user_api = identity.backends.ldap.UserApi(CONF) @@ -2410,12 +2385,7 @@ class LDAPIdentityEnabledEmulation(LDAPIdentity, unit.TestCase): # The filter, which _is_id_enabled is going to build, contains the # tree_dn, which better be escaped in this case. - exp_filter = '({}={}={},{})'.format( - mixin_impl.member_attribute, - mixin_impl.id_attr, - object_id, - sample_dn_filter_esc, - ) + exp_filter = f'({mixin_impl.member_attribute}={mixin_impl.id_attr}={object_id},{sample_dn_filter_esc})' with mixin_impl.get_connection() as conn: m = self.useFixture( @@ -2427,7 +2397,6 @@ class LDAPIdentityEnabledEmulation(LDAPIdentity, unit.TestCase): class LDAPPosixGroupsTest(LDAPTestSetup, unit.TestCase): - def assert_backends(self): _assert_backends(self, identity='ldap') @@ -2581,12 +2550,12 @@ class BaseMultiLDAPandSQLIdentity: role_id=self.role_member['id'], ) for x in range(1, self.domain_count): - users['user%s' % x] = unit.create_user( - PROVIDERS.identity_api, self.domains['domain%s' % x]['id'] + users[f'user{x}'] = unit.create_user( + PROVIDERS.identity_api, self.domains[f'domain{x}']['id'] ) PROVIDERS.assignment_api.create_grant( - user_id=users['user%s' % x]['id'], - domain_id=self.domains['domain%s' % x]['id'], + user_id=users[f'user{x}']['id'], + domain_id=self.domains[f'domain{x}']['id'], role_id=self.role_member['id'], ) @@ -2630,7 +2599,6 @@ class BaseMultiLDAPandSQLIdentity: pass def setup_initial_domains(self): - def create_domain(domain): try: ref = PROVIDERS.resource_api.create_domain( @@ -2642,7 +2610,7 @@ class BaseMultiLDAPandSQLIdentity: self.domains = {} for x in range(1, self.domain_count): - domain = 'domain%s' % x + domain = f'domain{x}' self.domains[domain] = create_domain( {'id': uuid.uuid4().hex, 'name': domain} ) @@ -2652,7 +2620,7 @@ class BaseMultiLDAPandSQLIdentity: users = self.create_users_across_domains() for user_num in range(self.domain_count): - user = 'user%s' % user_num + user = f'user{user_num}' with self.make_request(): PROVIDERS.identity_api.authenticate( user_id=users[user]['id'], password=users[user]['password'] @@ -2755,7 +2723,7 @@ class MultiLDAPandSQLIdentity( self.assertEqual(len(default_fixtures.USERS) + 1, len(users)) user_ids = {user['id'] for user in users} expected_user_ids = { - getattr(self, 'user_%s' % user['name'])['id'] + getattr(self, 'user_{}'.format(user['name']))['id'] for user in default_fixtures.USERS } expected_user_ids.add(_users['user0']['id']) @@ -3414,7 +3382,7 @@ class DomainSpecificLDAPandSQLIdentity( self.assertEqual(len(default_fixtures.USERS) + 1, len(users)) user_ids = {user['id'] for user in users} expected_user_ids = { - getattr(self, 'user_%s' % user['name'])['id'] + getattr(self, 'user_{}'.format(user['name']))['id'] for user in default_fixtures.USERS } expected_user_ids.add(_users['user0']['id']) @@ -3652,7 +3620,6 @@ class DomainSpecificSQLIdentity(DomainSpecificLDAPandSQLIdentity): class LdapFilterTests( identity_tests.FilterTests, LDAPTestSetup, unit.TestCase ): - def assert_backends(self): _assert_backends(self, identity='ldap') @@ -3677,7 +3644,6 @@ class LdapFilterTests( class LDAPMatchingRuleInChainTests(LDAPTestSetup, unit.TestCase): - def setUp(self): super().setUp() diff --git a/keystone/tests/unit/test_backend_ldap_pool.py b/keystone/tests/unit/test_backend_ldap_pool.py index 4a7a6afccf..dcb5ca62a1 100644 --- a/keystone/tests/unit/test_backend_ldap_pool.py +++ b/keystone/tests/unit/test_backend_ldap_pool.py @@ -128,7 +128,6 @@ class LdapPoolCommonTestMixin: ) def test_max_connection_error_raised(self): - who = CONF.ldap.user cred = CONF.ldap.password # get related connection manager instance @@ -149,7 +148,6 @@ class LdapPoolCommonTestMixin: ldappool_cm.size = CONF.ldap.pool_size def test_pool_size_expands_correctly(self): - who = CONF.ldap.user cred = CONF.ldap.password # get related connection manager instance diff --git a/keystone/tests/unit/test_backend_rules.py b/keystone/tests/unit/test_backend_rules.py index d4db778425..ad0c9f0e4c 100644 --- a/keystone/tests/unit/test_backend_rules.py +++ b/keystone/tests/unit/test_backend_rules.py @@ -44,8 +44,7 @@ class RulesPolicy(unit.TestCase, policy_tests.PolicyTests): def test_get_policy_returns_not_found(self): self.assertRaises( - exception.NotImplemented, - super().test_get_policy_returns_not_found, + exception.NotImplemented, super().test_get_policy_returns_not_found ) def test_update_policy_returns_not_found(self): diff --git a/keystone/tests/unit/test_backend_sql.py b/keystone/tests/unit/test_backend_sql.py index 8b603f540d..df8c75c40c 100644 --- a/keystone/tests/unit/test_backend_sql.py +++ b/keystone/tests/unit/test_backend_sql.py @@ -53,7 +53,6 @@ PROVIDERS = provider_api.ProviderAPIs class SqlTests(unit.SQLDriverOverrides, unit.TestCase): - def setUp(self): super().setUp() self.database_fixture = self.useFixture(database.Database()) @@ -76,7 +75,7 @@ class DataTypeRoundTrips(SqlTests): with sql.session_for_read() as session: val = session.scalar( sqlalchemy.select( - sqlalchemy.literal({"key": "value"}, type_=core.JsonBlob), + sqlalchemy.literal({"key": "value"}, type_=core.JsonBlob) ) ) @@ -95,7 +94,7 @@ class DataTypeRoundTrips(SqlTests): with sql.session_for_read() as session: val = session.scalar( sqlalchemy.select( - sqlalchemy.cast(sqlalchemy.null(), type_=core.JsonBlob), + sqlalchemy.cast(sqlalchemy.null(), type_=core.JsonBlob) ) ) @@ -112,7 +111,7 @@ class DataTypeRoundTrips(SqlTests): with sql.session_for_read() as session: val = session.scalar( sqlalchemy.select( - sqlalchemy.literal(None, type_=core.JsonBlob), + sqlalchemy.literal(None, type_=core.JsonBlob) ) ) @@ -126,7 +125,7 @@ class DataTypeRoundTrips(SqlTests): sqlalchemy.cast( sqlalchemy.literal(None, type_=core.JsonBlob), sqlalchemy.String, - ), + ) ) ) @@ -138,7 +137,7 @@ class DataTypeRoundTrips(SqlTests): datetime_value = datetime.datetime(2019, 5, 15, 10, 17, 55) val = session.scalar( sqlalchemy.select( - sqlalchemy.literal(datetime_value, type_=core.DateTimeInt), + sqlalchemy.literal(datetime_value, type_=core.DateTimeInt) ) ) @@ -155,7 +154,7 @@ class DataTypeRoundTrips(SqlTests): datetime_value, type_=core.DateTimeInt ), sqlalchemy.Integer, - ), + ) ) ) @@ -166,7 +165,7 @@ class DataTypeRoundTrips(SqlTests): with sql.session_for_read() as session: val = session.scalar( sqlalchemy.select( - sqlalchemy.literal(None, type_=core.DateTimeInt), + sqlalchemy.literal(None, type_=core.DateTimeInt) ) ) @@ -174,7 +173,6 @@ class DataTypeRoundTrips(SqlTests): class SqlModels(SqlTests): - def load_table(self, name): table = sqlalchemy.Table( name, @@ -209,9 +207,11 @@ class SqlModels(SqlTests): Example:: - cols = (('id', sql.String, 64), - ('enabled', sql.Boolean, True), - ('extra', sql.JsonBlob, None)) + cols = ( + ('id', sql.String, 64), + ('enabled', sql.Boolean, True), + ('extra', sql.JsonBlob, None), + ) self.assertExpectedSchema('table_name', cols) """ @@ -954,9 +954,9 @@ class SqlIdentity( projects = driver.list_projects_from_ids([ref_id]) self.assertThat(projects, matchers.HasLength(0)) - project_ids = [ - x for x in driver.list_project_ids_from_domain_ids([ref_id]) - ] + project_ids = list( + driver.list_project_ids_from_domain_ids([ref_id]) + ) self.assertNotIn(ref_id, project_ids) self.assertRaises( @@ -1111,7 +1111,6 @@ class SqlIdentity( class SqlTrust(SqlTests, trust_tests.TrustTests): - def test_trust_expires_at_int_matches_expires_at(self): with sql.session_for_write() as session: new_id = uuid.uuid4().hex @@ -1123,7 +1122,6 @@ class SqlTrust(SqlTests, trust_tests.TrustTests): class SqlCatalog(SqlTests, catalog_tests.CatalogTests): - _legacy_endpoint_id_in_endpoint = True _enabled_default_to_true_when_creating_endpoint = True @@ -1324,7 +1322,6 @@ class SqlImpliedRoles(SqlTests, assignment_tests.ImpliedRoleTests): class SqlFilterTests(SqlTests, identity_tests.FilterTests): - def clean_up_entities(self): """Clean up entity test data from Filter Test Cases.""" for entity in ['user', 'group', 'project']: @@ -1422,7 +1419,6 @@ class FakeTable(sql.ModelBase): class SqlDecorators(unit.TestCase): - def test_initialization_fail(self): self.assertRaises( exception.StringLengthExceeded, FakeTable, col='a' * 64 @@ -1441,7 +1437,6 @@ class SqlDecorators(unit.TestCase): class SqlModuleInitialization(unit.TestCase): - @mock.patch.object(sql.core, 'CONF') @mock.patch.object(options, 'set_defaults') def test_initialize_module(self, set_defaults, CONF): @@ -1452,7 +1447,6 @@ class SqlModuleInitialization(unit.TestCase): class SqlCredential(SqlTests): - def _create_credential_with_user_id(self, user_id=uuid.uuid4().hex): credential = unit.new_credential_ref( user_id=user_id, extra=uuid.uuid4().hex, type=uuid.uuid4().hex @@ -1556,7 +1550,6 @@ class SqlCredential(SqlTests): class SqlRegisteredLimit(SqlTests, limit_tests.RegisteredLimitTests): - def setUp(self): super().setUp() @@ -1576,7 +1569,6 @@ class SqlRegisteredLimit(SqlTests, limit_tests.RegisteredLimitTests): class SqlLimit(SqlTests, limit_tests.LimitTests): - def setUp(self): super().setUp() diff --git a/keystone/tests/unit/test_backend_templated.py b/keystone/tests/unit/test_backend_templated.py index 76d23bdd9d..c70ed31a12 100644 --- a/keystone/tests/unit/test_backend_templated.py +++ b/keystone/tests/unit/test_backend_templated.py @@ -29,7 +29,6 @@ BROKEN_WRITE_FUNCTIONALITY_MSG = ( class TestTemplatedCatalog(unit.TestCase, catalog_tests.CatalogTests): - DEFAULT_FIXTURE = { 'RegionOne': { 'compute': { @@ -109,17 +108,17 @@ class TestTemplatedCatalog(unit.TestCase, catalog_tests.CatalogTests): { 'interface': 'admin', 'region': 'RegionOne', - 'url': 'http://localhost:8774/v1.1/%s' % project_id, + 'url': f'http://localhost:8774/v1.1/{project_id}', }, { 'interface': 'public', 'region': 'RegionOne', - 'url': 'http://localhost:8774/v1.1/%s' % project_id, + 'url': f'http://localhost:8774/v1.1/{project_id}', }, { 'interface': 'internal', 'region': 'RegionOne', - 'url': 'http://localhost:8774/v1.1/%s' % project_id, + 'url': f'http://localhost:8774/v1.1/{project_id}', }, ], 'type': 'compute', @@ -169,32 +168,32 @@ class TestTemplatedCatalog(unit.TestCase, catalog_tests.CatalogTests): { 'interface': 'admin', 'region': 'RegionOne', - 'url': 'http://region-one:8774/v1.1/%s' % project_id, + 'url': f'http://region-one:8774/v1.1/{project_id}', }, { 'interface': 'public', 'region': 'RegionOne', - 'url': 'http://region-one:8774/v1.1/%s' % project_id, + 'url': f'http://region-one:8774/v1.1/{project_id}', }, { 'interface': 'internal', 'region': 'RegionOne', - 'url': 'http://region-one:8774/v1.1/%s' % project_id, + 'url': f'http://region-one:8774/v1.1/{project_id}', }, { 'interface': 'admin', 'region': 'RegionTwo', - 'url': 'http://region-two:8774/v1.1/%s' % project_id, + 'url': f'http://region-two:8774/v1.1/{project_id}', }, { 'interface': 'public', 'region': 'RegionTwo', - 'url': 'http://region-two:8774/v1.1/%s' % project_id, + 'url': f'http://region-two:8774/v1.1/{project_id}', }, { 'interface': 'internal', 'region': 'RegionTwo', - 'url': 'http://region-two:8774/v1.1/%s' % project_id, + 'url': f'http://region-two:8774/v1.1/{project_id}', }, ], 'type': 'compute', diff --git a/keystone/tests/unit/test_cli.py b/keystone/tests/unit/test_cli.py index b9536089ae..9949439fe5 100644 --- a/keystone/tests/unit/test_cli.py +++ b/keystone/tests/unit/test_cli.py @@ -61,7 +61,6 @@ PROVIDERS = provider_api.ProviderAPIs class CliLoggingTestCase(unit.BaseTestCase): - def setUp(self): self.config_fixture = self.useFixture(oslo_config.fixture.Config(CONF)) self.config_fixture.register_cli_opt(cli.command_opt) @@ -104,7 +103,6 @@ class CliLoggingTestCase(unit.BaseTestCase): class CliBootStrapTestCase(unit.SQLDriverOverrides, unit.TestCase): - def setUp(self): self.useFixture(database.Database()) super().setUp() @@ -410,7 +408,6 @@ class CliBootStrapTestCase(unit.SQLDriverOverrides, unit.TestCase): class CliBootStrapTestCaseWithEnvironment(CliBootStrapTestCase): - def config(self, config_files): CONF( args=['bootstrap'], @@ -575,7 +572,6 @@ class CliBootStrapTestCaseWithEnvironment(CliBootStrapTestCase): class CliDomainConfigAllTestCase(unit.SQLDriverOverrides, unit.TestCase): - def setUp(self): self.useFixture(database.Database()) super().setUp() @@ -619,7 +615,6 @@ class CliDomainConfigAllTestCase(unit.SQLDriverOverrides, unit.TestCase): ) def setup_initial_domains(self): - def create_domain(domain): return PROVIDERS.resource_api.create_domain(domain['id'], domain) @@ -630,7 +625,7 @@ class CliDomainConfigAllTestCase(unit.SQLDriverOverrides, unit.TestCase): self.domains = {} self.addCleanup(self.cleanup_domains) for x in range(1, self.domain_count): - domain = 'domain%s' % x + domain = f'domain{x}' self.domains[domain] = create_domain( {'id': uuid.uuid4().hex, 'name': domain} ) @@ -693,7 +688,6 @@ class CliDomainConfigAllTestCase(unit.SQLDriverOverrides, unit.TestCase): class CliDomainConfigSingleDomainTestCase(CliDomainConfigAllTestCase): - def config(self, config_files): CONF( args=['domain_config_upload', '--domain-name', 'Default'], @@ -746,7 +740,7 @@ class CliDomainConfigSingleDomainTestCase(CliDomainConfigAllTestCase): provider_api.ProviderAPIs._clear_registry_instances() with mock.patch('builtins.print') as mock_print: self.assertRaises(unit.UnexpectedExit, cli.DomainConfigUpload.main) - file_name = 'keystone.%s.conf' % self.default_domain['name'] + file_name = 'keystone.{}.conf'.format(self.default_domain['name']) error_msg = _( 'Domain: %(domain)s already has a configuration defined - ' 'ignoring file: %(file)s.' @@ -766,7 +760,6 @@ class CliDomainConfigSingleDomainTestCase(CliDomainConfigAllTestCase): class CliDomainConfigNoOptionsTestCase(CliDomainConfigAllTestCase): - def config(self, config_files): CONF( args=['domain_config_upload'], @@ -791,7 +784,6 @@ class CliDomainConfigNoOptionsTestCase(CliDomainConfigAllTestCase): class CliDomainConfigTooManyOptionsTestCase(CliDomainConfigAllTestCase): - def config(self, config_files): CONF( args=['domain_config_upload', '--all', '--domain-name', 'Default'], @@ -816,7 +808,6 @@ class CliDomainConfigTooManyOptionsTestCase(CliDomainConfigAllTestCase): class CliDomainConfigInvalidDomainTestCase(CliDomainConfigAllTestCase): - def config(self, config_files): self.invalid_domain_name = uuid.uuid4().hex CONF( @@ -833,7 +824,7 @@ class CliDomainConfigInvalidDomainTestCase(CliDomainConfigAllTestCase): provider_api.ProviderAPIs._clear_registry_instances() with mock.patch('builtins.print') as mock_print: self.assertRaises(unit.UnexpectedExit, cli.DomainConfigUpload.main) - file_name = 'keystone.%s.conf' % self.invalid_domain_name + file_name = f'keystone.{self.invalid_domain_name}.conf' error_msg = _( 'Invalid domain name: %(domain)s found in config file name: ' '%(file)s - ignoring this file.' @@ -847,7 +838,6 @@ class CliDomainConfigInvalidDomainTestCase(CliDomainConfigAllTestCase): class TestDomainConfigFinder(unit.BaseTestCase): - def setUp(self): super().setUp() self.logging = self.useFixture(fixtures.LoggerFixture()) @@ -855,7 +845,7 @@ class TestDomainConfigFinder(unit.BaseTestCase): @mock.patch('os.walk') def test_finder_ignores_files(self, mock_walk): mock_walk.return_value = [ - ['.', [], ['file.txt', 'keystone.conf', 'keystone.domain0.conf']], + ['.', [], ['file.txt', 'keystone.conf', 'keystone.domain0.conf']] ] domain_configs = list(cli._domain_config_finder('.')) @@ -879,7 +869,6 @@ class TestDomainConfigFinder(unit.BaseTestCase): class CliDBSyncTestCase(unit.BaseTestCase): - class FakeConfCommand: def __init__(self, parent): self.extension = False @@ -965,7 +954,6 @@ class CliDBSyncTestCase(unit.BaseTestCase): class TestMappingPopulate(unit.SQLDriverOverrides, unit.TestCase): - def setUp(self): sqldb = self.useFixture(database.Database()) super().setUp() @@ -1045,7 +1033,6 @@ class TestMappingPopulate(unit.SQLDriverOverrides, unit.TestCase): class CliDomainConfigUploadNothing(unit.BaseTestCase): - def setUp(self): super().setUp() @@ -1081,15 +1068,11 @@ class CliDomainConfigUploadNothing(unit.BaseTestCase): ) cli.DomainConfigUpload.main() - expected_msg = ( - 'No domain configs uploaded from %r' - % CONF.identity.domain_config_dir - ) + expected_msg = f'No domain configs uploaded from {CONF.identity.domain_config_dir!r}' self.assertThat(self.logging.output, matchers.Contains(expected_msg)) class CachingDoctorTests(unit.TestCase): - def test_symptom_caching_disabled(self): # Symptom Detected: Caching disabled self.config_fixture.config(group='cache', enabled=False) @@ -1185,7 +1168,6 @@ class CachingDoctorTests(unit.TestCase): class CredentialDoctorTests(unit.TestCase): - def test_credential_and_fernet_key_repositories_match(self): # Symptom Detected: Key repository paths are not unique directory = self.useFixture(fixtures.TempDir()).path @@ -1261,7 +1243,6 @@ class CredentialDoctorTests(unit.TestCase): class DatabaseDoctorTests(unit.TestCase): - def test_symptom_is_raised_if_database_connection_is_SQLite(self): # Symptom Detected: Database connection is sqlite self.config_fixture.config( @@ -1282,7 +1263,6 @@ class DatabaseDoctorTests(unit.TestCase): class DebugDoctorTests(unit.TestCase): - def test_symptom_debug_mode_is_enabled(self): # Symptom Detected: Debug mode is enabled self.config_fixture.config(debug=True) @@ -1294,7 +1274,6 @@ class DebugDoctorTests(unit.TestCase): class FederationDoctorTests(unit.TestCase): - def test_symptom_comma_in_SAML_public_certificate_path(self): # Symptom Detected: There is a comma in path to public cert file self.config_fixture.config(group='saml', certfile='file,cert.pem') @@ -1323,7 +1302,6 @@ class FederationDoctorTests(unit.TestCase): class LdapDoctorTests(unit.TestCase): - def test_user_enabled_emulation_dn_ignored_raised(self): # Symptom when user_enabled_emulation_dn is being ignored because the # user did not enable the user_enabled_emulation @@ -1523,7 +1501,6 @@ class LdapDoctorTests(unit.TestCase): class SecurityComplianceDoctorTests(unit.TestCase): - def test_minimum_password_age_greater_than_password_expires_days(self): # Symptom Detected: Minimum password age is greater than the password # expires days. Both values are positive integers greater than zero. @@ -1640,7 +1617,6 @@ class SecurityComplianceDoctorTests(unit.TestCase): class TokensDoctorTests(unit.TestCase): - def test_unreasonable_max_token_size_raised(self): # Symptom Detected: the max_token_size for fernet is greater than 255 self.config_fixture.config(group='token', provider='fernet') @@ -1660,7 +1636,6 @@ class TokensDoctorTests(unit.TestCase): class TokenFernetDoctorTests(unit.TestCase): - @mock.patch('keystone.cmd.doctor.tokens_fernet.utils') def test_usability_of_Fernet_key_repository_raised(self, mock_utils): # Symptom Detected: Fernet key repo is world readable @@ -1713,7 +1688,6 @@ class TokenFernetDoctorTests(unit.TestCase): class TestMappingPurge(unit.SQLDriverOverrides, unit.BaseTestCase): - class FakeConfCommand: def __init__(self, parent): self.extension = False @@ -1814,10 +1788,10 @@ class TestMappingPurge(unit.SQLDriverOverrides, unit.BaseTestCase): ) def fake_load_backends(): - return dict( - id_mapping_api=keystone.identity.core.MappingManager, - resource_api=None, - ) + return { + 'id_mapping_api': keystone.identity.core.MappingManager, + 'resource_api': None, + } self.useFixture( fixtures.MockPatch( @@ -1837,7 +1811,6 @@ class TestMappingPurge(unit.SQLDriverOverrides, unit.BaseTestCase): class TestUserMappingPurgeFunctional(unit.SQLDriverOverrides, unit.TestCase): - def setUp(self): sqldb = self.useFixture(database.Database()) super().setUp() @@ -1931,7 +1904,6 @@ class TestUserMappingPurgeFunctional(unit.SQLDriverOverrides, unit.TestCase): class TestGroupMappingPurgeFunctional(unit.SQLDriverOverrides, unit.TestCase): - def setUp(self): sqldb = self.useFixture(database.Database()) super().setUp() @@ -2023,7 +1995,6 @@ class TestGroupMappingPurgeFunctional(unit.SQLDriverOverrides, unit.TestCase): class TestTrustFlush(unit.SQLDriverOverrides, unit.BaseTestCase): - class FakeConfCommand: def __init__(self, parent): self.extension = False @@ -2061,7 +2032,7 @@ class TestTrustFlush(unit.SQLDriverOverrides, unit.BaseTestCase): ) def fake_load_backends(): - return dict(trust_api=keystone.trust.core.Manager()) + return {'trust_api': keystone.trust.core.Manager()} self.useFixture( fixtures.MockPatch( @@ -2084,7 +2055,7 @@ class TestTrustFlush(unit.SQLDriverOverrides, unit.BaseTestCase): ) def fake_load_backends(): - return dict(trust_api=keystone.trust.core.Manager()) + return {'trust_api': keystone.trust.core.Manager()} self.useFixture( fixtures.MockPatch( @@ -2099,7 +2070,6 @@ class TestTrustFlush(unit.SQLDriverOverrides, unit.BaseTestCase): class TestMappingEngineTester(unit.BaseTestCase): - class FakeConfCommand: def __init__(self, parent): self.extension = False @@ -2272,7 +2242,6 @@ class TestMappingEngineTester(unit.BaseTestCase): class CliStatusTestCase(unit.SQLDriverOverrides, unit.TestCase): - def setUp(self): self.useFixture(database.Database()) super().setUp() diff --git a/keystone/tests/unit/test_config.py b/keystone/tests/unit/test_config.py index 899a281e7d..78838bf7ab 100644 --- a/keystone/tests/unit/test_config.py +++ b/keystone/tests/unit/test_config.py @@ -23,7 +23,6 @@ CONF = keystone.conf.CONF class ConfigTestCase(unit.TestCase): - def config_files(self): config_files = super().config_files() diff --git a/keystone/tests/unit/test_contrib_ec2_core.py b/keystone/tests/unit/test_contrib_ec2_core.py index e9fe6b579f..b23bdbc896 100644 --- a/keystone/tests/unit/test_contrib_ec2_core.py +++ b/keystone/tests/unit/test_contrib_ec2_core.py @@ -66,7 +66,7 @@ class EC2ContribCoreV3(test_v3.RestfulTestCase): '/ec2tokens', body={'credentials': credentials}, expected_status=http.client.OK, - **kwargs + **kwargs, ) self.assertValidProjectScopedTokenResponse(resp, self.user) @@ -93,8 +93,7 @@ class EC2ContribCoreV3(test_v3.RestfulTestCase): ) body_hash = hashlib.sha256(hashed_payload.encode()).hexdigest() amz_credential = ( - 'AKIAIOSFODNN7EXAMPLE/%s/us-east-1/iam/aws4_request,' - % timestamp[:8] + f'AKIAIOSFODNN7EXAMPLE/{timestamp[:8]}/us-east-1/iam/aws4_request,' ) credentials = { @@ -198,8 +197,7 @@ class EC2ContribCoreV3(test_v3.RestfulTestCase): ) body_hash = hashlib.sha256(hashed_payload.encode()).hexdigest() amz_credential = ( - 'AKIAIOSFODNN7EXAMPLE/%s/us-east-1/iam/aws4_request,' - % timestamp[:8] + f'AKIAIOSFODNN7EXAMPLE/{timestamp[:8]}/us-east-1/iam/aws4_request,' ) credentials = { diff --git a/keystone/tests/unit/test_contrib_s3_core.py b/keystone/tests/unit/test_contrib_s3_core.py index a40b31adf3..87db119590 100644 --- a/keystone/tests/unit/test_contrib_s3_core.py +++ b/keystone/tests/unit/test_contrib_s3_core.py @@ -65,7 +65,7 @@ class S3ContribCore(test_v3.RestfulTestCase): } }, expected_status=http.client.OK, - **kwargs + **kwargs, ) self.assertValidProjectScopedTokenResponse( resp, self.user, forbid_token_id=True diff --git a/keystone/tests/unit/test_contrib_simple_cert.py b/keystone/tests/unit/test_contrib_simple_cert.py index c4d0630e1f..7f39d4ff25 100644 --- a/keystone/tests/unit/test_contrib_simple_cert.py +++ b/keystone/tests/unit/test_contrib_simple_cert.py @@ -16,13 +16,11 @@ from keystone.tests.unit import test_v3 class BaseTestCase(test_v3.RestfulTestCase): - CA_PATH = '/v3/OS-SIMPLE-CERT/ca' CERT_PATH = '/v3/OS-SIMPLE-CERT/certificates' class TestSimpleCert(BaseTestCase): - def request_cert(self, path): self.request( app=self.public_app, diff --git a/keystone/tests/unit/test_driver_hints.py b/keystone/tests/unit/test_driver_hints.py index 75d76194e4..e578c0cc76 100644 --- a/keystone/tests/unit/test_driver_hints.py +++ b/keystone/tests/unit/test_driver_hints.py @@ -17,7 +17,6 @@ from keystone.tests.unit import core as test class ListHintsTests(test.TestCase): - def test_create_iterate_satisfy(self): hints = driver_hints.Hints() hints.add_filter('t1', 'data1') diff --git a/keystone/tests/unit/test_entry_points.py b/keystone/tests/unit/test_entry_points.py index 1da8884f13..debbffcdf4 100644 --- a/keystone/tests/unit/test_entry_points.py +++ b/keystone/tests/unit/test_entry_points.py @@ -19,12 +19,7 @@ from keystone.tests.unit import core as test class TestEntryPoints(test.TestCase): def test_entry_point_middleware(self): """Assert that our list of expected middleware is present.""" - expected_names = [ - 'cors', - 'debug', - 'request_id', - 'sizelimit', - ] + expected_names = ['cors', 'debug', 'request_id', 'sizelimit'] em = stevedore.ExtensionManager('keystone.server_middleware') diff --git a/keystone/tests/unit/test_exception.py b/keystone/tests/unit/test_exception.py index e0d324d400..90d8b5a10e 100644 --- a/keystone/tests/unit/test_exception.py +++ b/keystone/tests/unit/test_exception.py @@ -148,8 +148,7 @@ class UnexpectedExceptionTestCase(ExceptionTestCase): self.config_fixture.config(debug=True, insecure_debug=True) e = exception.UnexpectedError(self.exc_str) self.assertEqual( - f'{self.exc_str} {exception.SecurityError.amendment}', - str(e), + f'{self.exc_str} {exception.SecurityError.amendment}', str(e) ) def test_unexpected_error_custom_message_exception_debug(self): @@ -157,8 +156,7 @@ class UnexpectedExceptionTestCase(ExceptionTestCase): orig_e = exception.NotFound(target=uuid.uuid4().hex) e = exception.UnexpectedError(orig_e) self.assertEqual( - f'{str(orig_e)} {exception.SecurityError.amendment}', - str(e), + f'{str(orig_e)} {exception.SecurityError.amendment}', str(e) ) def test_unexpected_error_custom_message_binary_debug(self): @@ -166,8 +164,7 @@ class UnexpectedExceptionTestCase(ExceptionTestCase): binary_msg = b'something' e = exception.UnexpectedError(binary_msg) self.assertEqual( - f'{str(binary_msg)} {exception.SecurityError.amendment}', - str(e), + f'{str(binary_msg)} {exception.SecurityError.amendment}', str(e) ) @@ -291,10 +288,10 @@ class TestSecurityErrorTranslation(unit.BaseTestCase): def test_nested_translation_of_SecurityErrors(self): e = self.CustomSecurityError(place='code') - ('Admiral found this in the log: %s') % e + (f'Admiral found this in the log: {e}') self.assertNotIn('programmer error', self.warning_log.output) def test_that_regular_Errors_can_be_deep_copied(self): e = self.CustomError(place='code') - ('Admiral found this in the log: %s') % e + (f'Admiral found this in the log: {e}') self.assertNotIn('programmer error', self.warning_log.output) diff --git a/keystone/tests/unit/test_hacking_checks.py b/keystone/tests/unit/test_hacking_checks.py index 58d5c15923..7a04770a9a 100644 --- a/keystone/tests/unit/test_hacking_checks.py +++ b/keystone/tests/unit/test_hacking_checks.py @@ -20,7 +20,6 @@ from keystone.tests.unit.ksfixtures import hacking as hacking_fixtures class BaseStyleCheck(unit.BaseTestCase): - def setUp(self): super().setUp() self.code_ex = self.useFixture(self.get_fixture()) @@ -54,7 +53,6 @@ class BaseStyleCheck(unit.BaseTestCase): class TestCheckForMutableDefaultArgs(BaseStyleCheck): - def get_checker(self): return checks.CheckForMutableDefaultArgs @@ -65,7 +63,6 @@ class TestCheckForMutableDefaultArgs(BaseStyleCheck): class TestBlockCommentsBeginWithASpace(BaseStyleCheck): - def get_checker(self): return checks.block_comments_begin_with_a_space @@ -76,7 +73,6 @@ class TestBlockCommentsBeginWithASpace(BaseStyleCheck): class TestTranslationChecks(BaseStyleCheck): - def get_checker(self): return checks.CheckForTranslationIssues @@ -101,7 +97,6 @@ class TestTranslationChecks(BaseStyleCheck): class TestDictConstructorWithSequenceCopy(BaseStyleCheck): - def get_checker(self): return checks.dict_constructor_with_sequence_copy diff --git a/keystone/tests/unit/test_ldap_livetest.py b/keystone/tests/unit/test_ldap_livetest.py index aaac3aa9c8..c50efcc625 100644 --- a/keystone/tests/unit/test_ldap_livetest.py +++ b/keystone/tests/unit/test_ldap_livetest.py @@ -36,7 +36,6 @@ def create_object(dn, attrs): class LiveLDAPIdentity(test_backend_ldap.LDAPIdentity): - def setUp(self): self._ldap_skip_live() super().setUp() @@ -107,16 +106,15 @@ class LiveLDAPIdentity(test_backend_ldap.LDAPIdentity): } aliased_users_ldif = { 'objectclass': ['alias', 'extensibleObject'], - 'aliasedobjectname': "ou=alt_users,%s" % CONF.ldap.suffix, + 'aliasedobjectname': f"ou=alt_users,{CONF.ldap.suffix}", } - create_object("ou=alt_users,%s" % CONF.ldap.suffix, alt_users_ldif) + create_object(f"ou=alt_users,{CONF.ldap.suffix}", alt_users_ldif) create_object( - "%s=alt_fake1,ou=alt_users,%s" - % (CONF.ldap.user_id_attribute, CONF.ldap.suffix), + f"{CONF.ldap.user_id_attribute}=alt_fake1,ou=alt_users,{CONF.ldap.suffix}", alt_fake_user_ldif, ) create_object( - "ou=alt_users,%s" % CONF.ldap.user_tree_dn, aliased_users_ldif + f"ou=alt_users,{CONF.ldap.user_tree_dn}", aliased_users_ldif ) self.config_fixture.config( diff --git a/keystone/tests/unit/test_ldap_pool_livetest.py b/keystone/tests/unit/test_ldap_pool_livetest.py index 5b9655eb67..bd267a0e27 100644 --- a/keystone/tests/unit/test_ldap_pool_livetest.py +++ b/keystone/tests/unit/test_ldap_pool_livetest.py @@ -62,7 +62,6 @@ class LiveLDAPPoolIdentity( self.test_user_enable_attribute_mask() def test_pool_size_expands_correctly(self): - who = CONF.ldap.user cred = CONF.ldap.password # get related connection manager instance diff --git a/keystone/tests/unit/test_ldap_tls_livetest.py b/keystone/tests/unit/test_ldap_tls_livetest.py index f55bccb415..dcc9fa1f89 100644 --- a/keystone/tests/unit/test_ldap_tls_livetest.py +++ b/keystone/tests/unit/test_ldap_tls_livetest.py @@ -35,7 +35,6 @@ def create_object(dn, attrs): class LiveTLSLDAPIdentity(test_ldap_livetest.LiveLDAPIdentity): - def _ldap_skip_live(self): self.skip_if_env_not_set('ENABLE_TLS_LDAP_LIVE_TEST') diff --git a/keystone/tests/unit/test_limits.py b/keystone/tests/unit/test_limits.py index 6828ad33fd..507770c540 100644 --- a/keystone/tests/unit/test_limits.py +++ b/keystone/tests/unit/test_limits.py @@ -26,7 +26,6 @@ PROVIDERS = provider_api.ProviderAPIs class LimitModelTestCase(test_v3.RestfulTestCase): - def test_get_default_limit_model_response_schema(self): schema = { 'type': 'object', @@ -39,7 +38,7 @@ class LimitModelTestCase(test_v3.RestfulTestCase): }, 'required': ['name', 'description'], 'additionalProperties': False, - }, + } }, 'required': ['model'], 'additionalProperties': False, @@ -264,7 +263,9 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): 'description': 'test description', } r = self.patch( - '/registered_limits/%s' % r.result['registered_limits'][0]['id'], + '/registered_limits/{}'.format( + r.result['registered_limits'][0]['id'] + ), body={'registered_limit': update_ref}, token=self.system_admin_token, expected_status=http.client.OK, @@ -292,12 +293,10 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): token=self.system_admin_token, expected_status=http.client.CREATED, ) - update_ref = { - 'region_id': self.region_id, - } + update_ref = {'region_id': self.region_id} registered_limit_id = r.result['registered_limits'][0]['id'] r = self.patch( - '/registered_limits/%s' % registered_limit_id, + f'/registered_limits/{registered_limit_id}', body={'registered_limit': update_ref}, token=self.system_admin_token, expected_status=http.client.OK, @@ -307,7 +306,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): update_ref['region_id'] = '' r = self.patch( - '/registered_limits/%s' % registered_limit_id, + f'/registered_limits/{registered_limit_id}', body={'registered_limit': update_ref}, token=self.system_admin_token, expected_status=http.client.BAD_REQUEST, @@ -329,7 +328,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): update_ref = {'description': 'test description'} registered_limit_id = r.result['registered_limits'][0]['id'] r = self.patch( - '/registered_limits/%s' % registered_limit_id, + f'/registered_limits/{registered_limit_id}', body={'registered_limit': update_ref}, token=self.system_admin_token, expected_status=http.client.OK, @@ -341,7 +340,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): update_ref['description'] = '' r = self.patch( - '/registered_limits/%s' % registered_limit_id, + f'/registered_limits/{registered_limit_id}', body={'registered_limit': update_ref}, token=self.system_admin_token, expected_status=http.client.OK, @@ -365,7 +364,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): update_ref = {'region_id': None} registered_limit_id = r.result['registered_limits'][0]['id'] r = self.patch( - '/registered_limits/%s' % registered_limit_id, + f'/registered_limits/{registered_limit_id}', body={'registered_limit': update_ref}, token=self.system_admin_token, expected_status=http.client.OK, @@ -403,7 +402,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): # region_id=None" already. So update ref2's region_id to None will # raise 409 Conflict Error. self.patch( - '/registered_limits/%s' % registered_limit_id, + f'/registered_limits/{registered_limit_id}', body={'registered_limit': update_ref}, token=self.system_admin_token, expected_status=http.client.CONFLICT, @@ -417,7 +416,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): 'default_limit': 5, } self.patch( - '/registered_limits/%s' % uuid.uuid4().hex, + f'/registered_limits/{uuid.uuid4().hex}', body={'registered_limit': update_ref}, token=self.system_admin_token, expected_status=http.client.NOT_FOUND, @@ -451,7 +450,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): update_ref5, ]: self.patch( - '/registered_limits/%s' % reg_id, + f'/registered_limits/{reg_id}', body={'registered_limit': input_limit}, token=self.system_admin_token, expected_status=http.client.BAD_REQUEST, @@ -491,7 +490,9 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): 'default_limit': 5, } self.patch( - '/registered_limits/%s' % r.result['registered_limits'][0]['id'], + '/registered_limits/{}'.format( + r.result['registered_limits'][0]['id'] + ), body={'registered_limit': update_ref}, token=self.system_admin_token, expected_status=http.client.FORBIDDEN, @@ -535,7 +536,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): self.assertEqual(registered_limits[0][key], ref2[key]) r = self.get( - '/registered_limits?service_id=%s' % self.service_id, + f'/registered_limits?service_id={self.service_id}', expected_status=http.client.OK, ) registered_limits = r.result['registered_limits'] @@ -549,7 +550,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): self.assertEqual(registered_limits[0][key], ref1[key]) r = self.get( - '/registered_limits?region_id=%s' % self.region_id2, + f'/registered_limits?region_id={self.region_id2}', expected_status=http.client.OK, ) registered_limits = r.result['registered_limits'] @@ -587,7 +588,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): '/registered_limits/fake_id', expected_status=http.client.NOT_FOUND ) r = self.get( - '/registered_limits/%s' % id1, expected_status=http.client.OK + f'/registered_limits/{id1}', expected_status=http.client.OK ) registered_limit = r.result['registered_limit'] for key in [ @@ -614,7 +615,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): ) id1 = r.result['registered_limits'][0]['id'] self.delete( - '/registered_limits/%s' % id1, + f'/registered_limits/{id1}', token=self.system_admin_token, expected_status=http.client.NO_CONTENT, ) @@ -656,7 +657,7 @@ class RegisteredLimitsTestCase(test_v3.RestfulTestCase): id = r.result['registered_limits'][0]['id'] self.delete( - '/registered_limits/%s' % id, expected_status=http.client.FORBIDDEN + f'/registered_limits/{id}', expected_status=http.client.FORBIDDEN ) @@ -1005,7 +1006,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): ) update_ref = {'resource_limit': 5, 'description': 'test description'} r = self.patch( - '/limits/%s' % r.result['limits'][0]['id'], + '/limits/{}'.format(r.result['limits'][0]['id']), body={'limit': update_ref}, token=self.system_admin_token, expected_status=http.client.OK, @@ -1018,7 +1019,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): def test_update_limit_not_found(self): update_ref = {'resource_limit': 5} self.patch( - '/limits/%s' % uuid.uuid4().hex, + f'/limits/{uuid.uuid4().hex}', body={'limit': update_ref}, token=self.system_admin_token, expected_status=http.client.NOT_FOUND, @@ -1047,7 +1048,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): invalid_description_update, ]: self.patch( - '/limits/%s' % limit_id, + f'/limits/{limit_id}', body={'limit': input_limit}, token=self.system_admin_token, expected_status=http.client.BAD_REQUEST, @@ -1096,7 +1097,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): self.assertEqual(limits[0][key], ref2[key]) r = self.get( - '/limits?service_id=%s' % self.service_id2, + f'/limits?service_id={self.service_id2}', expected_status=http.client.OK, ) limits = r.result['limits'] @@ -1105,7 +1106,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): self.assertEqual(limits[0][key], ref2[key]) r = self.get( - '/limits?region_id=%s' % self.region_id, + f'/limits?region_id={self.region_id}', expected_status=http.client.OK, ) limits = r.result['limits'] @@ -1173,7 +1174,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): # any project user can filter by their own project r = self.get( - '/limits?project_id=%s' % self.project_id, + f'/limits?project_id={self.project_id}', expected_status=http.client.OK, ) limits = r.result['limits'] @@ -1182,7 +1183,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): # a system scoped request can specify the project_id filter r = self.get( - '/limits?project_id=%s' % self.project_id, + f'/limits?project_id={self.project_id}', expected_status=http.client.OK, token=self.system_admin_token, ) @@ -1240,7 +1241,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): # if non system scoped request contain domain_id filter, keystone # will return an empty list. r = self.get( - '/limits?domain_id=%s' % self.domain_id, + f'/limits?domain_id={self.domain_id}', expected_status=http.client.OK, ) limits = r.result['limits'] @@ -1248,7 +1249,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): # a system scoped request can specify the domain_id filter r = self.get( - '/limits?domain_id=%s' % self.domain_id, + f'/limits?domain_id={self.domain_id}', expected_status=http.client.OK, auth=self.build_authentication_request( user_id=self.user['id'], @@ -1287,7 +1288,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): token=self.system_admin_token, expected_status=http.client.NOT_FOUND, ) - r = self.get('/limits/%s' % id1, expected_status=http.client.OK) + r = self.get(f'/limits/{id1}', expected_status=http.client.OK) limit = r.result['limit'] self.assertIsNone(limit['domain_id']) for key in [ @@ -1315,7 +1316,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): id1 = r.result['limits'][0]['id'] r = self.get( - '/limits/%s' % id1, + f'/limits/{id1}', expected_status=http.client.OK, auth=self.build_authentication_request( user_id=self.user['id'], @@ -1355,7 +1356,7 @@ class LimitsTestCase(test_v3.RestfulTestCase): ) id1 = r.result['limits'][0]['id'] self.delete( - '/limits/%s' % id1, + f'/limits/{id1}', token=self.system_admin_token, expected_status=http.client.NO_CONTENT, ) @@ -1374,7 +1375,6 @@ class LimitsTestCase(test_v3.RestfulTestCase): class StrictTwoLevelLimitsTestCase(LimitsTestCase): - def setUp(self): super().setUp() # Most of these tests require system-scoped tokens. Let's have one on @@ -1850,7 +1850,7 @@ class StrictTwoLevelLimitsTestCase(LimitsTestCase): update_dict = {'resource_limit': 9} self.patch( - '/limits/%s' % r.result['limits'][0]['id'], + '/limits/{}'.format(r.result['limits'][0]['id']), body={'limit': update_dict}, token=self.system_admin_token, expected_status=http.client.OK, @@ -1897,7 +1897,7 @@ class StrictTwoLevelLimitsTestCase(LimitsTestCase): update_dict = {'resource_limit': 11} self.patch( - '/limits/%s' % r.result['limits'][0]['id'], + '/limits/{}'.format(r.result['limits'][0]['id']), body={'limit': update_dict}, token=self.system_admin_token, expected_status=http.client.FORBIDDEN, @@ -1929,7 +1929,7 @@ class StrictTwoLevelLimitsTestCase(LimitsTestCase): update_dict = {'resource_limit': 9} self.patch( - '/limits/%s' % r.result['limits'][0]['id'], + '/limits/{}'.format(r.result['limits'][0]['id']), body={'limit': update_dict}, token=self.system_admin_token, expected_status=http.client.OK, @@ -1937,7 +1937,7 @@ class StrictTwoLevelLimitsTestCase(LimitsTestCase): update_dict = {'resource_limit': 11} self.patch( - '/limits/%s' % r.result['limits'][0]['id'], + '/limits/{}'.format(r.result['limits'][0]['id']), body={'limit': update_dict}, token=self.system_admin_token, expected_status=http.client.FORBIDDEN, @@ -1984,7 +1984,7 @@ class StrictTwoLevelLimitsTestCase(LimitsTestCase): update_dict = {'resource_limit': 8} self.patch( - '/limits/%s' % r.result['limits'][0]['id'], + '/limits/{}'.format(r.result['limits'][0]['id']), body={'limit': update_dict}, token=self.system_admin_token, expected_status=http.client.OK, @@ -2031,7 +2031,7 @@ class StrictTwoLevelLimitsTestCase(LimitsTestCase): update_dict = {'resource_limit': 6} self.patch( - '/limits/%s' % r.result['limits'][0]['id'], + '/limits/{}'.format(r.result['limits'][0]['id']), body={'limit': update_dict}, token=self.system_admin_token, expected_status=http.client.FORBIDDEN, diff --git a/keystone/tests/unit/test_middleware.py b/keystone/tests/unit/test_middleware.py index 06bb8a8fa8..53529e2848 100644 --- a/keystone/tests/unit/test_middleware.py +++ b/keystone/tests/unit/test_middleware.py @@ -40,7 +40,6 @@ PROVIDERS = provider_api.ProviderAPIs class MiddlewareRequestTestBase(unit.TestCase): - MIDDLEWARE_CLASS: ty.Any = None # override this in subclasses def _application(self): @@ -79,7 +78,6 @@ class MiddlewareRequestTestBase(unit.TestCase): # response rather than the error that is raised. class _Failing(self.MIDDLEWARE_CLASS): - _called = False def fill_context(i_self, *i_args, **i_kwargs): @@ -112,7 +110,6 @@ class MiddlewareRequestTestBase(unit.TestCase): class AuthContextMiddlewareTest( test_backend_sql.SqlTests, MiddlewareRequestTestBase ): - MIDDLEWARE_CLASS = auth_context.AuthContextMiddleware def setUp(self): @@ -742,8 +739,8 @@ class AuthContextMiddlewareTest( auth = tokenless_auth.TokenlessAuthHelper(env) expected_msg = ( 'Could not determine Identity Provider ID. The ' - 'configuration option %s was not found in the ' - 'request environment.' % CONF.tokenless_auth.issuer_attribute + f'configuration option {CONF.tokenless_auth.issuer_attribute} was not found in the ' + 'request environment.' ) # Check the content of the exception message as well self.assertRaisesRegex( diff --git a/keystone/tests/unit/test_policy.py b/keystone/tests/unit/test_policy.py index 8de43ba161..eaff961ff4 100644 --- a/keystone/tests/unit/test_policy.py +++ b/keystone/tests/unit/test_policy.py @@ -154,7 +154,6 @@ class PolicyTestCase(unit.TestCase): class PolicyScopeTypesEnforcementTestCase(unit.TestCase): - def setUp(self): super().setUp() rule = common_policy.RuleDefault( @@ -189,14 +188,13 @@ class PolicyScopeTypesEnforcementTestCase(unit.TestCase): class PolicyJsonTestCase(unit.TestCase): - def _get_default_policy_rules(self): """Return a dictionary of all in-code policies. All policies have a default value that is maintained in code. This method returns a dictionary containing all default policies. """ - rules = dict() + rules = {} for rule in policies.list_rules(): rules[rule.name] = rule.check_str return rules @@ -279,7 +277,6 @@ class PolicyJsonTestCase(unit.TestCase): class GeneratePolicyFileTestCase(unit.TestCase): - def test_policy_generator_from_command_line(self): # This test ensures keystone.common.policy:get_enforcer ignores # unexpected arguments before handing them off to oslo.config, which diff --git a/keystone/tests/unit/test_revoke.py b/keystone/tests/unit/test_revoke.py index d3e787b80a..86b4ce78b2 100644 --- a/keystone/tests/unit/test_revoke.py +++ b/keystone/tests/unit/test_revoke.py @@ -47,7 +47,6 @@ def _sample_blank_token(): class RevokeTests: - def _assertTokenRevoked(self, token_data): self.assertRaises( exception.TokenNotFound, diff --git a/keystone/tests/unit/test_shadow_users.py b/keystone/tests/unit/test_shadow_users.py index 1ca2796ebf..2c8627b1e0 100644 --- a/keystone/tests/unit/test_shadow_users.py +++ b/keystone/tests/unit/test_shadow_users.py @@ -40,9 +40,7 @@ class ShadowUsersTests( 'enabled': True, 'description': uuid.uuid4().hex, } - self.mapping = { - 'id': uuid.uuid4().hex, - } + self.mapping = {'id': uuid.uuid4().hex} self.protocol = { 'id': uuid.uuid4().hex, 'idp_id': self.idp['id'], @@ -68,7 +66,6 @@ class ShadowUsersTests( class TestUserWithFederatedUser(ShadowUsersTests): - def setUp(self): super().setUp() self.useFixture(database.Database()) diff --git a/keystone/tests/unit/test_sql_banned_operations.py b/keystone/tests/unit/test_sql_banned_operations.py index 3be60eb52a..006dcafd17 100644 --- a/keystone/tests/unit/test_sql_banned_operations.py +++ b/keystone/tests/unit/test_sql_banned_operations.py @@ -72,15 +72,12 @@ class BannedDBSchemaOperations(fixtures.Fixture): for op in self._banned_ops: self.useFixture( fixtures.MonkeyPatch( - 'alembic.op.%s' % op, - self._explode(op, self._revision), + f'alembic.op.{op}', self._explode(op, self._revision) ) ) -class KeystoneMigrationsWalk( - test_fixtures.OpportunisticDBTestMixin, -): +class KeystoneMigrationsWalk(test_fixtures.OpportunisticDBTestMixin): # Migrations can take a long time, particularly on underpowered CI nodes. # Give them some breathing room. TIMEOUT_SCALING_FACTOR = 4 @@ -142,12 +139,11 @@ class KeystoneMigrationsWalk( return self.assertIsNotNone( - getattr(self, '_check_%s' % version, None), - ('DB Migration %s does not have a test; you must add one') - % version, + getattr(self, f'_check_{version}', None), + (f'DB Migration {version} does not have a test; you must add one'), ) - pre_upgrade = getattr(self, '_pre_upgrade_%s' % version, None) + pre_upgrade = getattr(self, f'_pre_upgrade_{version}', None) if pre_upgrade: pre_upgrade(connection) @@ -166,7 +162,7 @@ class KeystoneMigrationsWalk( with BannedDBSchemaOperations(banned_ops, version): alembic_api.upgrade(self.config, version) - post_upgrade = getattr(self, '_check_%s' % version, None) + post_upgrade = getattr(self, f'_check_{version}', None) if post_upgrade: post_upgrade(connection) @@ -219,8 +215,7 @@ class KeystoneMigrationsWalk( inspector = sqlalchemy.inspect(connection) constraints = inspector.get_unique_constraints('trust') self.assertNotIn( - 'duplicate_trust_constraint', - {x['name'] for x in constraints}, + 'duplicate_trust_constraint', {x['name'] for x in constraints} ) all_constraints = [] @@ -241,8 +236,7 @@ class KeystoneMigrationsWalk( inspector = sqlalchemy.inspect(connection) constraints = inspector.get_unique_constraints('trust') self.assertIn( - 'duplicate_trust_constraint', - {x['name'] for x in constraints}, + 'duplicate_trust_constraint', {x['name'] for x in constraints} ) constraint = [ x for x in constraints if x['name'] == 'duplicate_trust_constraint' @@ -353,7 +347,7 @@ class KeystoneMigrationsWalk( with self.engine.begin() as connection: self.config.attributes['connection'] = connection script = alembic_script.ScriptDirectory.from_config(self.config) - revisions = [x for x in script.walk_revisions()] + revisions = list(script.walk_revisions()) # for some reason, 'walk_revisions' gives us the revisions in # reverse chronological order so we have to invert this diff --git a/keystone/tests/unit/test_sql_upgrade.py b/keystone/tests/unit/test_sql_upgrade.py index 9579e56367..a273e392cd 100644 --- a/keystone/tests/unit/test_sql_upgrade.py +++ b/keystone/tests/unit/test_sql_upgrade.py @@ -60,10 +60,7 @@ CONF = keystone.conf.CONF # is done to mirror the expected structure of the DB in the format of # { : [, , ...], ... } INITIAL_TABLE_STRUCTURE = { - 'config_register': [ - 'type', - 'domain_id', - ], + 'config_register': ['type', 'domain_id'], 'credential': [ 'id', 'user_id', @@ -83,19 +80,8 @@ INITIAL_TABLE_STRUCTURE = { 'enabled', 'extra', ], - 'group': [ - 'id', - 'domain_id', - 'name', - 'description', - 'extra', - ], - 'policy': [ - 'id', - 'type', - 'blob', - 'extra', - ], + 'group': ['id', 'domain_id', 'name', 'description', 'extra'], + 'policy': ['id', 'type', 'blob', 'extra'], 'project': [ 'id', 'name', @@ -106,41 +92,12 @@ INITIAL_TABLE_STRUCTURE = { 'parent_id', 'is_domain', ], - 'project_option': [ - 'project_id', - 'option_id', - 'option_value', - ], - 'project_tag': [ - 'project_id', - 'name', - ], - 'role': [ - 'id', - 'name', - 'extra', - 'domain_id', - 'description', - ], - 'role_option': [ - 'role_id', - 'option_id', - 'option_value', - ], - 'service': [ - 'id', - 'type', - 'extra', - 'enabled', - ], - 'token': [ - 'id', - 'expires', - 'extra', - 'valid', - 'trust_id', - 'user_id', - ], + 'project_option': ['project_id', 'option_id', 'option_value'], + 'project_tag': ['project_id', 'name'], + 'role': ['id', 'name', 'extra', 'domain_id', 'description'], + 'role_option': ['role_id', 'option_id', 'option_value'], + 'service': ['id', 'type', 'extra', 'enabled'], + 'token': ['id', 'expires', 'extra', 'valid', 'trust_id', 'user_id'], 'trust': [ 'id', 'trustor_user_id', @@ -155,10 +112,7 @@ INITIAL_TABLE_STRUCTURE = { 'redelegated_trust_id', 'redelegation_count', ], - 'trust_role': [ - 'trust_id', - 'role_id', - ], + 'trust_role': ['trust_id', 'role_id'], 'user': [ 'id', 'extra', @@ -168,46 +122,13 @@ INITIAL_TABLE_STRUCTURE = { 'last_active_at', 'domain_id', ], - 'user_option': [ - 'user_id', - 'option_id', - 'option_value', - ], - 'user_group_membership': [ - 'user_id', - 'group_id', - ], - 'region': [ - 'id', - 'description', - 'parent_region_id', - 'extra', - ], - 'assignment': [ - 'type', - 'actor_id', - 'target_id', - 'role_id', - 'inherited', - ], - 'id_mapping': [ - 'public_id', - 'domain_id', - 'local_id', - 'entity_type', - ], - 'whitelisted_config': [ - 'domain_id', - 'group', - 'option', - 'value', - ], - 'sensitive_config': [ - 'domain_id', - 'group', - 'option', - 'value', - ], + 'user_option': ['user_id', 'option_id', 'option_value'], + 'user_group_membership': ['user_id', 'group_id'], + 'region': ['id', 'description', 'parent_region_id', 'extra'], + 'assignment': ['type', 'actor_id', 'target_id', 'role_id', 'inherited'], + 'id_mapping': ['public_id', 'domain_id', 'local_id', 'entity_type'], + 'whitelisted_config': ['domain_id', 'group', 'option', 'value'], + 'sensitive_config': ['domain_id', 'group', 'option', 'value'], 'policy_association': [ 'id', 'policy_id', @@ -228,11 +149,7 @@ INITIAL_TABLE_STRUCTURE = { 'mapping_id', 'remote_id_attribute', ], - 'mapping': [ - 'id', - 'rules', - 'schema_version', - ], + 'mapping': ['id', 'rules', 'schema_version'], 'service_provider': [ 'auth_url', 'id', @@ -241,16 +158,8 @@ INITIAL_TABLE_STRUCTURE = { 'sp_url', 'relay_state_prefix', ], - 'idp_remote_ids': [ - 'idp_id', - 'remote_id', - ], - 'consumer': [ - 'id', - 'description', - 'secret', - 'extra', - ], + 'idp_remote_ids': ['idp_id', 'remote_id'], + 'consumer': ['id', 'description', 'secret', 'extra'], 'request_token': [ 'id', 'request_secret', @@ -286,20 +195,9 @@ INITIAL_TABLE_STRUCTURE = { 'audit_chain_id', ], 'project_endpoint': ['endpoint_id', 'project_id'], - 'endpoint_group': [ - 'id', - 'name', - 'description', - 'filters', - ], - 'project_endpoint_group': [ - 'endpoint_group_id', - 'project_id', - ], - 'implied_role': [ - 'prior_role_id', - 'implied_role_id', - ], + 'endpoint_group': ['id', 'name', 'description', 'filters'], + 'project_endpoint_group': ['endpoint_group_id', 'project_id'], + 'implied_role': ['prior_role_id', 'implied_role_id'], 'local_user': [ 'id', 'user_id', @@ -326,11 +224,7 @@ INITIAL_TABLE_STRUCTURE = { 'unique_id', 'display_name', ], - 'nonlocal_user': [ - 'domain_id', - 'name', - 'user_id', - ], + 'nonlocal_user': ['domain_id', 'name', 'user_id'], 'system_assignment': [ 'type', 'actor_id', @@ -368,10 +262,7 @@ INITIAL_TABLE_STRUCTURE = { 'system', 'unrestricted', ], - 'application_credential_role': [ - 'application_credential_id', - 'role_id', - ], + 'application_credential_role': ['application_credential_id', 'role_id'], 'access_rule': [ 'id', 'service', @@ -393,9 +284,7 @@ INITIAL_TABLE_STRUCTURE = { } -class MigrateBase( - db_fixtures.OpportunisticDBTestMixin, -): +class MigrateBase(db_fixtures.OpportunisticDBTestMixin): """Test complete orchestration between all database phases.""" def setUp(self): @@ -433,9 +322,7 @@ class MigrateBase( def load_table(self, name): table = sqlalchemy.Table( - name, - self.metadata, - autoload_with=self.engine, + name, self.metadata, autoload_with=self.engine ) return table @@ -445,14 +332,12 @@ class MigrateBase( # detect renamed or dropped tables try: sqlalchemy.Table( - table_name, - self.metadata, - autoload_with=self.engine, + table_name, self.metadata, autoload_with=self.engine ) except sqlalchemy.exc.NoSuchTableError: pass else: - raise AssertionError('Table "%s" already exists' % table_name) + raise AssertionError(f'Table "{table_name}" already exists') def assertTableColumns(self, table_name, expected_cols): """Assert that the table contains the expected set of columns.""" @@ -461,7 +346,7 @@ class MigrateBase( # Check if the columns are equal, but allow for a different order, # which might occur after an upgrade followed by a downgrade self.assertCountEqual( - expected_cols, actual_cols, '%s table' % table_name + expected_cols, actual_cols, f'{table_name} table' ) def test_db_sync_check(self): diff --git a/keystone/tests/unit/test_v3.py b/keystone/tests/unit/test_v3.py index ed39486eb0..daf82cec93 100644 --- a/keystone/tests/unit/test_v3.py +++ b/keystone/tests/unit/test_v3.py @@ -41,7 +41,6 @@ TIME_FORMAT = unit.TIME_FORMAT class RestfulTestCase( unit.SQLDriverOverrides, rest.RestfulTestCase, common_auth.AuthTestMixin ): - def generate_token_schema( self, system_scoped=False, domain_scoped=False, project_scoped=False ): @@ -51,23 +50,12 @@ class RestfulTestCase( 'items': { 'type': 'object', 'properties': { - 'id': { - 'type': 'string', - }, - 'name': { - 'type': 'string', - }, - 'description': { - 'type': 'string', - }, - 'options': { - 'type': 'object', - }, + 'id': {'type': 'string'}, + 'name': {'type': 'string'}, + 'description': {'type': 'string'}, + 'options': {'type': 'object'}, }, - 'required': [ - 'id', - 'name', - ], + 'required': ['id', 'name'], 'additionalProperties': False, }, 'minItems': 1, @@ -76,9 +64,7 @@ class RestfulTestCase( properties = { 'audit_ids': { 'type': 'array', - 'items': { - 'type': 'string', - }, + 'items': {'type': 'string'}, 'minItems': 1, 'maxItems': 2, }, @@ -86,16 +72,8 @@ class RestfulTestCase( 'type': 'string', 'pattern': unit.TIME_FORMAT_REGEX, }, - 'issued_at': { - 'type': 'string', - 'pattern': unit.TIME_FORMAT_REGEX, - }, - 'methods': { - 'type': 'array', - 'items': { - 'type': 'string', - }, - }, + 'issued_at': {'type': 'string', 'pattern': unit.TIME_FORMAT_REGEX}, + 'methods': {'type': 'array', 'items': {'type': 'string'}}, 'user': { 'type': 'object', 'required': ['id', 'name', 'domain', 'password_expires_at'], @@ -145,10 +123,7 @@ class RestfulTestCase( # FIXME(lbragstad): Remove this in favor of the predefined # ROLES_SCHEMA dictionary once bug 1763510 is fixed. ROLES_SCHEMA['items']['properties']['domain_id'] = { - 'type': [ - 'null', - 'string', - ], + 'type': ['null', 'string'] } properties['roles'] = ROLES_SCHEMA properties['is_domain'] = {'type': 'boolean'} @@ -352,9 +327,7 @@ class RestfulTestCase( }, }, 'scope': { - 'project': { - 'id': self.default_domain_project_id, - } + 'project': {'id': self.default_domain_project_id} }, } }, @@ -400,11 +373,7 @@ class RestfulTestCase( } }, }, - 'scope': { - 'project': { - 'id': self.project['id'], - } - }, + 'scope': {'project': {'id': self.project['id']}}, } }, ) @@ -450,11 +419,7 @@ class RestfulTestCase( } }, }, - 'scope': { - 'domain': { - 'id': self.domain['id'], - } - }, + 'scope': {'domain': {'id': self.domain['id']}}, } }, ) @@ -663,7 +628,7 @@ class RestfulTestCase( try: return datetime.datetime.strptime(dt, TIME_FORMAT) except Exception: - msg = '%s is not a valid ISO 8601 extended format date time.' % dt + msg = f'{dt} is not a valid ISO 8601 extended format date time.' raise AssertionError(msg) def assertValidTokenResponse(self, r, user=None, forbid_token_id=False): @@ -1166,7 +1131,6 @@ class RestfulTestCase( ref['links'] = links def assertRoleAssignmentInListResponse(self, resp, ref, expected=1): - found_count = 0 for entity in resp.result.get('role_assignments'): try: @@ -1285,7 +1249,6 @@ class RestfulTestCase( # Service providers (federation) def assertValidServiceProvider(self, entity, ref=None, *args, **kwargs): - attributes = frozenset( [ 'auth_url', @@ -1322,7 +1285,6 @@ class VersionTestCase(RestfulTestCase): # NOTE(gyee): test AuthContextMiddleware here instead of test_middleware.py # because we need the token class AuthContextMiddlewareTestCase(RestfulTestCase): - def load_fixtures(self, fixtures): self.load_sample_data() @@ -1350,7 +1312,6 @@ class AuthContextMiddlewareTestCase(RestfulTestCase): self.app_cred_r_secret = app_cred_ref['secret'] def _middleware_request(self, token, extra_environ=None): - def application(environ, start_response): body = b'body' headers = [ @@ -1414,9 +1375,7 @@ class AuthContextMiddlewareTestCase(RestfulTestCase): def test_domain_scoped_token_auth_context(self): # grant the domain role to user path = '/domains/{}/users/{}/roles/{}'.format( - self.domain['id'], - self.user['id'], - self.role['id'], + self.domain['id'], self.user['id'], self.role['id'] ) self.put(path=path) @@ -1458,7 +1417,6 @@ class AuthContextMiddlewareTestCase(RestfulTestCase): self.assertFalse(req_context.is_admin) def test_auth_context_app_cred_with_rule(self): - # # This is an open-coded _middleware_request(), which allows us to # supply paths and verify failure. We can refactor later if needed. @@ -1546,12 +1504,12 @@ class AssignmentTestMixin: query_params += 'scope.' elif k not in ['user_id', 'group_id', 'role_id']: raise ValueError( - 'Invalid key \'%s\' in provided filters.' % k + f'Invalid key \'{k}\' in provided filters.' ) query_params += '{}={}'.format(k.replace('_', '.'), v) - return '/role_assignments%s' % query_params + return f'/role_assignments{query_params}' def build_role_assignment_link(self, **attribs): """Build and return a role assignment link with provided attributes. @@ -1574,7 +1532,7 @@ class AssignmentTestMixin: link += '/roles/' + attribs['role_id'] if attribs.get('inherited_to_projects'): - return '/OS-INHERIT%s/inherited_to_projects' % link + return f'/OS-INHERIT{link}/inherited_to_projects' return link @@ -1606,8 +1564,7 @@ class AssignmentTestMixin: if attribs.get('group_id'): entity['links']['membership'] = '/groups/{}/users/{}'.format( - attribs['group_id'], - attribs['user_id'], + attribs['group_id'], attribs['user_id'] ) else: entity['group'] = {'id': attribs['group_id']} diff --git a/keystone/tests/unit/test_v3_application_credential.py b/keystone/tests/unit/test_v3_application_credential.py index 468c240207..803c7c2a4b 100644 --- a/keystone/tests/unit/test_v3_application_credential.py +++ b/keystone/tests/unit/test_v3_application_credential.py @@ -63,7 +63,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles) token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -89,7 +89,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles) token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -111,7 +111,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles, secret=secret) token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -123,7 +123,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body() token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -146,7 +146,9 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles) token = self.get_scoped_token() c.post( - '/v3/users/%s/application_credentials' % wrong_user['id'], + '/v3/users/{}/application_credentials'.format( + wrong_user['id'] + ), json=app_cred_body, expected_status_code=http.client.FORBIDDEN, headers={'X-Auth-Token': token}, @@ -158,7 +160,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles) token = self.get_scoped_token() c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.BAD_REQUEST, headers={'X-Auth-Token': token}, @@ -172,7 +174,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles, expires=expires) token = self.get_scoped_token() c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -185,7 +187,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles, expires=expires) token = self.get_scoped_token() c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.BAD_REQUEST, headers={'X-Auth-Token': token}, @@ -198,7 +200,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles, expires=expires) token = self.get_scoped_token() c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.BAD_REQUEST, headers={'X-Auth-Token': token}, @@ -210,7 +212,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body_1 = self._app_cred_body(roles=roles) token = self.get_scoped_token() app_cred_1 = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body_1, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -225,7 +227,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body_2 = self._app_cred_body(roles=roles) token = token_data.headers['x-subject-token'] c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body_2, expected_status_code=http.client.FORBIDDEN, headers={'X-Auth-Token': token}, @@ -264,7 +266,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): # only the roles from the trust token should be allowed, even if # the user has the role assigned on the project c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', headers={'X-Auth-Token': trust_token}, json=app_cred, expected_status_code=http.client.BAD_REQUEST, @@ -277,7 +279,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body_1['application_credential']['unrestricted'] = True token = self.get_scoped_token() app_cred_1 = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body_1, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -291,7 +293,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): ) app_cred_body_2 = self._app_cred_body(roles=roles) c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body_2, expected_status_code=http.client.CREATED, headers={ @@ -302,11 +304,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): def test_create_application_credential_with_access_rules(self): roles = [{'id': self.role_id}] access_rules = [ - { - 'path': '/v3/projects', - 'method': 'POST', - 'service': 'identity', - } + {'path': '/v3/projects', 'method': 'POST', 'service': 'identity'} ] app_cred_body = self._app_cred_body( roles=roles, access_rules=access_rules @@ -314,7 +312,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): with self.test_client() as c: token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', headers={'X-Auth-Token': token}, json=app_cred_body, expected_status_code=http.client.CREATED, @@ -326,7 +324,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): access_rule_id = resp_access_rules[0].pop('id') self.assertEqual(access_rules[0], resp_access_rules[0]) resp = c.get( - '/v3/users/%s/access_rules' % self.user_id, + f'/v3/users/{self.user_id}/access_rules', headers={'X-Auth-Token': token}, ) resp_access_rule = resp.json['access_rules'][0] @@ -334,8 +332,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): resp_access_rule.pop('links') self.assertEqual(access_rules[0], resp_access_rule) resp = c.get( - '/v3/users/%s/access_rules/%s' - % (self.user_id, access_rule_id), + f'/v3/users/{self.user_id}/access_rules/{access_rule_id}', headers={'X-Auth-Token': token}, ) resp_access_rule = resp.json['access_rule'] @@ -344,30 +341,23 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): self.assertEqual(access_rules[0], resp_access_rule) # can't delete an access rule in use c.delete( - '/v3/users/%s/access_rules/%s' - % (self.user_id, access_rule_id), + f'/v3/users/{self.user_id}/access_rules/{access_rule_id}', headers={'X-Auth-Token': token}, expected_status_code=http.client.FORBIDDEN, ) c.delete( - '/v3/users/%s/application_credentials/%s' - % (self.user_id, app_cred_id), + f'/v3/users/{self.user_id}/application_credentials/{app_cred_id}', headers={'X-Auth-Token': token}, ) c.delete( - '/v3/users/%s/access_rules/%s' - % (self.user_id, access_rule_id), + f'/v3/users/{self.user_id}/access_rules/{access_rule_id}', headers={'X-Auth-Token': token}, ) def test_create_application_credential_with_duplicate_access_rule(self): roles = [{'id': self.role_id}] access_rules = [ - { - 'path': '/v3/projects', - 'method': 'POST', - 'service': 'identity', - } + {'path': '/v3/projects', 'method': 'POST', 'service': 'identity'} ] app_cred_body_1 = self._app_cred_body( roles=roles, access_rules=access_rules @@ -375,7 +365,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): with self.test_client() as c: token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', headers={'X-Auth-Token': token}, json=app_cred_body_1, expected_status_code=http.client.CREATED, @@ -391,7 +381,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): with self.test_client() as c: token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', headers={'X-Auth-Token': token}, json=app_cred_body_2, expected_status_code=http.client.CREATED, @@ -402,11 +392,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): def test_create_application_credential_with_access_rule_by_id(self): roles = [{'id': self.role_id}] access_rules = [ - { - 'path': '/v3/projects', - 'method': 'POST', - 'service': 'identity', - } + {'path': '/v3/projects', 'method': 'POST', 'service': 'identity'} ] app_cred_body_1 = self._app_cred_body( roles=roles, access_rules=access_rules @@ -414,7 +400,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): with self.test_client() as c: token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', headers={'X-Auth-Token': token}, json=app_cred_body_1, expected_status_code=http.client.CREATED, @@ -432,7 +418,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): with self.test_client() as c: token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', headers={'X-Auth-Token': token}, json=app_cred_body_2, expected_status_code=http.client.CREATED, @@ -444,7 +430,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): with self.test_client() as c: token = self.get_scoped_token() resp = c.get( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', expected_status_code=http.client.OK, headers={'X-Auth-Token': token}, ) @@ -452,13 +438,13 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): roles = [{'id': self.role_id}] app_cred_body = self._app_cred_body(roles=roles) c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, ) resp = c.get( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', expected_status_code=http.client.OK, headers={'X-Auth-Token': token}, ) @@ -469,13 +455,13 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): ) app_cred_body['application_credential']['name'] = 'two' c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, ) resp = c.get( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', expected_status_code=http.client.OK, headers={'X-Auth-Token': token}, ) @@ -493,7 +479,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): with self.test_client() as c: token = self.get_scoped_token() resp = c.get( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', expected_status_code=http.client.OK, headers={'X-Auth-Token': token}, ) @@ -501,19 +487,19 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): roles = [{'id': second_role['id']}] app_cred_body = self._app_cred_body(roles=roles) c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, ) resp = c.get( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', expected_status_code=http.client.OK, headers={'X-Auth-Token': token}, ) PROVIDERS.role_api.delete_role(second_role['id']) resp = c.get( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', expected_status_code=http.client.OK, headers={'X-Auth-Token': token}, ) @@ -525,9 +511,9 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): token = self.get_scoped_token() name = app_cred_body['application_credential']['name'] search_path = ( - '/v3/users/%(user_id)s/application_credentials?' - 'name=%(name)s' - ) % {'user_id': self.user_id, 'name': name} + f'/v3/users/{self.user_id}/application_credentials?' + f'name={name}' + ) resp = c.get( search_path, expected_status_code=http.client.OK, @@ -535,7 +521,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): ) self.assertEqual([], resp.json['application_credentials']) resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -552,7 +538,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): ) app_cred_body['application_credential']['name'] = 'two' c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -573,15 +559,14 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles) token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, ) app_cred_id = resp.json['application_credential']['id'] c.head( - '/v3%s' - % MEMBER_PATH_FMT + f'/v3{MEMBER_PATH_FMT}' % {'user_id': self.user_id, 'app_cred_id': app_cred_id}, expected_status_code=http.client.OK, headers={'X-Auth-Token': token}, @@ -589,8 +574,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): expected_response = resp.json expected_response['application_credential'].pop('secret') resp = c.get( - '/v3%s' - % MEMBER_PATH_FMT + f'/v3{MEMBER_PATH_FMT}' % {'user_id': self.user_id, 'app_cred_id': app_cred_id}, expected_status_code=http.client.OK, headers={'X-Auth-Token': token}, @@ -601,15 +585,13 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): with self.test_client() as c: token = self.get_scoped_token() c.head( - '/v3%s' - % MEMBER_PATH_FMT + f'/v3{MEMBER_PATH_FMT}' % {'user_id': self.user_id, 'app_cred_id': uuid.uuid4().hex}, expected_status_code=http.client.NOT_FOUND, headers={'X-Auth-Token': token}, ) c.get( - '/v3%s' - % MEMBER_PATH_FMT + f'/v3{MEMBER_PATH_FMT}' % {'user_id': self.user_id, 'app_cred_id': uuid.uuid4().hex}, expected_status_code=http.client.NOT_FOUND, headers={'X-Auth-Token': token}, @@ -621,15 +603,14 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles) token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, ) app_cred_id = resp.json['application_credential']['id'] c.delete( - '/v3%s' - % MEMBER_PATH_FMT + f'/v3{MEMBER_PATH_FMT}' % {'user_id': self.user_id, 'app_cred_id': app_cred_id}, expected_status_code=http.client.NO_CONTENT, headers={'X-Auth-Token': token}, @@ -639,8 +620,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): with self.test_client() as c: token = self.get_scoped_token() c.delete( - '/v3%s' - % MEMBER_PATH_FMT + f'/v3{MEMBER_PATH_FMT}' % {'user_id': self.user_id, 'app_cred_id': uuid.uuid4().hex}, expected_status_code=http.client.NOT_FOUND, headers={'X-Auth-Token': token}, @@ -652,7 +632,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles) token = self.get_scoped_token() app_cred = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -664,16 +644,10 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): token_data = self.v3_create_token( auth_data, expected_status=http.client.CREATED ) - member_path = ( - '/v3%s' - % MEMBER_PATH_FMT - % { - 'user_id': self.user_id, - 'app_cred_id': app_cred.json['application_credential'][ - 'id' - ], - } - ) + member_path = f'/v3{MEMBER_PATH_FMT}' % { + 'user_id': self.user_id, + 'app_cred_id': app_cred.json['application_credential']['id'], + } token = token_data.headers['x-subject-token'] c.delete( member_path, @@ -689,7 +663,7 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body['application_credential']['unrestricted'] = True token = self.get_scoped_token() app_cred = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, @@ -701,16 +675,10 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): token_data = self.v3_create_token( auth_data, expected_status=http.client.CREATED ) - member_path = ( - '/v3%s' - % MEMBER_PATH_FMT - % { - 'user_id': self.user_id, - 'app_cred_id': app_cred.json['application_credential'][ - 'id' - ], - } - ) + member_path = f'/v3{MEMBER_PATH_FMT}' % { + 'user_id': self.user_id, + 'app_cred_id': app_cred.json['application_credential']['id'], + } c.delete( member_path, json=app_cred_body, @@ -726,24 +694,23 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): app_cred_body = self._app_cred_body(roles=roles) token = self.get_scoped_token() resp = c.post( - '/v3/users/%s/application_credentials' % self.user_id, + f'/v3/users/{self.user_id}/application_credentials', json=app_cred_body, expected_status_code=http.client.CREATED, headers={'X-Auth-Token': token}, ) # Application credentials are immutable - app_cred_body['application_credential'][ - 'description' - ] = "New Things" + app_cred_body['application_credential']['description'] = ( + "New Things" + ) app_cred_id = resp.json['application_credential']['id'] # NOTE(morgan): when the whole test case is converted to using # flask test_client, this extra v3 prefix will # need to be rolled into the base MEMBER_PATH_FMT - member_path = ( - '/v3%s' - % MEMBER_PATH_FMT - % {'user_id': self.user_id, 'app_cred_id': app_cred_id} - ) + member_path = f'/v3{MEMBER_PATH_FMT}' % { + 'user_id': self.user_id, + 'app_cred_id': app_cred_id, + } c.patch( member_path, json=app_cred_body, diff --git a/keystone/tests/unit/test_v3_assignment.py b/keystone/tests/unit/test_v3_assignment.py index a7549298c8..ee6f31017f 100644 --- a/keystone/tests/unit/test_v3_assignment.py +++ b/keystone/tests/unit/test_v3_assignment.py @@ -31,7 +31,6 @@ PROVIDERS = provider_api.ProviderAPIs class SystemRoleAssignmentMixin: - def _create_new_role(self): """Create a role available for use anywhere and return the ID.""" ref = unit.new_role_ref() @@ -105,10 +104,7 @@ class AssignmentTestCase( """Call ``PATCH /roles/{role_id}``.""" ref = unit.new_role_ref() del ref['id'] - r = self.patch( - f'/roles/{self.role_id}', - body={'role': ref}, - ) + r = self.patch(f'/roles/{self.role_id}', body={'role': ref}) self.assertValidRoleResponse(r, ref) def test_delete_role(self): @@ -122,12 +118,10 @@ class AssignmentTestCase( PROVIDERS.role_api.create_role(role['id'], role) collection_url = '/projects/{project_id}/users/{user_id}/roles'.format( - project_id=self.project['id'], - user_id=self.user['id'], + project_id=self.project['id'], user_id=self.user['id'] ) member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=role['id'], + collection_url=collection_url, role_id=role['id'] ) # There is a role assignment for self.user on self.project @@ -159,13 +153,9 @@ class AssignmentTestCase( user_id = uuid.uuid4().hex collection_url = '/projects/{project_id}/users/{user_id}/roles'.format( - project_id=self.project['id'], - user_id=user_id, - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + project_id=self.project['id'], user_id=user_id ) + member_url = f'{collection_url}/{self.role_id}' self.put(member_url, expected_status=http.client.NOT_FOUND) self.head(member_url, expected_status=http.client.NOT_FOUND) @@ -175,13 +165,11 @@ class AssignmentTestCase( time = timeutils.utcnow() with freezegun.freeze_time(time) as frozen_datetime: collection_url = ( - '/domains/%(domain_id)s/users/%(user_id)s/roles' - % {'domain_id': self.domain_id, 'user_id': self.user['id']} - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + '/domains/{domain_id}/users/{user_id}/roles'.format( + domain_id=self.domain_id, user_id=self.user['id'] + ) ) + member_url = f'{collection_url}/{self.role_id}' self.put(member_url) self.head(member_url) @@ -213,14 +201,8 @@ class AssignmentTestCase( """ user_id = uuid.uuid4().hex - collection_url = '/domains/{domain_id}/users/{user_id}/roles'.format( - domain_id=self.domain_id, - user_id=user_id, - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, - ) + collection_url = f'/domains/{self.domain_id}/users/{user_id}/roles' + member_url = f'{collection_url}/{self.role_id}' self.put(member_url, expected_status=http.client.NOT_FOUND) self.head(member_url, expected_status=http.client.NOT_FOUND) @@ -230,13 +212,9 @@ class AssignmentTestCase( time = timeutils.utcnow() with freezegun.freeze_time(time) as frozen_datetime: collection_url = ( - '/projects/%(project_id)s/groups/%(group_id)s/roles' - % {'project_id': self.project_id, 'group_id': self.group_id} - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + f'/projects/{self.project_id}/groups/{self.group_id}/roles' ) + member_url = f'{collection_url}/{self.role_id}' self.put(member_url) self.head(member_url) @@ -268,14 +246,8 @@ class AssignmentTestCase( """ group_id = uuid.uuid4().hex - collection_url = ( - '/projects/%(project_id)s/groups/%(group_id)s/roles' - % {'project_id': self.project_id, 'group_id': group_id} - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, - ) + collection_url = f'/projects/{self.project_id}/groups/{group_id}/roles' + member_url = f'{collection_url}/{self.role_id}' self.put(member_url, expected_status=http.client.NOT_FOUND) self.head(member_url, expected_status=http.client.NOT_FOUND) @@ -285,13 +257,9 @@ class AssignmentTestCase( time = timeutils.utcnow() with freezegun.freeze_time(time) as frozen_datetime: collection_url = ( - '/domains/%(domain_id)s/groups/%(group_id)s/roles' - % {'domain_id': self.domain_id, 'group_id': self.group_id} - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + f'/domains/{self.domain_id}/groups/{self.group_id}/roles' ) + member_url = f'{collection_url}/{self.role_id}' self.put(member_url) self.head(member_url) @@ -323,14 +291,8 @@ class AssignmentTestCase( """ group_id = uuid.uuid4().hex - collection_url = '/domains/{domain_id}/groups/{group_id}/roles'.format( - domain_id=self.domain_id, - group_id=group_id, - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, - ) + collection_url = f'/domains/{self.domain_id}/groups/{group_id}/roles' + member_url = f'{collection_url}/{self.role_id}' self.put(member_url, expected_status=http.client.NOT_FOUND) self.head(member_url, expected_status=http.client.NOT_FOUND) @@ -343,13 +305,9 @@ class AssignmentTestCase( user_ref = PROVIDERS.identity_api.create_user(new_user) # Assign the user a role on the project collection_url = '/projects/{project_id}/users/{user_id}/roles'.format( - project_id=self.project_id, - user_id=user_ref['id'], - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + project_id=self.project_id, user_id=user_ref['id'] ) + member_url = f'{collection_url}/{self.role_id}' self.put(member_url) # Check the user has the role assigned self.head(member_url) @@ -377,13 +335,11 @@ class AssignmentTestCase( # Assign the user a role on the project collection_url = ( - '/projects/%(project_id)s/groups/%(group_id)s/roles' - % {'project_id': self.project_id, 'group_id': group_ref['id']} - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + '/projects/{project_id}/groups/{group_id}/roles'.format( + project_id=self.project_id, group_id=group_ref['id'] + ) ) + member_url = f'{collection_url}/{self.role_id}' self.put(member_url) # Check the user has the role assigned @@ -402,8 +358,7 @@ class AssignmentTestCase( system_role = self._create_new_role() user = self._create_user() path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=user['id'], - role_id=system_role, + user_id=user['id'], role_id=system_role ) self.put(path) @@ -495,8 +450,7 @@ class AssignmentTestCase( system_role = self._create_new_role() group = self._create_group() path = '/system/groups/{group_id}/roles/{role_id}'.format( - group_id=group['id'], - role_id=system_role, + group_id=group['id'], role_id=system_role ) self.put(path) @@ -521,13 +475,9 @@ class AssignmentTestCase( PROVIDERS.resource_api.create_project(new_project['id'], new_project) collection_url = '/projects/{project_id}/users/{user_id}/roles'.format( - project_id=new_project['id'], - user_id=self.user['id'], - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + project_id=new_project['id'], user_id=self.user['id'] ) + member_url = f'{collection_url}/{self.role_id}' # create the user a grant on the new project self.put(member_url) @@ -554,13 +504,9 @@ class AssignmentTestCase( PROVIDERS.resource_api.create_domain(new_domain['id'], new_domain) collection_url = '/domains/{domain_id}/users/{user_id}/roles'.format( - domain_id=new_domain['id'], - user_id=self.user['id'], - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + domain_id=new_domain['id'], user_id=self.user['id'] ) + member_url = f'{collection_url}/{self.role_id}' # create the user a grant on the new domain self.put(member_url) @@ -587,13 +533,11 @@ class AssignmentTestCase( PROVIDERS.resource_api.create_project(new_project['id'], new_project) collection_url = ( - '/projects/%(project_id)s/groups/%(group_id)s/roles' - % {'project_id': new_project['id'], 'group_id': self.group['id']} - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + '/projects/{project_id}/groups/{group_id}/roles'.format( + project_id=new_project['id'], group_id=self.group['id'] + ) ) + member_url = f'{collection_url}/{self.role_id}' # create the group a grant on the new project self.put(member_url) @@ -620,13 +564,9 @@ class AssignmentTestCase( PROVIDERS.resource_api.create_domain(new_domain['id'], new_domain) collection_url = '/domains/{domain_id}/groups/{group_id}/roles'.format( - domain_id=new_domain['id'], - group_id=self.group['id'], - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + domain_id=new_domain['id'], group_id=self.group['id'] ) + member_url = f'{collection_url}/{self.role_id}' # create the group a grant on the new domain self.put(member_url) @@ -1032,8 +972,8 @@ class AssignmentTestCase( # Now list by various filters to make sure we get back the right ones - collection_url = ( - '/role_assignments?scope.project.id=%s' % project1['id'] + collection_url = '/role_assignments?scope.project.id={}'.format( + project1['id'] ) r = self.get(collection_url, expected_status=http.client.OK) self.head(collection_url, expected_status=http.client.OK) @@ -1043,8 +983,8 @@ class AssignmentTestCase( self.assertRoleAssignmentInListResponse(r, up_entity) self.assertRoleAssignmentInListResponse(r, gp_entity) - collection_url = ( - '/role_assignments?scope.domain.id=%s' % self.domain['id'] + collection_url = '/role_assignments?scope.domain.id={}'.format( + self.domain['id'] ) r = self.get(collection_url, expected_status=http.client.OK) self.head(collection_url, expected_status=http.client.OK) @@ -1054,7 +994,7 @@ class AssignmentTestCase( self.assertRoleAssignmentInListResponse(r, ud_entity) self.assertRoleAssignmentInListResponse(r, gd_entity) - collection_url = '/role_assignments?user.id=%s' % user1['id'] + collection_url = '/role_assignments?user.id={}'.format(user1['id']) r = self.get(collection_url, expected_status=http.client.OK) self.head(collection_url, expected_status=http.client.OK) self.assertValidRoleAssignmentListResponse( @@ -1063,7 +1003,7 @@ class AssignmentTestCase( self.assertRoleAssignmentInListResponse(r, up_entity) self.assertRoleAssignmentInListResponse(r, ud_entity) - collection_url = '/role_assignments?group.id=%s' % group1['id'] + collection_url = '/role_assignments?group.id={}'.format(group1['id']) r = self.get(collection_url, expected_status=http.client.OK) self.head(collection_url, expected_status=http.client.OK) self.assertValidRoleAssignmentListResponse( @@ -1072,7 +1012,9 @@ class AssignmentTestCase( self.assertRoleAssignmentInListResponse(r, gd_entity) self.assertRoleAssignmentInListResponse(r, gp_entity) - collection_url = '/role_assignments?role.id=%s' % self.role1['id'] + collection_url = '/role_assignments?role.id={}'.format( + self.role1['id'] + ) r = self.get(collection_url, expected_status=http.client.OK) self.head(collection_url, expected_status=http.client.OK) self.assertValidRoleAssignmentListResponse( @@ -1082,7 +1024,9 @@ class AssignmentTestCase( self.assertRoleAssignmentInListResponse(r, gp_entity) self.assertRoleAssignmentInListResponse(r, gs_entity) - collection_url = '/role_assignments?role.id=%s' % self.role2['id'] + collection_url = '/role_assignments?role.id={}'.format( + self.role2['id'] + ) r = self.get(collection_url, expected_status=http.client.OK) self.head(collection_url, expected_status=http.client.OK) self.assertValidRoleAssignmentListResponse( @@ -1095,9 +1039,10 @@ class AssignmentTestCase( # Let's try combining two filers together.... collection_url = ( - '/role_assignments?user.id=%(user_id)s' - '&scope.project.id=%(project_id)s' - % {'user_id': user1['id'], 'project_id': project1['id']} + '/role_assignments?user.id={user_id}' + '&scope.project.id={project_id}'.format( + user_id=user1['id'], project_id=project1['id'] + ) ) r = self.get(collection_url, expected_status=http.client.OK) self.head(collection_url, expected_status=http.client.OK) @@ -1110,7 +1055,9 @@ class AssignmentTestCase( # roles - this should return role assignment that were directly # assigned as well as by virtue of group membership - collection_url = '/role_assignments?effective&user.id=%s' % user1['id'] + collection_url = '/role_assignments?effective&user.id={}'.format( + user1['id'] + ) r = self.get(collection_url, expected_status=http.client.OK) self.head(collection_url, expected_status=http.client.OK) self.assertValidRoleAssignmentListResponse( @@ -1151,9 +1098,10 @@ class AssignmentTestCase( # scoped token. collection_url = ( - '/role_assignments?effective&user.id=%(user_id)s' - '&scope.project.id=%(project_id)s' - % {'user_id': user1['id'], 'project_id': project1['id']} + '/role_assignments?effective&user.id={user_id}' + '&scope.project.id={project_id}'.format( + user_id=user1['id'], project_id=project1['id'] + ) ) r = self.get(collection_url, expected_status=http.client.OK) self.head(collection_url, expected_status=http.client.OK) @@ -1181,15 +1129,11 @@ class AssignmentTestCase( ) self.put(url) url = '/domains/{}/users/{}/roles/{}'.format( - self.domain_id, - user['id'], - user_domain_role_id, + self.domain_id, user['id'], user_domain_role_id ) self.put(url) url = '/projects/{}/users/{}/roles/{}'.format( - self.project_id, - user['id'], - user_project_role_id, + self.project_id, user['id'], user_project_role_id ) self.put(url) @@ -1197,20 +1141,15 @@ class AssignmentTestCase( # project group = self._create_group() url = '/system/groups/{}/roles/{}'.format( - group['id'], - group_system_role_id, + group['id'], group_system_role_id ) self.put(url) url = '/domains/{}/groups/{}/roles/{}'.format( - self.domain_id, - group['id'], - group_domain_role_id, + self.domain_id, group['id'], group_domain_role_id ) self.put(url) url = '/projects/{}/groups/{}/roles/{}'.format( - self.project_id, - group['id'], - group_project_role_id, + self.project_id, group['id'], group_project_role_id ) self.put(url) @@ -1228,7 +1167,9 @@ class AssignmentTestCase( # /v3/role_assignments?scope_system=all&user.id=$USER_ID should return # one role assignment - url = '/role_assignments?scope.system=all&user.id=%s' % user['id'] + url = '/role_assignments?scope.system=all&user.id={}'.format( + user['id'] + ) response = self.get(url) self.assertValidRoleAssignmentListResponse(response, expected_length=1) self.assertEqual( @@ -1238,7 +1179,9 @@ class AssignmentTestCase( # /v3/role_assignments?scope_system=all&group.id=$GROUP_ID should # return one role assignment - url = '/role_assignments?scope.system=all&group.id=%s' % group['id'] + url = '/role_assignments?scope.system=all&group.id={}'.format( + group['id'] + ) response = self.get(url) self.assertValidRoleAssignmentListResponse(response, expected_length=1) self.assertEqual( @@ -1248,7 +1191,7 @@ class AssignmentTestCase( # /v3/role_assignments?user.id=$USER_ID should return 3 assignments # and system should be in that list of assignments - url = '/role_assignments?user.id=%s' % user['id'] + url = '/role_assignments?user.id={}'.format(user['id']) response = self.get(url) self.assertValidRoleAssignmentListResponse(response, expected_length=3) for assignment in response.json_body['role_assignments']: @@ -1263,7 +1206,7 @@ class AssignmentTestCase( # /v3/role_assignments?group.id=$GROUP_ID should return 3 assignments # and system should be in that list of assignments - url = '/role_assignments?group.id=%s' % group['id'] + url = '/role_assignments?group.id={}'.format(group['id']) response = self.get(url) self.assertValidRoleAssignmentListResponse(response, expected_length=3) for assignment in response.json_body['role_assignments']: @@ -1873,12 +1816,10 @@ class AssignmentInheritanceTestCase( # Define URLs direct_url = '{}/users/{}/roles/{}'.format( - target_url, - self.user_id, - role['id'], + target_url, self.user_id, role['id'] ) - inherited_url = ( - '/OS-INHERIT/%s/inherited_to_projects' % direct_url.lstrip('/') + inherited_url = '/OS-INHERIT/{}/inherited_to_projects'.format( + direct_url.lstrip('/') ) # Create the direct assignment @@ -1910,12 +1851,12 @@ class AssignmentInheritanceTestCase( def test_crud_inherited_and_direct_assignment_on_domains(self): self._test_crud_inherited_and_direct_assignment_on_target( - '/domains/%s' % self.domain_id + f'/domains/{self.domain_id}' ) def test_crud_inherited_and_direct_assignment_on_projects(self): self._test_crud_inherited_and_direct_assignment_on_target( - '/projects/%s' % self.project_id + f'/projects/{self.project_id}' ) def test_crud_user_inherited_domain_role_grants(self): @@ -1933,12 +1874,12 @@ class AssignmentInheritanceTestCase( ) base_collection_url = ( - '/OS-INHERIT/domains/%(domain_id)s/users/%(user_id)s/roles' - % {'domain_id': self.domain_id, 'user_id': self.user['id']} + '/OS-INHERIT/domains/{domain_id}/users/{user_id}/roles'.format( + domain_id=self.domain_id, user_id=self.user['id'] + ) ) member_url = '{collection_url}/{role_id}/inherited_to_projects'.format( - collection_url=base_collection_url, - role_id=role_list[0]['id'], + collection_url=base_collection_url, role_id=role_list[0]['id'] ) collection_url = base_collection_url + '/inherited_to_projects' @@ -2003,12 +1944,12 @@ class AssignmentInheritanceTestCase( # Now create our inherited role on the domain base_collection_url = ( - '/OS-INHERIT/domains/%(domain_id)s/users/%(user_id)s/roles' - % {'domain_id': domain['id'], 'user_id': user1['id']} + '/OS-INHERIT/domains/{domain_id}/users/{user_id}/roles'.format( + domain_id=domain['id'], user_id=user1['id'] + ) ) member_url = '{collection_url}/{role_id}/inherited_to_projects'.format( - collection_url=base_collection_url, - role_id=role_list[3]['id'], + collection_url=base_collection_url, role_id=role_list[3]['id'] ) collection_url = base_collection_url + '/inherited_to_projects' @@ -2023,9 +1964,10 @@ class AssignmentInheritanceTestCase( # Now use the list domain role assignments api to check if this # is included collection_url = ( - '/role_assignments?user.id=%(user_id)s' - '&scope.domain.id=%(domain_id)s' - % {'user_id': user1['id'], 'domain_id': domain['id']} + '/role_assignments?user.id={user_id}' + '&scope.domain.id={domain_id}'.format( + user_id=user1['id'], domain_id=domain['id'] + ) ) r = self.get(collection_url) self.assertValidRoleAssignmentListResponse( @@ -2043,9 +1985,10 @@ class AssignmentInheritanceTestCase( # turn into a project role, along with the two direct roles that are # on the project collection_url = ( - '/role_assignments?effective&user.id=%(user_id)s' - '&scope.project.id=%(project_id)s' - % {'user_id': user1['id'], 'project_id': project1['id']} + '/role_assignments?effective&user.id={user_id}' + '&scope.project.id={project_id}'.format( + user_id=user1['id'], project_id=project1['id'] + ) ) r = self.get(collection_url) self.assertValidRoleAssignmentListResponse( @@ -2105,28 +2048,30 @@ class AssignmentInheritanceTestCase( self.put(expected_entity4['links']['assignment']) collection_url_domain = ( - '/role_assignments?include_names&scope.domain.id=%(domain_id)s' - % {'domain_id': self.domain_id} + f'/role_assignments?include_names&scope.domain.id={self.domain_id}' ) rs_domain = self.get(collection_url_domain) collection_url_project = ( '/role_assignments?include_names&' - 'scope.project.id=%(project_id)s' % {'project_id': project1['id']} + 'scope.project.id={project_id}'.format(project_id=project1['id']) ) rs_project = self.get(collection_url_project) collection_url_group = ( - '/role_assignments?include_names&group.id=%(group_id)s' - % {'group_id': group['id']} + '/role_assignments?include_names&group.id={group_id}'.format( + group_id=group['id'] + ) ) rs_group = self.get(collection_url_group) collection_url_user = ( - '/role_assignments?include_names&user.id=%(user_id)s' - % {'user_id': user1['id']} + '/role_assignments?include_names&user.id={user_id}'.format( + user_id=user1['id'] + ) ) rs_user = self.get(collection_url_user) collection_url_role = ( - '/role_assignments?include_names&role.id=%(role_id)s' - % {'role_id': role1['id']} + '/role_assignments?include_names&role.id={role_id}'.format( + role_id=role1['id'] + ) ) rs_role = self.get(collection_url_role) # Make sure all entities were created successfully @@ -2207,8 +2152,8 @@ class AssignmentInheritanceTestCase( self.put(assignment_domain['links']['assignment']) self.put(assignment_project['links']['assignment']) - collection_url = '/role_assignments?user.id=%(user_id)s' % ( - {'user_id': user['id']} + collection_url = '/role_assignments?user.id={user_id}'.format( + user_id=user['id'] ) result = self.get(collection_url) # We have two role assignments based in both roles for the domain and @@ -2219,14 +2164,12 @@ class AssignmentInheritanceTestCase( self.assertRoleAssignmentInListResponse(result, assignment_domain) domain_url = '/domains/{}/users/{}/roles/{}'.format( - domain['id'], - user['id'], - role['id'], + domain['id'], user['id'], role['id'] ) self.delete(domain_url) - collection_url = '/role_assignments?user.id=%(user_id)s' % ( - {'user_id': user['id']} + collection_url = '/role_assignments?user.id={user_id}'.format( + user_id=user['id'] ) result = self.get(collection_url) # Now we only have one assignment for the project scope since the @@ -2283,8 +2226,8 @@ class AssignmentInheritanceTestCase( self.put(assignment['links']['assignment']) - collection_url = '/role_assignments?user.id=%(user_id)s' % ( - {'user_id': user['id']} + collection_url = '/role_assignments?user.id={user_id}'.format( + user_id=user['id'] ) result = self.get(collection_url) self.assertValidRoleAssignmentListResponse( @@ -2293,8 +2236,9 @@ class AssignmentInheritanceTestCase( self.assertRoleAssignmentInListResponse(result, assignment) collection_url = ( - '/role_assignments?include_names&' - 'user.id=%(user_id)s' % {'user_id': user['id']} + '/role_assignments?include_names&' 'user.id={user_id}'.format( + user_id=user['id'] + ) ) result = self.get(collection_url) self.assertValidRoleAssignmentListResponse( @@ -2344,12 +2288,12 @@ class AssignmentInheritanceTestCase( # Now create our inherited role on the domain base_collection_url = ( - '/OS-INHERIT/domains/%(domain_id)s/users/%(user_id)s/roles' - % {'domain_id': domain['id'], 'user_id': user1['id']} + '/OS-INHERIT/domains/{domain_id}/users/{user_id}/roles'.format( + domain_id=domain['id'], user_id=user1['id'] + ) ) member_url = '{collection_url}/{role_id}/inherited_to_projects'.format( - collection_url=base_collection_url, - role_id=role_list[3]['id'], + collection_url=base_collection_url, role_id=role_list[3]['id'] ) collection_url = base_collection_url + '/inherited_to_projects' @@ -2365,9 +2309,10 @@ class AssignmentInheritanceTestCase( # turn into a project role, along with the two direct roles that are # on the project collection_url = ( - '/role_assignments?effective&user.id=%(user_id)s' - '&scope.project.id=%(project_id)s' - % {'user_id': user1['id'], 'project_id': project1['id']} + '/role_assignments?effective&user.id={user_id}' + '&scope.project.id={project_id}'.format( + user_id=user1['id'], project_id=project1['id'] + ) ) r = self.get(collection_url) self.assertValidRoleAssignmentListResponse( @@ -2441,12 +2386,12 @@ class AssignmentInheritanceTestCase( # Now create our inherited role on the domain base_collection_url = ( - '/OS-INHERIT/domains/%(domain_id)s/groups/%(group_id)s/roles' - % {'domain_id': domain['id'], 'group_id': group1['id']} + '/OS-INHERIT/domains/{domain_id}/groups/{group_id}/roles'.format( + domain_id=domain['id'], group_id=group1['id'] + ) ) member_url = '{collection_url}/{role_id}/inherited_to_projects'.format( - collection_url=base_collection_url, - role_id=role_list[3]['id'], + collection_url=base_collection_url, role_id=role_list[3]['id'] ) collection_url = base_collection_url + '/inherited_to_projects' @@ -2461,9 +2406,10 @@ class AssignmentInheritanceTestCase( # Now use the list domain role assignments api to check if this # is included collection_url = ( - '/role_assignments?group.id=%(group_id)s' - '&scope.domain.id=%(domain_id)s' - % {'group_id': group1['id'], 'domain_id': domain['id']} + '/role_assignments?group.id={group_id}' + '&scope.domain.id={domain_id}'.format( + group_id=group1['id'], domain_id=domain['id'] + ) ) r = self.get(collection_url) self.assertValidRoleAssignmentListResponse( @@ -2481,9 +2427,10 @@ class AssignmentInheritanceTestCase( # turn into a user project role, along with the two direct roles # that are on the project collection_url = ( - '/role_assignments?effective&user.id=%(user_id)s' - '&scope.project.id=%(project_id)s' - % {'user_id': user1['id'], 'project_id': project1['id']} + '/role_assignments?effective&user.id={user_id}' + '&scope.project.id={project_id}'.format( + user_id=user1['id'], project_id=project1['id'] + ) ) r = self.get(collection_url) self.assertValidRoleAssignmentListResponse( @@ -2546,12 +2493,12 @@ class AssignmentInheritanceTestCase( # Now create two inherited roles on the domain, one for a user # and one for a domain base_collection_url = ( - '/OS-INHERIT/domains/%(domain_id)s/users/%(user_id)s/roles' - % {'domain_id': domain['id'], 'user_id': user1['id']} + '/OS-INHERIT/domains/{domain_id}/users/{user_id}/roles'.format( + domain_id=domain['id'], user_id=user1['id'] + ) ) member_url = '{collection_url}/{role_id}/inherited_to_projects'.format( - collection_url=base_collection_url, - role_id=role_list[3]['id'], + collection_url=base_collection_url, role_id=role_list[3]['id'] ) collection_url = base_collection_url + '/inherited_to_projects' @@ -2564,12 +2511,12 @@ class AssignmentInheritanceTestCase( ) base_collection_url = ( - '/OS-INHERIT/domains/%(domain_id)s/groups/%(group_id)s/roles' - % {'domain_id': domain['id'], 'group_id': group1['id']} + '/OS-INHERIT/domains/{domain_id}/groups/{group_id}/roles'.format( + domain_id=domain['id'], group_id=group1['id'] + ) ) member_url = '{collection_url}/{role_id}/inherited_to_projects'.format( - collection_url=base_collection_url, - role_id=role_list[4]['id'], + collection_url=base_collection_url, role_id=role_list[4]['id'] ) collection_url = base_collection_url + '/inherited_to_projects' @@ -2957,9 +2904,7 @@ class AssignmentInheritanceTestCase( # Without the subtree, we should get the one assignment on the # root project - collection_url = '/role_assignments?scope.project.id={project}'.format( - project=root_id - ) + collection_url = f'/role_assignments?scope.project.id={root_id}' r = self.get(collection_url) self.assertValidRoleAssignmentListResponse( r, resource_url=collection_url @@ -2970,8 +2915,8 @@ class AssignmentInheritanceTestCase( # With the subtree, we should get both assignments collection_url = ( - '/role_assignments?scope.project.id=%(project)s' - '&include_subtree=True' % {'project': root_id} + f'/role_assignments?scope.project.id={root_id}' + '&include_subtree=True' ) r = self.get(collection_url) self.assertValidRoleAssignmentListResponse( @@ -2985,8 +2930,8 @@ class AssignmentInheritanceTestCase( # With subtree=0, we should also only get the one assignment on the # root project collection_url = ( - '/role_assignments?scope.project.id=%(project)s' - '&include_subtree=0' % {'project': root_id} + f'/role_assignments?scope.project.id={root_id}' + '&include_subtree=0' ) r = self.get(collection_url) self.assertValidRoleAssignmentListResponse( @@ -3057,8 +3002,8 @@ class AssignmentInheritanceTestCase( # Get effective role assignments collection_url = ( - '/role_assignments?scope.project.id=%(project)s' - '&include_subtree=True&effective' % {'project': leaf_id} + f'/role_assignments?scope.project.id={leaf_id}' + '&include_subtree=True&effective' ) r = self.get(collection_url) self.assertValidRoleAssignmentListResponse( @@ -3154,7 +3099,7 @@ class ImpliedRolesTests( def test_list_implied_roles_none(self): self.prior = self._create_role() - url = '/roles/%s/implies' % (self.prior['id']) + url = '/roles/{}/implies'.format(self.prior['id']) response = self.get(url).json["role_inference"] self.head(url, expected_status=http.client.OK) self.assertEqual(self.prior['id'], response['prior_role']['id']) @@ -3179,7 +3124,7 @@ class ImpliedRolesTests( def _assert_expected_implied_role_response( self, expected_prior_id, expected_implied_ids ): - r = self.get('/roles/%s/implies' % expected_prior_id) + r = self.get(f'/roles/{expected_prior_id}/implies') response = r.json role_inference = response['role_inference'] self.assertEqual(expected_prior_id, role_inference['prior_role']['id']) @@ -3201,12 +3146,10 @@ class ImpliedRolesTests( def _assert_expected_role_inference_rule_response( self, expected_prior_id, expected_implied_id ): - url = '/roles/{}/implies/{}'.format( - expected_prior_id, expected_implied_id - ) + url = f'/roles/{expected_prior_id}/implies/{expected_implied_id}' response = self.get(url).json self.assertThat( - response['links']['self'], matchers.EndsWith('/v3%s' % url) + response['links']['self'], matchers.EndsWith(f'/v3{url}') ) role_inference = response['role_inference'] prior_role = role_inference['prior_role'] @@ -3214,14 +3157,14 @@ class ImpliedRolesTests( self.assertIsNotNone(prior_role['name']) self.assertThat( prior_role['links']['self'], - matchers.EndsWith('/v3/roles/%s' % expected_prior_id), + matchers.EndsWith(f'/v3/roles/{expected_prior_id}'), ) implied_role = role_inference['implies'] self.assertEqual(expected_implied_id, implied_role['id']) self.assertIsNotNone(implied_role['name']) self.assertThat( implied_role['links']['self'], - matchers.EndsWith('/v3/roles/%s' % expected_implied_id), + matchers.EndsWith(f'/v3/roles/{expected_implied_id}'), ) def _assert_two_roles_implied(self): @@ -3278,7 +3221,6 @@ class ImpliedRolesTests( self._assert_one_rule_defined() def test_CRD_implied_roles(self): - self._setup_prior_two_implied() self._assert_two_roles_implied() @@ -3568,7 +3510,7 @@ class DomainSpecificRoleTests(test_v3.RestfulTestCase, unit.TestCase): def test_get_and_list_domain_specific_roles(self): # Check we can get a domain specific role - r = self.get('/roles/%s' % self.domainA_role1['id']) + r = self.get('/roles/{}'.format(self.domainA_role1['id'])) self.assertValidRoleResponse(r, self.domainA_role1) # If we list without specifying a domain, we should only get global @@ -3584,7 +3526,7 @@ class DomainSpecificRoleTests(test_v3.RestfulTestCase, unit.TestCase): self.assertRoleNotInListResponse(r, self.domainB_role) # Now list those in domainA, making sure that's all we get back - r = self.get('/roles?domain_id=%s' % self.domainA['id']) + r = self.get('/roles?domain_id={}'.format(self.domainA['id'])) self.assertValidRoleListResponse(r, expected_length=2) self.assertRoleInListResponse(r, self.domainA_role1) self.assertRoleInListResponse(r, self.domainA_role2) @@ -3595,7 +3537,7 @@ class DomainSpecificRoleTests(test_v3.RestfulTestCase, unit.TestCase): '/roles/{role_id}'.format(role_id=self.domainA_role1['id']), body={'role': self.domainA_role1}, ) - r = self.get('/roles/%s' % self.domainA_role1['id']) + r = self.get('/roles/{}'.format(self.domainA_role1['id'])) self.assertValidRoleResponse(r, self.domainA_role1) def test_delete_domain_specific_roles(self): @@ -3605,11 +3547,11 @@ class DomainSpecificRoleTests(test_v3.RestfulTestCase, unit.TestCase): ) self.get( - '/roles/%s' % self.domainA_role1['id'], + '/roles/{}'.format(self.domainA_role1['id']), expected_status=http.client.NOT_FOUND, ) # Now re-list those in domainA, making sure there's only one left - r = self.get('/roles?domain_id=%s' % self.domainA['id']) + r = self.get('/roles?domain_id={}'.format(self.domainA['id'])) self.assertValidRoleListResponse(r, expected_length=1) self.assertRoleInListResponse(r, self.domainA_role2) @@ -3674,8 +3616,9 @@ class DomainSpecificRoleTests(test_v3.RestfulTestCase, unit.TestCase): # Now we create an implied rule from a role in domainA to a # role in domainB self.put( - '/roles/%s/implies/%s' - % (self.domainA_role1['id'], self.domainB_role['id']), + '/roles/{}/implies/{}'.format( + self.domainA_role1['id'], self.domainB_role['id'] + ), expected_status=http.client.CREATED, ) @@ -3769,7 +3712,7 @@ class ListUserProjectsTestCase(test_v3.RestfulTestCase): user = self.users[i] auth = self.auths[i] - url = '/users/%s/projects' % user['id'] + url = '/users/{}/projects'.format(user['id']) result = self.get(url, auth=auth) projects_result = result.json['projects'] self.assertEqual(1, len(projects_result)) @@ -3782,7 +3725,7 @@ class ListUserProjectsTestCase(test_v3.RestfulTestCase): auth = self.auths[i] # There are no disabled projects - url = '/users/%s/projects?enabled=True' % user['id'] + url = '/users/{}/projects?enabled=True'.format(user['id']) result = self.get(url, auth=auth) projects_result = result.json['projects'] self.assertEqual(1, len(projects_result)) @@ -3795,7 +3738,7 @@ class ListUserProjectsTestCase(test_v3.RestfulTestCase): project = self.projects[i] # There are no disabled projects - url = '/users/%s/projects?enabled=False' % user['id'] + url = '/users/{}/projects?enabled=False'.format(user['id']) result = self.get(url, auth=auth) self.assertEqual(0, len(result.json['projects'])) @@ -3815,16 +3758,14 @@ class ListUserProjectsTestCase(test_v3.RestfulTestCase): # Try looking for projects with a non-existent domain_id url = '/users/{}/projects?domain_id={}'.format( - user['id'], - uuid.uuid4().hex, + user['id'], uuid.uuid4().hex ) result = self.get(url, auth=auth) self.assertEqual(0, len(result.json['projects'])) # Now try a valid one url = '/users/{}/projects?domain_id={}'.format( - user['id'], - domain['id'], + user['id'], domain['id'] ) result = self.get(url, auth=auth) projects_result = result.json['projects'] @@ -3840,14 +3781,12 @@ class ListUserProjectsTestCase(test_v3.RestfulTestCase): class UserSystemRoleAssignmentTestCase( test_v3.RestfulTestCase, SystemRoleAssignmentMixin ): - def test_assign_system_role_to_user(self): system_role_id = self._create_new_role() # assign the user a role on the system member_url = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role_id, + user_id=self.user['id'], role_id=system_role_id ) self.put(member_url) @@ -3864,8 +3803,9 @@ class UserSystemRoleAssignmentTestCase( self.head(collection_url, expected_status=http.client.OK) response = self.get( - '/role_assignments?scope.system=all&user.id=%(user_id)s' - % {'user_id': self.user['id']} + '/role_assignments?scope.system=all&user.id={user_id}'.format( + user_id=self.user['id'] + ) ) self.assertValidRoleAssignmentListResponse(response) @@ -3874,16 +3814,16 @@ class UserSystemRoleAssignmentTestCase( # assign the user a role on the system member_url = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role_id, + user_id=self.user['id'], role_id=system_role_id ) self.put(member_url) # the response should contain one role assignment for the system role # and one for a role that was setup during setUp(). response = self.get( - '/role_assignments?user.id=%(user_id)s' - % {'user_id': self.user['id']} + '/role_assignments?user.id={user_id}'.format( + user_id=self.user['id'] + ) ) self.assertValidRoleAssignmentListResponse(response, expected_length=2) @@ -3899,8 +3839,9 @@ class UserSystemRoleAssignmentTestCase( self.assertEqual(response.json_body['roles'], []) response = self.get( - '/role_assignments?scope.system=all&user.id=%(user_id)s' - % {'user_id': self.user['id']} + '/role_assignments?scope.system=all&user.id={user_id}'.format( + user_id=self.user['id'] + ) ) self.assertEqual(len(response.json_body['role_assignments']), 0) self.assertValidRoleAssignmentListResponse(response) @@ -3910,16 +3851,16 @@ class UserSystemRoleAssignmentTestCase( # assign the user a role on the system member_url = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role_id, + user_id=self.user['id'], role_id=system_role_id ) self.put(member_url) # list project role assignments and save the role id of that # assignment, this assignment was created during setUp response = self.get( - '/projects/%(project_id)s/users/%(user_id)s/roles' - % {'project_id': self.project['id'], 'user_id': self.user['id']} + '/projects/{project_id}/users/{user_id}/roles'.format( + project_id=self.project['id'], user_id=self.user['id'] + ) ) self.assertEqual(len(response.json_body['roles']), 1) project_role_id = response.json_body['roles'][0]['id'] @@ -3938,8 +3879,9 @@ class UserSystemRoleAssignmentTestCase( # make sure the role_assignment API filters correctly based on system # scope response = self.get( - '/role_assignments?scope.system=all&user.id=%(user_id)s' - % {'user_id': self.user['id']} + '/role_assignments?scope.system=all&user.id={user_id}'.format( + user_id=self.user['id'] + ) ) self.assertEqual(len(response.json_body['role_assignments']), 1) system_assignment = response.json_body['role_assignments'][0] @@ -3949,9 +3891,9 @@ class UserSystemRoleAssignmentTestCase( # make sure the role_assignment API doesn't include the system role # assignment when we filter based on project path = ( - '/role_assignments?scope.project.id=%(project_id)s&' - 'user.id=%(user_id)s' - ) % {'project_id': self.project['id'], 'user_id': self.user['id']} + '/role_assignments?scope.project.id={project_id}&' + 'user.id={user_id}' + ).format(project_id=self.project['id'], user_id=self.user['id']) response = self.get(path) self.assertEqual(len(response.json_body['role_assignments']), 1) project_assignment = response.json_body['role_assignments'][0] @@ -3963,26 +3905,25 @@ class UserSystemRoleAssignmentTestCase( # assign a role to the user on a domain domain_member_url = ( - '/domains/%(domain_id)s/users/%(user_id)s/roles/%(role_id)s' - % { - 'domain_id': self.user['domain_id'], - 'user_id': self.user['id'], - 'role_id': domain_role_id, - } + '/domains/{domain_id}/users/{user_id}/roles/{role_id}'.format( + domain_id=self.user['domain_id'], + user_id=self.user['id'], + role_id=domain_role_id, + ) ) self.put(domain_member_url) # assign the user a role on the system member_url = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role_id, + user_id=self.user['id'], role_id=system_role_id ) self.put(member_url) # list domain role assignments response = self.get( - '/domains/%(domain_id)s/users/%(user_id)s/roles' - % {'domain_id': self.user['domain_id'], 'user_id': self.user['id']} + '/domains/{domain_id}/users/{user_id}/roles'.format( + domain_id=self.user['domain_id'], user_id=self.user['id'] + ) ) self.assertEqual(len(response.json_body['roles']), 1) @@ -4000,8 +3941,9 @@ class UserSystemRoleAssignmentTestCase( # make sure the role_assignment API filters correctly based on system # scope response = self.get( - '/role_assignments?scope.system=all&user.id=%(user_id)s' - % {'user_id': self.user['id']} + '/role_assignments?scope.system=all&user.id={user_id}'.format( + user_id=self.user['id'] + ) ) self.assertEqual(len(response.json_body['role_assignments']), 1) system_assignment = response.json_body['role_assignments'][0] @@ -4011,9 +3953,9 @@ class UserSystemRoleAssignmentTestCase( # make sure the role_assignment API doesn't include the system role # assignment when we filter based on domain path = ( - '/role_assignments?scope.domain.id=%(domain_id)s&' - 'user.id=%(user_id)s' - ) % {'domain_id': self.user['domain_id'], 'user_id': self.user['id']} + '/role_assignments?scope.domain.id={domain_id}&' + 'user.id={user_id}' + ).format(domain_id=self.user['domain_id'], user_id=self.user['id']) response = self.get(path) self.assertEqual(len(response.json_body['role_assignments']), 1) domain_assignment = response.json_body['role_assignments'][0] @@ -4024,8 +3966,7 @@ class UserSystemRoleAssignmentTestCase( # assign the user a role on the system member_url = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role_id, + user_id=self.user['id'], role_id=system_role_id ) self.put(member_url) @@ -4037,14 +3978,14 @@ class UserSystemRoleAssignmentTestCase( # check the user does't have the system role assignment member_url = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role_id, + user_id=self.user['id'], role_id=system_role_id ) self.head(member_url, expected_status=http.client.NOT_FOUND) response = self.get( - '/role_assignments?scope.system=all&user.id=%(user_id)s' - % {'user_id': self.user['id']} + '/role_assignments?scope.system=all&user.id={user_id}'.format( + user_id=self.user['id'] + ) ) self.assertEqual(len(response.json_body['role_assignments']), 0) self.assertValidRoleAssignmentListResponse(response) @@ -4054,8 +3995,7 @@ class UserSystemRoleAssignmentTestCase( # assign the user a role on the system member_url = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role_id, + user_id=self.user['id'], role_id=system_role_id ) self.put(member_url) @@ -4063,8 +4003,9 @@ class UserSystemRoleAssignmentTestCase( self.head(member_url) response = self.get( - '/role_assignments?scope.system=all&user.id=%(user_id)s' - % {'user_id': self.user['id']} + '/role_assignments?scope.system=all&user.id={user_id}'.format( + user_id=self.user['id'] + ) ) self.assertEqual(len(response.json_body['role_assignments']), 1) self.assertValidRoleAssignmentListResponse(response) @@ -4079,8 +4020,9 @@ class UserSystemRoleAssignmentTestCase( response = self.get(collection_url) self.assertEqual(len(response.json_body['roles']), 0) response = self.get( - '/role_assignments?scope.system=all&user.id=%(user_id)s' - % {'user_id': self.user['id']} + '/role_assignments?scope.system=all&user.id={user_id}'.format( + user_id=self.user['id'] + ) ) self.assertValidRoleAssignmentListResponse(response, expected_length=0) @@ -4090,8 +4032,8 @@ class UserSystemRoleAssignmentTestCase( # also true for project + domain scope. path = ( '/role_assignments?scope.system=all' - '&scope.domain.id=%(domain_id)s' - ) % {'domain_id': self.domain_id} + f'&scope.domain.id={self.domain_id}' + ) self.get(path, expected_status=http.client.BAD_REQUEST) def test_query_for_system_scope_and_project_scope_fails(self): @@ -4100,8 +4042,8 @@ class UserSystemRoleAssignmentTestCase( # also true for project + domain scope. path = ( '/role_assignments?scope.system=all' - '&scope.project.id=%(project_id)s' - ) % {'project_id': self.project_id} + f'&scope.project.id={self.project_id}' + ) self.get(path, expected_status=http.client.BAD_REQUEST) def test_query_for_role_id_does_not_return_system_user_roles(self): @@ -4109,16 +4051,15 @@ class UserSystemRoleAssignmentTestCase( # assign the user a role on the system member_url = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role_id, + user_id=self.user['id'], role_id=system_role_id ) self.put(member_url) # Make sure we only get one role assignment back since the system role # assignment shouldn't be returned. path = ( - '/role_assignments?role.id=%(role_id)s&user.id=%(user_id)s' - ) % {'role_id': self.role_id, 'user_id': self.user['id']} + '/role_assignments?role.id={role_id}&user.id={user_id}' + ).format(role_id=self.role_id, user_id=self.user['id']) response = self.get(path) self.assertValidRoleAssignmentListResponse(response, expected_length=1) @@ -4131,15 +4072,13 @@ class UserSystemRoleAssignmentTestCase( class GroupSystemRoleAssignmentTestCase( test_v3.RestfulTestCase, SystemRoleAssignmentMixin ): - def test_assign_system_role_to_group(self): system_role_id = self._create_new_role() group = self._create_group() # assign the role to the group globally member_url = '/system/groups/{group_id}/roles/{role_id}'.format( - group_id=group['id'], - role_id=system_role_id, + group_id=group['id'], role_id=system_role_id ) self.put(member_url) @@ -4156,8 +4095,9 @@ class GroupSystemRoleAssignmentTestCase( self.head(collection_url, expected_status=http.client.OK) response = self.get( - '/role_assignments?scope.system=all&group.id=%(group_id)s' - % {'group_id': group['id']} + '/role_assignments?scope.system=all&group.id={group_id}'.format( + group_id=group['id'] + ) ) self.assertValidRoleAssignmentListResponse(response, expected_length=1) self.assertEqual( @@ -4170,10 +4110,7 @@ class GroupSystemRoleAssignmentTestCase( group_id = uuid.uuid4().hex # assign the role to the group globally - member_url = '/system/groups/{group_id}/roles/{role_id}'.format( - group_id=group_id, - role_id=system_role_id, - ) + member_url = f'/system/groups/{group_id}/roles/{system_role_id}' self.put(member_url, expected_status=http.client.NOT_FOUND) def test_list_role_assignments_for_group_returns_all_assignments(self): @@ -4182,23 +4119,23 @@ class GroupSystemRoleAssignmentTestCase( # assign the role to the group globally and on a single project member_url = '/system/groups/{group_id}/roles/{role_id}'.format( + group_id=group['id'], role_id=system_role_id + ) + self.put(member_url) + member_url = ( + '/projects/{project_id}/groups/{group_id}/roles/{role_id}' + ).format( + project_id=self.project_id, group_id=group['id'], role_id=system_role_id, ) self.put(member_url) - member_url = ( - '/projects/%(project_id)s/groups/%(group_id)s/roles/%(role_id)s' - ) % { - 'project_id': self.project_id, - 'group_id': group['id'], - 'role_id': system_role_id, - } - self.put(member_url) # make sure both assignments exist in the response, there should be two response = self.get( - '/role_assignments?group.id=%(group_id)s' - % {'group_id': group['id']} + '/role_assignments?group.id={group_id}'.format( + group_id=group['id'] + ) ) self.assertValidRoleAssignmentListResponse(response, expected_length=2) @@ -4216,8 +4153,9 @@ class GroupSystemRoleAssignmentTestCase( self.assertEqual(response.json_body['roles'], []) response = self.get( - '/role_assignments?scope.system=all&group.id=%(group_id)s' - % {'group_id': group['id']} + '/role_assignments?scope.system=all&group.id={group_id}'.format( + group_id=group['id'] + ) ) self.assertValidRoleAssignmentListResponse(response, expected_length=0) @@ -4228,17 +4166,16 @@ class GroupSystemRoleAssignmentTestCase( # assign the group a role on the system and a role on a project member_url = '/system/groups/{group_id}/roles/{role_id}'.format( - group_id=group['id'], - role_id=system_role_id, + group_id=group['id'], role_id=system_role_id ) self.put(member_url) member_url = ( - '/projects/%(project_id)s/groups/%(group_id)s/roles/%(role_id)s' - ) % { - 'project_id': self.project_id, - 'group_id': group['id'], - 'role_id': project_role_id, - } + '/projects/{project_id}/groups/{group_id}/roles/{role_id}' + ).format( + project_id=self.project_id, + group_id=group['id'], + role_id=project_role_id, + ) self.put(member_url) # list system role assignments @@ -4253,8 +4190,9 @@ class GroupSystemRoleAssignmentTestCase( self.assertNotEqual(role['id'], project_role_id) response = self.get( - '/role_assignments?scope.system=all&group.id=%(group_id)s' - % {'group_id': group['id']} + '/role_assignments?scope.system=all&group.id={group_id}'.format( + group_id=group['id'] + ) ) self.assertValidRoleAssignmentListResponse(response, expected_length=1) @@ -4265,27 +4203,25 @@ class GroupSystemRoleAssignmentTestCase( # assign a role to the group on a domain domain_member_url = ( - '/domains/%(domain_id)s/groups/%(group_id)s/' - 'roles/%(role_id)s' - % { - 'domain_id': group['domain_id'], - 'group_id': group['id'], - 'role_id': domain_role_id, - } + '/domains/{domain_id}/groups/{group_id}/' 'roles/{role_id}'.format( + domain_id=group['domain_id'], + group_id=group['id'], + role_id=domain_role_id, + ) ) self.put(domain_member_url) # assign the group a role on the system member_url = '/system/groups/{group_id}/roles/{role_id}'.format( - group_id=group['id'], - role_id=system_role_id, + group_id=group['id'], role_id=system_role_id ) self.put(member_url) # list domain role assignments response = self.get( - '/domains/%(domain_id)s/groups/%(group_id)s/roles' - % {'domain_id': group['domain_id'], 'group_id': group['id']} + '/domains/{domain_id}/groups/{group_id}/roles'.format( + domain_id=group['domain_id'], group_id=group['id'] + ) ) self.assertEqual(len(response.json_body['roles']), 1) @@ -4301,8 +4237,9 @@ class GroupSystemRoleAssignmentTestCase( self.assertNotEqual(role['id'], domain_role_id) response = self.get( - '/role_assignments?scope.system=all&group.id=%(group_id)s' - % {'group_id': group['id']} + '/role_assignments?scope.system=all&group.id={group_id}'.format( + group_id=group['id'] + ) ) self.assertValidRoleAssignmentListResponse(response, expected_length=1) @@ -4312,8 +4249,7 @@ class GroupSystemRoleAssignmentTestCase( # assign the group a role on the system member_url = '/system/groups/{group_id}/roles/{role_id}'.format( - group_id=group['id'], - role_id=system_role_id, + group_id=group['id'], role_id=system_role_id ) self.put(member_url) @@ -4321,8 +4257,9 @@ class GroupSystemRoleAssignmentTestCase( self.head(member_url) response = self.get( - '/role_assignments?scope.system=all&group.id=%(group_id)s' - % {'group_id': group['id']} + '/role_assignments?scope.system=all&group.id={group_id}'.format( + group_id=group['id'] + ) ) self.assertValidRoleAssignmentListResponse(response, expected_length=1) self.assertEqual( @@ -4336,14 +4273,14 @@ class GroupSystemRoleAssignmentTestCase( # check the group does't have the system role assignment member_url = '/system/groups/{group_id}/roles/{role_id}'.format( - group_id=group['id'], - role_id=system_role_id, + group_id=group['id'], role_id=system_role_id ) self.head(member_url, expected_status=http.client.NOT_FOUND) response = self.get( - '/role_assignments?scope.system=all&group.id=%(group_id)s' - % {'group_id': group['id']} + '/role_assignments?scope.system=all&group.id={group_id}'.format( + group_id=group['id'] + ) ) self.assertValidRoleAssignmentListResponse(response, expected_length=0) @@ -4353,8 +4290,7 @@ class GroupSystemRoleAssignmentTestCase( # assign the group a role on the system member_url = '/system/groups/{group_id}/roles/{role_id}'.format( - group_id=group['id'], - role_id=system_role_id, + group_id=group['id'], role_id=system_role_id ) self.put(member_url) @@ -4362,8 +4298,9 @@ class GroupSystemRoleAssignmentTestCase( self.head(member_url) response = self.get( - '/role_assignments?scope.system=all&group.id=%(group_id)s' - % {'group_id': group['id']} + '/role_assignments?scope.system=all&group.id={group_id}'.format( + group_id=group['id'] + ) ) self.assertEqual(len(response.json_body['role_assignments']), 1) self.assertValidRoleAssignmentListResponse(response) @@ -4378,8 +4315,9 @@ class GroupSystemRoleAssignmentTestCase( response = self.get(collection_url) self.assertEqual(len(response.json_body['roles']), 0) response = self.get( - '/role_assignments?scope.system=all&group.id=%(group_id)s' - % {'group_id': group['id']} + '/role_assignments?scope.system=all&group.id={group_id}'.format( + group_id=group['id'] + ) ) self.assertValidRoleAssignmentListResponse(response, expected_length=0) @@ -4389,26 +4327,24 @@ class GroupSystemRoleAssignmentTestCase( # assign the group a role on the system member_url = '/system/groups/{group_id}/roles/{role_id}'.format( - group_id=group['id'], - role_id=system_role_id, + group_id=group['id'], role_id=system_role_id ) self.put(member_url) # assign the group a role on the system member_url = ( - '/projects/%(project_id)s/groups/%(group_id)s/roles/%(role_id)s' - % { - 'project_id': self.project_id, - 'group_id': group['id'], - 'role_id': self.role_id, - } + '/projects/{project_id}/groups/{group_id}/roles/{role_id}'.format( + project_id=self.project_id, + group_id=group['id'], + role_id=self.role_id, + ) ) self.put(member_url) # Make sure we only get one role assignment back since the system role # assignment shouldn't be returned. path = ( - '/role_assignments?role.id=%(role_id)s&group.id=%(group_id)s' - ) % {'role_id': self.role_id, 'group_id': group['id']} + '/role_assignments?role.id={role_id}&group.id={group_id}' + ).format(role_id=self.role_id, group_id=group['id']) response = self.get(path) self.assertValidRoleAssignmentListResponse(response, expected_length=1) diff --git a/keystone/tests/unit/test_v3_auth.py b/keystone/tests/unit/test_v3_auth.py index a9921e8503..3d30f26c48 100644 --- a/keystone/tests/unit/test_v3_auth.py +++ b/keystone/tests/unit/test_v3_auth.py @@ -691,12 +691,11 @@ class TokenAPITests: # grant the user a role on the project self.put( - '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' - % { - 'user_id': self.user['id'], - 'project_id': project['id'], - 'role_id': self.role['id'], - } + '/projects/{project_id}/users/{user_id}/roles/{role_id}'.format( + user_id=self.user['id'], + project_id=project['id'], + role_id=self.role['id'], + ) ) # make the new project the user's default project @@ -915,8 +914,7 @@ class TokenAPITests: def test_create_system_token_with_user_id(self): path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=self.role_id, + user_id=self.user['id'], role_id=self.role_id ) self.put(path=path) @@ -931,8 +929,7 @@ class TokenAPITests: def test_create_system_token_with_username(self): path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=self.role_id, + user_id=self.user['id'], role_id=self.role_id ) self.put(path=path) @@ -958,8 +955,7 @@ class TokenAPITests: def test_system_token_is_invalid_after_disabling_user(self): path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=self.role_id, + user_id=self.user['id'], role_id=self.role_id ) self.put(path=path) @@ -1004,14 +1000,12 @@ class TokenAPITests: group = self.post('/groups', body=ref).json_body['group'] path = '/system/groups/{group_id}/roles/{role_id}'.format( - group_id=group['id'], - role_id=self.role_id, + group_id=group['id'], role_id=self.role_id ) self.put(path=path) path = '/groups/{group_id}/users/{user_id}'.format( - group_id=group['id'], - user_id=self.user['id'], + group_id=group['id'], user_id=self.user['id'] ) self.put(path=path) @@ -1027,8 +1021,7 @@ class TokenAPITests: def test_revoke_system_token(self): path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=self.role_id, + user_id=self.user['id'], role_id=self.role_id ) self.put(path=path) @@ -1051,8 +1044,7 @@ class TokenAPITests: system_role = self.post('/roles', body=ref).json_body['role'] path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role['id'], + user_id=self.user['id'], role_id=system_role['id'] ) self.put(path=path) @@ -1076,8 +1068,7 @@ class TokenAPITests: system_role = self.post('/roles', body=ref).json_body['role'] path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role['id'], + user_id=self.user['id'], role_id=system_role['id'] ) self.put(path=path) @@ -1103,8 +1094,7 @@ class TokenAPITests: system_role = self.post('/roles', body=ref).json_body['role'] path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=system_role['id'], + user_id=self.user['id'], role_id=system_role['id'] ) self.put(path=path) @@ -1128,9 +1118,7 @@ class TokenAPITests: def test_create_domain_token_scoped_with_domain_id_and_user_id(self): # grant the user a role on the domain path = '/domains/{}/users/{}/roles/{}'.format( - self.domain['id'], - self.user['id'], - self.role['id'], + self.domain['id'], self.user['id'], self.role['id'] ) self.put(path=path) @@ -1145,9 +1133,7 @@ class TokenAPITests: def test_create_domain_token_scoped_with_domain_id_and_username(self): # grant the user a role on the domain path = '/domains/{}/users/{}/roles/{}'.format( - self.domain['id'], - self.user['id'], - self.role['id'], + self.domain['id'], self.user['id'], self.role['id'] ) self.put(path=path) @@ -1163,9 +1149,7 @@ class TokenAPITests: def test_create_domain_token_scoped_with_domain_id(self): # grant the user a role on the domain path = '/domains/{}/users/{}/roles/{}'.format( - self.domain['id'], - self.user['id'], - self.role['id'], + self.domain['id'], self.user['id'], self.role['id'] ) self.put(path=path) @@ -1181,9 +1165,7 @@ class TokenAPITests: def test_create_domain_token_scoped_with_domain_name(self): # grant the user a role on the domain path = '/domains/{}/users/{}/roles/{}'.format( - self.domain['id'], - self.user['id'], - self.role['id'], + self.domain['id'], self.user['id'], self.role['id'] ) self.put(path=path) @@ -1198,9 +1180,7 @@ class TokenAPITests: def test_create_domain_token_scoped_with_domain_name_and_username(self): # grant the user a role on the domain path = '/domains/{}/users/{}/roles/{}'.format( - self.domain['id'], - self.user['id'], - self.role['id'], + self.domain['id'], self.user['id'], self.role['id'] ) self.put(path=path) @@ -1216,9 +1196,7 @@ class TokenAPITests: def test_create_domain_token_with_only_domain_name_and_username(self): # grant the user a role on the domain path = '/domains/{}/users/{}/roles/{}'.format( - self.domain['id'], - self.user['id'], - self.role['id'], + self.domain['id'], self.user['id'], self.role['id'] ) self.put(path=path) @@ -1240,9 +1218,7 @@ class TokenAPITests: # grant the domain role to group path = '/domains/{}/groups/{}/roles/{}'.format( - self.domain['id'], - group['id'], - self.role['id'], + self.domain['id'], group['id'], self.role['id'] ) self.put(path=path) @@ -1901,7 +1877,7 @@ class TokenAPITests: self.assertValidProjectScopedTokenResponse(r) # Disable trustee - trustee_update_ref = dict(enabled=False) + trustee_update_ref = {'enabled': False} PROVIDERS.identity_api.update_user( trustee_user['id'], trustee_update_ref ) @@ -1936,7 +1912,7 @@ class TokenAPITests: trust_ref = unit.new_trust_ref( trustor_user_id=self.user_id, trustee_user_id=trustee_ref['id'], - expires=dict(minutes=1), + expires={'minutes': 1}, project_id=new_project_ref['id'], impersonation=True, role_ids=[self.role['id']], @@ -1975,7 +1951,7 @@ class TokenAPITests: r = self._validate_token(trust_scoped_token) self.assertValidProjectScopedTokenResponse(r) # Change trustee's password - trustee_update_ref = dict(password='Password1') + trustee_update_ref = {'password': 'Password1'} PROVIDERS.identity_api.update_user( trustee_user['id'], trustee_update_ref ) @@ -1992,7 +1968,7 @@ class TokenAPITests: self.assertValidProjectScopedTokenResponse(r) # Disable the trustor - trustor_update_ref = dict(enabled=False) + trustor_update_ref = {'enabled': False} PROVIDERS.identity_api.update_user(self.user['id'], trustor_update_ref) # Ensure validating a token for a disabled user fails self._validate_token( @@ -2007,7 +1983,7 @@ class TokenAPITests: self.assertValidProjectScopedTokenResponse(r) # Change trustor's password - trustor_update_ref = dict(password='Password1') + trustor_update_ref = {'password': 'Password1'} PROVIDERS.identity_api.update_user(self.user['id'], trustor_update_ref) # Ensure updating trustor's password revokes existing user's tokens self._validate_token( @@ -2025,7 +2001,7 @@ class TokenAPITests: self.domain['enabled'] = False PROVIDERS.resource_api.update_domain(self.domain['id'], self.domain) - trustor_update_ref = dict(password='Password1') + trustor_update_ref = {'password': 'Password1'} PROVIDERS.identity_api.update_user(self.user['id'], trustor_update_ref) # Ensure updating trustor's password revokes existing user's tokens self._validate_token( @@ -2407,9 +2383,7 @@ class TokenAPITests: # give the new user a role on a project path = '/projects/{}/users/{}/roles/{}'.format( - self.project['id'], - new_user['id'], - self.role['id'], + self.project['id'], new_user['id'], self.role['id'] ) self.put(path=path) @@ -2430,9 +2404,7 @@ class TokenAPITests: # remove the roles from the user for the given scope path = '/projects/{}/users/{}/roles/{}'.format( - self.project['id'], - new_user['id'], - self.role['id'], + self.project['id'], new_user['id'], self.role['id'] ) self.delete(path=path) @@ -2930,9 +2902,7 @@ class TokenAPITests: def _get_oauth2_access_token( self, client_id, client_cert_content, expected_status=http.client.OK ): - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - } + headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = {'grant_type': 'client_credentials', 'client_id': client_id} extra_environ = {'SSL_CLIENT_CERT': client_cert_content} data = parse.urlencode(data).encode() @@ -3142,7 +3112,6 @@ class AllowRescopeScopedTokenDisabledTests(test_v3.RestfulTestCase): ) def test_rescoped_domain_token_disabled(self): - self.domainA = unit.new_domain_ref() PROVIDERS.resource_api.create_domain(self.domainA['id'], self.domainA) PROVIDERS.assignment_api.create_grant( @@ -3237,7 +3206,7 @@ class TestFernetTokenAPIs( self.assertValidProjectScopedTokenResponse(r) # Disable the trustor - trustor_update_ref = dict(enabled=False) + trustor_update_ref = {'enabled': False} PROVIDERS.identity_api.update_user(self.user['id'], trustor_update_ref) # Ensure validating a token for a disabled user fails self._validate_token( @@ -3305,7 +3274,7 @@ class TestJWSTokenAPIs(test_v3.RestfulTestCase, TokenAPITests, TokenDataTests): self.assertValidProjectScopedTokenResponse(r) # Disable the trustor - trustor_update_ref = dict(enabled=False) + trustor_update_ref = {'enabled': False} PROVIDERS.identity_api.update_user(self.user['id'], trustor_update_ref) # Ensure validating a token for a disabled user fails self._validate_token( @@ -3462,12 +3431,11 @@ class TestTokenRevokeById(test_v3.RestfulTestCase): # assign a new role self.put( - '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' - % { - 'project_id': self.projectA['id'], - 'user_id': self.user1['id'], - 'role_id': role['id'], - } + '/projects/{project_id}/users/{user_id}/roles/{role_id}'.format( + project_id=self.projectA['id'], + user_id=self.user1['id'], + role_id=role['id'], + ) ) # both tokens should remain valid @@ -3506,13 +3474,11 @@ class TestTokenRevokeById(test_v3.RestfulTestCase): ) # Delete the grant, which should invalidate the token grant_url = ( - '/projects/%(project_id)s/users/%(user_id)s/' - 'roles/%(role_id)s' - % { - 'project_id': self.project['id'], - 'user_id': self.user['id'], - 'role_id': self.role['id'], - } + '/projects/{project_id}/users/{user_id}/' 'roles/{role_id}'.format( + project_id=self.project['id'], + user_id=self.user['id'], + role_id=self.role['id'], + ) ) self.delete(grant_url) self.head( @@ -3646,7 +3612,7 @@ class TestTokenRevokeById(test_v3.RestfulTestCase): ) # Delete the role, which should invalidate the tokens - role_url = '/roles/%s' % self.role1['id'] + role_url = '/roles/{}'.format(self.role1['id']) self.delete(role_url) # Check the tokens that used role1 is invalid @@ -3702,13 +3668,11 @@ class TestTokenRevokeById(test_v3.RestfulTestCase): ) # Assign a role, which should not affect the token grant_url = ( - '/domains/%(domain_id)s/users/%(user_id)s/' - 'roles/%(role_id)s' - % { - 'domain_id': self.domainB['id'], - 'user_id': self.user1['id'], - 'role_id': self.role1['id'], - } + '/domains/{domain_id}/users/{user_id}/' 'roles/{role_id}'.format( + domain_id=self.domainB['id'], + user_id=self.user1['id'], + role_id=self.role1['id'], + ) ) self.put(grant_url) self.head( @@ -3841,13 +3805,12 @@ class TestTokenRevokeById(test_v3.RestfulTestCase): # Delete the group grant, which should invalidate the # tokens for user1 and user2 grant_url = ( - '/projects/%(project_id)s/groups/%(group_id)s/' - 'roles/%(role_id)s' - % { - 'project_id': self.projectA['id'], - 'group_id': self.group1['id'], - 'role_id': self.role1['id'], - } + '/projects/{project_id}/groups/{group_id}/' + 'roles/{role_id}'.format( + project_id=self.projectA['id'], + group_id=self.group1['id'], + role_id=self.role1['id'], + ) ) self.delete(grant_url) PROVIDERS.assignment_api.delete_grant( @@ -3902,13 +3865,11 @@ class TestTokenRevokeById(test_v3.RestfulTestCase): ) # Delete the grant, which should invalidate the token grant_url = ( - '/domains/%(domain_id)s/groups/%(group_id)s/' - 'roles/%(role_id)s' - % { - 'domain_id': self.domainB['id'], - 'group_id': self.group1['id'], - 'role_id': self.role1['id'], - } + '/domains/{domain_id}/groups/{group_id}/' 'roles/{role_id}'.format( + domain_id=self.domainB['id'], + group_id=self.group1['id'], + role_id=self.role1['id'], + ) ) self.put(grant_url) self.head( @@ -3958,8 +3919,9 @@ class TestTokenRevokeById(test_v3.RestfulTestCase): # Remove user1 from group1, which should invalidate # the token self.delete( - '/groups/%(group_id)s/users/%(user_id)s' - % {'group_id': self.group1['id'], 'user_id': self.user1['id']} + '/groups/{group_id}/users/{user_id}'.format( + group_id=self.group1['id'], user_id=self.user1['id'] + ) ) self.head( '/auth/tokens', @@ -3974,8 +3936,9 @@ class TestTokenRevokeById(test_v3.RestfulTestCase): ) # Adding user2 to a group should not invalidate token self.put( - '/groups/%(group_id)s/users/%(user_id)s' - % {'group_id': self.group2['id'], 'user_id': self.user2['id']} + '/groups/{group_id}/users/{user_id}'.format( + group_id=self.group2['id'], user_id=self.user2['id'] + ) ) self.head( '/auth/tokens', @@ -3989,12 +3952,11 @@ class TestTokenRevokeById(test_v3.RestfulTestCase): with freezegun.freeze_time(time) as frozen_datetime: # This group grant is not needed for the test self.delete( - '/projects/%(p_id)s/groups/%(g_id)s/roles/%(r_id)s' - % { - 'p_id': self.projectA['id'], - 'g_id': self.group1['id'], - 'r_id': self.role1['id'], - } + '/projects/{p_id}/groups/{g_id}/roles/{r_id}'.format( + p_id=self.projectA['id'], + g_id=self.group1['id'], + r_id=self.role1['id'], + ) ) # NOTE(lbragstad): Here we advance the clock one second to pass @@ -4024,12 +3986,11 @@ class TestTokenRevokeById(test_v3.RestfulTestCase): # delete relationships between user1 and projectA from setUp self.delete( - '/projects/%(p_id)s/users/%(u_id)s/roles/%(r_id)s' - % { - 'p_id': self.projectA['id'], - 'u_id': self.user1['id'], - 'r_id': self.role1['id'], - } + '/projects/{p_id}/users/{u_id}/roles/{r_id}'.format( + p_id=self.projectA['id'], + u_id=self.user1['id'], + r_id=self.role1['id'], + ) ) # authorization for the first user should now fail self.head( @@ -4265,13 +4226,10 @@ class TestTokenRevokeApi(TestTokenRevokeById): found, 'event with correct values not in list, expected to ' 'find event with key-value pairs. Expected: ' - '"%(expected)s" Events: "%(events)s"' - % { - 'expected': ','.join( - [f"'{k}={v}'" for k, v in kwargs.items()] - ), - 'events': events, - }, + '"{expected}" Events: "{events}"'.format( + expected=','.join([f"'{k}={v}'" for k, v in kwargs.items()]), + events=events, + ), ) def test_list_delete_token_shows_in_event_list(self): @@ -4320,7 +4278,6 @@ class TestTokenRevokeApi(TestTokenRevokeById): ) def test_list_with_filter(self): - self.role_data_fixtures() events = self.get('/OS-REVOKE/events').json_body['events'] self.assertEqual(0, len(events)) @@ -4339,7 +4296,7 @@ class TestTokenRevokeApi(TestTokenRevokeById): timeutils.utcnow() + datetime.timedelta(seconds=1000) ) - events = self.get('/OS-REVOKE/events?since=%s' % (future)).json_body[ + events = self.get(f'/OS-REVOKE/events?since={future}').json_body[ 'events' ] self.assertEqual(0, len(events)) @@ -4499,7 +4456,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], allow_redelegation=True, ) @@ -4582,7 +4539,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=True, - expires=dict(minutes=10), + expires={'minutes': 10}, role_ids=[self.role_id], ) self.post( @@ -4699,7 +4656,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_names=[self.role['name']], allow_redelegation=True, ) @@ -4828,7 +4785,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=trustee_user_2['id'], project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], allow_redelegation=False, ) @@ -4984,7 +4941,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) @@ -5005,7 +4962,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) @@ -5022,13 +4979,11 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): PROVIDERS.role_api.create_role(role['id'], role) grant_url = ( - '/projects/%(project_id)s/users/%(user_id)s/' - 'roles/%(role_id)s' - % { - 'project_id': self.project_id, - 'user_id': self.user_id, - 'role_id': role['id'], - } + '/projects/{project_id}/users/{user_id}/' 'roles/{role_id}'.format( + project_id=self.project_id, + user_id=self.user_id, + role_id=role['id'], + ) ) # assign a new role @@ -5040,7 +4995,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[role['id']], ) @@ -5080,12 +5035,11 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): # assign the new role to trustee self.put( - '/projects/%(project_id)s/users/%(user_id)s/roles/%(role_id)s' - % { - 'project_id': self.project_id, - 'user_id': self.trustee_user['id'], - 'role_id': role['id'], - } + '/projects/{project_id}/users/{user_id}/roles/{role_id}'.format( + project_id=self.project_id, + user_id=self.trustee_user['id'], + role_id=role['id'], + ) ) # create a trust from trustor -> trustee @@ -5094,7 +5048,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) r = self.post('/OS-TRUST/trusts', body={'trust': ref}) @@ -5114,7 +5068,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=sub_trustee_user_id, project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[role['id']], ) r = self.post('/OS-TRUST/trusts', token=token, body={'trust': ref}) @@ -5144,7 +5098,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): if event.get('OS-TRUST:trust_id') == trust_id: found = True self.assertTrue( - found, 'event with trust_id %s not found in list' % trust_id + found, f'event with trust_id {trust_id} not found in list' ) def test_delete_trust_revokes_tokens(self): @@ -5153,7 +5107,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) r = self.post('/OS-TRUST/trusts', body={'trust': ref}) @@ -5186,7 +5140,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) @@ -5216,7 +5170,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) @@ -5248,7 +5202,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) @@ -5273,7 +5227,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) @@ -5291,19 +5245,19 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trust_token = r.headers.get('X-Subject-Token') self.get( - '/OS-TRUST/trusts?trustor_user_id=%s' % self.user_id, + f'/OS-TRUST/trusts?trustor_user_id={self.user_id}', token=trust_token, ) self.assertValidUserResponse( self.patch( - '/users/%s' % self.trustee_user['id'], + '/users/{}'.format(self.trustee_user['id']), body={'user': {'password': uuid.uuid4().hex}}, ) ) self.get( - '/OS-TRUST/trusts?trustor_user_id=%s' % self.user_id, + f'/OS-TRUST/trusts?trustor_user_id={self.user_id}', expected_status=http.client.UNAUTHORIZED, token=trust_token, ) @@ -5322,15 +5276,17 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): self.assertValidRoleListResponse(resp, self.role) self.head( - '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' - % {'trust_id': trust['id'], 'role_id': self.role['id']}, + '/OS-TRUST/trusts/{trust_id}/roles/{role_id}'.format( + trust_id=trust['id'], role_id=self.role['id'] + ), token=trust_token, expected_status=http.client.OK, ) resp = self.get( - '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' - % {'trust_id': trust['id'], 'role_id': self.role['id']}, + '/OS-TRUST/trusts/{trust_id}/roles/{role_id}'.format( + trust_id=trust['id'], role_id=self.role['id'] + ), token=trust_token, ) self.assertValidRoleResponse(resp, self.role) @@ -5341,7 +5297,7 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user['id'], project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], remaining_uses=3, ) @@ -5359,12 +5315,11 @@ class TrustAPIBehavior(test_v3.RestfulTestCase): ) self.v3_create_token(auth_data, expected_status=http.client.FORBIDDEN) - r = self.get('/OS-TRUST/trusts/%s' % trust_id) + r = self.get(f'/OS-TRUST/trusts/{trust_id}') self.assertEqual(3, r.result.get('trust').get('remaining_uses')) class TestTrustChain(test_v3.RestfulTestCase): - def config_overrides(self): super().config_overrides() self.config_fixture.config( @@ -5390,8 +5345,8 @@ class TestTrustChain(test_v3.RestfulTestCase): userB is trusting userC with trustC """ - self.user_list = list() - self.trust_chain = list() + self.user_list = [] + self.trust_chain = [] for _ in range(3): user = unit.create_user( PROVIDERS.identity_api, domain_id=self.domain_id @@ -5405,7 +5360,7 @@ class TestTrustChain(test_v3.RestfulTestCase): trustee_user_id=trustee['id'], project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], allow_redelegation=True, redelegation_count=3, @@ -5481,14 +5436,15 @@ class TestTrustChain(test_v3.RestfulTestCase): if event.get('OS-TRUST:trust_id') == trust_id: found = True self.assertTrue( - found, 'event with trust_id %s not found in list' % trust_id + found, f'event with trust_id {trust_id} not found in list' ) def test_delete_trust_cascade(self): self.assert_user_authenticate(self.user_list[0]) self.delete( - '/OS-TRUST/trusts/%(trust_id)s' - % {'trust_id': self.trust_chain[0]['id']} + '/OS-TRUST/trusts/{trust_id}'.format( + trust_id=self.trust_chain[0]['id'] + ) ) headers = {'X-Subject-Token': self.last_token} @@ -5502,8 +5458,9 @@ class TestTrustChain(test_v3.RestfulTestCase): def test_delete_broken_chain(self): self.assert_user_authenticate(self.user_list[0]) self.delete( - '/OS-TRUST/trusts/%(trust_id)s' - % {'trust_id': self.trust_chain[0]['id']} + '/OS-TRUST/trusts/{trust_id}'.format( + trust_id=self.trust_chain[0]['id'] + ) ) # Verify the two remaining trust have been deleted @@ -5517,8 +5474,9 @@ class TestTrustChain(test_v3.RestfulTestCase): # Assert chained trust have been deleted self.get( - '/OS-TRUST/trusts/%(trust_id)s' - % {'trust_id': self.trust_chain[i + 1]['id']}, + '/OS-TRUST/trusts/{trust_id}'.format( + trust_id=self.trust_chain[i + 1]['id'] + ), token=auth_token, expected_status=http.client.NOT_FOUND, ) @@ -5639,7 +5597,6 @@ class TestAuthContext(unit.TestCase): class TestAuthSpecificData(test_v3.RestfulTestCase): - def test_get_catalog_with_project_scoped_token(self): """Call ``GET /auth/catalog`` with a project-scoped token.""" r = self.get('/auth/catalog', expected_status=http.client.OK) @@ -5653,8 +5610,9 @@ class TestAuthSpecificData(test_v3.RestfulTestCase): """Call ``GET /auth/catalog`` with a domain-scoped token.""" # grant a domain role to a user self.put( - path='/domains/%s/users/%s/roles/%s' - % (self.domain['id'], self.user['id'], self.role['id']) + path='/domains/{}/users/{}/roles/{}'.format( + self.domain['id'], self.user['id'], self.role['id'] + ) ) self.get( @@ -5671,8 +5629,9 @@ class TestAuthSpecificData(test_v3.RestfulTestCase): """Call ``HEAD /auth/catalog`` with a domain-scoped token.""" # grant a domain role to a user self.put( - path='/domains/%s/users/%s/roles/%s' - % (self.domain['id'], self.user['id'], self.role['id']) + path='/domains/{}/users/{}/roles/{}'.format( + self.domain['id'], self.user['id'], self.role['id'] + ) ) self.head( @@ -5764,11 +5723,7 @@ class TestAuthSpecificData(test_v3.RestfulTestCase): r = self.post('/domains', body={'domain': ref}) authorized_domain_id = r.json['domain']['id'] - path = '/domains/{domain_id}/users/{user_id}/roles/{role_id}'.format( - domain_id=authorized_domain_id, - user_id=self.user_id, - role_id=self.role_id, - ) + path = f'/domains/{authorized_domain_id}/users/{self.user_id}/roles/{self.role_id}' self.put(path, expected_status=http.client.NO_CONTENT) r = self.get('/auth/domains', expected_status=http.client.OK) @@ -5786,8 +5741,9 @@ class TestAuthSpecificData(test_v3.RestfulTestCase): def test_get_domains_with_project_scoped_token(self): self.put( - path='/domains/%s/users/%s/roles/%s' - % (self.domain['id'], self.user['id'], self.role['id']) + path='/domains/{}/users/{}/roles/{}'.format( + self.domain['id'], self.user['id'], self.role['id'] + ) ) r = self.get('/auth/domains', expected_status=http.client.OK) @@ -5796,16 +5752,16 @@ class TestAuthSpecificData(test_v3.RestfulTestCase): def test_head_domains_with_project_scoped_token(self): self.put( - path='/domains/%s/users/%s/roles/%s' - % (self.domain['id'], self.user['id'], self.role['id']) + path='/domains/{}/users/{}/roles/{}'.format( + self.domain['id'], self.user['id'], self.role['id'] + ) ) self.head('/auth/domains', expected_status=http.client.OK) def test_get_system_roles_with_unscoped_token(self): path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=self.role_id, + user_id=self.user['id'], role_id=self.role_id ) self.put(path=path) @@ -5859,14 +5815,14 @@ class TestAuthSpecificData(test_v3.RestfulTestCase): def test_get_system_roles_with_project_scoped_token(self): path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=self.role_id, + user_id=self.user['id'], role_id=self.role_id ) self.put(path=path) self.put( - path='/domains/%s/users/%s/roles/%s' - % (self.domain['id'], self.user['id'], self.role['id']) + path='/domains/{}/users/{}/roles/{}'.format( + self.domain['id'], self.user['id'], self.role['id'] + ) ) domain_scoped_request = self.build_authentication_request( @@ -5887,8 +5843,7 @@ class TestAuthSpecificData(test_v3.RestfulTestCase): def test_get_system_roles_with_domain_scoped_token(self): path = '/system/users/{user_id}/roles/{role_id}'.format( - user_id=self.user['id'], - role_id=self.role_id, + user_id=self.user['id'], role_id=self.role_id ) self.put(path=path) @@ -5926,7 +5881,6 @@ class TestTrustAuthFernetTokenProvider(TrustAPIBehavior, TestTrustChain): class TestAuthTOTP(test_v3.RestfulTestCase): - def setUp(self): super().setUp() self.useFixture( @@ -5999,7 +5953,7 @@ class TestAuthTOTP(test_v3.RestfulTestCase): for cred in itertools.chain(other_creds, totp_creds): self.delete( - '/credentials/%s' % cred['id'], + '/credentials/{}'.format(cred['id']), expected_status=http.client.NO_CONTENT, ) @@ -6251,7 +6205,6 @@ class TestFetchRevocationList(test_v3.RestfulTestCase): class ApplicationCredentialAuth(test_v3.RestfulTestCase): - def setUp(self): super().setUp() self.app_cred_api = PROVIDERS.application_credential_api diff --git a/keystone/tests/unit/test_v3_catalog.py b/keystone/tests/unit/test_v3_catalog.py index 66bdc2785a..5e43ecfb18 100644 --- a/keystone/tests/unit/test_v3_catalog.py +++ b/keystone/tests/unit/test_v3_catalog.py @@ -37,7 +37,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): ref = unit.new_region_ref() region_id = ref.pop('id') r = self.put( - '/regions/%s' % region_id, + f'/regions/{region_id}', body={'region': ref}, expected_status=http.client.CREATED, ) @@ -51,7 +51,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): ref = unit.new_region_ref() region_id = ref['id'] r = self.put( - '/regions/%s' % region_id, + f'/regions/{region_id}', body={'region': ref}, expected_status=http.client.CREATED, ) @@ -65,13 +65,13 @@ class CatalogTestCase(test_v3.RestfulTestCase): ref = unit.new_region_ref() region_id = ref['id'] self.put( - '/regions/%s' % region_id, + f'/regions/{region_id}', body={'region': ref}, expected_status=http.client.CREATED, ) # Create region again with duplicate id self.put( - '/regions/%s' % region_id, + f'/regions/{region_id}', body={'region': ref}, expected_status=http.client.CONFLICT, ) @@ -163,7 +163,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): # but instead of using that ID, make up a new, conflicting one self.put( - '/regions/%s' % uuid.uuid4().hex, + f'/regions/{uuid.uuid4().hex}', body={'region': ref}, expected_status=http.client.BAD_REQUEST, ) @@ -187,7 +187,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): new_region = self._create_region_with_parent_id(parent_id) new_region = self._create_region_with_parent_id(parent_id) - r = self.get('/regions?parent_region_id=%s' % parent_id) + r = self.get(f'/regions?parent_region_id={parent_id}') for region in r.result['regions']: self.assertEqual(parent_id, region['parent_region_id']) @@ -203,10 +203,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): """Call ``PATCH /regions/{region_id}``.""" region = unit.new_region_ref() del region['id'] - r = self.patch( - f'/regions/{self.region_id}', - body={'region': region}, - ) + r = self.patch(f'/regions/{self.region_id}', body={'region': region}) self.assertValidRegionResponse(r, region) def test_update_region_without_description_keeps_original(self): @@ -217,10 +214,11 @@ class CatalogTestCase(test_v3.RestfulTestCase): region_updates = { # update with something that's not the description - 'parent_region_id': self.region_id, + 'parent_region_id': self.region_id } resp = self.patch( - '/regions/%s' % region_ref['id'], body={'region': region_updates} + '/regions/{}'.format(region_ref['id']), + body={'region': region_updates}, ) # NOTE(dstanek): Keystone should keep the original description. @@ -232,10 +230,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): """Call ``PATCH /regions/{region_id}``.""" region = unit.new_region_ref(description=None) del region['id'] - r = self.patch( - f'/regions/{self.region_id}', - body={'region': region}, - ) + r = self.patch(f'/regions/{self.region_id}', body={'region': region}) # NOTE(dstanek): Keystone should turn the provided None value into # an empty string before storing in the backend. @@ -371,9 +366,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): def test_get_head_service(self): """Call ``GET & HEAD /services/{service_id}``.""" - resource_url = '/services/{service_id}'.format( - service_id=self.service_id - ) + resource_url = f'/services/{self.service_id}' r = self.get(resource_url) self.assertValidServiceResponse(r, self.service) self.head(resource_url, expected_status=http.client.OK) @@ -383,8 +376,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): service = unit.new_service_ref() del service['id'] r = self.patch( - f'/services/{self.service_id}', - body={'service': service}, + f'/services/{self.service_id}', body={'service': service} ) self.assertValidServiceResponse(r, service) @@ -419,7 +411,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): """Call ``GET /endpoints?interface={interface}``.""" ref = self._create_random_endpoint(interface='internal') - response = self.get('/endpoints?interface=%s' % ref['interface']) + response = self.get('/endpoints?interface={}'.format(ref['interface'])) self.assertValidEndpointListResponse(response, ref=ref) for endpoint in response.json['endpoints']: @@ -429,7 +421,9 @@ class CatalogTestCase(test_v3.RestfulTestCase): """Call ``GET /endpoints?service_id={service_id}``.""" ref = self._create_random_endpoint() - response = self.get('/endpoints?service_id=%s' % ref['service_id']) + response = self.get( + '/endpoints?service_id={}'.format(ref['service_id']) + ) self.assertValidEndpointListResponse(response, ref=ref) for endpoint in response.json['endpoints']: @@ -439,7 +433,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): """Call ``GET /endpoints?region_id={region_id}``.""" ref = self._create_random_endpoint() - response = self.get('/endpoints?region_id=%s' % ref['region_id']) + response = self.get('/endpoints?region_id={}'.format(ref['region_id'])) self.assertValidEndpointListResponse(response, ref=ref) for endpoint in response.json['endpoints']: @@ -456,7 +450,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): parent_region_id = parent_region.result['region']['id'] self._create_random_endpoint(parent_region_id=parent_region_id) - response = self.get('/endpoints?region_id=%s' % parent_region_id) + response = self.get(f'/endpoints?region_id={parent_region_id}') self.assertEqual(0, len(response.json['endpoints'])) def test_list_endpoints_with_multiple_filters(self): @@ -469,8 +463,9 @@ class CatalogTestCase(test_v3.RestfulTestCase): # interface and region_id specified ref = self._create_random_endpoint(interface='internal') response = self.get( - '/endpoints?interface=%s®ion_id=%s' - % (ref['interface'], ref['region_id']) + '/endpoints?interface={}®ion_id={}'.format( + ref['interface'], ref['region_id'] + ) ) self.assertValidEndpointListResponse(response, ref=ref) @@ -481,8 +476,9 @@ class CatalogTestCase(test_v3.RestfulTestCase): # interface and service_id specified ref = self._create_random_endpoint(interface='internal') response = self.get( - '/endpoints?interface=%s&service_id=%s' - % (ref['interface'], ref['service_id']) + '/endpoints?interface={}&service_id={}'.format( + ref['interface'], ref['service_id'] + ) ) self.assertValidEndpointListResponse(response, ref=ref) @@ -493,8 +489,9 @@ class CatalogTestCase(test_v3.RestfulTestCase): # region_id and service_id specified ref = self._create_random_endpoint(interface='internal') response = self.get( - '/endpoints?region_id=%s&service_id=%s' - % (ref['region_id'], ref['service_id']) + '/endpoints?region_id={}&service_id={}'.format( + ref['region_id'], ref['service_id'] + ) ) self.assertValidEndpointListResponse(response, ref=ref) @@ -505,8 +502,9 @@ class CatalogTestCase(test_v3.RestfulTestCase): # interface, region_id and service_id specified ref = self._create_random_endpoint(interface='internal') response = self.get( - ('/endpoints?interface=%s®ion_id=%s&service_id=%s') - % (ref['interface'], ref['region_id'], ref['service_id']) + ('/endpoints?interface={}®ion_id={}&service_id={}').format( + ref['interface'], ref['region_id'], ref['service_id'] + ) ) self.assertValidEndpointListResponse(response, ref=ref) @@ -524,13 +522,13 @@ class CatalogTestCase(test_v3.RestfulTestCase): """ self._create_random_endpoint(interface='internal') - response = self.get('/endpoints?interface=%s' % uuid.uuid4().hex) + response = self.get(f'/endpoints?interface={uuid.uuid4().hex}') self.assertEqual(0, len(response.json['endpoints'])) - response = self.get('/endpoints?region_id=%s' % uuid.uuid4().hex) + response = self.get(f'/endpoints?region_id={uuid.uuid4().hex}') self.assertEqual(0, len(response.json['endpoints'])) - response = self.get('/endpoints?service_id=%s' % uuid.uuid4().hex) + response = self.get(f'/endpoints?service_id={uuid.uuid4().hex}') self.assertEqual(0, len(response.json['endpoints'])) def test_create_endpoint_no_enabled(self): @@ -646,9 +644,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): def test_get_head_endpoint(self): """Call ``GET & HEAD /endpoints/{endpoint_id}``.""" - resource_url = '/endpoints/{endpoint_id}'.format( - endpoint_id=self.endpoint_id - ) + resource_url = f'/endpoints/{self.endpoint_id}' r = self.get(resource_url) self.assertValidEndpointResponse(r, self.endpoint) self.head(resource_url, expected_status=http.client.OK) @@ -662,8 +658,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): ) del ref['id'] r = self.patch( - f'/endpoints/{self.endpoint_id}', - body={'endpoint': ref}, + f'/endpoints/{self.endpoint_id}', body={'endpoint': ref} ) ref['enabled'] = True self.assertValidEndpointResponse(r, ref) @@ -732,11 +727,12 @@ class CatalogTestCase(test_v3.RestfulTestCase): PROVIDERS.catalog_api.create_endpoint(ref['id'], ref) # delete the endpoint - self.delete('/endpoints/%s' % ref['id']) + self.delete('/endpoints/{}'.format(ref['id'])) # make sure it's deleted (GET should return Not Found) self.get( - '/endpoints/%s' % ref['id'], expected_status=http.client.NOT_FOUND + '/endpoints/{}'.format(ref['id']), + expected_status=http.client.NOT_FOUND, ) def test_endpoint_create_with_valid_url(self): @@ -790,9 +786,7 @@ class CatalogTestCase(test_v3.RestfulTestCase): class TestMultiRegion(test_v3.RestfulTestCase): - def test_catalog_with_multi_region_reports_all_endpoints(self): - # Create two separate regions first_region = self.post( '/regions', body={'region': unit.new_region_ref()} diff --git a/keystone/tests/unit/test_v3_credential.py b/keystone/tests/unit/test_v3_credential.py index c7758452ca..dd212c667f 100644 --- a/keystone/tests/unit/test_v3_credential.py +++ b/keystone/tests/unit/test_v3_credential.py @@ -38,7 +38,6 @@ CRED_TYPE_EC2 = ec2tokens.CRED_TYPE_EC2 class CredentialBaseTestCase(test_v3.RestfulTestCase): - def setUp(self): super().setUp() self.useFixture( @@ -104,7 +103,6 @@ class CredentialTestCase(CredentialBaseTestCase): """Test credential CRUD.""" def setUp(self): - super().setUp() self.credential = unit.new_credential_ref( @@ -149,7 +147,7 @@ class CredentialTestCase(CredentialBaseTestCase): credential['id'], credential ) - r = self.get('/credentials?user_id=%s' % self.user['id']) + r = self.get('/credentials?user_id={}'.format(self.user['id'])) self.assertValidCredentialListResponse(r, ref=self.credential) for cred in r.result['credentials']: self.assertEqual(self.user['id'], cred['user_id']) @@ -216,9 +214,7 @@ class CredentialTestCase(CredentialBaseTestCase): credential_user2_cert['id'], credential_user2_cert ) - r = self.get( - '/credentials?user_id=%s&type=ec2' % user1_id, token=token - ) + r = self.get(f'/credentials?user_id={user1_id}&type=ec2', token=token) self.assertValidCredentialListResponse(r, ref=credential_user1_ec2) self.assertThat(r.result['credentials'], matchers.HasLength(1)) cred = r.result['credentials'][0] @@ -234,8 +230,9 @@ class CredentialTestCase(CredentialBaseTestCase): def test_get_credential(self): """Call ``GET /credentials/{credential_id}``.""" r = self.get( - '/credentials/%(credential_id)s' - % {'credential_id': self.credential['id']} + '/credentials/{credential_id}'.format( + credential_id=self.credential['id'] + ) ) self.assertValidCredentialResponse(r, self.credential) @@ -246,8 +243,9 @@ class CredentialTestCase(CredentialBaseTestCase): ) del ref['id'] r = self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': self.credential['id']}, + '/credentials/{credential_id}'.format( + credential_id=self.credential['id'] + ), body={'credential': ref}, ) self.assertValidCredentialResponse(r, ref) @@ -263,9 +261,7 @@ class CredentialTestCase(CredentialBaseTestCase): # Updating the credential to ec2 requires a project_id update_ref = {'type': 'ec2', 'project_id': self.project_id} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, - body={'credential': update_ref}, + f'/credentials/{credential_id}', body={'credential': update_ref} ) def test_update_credential_to_ec2_missing_project_id(self): @@ -280,8 +276,7 @@ class CredentialTestCase(CredentialBaseTestCase): # will fail update_ref = {'type': 'ec2'} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, + f'/credentials/{credential_id}', body={'credential': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -300,9 +295,7 @@ class CredentialTestCase(CredentialBaseTestCase): # update request will not fail update_ref = {'type': 'ec2'} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, - body={'credential': update_ref}, + f'/credentials/{credential_id}', body={'credential': update_ref} ) def test_update_credential_non_owner(self): @@ -335,8 +328,7 @@ class CredentialTestCase(CredentialBaseTestCase): # Cannot change the credential to be owned by another user update_ref = {'user_id': self.user_id, 'project_id': self.project_id} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, + f'/credentials/{credential_id}', expected_status=403, auth=auth, body={'credential': update_ref}, @@ -356,8 +348,7 @@ class CredentialTestCase(CredentialBaseTestCase): blob['trust_id'] = uuid.uuid4().hex update_ref = {'blob': json.dumps(blob)} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, + f'/credentials/{credential_id}', body={'credential': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -365,8 +356,7 @@ class CredentialTestCase(CredentialBaseTestCase): del blob['trust_id'] update_ref = {'blob': json.dumps(blob)} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, + f'/credentials/{credential_id}', body={'credential': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -385,8 +375,7 @@ class CredentialTestCase(CredentialBaseTestCase): blob['app_cred_id'] = uuid.uuid4().hex update_ref = {'blob': json.dumps(blob)} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, + f'/credentials/{credential_id}', body={'credential': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -394,8 +383,7 @@ class CredentialTestCase(CredentialBaseTestCase): del blob['app_cred_id'] update_ref = {'blob': json.dumps(blob)} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, + f'/credentials/{credential_id}', body={'credential': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -414,8 +402,7 @@ class CredentialTestCase(CredentialBaseTestCase): blob['access_token_id'] = uuid.uuid4().hex update_ref = {'blob': json.dumps(blob)} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, + f'/credentials/{credential_id}', body={'credential': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -423,8 +410,7 @@ class CredentialTestCase(CredentialBaseTestCase): del blob['access_token_id'] update_ref = {'blob': json.dumps(blob)} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, + f'/credentials/{credential_id}', body={'credential': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -443,8 +429,7 @@ class CredentialTestCase(CredentialBaseTestCase): blob['access_id'] = uuid.uuid4().hex update_ref = {'blob': json.dumps(blob)} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, + f'/credentials/{credential_id}', body={'credential': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -452,8 +437,7 @@ class CredentialTestCase(CredentialBaseTestCase): del blob['access_id'] update_ref = {'blob': json.dumps(blob)} self.patch( - '/credentials/%(credential_id)s' - % {'credential_id': credential_id}, + f'/credentials/{credential_id}', body={'credential': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -461,8 +445,9 @@ class CredentialTestCase(CredentialBaseTestCase): def test_delete_credential(self): """Call ``DELETE /credentials/{credential_id}``.""" self.delete( - '/credentials/%(credential_id)s' - % {'credential_id': self.credential['id']} + '/credentials/{credential_id}'.format( + credential_id=self.credential['id'] + ) ) def test_delete_credential_retries_on_deadlock(self): @@ -646,7 +631,7 @@ class TestCredentialTrustScoped(CredentialBaseTestCase): trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) del ref['id'] @@ -733,7 +718,7 @@ class TestCredentialAppCreds(CredentialBaseTestCase): ref = unit.new_application_credential_ref(roles=[{'id': self.role_id}]) del ref['id'] r = self.post( - '/users/%s/application_credentials' % self.user_id, + f'/users/{self.user_id}/application_credentials', body={'application_credential': ref}, ) app_cred = r.result['application_credential'] @@ -870,7 +855,7 @@ class TestCredentialAccessToken(CredentialBaseTestCase): def _authorize_request_token(self, request_id): if isinstance(request_id, bytes): request_id = request_id.decode() - return '/OS-OAUTH1/authorize/%s' % (request_id) + return f'/OS-OAUTH1/authorize/{request_id}' def _get_access_token(self): consumer = self._create_single_consumer() @@ -986,7 +971,7 @@ class TestCredentialEc2(CredentialBaseTestCase): ) def _get_ec2_cred_uri(self): - return '/users/%s/credentials/OS-EC2' % self.user_id + return f'/users/{self.user_id}/credentials/OS-EC2' def _get_ec2_cred(self): uri = self._get_ec2_cred_uri() diff --git a/keystone/tests/unit/test_v3_domain_config.py b/keystone/tests/unit/test_v3_domain_config.py index 68356efbcb..4ea4e6e391 100644 --- a/keystone/tests/unit/test_v3_domain_config.py +++ b/keystone/tests/unit/test_v3_domain_config.py @@ -115,8 +115,9 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): self.domain['id'], self.config ) self.delete( - '/domains/%(domain_id)s/config/ldap' - % {'domain_id': self.domain['id']} + '/domains/{domain_id}/config/ldap'.format( + domain_id=self.domain['id'] + ) ) res = PROVIDERS.domain_config_api.get_config(self.domain['id']) self.assertNotIn('ldap', res) @@ -133,8 +134,7 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): ) invalid_domain_id = uuid.uuid4().hex self.delete( - '/domains/%(domain_id)s/config/ldap' - % {'domain_id': invalid_domain_id}, + f'/domains/{invalid_domain_id}/config/ldap', expected_status=exception.DomainNotFound.code, ) @@ -171,9 +171,7 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): self.domain['id'], self.config ) invalid_domain_id = uuid.uuid4().hex - url = '/domains/{domain_id}/config/ldap'.format( - domain_id=invalid_domain_id - ) + url = f'/domains/{invalid_domain_id}/config/ldap' self.get(url, expected_status=exception.DomainNotFound.code) self.head(url, expected_status=exception.DomainNotFound.code) @@ -202,9 +200,7 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): self.domain['id'], self.config ) invalid_domain_id = uuid.uuid4().hex - url = '/domains/{domain_id}/config/ldap/url'.format( - domain_id=invalid_domain_id - ) + url = f'/domains/{invalid_domain_id}/config/ldap/url' self.get(url, expected_status=exception.DomainNotFound.code) self.head(url, expected_status=exception.DomainNotFound.code) @@ -246,9 +242,7 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): config = {'ldap': {'url': uuid.uuid4().hex}} PROVIDERS.domain_config_api.create_config(self.domain['id'], config) invalid_domain_id = uuid.uuid4().hex - url = '/domains/{domain_id}/config/identity'.format( - domain_id=invalid_domain_id - ) + url = f'/domains/{invalid_domain_id}/config/identity' self.get(url, expected_status=exception.DomainNotFound.code) self.head(url, expected_status=exception.DomainNotFound.code) @@ -279,9 +273,7 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): config = {'ldap': {'url': uuid.uuid4().hex}} PROVIDERS.domain_config_api.create_config(self.domain['id'], config) invalid_domain_id = uuid.uuid4().hex - url = '/domains/{domain_id}/config/ldap/user_tree_dn'.format( - domain_id=invalid_domain_id - ) + url = f'/domains/{invalid_domain_id}/config/ldap/user_tree_dn' self.get(url, expected_status=exception.DomainNotFound.code) self.head(url, expected_status=exception.DomainNotFound.code) @@ -337,8 +329,9 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): 'ldap': {'url': uuid.uuid4().hex, 'user_filter': uuid.uuid4().hex} } r = self.patch( - '/domains/%(domain_id)s/config/ldap' - % {'domain_id': self.domain['id']}, + '/domains/{domain_id}/config/ldap'.format( + domain_id=self.domain['id'] + ), body={'config': new_config}, ) res = PROVIDERS.domain_config_api.get_config(self.domain['id']) @@ -365,8 +358,7 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): } invalid_domain_id = uuid.uuid4().hex self.patch( - '/domains/%(domain_id)s/config/ldap' - % {'domain_id': invalid_domain_id}, + f'/domains/{invalid_domain_id}/config/ldap', body={'config': new_config}, expected_status=exception.DomainNotFound.code, ) @@ -387,8 +379,9 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): } } self.patch( - '/domains/%(domain_id)s/config/%(invalid_group)s' - % {'domain_id': self.domain['id'], 'invalid_group': invalid_group}, + '/domains/{domain_id}/config/{invalid_group}'.format( + domain_id=self.domain['id'], invalid_group=invalid_group + ), body={'config': new_config}, expected_status=http.client.FORBIDDEN, ) @@ -398,8 +391,9 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): PROVIDERS.domain_config_api.create_config(self.domain['id'], config) new_config = {'identity': {'driver': uuid.uuid4().hex}} self.patch( - '/domains/%(domain_id)s/config/identity' - % {'domain_id': self.domain['id']}, + '/domains/{domain_id}/config/identity'.format( + domain_id=self.domain['id'] + ), body={'config': new_config}, expected_status=http.client.NOT_FOUND, ) @@ -423,8 +417,7 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): } invalid_domain_id = uuid.uuid4().hex self.patch( - '/domains/%(domain_id)s/config/%(invalid_group)s' - % {'domain_id': invalid_domain_id, 'invalid_group': invalid_group}, + f'/domains/{invalid_domain_id}/config/{invalid_group}', body={'config': new_config}, expected_status=exception.DomainNotFound.code, ) @@ -436,8 +429,9 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): ) new_config = {'url': uuid.uuid4().hex} r = self.patch( - '/domains/%(domain_id)s/config/ldap/url' - % {'domain_id': self.domain['id']}, + '/domains/{domain_id}/config/ldap/url'.format( + domain_id=self.domain['id'] + ), body={'config': new_config}, ) res = PROVIDERS.domain_config_api.get_config(self.domain['id']) @@ -459,8 +453,7 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): new_config = {'url': uuid.uuid4().hex} invalid_domain_id = uuid.uuid4().hex self.patch( - '/domains/%(domain_id)s/config/ldap/url' - % {'domain_id': invalid_domain_id}, + f'/domains/{invalid_domain_id}/config/ldap/url', body={'config': new_config}, expected_status=exception.DomainNotFound.code, ) @@ -475,11 +468,9 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): # Trying to update an option that is neither whitelisted or sensitive # should result in Forbidden. self.patch( - '/domains/%(domain_id)s/config/ldap/%(invalid_option)s' - % { - 'domain_id': self.domain['id'], - 'invalid_option': invalid_option, - }, + '/domains/{domain_id}/config/ldap/{invalid_option}'.format( + domain_id=self.domain['id'], invalid_option=invalid_option + ), body={'config': new_config}, expected_status=http.client.FORBIDDEN, ) @@ -487,8 +478,9 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): # config should result in NotFound new_config = {'suffix': uuid.uuid4().hex} self.patch( - '/domains/%(domain_id)s/config/ldap/suffix' - % {'domain_id': self.domain['id']}, + '/domains/{domain_id}/config/ldap/suffix'.format( + domain_id=self.domain['id'] + ), body={'config': new_config}, expected_status=http.client.NOT_FOUND, ) @@ -507,11 +499,7 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): new_config = {'ldap': {invalid_option: uuid.uuid4().hex}} invalid_domain_id = uuid.uuid4().hex self.patch( - '/domains/%(domain_id)s/config/ldap/%(invalid_option)s' - % { - 'domain_id': invalid_domain_id, - 'invalid_option': invalid_option, - }, + f'/domains/{invalid_domain_id}/config/ldap/{invalid_option}', body={'config': new_config}, expected_status=exception.DomainNotFound.code, ) @@ -576,7 +564,7 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): ) # Now try a totally invalid group - url = '/domains/config/%s/default' % uuid.uuid4().hex + url = f'/domains/config/{uuid.uuid4().hex}/default' self.get(url, expected_status=http.client.FORBIDDEN) self.head(url, expected_status=http.client.FORBIDDEN) @@ -596,13 +584,12 @@ class DomainConfigTestCase(test_v3.RestfulTestCase): def test_get_head_config_default_for_invalid_option(self): """Returning invalid configuration options is invalid.""" - url = '/domains/config/ldap/%s/default' % uuid.uuid4().hex + url = f'/domains/config/ldap/{uuid.uuid4().hex}/default' self.get(url, expected_status=http.client.FORBIDDEN) self.head(url, expected_status=http.client.FORBIDDEN) class SecurityRequirementsTestCase(test_v3.RestfulTestCase): - def setUp(self): super().setUp() @@ -720,8 +707,7 @@ class SecurityRequirementsTestCase(test_v3.RestfulTestCase): password_regex_description=password_regex_description, ) url = '/domains/{domain_id}/config/{group}'.format( - domain_id=domain['id'], - group='security_compliance', + domain_id=domain['id'], group='security_compliance' ) # Make sure regular users and administrators are forbidden from doing @@ -799,11 +785,7 @@ class SecurityRequirementsTestCase(test_v3.RestfulTestCase): ) group = 'security_compliance' option = 'password_regex' - url = '/domains/{domain_id}/config/{group}/{option}'.format( - domain_id=CONF.identity.default_domain_id, - group=group, - option=option, - ) + url = f'/domains/{CONF.identity.default_domain_id}/config/{group}/{option}' # Make sure regular users and administrators can ask for the # password regular expression. @@ -835,11 +817,7 @@ class SecurityRequirementsTestCase(test_v3.RestfulTestCase): ) group = 'security_compliance' option = 'password_regex_description' - url = '/domains/{domain_id}/config/{group}/{option}'.format( - domain_id=CONF.identity.default_domain_id, - group=group, - option=option, - ) + url = f'/domains/{CONF.identity.default_domain_id}/config/{group}/{option}' # Make sure regular users and administrators can ask for the # password regular expression. @@ -867,11 +845,7 @@ class SecurityRequirementsTestCase(test_v3.RestfulTestCase): """When an option isn't set, we should explicitly return None.""" group = 'security_compliance' option = 'password_regex' - url = '/domains/{domain_id}/config/{group}/{option}'.format( - domain_id=CONF.identity.default_domain_id, - group=group, - option=option, - ) + url = f'/domains/{CONF.identity.default_domain_id}/config/{group}/{option}' # Make sure regular users and administrators can ask for the password # regular expression, but since it isn't set the returned value should @@ -895,11 +869,7 @@ class SecurityRequirementsTestCase(test_v3.RestfulTestCase): """When an option isn't set, we should explicitly return None.""" group = 'security_compliance' option = 'password_regex_description' - url = '/domains/{domain_id}/config/{group}/{option}'.format( - domain_id=CONF.identity.default_domain_id, - group=group, - option=option, - ) + url = f'/domains/{CONF.identity.default_domain_id}/config/{group}/{option}' # Make sure regular users and administrators can ask for the password # regular expression description, but since it isn't set the returned @@ -965,10 +935,7 @@ class SecurityRequirementsTestCase(test_v3.RestfulTestCase): project_id=project['id'], ) user_token = self.get_requested_token(user_token) - url = '/domains/{domain_id}/config/{group}'.format( - domain_id=CONF.identity.default_domain_id, - group=group, - ) + url = f'/domains/{CONF.identity.default_domain_id}/config/{group}' response = self.get(url, token=user_token) self.assertEqual( response.result['config'][group]['password_regex'], password_regex @@ -1018,11 +985,7 @@ class SecurityRequirementsTestCase(test_v3.RestfulTestCase): """Make sure any updates to security compliance options fail.""" group = 'security_compliance' option = 'password_regex' - url = '/domains/{domain_id}/config/{group}/{option}'.format( - domain_id=CONF.identity.default_domain_id, - group=group, - option=option, - ) + url = f'/domains/{CONF.identity.default_domain_id}/config/{group}/{option}' new_config = {group: {option: uuid.uuid4().hex}} # Make sure regular users and administrators aren't allowed to modify @@ -1044,11 +1007,7 @@ class SecurityRequirementsTestCase(test_v3.RestfulTestCase): """Make sure any updates to security compliance options fail.""" group = 'security_compliance' option = 'password_regex_description' - url = '/domains/{domain_id}/config/{group}/{option}'.format( - domain_id=CONF.identity.default_domain_id, - group=group, - option=option, - ) + url = f'/domains/{CONF.identity.default_domain_id}/config/{group}/{option}' new_config = {group: {option: uuid.uuid4().hex}} # Make sure regular users and administrators aren't allowed to modify @@ -1075,11 +1034,7 @@ class SecurityRequirementsTestCase(test_v3.RestfulTestCase): """ group = 'security_compliance' option = 'lockout_failure_attempts' - url = '/domains/{domain_id}/config/{group}/{option}'.format( - domain_id=CONF.identity.default_domain_id, - group=group, - option=option, - ) + url = f'/domains/{CONF.identity.default_domain_id}/config/{group}/{option}' new_config = {group: {option: 1}} # Make sure this behavior is not possible for regular users or diff --git a/keystone/tests/unit/test_v3_endpoint_policy.py b/keystone/tests/unit/test_v3_endpoint_policy.py index 42a984db69..b4f7462a7b 100644 --- a/keystone/tests/unit/test_v3_endpoint_policy.py +++ b/keystone/tests/unit/test_v3_endpoint_policy.py @@ -82,54 +82,50 @@ class EndpointPolicyTestCase(test_v3.RestfulTestCase): def test_crud_for_policy_for_explicit_endpoint(self): """PUT, HEAD and DELETE for explicit endpoint policy.""" url = ( - '/policies/%(policy_id)s/OS-ENDPOINT-POLICY' - '/endpoints/%(endpoint_id)s' - ) % { - 'policy_id': self.policy['id'], - 'endpoint_id': self.endpoint['id'], - } + '/policies/{policy_id}/OS-ENDPOINT-POLICY' + '/endpoints/{endpoint_id}' + ).format(policy_id=self.policy['id'], endpoint_id=self.endpoint['id']) self._crud_test(url) def test_crud_for_policy_for_service(self): """PUT, HEAD and DELETE for service endpoint policy.""" url = ( - '/policies/%(policy_id)s/OS-ENDPOINT-POLICY' - '/services/%(service_id)s' - ) % {'policy_id': self.policy['id'], 'service_id': self.service['id']} + '/policies/{policy_id}/OS-ENDPOINT-POLICY' '/services/{service_id}' + ).format(policy_id=self.policy['id'], service_id=self.service['id']) self._crud_test(url) def test_crud_for_policy_for_region_and_service(self): """PUT, HEAD and DELETE for region and service endpoint policy.""" url = ( - '/policies/%(policy_id)s/OS-ENDPOINT-POLICY' - '/services/%(service_id)s/regions/%(region_id)s' - ) % { - 'policy_id': self.policy['id'], - 'service_id': self.service['id'], - 'region_id': self.region['id'], - } + '/policies/{policy_id}/OS-ENDPOINT-POLICY' + '/services/{service_id}/regions/{region_id}' + ).format( + policy_id=self.policy['id'], + service_id=self.service['id'], + region_id=self.region['id'], + ) self._crud_test(url) def test_get_policy_for_endpoint(self): """GET /endpoints/{endpoint_id}/policy.""" self.put( - '/policies/%(policy_id)s/OS-ENDPOINT-POLICY' - '/endpoints/%(endpoint_id)s' - % { - 'policy_id': self.policy['id'], - 'endpoint_id': self.endpoint['id'], - } + '/policies/{policy_id}/OS-ENDPOINT-POLICY' + '/endpoints/{endpoint_id}'.format( + policy_id=self.policy['id'], endpoint_id=self.endpoint['id'] + ) ) self.head( - '/endpoints/%(endpoint_id)s/OS-ENDPOINT-POLICY' - '/policy' % {'endpoint_id': self.endpoint['id']}, + '/endpoints/{endpoint_id}/OS-ENDPOINT-POLICY' '/policy'.format( + endpoint_id=self.endpoint['id'] + ), expected_status=http.client.OK, ) r = self.get( - '/endpoints/%(endpoint_id)s/OS-ENDPOINT-POLICY' - '/policy' % {'endpoint_id': self.endpoint['id']} + '/endpoints/{endpoint_id}/OS-ENDPOINT-POLICY' '/policy'.format( + endpoint_id=self.endpoint['id'] + ) ) self.assertValidPolicyResponse(r, ref=self.policy) @@ -146,12 +142,9 @@ class EndpointPolicyTestCase(test_v3.RestfulTestCase): def test_endpoint_association_cleanup_when_endpoint_deleted(self): url = ( - '/policies/%(policy_id)s/OS-ENDPOINT-POLICY' - '/endpoints/%(endpoint_id)s' - ) % { - 'policy_id': self.policy['id'], - 'endpoint_id': self.endpoint['id'], - } + '/policies/{policy_id}/OS-ENDPOINT-POLICY' + '/endpoints/{endpoint_id}' + ).format(policy_id=self.policy['id'], endpoint_id=self.endpoint['id']) self.put(url) self.head(url) @@ -164,13 +157,13 @@ class EndpointPolicyTestCase(test_v3.RestfulTestCase): def test_region_service_association_cleanup_when_region_deleted(self): url = ( - '/policies/%(policy_id)s/OS-ENDPOINT-POLICY' - '/services/%(service_id)s/regions/%(region_id)s' - ) % { - 'policy_id': self.policy['id'], - 'service_id': self.service['id'], - 'region_id': self.region['id'], - } + '/policies/{policy_id}/OS-ENDPOINT-POLICY' + '/services/{service_id}/regions/{region_id}' + ).format( + policy_id=self.policy['id'], + service_id=self.service['id'], + region_id=self.region['id'], + ) self.put(url) self.head(url) @@ -181,13 +174,13 @@ class EndpointPolicyTestCase(test_v3.RestfulTestCase): def test_region_service_association_cleanup_when_service_deleted(self): url = ( - '/policies/%(policy_id)s/OS-ENDPOINT-POLICY' - '/services/%(service_id)s/regions/%(region_id)s' - ) % { - 'policy_id': self.policy['id'], - 'service_id': self.service['id'], - 'region_id': self.region['id'], - } + '/policies/{policy_id}/OS-ENDPOINT-POLICY' + '/services/{service_id}/regions/{region_id}' + ).format( + policy_id=self.policy['id'], + service_id=self.service['id'], + region_id=self.region['id'], + ) self.put(url) self.head(url) @@ -200,9 +193,8 @@ class EndpointPolicyTestCase(test_v3.RestfulTestCase): def test_service_association_cleanup_when_service_deleted(self): url = ( - '/policies/%(policy_id)s/OS-ENDPOINT-POLICY' - '/services/%(service_id)s' - ) % {'policy_id': self.policy['id'], 'service_id': self.service['id']} + '/policies/{policy_id}/OS-ENDPOINT-POLICY' '/services/{service_id}' + ).format(policy_id=self.policy['id'], service_id=self.service['id']) self.put(url) self.get(url, expected_status=http.client.NO_CONTENT) @@ -215,9 +207,8 @@ class EndpointPolicyTestCase(test_v3.RestfulTestCase): def test_service_association_cleanup_when_policy_deleted(self): url = ( - '/policies/%(policy_id)s/OS-ENDPOINT-POLICY' - '/services/%(service_id)s' - ) % {'policy_id': self.policy['id'], 'service_id': self.service['id']} + '/policies/{policy_id}/OS-ENDPOINT-POLICY' '/services/{service_id}' + ).format(policy_id=self.policy['id'], service_id=self.service['id']) self.put(url) self.get(url, expected_status=http.client.NO_CONTENT) @@ -239,24 +230,17 @@ class JsonHomeTests(test_v3.JsonHomeTestMixin): ) JSON_HOME_DATA = { - EXTENSION_LOCATION - + '/endpoint_policy': { + EXTENSION_LOCATION + '/endpoint_policy': { 'href-template': '/endpoints/{endpoint_id}/OS-ENDPOINT-POLICY/' 'policy', - 'href-vars': { - 'endpoint_id': PARAM_LOCATION + '/endpoint_id', - }, + 'href-vars': {'endpoint_id': PARAM_LOCATION + '/endpoint_id'}, }, - EXTENSION_LOCATION - + '/policy_endpoints': { + EXTENSION_LOCATION + '/policy_endpoints': { 'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/' 'endpoints', - 'href-vars': { - 'policy_id': PARAM_LOCATION + '/policy_id', - }, + 'href-vars': {'policy_id': PARAM_LOCATION + '/policy_id'}, }, - EXTENSION_LOCATION - + '/endpoint_policy_association': { + EXTENSION_LOCATION + '/endpoint_policy_association': { 'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/' 'endpoints/{endpoint_id}', 'href-vars': { @@ -264,8 +248,7 @@ class JsonHomeTests(test_v3.JsonHomeTestMixin): 'endpoint_id': PARAM_LOCATION + '/endpoint_id', }, }, - EXTENSION_LOCATION - + '/service_policy_association': { + EXTENSION_LOCATION + '/service_policy_association': { 'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/' 'services/{service_id}', 'href-vars': { @@ -273,8 +256,7 @@ class JsonHomeTests(test_v3.JsonHomeTestMixin): 'service_id': PARAM_LOCATION + '/service_id', }, }, - EXTENSION_LOCATION - + '/region_and_service_policy_association': { + EXTENSION_LOCATION + '/region_and_service_policy_association': { 'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/' 'services/{service_id}/regions/{region_id}', 'href-vars': { diff --git a/keystone/tests/unit/test_v3_federation.py b/keystone/tests/unit/test_v3_federation.py index f831e3c8c3..8599bd2801 100644 --- a/keystone/tests/unit/test_v3_federation.py +++ b/keystone/tests/unit/test_v3_federation.py @@ -58,7 +58,6 @@ def dummy_validator(*args, **kwargs): class FederatedSetupMixin: - ACTION = 'authenticate' IDP = 'ORG_IDP' PROTOCOL = 'saml2' @@ -104,7 +103,6 @@ class FederatedSetupMixin: self.assertEqual(token_projects, projects_ref) def _check_scoped_token_attributes(self, token): - for obj in ( 'user', 'catalog', @@ -369,9 +367,7 @@ class FederatedSetupMixin: ], 'remote': [ {'type': 'UserName'}, - { - 'type': 'Email', - }, + {'type': 'Email'}, {'type': 'orgPersonType', 'any_one_of': ['Employee']}, ], }, @@ -382,9 +378,7 @@ class FederatedSetupMixin: ], 'remote': [ {'type': self.ASSERTION_PREFIX + 'UserName'}, - { - 'type': self.ASSERTION_PREFIX + 'Email', - }, + {'type': self.ASSERTION_PREFIX + 'Email'}, { 'type': self.ASSERTION_PREFIX + 'orgPersonType', 'any_one_of': ['SuperEmployee'], @@ -425,12 +419,8 @@ class FederatedSetupMixin: {'user': {'name': '{0}', 'id': '{1}'}}, ], 'remote': [ - { - 'type': 'UserName', - }, - { - 'type': 'Email', - }, + {'type': 'UserName'}, + {'type': 'Email'}, {'type': 'FirstName', 'any_one_of': ['Jill']}, {'type': 'LastName', 'any_one_of': ['Smith']}, ], @@ -441,12 +431,8 @@ class FederatedSetupMixin: {'user': {'name': '{0}', 'id': '{1}'}}, ], 'remote': [ - { - 'type': 'UserName', - }, - { - 'type': 'Email', - }, + {'type': 'UserName'}, + {'type': 'Email'}, { 'type': 'Email', 'any_one_of': ['testacct@example.com'], @@ -466,12 +452,8 @@ class FederatedSetupMixin: }, ], "remote": [ - { - 'type': 'UserName', - }, - { - 'type': 'Email', - }, + {'type': 'UserName'}, + {'type': 'Email'}, { "type": "orgPersonType", "any_one_of": ["CEO", "CTO"], @@ -489,12 +471,8 @@ class FederatedSetupMixin: }, ], "remote": [ - { - "type": "UserName", - }, - { - "type": "Email", - }, + {"type": "UserName"}, + {"type": "Email"}, {"type": "orgPersonType", "any_one_of": ["Managers"]}, ], }, @@ -509,12 +487,8 @@ class FederatedSetupMixin: }, ], "remote": [ - { - "type": "UserName", - }, - { - "type": "Email", - }, + {"type": "UserName"}, + {"type": "Email"}, {"type": "UserName", "any_one_of": ["IamTester"]}, ], }, @@ -549,12 +523,8 @@ class FederatedSetupMixin: { "local": [{'user': {'name': '{0}', 'id': '{1}'}}], "remote": [ - { - 'type': 'UserName', - }, - { - 'type': 'Email', - }, + {'type': 'UserName'}, + {'type': 'Email'}, { 'type': 'orgPersonType', 'any_one_of': ['NoGroupsOrg'], @@ -777,7 +747,7 @@ class FederatedIdentityProviderTests(test_v3.RestfulTestCase): def _create_mapping(self, mapping_id): mapping = mapping_fixtures.MAPPING_EPHEMERAL_USER mapping['id'] = mapping_id - url = '/OS-FEDERATION/mappings/%s' % mapping_id + url = f'/OS-FEDERATION/mappings/{mapping_id}' self.put( url, body={'mapping': mapping}, expected_status=http.client.CREATED ) @@ -1544,21 +1514,18 @@ class FederatedIdentityProviderTests(test_v3.RestfulTestCase): # DELETE/PATCH/PUT on non-trailing `/` results in # METHOD_NOT_ALLOWED c.delete( - '/v3/OS-FEDERATION/identity_providers/%(idp_id)s' - '/protocols' % {'idp_id': idp_id}, + f'/v3/OS-FEDERATION/identity_providers/{idp_id}' '/protocols', headers={'X-Auth-Token': token}, expected_status_code=http.client.METHOD_NOT_ALLOWED, ) c.patch( - '/v3/OS-FEDERATION/identity_providers/%(idp_id)s' - '/protocols/' % {'idp_id': idp_id}, + f'/v3/OS-FEDERATION/identity_providers/{idp_id}' '/protocols/', json={'protocol': protocol}, headers={'X-Auth-Token': token}, expected_status_code=http.client.METHOD_NOT_ALLOWED, ) c.put( - '/v3/OS-FEDERATION/identity_providers/%(idp_id)s' - '/protocols' % {'idp_id': idp_id}, + f'/v3/OS-FEDERATION/identity_providers/{idp_id}' '/protocols', json={'protocol': protocol}, headers={'X-Auth-Token': token}, expected_status_code=http.client.METHOD_NOT_ALLOWED, @@ -1568,21 +1535,18 @@ class FederatedIdentityProviderTests(test_v3.RestfulTestCase): # remapped to without the trailing '/' by the normalization # middleware. c.delete( - '/v3/OS-FEDERATION/identity_providers/%(idp_id)s' - '/protocols/' % {'idp_id': idp_id}, + f'/v3/OS-FEDERATION/identity_providers/{idp_id}' '/protocols/', headers={'X-Auth-Token': token}, expected_status_code=http.client.METHOD_NOT_ALLOWED, ) c.patch( - '/v3/OS-FEDERATION/identity_providers/%(idp_id)s' - '/protocols/' % {'idp_id': idp_id}, + f'/v3/OS-FEDERATION/identity_providers/{idp_id}' '/protocols/', json={'protocol': protocol}, headers={'X-Auth-Token': token}, expected_status_code=http.client.METHOD_NOT_ALLOWED, ) c.put( - '/v3/OS-FEDERATION/identity_providers/%(idp_id)s' - '/protocols/' % {'idp_id': idp_id}, + f'/v3/OS-FEDERATION/identity_providers/{idp_id}' '/protocols/', json={'protocol': protocol}, headers={'X-Auth-Token': token}, expected_status_code=http.client.METHOD_NOT_ALLOWED, @@ -1632,7 +1596,7 @@ class FederatedIdentityProviderTests(test_v3.RestfulTestCase): proto_id = proto_id['id'] protocol_ids.append(proto_id) - url = "%s/protocols" % idp_id + url = f"{idp_id}/protocols" url = self.base_url(suffix=url) resp = self.get(url) self.assertValidListResponse( @@ -1979,7 +1943,6 @@ class MappingCRUDTests(test_v3.RestfulTestCase): class FederatedTokenTests(test_v3.RestfulTestCase, FederatedSetupMixin): - def auth_plugin_config_override(self): methods = ['saml2', 'token'] super().auth_plugin_config_override(methods) @@ -2487,7 +2450,7 @@ class FederatedTokenTests(test_v3.RestfulTestCase, FederatedSetupMixin): projects_resp = r.result['projects'] projects = {p['id'] for p in projects_resp} self.assertEqual( - projects_ref, projects, 'match failed for url %s' % url + projects_ref, projects, f'match failed for url {url}' ) # TODO(samueldmq): Create another test class for role inheritance tests. @@ -2530,7 +2493,7 @@ class FederatedTokenTests(test_v3.RestfulTestCase, FederatedSetupMixin): self.assertIn( expected_project_id, project_ids, - 'Projects match failed for url %s' % url, + f'Projects match failed for url {url}', ) def test_list_domains(self): @@ -2558,7 +2521,7 @@ class FederatedTokenTests(test_v3.RestfulTestCase, FederatedSetupMixin): domains_resp = r.result['domains'] domains = {p['id'] for p in domains_resp} self.assertEqual( - domains_ref, domains, 'match failed for url %s' % url + domains_ref, domains, f'match failed for url {url}' ) def test_full_workflow(self): @@ -2674,11 +2637,7 @@ class FederatedTokenTests(test_v3.RestfulTestCase, FederatedSetupMixin): "local": [ {"groups": "{0}", "domain": {"name": domain_name}} ], - "remote": [ - { - "type": "REMOTE_USER_GROUPS", - } - ], + "remote": [{"type": "REMOTE_USER_GROUPS"}], }, ] } @@ -2790,11 +2749,7 @@ class FederatedTokenTests(test_v3.RestfulTestCase, FederatedSetupMixin): "local": [ {"groups": "{0}", "domain": {"name": domain_name}} ], - "remote": [ - { - "type": "REMOTE_USER_GROUPS", - } - ], + "remote": [{"type": "REMOTE_USER_GROUPS"}], }, ] } @@ -2891,11 +2846,7 @@ class FederatedTokenTests(test_v3.RestfulTestCase, FederatedSetupMixin): "local": [ {"groups": "{0}", "domain": {"name": domain_name}} ], - "remote": [ - { - "type": "REMOTE_USER_GROUPS", - } - ], + "remote": [{"type": "REMOTE_USER_GROUPS"}], }, ] } @@ -3829,7 +3780,7 @@ class JsonHomeTests(test_v3.RestfulTestCase, test_v3.JsonHomeTestMixin): 'idp_id': 'https://docs.openstack.org/api/openstack-identity/3' '/ext/OS-FEDERATION/1.0/param/idp_id' }, - }, + } } @@ -3848,7 +3799,6 @@ def _load_xml(filename): class SAMLGenerationTests(test_v3.RestfulTestCase): - SP_AUTH_URL = ( 'http://beta.com:5000/v3/OS-FEDERATION/identity_providers' '/BETA/protocols/saml2/auth' @@ -4426,12 +4376,11 @@ class SAMLGenerationTests(test_v3.RestfulTestCase): # The function __str__ in subprocess.CalledProcessError is # different between py3.6 and lower python version. expected_log = ( - r"Error when signing assertion, reason: Command '%s' returned " - r"non-zero exit status %s\.? %s\n" - % (CONF.saml.xmlsec1_binary, sample_returncode, sample_output) + rf"Error when signing assertion, reason: Command '{CONF.saml.xmlsec1_binary}' returned " + rf"non-zero exit status {sample_returncode}\.? {sample_output}\n" ) self.assertRegex( - logger_fixture.output, re.compile(r'%s' % expected_log) + logger_fixture.output, re.compile(rf'{expected_log}') ) @mock.patch('oslo_utils.fileutils.write_to_tempfile') @@ -4450,15 +4399,14 @@ class SAMLGenerationTests(test_v3.RestfulTestCase): self.signed_assertion, ) expected_log = ( - 'Error when signing assertion, reason: %s\n' % exception_msg + f'Error when signing assertion, reason: {exception_msg}\n' ) self.assertIn(expected_log, logger_fixture.output) def test_sign_assertion_logs_message_if_xmlsec1_is_not_installed(self): with mock.patch.object(subprocess, 'check_output') as co_mock: co_mock.side_effect = subprocess.CalledProcessError( - returncode=1, - cmd=CONF.saml.xmlsec1_binary, + returncode=1, cmd=CONF.saml.xmlsec1_binary ) logger_fixture = self.useFixture(fixtures.LoggerFixture()) self.assertRaises( @@ -5036,7 +4984,7 @@ class WebSSOTests(FederatedTokenTests): def test_federated_sso_auth(self): environment = { self.REMOTE_ID_ATTR: self.REMOTE_IDS[0], - 'QUERY_STRING': 'origin=%s' % self.ORIGIN, + 'QUERY_STRING': f'origin={self.ORIGIN}', } environment.update(mapping_fixtures.EMPLOYEE_ASSERTION) with self.make_request(environ=environment): @@ -5069,7 +5017,7 @@ class WebSSOTests(FederatedTokenTests): environment = { self.PROTOCOL_REMOTE_ID_ATTR: self.REMOTE_IDS[0], - 'QUERY_STRING': 'origin=%s' % self.ORIGIN, + 'QUERY_STRING': f'origin={self.ORIGIN}', } environment.update(mapping_fixtures.EMPLOYEE_ASSERTION) with self.make_request(environ=environment): @@ -5084,7 +5032,7 @@ class WebSSOTests(FederatedTokenTests): def test_federated_sso_auth_bad_remote_id(self): environment = { self.REMOTE_ID_ATTR: self.IDP, - 'QUERY_STRING': 'origin=%s' % self.ORIGIN, + 'QUERY_STRING': f'origin={self.ORIGIN}', } environment.update(mapping_fixtures.EMPLOYEE_ASSERTION) with self.make_request(environ=environment): @@ -5117,7 +5065,7 @@ class WebSSOTests(FederatedTokenTests): def test_federated_sso_auth_protocol_not_found(self): environment = { self.REMOTE_ID_ATTR: self.REMOTE_IDS[0], - 'QUERY_STRING': 'origin=%s' % self.ORIGIN, + 'QUERY_STRING': f'origin={self.ORIGIN}', } environment.update(mapping_fixtures.EMPLOYEE_ASSERTION) with self.make_request(environ=environment): @@ -5130,7 +5078,7 @@ class WebSSOTests(FederatedTokenTests): def test_federated_sso_untrusted_dashboard(self): environment = { self.REMOTE_ID_ATTR: self.REMOTE_IDS[0], - 'QUERY_STRING': 'origin=%s' % uuid.uuid4().hex, + 'QUERY_STRING': f'origin={uuid.uuid4().hex}', } environment.update(mapping_fixtures.EMPLOYEE_ASSERTION) with self.make_request(environ=environment): @@ -5143,7 +5091,7 @@ class WebSSOTests(FederatedTokenTests): def test_federated_sso_untrusted_dashboard_bad_remote_id(self): environment = { self.REMOTE_ID_ATTR: self.IDP, - 'QUERY_STRING': 'origin=%s' % uuid.uuid4().hex, + 'QUERY_STRING': f'origin={uuid.uuid4().hex}', } environment.update(mapping_fixtures.EMPLOYEE_ASSERTION) with self.make_request(environ=environment): @@ -5156,7 +5104,7 @@ class WebSSOTests(FederatedTokenTests): def test_federated_sso_missing_remote_id(self): environment = copy.deepcopy(mapping_fixtures.EMPLOYEE_ASSERTION) with self.make_request( - environ=environment, query_string='origin=%s' % self.ORIGIN + environ=environment, query_string=f'origin={self.ORIGIN}' ): self.assertRaises( exception.Unauthorized, @@ -5168,7 +5116,7 @@ class WebSSOTests(FederatedTokenTests): environment = {self.REMOTE_ID_ATTR: self.REMOTE_IDS[0]} environment.update(mapping_fixtures.EMPLOYEE_ASSERTION) with self.make_request( - environ=environment, query_string='origin=%s' % self.ORIGIN + environ=environment, query_string=f'origin={self.ORIGIN}' ): resp = auth_api.AuthFederationWebSSOIDPsResource._perform_auth( self.idp['id'], self.PROTOCOL @@ -5194,7 +5142,7 @@ class WebSSOTests(FederatedTokenTests): ) environment = { self.PROTOCOL_REMOTE_ID_ATTR: self.REMOTE_IDS[0], - 'QUERY_STRING': 'origin=%s' % self.ORIGIN, + 'QUERY_STRING': f'origin={self.ORIGIN}', } environment.update(mapping_fixtures.EMPLOYEE_ASSERTION) with self.make_request(environ=environment): diff --git a/keystone/tests/unit/test_v3_filters.py b/keystone/tests/unit/test_v3_filters.py index 742f0e8e8f..67585e97e4 100644 --- a/keystone/tests/unit/test_v3_filters.py +++ b/keystone/tests/unit/test_v3_filters.py @@ -117,7 +117,7 @@ class IdentityTestFilteredCase(filtering.FilterTests, test_v3.RestfulTestCase): """ self._set_policy({"identity:list_users": []}) - url_by_name = '/users?domain_id=%s' % self.domainB['id'] + url_by_name = '/users?domain_id={}'.format(self.domainB['id']) r = self.get(url_by_name, auth=self.auth) # We should get back two users, those in DomainB id_list = self._get_id_list_from_ref_list(r.result.get('users')) @@ -146,14 +146,14 @@ class IdentityTestFilteredCase(filtering.FilterTests, test_v3.RestfulTestCase): # Try a few ways of specifying 'false' for val in ('0', 'false', 'False', 'FALSE', 'n', 'no', 'off'): - r = self.get('/domains?enabled=%s' % val, auth=self.auth) + r = self.get(f'/domains?enabled={val}', auth=self.auth) id_list = self._get_id_list_from_ref_list(r.result.get('domains')) self.assertEqual([self.domainC['id']], id_list) # Now try a few ways of specifying 'true' when we should get back # the other two domains, plus the default domain for val in ('1', 'true', 'True', 'TRUE', 'y', 'yes', 'on'): - r = self.get('/domains?enabled=%s' % val, auth=self.auth) + r = self.get(f'/domains?enabled={val}', auth=self.auth) id_list = self._get_id_list_from_ref_list(r.result.get('domains')) self.assertEqual(3, len(id_list)) self.assertIn(self.domainA['id'], id_list) @@ -180,7 +180,7 @@ class IdentityTestFilteredCase(filtering.FilterTests, test_v3.RestfulTestCase): new_policy = {"identity:list_domains": []} self._set_policy(new_policy) - my_url = '/domains?enabled&name=%s' % self.domainA['name'] + my_url = '/domains?enabled&name={}'.format(self.domainA['name']) r = self.get(my_url, auth=self.auth) id_list = self._get_id_list_from_ref_list(r.result.get('domains')) self.assertEqual(1, len(id_list)) @@ -200,7 +200,7 @@ class IdentityTestFilteredCase(filtering.FilterTests, test_v3.RestfulTestCase): new_policy = {"identity:list_domains": []} self._set_policy(new_policy) - my_url = '/domains?enableds=0&name=%s' % self.domainA['name'] + my_url = '/domains?enableds=0&name={}'.format(self.domainA['name']) r = self.get(my_url, auth=self.auth) id_list = self._get_id_list_from_ref_list(r.result.get('domains')) @@ -227,7 +227,6 @@ class IdentityTestFilteredCase(filtering.FilterTests, test_v3.RestfulTestCase): # token. time = timeutils.utcnow() with freezegun.freeze_time(time) as frozen_datetime: - self._set_policy({"identity:list_users": []}) user = self.user1 user['name'] = '%my%name%' @@ -450,12 +449,7 @@ class IdentityPasswordExpiryFilteredTestCase( {operator}:{timestamp} """ - url = '/users?password_expires_at={}:{}&password_expires_at={}:{}'.format( - first_operator, - first_time, - second_operator, - second_time, - ) + url = f'/users?password_expires_at={first_operator}:{first_time}&password_expires_at={second_operator}:{second_time}' return url def _format_timestamp(self, timestamp): @@ -656,8 +650,7 @@ class IdentityPasswordExpiryFilteredTestCase( """ url = ( '/groups/' + self.group_id + '/users' - '?password_expires_at=%s:%s&password_expires_at=%s:%s' - % (first_operator, first_time, second_operator, second_time) + f'?password_expires_at={first_operator}:{first_time}&password_expires_at={second_operator}:{second_time}' ) return url @@ -896,17 +889,17 @@ class IdentityTestListLimitCase(IdentityTestFilteredCase): if entity == 'policy': plural = 'policies' else: - plural = '%ss' % entity + plural = f'{entity}s' - self._set_policy({"identity:list_%s" % plural: []}) + self._set_policy({f"identity:list_{plural}": []}) self.config_fixture.config(list_limit=5) self.config_fixture.config(group=driver, list_limit=None) - r = self.get('/%s' % plural, auth=self.auth) + r = self.get(f'/{plural}', auth=self.auth) self.assertEqual(5, len(r.result.get(plural))) self.assertIs(r.result.get('truncated'), True) self.config_fixture.config(group=driver, list_limit=4) - r = self.get('/%s' % plural, auth=self.auth) + r = self.get(f'/{plural}', auth=self.auth) self.assertEqual(4, len(r.result.get(plural))) self.assertIs(r.result.get('truncated'), True) diff --git a/keystone/tests/unit/test_v3_identity.py b/keystone/tests/unit/test_v3_identity.py index 407d17fc1b..799c0ed4c5 100644 --- a/keystone/tests/unit/test_v3_identity.py +++ b/keystone/tests/unit/test_v3_identity.py @@ -171,7 +171,7 @@ class IdentityTestCase(test_v3.RestfulTestCase): # Query strings are not normalized: so we get all users back (like # self.user), not just the ones in the specified domain. - r = self.get('/users?domain-id=%s' % domain1['id']) + r = self.get('/users?domain-id={}'.format(domain1['id'])) self.assertValidUserListResponse(r, ref=self.user) self.assertNotEqual(domain1['id'], self.user['domain_id']) @@ -192,7 +192,7 @@ class IdentityTestCase(test_v3.RestfulTestCase): # 'domain-id', then it'll be stored into extras rather than normalized, # and the user's actual 'domain_id' is not affected. r = self.patch( - '/users/%s' % user['id'], + '/users/{}'.format(user['id']), body={'user': {'domain-id': domain2['id']}}, ) self.assertEqual(domain2['id'], r.json['user']['domain-id']) @@ -341,8 +341,9 @@ class IdentityTestCase(test_v3.RestfulTestCase): def test_add_user_to_group(self): """Call ``PUT /groups/{group_id}/users/{user_id}``.""" self.put( - '/groups/%(group_id)s/users/%(user_id)s' - % {'group_id': self.group_id, 'user_id': self.user['id']} + '/groups/{group_id}/users/{user_id}'.format( + group_id=self.group_id, user_id=self.user['id'] + ) ) def test_list_head_groups_for_user(self): @@ -355,8 +356,9 @@ class IdentityTestCase(test_v3.RestfulTestCase): ) self.put( - '/groups/%(group_id)s/users/%(user_id)s' - % {'group_id': self.group_id, 'user_id': user1['id']} + '/groups/{group_id}/users/{user_id}'.format( + group_id=self.group_id, user_id=user1['id'] + ) ) # Scenarios below are written to test the default policy configuration @@ -399,42 +401,44 @@ class IdentityTestCase(test_v3.RestfulTestCase): def test_check_user_in_group(self): """Call ``HEAD /groups/{group_id}/users/{user_id}``.""" self.put( - '/groups/%(group_id)s/users/%(user_id)s' - % {'group_id': self.group_id, 'user_id': self.user['id']} + '/groups/{group_id}/users/{user_id}'.format( + group_id=self.group_id, user_id=self.user['id'] + ) ) self.head( - '/groups/%(group_id)s/users/%(user_id)s' - % {'group_id': self.group_id, 'user_id': self.user['id']} + '/groups/{group_id}/users/{user_id}'.format( + group_id=self.group_id, user_id=self.user['id'] + ) ) def test_list_head_users_in_group(self): """Call ``GET & HEAD /groups/{group_id}/users``.""" self.put( - '/groups/%(group_id)s/users/%(user_id)s' - % {'group_id': self.group_id, 'user_id': self.user['id']} - ) - resource_url = '/groups/{group_id}/users'.format( - group_id=self.group_id + '/groups/{group_id}/users/{user_id}'.format( + group_id=self.group_id, user_id=self.user['id'] + ) ) + resource_url = f'/groups/{self.group_id}/users' r = self.get(resource_url) self.assertValidUserListResponse( r, ref=self.user, resource_url=resource_url ) self.assertIn( - f'/groups/{self.group_id}/users', - r.result['links']['self'], + f'/groups/{self.group_id}/users', r.result['links']['self'] ) self.head(resource_url, expected_status=http.client.OK) def test_remove_user_from_group(self): """Call ``DELETE /groups/{group_id}/users/{user_id}``.""" self.put( - '/groups/%(group_id)s/users/%(user_id)s' - % {'group_id': self.group_id, 'user_id': self.user['id']} + '/groups/{group_id}/users/{user_id}'.format( + group_id=self.group_id, user_id=self.user['id'] + ) ) self.delete( - '/groups/%(group_id)s/users/%(user_id)s' - % {'group_id': self.group_id, 'user_id': self.user['id']} + '/groups/{group_id}/users/{user_id}'.format( + group_id=self.group_id, user_id=self.user['id'] + ) ) def test_update_ephemeral_user(self): @@ -487,7 +491,7 @@ class IdentityTestCase(test_v3.RestfulTestCase): # administrative password reset new_password = uuid.uuid4().hex self.patch( - '/users/%s' % user_ref['id'], + '/users/{}'.format(user_ref['id']), body={'user': {'password': new_password}}, ) @@ -520,7 +524,7 @@ class IdentityTestCase(test_v3.RestfulTestCase): # administrative password reset new_password = uuid.uuid4().hex r = self.patch( - '/users/%s' % user_ref['id'], + '/users/{}'.format(user_ref['id']), body={'user': {'password': new_password}}, ) self.assertValidUserResponse(r, user_ref) @@ -537,12 +541,12 @@ class IdentityTestCase(test_v3.RestfulTestCase): ) lock_pw_opt = options.LOCK_PASSWORD_OPT.option_name update_user_body = {'user': {'options': {lock_pw_opt: True}}} - self.patch('/users/%s' % user_ref['id'], body=update_user_body) + self.patch('/users/{}'.format(user_ref['id']), body=update_user_body) # administrative password reset new_password = uuid.uuid4().hex r = self.patch( - '/users/%s' % user_ref['id'], + '/users/{}'.format(user_ref['id']), body={'user': {'password': new_password}}, ) self.assertValidUserResponse(r, user_ref) @@ -697,10 +701,7 @@ class IdentityTestCase(test_v3.RestfulTestCase): """Call ``PATCH /groups/{group_id}``.""" group = unit.new_group_ref(domain_id=self.domain_id) del group['id'] - r = self.patch( - f'/groups/{self.group_id}', - body={'group': group}, - ) + r = self.patch(f'/groups/{self.group_id}', body={'group': group}) self.assertValidGroupResponse(r, group) def test_update_group_domain_id(self): @@ -746,7 +747,7 @@ class IdentityTestCase(test_v3.RestfulTestCase): # administrative password reset new_password = uuid.uuid4().hex self.patch( - '/users/%s' % user_ref['id'], + '/users/{}'.format(user_ref['id']), body={'user': {'password': new_password}}, ) @@ -786,7 +787,6 @@ class IdentityTestCase(test_v3.RestfulTestCase): class ChangePasswordTestCase(test_v3.RestfulTestCase): - def setUp(self): super().setUp() self.user_ref = unit.create_user( @@ -806,7 +806,7 @@ class ChangePasswordTestCase(test_v3.RestfulTestCase): def change_password(self, expected_status, **kwargs): """Return a test response for a change password request.""" return self.post( - '/users/%s/password' % self.user_ref['id'], + '/users/{}/password'.format(self.user_ref['id']), body={'user': kwargs}, token=self.token, expected_status=expected_status, @@ -814,7 +814,6 @@ class ChangePasswordTestCase(test_v3.RestfulTestCase): class UserSelfServiceChangingPasswordsTestCase(ChangePasswordTestCase): - def _create_user_with_expired_password(self): expire_days = CONF.security_compliance.password_expires_days + 1 time = timeutils.utcnow() - datetime.timedelta(expire_days) @@ -905,7 +904,7 @@ class UserSelfServiceChangingPasswordsTestCase(ChangePasswordTestCase): # Lock the user's password lock_pw_opt = options.LOCK_PASSWORD_OPT.option_name user_patch = {'user': {'options': {lock_pw_opt: True}}} - self.patch('/users/%s' % user_id, body=user_patch) + self.patch(f'/users/{user_id}', body=user_patch) # Fail, password is locked new_password = uuid.uuid4().hex @@ -915,14 +914,14 @@ class UserSelfServiceChangingPasswordsTestCase(ChangePasswordTestCase): 'password': new_password, } } - path = '/users/%s/password' % user_id + path = f'/users/{user_id}/password' self.post(path, body=body, expected_status=http.client.BAD_REQUEST) # Unlock the password, and change should work user_patch['user']['options'][lock_pw_opt] = False - self.patch('/users/%s' % user_id, body=user_patch) + self.patch(f'/users/{user_id}', body=user_patch) - path = '/users/%s/password' % user_id + path = f'/users/{user_id}/password' self.post(path, body=body, expected_status=http.client.NO_CONTENT) frozen_datetime.tick(delta=datetime.timedelta(seconds=1)) @@ -934,15 +933,15 @@ class UserSelfServiceChangingPasswordsTestCase(ChangePasswordTestCase): auth_data, expected_status=http.client.CREATED ) - path = '/users/%s' % user_id + path = f'/users/{user_id}' user = self.get(path).json_body['user'] self.assertIn(lock_pw_opt, user['options']) self.assertFalse(user['options'][lock_pw_opt]) # Completely unset the option from the user's reference user_patch['user']['options'][lock_pw_opt] = None - self.patch('/users/%s' % user_id, body=user_patch) - path = '/users/%s' % user_id + self.patch(f'/users/{user_id}', body=user_patch) + path = f'/users/{user_id}' user = self.get(path).json_body['user'] self.assertNotIn(lock_pw_opt, user['options']) @@ -975,7 +974,8 @@ class UserSelfServiceChangingPasswordsTestCase(ChangePasswordTestCase): # disable the user account self.user_ref['enabled'] = False self.patch( - '/users/%s' % self.user_ref['id'], body={'user': self.user_ref} + '/users/{}'.format(self.user_ref['id']), + body={'user': self.user_ref}, ) self.change_password( @@ -1027,7 +1027,8 @@ class UserSelfServiceChangingPasswordsTestCase(ChangePasswordTestCase): # disable the user account self.user_ref['enabled'] = False self.patch( - '/users/%s' % self.user_ref['id'], body={'user': self.user_ref} + '/users/{}'.format(self.user_ref['id']), + body={'user': self.user_ref}, ) new_password = uuid.uuid4().hex @@ -1135,7 +1136,6 @@ class UserSelfServiceChangingPasswordsTestCase(ChangePasswordTestCase): class PasswordValidationTestCase(ChangePasswordTestCase): - def setUp(self): super().setUp() # passwords requires: 1 letter, 1 digit, 7 chars @@ -1275,10 +1275,7 @@ class UserFederatedAttributesTests(test_v3.RestfulTestCase): def _test_list_users_with_federated_parameter(self, parameter): # construct the resource url based off what's passed in parameter - resource_url = '/users?{}={}'.format( - parameter[0], - self.fed_dict[parameter[0]], - ) + resource_url = f'/users?{parameter[0]}={self.fed_dict[parameter[0]]}' for attr in parameter[1:]: resource_url += f'&{attr}={self.fed_dict[attr]}' r = self.get(resource_url) @@ -1293,9 +1290,8 @@ class UserFederatedAttributesTests(test_v3.RestfulTestCase): if not any('unique_id' in x for x in parameter): # Check that we get two matches here since fed_user2 and fed_user3 # both have the same idp and protocol - resource_url = '/users?{}={}'.format( - parameter[0], - self.fed_dict2[parameter[0]], + resource_url = ( + f'/users?{parameter[0]}={self.fed_dict2[parameter[0]]}' ) for attr in parameter[1:]: resource_url += f'&{attr}={self.fed_dict2[attr]}' diff --git a/keystone/tests/unit/test_v3_oauth1.py b/keystone/tests/unit/test_v3_oauth1.py index 3ccfba2727..8229b88503 100644 --- a/keystone/tests/unit/test_v3_oauth1.py +++ b/keystone/tests/unit/test_v3_oauth1.py @@ -47,7 +47,6 @@ def _urllib_parse_qs_text_keys(content): class OAuth1Tests(test_v3.RestfulTestCase): - CONSUMER_URL = '/OS-OAUTH1/consumers' def setUp(self): @@ -113,11 +112,10 @@ class OAuth1Tests(test_v3.RestfulTestCase): def _authorize_request_token(self, request_id): if isinstance(request_id, bytes): request_id = request_id.decode() - return '/OS-OAUTH1/authorize/%s' % (request_id) + return f'/OS-OAUTH1/authorize/{request_id}' class ConsumerCRUDTests(OAuth1Tests): - def _consumer_create( self, description=None, description_flag=True, **kwargs ): @@ -158,13 +156,13 @@ class ConsumerCRUDTests(OAuth1Tests): def test_consumer_delete(self): consumer = self._create_single_consumer() consumer_id = consumer['id'] - resp = self.delete(self.CONSUMER_URL + '/%s' % consumer_id) + resp = self.delete(self.CONSUMER_URL + f'/{consumer_id}') self.assertResponseStatus(resp, http.client.NO_CONTENT) def test_consumer_get_head(self): consumer = self._create_single_consumer() consumer_id = consumer['id'] - url = self.CONSUMER_URL + '/%s' % consumer_id + url = self.CONSUMER_URL + f'/{consumer_id}' resp = self.get(url) self_url = ['http://localhost/v3', self.CONSUMER_URL, '/', consumer_id] self_url = ''.join(self_url) @@ -193,7 +191,7 @@ class ConsumerCRUDTests(OAuth1Tests): update_ref = {'description': update_description} update_resp = self.patch( - self.CONSUMER_URL + '/%s' % original_id, + self.CONSUMER_URL + f'/{original_id}', body={'consumer': update_ref}, ) consumer = update_resp.result['consumer'] @@ -207,7 +205,7 @@ class ConsumerCRUDTests(OAuth1Tests): update_ref['description'] = uuid.uuid4().hex update_ref['secret'] = uuid.uuid4().hex self.patch( - self.CONSUMER_URL + '/%s' % original_id, + self.CONSUMER_URL + f'/{original_id}', body={'consumer': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -222,7 +220,7 @@ class ConsumerCRUDTests(OAuth1Tests): update_ref['description'] = update_description update_ref['id'] = update_description self.patch( - self.CONSUMER_URL + '/%s' % original_id, + self.CONSUMER_URL + f'/{original_id}', body={'consumer': update_ref}, expected_status=http.client.BAD_REQUEST, ) @@ -245,7 +243,7 @@ class ConsumerCRUDTests(OAuth1Tests): update_ref = {field1_name: field1_new_value, field2_name: field2_value} update_resp = self.patch( - self.CONSUMER_URL + '/%s' % consumer_id, + self.CONSUMER_URL + f'/{consumer_id}', body={'consumer': update_ref}, ) consumer = update_resp.result['consumer'] @@ -265,15 +263,12 @@ class ConsumerCRUDTests(OAuth1Tests): self.assertIsNotNone(consumer['secret']) def test_consumer_get_bad_id(self): - url = self.CONSUMER_URL + '/{consumer_id}'.format( - consumer_id=uuid.uuid4().hex - ) + url = self.CONSUMER_URL + f'/{uuid.uuid4().hex}' self.get(url, expected_status=http.client.NOT_FOUND) self.head(url, expected_status=http.client.NOT_FOUND) class OAuthFlowTests(OAuth1Tests): - def test_oauth_flow(self): consumer = self._create_single_consumer() consumer_id = consumer['id'] @@ -343,15 +338,12 @@ class OAuthFlowTests(OAuth1Tests): class AccessTokenCRUDTests(OAuthFlowTests): def test_delete_access_token_dne(self): self.delete( - '/users/%(user)s/OS-OAUTH1/access_tokens/%(auth)s' - % {'user': self.user_id, 'auth': uuid.uuid4().hex}, + f'/users/{self.user_id}/OS-OAUTH1/access_tokens/{uuid.uuid4().hex}', expected_status=http.client.NOT_FOUND, ) def test_list_no_access_tokens(self): - url = '/users/{user_id}/OS-OAUTH1/access_tokens'.format( - user_id=self.user_id - ) + url = f'/users/{self.user_id}/OS-OAUTH1/access_tokens' resp = self.get(url) entities = resp.result['access_tokens'] self.assertEqual([], entities) @@ -363,10 +355,7 @@ class AccessTokenCRUDTests(OAuthFlowTests): self.test_oauth_flow() access_token_key_string = self.access_token.key.decode() - url = '/users/{user_id}/OS-OAUTH1/access_tokens/{key}'.format( - user_id=self.user_id, - key=access_token_key_string, - ) + url = f'/users/{self.user_id}/OS-OAUTH1/access_tokens/{access_token_key_string}' resp = self.get(url) entity = resp.result['access_token'] self.assertEqual(access_token_key_string, entity['id']) @@ -376,19 +365,15 @@ class AccessTokenCRUDTests(OAuthFlowTests): self.head(url, expected_status=http.client.OK) def test_get_access_token_dne(self): - url = '/users/{user_id}/OS-OAUTH1/access_tokens/{key}'.format( - user_id=self.user_id, - key=uuid.uuid4().hex, + url = ( + f'/users/{self.user_id}/OS-OAUTH1/access_tokens/{uuid.uuid4().hex}' ) self.get(url, expected_status=http.client.NOT_FOUND) self.head(url, expected_status=http.client.NOT_FOUND) def test_list_all_roles_in_access_token(self): self.test_oauth_flow() - url = '/users/{id}/OS-OAUTH1/access_tokens/{key}/roles'.format( - id=self.user_id, - key=self.access_token.key.decode(), - ) + url = f'/users/{self.user_id}/OS-OAUTH1/access_tokens/{self.access_token.key.decode()}/roles' resp = self.get(url) entities = resp.result['roles'] self.assertTrue(entities) @@ -400,14 +385,7 @@ class AccessTokenCRUDTests(OAuthFlowTests): self.test_oauth_flow() access_token_key = self.access_token.key.decode() - url = ( - '/users/%(id)s/OS-OAUTH1/access_tokens/%(key)s/roles/%(role)s' - % { - 'id': self.user_id, - 'key': access_token_key, - 'role': self.role_id, - } - ) + url = f'/users/{self.user_id}/OS-OAUTH1/access_tokens/{access_token_key}/roles/{self.role_id}' resp = self.get(url) entity = resp.result['role'] self.assertEqual(self.role_id, entity['id']) @@ -418,23 +396,14 @@ class AccessTokenCRUDTests(OAuthFlowTests): self.test_oauth_flow() access_token_key = self.access_token.key.decode() - url = ( - '/users/%(id)s/OS-OAUTH1/access_tokens/%(key)s/roles/%(role)s' - % { - 'id': self.user_id, - 'key': access_token_key, - 'role': uuid.uuid4().hex, - } - ) + url = f'/users/{self.user_id}/OS-OAUTH1/access_tokens/{access_token_key}/roles/{uuid.uuid4().hex}' self.get(url, expected_status=http.client.NOT_FOUND) self.head(url, expected_status=http.client.NOT_FOUND) def test_list_and_delete_access_tokens(self): self.test_oauth_flow() # List access_tokens should be > 0 - url = '/users/{user_id}/OS-OAUTH1/access_tokens'.format( - user_id=self.user_id - ) + url = f'/users/{self.user_id}/OS-OAUTH1/access_tokens' resp = self.get(url) self.head(url, expected_status=http.client.OK) entities = resp.result['access_tokens'] @@ -444,8 +413,7 @@ class AccessTokenCRUDTests(OAuthFlowTests): access_token_key = self.access_token.key.decode() # Delete access_token resp = self.delete( - '/users/%(user)s/OS-OAUTH1/access_tokens/%(auth)s' - % {'user': self.user_id, 'auth': access_token_key} + f'/users/{self.user_id}/OS-OAUTH1/access_tokens/{access_token_key}' ) self.assertResponseStatus(resp, http.client.NO_CONTENT) @@ -458,7 +426,6 @@ class AccessTokenCRUDTests(OAuthFlowTests): class AuthTokenTests: - def test_keystone_token_is_valid(self): self.test_oauth_flow() headers = { @@ -496,8 +463,7 @@ class AuthTokenTests: access_token_key = self.access_token.key.decode() # Delete access token resp = self.delete( - '/users/%(user)s/OS-OAUTH1/access_tokens/%(auth)s' - % {'user': self.user_id, 'auth': access_token_key} + f'/users/{self.user_id}/OS-OAUTH1/access_tokens/{access_token_key}' ) self.assertResponseStatus(resp, http.client.NO_CONTENT) @@ -517,17 +483,11 @@ class AuthTokenTests: # Delete consumer consumer_id = self.consumer['key'] - resp = self.delete( - '/OS-OAUTH1/consumers/%(consumer_id)s' - % {'consumer_id': consumer_id} - ) + resp = self.delete(f'/OS-OAUTH1/consumers/{consumer_id}') self.assertResponseStatus(resp, http.client.NO_CONTENT) # List access_token should be 0 - resp = self.get( - '/users/%(user_id)s/OS-OAUTH1/access_tokens' - % {'user_id': self.user_id} - ) + resp = self.get(f'/users/{self.user_id}/OS-OAUTH1/access_tokens') entities = resp.result['access_tokens'] self.assertEqual([], entities) @@ -624,7 +584,7 @@ class AuthTokenTests: trustee_user_id=self.user_id, project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) del ref['id'] @@ -672,7 +632,7 @@ class AuthTokenTests: trustee_user_id=self.user_id, project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) del ref['id'] @@ -704,7 +664,7 @@ class AuthTokenTests: } ) self.test_oauth_flow() - url = '/users/%s/OS-OAUTH1/access_tokens' % self.user_id + url = f'/users/{self.user_id}/OS-OAUTH1/access_tokens' self.get( url, token=self.keystone_token_id, @@ -736,12 +696,11 @@ class AuthTokenTests: {"identity:list_access_tokens": [], "identity:create_trust": []} ) trust_token = self._create_trust_get_token() - url = '/users/%s/OS-OAUTH1/access_tokens' % self.user_id + url = f'/users/{self.user_id}/OS-OAUTH1/access_tokens' self.get(url, token=trust_token, expected_status=http.client.FORBIDDEN) class FernetAuthTokenTests(AuthTokenTests, OAuthFlowTests): - def config_overrides(self): super().config_overrides() self.config_fixture.config(group='token', provider='fernet') @@ -758,7 +717,6 @@ class FernetAuthTokenTests(AuthTokenTests, OAuthFlowTests): class MaliciousOAuth1Tests(OAuth1Tests): - def _switch_baseurl_scheme(self): """Switch the base url scheme.""" base_url_list = list(urlparse.urlparse(self.base_url)) @@ -1230,7 +1188,6 @@ class MaliciousOAuth1Tests(OAuth1Tests): class OAuthNotificationTests( OAuth1Tests, test_notifications.BaseNotificationTest ): - def test_create_consumer(self): consumer_ref = self._create_single_consumer() self._assert_notify_sent( @@ -1355,8 +1312,7 @@ class OAuthNotificationTests( ) resp = self.delete( - '/users/%(user)s/OS-OAUTH1/access_tokens/%(auth)s' - % {'user': self.user_id, 'auth': self.access_token.key.decode()} + f'/users/{self.user_id}/OS-OAUTH1/access_tokens/{self.access_token.key.decode()}' ) self.assertResponseStatus(resp, http.client.NO_CONTENT) @@ -1375,7 +1331,6 @@ class OAuthNotificationTests( class OAuthCADFNotificationTests(OAuthNotificationTests): - def setUp(self): """Repeat the tests for CADF notifications.""" super().setUp() @@ -1385,7 +1340,5 @@ class OAuthCADFNotificationTests(OAuthNotificationTests): class JsonHomeTests(OAuth1Tests, test_v3.JsonHomeTestMixin): JSON_HOME_DATA = { 'https://docs.openstack.org/api/openstack-identity/3/ext/OS-OAUTH1/1.0' - '/rel/consumers': { - 'href': '/OS-OAUTH1/consumers', - }, + '/rel/consumers': {'href': '/OS-OAUTH1/consumers'} } diff --git a/keystone/tests/unit/test_v3_oauth2.py b/keystone/tests/unit/test_v3_oauth2.py index 87469d6dab..b8de35f21a 100644 --- a/keystone/tests/unit/test_v3_oauth2.py +++ b/keystone/tests/unit/test_v3_oauth2.py @@ -109,9 +109,7 @@ class OAuth2AuthnMethodsTests(test_v3.OAuth2RestfulTestCase): """client_secret_basic is used if a client sercret is found.""" client_id = 'client_id' client_secret = 'client_secret' - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - } + headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = { 'grant_type': 'client_credentials', 'client_id': client_id, @@ -160,9 +158,7 @@ class OAuth2AuthnMethodsTests(test_v3.OAuth2RestfulTestCase): client_id = 'client_id' client_cert, _ = self._create_certificates() cert_content = self._get_cert_content(client_cert) - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - } + headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = {'grant_type': 'client_credentials', 'client_id': client_id} _ = self._get_access_token( headers=headers, @@ -189,10 +185,7 @@ class OAuth2AuthnMethodsTests(test_v3.OAuth2RestfulTestCase): 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': f'Basic {b64str}', } - data = { - 'grant_type': 'client_credentials', - 'client_id': client_id_c, - } + data = {'grant_type': 'client_credentials', 'client_id': client_id_c} _ = self._get_access_token( headers=headers, @@ -229,8 +222,7 @@ class OAuth2SecretBasicTests(test_v3.OAuth2RestfulTestCase): LOG.debug(f'is_debug_enabled: {log.is_debug_enabled(CONF)}') LOG.debug(f'get_default_log_levels: {log.get_default_log_levels()}') self.config_fixture.config( - group='oauth2', - oauth2_authn_methods=['client_secret_basic'], + group='oauth2', oauth2_authn_methods=['client_secret_basic'] ) def _assert_error_resp(self, error_resp, error_msg, error_description): @@ -329,9 +321,7 @@ class OAuth2SecretBasicTests(test_v3.OAuth2RestfulTestCase): """Test case when there is no client authorization.""" client_name = 'client_name_test' app_cred = self._create_app_cred(self.user_id, client_name) - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - } + headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = { 'grant_type': 'client_credentials', 'client_id': app_cred.get('id'), @@ -356,9 +346,10 @@ class OAuth2SecretBasicTests(test_v3.OAuth2RestfulTestCase): client_id = app_cred.get('id') base = ( - 'username="%s", realm="%s", nonce="%s", uri="%s", ' - 'response="%s"' - % (client_id, 'realm', 'nonce', 'path', 'responding') + 'username="{}", realm="{}", nonce="{}", uri="{}", ' + 'response="{}"'.format( + client_id, 'realm', 'nonce', 'path', 'responding' + ) ) headers = { @@ -730,11 +721,9 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): self.config_fixture.config( group='oauth2', oauth2_cert_dn_mapping_id='oauth2_mapping' ) - ( - self.oauth2_user, - self.oauth2_user_domain, - _, - ) = self._create_project_user() + (self.oauth2_user, self.oauth2_user_domain, _) = ( + self._create_project_user() + ) *_, self.client_cert, self.client_key = self._create_certificates( client_dn=unit.create_dn( user_id=self.oauth2_user.get('id'), @@ -829,26 +818,26 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): remote = [] for k in info: if k == 'user.name': - local_user['name'] = '{%s}' % index + local_user['name'] = f'{{{index}}}' remote.append({'type': info.get(k)}) index += 1 elif k == 'user.id': - local_user['id'] = '{%s}' % index + local_user['id'] = f'{{{index}}}' remote.append({'type': info.get(k)}) index += 1 elif k == 'user.email': - local_user['email'] = '{%s}' % index + local_user['email'] = f'{{{index}}}' remote.append({'type': info.get(k)}) index += 1 elif k == 'user.domain.name' or k == 'user.domain.id': if not local_user.get('domain'): local_user['domain'] = {} if k == 'user.domain.name': - local_user['domain']['name'] = '{%s}' % index + local_user['domain']['name'] = f'{{{index}}}' remote.append({'type': info.get(k)}) index += 1 else: - local_user['domain']['id'] = '{%s}' % index + local_user['domain']['id'] = f'{{{index}}}' remote.append({'type': info.get(k)}) index += 1 else: @@ -866,9 +855,7 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): client_cert_content=None, expected_status=http.client.OK, ): - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - } + headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = {'grant_type': 'client_credentials'} if client_id: data.update({'client_id': client_id}) @@ -1241,7 +1228,7 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): self.assertUnauthorizedResp(resp) self.assertIn( 'Get OAuth2.0 Access Token API: ' - 'mapping id %s is not found. ' % 'oauth2_mapping', + 'mapping id {} is not found. '.format('oauth2_mapping'), self.log_fix.output, ) @@ -1274,7 +1261,7 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): self.assertUnauthorizedResp(resp) self.assertIn( 'Get OAuth2.0 Access Token API: ' - 'mapping id %s is not found. ' % 'oauth2_custom', + 'mapping id {} is not found. '.format('oauth2_custom'), self.log_fix.output, ) self.config_fixture.config( @@ -1759,7 +1746,7 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): self.assertUnauthorizedResp(resp) self.assertIn( 'Get OAuth2.0 Access Token API: ' - 'the user does not exist. user id: %s' % user_id_not_exist, + f'the user does not exist. user id: {user_id_not_exist}', self.log_fix.output, ) @@ -1788,9 +1775,10 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): ) self.assertUnauthorizedResp(resp) self.assertIn( - 'Get OAuth2.0 Access Token API: %s check failed. ' - 'DN value: %s, DB value: %s.' - % ('user id', user.get('id') + '_diff', user.get('id')), + 'Get OAuth2.0 Access Token API: {} check failed. ' + 'DN value: {}, DB value: {}.'.format( + 'user id', user.get('id') + '_diff', user.get('id') + ), self.log_fix.output, ) @@ -1819,9 +1807,10 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): ) self.assertUnauthorizedResp(resp) self.assertIn( - 'Get OAuth2.0 Access Token API: %s check failed. ' - 'DN value: %s, DB value: %s.' - % ('user name', user.get('name') + '_diff', user.get('name')), + 'Get OAuth2.0 Access Token API: {} check failed. ' + 'DN value: {}, DB value: {}.'.format( + 'user name', user.get('name') + '_diff', user.get('name') + ), self.log_fix.output, ) @@ -1850,9 +1839,10 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): ) self.assertUnauthorizedResp(resp) self.assertIn( - 'Get OAuth2.0 Access Token API: %s check failed. ' - 'DN value: %s, DB value: %s.' - % ('user email', user.get('email') + '_diff', user.get('email')), + 'Get OAuth2.0 Access Token API: {} check failed. ' + 'DN value: {}, DB value: {}.'.format( + 'user email', user.get('email') + '_diff', user.get('email') + ), self.log_fix.output, ) @@ -1881,9 +1871,8 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): ) self.assertUnauthorizedResp(resp) self.assertIn( - 'Get OAuth2.0 Access Token API: %s check failed. ' - 'DN value: %s, DB value: %s.' - % ( + 'Get OAuth2.0 Access Token API: {} check failed. ' + 'DN value: {}, DB value: {}.'.format( 'user domain id', user_domain.get('id') + '_diff', user_domain.get('id'), @@ -1916,9 +1905,8 @@ class OAuth2CertificateTests(test_v3.OAuth2RestfulTestCase): ) self.assertUnauthorizedResp(resp) self.assertIn( - 'Get OAuth2.0 Access Token API: %s check failed. ' - 'DN value: %s, DB value: %s.' - % ( + 'Get OAuth2.0 Access Token API: {} check failed. ' + 'DN value: {}, DB value: {}.'.format( 'user domain name', user_domain.get('name') + '_diff', user_domain.get('name'), diff --git a/keystone/tests/unit/test_v3_os_revoke.py b/keystone/tests/unit/test_v3_os_revoke.py index c9a2af91f2..2f35e07703 100644 --- a/keystone/tests/unit/test_v3_os_revoke.py +++ b/keystone/tests/unit/test_v3_os_revoke.py @@ -35,12 +35,9 @@ def _future_time_string(): class OSRevokeTests(test_v3.RestfulTestCase, test_v3.JsonHomeTestMixin): - JSON_HOME_DATA = { 'https://docs.openstack.org/api/openstack-identity/3/ext/OS-REVOKE/1.0' - '/rel/events': { - 'href': '/OS-REVOKE/events', - }, + '/rel/events': {'href': '/OS-REVOKE/events'} } def test_get_empty_list(self): @@ -60,20 +57,12 @@ class OSRevokeTests(test_v3.RestfulTestCase, test_v3.JsonHomeTestMixin): self.assertLessEqual( before_time, event_issued_before, - 'invalid event issued_before time; %s is not later than %s.' - % ( - utils.isotime(event_issued_before, subsecond=True), - utils.isotime(before_time, subsecond=True), - ), + f'invalid event issued_before time; {utils.isotime(event_issued_before, subsecond=True)} is not later than {utils.isotime(before_time, subsecond=True)}.', ) self.assertLessEqual( event_issued_before, after_time, - 'invalid event issued_before time; %s is not earlier than %s.' - % ( - utils.isotime(event_issued_before, subsecond=True), - utils.isotime(after_time, subsecond=True), - ), + f'invalid event issued_before time; {utils.isotime(event_issued_before, subsecond=True)} is not earlier than {utils.isotime(after_time, subsecond=True)}.', ) del event['issued_before'] del event['revoked_at'] @@ -98,7 +87,7 @@ class OSRevokeTests(test_v3.RestfulTestCase, test_v3.JsonHomeTestMixin): def test_disabled_project_in_list(self): project_id = uuid.uuid4().hex - sample = dict() + sample = {} sample['project_id'] = str(project_id) before_time = timeutils.utcnow().replace(microsecond=0) PROVIDERS.revoke_api.revoke( @@ -112,7 +101,7 @@ class OSRevokeTests(test_v3.RestfulTestCase, test_v3.JsonHomeTestMixin): def test_disabled_domain_in_list(self): domain_id = uuid.uuid4().hex - sample = dict() + sample = {} sample['domain_id'] = str(domain_id) before_time = timeutils.utcnow().replace(microsecond=0) PROVIDERS.revoke_api.revoke( @@ -137,7 +126,7 @@ class OSRevokeTests(test_v3.RestfulTestCase, test_v3.JsonHomeTestMixin): def test_since_future_time_no_events(self): domain_id = uuid.uuid4().hex - sample = dict() + sample = {} sample['domain_id'] = str(domain_id) PROVIDERS.revoke_api.revoke( @@ -148,7 +137,7 @@ class OSRevokeTests(test_v3.RestfulTestCase, test_v3.JsonHomeTestMixin): events = resp.json_body['events'] self.assertEqual(1, len(events)) - resp = self.get('/OS-REVOKE/events?since=%s' % _future_time_string()) + resp = self.get(f'/OS-REVOKE/events?since={_future_time_string()}') events = resp.json_body['events'] self.assertEqual([], events) diff --git a/keystone/tests/unit/test_v3_policy.py b/keystone/tests/unit/test_v3_policy.py index 9e37bcc2d7..dae113b29e 100644 --- a/keystone/tests/unit/test_v3_policy.py +++ b/keystone/tests/unit/test_v3_policy.py @@ -56,14 +56,9 @@ class PolicyTestCase(test_v3.RestfulTestCase): def test_update_policy(self): """Call ``PATCH /policies/{policy_id}``.""" - self.policy['blob'] = json.dumps( - { - 'data': uuid.uuid4().hex, - } - ) + self.policy['blob'] = json.dumps({'data': uuid.uuid4().hex}) r = self.patch( - f'/policies/{self.policy_id}', - body={'policy': self.policy}, + f'/policies/{self.policy_id}', body={'policy': self.policy} ) self.assertValidPolicyResponse(r, self.policy) diff --git a/keystone/tests/unit/test_v3_resource.py b/keystone/tests/unit/test_v3_resource.py index 418ad9df48..cfd91dbe0b 100644 --- a/keystone/tests/unit/test_v3_resource.py +++ b/keystone/tests/unit/test_v3_resource.py @@ -112,8 +112,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Retrieve its correspondent project r = self.get( - '/projects/%(project_id)s' - % {'project_id': r.result['domain']['id']} + '/projects/{project_id}'.format( + project_id=r.result['domain']['id'] + ) ) self.assertValidProjectResponse(r) @@ -220,10 +221,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): """Call ``PATCH /domains/{domain_id}``.""" ref = unit.new_domain_ref() del ref['id'] - r = self.patch( - f'/domains/{self.domain_id}', - body={'domain': ref}, - ) + r = self.patch(f'/domains/{self.domain_id}', body={'domain': ref}) self.assertValidDomainResponse(r, ref) def test_update_domain_unsafe(self): @@ -235,10 +233,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): ) ref = unit.new_domain_ref(name=unsafe_name) del ref['id'] - self.patch( - f'/domains/{self.domain_id}', - body={'domain': ref}, - ) + self.patch(f'/domains/{self.domain_id}', body={'domain': ref}) unsafe_name = 'i am still not / safe' for config_setting in ['new', 'strict']: @@ -260,10 +255,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # By default, we should be able to create unsafe names ref = unit.new_domain_ref(name=unsafe_name) del ref['id'] - self.patch( - f'/domains/{self.domain_id}', - body={'domain': ref}, - ) + self.patch(f'/domains/{self.domain_id}', body={'domain': ref}) def test_update_domain_updates_is_domain_project(self): """Check the project that acts as a domain is updated. @@ -277,14 +269,15 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Disable it self.patch( - '/domains/%s' % r.result['domain']['id'], + '/domains/{}'.format(r.result['domain']['id']), body={'domain': {'enabled': False}}, ) # Retrieve its correspondent project r = self.get( - '/projects/%(project_id)s' - % {'project_id': r.result['domain']['id']} + '/projects/{project_id}'.format( + project_id=r.result['domain']['id'] + ) ) self.assertValidProjectResponse(r) @@ -475,10 +468,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): ) # Disable and delete the domain with no error. self.patch( - f'/domains/{domain_id}', - body={'domain': {'enabled': False}}, + f'/domains/{domain_id}', body={'domain': {'enabled': False}} ) - self.delete('/domains/%s' % domain_id) + self.delete(f'/domains/{domain_id}') # The Idp is deleted as well self.get( '/OS-FEDERATION/identity_providers/test_idp', @@ -497,36 +489,34 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Retrieve its correspondent project self.get( - '/projects/%(project_id)s' - % {'project_id': r.result['domain']['id']} + '/projects/{project_id}'.format( + project_id=r.result['domain']['id'] + ) ) # Delete the domain self.patch( - '/domains/%s' % r.result['domain']['id'], + '/domains/{}'.format(r.result['domain']['id']), body={'domain': {'enabled': False}}, ) - self.delete('/domains/%s' % r.result['domain']['id']) + self.delete('/domains/{}'.format(r.result['domain']['id'])) # The created project is deleted as well self.get( - '/projects/%(project_id)s' - % {'project_id': r.result['domain']['id']}, + '/projects/{project_id}'.format( + project_id=r.result['domain']['id'] + ), expected_status=404, ) def test_delete_default_domain(self): # Need to disable it first. self.patch( - '/domains/%(domain_id)s' - % {'domain_id': CONF.identity.default_domain_id}, + f'/domains/{CONF.identity.default_domain_id}', body={'domain': {'enabled': False}}, ) - self.delete( - '/domains/%(domain_id)s' - % {'domain_id': CONF.identity.default_domain_id} - ) + self.delete(f'/domains/{CONF.identity.default_domain_id}') def test_token_revoked_once_domain_disabled(self): """Test token from a disabled domain has been invalidated. @@ -769,13 +759,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): """Call ``POST /projects``.""" # Grant a domain role for the user collection_url = '/domains/{domain_id}/users/{user_id}/roles'.format( - domain_id=self.domain_id, - user_id=self.user['id'], - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + domain_id=self.domain_id, user_id=self.user['id'] ) + member_url = f'{collection_url}/{self.role_id}' self.put(member_url) # Create an authentication request for a domain scoped token @@ -797,13 +783,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): """Call ``POST /projects``.""" # Grant a domain role for the user collection_url = '/domains/{domain_id}/users/{user_id}/roles'.format( - domain_id=self.domain_id, - user_id=self.user['id'], - ) - member_url = '{collection_url}/{role_id}'.format( - collection_url=collection_url, - role_id=self.role_id, + domain_id=self.domain_id, user_id=self.user['id'] ) + member_url = f'{collection_url}/{self.role_id}' self.put(member_url) # Create an authentication request for a domain scoped token @@ -991,8 +973,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): project, tags = self._create_project_and_tags(num_of_tags=2) ref = {'project': {'name': 'tags and name'}} resp = self.patch( - '/projects/{project_id}'.format(project_id=project['id']), - body=ref, + '/projects/{project_id}'.format(project_id=project['id']), body=ref ) url = '/projects?tags-any=%(values)s&name=%(name)s' resp = self.get(url % {'values': tags[0], 'name': 'tags and name'}) @@ -1020,8 +1001,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Query for projects[0] immediate children - it will # be only projects[1] r = self.get( - '/projects?parent_id=%(project_id)s' - % {'project_id': projects[0]['project']['id']} + '/projects?parent_id={project_id}'.format( + project_id=projects[0]['project']['id'] + ) ) self.assertValidProjectListResponse(r) @@ -1034,8 +1016,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Query for projects[1] immediate children - it will # be projects[2] and projects[3] r = self.get( - '/projects?parent_id=%(project_id)s' - % {'project_id': projects[1]['project']['id']} + '/projects?parent_id={project_id}'.format( + project_id=projects[1]['project']['id'] + ) ) self.assertValidProjectListResponse(r) @@ -1047,8 +1030,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Query for projects[2] immediate children - it will be an empty list r = self.get( - '/projects?parent_id=%(project_id)s' - % {'project_id': projects[2]['project']['id']} + '/projects?parent_id={project_id}'.format( + project_id=projects[2]['project']['id'] + ) ) self.assertValidProjectListResponse(r) @@ -1064,9 +1048,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): def test_get_head_project(self): """Call ``GET & HEAD /projects/{project_id}``.""" - resource_url = '/projects/{project_id}'.format( - project_id=self.project_id - ) + resource_url = f'/projects/{self.project_id}' r = self.get(resource_url) self.assertValidProjectResponse(r, self.project) self.head(resource_url, expected_status=http.client.OK) @@ -1079,8 +1061,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): ) self.get( - '/projects/%(project_id)s?parents_as_list' - % {'project_id': uuid.uuid4().hex}, + f'/projects/{uuid.uuid4().hex}?parents_as_list', expected_status=http.client.NOT_FOUND, ) @@ -1092,8 +1073,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): ) self.get( - '/projects/%(project_id)s?subtree_as_list' - % {'project_id': uuid.uuid4().hex}, + f'/projects/{uuid.uuid4().hex}?subtree_as_list', expected_status=http.client.NOT_FOUND, ) @@ -1103,8 +1083,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Query for projects[2] parents_as_ids r = self.get( - '/projects/%(project_id)s?parents_as_ids' - % {'project_id': projects[2]['project']['id']} + '/projects/{project_id}?parents_as_ids'.format( + project_id=projects[2]['project']['id'] + ) ) self.assertValidProjectResponse(r, projects[2]['project']) @@ -1132,8 +1113,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Query for projects[0] parents_as_ids r = self.get( - '/projects/%(project_id)s?parents_as_ids' - % {'project_id': projects[0]['project']['id']} + '/projects/{project_id}?parents_as_ids'.format( + project_id=projects[0]['project']['id'] + ) ) self.assertValidProjectResponse(r, projects[0]['project']) @@ -1144,10 +1126,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): self.assertDictEqual(expected_dict, parents_as_ids) # Query for is_domain_project parents_as_ids - r = self.get( - '/projects/%(project_id)s?parents_as_ids' - % {'project_id': is_domain_project_id} - ) + r = self.get(f'/projects/{is_domain_project_id}?parents_as_ids') parents_as_ids = r.result['project']['parents'] @@ -1181,8 +1160,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Make the API call r = self.get( - '/projects/%(project_id)s?parents_as_list' - % {'project_id': subproject['project']['id']} + '/projects/{project_id}?parents_as_list'.format( + project_id=subproject['project']['id'] + ) ) self.assertValidProjectResponse(r, subproject['project']) @@ -1217,8 +1197,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Make the API call r = self.get( - '/projects/%(project_id)s?parents_as_list' - % {'project_id': subproject['project']['id']} + '/projects/{project_id}?parents_as_list'.format( + project_id=subproject['project']['id'] + ) ) self.assertValidProjectResponse(r, subproject['project']) @@ -1237,8 +1218,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): projects = self._create_projects_hierarchy(hierarchy_size=2) self.get( - '/projects/%(project_id)s?parents_as_list&parents_as_ids' - % {'project_id': projects[1]['project']['id']}, + '/projects/{project_id}?parents_as_list&parents_as_ids'.format( + project_id=projects[1]['project']['id'] + ), expected_status=http.client.BAD_REQUEST, ) @@ -1297,8 +1279,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # "include_limits" should work together with "parents_as_list" or # "subtree_as_list". Only using "include_limits" really does nothing. r = self.get( - '/projects/%(project_id)s?include_limits' - % {'project_id': subproject['project']['id']} + '/projects/{project_id}?include_limits'.format( + project_id=subproject['project']['id'] + ) ) self.assertNotIn('parents', r.result['project']) @@ -1307,8 +1290,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # using "include_limits" with "parents_as_list" r = self.get( - '/projects/%(project_id)s?include_limits&parents_as_list' - % {'project_id': subproject['project']['id']} + '/projects/{project_id}?include_limits&parents_as_list'.format( + project_id=subproject['project']['id'] + ) ) self.assertEqual(2, len(r.result['project']['parents'])) @@ -1324,8 +1308,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # using "include_limits" with "subtree_as_list" r = self.get( - '/projects/%(project_id)s?include_limits&subtree_as_list' - % {'project_id': parent['project']['id']} + '/projects/{project_id}?include_limits&subtree_as_list'.format( + project_id=parent['project']['id'] + ) ) self.assertEqual(2, len(r.result['project']['subtree'])) @@ -1449,8 +1434,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Query for projects[0] subtree_as_ids r = self.get( - '/projects/%(project_id)s?subtree_as_ids' - % {'project_id': projects[0]['project']['id']} + '/projects/{project_id}?subtree_as_ids'.format( + project_id=projects[0]['project']['id'] + ) ) self.assertValidProjectResponse(r, projects[0]['project']) subtree_as_ids = r.result['project']['subtree'] @@ -1475,8 +1461,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Now query for projects[1] subtree_as_ids r = self.get( - '/projects/%(project_id)s?subtree_as_ids' - % {'project_id': projects[1]['project']['id']} + '/projects/{project_id}?subtree_as_ids'.format( + project_id=projects[1]['project']['id'] + ) ) self.assertValidProjectResponse(r, projects[1]['project']) subtree_as_ids = r.result['project']['subtree'] @@ -1495,8 +1482,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Now query for projects[3] subtree_as_ids r = self.get( - '/projects/%(project_id)s?subtree_as_ids' - % {'project_id': projects[3]['project']['id']} + '/projects/{project_id}?subtree_as_ids'.format( + project_id=projects[3]['project']['id'] + ) ) self.assertValidProjectResponse(r, projects[3]['project']) subtree_as_ids = r.result['project']['subtree'] @@ -1530,8 +1518,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Make the API call r = self.get( - '/projects/%(project_id)s?subtree_as_list' - % {'project_id': parent['project']['id']} + '/projects/{project_id}?subtree_as_list'.format( + project_id=parent['project']['id'] + ) ) self.assertValidProjectResponse(r, parent['project']) @@ -1565,8 +1554,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): # Make the API call r = self.get( - '/projects/%(project_id)s?subtree_as_list' - % {'project_id': parent['project']['id']} + '/projects/{project_id}?subtree_as_list'.format( + project_id=parent['project']['id'] + ) ) self.assertValidProjectResponse(r, parent['project']) @@ -1585,8 +1575,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): projects = self._create_projects_hierarchy(hierarchy_size=2) self.get( - '/projects/%(project_id)s?subtree_as_list&subtree_as_ids' - % {'project_id': projects[1]['project']['id']}, + '/projects/{project_id}?subtree_as_list&subtree_as_ids'.format( + project_id=projects[1]['project']['id'] + ), expected_status=http.client.BAD_REQUEST, ) @@ -1596,10 +1587,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): domain_id=self.domain_id, parent_id=self.project['parent_id'] ) del ref['id'] - r = self.patch( - f'/projects/{self.project_id}', - body={'project': ref}, - ) + r = self.patch(f'/projects/{self.project_id}', body={'project': ref}) self.assertValidProjectResponse(r, ref) def test_update_project_unsafe(self): @@ -1615,10 +1603,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): parent_id=self.project['parent_id'], ) del ref['id'] - self.patch( - f'/projects/{self.project_id}', - body={'project': ref}, - ) + self.patch(f'/projects/{self.project_id}', body={'project': ref}) unsafe_name = 'i am still not / safe' for config_setting in ['new', 'strict']: @@ -1648,10 +1633,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): parent_id=self.project['parent_id'], ) del ref['id'] - self.patch( - f'/projects/{self.project_id}', - body={'project': ref}, - ) + self.patch(f'/projects/{self.project_id}', body={'project': ref}) def test_update_project_domain_id(self): """Call ``PATCH /projects/{project_id}`` with domain_id. @@ -1691,8 +1673,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): project['parent_id'] = resp.result['project']['parent_id'] project['is_domain'] = True self.patch( - '/projects/%(project_id)s' - % {'project_id': resp.result['project']['id']}, + '/projects/{project_id}'.format( + project_id=resp.result['project']['id'] + ), body={'project': project}, expected_status=http.client.BAD_REQUEST, ) @@ -1767,8 +1750,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): """Call ``DELETE /projects/{project_id}``.""" projects = self._create_projects_hierarchy() self.delete( - '/projects/%(project_id)s' - % {'project_id': projects[0]['project']['id']}, + '/projects/{project_id}'.format( + project_id=projects[0]['project']['id'] + ), expected_status=http.client.FORBIDDEN, ) @@ -1808,13 +1792,11 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): case_tags = ['case', 'CASE'] for tag in case_tags: self.put( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': self.project_id, 'value': tag}, + f'/projects/{self.project_id}/tags/{tag}', expected_status=http.client.CREATED, ) resp = self.get( - f'/projects/{self.project_id}', - expected_status=http.client.OK, + f'/projects/{self.project_id}', expected_status=http.client.OK ) for tag in case_tags: self.assertIn(tag, resp.result['project']['tags']) @@ -1822,34 +1804,37 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): def test_get_single_project_tag(self): project, tags = self._create_project_and_tags() self.get( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': project['id'], 'value': tags[0]}, + '/projects/{project_id}/tags/{value}'.format( + project_id=project['id'], value=tags[0] + ), expected_status=http.client.NO_CONTENT, ) self.head( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': project['id'], 'value': tags[0]}, + '/projects/{project_id}/tags/{value}'.format( + project_id=project['id'], value=tags[0] + ), expected_status=http.client.NO_CONTENT, ) def test_get_project_tag_that_does_not_exist(self): project, _ = self._create_project_and_tags() self.get( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': project['id'], 'value': uuid.uuid4().hex}, + '/projects/{project_id}/tags/{value}'.format( + project_id=project['id'], value=uuid.uuid4().hex + ), expected_status=http.client.NOT_FOUND, ) def test_delete_project_tag(self): project, tags = self._create_project_and_tags() self.delete( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': project['id'], 'value': tags[0]}, + '/projects/{project_id}/tags/{value}'.format( + project_id=project['id'], value=tags[0] + ), expected_status=http.client.NO_CONTENT, ) self.get( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': self.project_id, 'value': tags[0]}, + f'/projects/{self.project_id}/tags/{tags[0]}', expected_status=http.client.NOT_FOUND, ) @@ -1860,8 +1845,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): expected_status=http.client.NO_CONTENT, ) self.get( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': self.project_id, 'value': tags[0]}, + f'/projects/{self.project_id}/tags/{tags[0]}', expected_status=http.client.NOT_FOUND, ) resp = self.get( @@ -1872,54 +1856,51 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): def test_create_project_tag_invalid_project_id(self): self.put( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': uuid.uuid4().hex, 'value': uuid.uuid4().hex}, + f'/projects/{uuid.uuid4().hex}/tags/{uuid.uuid4().hex}', expected_status=http.client.NOT_FOUND, ) def test_create_project_tag_unsafe_name(self): tag = uuid.uuid4().hex + ',' self.put( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': self.project_id, 'value': tag}, + f'/projects/{self.project_id}/tags/{tag}', expected_status=http.client.BAD_REQUEST, ) def test_create_project_tag_already_exists(self): project, tags = self._create_project_and_tags() self.put( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': project['id'], 'value': tags[0]}, + '/projects/{project_id}/tags/{value}'.format( + project_id=project['id'], value=tags[0] + ), expected_status=http.client.BAD_REQUEST, ) def test_create_project_tag_over_tag_limit(self): project, _ = self._create_project_and_tags(num_of_tags=80) self.put( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': project['id'], 'value': uuid.uuid4().hex}, + '/projects/{project_id}/tags/{value}'.format( + project_id=project['id'], value=uuid.uuid4().hex + ), expected_status=http.client.BAD_REQUEST, ) def test_create_project_tag_name_over_character_limit(self): tag = 'a' * 256 self.put( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': self.project_id, 'value': tag}, + f'/projects/{self.project_id}/tags/{tag}', expected_status=http.client.BAD_REQUEST, ) def test_delete_tag_invalid_project_id(self): self.delete( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': uuid.uuid4().hex, 'value': uuid.uuid4().hex}, + f'/projects/{uuid.uuid4().hex}/tags/{uuid.uuid4().hex}', expected_status=http.client.NOT_FOUND, ) def test_delete_project_tag_not_found(self): self.delete( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': self.project_id, 'value': uuid.uuid4().hex}, + f'/projects/{self.project_id}/tags/{uuid.uuid4().hex}', expected_status=http.client.NOT_FOUND, ) @@ -1935,22 +1916,21 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): def test_check_if_project_tag_exists(self): project, tags = self._create_project_and_tags(num_of_tags=5) self.head( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': project['id'], 'value': tags[0]}, + '/projects/{project_id}/tags/{value}'.format( + project_id=project['id'], value=tags[0] + ), expected_status=http.client.NO_CONTENT, ) def test_list_project_tags_for_project_with_no_tags(self): resp = self.get( - f'/projects/{self.project_id}/tags', - expected_status=http.client.OK, + f'/projects/{self.project_id}/tags', expected_status=http.client.OK ) self.assertEqual([], resp.result['tags']) def test_check_project_with_no_tags(self): self.head( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': self.project_id, 'value': uuid.uuid4().hex}, + f'/projects/{self.project_id}/tags/{uuid.uuid4().hex}', expected_status=http.client.NOT_FOUND, ) @@ -1967,8 +1947,9 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): tag = uuid.uuid4().hex project, tags = self._create_project_and_tags(num_of_tags=5) self.put( - '/projects/%(project_id)s/tags/%(value)s' - % {'project_id': project['id'], 'value': tag}, + '/projects/{project_id}/tags/{value}'.format( + project_id=project['id'], value=tag + ), expected_status=http.client.CREATED, ) resp = self.put( @@ -1985,8 +1966,7 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): for char in invalid_chars: tags[0] = uuid.uuid4().hex + char self.put( - '/projects/%(project_id)s/tags' - % {'project_id': project['id']}, + '/projects/{project_id}/tags'.format(project_id=project['id']), body={'tags': tags}, expected_status=http.client.BAD_REQUEST, ) @@ -2016,13 +1996,10 @@ class ResourceTestCase(test_v3.RestfulTestCase, test_v3.AssignmentTestMixin): role = resp.result['role'] self.put( - '/OS-INHERIT/domains/%(domain_id)s/users/%(user_id)s/roles/' - '%(role_id)s/inherited_to_projects' - % { - 'domain_id': domain['id'], - 'user_id': user['id'], - 'role_id': role['id'], - } + '/OS-INHERIT/domains/{domain_id}/users/{user_id}/roles/' + '{role_id}/inherited_to_projects'.format( + domain_id=domain['id'], user_id=user['id'], role_id=role['id'] + ) ) resp = self.get('/users/{user}/projects'.format(user=user['id'])) diff --git a/keystone/tests/unit/test_v3_trust.py b/keystone/tests/unit/test_v3_trust.py index d22555efb5..bd9e13e55a 100644 --- a/keystone/tests/unit/test_v3_trust.py +++ b/keystone/tests/unit/test_v3_trust.py @@ -134,13 +134,15 @@ class TestTrustOperations(test_v3.RestfulTestCase): roles = self.assertValidRoleListResponse(r, self.role) self.assertIn(self.role['id'], [x['id'] for x in roles]) self.head( - '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' - % {'trust_id': trust['id'], 'role_id': self.role['id']}, + '/OS-TRUST/trusts/{trust_id}/roles/{role_id}'.format( + trust_id=trust['id'], role_id=self.role['id'] + ), expected_status=http.client.OK, ) r = self.get( - '/OS-TRUST/trusts/%(trust_id)s/roles/%(role_id)s' - % {'trust_id': trust['id'], 'role_id': self.role['id']} + '/OS-TRUST/trusts/{trust_id}/roles/{role_id}'.format( + trust_id=trust['id'], role_id=self.role['id'] + ) ) self.assertValidRoleResponse(r, self.role) @@ -164,7 +166,7 @@ class TestTrustOperations(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) for i in range(3): @@ -186,7 +188,7 @@ class TestTrustOperations(test_v3.RestfulTestCase): # list all trusts for the trustor list_for_trustor_url = ( - '/OS-TRUST/trusts?trustor_user_id=%s' % self.user_id + f'/OS-TRUST/trusts?trustor_user_id={self.user_id}' ) r = self.get(list_for_trustor_url) self.head(list_for_trustor_url, expected_status=http.client.OK) @@ -196,7 +198,7 @@ class TestTrustOperations(test_v3.RestfulTestCase): # list all trusts for trustee as the trustor list_as_trustor_url = ( - '/OS-TRUST/trusts?trustee_user_id=%s' % self.user_id + f'/OS-TRUST/trusts?trustee_user_id={self.user_id}' ) r = self.get(list_as_trustor_url) self.head(list_as_trustor_url, expected_status=http.client.OK) @@ -242,7 +244,7 @@ class TestTrustOperations(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) r = self.post('/OS-TRUST/trusts', body={'trust': ref}) @@ -415,7 +417,7 @@ class TestTrustOperations(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) resp = self.post('/OS-TRUST/trusts', body={'trust': ref}) @@ -447,7 +449,7 @@ class TestTrustOperations(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=True, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) resp = self.post('/OS-TRUST/trusts', body={'trust': ref}) @@ -605,7 +607,6 @@ class TestTrustOperations(test_v3.RestfulTestCase): class TrustsWithApplicationCredentials(test_v3.RestfulTestCase): - def setUp(self): super().setUp() self.trustee_user = unit.create_user( @@ -655,7 +656,7 @@ class TrustsWithApplicationCredentials(test_v3.RestfulTestCase): trustee_user_id=self.trustee_user_id, project_id=self.project_id, impersonation=False, - expires=dict(minutes=1), + expires={'minutes': 1}, role_ids=[self.role_id], ) r = self.post('/OS-TRUST/trusts', body={'trust': ref}) diff --git a/keystone/tests/unit/test_validation.py b/keystone/tests/unit/test_validation.py index 6e9d0fb7b8..81c65e79cc 100644 --- a/keystone/tests/unit/test_validation.py +++ b/keystone/tests/unit/test_validation.py @@ -133,7 +133,6 @@ _INVALID_NAMES = [True, 24, ' ', '', 'a' * 256, None] class CommonValidationTestCase(unit.BaseTestCase): - def test_nullable_type_only(self): bool_without_enum = copy.deepcopy(parameter_types.boolean) bool_without_enum.pop('enum') @@ -173,7 +172,6 @@ class CommonValidationTestCase(unit.BaseTestCase): class EntityValidationTestCase(unit.BaseTestCase): - def setUp(self): super().setUp() self.resource_name = 'some resource name' @@ -2151,18 +2149,13 @@ class ServiceProviderValidationTestCase(unit.BaseTestCase): def test_validate_sp_request_without_sp_url_fails(self): """Validate request fails without `sp_url`.""" - request_to_validate = { - 'auth_url': self.valid_auth_url, - } + request_to_validate = {'auth_url': self.valid_auth_url} self.assertRaises( exception.SchemaValidationError, self.create_sp_validator.validate, request_to_validate, ) - request_to_validate = { - 'auth_url': self.valid_auth_url, - 'sp_url': None, - } + request_to_validate = {'auth_url': self.valid_auth_url, 'sp_url': None} self.assertRaises( exception.SchemaValidationError, self.create_sp_validator.validate, diff --git a/keystone/tests/unit/test_versions.py b/keystone/tests/unit/test_versions.py index d62e495bc0..2c579cdcff 100644 --- a/keystone/tests/unit/test_versions.py +++ b/keystone/tests/unit/test_versions.py @@ -48,13 +48,7 @@ v3_EXPECTED_RESPONSE = { v3_VERSION_RESPONSE = {"version": v3_EXPECTED_RESPONSE} -VERSIONS_RESPONSE = { - "versions": { - "values": [ - v3_EXPECTED_RESPONSE, - ] - } -} +VERSIONS_RESPONSE = {"versions": {"values": [v3_EXPECTED_RESPONSE]}} _build_ec2tokens_relation = functools.partial( json_home.build_v3_extension_resource_relation, @@ -232,9 +226,7 @@ V3_JSON_HOME_RESOURCES = { }, json_home.build_v3_resource_relation('domain'): { 'href-template': '/domains/{domain_id}', - 'href-vars': { - 'domain_id': json_home.Parameters.DOMAIN_ID, - }, + 'href-vars': {'domain_id': json_home.Parameters.DOMAIN_ID}, }, json_home.build_v3_resource_relation('domain_group_role'): { 'href-template': '/domains/{domain_id}/groups/{group_id}/roles/{role_id}', @@ -270,9 +262,7 @@ V3_JSON_HOME_RESOURCES = { json_home.build_v3_resource_relation('endpoint'): { 'href-template': '/endpoints/{endpoint_id}', 'href-vars': { - 'endpoint_id': json_home.build_v3_parameter_relation( - 'endpoint_id' - ), + 'endpoint_id': json_home.build_v3_parameter_relation('endpoint_id') }, }, json_home.build_v3_resource_relation('endpoints'): {'href': '/endpoints'}, @@ -290,9 +280,7 @@ V3_JSON_HOME_RESOURCES = { }, _build_ec2tokens_relation(resource_name='user_credentials'): { 'href-template': '/users/{user_id}/credentials/OS-EC2', - 'href-vars': { - 'user_id': json_home.Parameters.USER_ID, - }, + 'href-vars': {'user_id': json_home.Parameters.USER_ID}, }, REVOCATIONS_RELATION: {'href': '/auth/tokens/OS-PKI/revoked'}, 'https://docs.openstack.org/api/openstack-identity/3/ext/OS-REVOKE/1.0/rel' @@ -305,9 +293,7 @@ V3_JSON_HOME_RESOURCES = { }, _build_trust_relation(resource_name='trust'): { 'href-template': '/OS-TRUST/trusts/{trust_id}', - 'href-vars': { - 'trust_id': TRUST_ID_PARAMETER_RELATION, - }, + 'href-vars': {'trust_id': TRUST_ID_PARAMETER_RELATION}, }, _build_trust_relation(resource_name='trust_role'): { 'href-template': '/OS-TRUST/trusts/{trust_id}/roles/{role_id}', @@ -318,9 +304,7 @@ V3_JSON_HOME_RESOURCES = { }, _build_trust_relation(resource_name='trust_roles'): { 'href-template': '/OS-TRUST/trusts/{trust_id}/roles', - 'href-vars': { - 'trust_id': TRUST_ID_PARAMETER_RELATION, - }, + 'href-vars': {'trust_id': TRUST_ID_PARAMETER_RELATION}, }, _build_trust_relation(resource_name='trusts'): { 'href': '/OS-TRUST/trusts' @@ -329,9 +313,7 @@ V3_JSON_HOME_RESOURCES = { 's3tokens': {'href': '/s3tokens'}, json_home.build_v3_resource_relation('group'): { 'href-template': '/groups/{group_id}', - 'href-vars': { - 'group_id': json_home.Parameters.GROUP_ID, - }, + 'href-vars': {'group_id': json_home.Parameters.GROUP_ID}, }, json_home.build_v3_resource_relation('group_user'): { 'href-template': '/groups/{group_id}/users/{user_id}', @@ -342,23 +324,19 @@ V3_JSON_HOME_RESOURCES = { }, json_home.build_v3_resource_relation('group_users'): { 'href-template': '/groups/{group_id}/users', - 'href-vars': { - 'group_id': json_home.Parameters.GROUP_ID, - }, + 'href-vars': {'group_id': json_home.Parameters.GROUP_ID}, }, json_home.build_v3_resource_relation('groups'): {'href': '/groups'}, json_home.build_v3_resource_relation('policies'): {'href': '/policies'}, json_home.build_v3_resource_relation('policy'): { 'href-template': '/policies/{policy_id}', 'href-vars': { - 'policy_id': json_home.build_v3_parameter_relation('policy_id'), + 'policy_id': json_home.build_v3_parameter_relation('policy_id') }, }, json_home.build_v3_resource_relation('project'): { 'href-template': '/projects/{project_id}', - 'href-vars': { - 'project_id': json_home.Parameters.PROJECT_ID, - }, + 'href-vars': {'project_id': json_home.Parameters.PROJECT_ID}, }, json_home.build_v3_resource_relation('project_group_role'): { 'href-template': '/projects/{project_id}/groups/{group_id}/roles/{role_id}', @@ -401,15 +379,13 @@ V3_JSON_HOME_RESOURCES = { json_home.build_v3_resource_relation('region'): { 'href-template': '/regions/{region_id}', 'href-vars': { - 'region_id': json_home.build_v3_parameter_relation('region_id'), + 'region_id': json_home.build_v3_parameter_relation('region_id') }, }, json_home.build_v3_resource_relation('regions'): {'href': '/regions'}, json_home.build_v3_resource_relation('role'): { 'href-template': '/roles/{role_id}', - 'href-vars': { - 'role_id': json_home.Parameters.ROLE_ID, - }, + 'href-vars': {'role_id': json_home.Parameters.ROLE_ID}, }, json_home.build_v3_resource_relation('implied_roles'): { 'href-template': '/roles/{prior_role_id}/implies', @@ -423,7 +399,7 @@ V3_JSON_HOME_RESOURCES = { }, }, json_home.build_v3_resource_relation('role_inferences'): { - 'href': '/role_inferences', + 'href': '/role_inferences' }, json_home.build_v3_resource_relation('role_assignments'): { 'href': '/role_assignments' @@ -438,27 +414,19 @@ V3_JSON_HOME_RESOURCES = { json_home.build_v3_resource_relation('services'): {'href': '/services'}, json_home.build_v3_resource_relation('user'): { 'href-template': '/users/{user_id}', - 'href-vars': { - 'user_id': json_home.Parameters.USER_ID, - }, + 'href-vars': {'user_id': json_home.Parameters.USER_ID}, }, json_home.build_v3_resource_relation('user_change_password'): { 'href-template': '/users/{user_id}/password', - 'href-vars': { - 'user_id': json_home.Parameters.USER_ID, - }, + 'href-vars': {'user_id': json_home.Parameters.USER_ID}, }, json_home.build_v3_resource_relation('user_groups'): { 'href-template': '/users/{user_id}/groups', - 'href-vars': { - 'user_id': json_home.Parameters.USER_ID, - }, + 'href-vars': {'user_id': json_home.Parameters.USER_ID}, }, json_home.build_v3_resource_relation('user_projects'): { 'href-template': '/users/{user_id}/projects', - 'href-vars': { - 'user_id': json_home.Parameters.USER_ID, - }, + 'href-vars': {'user_id': json_home.Parameters.USER_ID}, }, json_home.build_v3_resource_relation('users'): {'href': '/users'}, json_home.build_v3_extension_resource_relation( @@ -467,9 +435,7 @@ V3_JSON_HOME_RESOURCES = { _build_federation_rel(resource_name='domains'): {'href': '/auth/domains'}, _build_federation_rel(resource_name='websso'): { 'href-template': '/auth/OS-FEDERATION/websso/{protocol_id}', - 'href-vars': { - 'protocol_id': PROTOCOL_ID_PARAM_RELATION, - }, + 'href-vars': {'protocol_id': PROTOCOL_ID_PARAM_RELATION}, }, _build_federation_rel(resource_name='projects'): { 'href': '/auth/projects' @@ -494,9 +460,7 @@ V3_JSON_HOME_RESOURCES = { }, _build_federation_rel(resource_name='identity_provider'): { 'href-template': '/OS-FEDERATION/identity_providers/{idp_id}', - 'href-vars': { - 'idp_id': IDP_ID_PARAMETER_RELATION, - }, + 'href-vars': {'idp_id': IDP_ID_PARAMETER_RELATION}, }, _build_federation_rel(resource_name='identity_providers_websso'): { 'href-template': FEDERATED_IDP_SPECIFIC_WEBSSO, @@ -507,15 +471,11 @@ V3_JSON_HOME_RESOURCES = { }, _build_federation_rel(resource_name='service_provider'): { 'href-template': '/OS-FEDERATION/service_providers/{sp_id}', - 'href-vars': { - 'sp_id': SP_ID_PARAMETER_RELATION, - }, + 'href-vars': {'sp_id': SP_ID_PARAMETER_RELATION}, }, _build_federation_rel(resource_name='mapping'): { 'href-template': '/OS-FEDERATION/mappings/{mapping_id}', - 'href-vars': { - 'mapping_id': MAPPING_ID_PARAM_RELATION, - }, + 'href-vars': {'mapping_id': MAPPING_ID_PARAM_RELATION}, }, _build_federation_rel(resource_name='identity_provider_protocol'): { 'href-template': BASE_IDP_PROTOCOL + '/{protocol_id}', @@ -546,15 +506,11 @@ V3_JSON_HOME_RESOURCES = { }, _build_oauth1_rel(resource_name='authorize_request_token'): { 'href-template': '/OS-OAUTH1/authorize/{request_token_id}', - 'href-vars': { - 'request_token_id': REQUEST_TOKEN_ID_PARAMETER_RELATION, - }, + 'href-vars': {'request_token_id': REQUEST_TOKEN_ID_PARAMETER_RELATION}, }, _build_oauth1_rel(resource_name='consumer'): { 'href-template': '/OS-OAUTH1/consumers/{consumer_id}', - 'href-vars': { - 'consumer_id': CONSUMER_ID_PARAMETER_RELATION, - }, + 'href-vars': {'consumer_id': CONSUMER_ID_PARAMETER_RELATION}, }, _build_oauth1_rel(resource_name='user_access_token'): { 'href-template': BASE_ACCESS_TOKEN, @@ -565,9 +521,7 @@ V3_JSON_HOME_RESOURCES = { }, _build_oauth1_rel(resource_name='user_access_tokens'): { 'href-template': '/users/{user_id}/OS-OAUTH1/access_tokens', - 'href-vars': { - 'user_id': json_home.Parameters.USER_ID, - }, + 'href-vars': {'user_id': json_home.Parameters.USER_ID}, }, _build_oauth1_rel(resource_name='user_access_token_role'): { 'href-template': BASE_ACCESS_TOKEN + '/roles/{role_id}', @@ -586,9 +540,7 @@ V3_JSON_HOME_RESOURCES = { }, _build_ep_policy_rel(resource_name='endpoint_policy'): { 'href-template': '/endpoints/{endpoint_id}/OS-ENDPOINT-POLICY/policy', - 'href-vars': { - 'endpoint_id': json_home.Parameters.ENDPOINT_ID, - }, + 'href-vars': {'endpoint_id': json_home.Parameters.ENDPOINT_ID}, }, _build_ep_policy_rel(resource_name='endpoint_policy_association'): { 'href-template': BASE_EP_POLICY + '/endpoints/{endpoint_id}', @@ -599,9 +551,7 @@ V3_JSON_HOME_RESOURCES = { }, _build_ep_policy_rel(resource_name='policy_endpoints'): { 'href-template': BASE_EP_POLICY + '/endpoints', - 'href-vars': { - 'policy_id': json_home.Parameters.POLICY_ID, - }, + 'href-vars': {'policy_id': json_home.Parameters.POLICY_ID}, }, _build_ep_policy_rel( resource_name='region_and_service_policy_association' @@ -625,7 +575,7 @@ V3_JSON_HOME_RESOURCES = { _build_ep_filter_rel(resource_name='endpoint_group'): { 'href-template': '/OS-EP-FILTER/endpoint_groups/{endpoint_group_id}', 'href-vars': { - 'endpoint_group_id': ENDPOINT_GROUP_ID_PARAMETER_RELATION, + 'endpoint_group_id': ENDPOINT_GROUP_ID_PARAMETER_RELATION }, }, _build_ep_filter_rel( @@ -642,14 +592,12 @@ V3_JSON_HOME_RESOURCES = { }, _build_ep_filter_rel(resource_name='endpoint_projects'): { 'href-template': '/OS-EP-FILTER/endpoints/{endpoint_id}/projects', - 'href-vars': { - 'endpoint_id': json_home.Parameters.ENDPOINT_ID, - }, + 'href-vars': {'endpoint_id': json_home.Parameters.ENDPOINT_ID}, }, _build_ep_filter_rel(resource_name='endpoints_in_endpoint_group'): { 'href-template': BASE_EP_FILTER + '/endpoints', 'href-vars': { - 'endpoint_group_id': ENDPOINT_GROUP_ID_PARAMETER_RELATION, + 'endpoint_group_id': ENDPOINT_GROUP_ID_PARAMETER_RELATION }, }, _build_ep_filter_rel(resource_name='project_endpoint_groups'): { @@ -658,9 +606,7 @@ V3_JSON_HOME_RESOURCES = { + '/projects/{project_id}' + '/endpoint_groups' ), - 'href-vars': { - 'project_id': json_home.Parameters.PROJECT_ID, - }, + 'href-vars': {'project_id': json_home.Parameters.PROJECT_ID}, }, _build_ep_filter_rel(resource_name='project_endpoint'): { 'href-template': ( @@ -673,16 +619,14 @@ V3_JSON_HOME_RESOURCES = { }, _build_ep_filter_rel(resource_name='project_endpoints'): { 'href-template': '/OS-EP-FILTER/projects/{project_id}/endpoints', - 'href-vars': { - 'project_id': json_home.Parameters.PROJECT_ID, - }, + 'href-vars': {'project_id': json_home.Parameters.PROJECT_ID}, }, _build_ep_filter_rel( resource_name='projects_associated_with_endpoint_group' ): { 'href-template': BASE_EP_FILTER + '/projects', 'href-vars': { - 'endpoint_group_id': ENDPOINT_GROUP_ID_PARAMETER_RELATION, + 'endpoint_group_id': ENDPOINT_GROUP_ID_PARAMETER_RELATION }, }, _build_os_inherit_rel( @@ -921,7 +865,7 @@ class VersionTestCase(unit.TestCase): for version in expected['versions']['values']: if version['id'].startswith('v3'): self._paste_in_port( - version, 'http://localhost:%s/v3/' % self.public_port + version, f'http://localhost:{self.public_port}/v3/' ) self.assertThat(data, _VersionsEqual(expected)) @@ -947,7 +891,7 @@ class VersionTestCase(unit.TestCase): data = jsonutils.loads(resp.body) expected = v3_VERSION_RESPONSE self._paste_in_port( - expected['version'], 'http://localhost:%s/v3/' % self.public_port + expected['version'], f'http://localhost:{self.public_port}/v3/' ) self.assertEqual(expected, data) @@ -979,7 +923,7 @@ class VersionTestCase(unit.TestCase): data = jsonutils.loads(resp.body) expected = v3_VERSION_RESPONSE self._paste_in_port( - expected['version'], 'http://localhost:%s/v3/' % self.public_port + expected['version'], f'http://localhost:{self.public_port}/v3/' ) self.assertEqual(expected, data) @@ -987,7 +931,7 @@ class VersionTestCase(unit.TestCase): v3_only_response = {"versions": {"values": [v3_EXPECTED_RESPONSE]}} self._paste_in_port( v3_only_response['versions']['values'][0], - 'http://localhost:%s/v3/' % self.public_port, + f'http://localhost:{self.public_port}/v3/', ) resp = client.get('/') self.assertEqual(300, resp.status_int) @@ -1106,7 +1050,7 @@ class VersionSingleAppTestCase(unit.TestCase): self.assertEqual(300, resp.status_int) data = jsonutils.loads(resp.body) expected = VERSIONS_RESPONSE - url_with_port = 'http://localhost:%s/v3/' % self.public_port + url_with_port = f'http://localhost:{self.public_port}/v3/' for version in expected['versions']['values']: # TODO(morgan): Eliminate the need to do the "paste-in-port" part # of the tests. Ultimately, this is very hacky and shows we are diff --git a/keystone/tests/unit/tests/test_core.py b/keystone/tests/unit/tests/test_core.py index cc0528c607..a2e1177d2a 100644 --- a/keystone/tests/unit/tests/test_core.py +++ b/keystone/tests/unit/tests/test_core.py @@ -25,7 +25,6 @@ LOG = log.getLogger(__name__) class BaseTestTestCase(unit.BaseTestCase): - def test_unexpected_exit(self): # if a test calls sys.exit it raises rather than exiting. self.assertThat( @@ -34,7 +33,6 @@ class BaseTestTestCase(unit.BaseTestCase): class TestOverrideSkipping(unit.BaseTestCase): - class TestParent(unit.BaseTestCase): def test_in_parent(self): pass @@ -70,7 +68,6 @@ class TestOverrideSkipping(unit.BaseTestCase): class TestTestCase(unit.TestCase): - def test_bad_log(self): # If the arguments are invalid for the string in a log it raises an # exception during testing. diff --git a/keystone/tests/unit/tests/test_utils.py b/keystone/tests/unit/tests/test_utils.py index 4deb225114..c9b3a54fa5 100644 --- a/keystone/tests/unit/tests/test_utils.py +++ b/keystone/tests/unit/tests/test_utils.py @@ -19,9 +19,7 @@ from keystone.tests.unit import utils class TestWipDecorator(testcase.TestCase): - def test_raises_SkipError_when_broken_test_fails(self): - @utils.wip('waiting on bug #000000') def test(): raise Exception('i expected a failure - this is a WIP') @@ -30,7 +28,6 @@ class TestWipDecorator(testcase.TestCase): self.assertThat(str(e), matchers.Contains('#000000')) def test_raises_AssertionError_when_test_passes(self): - @utils.wip('waiting on bug #000000') def test(): pass # literally diff --git a/keystone/tests/unit/token/test_fernet_provider.py b/keystone/tests/unit/token/test_fernet_provider.py index b1651b6ea2..70a0d975da 100644 --- a/keystone/tests/unit/token/test_fernet_provider.py +++ b/keystone/tests/unit/token/test_fernet_provider.py @@ -199,9 +199,7 @@ class TestValidate(unit.TestCase): # Check the user fields in the token result when use validate_v3_token # when the token has federated info. - group_ids = [ - uuid.uuid4().hex, - ] + group_ids = [uuid.uuid4().hex] self._test_validate_v3_token_federted_info(group_ids) def test_validate_v3_token_federated_info_empty_group(self): @@ -250,9 +248,7 @@ class TestValidate(unit.TestCase): trustor_user_id, trustee_user_id, project_id=project_ref['id'], - role_ids=[ - role_ref['id'], - ], + role_ids=[role_ref['id']], ) trust_ref = PROVIDERS.trust_api.create_trust( trust_ref['id'], trust_ref, trust_ref['roles'] @@ -286,7 +282,6 @@ class TestValidate(unit.TestCase): class TestValidateWithoutCache(TestValidate): - def config_overrides(self): super().config_overrides() self.config_fixture.config(group='token', caching=False) @@ -916,7 +911,7 @@ class TestFernetKeyRotation(unit.TestCase): # Simulate the disk full situation mock_open = mock.mock_open() file_handle = mock_open() - file_handle.flush.side_effect = IOError('disk full') + file_handle.flush.side_effect = OSError('disk full') with mock.patch('keystone.common.fernet_utils.open', mock_open): self.assertRaises(IOError, key_utils.rotate_keys) @@ -976,7 +971,6 @@ class TestFernetKeyRotation(unit.TestCase): class TestLoadKeys(unit.TestCase): - def assertValidFernetKeys(self, keys): # Make sure each key is a non-empty string for key in keys: diff --git a/keystone/tests/unit/token/test_jws_provider.py b/keystone/tests/unit/token/test_jws_provider.py index 885fe6ec94..02d82d3266 100644 --- a/keystone/tests/unit/token/test_jws_provider.py +++ b/keystone/tests/unit/token/test_jws_provider.py @@ -29,7 +29,6 @@ PROVIDERS = provider_api.ProviderAPIs class TestJWSProvider(unit.TestCase): - def setUp(self): super().setUp() self.config_fixture.config(group='token', provider='jws') diff --git a/keystone/tests/unit/token/test_token_serialization.py b/keystone/tests/unit/token/test_token_serialization.py index 1eb6818cc0..d6e979f46f 100644 --- a/keystone/tests/unit/token/test_token_serialization.py +++ b/keystone/tests/unit/token/test_token_serialization.py @@ -23,7 +23,6 @@ from keystone.tests.unit import base_classes class TestTokenSerialization(base_classes.TestCaseWithBootstrap): - def setUp(self): super().setUp() self.admin_user_id = self.bootstrapper.admin_user_id diff --git a/keystone/tests/unit/trust/test_backends.py b/keystone/tests/unit/trust/test_backends.py index 1dec2f2a49..12f535b97d 100644 --- a/keystone/tests/unit/trust/test_backends.py +++ b/keystone/tests/unit/trust/test_backends.py @@ -443,8 +443,7 @@ class TrustTests: ) self.assertIsNotNone(trust_data) PROVIDERS.trust_api.flush_expired_and_soft_deleted_trusts( - trustee_user_id=self.user_two['id'], - date=timeutils.utcnow(), + trustee_user_id=self.user_two['id'], date=timeutils.utcnow() ) trusts = self.trust_api.list_trusts() self.assertEqual(len(trusts), 1) @@ -479,8 +478,7 @@ class TrustTests: self.assertIsNotNone(trust_data) PROVIDERS.trust_api.flush_expired_and_soft_deleted_trusts( - trustor_user_id=self.user_foo['id'], - date=timeutils.utcnow(), + trustor_user_id=self.user_foo['id'], date=timeutils.utcnow() ) trusts = self.trust_api.list_trusts() self.assertEqual(len(trusts), 1) diff --git a/keystone/tests/unit/utils.py b/keystone/tests/unit/utils.py index d0f1ccd775..38c0e53114 100644 --- a/keystone/tests/unit/utils.py +++ b/keystone/tests/unit/utils.py @@ -89,27 +89,19 @@ def wip(message, expected_exception=Exception, bug=None): __e, expected_exception ): raise AssertionError( - 'Work In Progress Test Failed%(bugstr)s with ' - 'unexpected exception. Expected "%(expected)s" ' - 'got "%(exception)s": %(message)s ' - % { - 'message': message, - 'bugstr': bugstr, - 'expected': expected_exception.__class__.__name__, - 'exception': __e.__class__.__name__, - } + f'Work In Progress Test Failed{bugstr} with ' + f'unexpected exception. Expected "{expected_exception.__class__.__name__}" ' + f'got "{__e.__class__.__name__}": {message} ' ) # NOTE(notmorgan): We got the expected exception we can safely # skip this test. raise unittest.SkipTest( 'Work In Progress Test Failed as ' - 'expected%(bugstr)s: %(message)s' - % {'message': message, 'bugstr': bugstr} + f'expected{bugstr}: {message}' ) raise AssertionError( - 'Work In Progress Test Passed%(bugstr)s: ' - '%(message)s' % {'message': message, 'bugstr': bugstr} + f'Work In Progress Test Passed{bugstr}: ' f'{message}' ) return run_test diff --git a/keystone/token/provider.py b/keystone/token/provider.py index bb699e588a..46b75719f3 100644 --- a/keystone/token/provider.py +++ b/keystone/token/provider.py @@ -108,7 +108,7 @@ class Manager(manager.Manager): ['project', self._drop_token_cache], ], notifications.ACTIONS.internal: [ - [notifications.INVALIDATE_TOKEN_CACHE, self._drop_token_cache], + [notifications.INVALIDATE_TOKEN_CACHE, self._drop_token_cache] ], } @@ -254,7 +254,6 @@ class Manager(manager.Manager): thumbprint=None, parent_audit_id=None, ): - # NOTE(lbragstad): Grab a blank token object and use composition to # build the token according to the authentication and authorization # context. This cuts down on the amount of logic we have to stuff into diff --git a/keystone/token/providers/jws/core.py b/keystone/token/providers/jws/core.py index 15490915ca..23af16cb3a 100644 --- a/keystone/token/providers/jws/core.py +++ b/keystone/token/providers/jws/core.py @@ -26,7 +26,6 @@ CONF = keystone.conf.CONF class Provider(base.Provider): - def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -92,7 +91,6 @@ class Provider(base.Provider): class JWSFormatter: - # NOTE(lbragstad): If in the future we expand support for different # algorithms, make this configurable and validate it against a blessed list # of supported algorithms. @@ -133,7 +131,6 @@ class JWSFormatter: app_cred_id=None, thumbprint=None, ): - issued_at = utils.isotime(subsecond=True) issued_at_int = self._convert_time_string_to_int(issued_at) expires_at_int = self._convert_time_string_to_int(expires_at) @@ -213,7 +210,7 @@ class JWSFormatter: ) def _decode_token_from_id(self, token_id): - options = dict() + options = {} options['verify_exp'] = False for public_key in self.public_keys: try: diff --git a/keystone/token/token_formatters.py b/keystone/token/token_formatters.py index 7644a745ce..65195ec75c 100644 --- a/keystone/token/token_formatters.py +++ b/keystone/token/token_formatters.py @@ -185,7 +185,7 @@ class TokenFormatter: if len(token) > CONF.max_token_size: LOG.info( f'Fernet token created with length of {len(token)} ' - f'characters, which exceeds {CONF.max_token_size} characters', + f'characters, which exceeds {CONF.max_token_size} characters' ) return token @@ -807,7 +807,6 @@ class FederatedUnscopedPayload(BasePayload): class FederatedScopedPayload(FederatedUnscopedPayload): - @classmethod def assemble( cls, diff --git a/keystone/trust/backends/base.py b/keystone/trust/backends/base.py index 1eeb6984d0..8945818514 100644 --- a/keystone/trust/backends/base.py +++ b/keystone/trust/backends/base.py @@ -18,7 +18,6 @@ from keystone import exception class TrustDriverBase(metaclass=abc.ABCMeta): - @abc.abstractmethod def create_trust(self, trust_id, trust, roles): """Create a new trust. diff --git a/keystone/trust/backends/sql.py b/keystone/trust/backends/sql.py index 2584d3a811..e98f5530b9 100644 --- a/keystone/trust/backends/sql.py +++ b/keystone/trust/backends/sql.py @@ -41,10 +41,7 @@ class TrustModel(sql.ModelBase, sql.ModelDictMixinWithExtras): ] id = sql.Column(sql.String(64), primary_key=True) # user id of owner - trustor_user_id = sql.Column( - sql.String(64), - nullable=False, - ) + trustor_user_id = sql.Column(sql.String(64), nullable=False) # user_id of user allowed to consume this preauth trustee_user_id = sql.Column(sql.String(64), nullable=False) project_id = sql.Column(sql.String(64)) diff --git a/releasenotes/source/conf.py b/releasenotes/source/conf.py index 883bc2ffae..194c2fd965 100644 --- a/releasenotes/source/conf.py +++ b/releasenotes/source/conf.py @@ -36,10 +36,7 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = [ - 'openstackdocstheme', - 'reno.sphinxext', -] +extensions = ['openstackdocstheme', 'reno.sphinxext'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -202,7 +199,7 @@ latex_documents = [ 'Keystone Release Notes Documentation', 'Keystone Developers', 'manual', - ), + ) ] # The name of an image file (relative to this directory) to place at the top of @@ -258,7 +255,7 @@ texinfo_documents = [ 'KeystoneReleaseNotes', 'Identity, Authentication and Access Management for OpenStack.', 'Miscellaneous', - ), + ) ] # Documents to append as an appendix to all manuals. diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000000..366771e0bd --- /dev/null +++ b/ruff.toml @@ -0,0 +1,15 @@ +line-length = 79 +target-version = "py38" + +[lint] +# enable the following rule classes: +# +# C4: https://docs.astral.sh/ruff/rules/#flake8-comprehensions-c4 +# UP: https://docs.astral.sh/ruff/rules/#pyupgrade-up +select = ["C4", "UP"] + +[format] +quote-style = "preserve" +docstring-code-format = true +docstring-code-line-length = "dynamic" +skip-magic-trailing-comma = true diff --git a/tox.ini b/tox.ini index 63ebbf3c27..06e8354ab8 100644 --- a/tox.ini +++ b/tox.ini @@ -80,6 +80,8 @@ commands = passenv = KSTEST_* [flake8] +# We only enable the hacking (H) +select = H application-import-names = keystone import-order-style = pep8 filename = *.py,keystone-manage @@ -102,27 +104,6 @@ enable-extensions = H203,H904 ignore = D100,D101,D102,D103,D104,D106,D107,E203,D203,D401,E402,H211,H214,W503,W504 exclude = .venv,.git,.tox,build,dist,*lib/python*,*egg,tools,vendor,.update-venv,*.ini,*.po,*.pot max-complexity = 24 -per-file-ignores = -# URL lines too long - keystone/common/password_hashing.py: E501 - keystone/api/auth.py: E501 - keystone/api/users.py: E501 - keystone/federation/utils.py: E501 - keystone/assignment/core.py: E501 - keystone/common/policies/endpoint_group.py: E501 - keystone/exception.py: E501 - keystone/resource/core.py: E501 - keystone/tests/protection/v3/test_credentials.py: E501 - keystone/tests/protection/v3/test_grants.py: E501 - keystone/tests/protection/v3/test_groups.py: E501 - keystone/tests/unit/assignment/test_backends.py: E501 - keystone/tests/unit/ksfixtures/__init__.py: H301,F401,E501 - keystone/tests/unit/test_associate_project_endpoint_extension.py: E501 - keystone/tests/unit/test_backend_ldap.py: E501 - keystone/tests/unit/test_cli.py: E501 - keystone/tests/unit/test_versions.py: E501 - keystone/tests/unit/test_v3_filters.py: E501 - keystone/token/providers/jws/core.py: E501 [testenv:docs] deps =