From 76eb3d22dc0e1f94e40efb0f73461d09428f6fce Mon Sep 17 00:00:00 2001 From: selfisekai Date: Fri, 18 Sep 2020 18:12:30 +0200 Subject: [PATCH] absolute_url util (closes #9) --- librefi/utils.py | 23 ++++++++++++++++++++++- tests/url_utils.py | 15 +++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/url_utils.py diff --git a/librefi/utils.py b/librefi/utils.py index 8355694..406a31a 100644 --- a/librefi/utils.py +++ b/librefi/utils.py @@ -1,7 +1,7 @@ # flake8: noqa: E501 import re -from urllib.parse import parse_qs, quote as qs_quote +from urllib.parse import parse_qs, quote as qs_quote, urlparse from datetime import datetime import random @@ -131,3 +131,24 @@ def dump_qs(obj): strng += qs_quote(str(el[0]), encoding="utf8") + "=" + \ qs_quote(str(el[1]), encoding="utf8") + "&" return strng[:-1] + + +def absolute_url(new_url: str, old_url: str): + if new_url.startswith("http:") or new_url.startswith("https:"): + return new_url + + old = urlparse(old_url) + scheme = old.scheme if old.scheme is not None else "http" + + if new_url.startswith("://"): + return scheme + new_url + if new_url.startswith("//"): + return scheme + ":" + new_url + + hostname = old.netloc + + if new_url.startswith("/"): + return scheme + "://" + hostname + new_url + + # like "hostname/path?query", if other checks fail + return scheme + "://" + new_url diff --git a/tests/url_utils.py b/tests/url_utils.py new file mode 100644 index 0000000..7dc34dc --- /dev/null +++ b/tests/url_utils.py @@ -0,0 +1,15 @@ +from librefi.utils import absolute_url + +OLD_URL = "https://sakamoto.pl/ddd" +NEW_URL_RELATIVE = "/DDD?test=yes" + +# expected value +NEW_URL_ABSOLUTE = "https://sakamoto.pl/DDD?test=yes" + + +def test_basic(): + abso = absolute_url(NEW_URL_RELATIVE, OLD_URL) + assert isinstance(abso, (str)) + print(abso) + assert abso == NEW_URL_ABSOLUTE + pass