]> git.ipfire.org Git - thirdparty/httpx.git/commitdiff
added authority copy feature in URL.copy_with (#436)
authorCan Sarıgöl <cansarigol@derinbilgi.com.tr>
Fri, 4 Oct 2019 08:17:25 +0000 (11:17 +0300)
committerTom Christie <tom@tomchristie.com>
Fri, 4 Oct 2019 08:17:25 +0000 (09:17 +0100)
httpx/models.py
tests/models/test_url.py

index 887d8aedb6940ed48c155e2db385555077bdbc2b..97820e0aff86bea8a5ec029b810dfc290d85642b 100644 (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":
index 0bba256690ec31a7e161a6786126e3340965e916..c4a74a8c210dcb0e8fe57be7fa4f29860a0ab0e6 100644 (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"