From: Can Sarıgöl Date: Fri, 4 Oct 2019 08:17:25 +0000 (+0300) Subject: added authority copy feature in URL.copy_with (#436) X-Git-Tag: 0.7.5~15 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e6da325e8be4a7194571adea67053446c75d9aa3;p=thirdparty%2Fhttpx.git added authority copy feature in URL.copy_with (#436) --- diff --git a/httpx/models.py b/httpx/models.py index 887d8aed..97820e0a 100644 --- a/httpx/models.py +++ b/httpx/models.py @@ -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": diff --git a/tests/models/test_url.py b/tests/models/test_url.py index 0bba2566..c4a74a8c 100644 --- a/tests/models/test_url.py +++ b/tests/models/test_url.py @@ -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"