From e6da325e8be4a7194571adea67053446c75d9aa3 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Can=20Sar=C4=B1g=C3=B6l?= Date: Fri, 4 Oct 2019 11:17:25 +0300 Subject: [PATCH] added authority copy feature in URL.copy_with (#436) --- httpx/models.py | 22 ++++++++++++++++++++++ tests/models/test_url.py | 14 ++++++++++++++ 2 files changed, 36 insertions(+) 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" -- 2.47.3