added authority copy feature in URL.copy_with (#436)

This commit is contained in:
Can Sarıgöl 2019-10-04 11:17:25 +03:00 committed by Tom Christie
parent f504399781
commit e6da325e8b
2 changed files with 36 additions and 0 deletions

View File

@ -207,6 +207,28 @@ class URL:
return Origin(self)
def copy_with(self, **kwargs: typing.Any) -> "URL":
if (
"username" in kwargs
or "password" in kwargs
or "host" in kwargs
or "port" in kwargs
):
host = kwargs.pop("host", self.host)
port = kwargs.pop("port", self.port)
username = kwargs.pop("username", self.username)
password = kwargs.pop("password", self.password)
authority = host
if port is not None:
authority += f":{port}"
if username is not None:
userpass = username
if password is not None:
userpass += f":{password}"
authority = f"{userpass}@{authority}"
kwargs["authority"] = authority
return URL(self._uri_reference.copy_with(**kwargs).unsplit())
def join(self, relative_url: URLTypes) -> "URL":

View File

@ -190,3 +190,17 @@ def test_origin_from_url_string():
assert origin.is_ssl
assert origin.host == "example.com"
assert origin.port == 443
def test_url_copywith_for_authority():
copy_with_kwargs = {
"username": "username",
"password": "password",
"port": 444,
"host": "example.net",
}
url = URL("https://example.org")
new = url.copy_with(**copy_with_kwargs)
for k, v in copy_with_kwargs.items():
assert getattr(new, k) == v
assert str(new) == "https://username:password@example.net:444"