diff options
author | Aarni Koskela <akx@iki.fi> | 2022-10-27 15:14:12 +0300 |
---|---|---|
committer | Ivan Kanakarakis <ivan.kanak@gmail.com> | 2022-11-15 13:06:41 +0200 |
commit | 15f131d08a0905662bc578d1d9c7d8fa8d8fda43 (patch) | |
tree | 2c364fefc8d79c56dca8bef530c20141f6d4a39b | |
parent | 3824f60d97ea977c852d6e256b8a38e9d029e405 (diff) | |
download | pysaml2-15f131d08a0905662bc578d1d9c7d8fa8d8fda43.tar.gz |
Run flynt + black + isort
64 files changed, 404 insertions, 449 deletions
diff --git a/example/idp2/idp.py b/example/idp2/idp.py index 300e43a2..6bd85a5e 100755 --- a/example/idp2/idp.py +++ b/example/idp2/idp.py @@ -359,7 +359,7 @@ class SSO(Service): kwargs = {} http_args = IDP.apply_binding( - self.binding_out, "%s" % _resp, self.destination, relay_state, response=True, **kwargs + self.binding_out, f"{_resp}", self.destination, relay_state, response=True, **kwargs ) logger.debug("HTTPargs: %s", http_args) @@ -587,7 +587,7 @@ def do_verify(environ, start_response, _): kaka = set_cookie("idpauthn", "/", uid, query["authn_reference"][0]) - lox = "{}?id={}&key={}".format(query["redirect_uri"][0], uid, query["key"][0]) + lox = f"{query['redirect_uri'][0]}?id={uid}&key={query['key'][0]}" logger.debug("Redirect => %s", lox) resp = Redirect(lox, headers=[kaka], content="text/html") @@ -622,7 +622,7 @@ class SLO(Service): req_info = IDP.parse_logout_request(request, binding) except Exception as exc: logger.error("Bad request: %s", exc) - resp = BadRequest("%s" % exc) + resp = BadRequest(f"{exc}") return resp(self.environ, self.start_response) msg = req_info.message @@ -652,10 +652,10 @@ class SLO(Service): response = True try: - hinfo = IDP.apply_binding(binding, "%s" % resp, destination, relay_state, response=response) + hinfo = IDP.apply_binding(binding, f"{resp}", destination, relay_state, response=response) except Exception as exc: logger.error("ServiceError: %s", exc) - resp = ServiceError("%s" % exc) + resp = ServiceError(f"{exc}") return resp(self.environ, self.start_response) # _tlh = dict2list_of_tuples(hinfo["headers"]) @@ -698,7 +698,7 @@ class NMI(Service): _resp = IDP.create_manage_name_id_response(request) # It's using SOAP binding - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % _resp, "", relay_state, response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{_resp}", "", relay_state, response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -720,7 +720,7 @@ class AIDR(Service): resp = NotFound(aid) return resp(self.environ, self.start_response) - hinfo = IDP.apply_binding(BINDING_URI, "%s" % assertion, response=True) + hinfo = IDP.apply_binding(BINDING_URI, f"{assertion}", response=True) logger.debug("HINFO: %s", hinfo) resp = Response(hinfo["data"], headers=hinfo["headers"]) @@ -746,7 +746,7 @@ class ARS(Service): msg = IDP.create_artifact_response(_req, _req.artifact.text) - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % msg, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{msg}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -767,7 +767,7 @@ class AQS(Service): msg = IDP.create_authn_query_response(_query.subject, _query.requested_authn_context, _query.session_index) logger.debug("response: %s", msg) - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % msg, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{msg}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -796,7 +796,7 @@ class ATTR(Service): msg = IDP.create_attribute_response(identity, name_id=name_id, **args) logger.debug("response: %s", msg) - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % msg, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{msg}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -829,7 +829,7 @@ class NIM(Service): _resp = IDP.create_name_id_mapping_response(name_id, **info) # Only SOAP - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % _resp, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{_resp}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) diff --git a/example/idp2/idp_uwsgi.py b/example/idp2/idp_uwsgi.py index 442cbae4..ab14e0ec 100755 --- a/example/idp2/idp_uwsgi.py +++ b/example/idp2/idp_uwsgi.py @@ -311,7 +311,7 @@ class SSO(Service): kwargs = {} http_args = IDP.apply_binding( - self.binding_out, "%s" % _resp, self.destination, relay_state, response=True, **kwargs + self.binding_out, f"{_resp}", self.destination, relay_state, response=True, **kwargs ) logger.debug("HTTPargs: %s", http_args) @@ -511,7 +511,7 @@ def do_verify(environ, start_response, _): kaka = set_cookie("idpauthn", "/", uid, query["authn_reference"][0]) - lox = "{}?id={}&key={}".format(query["redirect_uri"][0], uid, query["key"][0]) + lox = f"{query['redirect_uri'][0]}?id={uid}&key={query['key'][0]}" logger.debug("Redirect => %s", lox) resp = Redirect(lox, headers=[kaka], content="text/html") @@ -545,7 +545,7 @@ class SLO(Service): req_info = IDP.parse_logout_request(body, binding) except Exception as exc: logger.error("Bad request: %s", exc) - resp = BadRequest("%s" % exc) + resp = BadRequest(f"{exc}") return resp(self.environ, self.start_response) msg = req_info.message @@ -562,16 +562,16 @@ class SLO(Service): IDP.session_db.remove_authn_statements(msg.name_id) except KeyError as exc: logger.error("ServiceError: %s", exc) - resp = ServiceError("%s" % exc) + resp = ServiceError(f"{exc}") return resp(self.environ, self.start_response) resp = IDP.create_logout_response(msg, [binding]) try: - hinfo = IDP.apply_binding(binding, "%s" % resp, "", relay_state) + hinfo = IDP.apply_binding(binding, f"{resp}", "", relay_state) except Exception as exc: logger.error("ServiceError: %s", exc) - resp = ServiceError("%s" % exc) + resp = ServiceError(f"{exc}") return resp(self.environ, self.start_response) # _tlh = dict2list_of_tuples(hinfo["headers"]) @@ -604,7 +604,7 @@ class NMI(Service): _resp = IDP.create_manage_name_id_response(request) # It's using SOAP binding - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % _resp, "", relay_state, response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{_resp}", "", relay_state, response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -626,7 +626,7 @@ class AIDR(Service): resp = NotFound(aid) return resp(self.environ, self.start_response) - hinfo = IDP.apply_binding(BINDING_URI, "%s" % assertion, response=True) + hinfo = IDP.apply_binding(BINDING_URI, f"{assertion}", response=True) logger.debug("HINFO: %s", hinfo) resp = Response(hinfo["data"], headers=hinfo["headers"]) @@ -652,7 +652,7 @@ class ARS(Service): msg = IDP.create_artifact_response(_req, _req.artifact.text) - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % msg, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{msg}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -673,7 +673,7 @@ class AQS(Service): msg = IDP.create_authn_query_response(_query.subject, _query.requested_authn_context, _query.session_index) logger.debug("response: %s", msg) - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % msg, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{msg}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -702,7 +702,7 @@ class ATTR(Service): msg = IDP.create_attribute_response(identity, name_id=name_id, **args) logger.debug("response: %s", msg) - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % msg, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{msg}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -735,7 +735,7 @@ class NIM(Service): _resp = IDP.create_name_id_mapping_response(name_id, **info) # Only SOAP - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % _resp, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{_resp}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -948,8 +948,8 @@ from mako.lookup import TemplateLookup AUTHN_BROKER = AuthnBroker() -AUTHN_BROKER.add(authn_context_class_ref(PASSWORD), username_password_authn, 10, "http://%s" % socket.gethostname()) -AUTHN_BROKER.add(authn_context_class_ref(UNSPECIFIED), "", 0, "http://%s" % socket.gethostname()) +AUTHN_BROKER.add(authn_context_class_ref(PASSWORD), username_password_authn, 10, f"http://{socket.gethostname()}") +AUTHN_BROKER.add(authn_context_class_ref(UNSPECIFIED), "", 0, f"http://{socket.gethostname()}") CONFIG = importlib.import_module(args.config) IDP = server.Server(args.config, cache=Cache()) IDP.ticket = {} diff --git a/example/idp2_repoze/idp.py b/example/idp2_repoze/idp.py index 9be36b71..d42f8262 100755 --- a/example/idp2_repoze/idp.py +++ b/example/idp2_repoze/idp.py @@ -309,7 +309,7 @@ class SSO(Service): return resp(self.environ, self.start_response) logger.info("AuthNResponse: %s", _resp) - http_args = IDP.apply_binding(self.binding_out, "%s" % _resp, self.destination, relay_state, response=True) + http_args = IDP.apply_binding(self.binding_out, f"{_resp}", self.destination, relay_state, response=True) logger.debug("HTTPargs: %s", http_args) return self.response(self.binding_out, http_args) @@ -505,7 +505,7 @@ def do_verify(environ, start_response, _): kaka = set_cookie("idpauthn", "/", uid, query["authn_reference"][0]) - lox = "{}?id={}&key={}".format(query["redirect_uri"][0], uid, query["key"][0]) + lox = f"{query['redirect_uri'][0]}?id={uid}&key={query['key'][0]}" logger.debug("Redirect => %s", lox) resp = Redirect(lox, headers=[kaka], content="text/html") @@ -539,7 +539,7 @@ class SLO(Service): req_info = IDP.parse_logout_request(body, binding) except Exception as exc: logger.error("Bad request: %s", exc) - resp = BadRequest("%s" % exc) + resp = BadRequest(f"{exc}") return resp(self.environ, self.start_response) msg = req_info.message @@ -556,16 +556,16 @@ class SLO(Service): IDP.session_db.remove_authn_statements(msg.name_id) except KeyError as exc: logger.error("ServiceError: %s", exc) - resp = ServiceError("%s" % exc) + resp = ServiceError(f"{exc}") return resp(self.environ, self.start_response) resp = IDP.create_logout_response(msg, [binding]) try: - hinfo = IDP.apply_binding(binding, "%s" % resp, "", relay_state) + hinfo = IDP.apply_binding(binding, f"{resp}", "", relay_state) except Exception as exc: logger.error("ServiceError: %s", exc) - resp = ServiceError("%s" % exc) + resp = ServiceError(f"{exc}") return resp(self.environ, self.start_response) # _tlh = dict2list_of_tuples(hinfo["headers"]) @@ -598,7 +598,7 @@ class NMI(Service): _resp = IDP.create_manage_name_id_response(request) # It's using SOAP binding - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % _resp, "", relay_state, response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{_resp}", "", relay_state, response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -620,7 +620,7 @@ class AIDR(Service): resp = NotFound(aid) return resp(self.environ, self.start_response) - hinfo = IDP.apply_binding(BINDING_URI, "%s" % assertion, response=True) + hinfo = IDP.apply_binding(BINDING_URI, f"{assertion}", response=True) logger.debug("HINFO: %s", hinfo) resp = Response(hinfo["data"], headers=hinfo["headers"]) @@ -646,7 +646,7 @@ class ARS(Service): msg = IDP.create_artifact_response(_req, _req.artifact.text) - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % msg, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{msg}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -667,7 +667,7 @@ class AQS(Service): msg = IDP.create_authn_query_response(_query.subject, _query.requested_authn_context, _query.session_index) logger.debug("response: %s", msg) - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % msg, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{msg}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -696,7 +696,7 @@ class ATTR(Service): msg = IDP.create_attribute_response(identity, name_id=name_id, **args) logger.debug("response: %s", msg) - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % msg, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{msg}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -729,7 +729,7 @@ class NIM(Service): _resp = IDP.create_name_id_mapping_response(name_id, **info) # Only SOAP - hinfo = IDP.apply_binding(BINDING_SOAP, "%s" % _resp, "", "", response=True) + hinfo = IDP.apply_binding(BINDING_SOAP, f"{_resp}", "", "", response=True) resp = Response(hinfo["data"], headers=hinfo["headers"]) return resp(self.environ, self.start_response) @@ -937,8 +937,8 @@ from mako.lookup import TemplateLookup AUTHN_BROKER = AuthnBroker() -AUTHN_BROKER.add(authn_context_class_ref(PASSWORD), username_password_authn, 10, "http://%s" % socket.gethostname()) -AUTHN_BROKER.add(authn_context_class_ref(UNSPECIFIED), "", 0, "http://%s" % socket.gethostname()) +AUTHN_BROKER.add(authn_context_class_ref(PASSWORD), username_password_authn, 10, f"http://{socket.gethostname()}") +AUTHN_BROKER.add(authn_context_class_ref(UNSPECIFIED), "", 0, f"http://{socket.gethostname()}") IDP = server.Server(args.config, cache=Cache()) IDP.ticket = {} diff --git a/example/sp-repoze/sp.py b/example/sp-repoze/sp.py index 109e40e7..d0429289 100755 --- a/example/sp-repoze/sp.py +++ b/example/sp-repoze/sp.py @@ -26,21 +26,21 @@ args = None def dict_to_table(ava, lev=0, width=1): - txt = ['<table border=%s bordercolor="black">\n' % width] + txt = [f'<table border={width} bordercolor="black">\n'] for prop, valarr in ava.items(): txt.append("<tr>\n") if isinstance(valarr, basestring): - txt.append("<th>%s</th>\n" % str(prop)) + txt.append(f"<th>{str(prop)}</th>\n") try: - txt.append("<td>%s</td>\n" % valarr.encode("utf8")) + txt.append(f"<td>{valarr.encode('utf8')}</td>\n") except AttributeError: - txt.append("<td>%s</td>\n" % valarr) + txt.append(f"<td>{valarr}</td>\n") elif isinstance(valarr, list): i = 0 n = len(valarr) for val in valarr: if not i: - txt.append("<th rowspan=%d>%s</td>\n" % (len(valarr), prop)) + txt.append(f"<th rowspan={len(valarr)}>{prop}</td>\n") else: txt.append("<tr>\n") if isinstance(val, dict): @@ -49,15 +49,15 @@ def dict_to_table(ava, lev=0, width=1): txt.append("</td>\n") else: try: - txt.append("<td>%s</td>\n" % val.encode("utf8")) + txt.append(f"<td>{val.encode('utf8')}</td>\n") except AttributeError: - txt.append("<td>%s</td>\n" % val) + txt.append(f"<td>{val}</td>\n") if n > 1: txt.append("</tr>\n") n -= 1 i += 1 elif isinstance(valarr, dict): - txt.append("<th>%s</th>\n" % prop) + txt.append(f"<th>{prop}</th>\n") txt.append("<td>\n") txt.extend(dict_to_table(valarr, lev + 1, width - 1)) txt.append("</td>\n") diff --git a/example/sp-wsgi/sp.py b/example/sp-wsgi/sp.py index 0540d71a..35061236 100755 --- a/example/sp-wsgi/sp.py +++ b/example/sp-wsgi/sp.py @@ -72,18 +72,18 @@ POLICY = None def dict_to_table(ava, lev=0, width=1): - txt = ['<table border=%s bordercolor="black">\n' % width] + txt = [f'<table border={width} bordercolor="black">\n'] for prop, valarr in ava.items(): txt.append("<tr>\n") if isinstance(valarr, str): - txt.append("<th>%s</th>\n" % str(prop)) - txt.append("<td>%s</td>\n" % valarr) + txt.append(f"<th>{str(prop)}</th>\n") + txt.append(f"<td>{valarr}</td>\n") elif isinstance(valarr, list): i = 0 n = len(valarr) for val in valarr: if not i: - txt.append("<th rowspan=%d>%s</td>\n" % (len(valarr), prop)) + txt.append(f"<th rowspan={len(valarr)}>{prop}</td>\n") else: txt.append("<tr>\n") if isinstance(val, dict): @@ -91,13 +91,13 @@ def dict_to_table(ava, lev=0, width=1): txt.extend(dict_to_table(val, lev + 1, width - 1)) txt.append("</td>\n") else: - txt.append("<td>%s</td>\n" % val) + txt.append(f"<td>{val}</td>\n") if n > 1: txt.append("</tr>\n") n -= 1 i += 1 elif isinstance(valarr, dict): - txt.append("<th>%s</th>\n" % prop) + txt.append(f"<th>{prop}</th>\n") txt.append("<td>\n") txt.extend(dict_to_table(valarr, lev + 1, width - 1)) txt.append("</td>\n") @@ -555,7 +555,7 @@ class SSO: logger.debug("Redirect to Discovery Service function") eid = _cli.config.entityid ret = _cli.config.getattr("endpoints", "sp")["discovery_response"][0][0] - ret += "?sid=%s" % sid_ + ret += f"?sid={sid_}" loc = _cli.create_discovery_service_request(self.discosrv, eid, **{"return": ret}) return -1, SeeOther(loc) elif len(idps) == 1: @@ -598,7 +598,7 @@ class SSO: ) _rstate = rndstr() self.cache.relay_state[_rstate] = came_from - ht_args = _cli.apply_binding(_binding, "%s" % req, destination, relay_state=_rstate, sigalg=sigalg) + ht_args = _cli.apply_binding(_binding, f"{req}", destination, relay_state=_rstate, sigalg=sigalg) _sid = req_id if cert is not None: @@ -606,7 +606,7 @@ class SSO: except Exception as exc: logger.exception(exc) - resp = ServiceError("Failed to construct the AuthnRequest: %s" % exc) + resp = ServiceError(f"Failed to construct the AuthnRequest: {exc}") return resp # remember the request @@ -773,17 +773,17 @@ urls = [ def add_urls(): base = "acs" - urls.append(("%s/post$" % base, (ACS, "post", SP))) - urls.append(("%s/post/(.*)$" % base, (ACS, "post", SP))) - urls.append(("%s/redirect$" % base, (ACS, "redirect", SP))) - urls.append(("%s/redirect/(.*)$" % base, (ACS, "redirect", SP))) + urls.append((f"{base}/post$", (ACS, "post", SP))) + urls.append((f"{base}/post/(.*)$", (ACS, "post", SP))) + urls.append((f"{base}/redirect$", (ACS, "redirect", SP))) + urls.append((f"{base}/redirect/(.*)$", (ACS, "redirect", SP))) base = "slo" - urls.append(("%s/post$" % base, (SLO, "post", SP))) - urls.append(("%s/post/(.*)$" % base, (SLO, "post", SP))) - urls.append(("%s/redirect$" % base, (SLO, "redirect", SP))) - urls.append(("%s/redirect/(.*)$" % base, (SLO, "redirect", SP))) + urls.append((f"{base}/post$", (SLO, "post", SP))) + urls.append((f"{base}/post/(.*)$", (SLO, "post", SP))) + urls.append((f"{base}/redirect$", (SLO, "redirect", SP))) + urls.append((f"{base}/redirect/(.*)$", (SLO, "redirect", SP))) # ---------------------------------------------------------------------------- @@ -847,14 +847,14 @@ def application(environ, start_response): return handle_static(environ, start_response, path) return not_found(environ, start_response) except StatusError as err: - logging.error("StatusError: %s" % err) - resp = BadRequest("%s" % err) + logging.error(f"StatusError: {err}") + resp = BadRequest(f"{err}") return resp(environ, start_response) except Exception as err: # _err = exception_trace("RUN", err) # logging.error(exception_trace("RUN", _err)) print(err, file=sys.stderr) - resp = ServiceError("%s" % err) + resp = ServiceError(f"{err}") return resp(environ, start_response) @@ -932,7 +932,7 @@ if __name__ == "__main__": # your cert and all the way up to the top CERT_CHAIN = service_conf.CERT_CHAIN - SP = Saml2Client(config_file="%s" % CNFBASE) + SP = Saml2Client(config_file=f"{CNFBASE}") POLICY = service_conf.POLICY diff --git a/src/saml2/__init__.py b/src/saml2/__init__.py index 6259373c..c5142c55 100644 --- a/src/saml2/__init__.py +++ b/src/saml2/__init__.py @@ -587,7 +587,7 @@ class SamlBase(ExtensionContainer): uri_set = self.get_ns_map(elements, set()) prefix_map = {} for uri in sorted(uri_set): - prefix_map["encas%d" % len(prefix_map)] = uri + prefix_map[f"encas{len(prefix_map)}"] = uri return prefix_map def get_xml_string_with_self_contained_assertion_within_advice_encrypted_assertion(self, assertion_tag, advice_tag): @@ -743,7 +743,7 @@ class SamlBase(ExtensionContainer): elif val is None: pass else: - raise ValueError("Type shouldn't be '%s'" % val) + raise ValueError(f"Type shouldn't be '{val}'") return self diff --git a/src/saml2/assertion.py b/src/saml2/assertion.py index 08c4f908..344c7863 100644 --- a/src/saml2/assertion.py +++ b/src/saml2/assertion.py @@ -117,7 +117,7 @@ def filter_on_attributes(ava, required=None, optional=None, acs=None, fail_on_un if _fn: _apply_attr_value_restrictions(attr, res, True) elif fail_on_unfulfilled_requirements: - desc = "Required attribute missing: '%s'" % (attr["name"]) + desc = f"Required attribute missing: '{attr['name']}'" raise MissingValue(desc) if optional is None: @@ -284,7 +284,7 @@ def compile(restrictions): try: _mod = importlib.import_module(cat) except ImportError: - _mod = importlib.import_module("saml2.entity_category.%s" % cat) + _mod = importlib.import_module(f"saml2.entity_category.{cat}") _ec = {} for key, items in _mod.RELEASE.items(): @@ -788,7 +788,7 @@ class Assertion(dict): if encrypt == "attributes": for attr in attr_statement.attribute: - enc = sec_context.encrypt(text="%s" % attr) + enc = sec_context.encrypt(text=f"{attr}") encd = xmlenc.encrypted_data_from_string(enc) encattr = saml.EncryptedAttribute(encrypted_data=encd) diff --git a/src/saml2/attribute_converter.py b/src/saml2/attribute_converter.py index 505d1564..7e86b917 100644 --- a/src/saml2/attribute_converter.py +++ b/src/saml2/attribute_converter.py @@ -70,7 +70,7 @@ def ac_factory(path=""): from saml2 import attributemaps for typ in attributemaps.__all__: - mod = import_module(".%s" % typ, "saml2.attributemaps") + mod = import_module(f".{typ}", "saml2.attributemaps") acs.extend(_attribute_map_module_to_acs(mod)) return acs @@ -223,7 +223,7 @@ def d_to_local_name(acs, attr): try: return attr["friendly_name"] except KeyError: - raise ConverterError("Could not find local name for %s" % attr) + raise ConverterError(f"Could not find local name for {attr}") class AttributeConverter: diff --git a/src/saml2/authn.py b/src/saml2/authn.py index a7ef3355..dfd0a925 100644 --- a/src/saml2/authn.py +++ b/src/saml2/authn.py @@ -97,7 +97,7 @@ def create_return_url(base, query, **kwargs): else: _pre = base - logger.debug("kwargs: %s" % kwargs) + logger.debug(f"kwargs: {kwargs}") return f"{_pre}?{url_encode_params(kwargs)}" @@ -144,7 +144,7 @@ class UsernamePasswordMako(UserAuthnMethod): "logo_url": logo_url, "query": query, } - logger.debug("do_authentication argv: %s" % argv) + logger.debug(f"do_authentication argv: {argv}") mte = self.template_lookup.get_template(self.mako_template) resp.message = mte.render(**argv) return resp @@ -190,7 +190,7 @@ class UsernamePasswordMako(UserAuthnMethod): if cookie is None: return None else: - logger.debug("kwargs: %s" % kwargs) + logger.debug(f"kwargs: {kwargs}") try: info, timestamp = parse_cookie(self.cookie_name, self.srv.seed, cookie) if self.active[info] == timestamp: diff --git a/src/saml2/cache.py b/src/saml2/cache.py index 56351fe7..5aaddbdb 100644 --- a/src/saml2/cache.py +++ b/src/saml2/cache.py @@ -104,7 +104,7 @@ class Cache: (timestamp, info) = self._db[cni][entity_id] info = info.copy() if check_not_on_or_after and time_util.after(timestamp): - raise TooOld("past %s" % str(timestamp)) + raise TooOld(f"past {str(timestamp)}") if "name_id" in info and isinstance(info["name_id"], str): info["name_id"] = decode(info["name_id"]) diff --git a/src/saml2/cert.py b/src/saml2/cert.py index 247b9f56..c5f62660 100644 --- a/src/saml2/cert.py +++ b/src/saml2/cert.py @@ -117,8 +117,8 @@ class OpenSSLWrapper: k_f = None if write_to_file: - cert_file = "%s.crt" % cn - key_file = "%s.key" % cn + cert_file = f"{cn}.crt" + key_file = f"{cn}.key" try: remove(cert_file) except Exception: @@ -331,9 +331,9 @@ class OpenSSLWrapper: crypto.verify(ca_cert, cert_crypto.signature, cert_crypto.tbs_certificate_bytes, cert_algorithm) return True, "Signed certificate is valid and correctly signed by CA certificate." except crypto.Error as e: - return False, "Certificate is incorrectly signed: %s" % str(e) + return False, f"Certificate is incorrectly signed: {str(e)}" except Exception as e: - return False, "Certificate is not valid for an unknown reason. %s" % str(e) + return False, f"Certificate is not valid for an unknown reason. {str(e)}" def read_cert_from_file(cert_file, cert_type="pem"): diff --git a/src/saml2/client.py b/src/saml2/client.py index 4f947954..1a40258d 100644 --- a/src/saml2/client.py +++ b/src/saml2/client.py @@ -427,8 +427,8 @@ class Saml2Client(Base): ) def _use_soap(self, destination, query_type, **kwargs): - _create_func = getattr(self, "create_%s" % query_type) - _response_func = getattr(self, "parse_%s_response" % query_type) + _create_func = getattr(self, f"create_{query_type}") + _response_func = getattr(self, f"parse_{query_type}_response") try: response_args = kwargs["response_args"] del kwargs["response_args"] @@ -501,7 +501,7 @@ class Saml2Client(Base): srvs = self.metadata.assertion_id_request_service(entity_id, BINDING_SOAP) if not srvs: - raise NoServiceDefined("{}: {}".format(entity_id, "assertion_id_request_service")) + raise NoServiceDefined(f"{entity_id}: assertion_id_request_service") if isinstance(assertion_ids, str): assertion_ids = [assertion_ids] diff --git a/src/saml2/client_base.py b/src/saml2/client_base.py index 8b548c44..673dae75 100644 --- a/src/saml2/client_base.py +++ b/src/saml2/client_base.py @@ -220,7 +220,7 @@ class Base(Entity): # IdP in the configuration raise exception eids = self.metadata.with_descriptor("idpsso") if len(eids) > 1: - raise IdpUnspecified("Too many IdPs to choose from: %s" % eids) + raise IdpUnspecified(f"Too many IdPs to choose from: {eids}") try: srvs = self.metadata.single_sign_on_service(list(eids.keys())[0], binding) diff --git a/src/saml2/discovery.py b/src/saml2/discovery.py index d4be1ef3..2f777d01 100644 --- a/src/saml2/discovery.py +++ b/src/saml2/discovery.py @@ -52,7 +52,7 @@ class DiscoveryServer(Entity): is_passive = dsr.get("isPassive") if is_passive not in ["true", "false"]: - raise ValueError("Invalid value '{v}' for attribute '{attr}'".format(v=is_passive, attr="isPassive")) + raise ValueError(f"Invalid value '{is_passive}' for attribute 'isPassive'") if "isPassive" in dsr and dsr["isPassive"] == "true": dsr["isPassive"] = True diff --git a/src/saml2/ecp.py b/src/saml2/ecp.py index 4615fc49..5e1ad0b7 100644 --- a/src/saml2/ecp.py +++ b/src/saml2/ecp.py @@ -137,7 +137,7 @@ def handle_ecp_authn_response(cls, soap_message, outstanding=None): response = authn_response(cls.config, cls.service_urls(), outstanding, allow_unsolicited=True) - response.loads("%s" % rdict["body"], False, soap_message) + response.loads(f"{rdict['body']}", False, soap_message) response.verify() cls.users.add_information_about_person(response.session_info()) @@ -163,7 +163,7 @@ def ecp_response(target_url, response): soap_envelope = soapenv.Envelope(header=header, body=body) - return "%s" % soap_envelope + return f"{soap_envelope}" class ECPServer(Server): diff --git a/src/saml2/ecp_client.py b/src/saml2/ecp_client.py index ce1fca2c..fe051990 100644 --- a/src/saml2/ecp_client.py +++ b/src/saml2/ecp_client.py @@ -167,8 +167,8 @@ class Client(Entity): _acs_url = _ecp_response.assertion_consumer_service_url if rc_url != _acs_url: error = ( - "response_consumer_url '%s' does not match" % rc_url, - "assertion_consumer_service_url '%s" % _acs_url, + f"response_consumer_url '{rc_url}' does not match", + f"assertion_consumer_service_url '{_acs_url}", ) # Send an error message to the SP _ = self.send(rc_url, "POST", data=soap.soap_fault(error)) @@ -247,7 +247,7 @@ class Client(Entity): # url I started off with. pass else: - raise SAMLError("Error POSTing package to SP: %s" % response.text) + raise SAMLError(f"Error POSTing package to SP: {response.text}") logger.debug("[P3] SP response: %s", response.text) @@ -262,14 +262,14 @@ class Client(Entity): headers = set_list2dict(headers) headers["PAOS"] = PAOS_HEADER_INFO if "Accept" in headers: - headers["Accept"] += ";%s" % MIME_PAOS + headers["Accept"] += f";{MIME_PAOS}" elif "accept" in headers: headers["Accept"] = headers["accept"] - headers["Accept"] += ";%s" % MIME_PAOS + headers["Accept"] += f";{MIME_PAOS}" del headers["accept"] headers = dict2set_list(headers) else: - headers = [("Accept", "text/html; %s" % MIME_PAOS), ("PAOS", PAOS_HEADER_INFO)] + headers = [("Accept", f"text/html; {MIME_PAOS}"), ("PAOS", PAOS_HEADER_INFO)] return headers @@ -298,7 +298,7 @@ class Client(Entity): print(response.text) if response.status_code != 200: - raise SAMLError("Request to SP failed: %s" % response.text) + raise SAMLError(f"Request to SP failed: {response.text}") # The response might be a AuthnRequest instance in a SOAP envelope # body. If so it's the start of the ECP conversation diff --git a/src/saml2/entity.py b/src/saml2/entity.py index f826177e..9d0d2dcf 100644 --- a/src/saml2/entity.py +++ b/src/saml2/entity.py @@ -122,7 +122,7 @@ def create_artifact(entity_id, message_handle, endpoint_index=0): if not isinstance(message_handle, bytes): message_handle = message_handle.encode("utf-8") - ter = b"".join((ARTIFACT_TYPECODE, ("%.2x" % endpoint_index).encode("ascii"), sourceid.digest(), message_handle)) + ter = b"".join((ARTIFACT_TYPECODE, (f"{endpoint_index:02x}").encode("ascii"), sourceid.digest(), message_handle)) return base64.b64encode(ter).decode("ascii") @@ -160,7 +160,7 @@ class Entity(HTTPBase): tmp = make_temp(r.text, ".pem", False, self.config.delete_tmpfiles) setattr(self.config, item, tmp.name) else: - raise Exception("Could not fetch certificate from %s" % _val) + raise Exception(f"Could not fetch certificate from {_val}") HTTPBase.__init__( self, @@ -214,7 +214,7 @@ class Entity(HTTPBase): try: self.metadata.reload(metadata_conf) except Exception as ex: - logger.error("Loading metadata failed; reason: %s" % str(ex)) + logger.error(f"Loading metadata failed; reason: {str(ex)}") return False self.sourceid = self.metadata.construct_source_id() @@ -305,7 +305,7 @@ class Entity(HTTPBase): else: info = self.use_http_artifact(msg_str, destination, relay_state) else: - raise SAMLError("Unknown binding type: %s" % binding) + raise SAMLError(f"Unknown binding type: {binding}") return info @@ -327,8 +327,8 @@ class Entity(HTTPBase): else: descr_type = "spsso" - _url = getattr(request, "%s_url" % service, None) - _index = getattr(request, "%s_index" % service, None) + _url = getattr(request, f"{service}_url", None) + _index = getattr(request, f"{service}_index", None) for binding in bindings: try: @@ -438,7 +438,7 @@ class Entity(HTTPBase): BINDING_HTTP_ARTIFACT, None, ]: - raise UnknownBinding("Don't know how to handle '%s'" % binding) + raise UnknownBinding(f"Don't know how to handle '{binding}'") else: try: if binding == BINDING_HTTP_REDIRECT: @@ -446,14 +446,14 @@ class Entity(HTTPBase): elif binding == BINDING_HTTP_POST: xmlstr = base64.b64decode(txt) elif binding == BINDING_SOAP: - func = getattr(soap, "parse_soap_enveloped_saml_%s" % msgtype) + func = getattr(soap, f"parse_soap_enveloped_saml_{msgtype}") xmlstr = func(txt) elif binding == BINDING_HTTP_ARTIFACT: xmlstr = base64.b64decode(txt) else: xmlstr = txt except Exception: - raise UnravelError("Unravelling binding '%s' failed" % binding) + raise UnravelError(f"Unravelling binding '{binding}' failed") return xmlstr @@ -837,7 +837,7 @@ class Entity(HTTPBase): ) node_xpath = "".join( [ - '/*[local-name()="%s"]' % v + f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] ] ) @@ -1459,7 +1459,7 @@ class Entity(HTTPBase): logger.error("Unsolicited response") raise except Exception as err: - if "not well-formed" in "%s" % err: + if "not well-formed" in f"{err}": logger.error("Not well-formed XML") raise else: @@ -1579,11 +1579,7 @@ class Entity(HTTPBase): typecode = _art[:2] if typecode != ARTIFACT_TYPECODE: - raise ValueError( - "Invalid artifact typecode '{invalid}' should be {valid}".format( - invalid=typecode, valid=ARTIFACT_TYPECODE - ) - ) + raise ValueError(f"Invalid artifact typecode '{typecode}' should be {ARTIFACT_TYPECODE}") try: endpoint_index = str(int(_art[2:4])) @@ -1592,7 +1588,7 @@ class Entity(HTTPBase): entity = self.sourceid[_art[4:24]] destination = None - for desc in entity["%s_descriptor" % descriptor]: + for desc in entity[f"{descriptor}_descriptor"]: for srv in desc["artifact_resolution_service"]: if srv["index"] == endpoint_index: destination = srv["location"] diff --git a/src/saml2/httpbase.py b/src/saml2/httpbase.py index f183cf8e..11685d4f 100644 --- a/src/saml2/httpbase.py +++ b/src/saml2/httpbase.py @@ -134,7 +134,7 @@ class HTTPBase: # print(cookie) if cookie.expires and cookie.expires <= now: continue - if not re.search("%s$" % cookie.domain, _domain): + if not re.search(f"{cookie.domain}$", _domain): continue if not re.match(cookie.path, part.path): continue @@ -233,7 +233,7 @@ class HTTPBase: r = requests.request(method, url, **_kwargs) logger.debug("Response status: %s", r.status_code) except requests.ConnectionError as exc: - raise ConnectionError("%s" % exc) + raise ConnectionError(f"{exc}") try: self.set_cookie(SimpleCookie(r.headers["set-cookie"]), r) diff --git a/src/saml2/mdstore.py b/src/saml2/mdstore.py index 95ab0945..639c7a2d 100644 --- a/src/saml2/mdstore.py +++ b/src/saml2/mdstore.py @@ -426,14 +426,14 @@ class MetaData: Returns any entities with the specified descriptor """ res = {} - desc = "%s_descriptor" % descriptor + desc = f"{descriptor}_descriptor" for eid, ent in self.items(): if desc in ent: res[eid] = ent return res def __str__(self): - return "%s" % self.items() + return f"{self.items()}" def construct_source_id(self): raise NotImplementedError @@ -490,13 +490,13 @@ class MetaData: res = [] for descr in ["spsso", "idpsso", "role", "authn_authority", "attribute_authority", "pdp"]: try: - srvs = ent["%s_descriptor" % descr] + srvs = ent[f"{descr}_descriptor"] except KeyError: continue res.extend(extract_certs(srvs)) else: - srvs = ent["%s_descriptor" % descriptor] + srvs = ent[f"{descriptor}_descriptor"] res = extract_certs(srvs) return res @@ -552,7 +552,7 @@ class InMemoryMetaData(MetaData): # have I seen this entity_id before ? If so if log: ignore it if entity_descr.entity_id in self.entity: - print("Duplicated Entity descriptor (entity id: '%s')" % entity_descr.entity_id, file=sys.stderr) + print(f"Duplicated Entity descriptor (entity id: '{entity_descr.entity_id}')", file=sys.stderr) return _ent = to_dict(entity_descr, metadata_modules()) @@ -561,7 +561,7 @@ class InMemoryMetaData(MetaData): for descr in ["spsso", "idpsso", "role", "authn_authority", "attribute_authority", "pdp", "affiliation"]: _res = [] try: - _items = _ent["%s_descriptor" % descr] + _items = _ent[f"{descr}_descriptor"] except KeyError: continue @@ -576,7 +576,7 @@ class InMemoryMetaData(MetaData): _res.append(item) break if not _res: - del _ent["%s_descriptor" % descr] + del _ent[f"{descr}_descriptor"] else: flag += 1 @@ -1082,7 +1082,7 @@ class MetadataStore(MetaData): url = args[1] _md = MetaDataMDX(url, http_client_timeout=self.http_client_timeout) else: - raise SAMLError("Unknown metadata type '%s'" % typ) + raise SAMLError(f"Unknown metadata type '{typ}'") _md.load() self.metadata[key] = _md @@ -1115,13 +1115,13 @@ class MetadataStore(MetaData): try: key = item["class"] except (KeyError, AttributeError): - raise SAMLError("Misconfiguration in metadata %s" % item) + raise SAMLError(f"Misconfiguration in metadata {item}") mod, clas = key.rsplit(".", 1) try: mod = importlib.import_module(mod) MDloader = getattr(mod, clas) except (ImportError, AttributeError): - raise SAMLError("Unknown metadata loader %s" % key) + raise SAMLError(f"Unknown metadata loader {key}") # Separately handle MDExtern if MDloader == MetaDataExtern: @@ -1243,25 +1243,25 @@ class MetadataStore(MetaData): raise AttributeError("Missing type specification") if binding is None: binding = BINDING_SOAP - return self.service(entity_id, "%s_descriptor" % typ, "assertion_id_request_service", binding) + return self.service(entity_id, f"{typ}_descriptor", "assertion_id_request_service", binding) def single_logout_service(self, entity_id, binding=None, typ=None): # IDP + SP if typ is None: raise AttributeError("Missing type specification") - return self.service(entity_id, "%s_descriptor" % typ, "single_logout_service", binding) + return self.service(entity_id, f"{typ}_descriptor", "single_logout_service", binding) def manage_name_id_service(self, entity_id, binding=None, typ=None): # IDP + SP if binding is None: binding = BINDING_HTTP_REDIRECT - return self.service(entity_id, "%s_descriptor" % typ, "manage_name_id_service", binding) + return self.service(entity_id, f"{typ}_descriptor", "manage_name_id_service", binding) def artifact_resolution_service(self, entity_id, binding=None, typ=None): # IDP + SP if binding is None: binding = BINDING_HTTP_REDIRECT - return self.service(entity_id, "%s_descriptor" % typ, "artifact_resolution_service", binding) + return self.service(entity_id, f"{typ}_descriptor", "artifact_resolution_service", binding) def assertion_consumer_service(self, entity_id, binding=None, _="spsso"): # SP @@ -1699,7 +1699,7 @@ class MetadataStore(MetaData): except AttributeError: res.entity_descriptor.append(_md.entity_descr) - return "%s" % res + return f"{res}" elif format == "md": # self.items() returns dictitems(), convert that back into a dict return json.dumps(dict(self.items()), indent=2) diff --git a/src/saml2/metadata.py b/src/saml2/metadata.py index d87be05f..d7f19453 100644 --- a/src/saml2/metadata.py +++ b/src/saml2/metadata.py @@ -351,7 +351,7 @@ DEFAULT_BINDING = { def do_extensions(mname, item): try: - _mod = __import__("saml2.extension.%s" % mname, globals(), locals(), mname) + _mod = __import__(f"saml2.extension.{mname}", globals(), locals(), mname) except ImportError: return None else: @@ -567,7 +567,7 @@ def do_idpsso_descriptor(conf, cert=None, enc_cert=None): if val is None: setattr(idpsso, key, DEFAULT[key]) else: - setattr(idpsso, key, ("%s" % val).lower()) + setattr(idpsso, key, (f"{val}").lower()) except KeyError: setattr(idpsso, key, DEFAULTS[key]) @@ -771,7 +771,7 @@ def entities_descriptor(eds, valid_for, name, ident, sign, secc, sign_alg=None, entities.signature = pre_signature_part(ident, secc.my_cert, 1, sign_alg=sign_alg, digest_alg=digest_alg) entities.id = ident - xmldoc = secc.sign_statement("%s" % entities, class_name(entities)) + xmldoc = secc.sign_statement(f"{entities}", class_name(entities)) entities = md.entities_descriptor_from_string(xmldoc) else: xmldoc = None @@ -793,6 +793,6 @@ def sign_entity_descriptor(edesc, ident, secc, sign_alg=None, digest_alg=None): edesc.signature = pre_signature_part(ident, secc.my_cert, 1, sign_alg=sign_alg, digest_alg=digest_alg) edesc.id = ident - xmldoc = secc.sign_statement("%s" % edesc, class_name(edesc)) + xmldoc = secc.sign_statement(f"{edesc}", class_name(edesc)) edesc = md.entity_descriptor_from_string(xmldoc) return edesc, xmldoc diff --git a/src/saml2/mongo_store.py b/src/saml2/mongo_store.py index 23729237..f2fc0a6e 100644 --- a/src/saml2/mongo_store.py +++ b/src/saml2/mongo_store.py @@ -422,7 +422,7 @@ class MetadataMDB(InMemoryMetaData): elif len(res) == 1: return unprotect(res[0]["entity_description"]) else: - raise CorruptDatabase("More then one document with key %s" % item) + raise CorruptDatabase(f"More then one document with key {item}") def bindings(self, entity_id, typ, service): pass diff --git a/src/saml2/pack.py b/src/saml2/pack.py index 30b9cdf9..4a081ed1 100644 --- a/src/saml2/pack.py +++ b/src/saml2/pack.py @@ -177,7 +177,7 @@ def http_redirect_message( elif typ == "SAMLart": args = {typ: message} else: - raise Exception("Unknown message type: %s" % typ) + raise Exception(f"Unknown message type: {typ}") if relay_state: args["RelayState"] = relay_state @@ -297,7 +297,7 @@ def parse_soap_enveloped_saml(text, body_class, header_class=None): try: body = saml2.create_class_from_element_tree(body_class, sub) except Exception: - raise Exception("Wrong body type (%s) in SOAP envelope" % sub.tag) + raise Exception(f"Wrong body type ({sub.tag}) in SOAP envelope") elif part.tag == "{%s}Header" % NAMESPACE: if not header_class: raise Exception("Header where I didn't expect one") @@ -325,7 +325,7 @@ def packager(identifier): try: return PACKING[identifier] except KeyError: - raise Exception("Unknown binding type: %s" % identifier) + raise Exception(f"Unknown binding type: {identifier}") def factory(binding, message, location, relay_state="", typ="SAMLRequest", **kwargs): diff --git a/src/saml2/response.py b/src/saml2/response.py index 7d51ce6d..3b564c62 100644 --- a/src/saml2/response.py +++ b/src/saml2/response.py @@ -535,14 +535,14 @@ class AuthnResponse(StatusResponse): # del self.outstanding_queries[self.in_response_to] try: if not self.check_subject_confirmation_in_response_to(self.in_response_to): - raise UnsolicitedResponse("Unsolicited response: %s" % self.in_response_to) + raise UnsolicitedResponse(f"Unsolicited response: {self.in_response_to}") except AttributeError: pass elif self.allow_unsolicited: # Should check that I haven't seen this before pass else: - raise UnsolicitedResponse("Unsolicited response: %s" % self.in_response_to) + raise UnsolicitedResponse(f"Unsolicited response: {self.in_response_to}") return self @@ -609,7 +609,7 @@ class AuthnResponse(StatusResponse): if not for_me(conditions, self.entity_id): if not lax: - raise Exception("AudienceRestrictions conditions not satisfied! (Local entity_id=%s)" % self.entity_id) + raise Exception(f"AudienceRestrictions conditions not satisfied! (Local entity_id={self.entity_id})") if conditions.condition: # extra conditions for cond in conditions.condition: @@ -1000,7 +1000,7 @@ class AuthnResponse(StatusResponse): if self.context == "AuthnReq" or self.context == "AttrQuery": self.ava = self.get_identity() - logger.debug("--- AVA: %s" % self.ava) + logger.debug(f"--- AVA: {self.ava}") return True diff --git a/src/saml2/s2repoze/plugins/formswithhidden.py b/src/saml2/s2repoze/plugins/formswithhidden.py index 1483af92..8c120f07 100644 --- a/src/saml2/s2repoze/plugins/formswithhidden.py +++ b/src/saml2/s2repoze/plugins/formswithhidden.py @@ -92,7 +92,7 @@ class FormHiddenPlugin(FormPlugin): query = parse_dict_querystring(environ) hidden = [] for key, val in query.items(): - hidden.append(HIDDEN_PRE_LINE % ("_%s_" % key, val)) + hidden.append(HIDDEN_PRE_LINE % (f"_{key}_", val)) logger.info("hidden: %s", hidden) form = self.formbody or _DEFAULT_FORM diff --git a/src/saml2/s2repoze/plugins/sp.py b/src/saml2/s2repoze/plugins/sp.py index 9d107795..d71541ea 100644 --- a/src/saml2/s2repoze/plugins/sp.py +++ b/src/saml2/s2repoze/plugins/sp.py @@ -65,7 +65,7 @@ def construct_came_from(environ): def exception_trace(tag, exc, log): message = traceback.format_exception(*sys.exc_info()) - log.error("[{}] ExcList: {}".format(tag, "".join(message))) + log.error(f"[{tag}] ExcList: {''.join(message)}") log.error(f"[{tag}] Exception: {exc}") @@ -247,7 +247,7 @@ class SAML2Plugin: logger.debug("Redirect to Discovery Service function") eid = _cli.config.entityid ret = _cli.config.getattr("endpoints", "sp")["discovery_response"][0][0] - ret += "?sid=%s" % sid_ + ret += f"?sid={sid_}" loc = _cli.create_discovery_service_request(self.discosrv, eid, **{"return": ret}) return -1, SeeOther(loc) @@ -343,7 +343,7 @@ class SAML2Plugin: sign=False, extensions=extensions, ) - msg_str = "%s" % req + msg_str = f"{req}" _sid = req_id if cert is not None: @@ -359,8 +359,8 @@ class SAML2Plugin: logger.debug("ht_args: %s", ht_args) except Exception as exc: - logger.exception("Failed to construct the AuthnRequest: %s" % str(exc)) - raise Exception("Failed to construct the AuthnRequest: %s" % exc) + logger.exception(f"Failed to construct the AuthnRequest: {str(exc)}") + raise Exception(f"Failed to construct the AuthnRequest: {exc}") try: path_info = environ.get("PATH_INFO") diff --git a/src/saml2/s_utils.py b/src/saml2/s_utils.py index e8fadfa1..1284e3e9 100644 --- a/src/saml2/s_utils.py +++ b/src/saml2/s_utils.py @@ -318,7 +318,7 @@ def do_ava(val, typ=""): elif val is None: attrval = None else: - raise OtherError("strange value type on: %s" % val) + raise OtherError(f"strange value type on: {val}") if typ: for ava in attrval: @@ -417,9 +417,9 @@ def exception_trace(exc): message = traceback.format_exception(*sys.exc_info()) try: - _exc = "Exception: %s" % exc + _exc = f"Exception: {exc}" except UnicodeEncodeError: - _exc = "Exception: %s" % exc.message.encode("utf-8", "replace") + _exc = f"Exception: {exc.message.encode('utf-8', 'replace')}" return {"message": _exc, "content": "".join(message)} diff --git a/src/saml2/sigver.py b/src/saml2/sigver.py index cae27914..01a12a71 100644 --- a/src/saml2/sigver.py +++ b/src/saml2/sigver.py @@ -70,7 +70,7 @@ from saml2.xmlenc import EncryptionMethod logger = logging.getLogger(__name__) -SIG = "{{{ns}#}}{attribute}".format(ns=ds.NAMESPACE, attribute="Signature") +SIG = f"{{{ds.NAMESPACE}#}}Signature" # RSA_1_5 is considered deprecated RSA_1_5 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5" @@ -568,7 +568,7 @@ def verify_redirect_signature(saml_msg, crypto, cert=None, sigkey=None): try: signer = crypto.get_signer(saml_msg["SigAlg"], sigkey) except KeyError: - raise Unsupported("Signature algorithm: {alg}".format(alg=saml_msg["SigAlg"])) + raise Unsupported(f"Signature algorithm: {saml_msg['SigAlg']}") else: if saml_msg["SigAlg"] in SIGNER_ALGS: if "SAMLRequest" in saml_msg: @@ -846,9 +846,7 @@ class CryptoBackendXmlSec1(CryptoBackend): p_err = p_err.decode() if pof.returncode != 0: - errmsg = "returncode={code}\nerror={err}\noutput={out}".format( - code=pof.returncode, err=p_err, out=p_out - ) + errmsg = f"returncode={pof.returncode}\nerror={p_err}\noutput={p_out}" logger.error(errmsg) raise XmlsecError(errmsg) diff --git a/src/saml2/soap.py b/src/saml2/soap.py index 866bff14..14593afb 100644 --- a/src/saml2/soap.py +++ b/src/saml2/soap.py @@ -188,7 +188,7 @@ def class_instances_from_soap_enveloped_saml_thingies(text, modules): try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: - raise XmlParseError("%s" % exc) + raise XmlParseError(f"{exc}") envelope_tag = "{%s}Envelope" % soapenv.NAMESPACE if envelope.tag != envelope_tag: @@ -220,7 +220,7 @@ def open_soap_envelope(text): try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: - raise XmlParseError("%s" % exc) + raise XmlParseError(f"{exc}") envelope_tag = "{%s}Envelope" % soapenv.NAMESPACE if envelope.tag != envelope_tag: @@ -261,7 +261,7 @@ def make_soap_enveloped_saml_thingy(thingy, headers=None): soap_envelope.body = soapenv.Body() soap_envelope.body.add_extension_element(thingy) - return "%s" % soap_envelope + return f"{soap_envelope}" def soap_fault(message=None, actor=None, code=None, detail=None): @@ -291,4 +291,4 @@ def soap_fault(message=None, actor=None, code=None, detail=None): detail=_detail, ) - return "%s" % fault + return f"{fault}" diff --git a/src/saml2/tools/parse_xsd2.py b/src/saml2/tools/parse_xsd2.py index 432f25a7..49aa84fa 100644 --- a/src/saml2/tools/parse_xsd2.py +++ b/src/saml2/tools/parse_xsd2.py @@ -54,7 +54,7 @@ PROTECTED_KEYWORDS = ["import", "def", "if", "else", "return", "for", "while", " def def_init(imports, attributes): indent = INDENT + INDENT indent3 = INDENT + INDENT + INDENT - line = ["%sdef __init__(self," % INDENT] + line = [f"{INDENT}def __init__(self,"] for elem in attributes: if elem[0] in PROTECTED_KEYWORDS: @@ -75,10 +75,10 @@ def def_init(imports, attributes): _name = elem line.append(f"{indent3}{_name}=None,") - line.append("%stext=None," % indent3) - line.append("%sextension_elements=None," % indent3) - line.append("%sextension_attributes=None," % indent3) - line.append("%s):" % indent) + line.append(f"{indent3}text=None,") + line.append(f"{indent3}extension_elements=None,") + line.append(f"{indent3}extension_attributes=None,") + line.append(f"{indent}):") return line @@ -86,14 +86,14 @@ def base_init(imports): line = [] indent4 = INDENT + INDENT + INDENT + INDENT if not imports: - line.append("%sSamlBase.__init__(self, " % (INDENT + INDENT)) + line.append(f"{INDENT + INDENT}SamlBase.__init__(self, ") for attr in BASE_ELEMENT: if attr in PROTECTED_KEYWORDS: _name = attr + "_" else: _name = attr line.append(f"{indent4}{_name}={_name},") - line.append("%s)" % indent4) + line.append(f"{indent4})") else: # TODO have to keep apart which properties come from which superior for sup, elems in imports.items(): @@ -106,7 +106,7 @@ def base_init(imports): else: _name = attr line.append(f"{indent4}{_name}={_name},") - line.append("%s)" % indent4) + line.append(f"{indent4})") return line @@ -341,7 +341,7 @@ class PyObj: if not superior: line.append(f"class {c_name}(SamlBase):") else: - line.append("class {}({}):".format(c_name, ",".join(sups))) + line.append(f"class {c_name}({','.join(sups)}):") if hasattr(self, "scoped"): pass @@ -383,7 +383,7 @@ class PyObj: line.append("") if not self.abstract or not self.class_name.endswith("_"): - line.append("def %s_from_string(xml_string):" % pyify(self.class_name)) + line.append(f"def {pyify(self.class_name)}_from_string(xml_string):") line.append(f"{INDENT}return saml2.create_class_from_xml_string({self.class_name}, xml_string)") line.append("") @@ -800,12 +800,12 @@ def _spec(elem): name = elem.name except AttributeError: name = "anonymous" - txt = "%s" % name + txt = f"{name}" try: - txt += " ref: %s" % elem.ref + txt += f" ref: {elem.ref}" except AttributeError: try: - txt += " type: %s" % elem.type + txt += f" type: {elem.type}" except AttributeError: pass @@ -825,7 +825,7 @@ def _spec(elem): def _do_from_string(name): print - print("def %s_from_string(xml_string):" % pyify(name)) + print(f"def {pyify(name)}_from_string(xml_string):") print(f"{INDENT}return saml2.create_class_from_xml_string({name}, xml_string)") @@ -917,7 +917,7 @@ class Attribute(Simple): name = self.ref pyname = pyify(name) else: # referering to what - raise Exception("Strange reference: %s" % self.ref) + raise Exception(f"Strange reference: {self.ref}") objekt = PyAttribute(name, pyname, external=external, root=top) @@ -1085,7 +1085,7 @@ class Complex: if DEBUG: print(self.__dict__) - print("#-- %d parts" % len(self.parts)) + print(f"#-- {len(self.parts)} parts") self._extend(top, sup, argv, parent) @@ -1307,7 +1307,7 @@ class Sequence(Complex): argv_copy[key] = val if DEBUG: - print("#Sequence: %s" % argv) + print(f"#Sequence: {argv}") return Complex.collect(self, top, sup, argv_copy, parent) @@ -1371,7 +1371,7 @@ class Choice(Complex): argv_copy["minOccurs"] = 0 if DEBUG: - print("#Choice: %s" % argv) + print(f"#Choice: {argv}") return Complex.collect(self, top, sup, argv_copy, parent=parent) @@ -1664,16 +1664,15 @@ def output(elem, target_namespace, eldict, ignore=None): def intro(): print( - """#!/usr/bin/env python + f"""#!/usr/bin/env python # -# Generated %s by parse_xsd.py version %s. +# Generated {time.ctime()} by parse_xsd.py version {__version__}. # import saml2 from saml2 import SamlBase """ - % (time.ctime(), __version__) ) @@ -1887,12 +1886,12 @@ class Schema(Complex): intro() for modul in self.add: - print("from %s import *" % modul) + print(f"from {modul} import *") for _namespace, (mod, namn) in self.impo.items(): if namn: print(f"import {mod} as {namn}") print() - print("NAMESPACE = '%s'" % self.target_namespace) + print(f"NAMESPACE = '{self.target_namespace}'") print for defs in self.defs: @@ -1923,7 +1922,7 @@ class Schema(Complex): print for attrgrp in self.attrgrp: - print("AG_%s = [" % attrgrp.name) + print(f"AG_{attrgrp.name} = [") for prop in attrgrp.properties[0]: if isinstance(prop.type, PyObj): print(f"{INDENT}('{prop.name}', {prop.type.name}_, {prop.required}),") @@ -2110,7 +2109,7 @@ def read_schema(doc, add, defs, impo, modul, ignore, sdir): elif namespace in ignore: continue else: - raise Exception("Undefined namespace: %s" % namespace) + raise Exception(f"Undefined namespace: {namespace}") _schema = Schema(tree._root, impo, add, modul, defs) _included_parts = [] @@ -2175,7 +2174,7 @@ def main(): elif opt in ("-I", "--ignore"): ignore.append(arg) else: - raise Exception("unhandled option %s" % opt) + raise Exception(f"unhandled option {opt}") if not args: print("No XSD-file specified") diff --git a/src/saml2/tools/sync_attrmaps.py b/src/saml2/tools/sync_attrmaps.py index f20e2d6c..1a3743de 100644 --- a/src/saml2/tools/sync_attrmaps.py +++ b/src/saml2/tools/sync_attrmaps.py @@ -59,14 +59,14 @@ class AMap: try: assert self.mod.MAP["to"][val] == key except KeyError: # missing value - print("# Added {}={}".format(self.mod.MAP["to"][val], key)) + print(f"# Added {self.mod.MAP['to'][val]}={key}") self.mod.MAP["to"][val] = key except AssertionError: - raise Exception("Mismatch key:{} '{}' != '{}'".format(key, val, self.mod.MAP["to"][val])) + raise Exception(f"Mismatch key:{key} '{val}' != '{self.mod.MAP['to'][val]}'") for val in self.mod.MAP["to"].values(): if val not in self.mod.MAP["fro"]: - print("# Missing URN '%s'" % val) + print(f"# Missing URN '{val}'") def do_fro(self): txt = ["%s'fro': {" % self.indent] @@ -107,7 +107,7 @@ class AMap: text.extend(["", ""]) text.append("MAP = {") - text.append("{}'identifier': '{}',".format(self.indent, self.mod.MAP["identifier"])) + text.append(f"{self.indent}'identifier': '{self.mod.MAP['identifier']}',") text.extend(self.do_fro()) text.extend(self.do_to()) @@ -122,7 +122,7 @@ if __name__ == "__main__": directory, fname = os.path.split(_name) amap = AMap(directory, fname, 4 * " ") f = open(_name, "w") - f.write("%s" % amap) + f.write(f"{amap}") f.close() elif os.path.isdir(_name): for fname in os.listdir(_name): @@ -133,5 +133,5 @@ if __name__ == "__main__": print(10 * "=" + fname + 10 * "=") amap = AMap(_name, fname, 4 * " ") f = open(fname, "w") - f.write("%s" % amap) + f.write(f"{amap}") f.close() diff --git a/src/saml2/validate.py b/src/saml2/validate.py index 33083886..ae66504b 100644 --- a/src/saml2/validate.py +++ b/src/saml2/validate.py @@ -359,7 +359,7 @@ def valid_instance(instance): for (name, typ, required) in instclass.c_attributes.values(): value = getattr(instance, name, "") if required and not value: - txt = "Required value on property '%s' missing" % name + txt = f"Required value on property '{name}' missing" raise MustValueError(f"Class '{class_name}' instance: {txt}") if value: @@ -404,13 +404,9 @@ def valid_instance(instance): if _card: if _cmin is not None and _cmin > vlen: - raise NotValid( - "Class '%s' instance cardinality error: %s" % (class_name, f"less then min ({vlen}<{_cmin})") - ) + raise NotValid(f"Class '{class_name}' instance cardinality error: less then min ({vlen}<{_cmin})") if _cmax is not None and vlen > _cmax: - raise NotValid( - "Class '%s' instance cardinality error: %s" % (class_name, f"more then max ({vlen}>{_cmax})") - ) + raise NotValid(f"Class '{class_name}' instance cardinality error: more then max ({vlen}>{_cmax})") if _list: for val in value: @@ -420,9 +416,7 @@ def valid_instance(instance): _valid_instance(instance, value) else: if _cmin: - raise NotValid( - "Class '{}' instance cardinality error: {}".format(class_name, "too few values on %s" % name) - ) + raise NotValid(f"Class '{class_name}' instance cardinality error: too few values on {name}") return True diff --git a/src/saml2test/__init__.py b/src/saml2test/__init__.py index 81eace7f..e4f1d6bf 100644 --- a/src/saml2test/__init__.py +++ b/src/saml2test/__init__.py @@ -88,9 +88,9 @@ def exception_trace(tag, exc, log=None): message = traceback.format_exception(*sys.exc_info()) try: - _exc = "Exception: %s" % exc + _exc = f"Exception: {exc}" except UnicodeEncodeError: - _exc = "Exception: %s" % exc.message.encode("utf-8", "replace") + _exc = f"Exception: {exc.message.encode('utf-8', 'replace')}" return {"status": CRITICAL, "message": _exc, "content": "".join(message)} diff --git a/src/saml2test/check.py b/src/saml2test/check.py index 47ea170c..158397fb 100644 --- a/src/saml2test/check.py +++ b/src/saml2test/check.py @@ -164,7 +164,7 @@ class VerifyError(Error): try: assert item["error"] in self._kwargs["error"] except AssertionError: - self._message = "Wrong type of error, got %s" % item["error"] + self._message = f"Wrong type of error, got {item['error']}" self._status = self.status return {} diff --git a/src/saml2test/opfunc.py b/src/saml2test/opfunc.py index 78096c2e..51b01b0c 100644 --- a/src/saml2test/opfunc.py +++ b/src/saml2test/opfunc.py @@ -212,9 +212,7 @@ def do_click(client, form, **kwargs): else: _nr += 1 except ControlNotFoundError: - raise Exception( - "No submit control with the name='%s' and " "value='%s' could be found" % (_name, _val) - ) + raise Exception(f"No submit control with the name='{_name}' and value='{_val}' could be found") else: request = form.click() diff --git a/src/saml2test/tool.py b/src/saml2test/tool.py index b0bbf66c..fa600955 100644 --- a/src/saml2test/tool.py +++ b/src/saml2test/tool.py @@ -87,7 +87,7 @@ class Conversation: chk = self.check_factory(test)() chk(self, self.test_output) if bryt: - e = FatalError("%s" % err) + e = FatalError(f"{err}") e.trace = "".join(traceback.format_exception(*sys.exc_info())) raise e @@ -125,7 +125,7 @@ class Conversation: else: rdseq.append(url) if len(rdseq) > 8: - raise FatalError("Too long sequence of redirects: %s" % rdseq) + raise FatalError(f"Too long sequence of redirects: {rdseq}") logger.info("HTTP %d Location: %s", _response.status_code, url) # If back to me @@ -153,7 +153,7 @@ class Conversation: logger.info("GET %s", url) _response = self.client.send(url, "GET") except Exception as err: - raise FatalError("%s" % err) + raise FatalError(f"{err}") content = _response.text logger.info("<-- CONTENT: %s", content) diff --git a/tests/_test_80_p11_backend.py b/tests/_test_80_p11_backend.py index 07af1f47..475eeb83 100644 --- a/tests/_test_80_p11_backend.py +++ b/tests/_test_80_p11_backend.py @@ -59,7 +59,7 @@ class FakeConfig: self.only_use_keys_in_metadata = False self.metadata = None self.cert_file = pub_key - self.key_file = "pkcs11://%s:0/test?pin=secret1" % P11_MODULE + self.key_file = f"pkcs11://{P11_MODULE}:0/test?pin=secret1" self.debug = False self.cert_handler_extra_class = None self.generate_cert_info = False @@ -92,7 +92,7 @@ class TestPKCS11: logging.debug("Generating softhsm.conf") with open(self.softhsm_conf, "w") as f: - f.write("#Generated by pysaml2 cryptobackend test\n0:%s\n" % self.softhsm_db) + f.write(f"#Generated by pysaml2 cryptobackend test\n0:{self.softhsm_db}\n") logging.debug("Initializing the token") self._p( ["softhsm", "--slot", "0", "--label", "test", "--init-token", "--pin", "secret1", "--so-pin", "secret2"] @@ -168,7 +168,7 @@ class TestPKCS11: print("-" * 64) traceback.print_exc() print("-" * 64) - logging.warning("PKCS11 tests disabled: unable to initialize test token: %s" % ex) + logging.warning(f"PKCS11 tests disabled: unable to initialize test token: {ex}") raise def teardown_class(self): @@ -212,7 +212,7 @@ class TestPKCS11: ass = self._assertion print(ass) - sign_ass = self.sec.sign_assertion("%s" % ass, node_id=ass.id) + sign_ass = self.sec.sign_assertion(f"{ass}", node_id=ass.id) # print(sign_ass) sass = saml.assertion_from_string(sign_ass) # print(sass) @@ -221,7 +221,7 @@ class TestPKCS11: assert sass.id == "11111" assert time_util.str_to_time(sass.issue_instant) - print("Crypto version : %s" % (self.sec.crypto.version())) + print(f"Crypto version : {self.sec.crypto.version()}") item = self.sec.check_signature(sass, class_name(sass), sign_ass) diff --git a/tests/disco_conf.py b/tests/disco_conf.py index 0eafa707..cb119758 100644 --- a/tests/disco_conf.py +++ b/tests/disco_conf.py @@ -7,13 +7,13 @@ from saml2.extension.idpdisc import BINDING_DISCO BASE = "http://localhost:8088" CONFIG = { - "entityid": "%s/disco.xml" % BASE, + "entityid": f"{BASE}/disco.xml", "name": "Rolands Discoserver", "service": { "ds": { "endpoints": { "disco_service": [ - ("%s/disco" % BASE, BINDING_DISCO), + (f"{BASE}/disco", BINDING_DISCO), ] }, }, diff --git a/tests/fakeIDP.py b/tests/fakeIDP.py index a126f89b..00dda20e 100644 --- a/tests/fakeIDP.py +++ b/tests/fakeIDP.py @@ -22,7 +22,7 @@ AUTHN = {"class_ref": INTERNETPROTOCOLPASSWORD, "authn_auth": "http://www.exampl def unpack_form(_str, ver="SAMLRequest"): - SR_STR = 'name="%s" value="' % ver + SR_STR = f'name="{ver}" value="' RS_STR = 'name="RelayState" value="' i = _str.find(SR_STR) @@ -118,7 +118,7 @@ class FakeIDP(Server): authn_resp = self.create_authn_response(identity, userid=userid, authn=AUTHN, **resp_args) - response = "%s" % authn_resp + response = f"{authn_resp}" _dict = pack.factory(_binding, response, resp_args["destination"], relay_state, "SAMLResponse") return DummyResponse(**_dict) @@ -147,9 +147,9 @@ class FakeIDP(Server): # class_name(attr_resp), # nodeid=attr_resp.id) # soap_message = _signed - response = "%s" % soap_message + response = f"{soap_message}" else: # Just POST - response = "%s" % attr_resp + response = f"{attr_resp}" return DummyResponse(status=200, data=response) @@ -172,8 +172,8 @@ class FakeIDP(Server): # class_name(attr_resp), # nodeid=attr_resp.id) # soap_message = _signed - response = "%s" % soap_message + response = f"{soap_message}" else: # Just POST - response = "%s" % _resp + response = f"{_resp}" return DummyResponse(status=200, data=response) diff --git a/tests/idp_all_conf.py b/tests/idp_all_conf.py index 0a99b85d..b880b9eb 100644 --- a/tests/idp_all_conf.py +++ b/tests/idp_all_conf.py @@ -17,37 +17,37 @@ CONFIG = { "name": "Rolands IdP", "service": { "aa": { - "endpoints": {"attribute_service": [("%s/aap" % BASE, BINDING_HTTP_POST), ("%s/aas" % BASE, BINDING_SOAP)]}, + "endpoints": {"attribute_service": [(f"{BASE}/aap", BINDING_HTTP_POST), (f"{BASE}/aas", BINDING_SOAP)]}, }, "aq": { - "endpoints": {"authn_query_service": [("%s/aqs" % BASE, BINDING_SOAP)]}, + "endpoints": {"authn_query_service": [(f"{BASE}/aqs", BINDING_SOAP)]}, }, "idp": { "endpoints": { "single_sign_on_service": [ - ("%s/sso/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/sso/post" % BASE, BINDING_HTTP_POST), - ("%s/sso/art" % BASE, BINDING_HTTP_ARTIFACT), - ("%s/sso/paos" % BASE, BINDING_SOAP), + (f"{BASE}/sso/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/sso/post", BINDING_HTTP_POST), + (f"{BASE}/sso/art", BINDING_HTTP_ARTIFACT), + (f"{BASE}/sso/paos", BINDING_SOAP), ], "single_logout_service": [ - ("%s/slo/soap" % BASE, BINDING_SOAP), - ("%s/slo/post" % BASE, BINDING_HTTP_POST), + (f"{BASE}/slo/soap", BINDING_SOAP), + (f"{BASE}/slo/post", BINDING_HTTP_POST), ], - "artifact_resolution_service": [("%s/ars" % BASE, BINDING_SOAP)], - "assertion_id_request_service": [("%s/airs" % BASE, BINDING_URI)], - "authn_query_service": [("%s/aqs" % BASE, BINDING_SOAP)], + "artifact_resolution_service": [(f"{BASE}/ars", BINDING_SOAP)], + "assertion_id_request_service": [(f"{BASE}/airs", BINDING_URI)], + "authn_query_service": [(f"{BASE}/aqs", BINDING_SOAP)], "manage_name_id_service": [ - ("%s/mni/soap" % BASE, BINDING_SOAP), - ("%s/mni/post" % BASE, BINDING_HTTP_POST), - ("%s/mni/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/mni/art" % BASE, BINDING_HTTP_ARTIFACT), + (f"{BASE}/mni/soap", BINDING_SOAP), + (f"{BASE}/mni/post", BINDING_HTTP_POST), + (f"{BASE}/mni/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/mni/art", BINDING_HTTP_ARTIFACT), ], "name_id_mapping_service": [ - ("%s/nim/soap" % BASE, BINDING_SOAP), - ("%s/nim/post" % BASE, BINDING_HTTP_POST), - ("%s/nim/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/nim/art" % BASE, BINDING_HTTP_ARTIFACT), + (f"{BASE}/nim/soap", BINDING_SOAP), + (f"{BASE}/nim/post", BINDING_HTTP_POST), + (f"{BASE}/nim/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/nim/art", BINDING_HTTP_ARTIFACT), ], }, "policy": { diff --git a/tests/idp_conf.py b/tests/idp_conf.py index 9411554d..4f76aba0 100644 --- a/tests/idp_conf.py +++ b/tests/idp_conf.py @@ -17,8 +17,8 @@ CONFIG = { "service": { "idp": { "endpoints": { - "single_sign_on_service": [("%s/sso" % BASE, BINDING_HTTP_REDIRECT)], - "single_logout_service": [("%s/slo" % BASE, BINDING_SOAP), ("%s/slop" % BASE, BINDING_HTTP_POST)], + "single_sign_on_service": [(f"{BASE}/sso", BINDING_HTTP_REDIRECT)], + "single_logout_service": [(f"{BASE}/slo", BINDING_SOAP), (f"{BASE}/slop", BINDING_HTTP_POST)], }, "policy": { "default": { diff --git a/tests/idp_conf_ec.py b/tests/idp_conf_ec.py index 601b8b0b..eef4d2c9 100644 --- a/tests/idp_conf_ec.py +++ b/tests/idp_conf_ec.py @@ -17,8 +17,8 @@ CONFIG = { "service": { "idp": { "endpoints": { - "single_sign_on_service": [("%s/sso" % BASE, BINDING_HTTP_REDIRECT)], - "single_logout_service": [("%s/slo" % BASE, BINDING_SOAP), ("%s/slop" % BASE, BINDING_HTTP_POST)], + "single_sign_on_service": [(f"{BASE}/sso", BINDING_HTTP_REDIRECT)], + "single_logout_service": [(f"{BASE}/slo", BINDING_SOAP), (f"{BASE}/slop", BINDING_HTTP_POST)], }, "policy": { "default": { diff --git a/tests/idp_conf_mdb.py b/tests/idp_conf_mdb.py index e6b94527..fb5d325d 100644 --- a/tests/idp_conf_mdb.py +++ b/tests/idp_conf_mdb.py @@ -13,41 +13,41 @@ from saml2.saml import NAMEID_FORMAT_PERSISTENT BASE = "http://localhost:8088" CONFIG = { - "entityid": "%s/saml/idp" % BASE, + "entityid": f"{BASE}/saml/idp", "name": "Rolands IdP", "service": { "aa": { - "endpoints": {"attribute_service": [("%s/aap" % BASE, BINDING_HTTP_POST), ("%s/aas" % BASE, BINDING_SOAP)]}, + "endpoints": {"attribute_service": [(f"{BASE}/aap", BINDING_HTTP_POST), (f"{BASE}/aas", BINDING_SOAP)]}, }, "aq": { - "endpoints": {"authn_query_service": [("%s/aqs" % BASE, BINDING_SOAP)]}, + "endpoints": {"authn_query_service": [(f"{BASE}/aqs", BINDING_SOAP)]}, }, "idp": { "endpoints": { "single_sign_on_service": [ - ("%s/sso/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/sso/post" % BASE, BINDING_HTTP_POST), - ("%s/sso/art" % BASE, BINDING_HTTP_ARTIFACT), - ("%s/sso/paos" % BASE, BINDING_SOAP), + (f"{BASE}/sso/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/sso/post", BINDING_HTTP_POST), + (f"{BASE}/sso/art", BINDING_HTTP_ARTIFACT), + (f"{BASE}/sso/paos", BINDING_SOAP), ], "single_logout_service": [ - ("%s/slo/soap" % BASE, BINDING_SOAP), - ("%s/slo/post" % BASE, BINDING_HTTP_POST), + (f"{BASE}/slo/soap", BINDING_SOAP), + (f"{BASE}/slo/post", BINDING_HTTP_POST), ], - "artifact_resolution_service": [("%s/ars" % BASE, BINDING_SOAP)], - "assertion_id_request_service": [("%s/airs" % BASE, BINDING_URI)], - "authn_query_service": [("%s/aqs" % BASE, BINDING_SOAP)], + "artifact_resolution_service": [(f"{BASE}/ars", BINDING_SOAP)], + "assertion_id_request_service": [(f"{BASE}/airs", BINDING_URI)], + "authn_query_service": [(f"{BASE}/aqs", BINDING_SOAP)], "manage_name_id_service": [ - ("%s/mni/soap" % BASE, BINDING_SOAP), - ("%s/mni/post" % BASE, BINDING_HTTP_POST), - ("%s/mni/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/mni/art" % BASE, BINDING_HTTP_ARTIFACT), + (f"{BASE}/mni/soap", BINDING_SOAP), + (f"{BASE}/mni/post", BINDING_HTTP_POST), + (f"{BASE}/mni/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/mni/art", BINDING_HTTP_ARTIFACT), ], "name_id_mapping_service": [ - ("%s/nim/soap" % BASE, BINDING_SOAP), - ("%s/nim/post" % BASE, BINDING_HTTP_POST), - ("%s/nim/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/nim/art" % BASE, BINDING_HTTP_ARTIFACT), + (f"{BASE}/nim/soap", BINDING_SOAP), + (f"{BASE}/nim/post", BINDING_HTTP_POST), + (f"{BASE}/nim/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/nim/art", BINDING_HTTP_ARTIFACT), ], }, "policy": { diff --git a/tests/idp_conf_mdb2.py b/tests/idp_conf_mdb2.py index de8e50ca..3a4b9e7d 100644 --- a/tests/idp_conf_mdb2.py +++ b/tests/idp_conf_mdb2.py @@ -13,41 +13,41 @@ from saml2.saml import NAMEID_FORMAT_PERSISTENT BASE = "http://localhost:8089" CONFIG = { - "entityid": "%s/saml/idp2" % BASE, + "entityid": f"{BASE}/saml/idp2", "name": "Rolands 2nd IdP", "service": { "aa": { - "endpoints": {"attribute_service": [("%s/aap" % BASE, BINDING_HTTP_POST), ("%s/aas" % BASE, BINDING_SOAP)]}, + "endpoints": {"attribute_service": [(f"{BASE}/aap", BINDING_HTTP_POST), (f"{BASE}/aas", BINDING_SOAP)]}, }, "aq": { - "endpoints": {"authn_query_service": [("%s/aqs" % BASE, BINDING_SOAP)]}, + "endpoints": {"authn_query_service": [(f"{BASE}/aqs", BINDING_SOAP)]}, }, "idp": { "endpoints": { "single_sign_on_service": [ - ("%s/sso/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/sso/post" % BASE, BINDING_HTTP_POST), - ("%s/sso/art" % BASE, BINDING_HTTP_ARTIFACT), - ("%s/sso/paos" % BASE, BINDING_SOAP), + (f"{BASE}/sso/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/sso/post", BINDING_HTTP_POST), + (f"{BASE}/sso/art", BINDING_HTTP_ARTIFACT), + (f"{BASE}/sso/paos", BINDING_SOAP), ], "single_logout_service": [ - ("%s/slo/soap" % BASE, BINDING_SOAP), - ("%s/slo/post" % BASE, BINDING_HTTP_POST), + (f"{BASE}/slo/soap", BINDING_SOAP), + (f"{BASE}/slo/post", BINDING_HTTP_POST), ], - "artifact_resolution_service": [("%s/ars" % BASE, BINDING_SOAP)], - "assertion_id_request_service": [("%s/airs" % BASE, BINDING_URI)], - "authn_query_service": [("%s/aqs" % BASE, BINDING_SOAP)], + "artifact_resolution_service": [(f"{BASE}/ars", BINDING_SOAP)], + "assertion_id_request_service": [(f"{BASE}/airs", BINDING_URI)], + "authn_query_service": [(f"{BASE}/aqs", BINDING_SOAP)], "manage_name_id_service": [ - ("%s/mni/soap" % BASE, BINDING_SOAP), - ("%s/mni/post" % BASE, BINDING_HTTP_POST), - ("%s/mni/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/mni/art" % BASE, BINDING_HTTP_ARTIFACT), + (f"{BASE}/mni/soap", BINDING_SOAP), + (f"{BASE}/mni/post", BINDING_HTTP_POST), + (f"{BASE}/mni/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/mni/art", BINDING_HTTP_ARTIFACT), ], "name_id_mapping_service": [ - ("%s/nim/soap" % BASE, BINDING_SOAP), - ("%s/nim/post" % BASE, BINDING_HTTP_POST), - ("%s/nim/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/nim/art" % BASE, BINDING_HTTP_ARTIFACT), + (f"{BASE}/nim/soap", BINDING_SOAP), + (f"{BASE}/nim/post", BINDING_HTTP_POST), + (f"{BASE}/nim/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/nim/art", BINDING_HTTP_ARTIFACT), ], }, "policy": { diff --git a/tests/idp_conf_sp_no_encrypt.py b/tests/idp_conf_sp_no_encrypt.py index 614b1a3e..b47e4efe 100644 --- a/tests/idp_conf_sp_no_encrypt.py +++ b/tests/idp_conf_sp_no_encrypt.py @@ -16,8 +16,8 @@ CONFIG = { "service": { "idp": { "endpoints": { - "single_sign_on_service": [("%s/sso" % BASE, BINDING_HTTP_REDIRECT)], - "single_logout_service": [("%s/slo" % BASE, BINDING_SOAP), ("%s/slop" % BASE, BINDING_HTTP_POST)], + "single_sign_on_service": [(f"{BASE}/sso", BINDING_HTTP_REDIRECT)], + "single_logout_service": [(f"{BASE}/slo", BINDING_SOAP), (f"{BASE}/slop", BINDING_HTTP_POST)], }, "policy": { "default": { diff --git a/tests/idp_conf_verify_cert.py b/tests/idp_conf_verify_cert.py index 1536385a..e6c52299 100644 --- a/tests/idp_conf_verify_cert.py +++ b/tests/idp_conf_verify_cert.py @@ -27,8 +27,8 @@ CONFIG = { "verify_encrypt_cert_advice": verify_encrypt_cert, "verify_encrypt_cert_assertion": verify_encrypt_cert, "endpoints": { - "single_sign_on_service": [("%s/sso" % BASE, BINDING_HTTP_REDIRECT)], - "single_logout_service": [("%s/slo" % BASE, BINDING_SOAP), ("%s/slop" % BASE, BINDING_HTTP_POST)], + "single_sign_on_service": [(f"{BASE}/sso", BINDING_HTTP_REDIRECT)], + "single_logout_service": [(f"{BASE}/slo", BINDING_SOAP), (f"{BASE}/slop", BINDING_HTTP_POST)], }, "policy": { "default": { diff --git a/tests/idp_test/target_idp.py b/tests/idp_test/target_idp.py index 7028eb4d..bafb538d 100755 --- a/tests/idp_test/target_idp.py +++ b/tests/idp_test/target_idp.py @@ -15,20 +15,20 @@ BASE = "http://localhost:8088" metadata = open("./idp/idp.xml").read() info = { - "entity_id": "%s/idp.xml" % BASE, + "entity_id": f"{BASE}/idp.xml", "interaction": [ { - "matches": {"url": "%s/sso/redirect" % BASE, "title": "IDP test login"}, + "matches": {"url": f"{BASE}/sso/redirect", "title": "IDP test login"}, "page-type": "login", "control": {"type": "form", "set": {"login": "roland", "password": "dianakra"}}, }, { - "matches": {"url": "%s/sso/post" % BASE, "title": "IDP test login"}, + "matches": {"url": f"{BASE}/sso/post", "title": "IDP test login"}, "page-type": "login", "control": {"type": "form", "set": {"login": "roland", "password": "dianakra"}}, }, { - "matches": {"url": "%s/sso/redirect" % BASE, "title": "SAML 2.0 POST"}, + "matches": {"url": f"{BASE}/sso/redirect", "title": "SAML 2.0 POST"}, "page-type": "other", "control": { "index": 0, @@ -36,12 +36,12 @@ info = { }, }, { - "matches": {"url": "%s/sso/post" % BASE, "title": "SAML 2.0 POST"}, + "matches": {"url": f"{BASE}/sso/post", "title": "SAML 2.0 POST"}, "page-type": "other", "control": {"index": 0, "type": "form", "set": {}}, }, { - "matches": {"url": "%s/slo/post" % BASE, "title": "SAML 2.0 POST"}, + "matches": {"url": f"{BASE}/slo/post", "title": "SAML 2.0 POST"}, "page-type": "other", "control": {"index": 0, "type": "form", "set": {}}, }, diff --git a/tests/localhost.py b/tests/localhost.py index 1e715b8b..762bd5b3 100755 --- a/tests/localhost.py +++ b/tests/localhost.py @@ -12,25 +12,25 @@ BASE = "http://localhost:8088" metadata = open("idp_test/idp.xml").read() info = { - "entity_id": "%s/idp.xml" % BASE, + "entity_id": f"{BASE}/idp.xml", "interaction": [ { - "matches": {"url": "%s/login" % BASE, "title": "IDP test login"}, + "matches": {"url": f"{BASE}/login", "title": "IDP test login"}, "page-type": "login", "control": {"type": "form", "set": {"login": "roland", "password": "dianakra"}}, }, { - "matches": {"url": "%s/sso/redirect" % BASE, "title": "SAML 2.0 POST"}, + "matches": {"url": f"{BASE}/sso/redirect", "title": "SAML 2.0 POST"}, "page-type": "other", "control": {"index": 0, "type": "form", "set": {}}, }, { - "matches": {"url": "%s/sso/post" % BASE, "title": "SAML 2.0 POST"}, + "matches": {"url": f"{BASE}/sso/post", "title": "SAML 2.0 POST"}, "page-type": "other", "control": {"index": 0, "type": "form", "set": {}}, }, { - "matches": {"url": "%s/slo/post" % BASE, "title": "SAML 2.0 POST"}, + "matches": {"url": f"{BASE}/slo/post", "title": "SAML 2.0 POST"}, "page-type": "other", "control": {"index": 0, "type": "form", "set": {}}, }, diff --git a/tests/servera_conf.py b/tests/servera_conf.py index b7fb487d..7277568c 100644 --- a/tests/servera_conf.py +++ b/tests/servera_conf.py @@ -23,19 +23,19 @@ CONFIG = { "sp": { "endpoints": { "assertion_consumer_service": [ - ("%s/" % BASE, BINDING_HTTP_POST), - ("%s/paos" % BASE, BINDING_PAOS), - ("%s/redirect" % BASE, BINDING_HTTP_REDIRECT), + (f"{BASE}/", BINDING_HTTP_POST), + (f"{BASE}/paos", BINDING_PAOS), + (f"{BASE}/redirect", BINDING_HTTP_REDIRECT), ], - "artifact_resolution_service": [("%s/ars" % BASE, BINDING_SOAP)], + "artifact_resolution_service": [(f"{BASE}/ars", BINDING_SOAP)], "manage_name_id_service": [ - ("%s/mni/soap" % BASE, BINDING_SOAP), - ("%s/mni/post" % BASE, BINDING_HTTP_POST), - ("%s/mni/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/mni/art" % BASE, BINDING_HTTP_ARTIFACT), + (f"{BASE}/mni/soap", BINDING_SOAP), + (f"{BASE}/mni/post", BINDING_HTTP_POST), + (f"{BASE}/mni/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/mni/art", BINDING_HTTP_ARTIFACT), ], - "single_logout_service": [("%s/sls" % BASE, BINDING_SOAP)], - "discovery_response": [("%s/disco" % BASE, BINDING_DISCO)], + "single_logout_service": [(f"{BASE}/sls", BINDING_SOAP)], + "discovery_response": [(f"{BASE}/disco", BINDING_DISCO)], }, "required_attributes": ["surName", "givenName", "mail"], "optional_attributes": ["title", "eduPersonAffiliation"], diff --git a/tests/sp_test/config.py b/tests/sp_test/config.py index 7e23d0c7..d7ad0e41 100644 --- a/tests/sp_test/config.py +++ b/tests/sp_test/config.py @@ -22,24 +22,24 @@ else: BASE = "http://localhost:8088" CONFIG = { - "entityid": "%s/idp.xml" % BASE, + "entityid": f"{BASE}/idp.xml", "description": "My IDP", "service": { "idp": { "name": "Rolands IdP", "endpoints": { "single_sign_on_service": [ - ("%s/sso/redirect" % BASE, BINDING_HTTP_REDIRECT), - ("%s/sso/post" % BASE, BINDING_HTTP_POST), + (f"{BASE}/sso/redirect", BINDING_HTTP_REDIRECT), + (f"{BASE}/sso/post", BINDING_HTTP_POST), ], "single_logout_service": [ - ("%s/slo/post" % BASE, BINDING_HTTP_POST), - ("%s/slo/redirect" % BASE, BINDING_HTTP_REDIRECT), + (f"{BASE}/slo/post", BINDING_HTTP_POST), + (f"{BASE}/slo/redirect", BINDING_HTTP_REDIRECT), ], - "assertion_id_request_service": [("%s/airs" % BASE, BINDING_URI)], + "assertion_id_request_service": [(f"{BASE}/airs", BINDING_URI)], "manage_name_id_service": [ - ("%s/mni/post" % BASE, BINDING_HTTP_POST), - ("%s/mni/redirect" % BASE, BINDING_HTTP_REDIRECT), + (f"{BASE}/mni/post", BINDING_HTTP_POST), + (f"{BASE}/mni/redirect", BINDING_HTTP_REDIRECT), ], }, "policy": { diff --git a/tests/sp_test/targetsp.py b/tests/sp_test/targetsp.py index f47269dc..225930ae 100755 --- a/tests/sp_test/targetsp.py +++ b/tests/sp_test/targetsp.py @@ -16,7 +16,7 @@ AUTHN = {"class_ref": AUTHN_PASSWORD, "authn_auth": "http://lingon.catalogix.se/ info = { "start_page": BASE, - "entity_id": "%s/sp.xml" % BASE, + "entity_id": f"{BASE}/sp.xml", "result": { "matches": {"content": "<h2>Your identity are"}, }, diff --git a/tests/test_12_s_utils.py b/tests/test_12_s_utils.py index f5d8e103..454cd0bb 100644 --- a/tests/test_12_s_utils.py +++ b/tests/test_12_s_utils.py @@ -77,7 +77,7 @@ def test_inflate_then_deflate(): def test_status_success(): status = utils.success_status_factory() - status_text = "%s" % status + status_text = f"{status}" assert status_text in (SUCCESS_STATUS_NO_HEADER, SUCCESS_STATUS) assert status.status_code.value == samlp.STATUS_SUCCESS @@ -87,7 +87,7 @@ def test_error_status(): "Error resolving principal", samlp.STATUS_UNKNOWN_PRINCIPAL, samlp.STATUS_RESPONDER ) - status_text = "%s" % status + status_text = f"{status}" print(status_text) assert status_text in (ERROR_STATUS_NO_HEADER, ERROR_STATUS) @@ -95,20 +95,20 @@ def test_error_status(): def test_status_from_exception(): e = utils.UnknownPrincipal("Error resolving principal") stat = utils.error_status_factory(e) - status_text = "%s" % stat + status_text = f"{stat}" print(status_text) assert status_text in (ERROR_STATUS_NO_HEADER, ERROR_STATUS) def test_status_from_tuple(): stat = utils.error_status_factory((samlp.STATUS_UNKNOWN_PRINCIPAL, "Error resolving principal")) - status_text = "%s" % stat + status_text = f"{stat}" assert status_text in (ERROR_STATUS_NO_HEADER, ERROR_STATUS) def test_status_from_tuple_empty_message(): stat = utils.error_status_factory((samlp.STATUS_UNKNOWN_PRINCIPAL, None)) - status_text = "%s" % stat + status_text = f"{stat}" assert status_text in (ERROR_STATUS_EMPTY, ERROR_STATUS_NO_HEADER_EMPTY) diff --git a/tests/test_30_mdstore.py b/tests/test_30_mdstore.py index 91cef719..1c67a701 100644 --- a/tests/test_30_mdstore.py +++ b/tests/test_30_mdstore.py @@ -199,7 +199,7 @@ def _eq(l1, l2): def _fix_valid_until(xmlstring): new_date = datetime.datetime.now() + datetime.timedelta(days=1) new_date = new_date.strftime("%Y-%m-%dT%H:%M:%SZ") - return re.sub(r' validUntil=".*?"', ' validUntil="%s"' % new_date, xmlstring) + return re.sub(r' validUntil=".*?"', f' validUntil="{new_date}"', xmlstring) def test_invalid_metadata(): diff --git a/tests/test_30_mdstore_old.py b/tests/test_30_mdstore_old.py index 64c20d84..412d54c6 100644 --- a/tests/test_30_mdstore_old.py +++ b/tests/test_30_mdstore_old.py @@ -113,7 +113,7 @@ def _eq(l1, l2): def _fix_valid_until(xmlstring): new_date = datetime.datetime.now() + datetime.timedelta(days=1) new_date = new_date.strftime("%Y-%m-%dT%H:%M:%SZ") - return re.sub(r' validUntil=".*?"', ' validUntil="%s"' % new_date, xmlstring) + return re.sub(r' validUntil=".*?"', f' validUntil="{new_date}"', xmlstring) def test_swami_1(): diff --git a/tests/test_40_sigver.py b/tests/test_40_sigver.py index df889ff8..f026fa39 100644 --- a/tests/test_40_sigver.py +++ b/tests/test_40_sigver.py @@ -183,7 +183,7 @@ class TestSecurity: def test_sign_assertion(self): ass = self._assertion print(ass) - sign_ass = self.sec.sign_assertion("%s" % ass, node_id=ass.id) + sign_ass = self.sec.sign_assertion(f"{ass}", node_id=ass.id) # print(sign_ass) sass = saml.assertion_from_string(sign_ass) # print(sass) @@ -192,7 +192,7 @@ class TestSecurity: assert sass.id == "id-11111" assert time_util.str_to_time(sass.issue_instant) - print("Crypto version : %s" % (self.sec.crypto.version())) + print(f"Crypto version : {self.sec.crypto.version()}") item = self.sec.check_signature(sass, class_name(sass), sign_ass) @@ -209,7 +209,7 @@ class TestSecurity: assert sass.id == "id-11111" assert time_util.str_to_time(sass.issue_instant) - print("Crypto version : %s" % (self.sec.crypto.version())) + print(f"Crypto version : {self.sec.crypto.version()}") item = self.sec.check_signature(sass, class_name(sass), sign_ass, must=True) @@ -488,7 +488,7 @@ class TestSecurityNonAsciiAva: def test_sign_assertion(self): ass = self._assertion print(ass) - sign_ass = self.sec.sign_assertion("%s" % ass, node_id=ass.id) + sign_ass = self.sec.sign_assertion(f"{ass}", node_id=ass.id) # print(sign_ass) sass = saml.assertion_from_string(sign_ass) # print(sass) @@ -498,7 +498,7 @@ class TestSecurityNonAsciiAva: assert sass.id == "id-11111" assert time_util.str_to_time(sass.issue_instant) - print("Crypto version : %s" % (self.sec.crypto.version())) + print(f"Crypto version : {self.sec.crypto.version()}") item = self.sec.check_signature(sass, class_name(sass), sign_ass) @@ -515,7 +515,7 @@ class TestSecurityNonAsciiAva: assert sass.id == "id-11111" assert time_util.str_to_time(sass.issue_instant) - print("Crypto version : %s" % (self.sec.crypto.version())) + print(f"Crypto version : {self.sec.crypto.version()}") item = self.sec.check_signature(sass, class_name(sass), sign_ass, must=True) diff --git a/tests/test_50_server.py b/tests/test_50_server.py index c593623c..2784d172 100644 --- a/tests/test_50_server.py +++ b/tests/test_50_server.py @@ -217,7 +217,7 @@ class TestServer1: # should raise an error because faulty spentityid binding = BINDING_HTTP_REDIRECT - htargs = self.client.apply_binding(binding, "%s" % authn_request, "http://www.example.com", "abcd") + htargs = self.client.apply_binding(binding, f"{authn_request}", "http://www.example.com", "abcd") _dict = parse_qs(htargs["headers"][0][1].split("?")[1]) print(_dict) with raises(OtherError): @@ -227,7 +227,7 @@ class TestServer1: req_id, authn_request = self.client.create_authn_request(destination="http://www.example.com") binding = BINDING_HTTP_REDIRECT - htargs = self.client.apply_binding(binding, "%s" % authn_request, "http://www.example.com", "abcd") + htargs = self.client.apply_binding(binding, f"{authn_request}", "http://www.example.com", "abcd") _dict = parse_qs(htargs["headers"][0][1].split("?")[1]) print(_dict) @@ -256,7 +256,7 @@ class TestServer1: print(authn_request) binding = BINDING_HTTP_REDIRECT - htargs = self.client.apply_binding(binding, "%s" % authn_request, "http://www.example.com", "abcd") + htargs = self.client.apply_binding(binding, f"{authn_request}", "http://www.example.com", "abcd") _dict = parse_qs(htargs["headers"][0][1].split("?")[1]) print(_dict) @@ -624,7 +624,7 @@ class TestServer1: ) assert valid - decr_text_old = copy.deepcopy("%s" % signed_resp) + decr_text_old = copy.deepcopy(f"{signed_resp}") with raises(DecryptError): decr_text = self.server.sec.decrypt( @@ -769,7 +769,7 @@ class TestServer1: encrypt_cert_advice=cert_str_advice, ) - _resp = "%s" % _resp + _resp = f"{_resp}" sresponse = response_from_string(_resp) @@ -889,7 +889,7 @@ class TestServer1: pefim=True, ) - _resp = "%s" % _resp + _resp = f"{_resp}" sresponse = response_from_string(_resp) @@ -1293,7 +1293,7 @@ class TestServer1NonAsciiAva: # should raise an error because faulty spentityid binding = BINDING_HTTP_REDIRECT - htargs = self.client.apply_binding(binding, "%s" % authn_request, "http://www.example.com", "abcd") + htargs = self.client.apply_binding(binding, f"{authn_request}", "http://www.example.com", "abcd") _dict = parse_qs(htargs["headers"][0][1].split("?")[1]) print(_dict) with raises(OtherError): @@ -1303,7 +1303,7 @@ class TestServer1NonAsciiAva: req_id, authn_request = self.client.create_authn_request(destination="http://www.example.com") binding = BINDING_HTTP_REDIRECT - htargs = self.client.apply_binding(binding, "%s" % authn_request, "http://www.example.com", "abcd") + htargs = self.client.apply_binding(binding, f"{authn_request}", "http://www.example.com", "abcd") _dict = parse_qs(htargs["headers"][0][1].split("?")[1]) print(_dict) @@ -1332,7 +1332,7 @@ class TestServer1NonAsciiAva: print(authn_request) binding = BINDING_HTTP_REDIRECT - htargs = self.client.apply_binding(binding, "%s" % authn_request, "http://www.example.com", "abcd") + htargs = self.client.apply_binding(binding, f"{authn_request}", "http://www.example.com", "abcd") _dict = parse_qs(htargs["headers"][0][1].split("?")[1]) print(_dict) @@ -1700,7 +1700,7 @@ class TestServer1NonAsciiAva: ) assert valid - decr_text_old = copy.deepcopy("%s" % signed_resp) + decr_text_old = copy.deepcopy(f"{signed_resp}") with raises(DecryptError): decr_text = self.server.sec.decrypt( @@ -1845,7 +1845,7 @@ class TestServer1NonAsciiAva: encrypt_cert_advice=cert_str_advice, ) - _resp = "%s" % _resp + _resp = f"{_resp}" sresponse = response_from_string(_resp) @@ -1965,7 +1965,7 @@ class TestServer1NonAsciiAva: pefim=True, ) - _resp = "%s" % _resp + _resp = f"{_resp}" sresponse = response_from_string(_resp) @@ -2408,7 +2408,7 @@ class TestServerLogout: response = server.create_logout_response(request, bindings) binding, destination = server.pick_binding("single_logout_service", bindings, "spsso", request) - http_args = server.apply_binding(binding, "%s" % response, destination, "relay_state", response=True) + http_args = server.apply_binding(binding, f"{response}", destination, "relay_state", response=True) assert len(http_args) == 5 assert http_args["headers"][0][0] == "Location" @@ -2424,7 +2424,7 @@ class TestServerLogout: response = server.create_logout_response(request, bindings) binding, destination = server.pick_binding("single_logout_service", bindings, "spsso", request) - http_args = server.apply_binding(binding, "%s" % response, destination, "relay_state", response=True) + http_args = server.apply_binding(binding, f"{response}", destination, "relay_state", response=True) assert len(http_args) == 5 assert len(http_args["data"]) > 0 diff --git a/tests/test_51_client.py b/tests/test_51_client.py index 9a1ff516..e1eb85ec 100644 --- a/tests/test_51_client.py +++ b/tests/test_51_client.py @@ -183,7 +183,7 @@ class TestClient: format=saml.NAMEID_FORMAT_PERSISTENT, message_id="id1", ) - reqstr = "%s" % req.to_string().decode() + reqstr = f"{req.to_string().decode()}" assert req.destination == "https://idp.example.com/idp/" assert req.id == "id1" @@ -353,7 +353,7 @@ class TestClient: conf = config.SPConfig() conf.load_file("sp_conf_nameidpolicy") client = Saml2Client(conf) - ar_str = "%s" % client.create_authn_request("http://www.example.com/sso", message_id="id1")[1] + ar_str = f"{client.create_authn_request('http://www.example.com/sso', message_id='id1')[1]}" ar = samlp.authn_request_from_string(ar_str) assert ar.assertion_consumer_service_url == ("http://lingon.catalogix" ".se:8087/") @@ -395,7 +395,7 @@ class TestClient: def test_sign_auth_request_0(self): req_id, areq = self.client.create_authn_request("http://www.example.com/sso", sign=True, message_id="id1") - ar_str = "%s" % areq + ar_str = f"{areq}" ar = samlp.authn_request_from_string(ar_str) assert ar @@ -477,7 +477,7 @@ class TestClient: authn=AUTHN, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -562,7 +562,7 @@ class TestClient: encrypt_cert_advice=cert_str, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -596,7 +596,7 @@ class TestClient: pefim=True, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -630,7 +630,7 @@ class TestClient: pefim=True, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -669,7 +669,7 @@ class TestClient: encrypt_cert_assertion=cert_str, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -713,7 +713,7 @@ class TestClient: encrypt_cert_advice=cert_advice_str, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -750,7 +750,7 @@ class TestClient: encrypted_advice_attributes=True, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -788,7 +788,7 @@ class TestClient: encrypt_cert_assertion=cert_str, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -937,7 +937,7 @@ class TestClient: assers = extension_elements_to_elements(enc_ass.extension_elements, [saml, samlp]) for ass in assers: if ass.signature: - if not _csec.verify_signature("%s" % ass, sign_cert_file, node_name=class_name(ass)): + if not _csec.verify_signature(f"{ass}", sign_cert_file, node_name=class_name(ass)): continue resp_ass.append(ass) @@ -989,7 +989,7 @@ class TestClient: encrypted_assertion=EncryptedAssertion(), ) - xmldoc = "%s" % response + xmldoc = f"{response}" # strangely enough I get different tags if I run this test separately # or as part of a bunch of tests. xmldoc = add_subelement(xmldoc, "EncryptedAssertion", sigass) @@ -1079,7 +1079,7 @@ class TestClient: response.assertion.append(assertion) response = _sec.sign_statement( - "%s" % response, class_name(a_assertion), key_file=self.client.sec.key_file, node_id=a_assertion.id + f"{response}", class_name(a_assertion), key_file=self.client.sec.key_file, node_id=a_assertion.id ) # xmldoc = "%s" % response @@ -1088,10 +1088,7 @@ class TestClient: # xmldoc = add_subelement(xmldoc, "EncryptedAssertion", sigass) node_xpath = "".join( - [ - '/*[local-name()="%s"]' % v - for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] - ] + [f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]] ) enctext = _sec.crypto.encrypt_assertion( @@ -1243,14 +1240,11 @@ class TestClient: ) response = _sec.sign_statement( - "%s" % response, class_name(a_assertion_1), key_file=self.server.sec.key_file, node_id=a_assertion_1.id + f"{response}", class_name(a_assertion_1), key_file=self.server.sec.key_file, node_id=a_assertion_1.id ) node_xpath = "".join( - [ - '/*[local-name()="%s"]' % v - for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] - ] + [f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]] ) enctext = _sec.crypto.encrypt_assertion( @@ -1271,14 +1265,11 @@ class TestClient: ) response = _sec.sign_statement( - "%s" % response, class_name(a_assertion_2), key_file=self.server.sec.key_file, node_id=a_assertion_2.id + f"{response}", class_name(a_assertion_2), key_file=self.server.sec.key_file, node_id=a_assertion_2.id ) node_xpath = "".join( - [ - '/*[local-name()="%s"]' % v - for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] - ] + [f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]] ) enctext = _sec.crypto.encrypt_assertion( @@ -1294,7 +1285,7 @@ class TestClient: response = response.get_xml_string_with_self_contained_assertion_within_encrypted_assertion(assertion_tag) response = _sec.sign_statement( - "%s" % response, class_name(assertion_1), key_file=self.server.sec.key_file, node_id=assertion_1.id + f"{response}", class_name(assertion_1), key_file=self.server.sec.key_file, node_id=assertion_1.id ) enctext = _sec.crypto.encrypt_assertion( @@ -1319,14 +1310,11 @@ class TestClient: ) response = _sec.sign_statement( - "%s" % response, class_name(a_assertion_3), key_file=self.server.sec.key_file, node_id=a_assertion_3.id + f"{response}", class_name(a_assertion_3), key_file=self.server.sec.key_file, node_id=a_assertion_3.id ) node_xpath = "".join( - [ - '/*[local-name()="%s"]' % v - for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] - ] + [f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]] ) enctext = _sec.crypto.encrypt_assertion( @@ -1348,14 +1336,11 @@ class TestClient: ) response = _sec.sign_statement( - "%s" % response, class_name(a_assertion_4), key_file=self.server.sec.key_file, node_id=a_assertion_4.id + f"{response}", class_name(a_assertion_4), key_file=self.server.sec.key_file, node_id=a_assertion_4.id ) node_xpath = "".join( - [ - '/*[local-name()="%s"]' % v - for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] - ] + [f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]] ) enctext = _sec.crypto.encrypt_assertion( @@ -1365,7 +1350,7 @@ class TestClient: response = samlp.response_from_string(enctext) response = _sec.sign_statement( - "%s" % response, + f"{response}", class_name(response.assertion[0]), key_file=self.server.sec.key_file, node_id=response.assertion[0].id, @@ -1865,7 +1850,7 @@ class TestClientNonAsciiAva: format=saml.NAMEID_FORMAT_PERSISTENT, message_id="id1", ) - reqstr = "%s" % req.to_string().decode() + reqstr = f"{req.to_string().decode()}" assert req.destination == "https://idp.example.com/idp/" assert req.id == "id1" @@ -1995,7 +1980,7 @@ class TestClientNonAsciiAva: conf = config.SPConfig() conf.load_file("sp_conf_nameidpolicy") client = Saml2Client(conf) - ar_str = "%s" % client.create_authn_request("http://www.example.com/sso", message_id="id1")[1] + ar_str = f"{client.create_authn_request('http://www.example.com/sso', message_id='id1')[1]}" ar = samlp.authn_request_from_string(ar_str) assert ar.assertion_consumer_service_url == ("http://lingon.catalogix" ".se:8087/") @@ -2037,7 +2022,7 @@ class TestClientNonAsciiAva: def test_sign_auth_request_0(self): req_id, areq = self.client.create_authn_request("http://www.example.com/sso", sign=True, message_id="id1") - ar_str = "%s" % areq + ar_str = f"{areq}" ar = samlp.authn_request_from_string(ar_str) assert ar @@ -2089,7 +2074,7 @@ class TestClientNonAsciiAva: authn=AUTHN, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode("utf-8")) @@ -2174,7 +2159,7 @@ class TestClientNonAsciiAva: encrypt_cert_advice=cert_str, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -2208,7 +2193,7 @@ class TestClientNonAsciiAva: pefim=True, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -2242,7 +2227,7 @@ class TestClientNonAsciiAva: pefim=True, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -2281,7 +2266,7 @@ class TestClientNonAsciiAva: encrypt_cert_assertion=cert_str, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -2325,7 +2310,7 @@ class TestClientNonAsciiAva: encrypt_cert_advice=cert_advice_str, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -2362,7 +2347,7 @@ class TestClientNonAsciiAva: encrypted_advice_attributes=True, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -2400,7 +2385,7 @@ class TestClientNonAsciiAva: encrypt_cert_assertion=cert_str, ) - resp_str = "%s" % resp + resp_str = f"{resp}" resp_str = b64encode(resp_str.encode()) @@ -2601,7 +2586,7 @@ class TestClientNonAsciiAva: assers = extension_elements_to_elements(enc_ass.extension_elements, [saml, samlp]) for ass in assers: if ass.signature: - if not _csec.verify_signature("%s" % ass, sign_cert_file, node_name=class_name(ass)): + if not _csec.verify_signature(f"{ass}", sign_cert_file, node_name=class_name(ass)): continue resp_ass.append(ass) @@ -2653,7 +2638,7 @@ class TestClientNonAsciiAva: encrypted_assertion=EncryptedAssertion(), ) - xmldoc = "%s" % response + xmldoc = f"{response}" # strangely enough I get different tags if I run this test separately # or as part of a bunch of tests. xmldoc = add_subelement(xmldoc, "EncryptedAssertion", sigass) @@ -2743,7 +2728,7 @@ class TestClientNonAsciiAva: response.assertion.append(assertion) response = _sec.sign_statement( - "%s" % response, class_name(a_assertion), key_file=self.client.sec.key_file, node_id=a_assertion.id + f"{response}", class_name(a_assertion), key_file=self.client.sec.key_file, node_id=a_assertion.id ) # xmldoc = "%s" % response @@ -2752,10 +2737,7 @@ class TestClientNonAsciiAva: # xmldoc = add_subelement(xmldoc, "EncryptedAssertion", sigass) node_xpath = "".join( - [ - '/*[local-name()="%s"]' % v - for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] - ] + [f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]] ) enctext = _sec.crypto.encrypt_assertion( @@ -2906,14 +2888,11 @@ class TestClientNonAsciiAva: ) response = _sec.sign_statement( - "%s" % response, class_name(a_assertion_1), key_file=self.server.sec.key_file, node_id=a_assertion_1.id + f"{response}", class_name(a_assertion_1), key_file=self.server.sec.key_file, node_id=a_assertion_1.id ) node_xpath = "".join( - [ - '/*[local-name()="%s"]' % v - for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] - ] + [f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]] ) enctext = _sec.crypto.encrypt_assertion( @@ -2934,14 +2913,11 @@ class TestClientNonAsciiAva: ) response = _sec.sign_statement( - "%s" % response, class_name(a_assertion_2), key_file=self.server.sec.key_file, node_id=a_assertion_2.id + f"{response}", class_name(a_assertion_2), key_file=self.server.sec.key_file, node_id=a_assertion_2.id ) node_xpath = "".join( - [ - '/*[local-name()="%s"]' % v - for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] - ] + [f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]] ) enctext = _sec.crypto.encrypt_assertion( @@ -2957,7 +2933,7 @@ class TestClientNonAsciiAva: response = response.get_xml_string_with_self_contained_assertion_within_encrypted_assertion(assertion_tag) response = _sec.sign_statement( - "%s" % response, class_name(assertion_1), key_file=self.server.sec.key_file, node_id=assertion_1.id + f"{response}", class_name(assertion_1), key_file=self.server.sec.key_file, node_id=assertion_1.id ) enctext = _sec.crypto.encrypt_assertion( @@ -2982,14 +2958,11 @@ class TestClientNonAsciiAva: ) response = _sec.sign_statement( - "%s" % response, class_name(a_assertion_3), key_file=self.server.sec.key_file, node_id=a_assertion_3.id + f"{response}", class_name(a_assertion_3), key_file=self.server.sec.key_file, node_id=a_assertion_3.id ) node_xpath = "".join( - [ - '/*[local-name()="%s"]' % v - for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] - ] + [f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]] ) enctext = _sec.crypto.encrypt_assertion( @@ -3011,14 +2984,11 @@ class TestClientNonAsciiAva: ) response = _sec.sign_statement( - "%s" % response, class_name(a_assertion_4), key_file=self.server.sec.key_file, node_id=a_assertion_4.id + f"{response}", class_name(a_assertion_4), key_file=self.server.sec.key_file, node_id=a_assertion_4.id ) node_xpath = "".join( - [ - '/*[local-name()="%s"]' % v - for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"] - ] + [f'/*[local-name()="{v}"]' for v in ["Response", "Assertion", "Advice", "EncryptedAssertion", "Assertion"]] ) enctext = _sec.crypto.encrypt_assertion( @@ -3028,7 +2998,7 @@ class TestClientNonAsciiAva: response = samlp.response_from_string(enctext) response = _sec.sign_statement( - "%s" % response, + f"{response}", class_name(response.assertion[0]), key_file=self.server.sec.key_file, node_id=response.assertion[0].id, @@ -3063,7 +3033,7 @@ class TestClientNonAsciiAva: # Revert configuration change to disallow unsinged responses self.client.want_response_signed = True - msg_str = "%s" % self.client.create_authn_request("http://localhost:8088/sso", message_id="id1")[1] + msg_str = f"{self.client.create_authn_request('http://localhost:8088/sso', message_id='id1')[1]}" info = self.client.apply_binding( BINDING_HTTP_REDIRECT, msg_str, destination="", relay_state="relay2", sign=True, sigalg=SIG_RSA_SHA256 diff --git a/tests/test_64_artifact.py b/tests/test_64_artifact.py index 2398d70b..25a19184 100644 --- a/tests/test_64_artifact.py +++ b/tests/test_64_artifact.py @@ -176,7 +176,7 @@ def test_artifact_flow(): }, name_id=name_id, authn=AUTHN, - **resp_args + **resp_args, ) print(response) @@ -189,7 +189,7 @@ def test_artifact_flow(): "single_sign_on_service", [BINDING_HTTP_ARTIFACT], entity_id=idp.config.entityid ) - hinfo = sp.apply_binding(binding, "%s" % artifact, destination, relay_state, response=True) + hinfo = sp.apply_binding(binding, f"{artifact}", destination, relay_state, response=True) # ========== SP ========= diff --git a/tests/test_65_authn_query.py b/tests/test_65_authn_query.py index 71c934c3..23faf47d 100644 --- a/tests/test_65_authn_query.py +++ b/tests/test_65_authn_query.py @@ -85,7 +85,7 @@ def test_flow(): authn=AUTHN, ) - hinfo = idp.apply_binding(binding, "%s" % resp, destination, relay_state) + hinfo = idp.apply_binding(binding, f"{resp}", destination, relay_state) # ------- @SP ---------- @@ -107,7 +107,7 @@ def test_flow(): assert isinstance(aq, AuthnQuery) binding = BINDING_SOAP - hinfo = sp.apply_binding(binding, "%s" % aq, destination, "state2") + hinfo = sp.apply_binding(binding, f"{aq}", destination, "state2") # -------- @IDP ---------- @@ -122,7 +122,7 @@ def test_flow(): print(p_res) - hinfo = idp.apply_binding(binding, "%s" % p_res, "", "state2", response=True) + hinfo = idp.apply_binding(binding, f"{p_res}", "", "state2", response=True) # ------- @SP ---------- diff --git a/tests/test_67_manage_name_id.py b/tests/test_67_manage_name_id.py index 3a54f01e..c41d8c0b 100644 --- a/tests/test_67_manage_name_id.py +++ b/tests/test_67_manage_name_id.py @@ -23,7 +23,7 @@ def test_basic(): mid, mreq = sp.create_manage_name_id_request(destination, name_id=nameid, new_id=newid) print(mreq) - rargs = sp.apply_binding(binding, "%s" % mreq, destination, "") + rargs = sp.apply_binding(binding, f"{mreq}", destination, "") # --------- @IDP -------------- @@ -45,7 +45,7 @@ def test_flow(): mid, midq = sp.create_manage_name_id_request(destination, name_id=nameid, new_id=newid) print(midq) - rargs = sp.apply_binding(binding, "%s" % midq, destination, "") + rargs = sp.apply_binding(binding, f"{midq}", destination, "") # --------- @IDP -------------- @@ -60,7 +60,7 @@ def test_flow(): else: destination = "" - respargs = idp.apply_binding(binding, "%s" % mnir, destination, "") + respargs = idp.apply_binding(binding, f"{mnir}", destination, "") print(respargs) diff --git a/tests/test_68_assertion_id.py b/tests/test_68_assertion_id.py index 9f254fcf..34792efc 100644 --- a/tests/test_68_assertion_id.py +++ b/tests/test_68_assertion_id.py @@ -75,7 +75,7 @@ def test_basic_flow(): authn=AUTHN, ) - hinfo = idp.apply_binding(binding, "%s" % resp, destination, relay_state) + hinfo = idp.apply_binding(binding, f"{resp}", destination, relay_state) # --------- @SP ------------- @@ -100,7 +100,7 @@ def test_basic_flow(): resp = idp.create_assertion_id_request_response(aid) - hinfo = idp.apply_binding(binding, "%s" % resp, None, "", response=True) + hinfo = idp.apply_binding(binding, f"{resp}", None, "", response=True) # ----------- @SP ------------- diff --git a/tests/test_77_authn_context.py b/tests/test_77_authn_context.py index 643149b8..b798720a 100644 --- a/tests/test_77_authn_context.py +++ b/tests/test_77_authn_context.py @@ -54,7 +54,7 @@ def test_factory(): def test_authn_decl_in_authn_context(): authnctxt = AuthnContext(authn_context_decl=ACD) - acs = authn_context_from_string("%s" % authnctxt) + acs = authn_context_from_string(f"{authnctxt}") if acs.extension_elements: cacd = authn_context_decl_from_extension_elements(acs.extension_elements) if cacd: @@ -102,7 +102,7 @@ def test_authn_3(): level += 4 ac = authn_context_class_ref(ref) - authn.add(ac, REF2METHOD[ref], level, "https://www.example.com/%s" % "al%d" % level) + authn.add(ac, REF2METHOD[ref], level, f"https://www.example.com/{'al%d'}" % level) rac = requested_authn_context(AL1, "minimum") diff --git a/tests/test_82_pefim.py b/tests/test_82_pefim.py index abce6f58..ce223f27 100644 --- a/tests/test_82_pefim.py +++ b/tests/test_82_pefim.py @@ -39,7 +39,7 @@ print(req) # Get a certificate from an authn request -xml = "%s" % req +xml = f"{req}" parsed = authn_request_from_string(xml) diff --git a/tests/test_88_nsprefix.py b/tests/test_88_nsprefix.py index 5b790f23..d61e0d19 100644 --- a/tests/test_88_nsprefix.py +++ b/tests/test_88_nsprefix.py @@ -13,13 +13,13 @@ def test_nsprefix(): status_message = samlp.StatusMessage() status_message.text = "OK" - txt = "%s" % status_message + txt = f"{status_message}" assert "ns0:StatusMessage" in txt status_message.register_prefix({"saml2": saml.NAMESPACE, "saml2p": samlp.NAMESPACE}) - txt = "%s" % status_message + txt = f"{status_message}" assert "saml2p:StatusMessage" in txt @@ -39,7 +39,7 @@ def test_nsprefix2(): nsprefix={"saml2": saml.NAMESPACE, "saml2p": samlp.NAMESPACE}, ) - txt = "%s" % req + txt = f"{req}" assert "saml2p:AuthnRequest" in txt assert "saml2:Issuer" in txt diff --git a/tests/test_89_http_post_relay_state.py b/tests/test_89_http_post_relay_state.py index 846782ec..f04b25cd 100644 --- a/tests/test_89_http_post_relay_state.py +++ b/tests/test_89_http_post_relay_state.py @@ -65,7 +65,7 @@ def test_relay_state(): # typical from a Shibboleth SP to create the HTML that carries # the SAML response. relay_state = SHIB_SP_RELAY_STATE - html = idp.apply_binding(BINDING_HTTP_POST, "%s" % resp, destination, relay_state)["data"] + html = idp.apply_binding(BINDING_HTTP_POST, f"{resp}", destination, relay_state)["data"] # Parse the HTML and verify that it contains the correct relay state. parser = RelayStateHTMLParser(relay_state) @@ -74,7 +74,7 @@ def test_relay_state(): # Apply the HTTP_POST binding to the response with relay state None. relay_state = None - html = idp.apply_binding(BINDING_HTTP_POST, "%s" % resp, destination, relay_state)["data"] + html = idp.apply_binding(BINDING_HTTP_POST, f"{resp}", destination, relay_state)["data"] # Parse the HTML and verify that it does not contain a relay state. parser = RelayStateHTMLParser(relay_state) @@ -84,7 +84,7 @@ def test_relay_state(): # Apply the HTTP_POST binding to the response with empty # string relay state. relay_state = "" - html = idp.apply_binding(BINDING_HTTP_POST, "%s" % resp, destination, relay_state)["data"] + html = idp.apply_binding(BINDING_HTTP_POST, f"{resp}", destination, relay_state)["data"] # Parse the HTML and verify that it does not contain a relay state. parser = RelayStateHTMLParser(relay_state) |