Skip to content
Myr

test_url.py

This file

Path

tests/models/test_url.py

887 lines · 26.5 KiB · Python

Last changed by

Resolve queryparam quoting (#3187)Tom Christiebefore adoptiona7092af

History of this file

Take it

1import pytest23import httpx45# Tests for `httpx.URL` instantiation and property accessors.678def test_basic_url():9    url = httpx.URL("https://www.example.com/")1011    assert url.scheme == "https"12    assert url.userinfo == b""13    assert url.netloc == b"www.example.com"14    assert url.host == "www.example.com"15    assert url.port is None16    assert url.path == "/"17    assert url.query == b""18    assert url.fragment == ""1920    assert str(url) == "https://www.example.com/"21    assert repr(url) == "URL('https://www.example.com/')"222324def test_complete_url():25    url = httpx.URL("https://example.org:123/path/to/somewhere?abc=123#anchor")26    assert url.scheme == "https"27    assert url.host == "example.org"28    assert url.port == 12329    assert url.path == "/path/to/somewhere"30    assert url.query == b"abc=123"31    assert url.raw_path == b"/path/to/somewhere?abc=123"32    assert url.fragment == "anchor"3334    assert str(url) == "https://example.org:123/path/to/somewhere?abc=123#anchor"35    assert (36        repr(url) == "URL('https://example.org:123/path/to/somewhere?abc=123#anchor')"37    )383940def test_url_with_empty_query():41    """42    URLs with and without a trailing `?` but an empty query component43    should preserve the information on the raw path.44    """45    url = httpx.URL("https://www.example.com/path")46    assert url.path == "/path"47    assert url.query == b""48    assert url.raw_path == b"/path"4950    url = httpx.URL("https://www.example.com/path?")51    assert url.path == "/path"52    assert url.query == b""53    assert url.raw_path == b"/path?"545556def test_url_no_scheme():57    url = httpx.URL("://example.com")58    assert url.scheme == ""59    assert url.host == "example.com"60    assert url.path == "/"616263def test_url_no_authority():64    url = httpx.URL("http://")65    assert url.scheme == "http"66    assert url.host == ""67    assert url.path == "/"686970# Tests for percent encoding across path, query, and fragment...717273@pytest.mark.parametrize(74    "url,raw_path,path,query,fragment",75    [76        # URL with unescaped chars in path.77        (78            "https://example.com/!$&'()*+,;= abc ABC 123 :/[]@",79            b"/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@",80            "/!$&'()*+,;= abc ABC 123 :/[]@",81            b"",82            "",83        ),84        # URL with escaped chars in path.85        (86            "https://example.com/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@",87            b"/!$&'()*+,;=%20abc%20ABC%20123%20:/[]@",88            "/!$&'()*+,;= abc ABC 123 :/[]@",89            b"",90            "",91        ),92        # URL with mix of unescaped and escaped chars in path.93        # WARNING: This has the incorrect behaviour, adding the test as an interim step.94        (95            "https://example.com/ %61%62%63",96            b"/%20%61%62%63",97            "/ abc",98            b"",99            "",100        ),101        # URL with unescaped chars in query.102        (103            "https://example.com/?!$&'()*+,;= abc ABC 123 :/[]@?",104            b"/?!$&'()*+,;=%20abc%20ABC%20123%20:/[]@?",105            "/",106            b"!$&'()*+,;=%20abc%20ABC%20123%20:/[]@?",107            "",108        ),109        # URL with escaped chars in query.110        (111            "https://example.com/?!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?",112            b"/?!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?",113            "/",114            b"!$&%27()*+,;=%20abc%20ABC%20123%20:%2F[]@?",115            "",116        ),117        # URL with mix of unescaped and escaped chars in query.118        (119            "https://example.com/?%20%97%98%99",120            b"/?%20%97%98%99",121            "/",122            b"%20%97%98%99",123            "",124        ),125        # URL encoding characters in fragment.126        (127            "https://example.com/#!$&'()*+,;= abc ABC 123 :/[]@?#",128            b"/",129            "/",130            b"",131            "!$&'()*+,;= abc ABC 123 :/[]@?#",132        ),133    ],134)135def test_path_query_fragment(url, raw_path, path, query, fragment):136    url = httpx.URL(url)137    assert url.raw_path == raw_path138    assert url.path == path139    assert url.query == query140    assert url.fragment == fragment141142143def test_url_query_encoding():144    """145    URL query parameters should use '%20' for encoding spaces,146    and should treat '/' as a safe character. This behaviour differs147    across clients, but we're matching browser behaviour here.148149    See https://github.com/encode/httpx/issues/2536150    and https://github.com/encode/httpx/discussions/2460151    """152    url = httpx.URL("https://www.example.com/?a=b c&d=e/f")153    assert url.raw_path == b"/?a=b%20c&d=e/f"154155    url = httpx.URL("https://www.example.com/", params={"a": "b c", "d": "e/f"})156    assert url.raw_path == b"/?a=b%20c&d=e%2Ff"157158159def test_url_params():160    url = httpx.URL("https://example.org:123/path/to/somewhere", params={"a": "123"})161    assert str(url) == "https://example.org:123/path/to/somewhere?a=123"162    assert url.params == httpx.QueryParams({"a": "123"})163164    url = httpx.URL(165        "https://example.org:123/path/to/somewhere?b=456", params={"a": "123"}166    )167    assert str(url) == "https://example.org:123/path/to/somewhere?a=123"168    assert url.params == httpx.QueryParams({"a": "123"})169170171# Tests for username and password172173174@pytest.mark.parametrize(175    "url,userinfo,username,password",176    [177        # username and password in URL.178        (179            "https://username:password@example.com",180            b"username:password",181            "username",182            "password",183        ),184        # username and password in URL with percent escape sequences.185        (186            "https://username%40gmail.com:pa%20ssword@example.com",187            b"username%40gmail.com:pa%20ssword",188            "username@gmail.com",189            "pa ssword",190        ),191        (192            "https://user%20name:p%40ssword@example.com",193            b"user%20name:p%40ssword",194            "user name",195            "p@ssword",196        ),197        # username and password in URL without percent escape sequences.198        (199            "https://username@gmail.com:pa ssword@example.com",200            b"username%40gmail.com:pa%20ssword",201            "username@gmail.com",202            "pa ssword",203        ),204        (205            "https://user name:p@ssword@example.com",206            b"user%20name:p%40ssword",207            "user name",208            "p@ssword",209        ),210    ],211)212def test_url_username_and_password(url, userinfo, username, password):213    url = httpx.URL(url)214    assert url.userinfo == userinfo215    assert url.username == username216    assert url.password == password217218219# Tests for different host types220221222def test_url_valid_host():223    url = httpx.URL("https://example.com/")224    assert url.host == "example.com"225226227def test_url_normalized_host():228    url = httpx.URL("https://EXAMPLE.com/")229    assert url.host == "example.com"230231232def test_url_percent_escape_host():233    url = httpx.URL("https://exam%le.com/")234    assert url.host == "exam%25le.com"235236237def test_url_ipv4_like_host():238    """rare host names used to quality as IPv4"""239    url = httpx.URL("https://023b76x43144/")240    assert url.host == "023b76x43144"241242243# Tests for different port types244245246def test_url_valid_port():247    url = httpx.URL("https://example.com:123/")248    assert url.port == 123249250251def test_url_normalized_port():252    # If the port matches the scheme default it is normalized to None.253    url = httpx.URL("https://example.com:443/")254    assert url.port is None255256257def test_url_invalid_port():258    with pytest.raises(httpx.InvalidURL) as exc:259        httpx.URL("https://example.com:abc/")260    assert str(exc.value) == "Invalid port: 'abc'"261262263# Tests for path handling264265266def test_url_normalized_path():267    url = httpx.URL("https://example.com/abc/def/../ghi/./jkl")268    assert url.path == "/abc/ghi/jkl"269270271def test_url_escaped_path():272    url = httpx.URL("https://example.com/ /🌟/")273    assert url.raw_path == b"/%20/%F0%9F%8C%9F/"274275276def test_url_leading_dot_prefix_on_absolute_url():277    url = httpx.URL("https://example.com/../abc")278    assert url.path == "/abc"279280281def test_url_leading_dot_prefix_on_relative_url():282    url = httpx.URL("../abc")283    assert url.path == "../abc"284285286# Tests for query parameter percent encoding.287#288# Percent-encoding in `params={}` should match browser form behavior.289290291def test_param_with_space():292    # Params passed as form key-value pairs should be escaped.293    url = httpx.URL("http://webservice", params={"u": "with spaces"})294    assert str(url) == "http://webservice?u=with%20spaces"295296297def test_param_does_not_require_encoding():298    # Params passed as form key-value pairs should be escaped.299    url = httpx.URL("http://webservice", params={"u": "%"})300    assert str(url) == "http://webservice?u=%25"301302303def test_param_with_percent_encoded():304    # Params passed as form key-value pairs should always be escaped,305    # even if they include a valid escape sequence.306    # We want to match browser form behaviour here.307    url = httpx.URL("http://webservice", params={"u": "with%20spaces"})308    assert str(url) == "http://webservice?u=with%2520spaces"309310311def test_param_with_existing_escape_requires_encoding():312    # Params passed as form key-value pairs should always be escaped,313    # even if they include a valid escape sequence.314    # We want to match browser form behaviour here.315    url = httpx.URL("http://webservice", params={"u": "http://example.com?q=foo%2Fa"})316    assert str(url) == "http://webservice?u=http%3A%2F%2Fexample.com%3Fq%3Dfoo%252Fa"317318319# Tests for query parameter percent encoding.320#321# Percent-encoding in `url={}` should match browser URL bar behavior.322323324def test_query_with_existing_percent_encoding():325    # Valid percent encoded sequences should not be double encoded.326    url = httpx.URL("http://webservice?u=phrase%20with%20spaces")327    assert str(url) == "http://webservice?u=phrase%20with%20spaces"328329330def test_query_requiring_percent_encoding():331    # Characters that require percent encoding should be encoded.332    url = httpx.URL("http://webservice?u=phrase with spaces")333    assert str(url) == "http://webservice?u=phrase%20with%20spaces"334335336def test_query_with_mixed_percent_encoding():337    # When a mix of encoded and unencoded characters are present,338    # characters that require percent encoding should be encoded,339    # while existing sequences should not be double encoded.340    url = httpx.URL("http://webservice?u=phrase%20with spaces")341    assert str(url) == "http://webservice?u=phrase%20with%20spaces"342343344# Tests for invalid URLs345346347def test_url_invalid_hostname():348    """349    Ensure that invalid URLs raise an `httpx.InvalidURL` exception.350    """351    with pytest.raises(httpx.InvalidURL):352        httpx.URL("https://😇/")353354355def test_url_excessively_long_url():356    with pytest.raises(httpx.InvalidURL) as exc:357        httpx.URL("https://www.example.com/" + "x" * 100_000)358    assert str(exc.value) == "URL too long"359360361def test_url_excessively_long_component():362    with pytest.raises(httpx.InvalidURL) as exc:363        httpx.URL("https://www.example.com", path="/" + "x" * 100_000)364    assert str(exc.value) == "URL component 'path' too long"365366367def test_url_non_printing_character_in_url():368    with pytest.raises(httpx.InvalidURL) as exc:369        httpx.URL("https://www.example.com/\n")370    assert str(exc.value) == "Invalid non-printable ASCII character in URL"371372373def test_url_non_printing_character_in_component():374    with pytest.raises(httpx.InvalidURL) as exc:375        httpx.URL("https://www.example.com", path="/\n")376    assert (377        str(exc.value)378        == "Invalid non-printable ASCII character in URL component 'path'"379    )380381382# Test for url components383384385def test_url_with_components():386    url = httpx.URL(scheme="https", host="www.example.com", path="/")387388    assert url.scheme == "https"389    assert url.userinfo == b""390    assert url.host == "www.example.com"391    assert url.port is None392    assert url.path == "/"393    assert url.query == b""394    assert url.fragment == ""395396    assert str(url) == "https://www.example.com/"397398399def test_urlparse_with_invalid_component():400    with pytest.raises(TypeError) as exc:401        httpx.URL(scheme="https", host="www.example.com", incorrect="/")402    assert str(exc.value) == "'incorrect' is an invalid keyword argument for URL()"403404405def test_urlparse_with_invalid_scheme():406    with pytest.raises(httpx.InvalidURL) as exc:407        httpx.URL(scheme="~", host="www.example.com", path="/")408    assert str(exc.value) == "Invalid URL component 'scheme'"409410411def test_urlparse_with_invalid_path():412    with pytest.raises(httpx.InvalidURL) as exc:413        httpx.URL(scheme="https", host="www.example.com", path="abc")414    assert str(exc.value) == "For absolute URLs, path must be empty or begin with '/'"415416    with pytest.raises(httpx.InvalidURL) as exc:417        httpx.URL(path="//abc")418    assert (419        str(exc.value)420        == "URLs with no authority component cannot have a path starting with '//'"421    )422423    with pytest.raises(httpx.InvalidURL) as exc:424        httpx.URL(path=":abc")425    assert (426        str(exc.value)427        == "URLs with no scheme component cannot have a path starting with ':'"428    )429430431def test_url_with_relative_path():432    # This path would be invalid for an absolute URL, but is valid as a relative URL.433    url = httpx.URL(path="abc")434    assert url.path == "abc"435436437# Tests for `httpx.URL` python built-in operators.438439440def test_url_eq_str():441    """442    Ensure that `httpx.URL` supports the equality operator.443    """444    url = httpx.URL("https://example.org:123/path/to/somewhere?abc=123#anchor")445    assert url == "https://example.org:123/path/to/somewhere?abc=123#anchor"446    assert str(url) == url447448449def test_url_set():450    """451    Ensure that `httpx.URL` instances can be used in sets.452    """453    urls = (454        httpx.URL("http://example.org:123/path/to/somewhere"),455        httpx.URL("http://example.org:123/path/to/somewhere/else"),456    )457458    url_set = set(urls)459460    assert all(url in urls for url in url_set)461462463# Tests for TypeErrors when instantiating `httpx.URL`.464465466def test_url_invalid_type():467    """468    Ensure that invalid types on `httpx.URL()` raise a `TypeError`.469    """470471    class ExternalURLClass:  # representing external URL class472        pass473474    with pytest.raises(TypeError):475        httpx.URL(ExternalURLClass())  # type: ignore476477478def test_url_with_invalid_component():479    with pytest.raises(TypeError) as exc:480        httpx.URL(scheme="https", host="www.example.com", incorrect="/")481    assert str(exc.value) == "'incorrect' is an invalid keyword argument for URL()"482483484# Tests for `URL.join()`.485486487def test_url_join():488    """489    Some basic URL joining tests.490    """491    url = httpx.URL("https://example.org:123/path/to/somewhere")492    assert url.join("/somewhere-else") == "https://example.org:123/somewhere-else"493    assert (494        url.join("somewhere-else") == "https://example.org:123/path/to/somewhere-else"495    )496    assert (497        url.join("../somewhere-else") == "https://example.org:123/path/somewhere-else"498    )499    assert url.join("../../somewhere-else") == "https://example.org:123/somewhere-else"500501502def test_relative_url_join():503    url = httpx.URL("/path/to/somewhere")504    assert url.join("/somewhere-else") == "/somewhere-else"505    assert url.join("somewhere-else") == "/path/to/somewhere-else"506    assert url.join("../somewhere-else") == "/path/somewhere-else"507    assert url.join("../../somewhere-else") == "/somewhere-else"508509510def test_url_join_rfc3986():511    """512    URL joining tests, as-per reference examples in RFC 3986.513514    https://tools.ietf.org/html/rfc3986#section-5.4515    """516517    url = httpx.URL("http://example.com/b/c/d;p?q")518519    assert url.join("g") == "http://example.com/b/c/g"520    assert url.join("./g") == "http://example.com/b/c/g"521    assert url.join("g/") == "http://example.com/b/c/g/"522    assert url.join("/g") == "http://example.com/g"523    assert url.join("//g") == "http://g"524    assert url.join("?y") == "http://example.com/b/c/d;p?y"525    assert url.join("g?y") == "http://example.com/b/c/g?y"526    assert url.join("#s") == "http://example.com/b/c/d;p?q#s"527    assert url.join("g#s") == "http://example.com/b/c/g#s"528    assert url.join("g?y#s") == "http://example.com/b/c/g?y#s"529    assert url.join(";x") == "http://example.com/b/c/;x"530    assert url.join("g;x") == "http://example.com/b/c/g;x"531    assert url.join("g;x?y#s") == "http://example.com/b/c/g;x?y#s"532    assert url.join("") == "http://example.com/b/c/d;p?q"533    assert url.join(".") == "http://example.com/b/c/"534    assert url.join("./") == "http://example.com/b/c/"535    assert url.join("..") == "http://example.com/b/"536    assert url.join("../") == "http://example.com/b/"537    assert url.join("../g") == "http://example.com/b/g"538    assert url.join("../..") == "http://example.com/"539    assert url.join("../../") == "http://example.com/"540    assert url.join("../../g") == "http://example.com/g"541542    assert url.join("../../../g") == "http://example.com/g"543    assert url.join("../../../../g") == "http://example.com/g"544545    assert url.join("/./g") == "http://example.com/g"546    assert url.join("/../g") == "http://example.com/g"547    assert url.join("g.") == "http://example.com/b/c/g."548    assert url.join(".g") == "http://example.com/b/c/.g"549    assert url.join("g..") == "http://example.com/b/c/g.."550    assert url.join("..g") == "http://example.com/b/c/..g"551552    assert url.join("./../g") == "http://example.com/b/g"553    assert url.join("./g/.") == "http://example.com/b/c/g/"554    assert url.join("g/./h") == "http://example.com/b/c/g/h"555    assert url.join("g/../h") == "http://example.com/b/c/h"556    assert url.join("g;x=1/./y") == "http://example.com/b/c/g;x=1/y"557    assert url.join("g;x=1/../y") == "http://example.com/b/c/y"558559    assert url.join("g?y/./x") == "http://example.com/b/c/g?y/./x"560    assert url.join("g?y/../x") == "http://example.com/b/c/g?y/../x"561    assert url.join("g#s/./x") == "http://example.com/b/c/g#s/./x"562    assert url.join("g#s/../x") == "http://example.com/b/c/g#s/../x"563564565def test_resolution_error_1833():566    """567    See https://github.com/encode/httpx/issues/1833568    """569    url = httpx.URL("https://example.com/?[]")570    assert url.join("/") == "https://example.com/"571572573# Tests for `URL.copy_with()`.574575576def test_copy_with():577    url = httpx.URL("https://www.example.com/")578    assert str(url) == "https://www.example.com/"579580    url = url.copy_with()581    assert str(url) == "https://www.example.com/"582583    url = url.copy_with(scheme="http")584    assert str(url) == "http://www.example.com/"585586    url = url.copy_with(netloc=b"example.com")587    assert str(url) == "http://example.com/"588589    url = url.copy_with(path="/abc")590    assert str(url) == "http://example.com/abc"591592593def test_url_copywith_authority_subcomponents():594    copy_with_kwargs = {595        "username": "username",596        "password": "password",597        "port": 444,598        "host": "example.net",599    }600    url = httpx.URL("https://example.org")601    new = url.copy_with(**copy_with_kwargs)602    assert str(new) == "https://username:password@example.net:444"603604605def test_url_copywith_netloc():606    copy_with_kwargs = {607        "netloc": b"example.net:444",608    }609    url = httpx.URL("https://example.org")610    new = url.copy_with(**copy_with_kwargs)611    assert str(new) == "https://example.net:444"612613614def test_url_copywith_userinfo_subcomponents():615    copy_with_kwargs = {616        "username": "tom@example.org",617        "password": "abc123@ %",618    }619    url = httpx.URL("https://example.org")620    new = url.copy_with(**copy_with_kwargs)621    assert str(new) == "https://tom%40example.org:abc123%40%20%25@example.org"622    assert new.username == "tom@example.org"623    assert new.password == "abc123@ %"624    assert new.userinfo == b"tom%40example.org:abc123%40%20%25"625626627def test_url_copywith_invalid_component():628    url = httpx.URL("https://example.org")629    with pytest.raises(TypeError):630        url.copy_with(pathh="/incorrect-spelling")631    with pytest.raises(TypeError):632        url.copy_with(userinfo="should be bytes")633634635def test_url_copywith_urlencoded_path():636    url = httpx.URL("https://example.org")637    url = url.copy_with(path="/path to somewhere")638    assert url.path == "/path to somewhere"639    assert url.query == b""640    assert url.raw_path == b"/path%20to%20somewhere"641642643def test_url_copywith_query():644    url = httpx.URL("https://example.org")645    url = url.copy_with(query=b"a=123")646    assert url.path == "/"647    assert url.query == b"a=123"648    assert url.raw_path == b"/?a=123"649650651def test_url_copywith_raw_path():652    url = httpx.URL("https://example.org")653    url = url.copy_with(raw_path=b"/some/path")654    assert url.path == "/some/path"655    assert url.query == b""656    assert url.raw_path == b"/some/path"657658    url = httpx.URL("https://example.org")659    url = url.copy_with(raw_path=b"/some/path?")660    assert url.path == "/some/path"661    assert url.query == b""662    assert url.raw_path == b"/some/path?"663664    url = httpx.URL("https://example.org")665    url = url.copy_with(raw_path=b"/some/path?a=123")666    assert url.path == "/some/path"667    assert url.query == b"a=123"668    assert url.raw_path == b"/some/path?a=123"669670671def test_url_copywith_security():672    """673    Prevent unexpected changes on URL after calling copy_with (CVE-2021-41945)674    """675    with pytest.raises(httpx.InvalidURL):676        httpx.URL("https://u:p@[invalid!]//evilHost/path?t=w#tw")677678    url = httpx.URL("https://example.com/path?t=w#tw")679    bad = "https://xxxx:xxxx@xxxxxxx/xxxxx/xxx?x=x#xxxxx"680    with pytest.raises(httpx.InvalidURL):681        url.copy_with(scheme=bad)682683684# Tests for copy-modifying-parameters methods.685#686# `URL.copy_set_param()`687# `URL.copy_add_param()`688# `URL.copy_remove_param()`689# `URL.copy_merge_params()`690691692def test_url_set_param_manipulation():693    """694    Some basic URL query parameter manipulation.695    """696    url = httpx.URL("https://example.org:123/?a=123")697    assert url.copy_set_param("a", "456") == "https://example.org:123/?a=456"698699700def test_url_add_param_manipulation():701    """702    Some basic URL query parameter manipulation.703    """704    url = httpx.URL("https://example.org:123/?a=123")705    assert url.copy_add_param("a", "456") == "https://example.org:123/?a=123&a=456"706707708def test_url_remove_param_manipulation():709    """710    Some basic URL query parameter manipulation.711    """712    url = httpx.URL("https://example.org:123/?a=123")713    assert url.copy_remove_param("a") == "https://example.org:123/"714715716def test_url_merge_params_manipulation():717    """718    Some basic URL query parameter manipulation.719    """720    url = httpx.URL("https://example.org:123/?a=123")721    assert url.copy_merge_params({"b": "456"}) == "https://example.org:123/?a=123&b=456"722723724# Tests for IDNA hostname support.725726727@pytest.mark.parametrize(728    "given,idna,host,raw_host,scheme,port",729    [730        (731            "http://中国.icom.museum:80/",732            "http://xn--fiqs8s.icom.museum:80/",733            "中国.icom.museum",734            b"xn--fiqs8s.icom.museum",735            "http",736            None,737        ),738        (739            "http://Königsgäßchen.de",740            "http://xn--knigsgchen-b4a3dun.de",741            "königsgäßchen.de",742            b"xn--knigsgchen-b4a3dun.de",743            "http",744            None,745        ),746        (747            "https://faß.de",748            "https://xn--fa-hia.de",749            "faß.de",750            b"xn--fa-hia.de",751            "https",752            None,753        ),754        (755            "https://βόλος.com:443",756            "https://xn--nxasmm1c.com:443",757            "βόλος.com",758            b"xn--nxasmm1c.com",759            "https",760            None,761        ),762        (763            "http://ශ්‍රී.com:444",764            "http://xn--10cl1a0b660p.com:444",765            "ශ්‍රී.com",766            b"xn--10cl1a0b660p.com",767            "http",768            444,769        ),770        (771            "https://نامه‌ای.com:4433",772            "https://xn--mgba3gch31f060k.com:4433",773            "نامه‌ای.com",774            b"xn--mgba3gch31f060k.com",775            "https",776            4433,777        ),778    ],779    ids=[780        "http_with_port",781        "unicode_tr46_compat",782        "https_without_port",783        "https_with_port",784        "http_with_custom_port",785        "https_with_custom_port",786    ],787)788def test_idna_url(given, idna, host, raw_host, scheme, port):789    url = httpx.URL(given)790    assert url == httpx.URL(idna)791    assert url.host == host792    assert url.raw_host == raw_host793    assert url.scheme == scheme794    assert url.port == port795796797def test_url_unescaped_idna_host():798    url = httpx.URL("https://中国.icom.museum/")799    assert url.raw_host == b"xn--fiqs8s.icom.museum"800801802def test_url_escaped_idna_host():803    url = httpx.URL("https://xn--fiqs8s.icom.museum/")804    assert url.raw_host == b"xn--fiqs8s.icom.museum"805806807def test_url_invalid_idna_host():808    with pytest.raises(httpx.InvalidURL) as exc:809        httpx.URL("https://☃.com/")810    assert str(exc.value) == "Invalid IDNA hostname: '☃.com'"811812813# Tests for IPv4 hostname support.814815816def test_url_valid_ipv4():817    url = httpx.URL("https://1.2.3.4/")818    assert url.host == "1.2.3.4"819820821def test_url_invalid_ipv4():822    with pytest.raises(httpx.InvalidURL) as exc:823        httpx.URL("https://999.999.999.999/")824    assert str(exc.value) == "Invalid IPv4 address: '999.999.999.999'"825826827# Tests for IPv6 hostname support.828829830def test_ipv6_url():831    url = httpx.URL("http://[::ffff:192.168.0.1]:5678/")832833    assert url.host == "::ffff:192.168.0.1"834    assert url.netloc == b"[::ffff:192.168.0.1]:5678"835836837def test_url_valid_ipv6():838    url = httpx.URL("https://[2001:db8::ff00:42:8329]/")839    assert url.host == "2001:db8::ff00:42:8329"840841842def test_url_invalid_ipv6():843    with pytest.raises(httpx.InvalidURL) as exc:844        httpx.URL("https://[2001]/")845    assert str(exc.value) == "Invalid IPv6 address: '[2001]'"846847848@pytest.mark.parametrize("host", ["[::ffff:192.168.0.1]", "::ffff:192.168.0.1"])849def test_ipv6_url_from_raw_url(host):850    url = httpx.URL(scheme="https", host=host, port=443, path="/")851852    assert url.host == "::ffff:192.168.0.1"853    assert url.netloc == b"[::ffff:192.168.0.1]"854    assert str(url) == "https://[::ffff:192.168.0.1]/"855856857@pytest.mark.parametrize(858    "url_str",859    [860        "http://127.0.0.1:1234",861        "http://example.com:1234",862        "http://[::ffff:127.0.0.1]:1234",863    ],864)865@pytest.mark.parametrize("new_host", ["[::ffff:192.168.0.1]", "::ffff:192.168.0.1"])866def test_ipv6_url_copy_with_host(url_str, new_host):867    url = httpx.URL(url_str).copy_with(host=new_host)868869    assert url.host == "::ffff:192.168.0.1"870    assert url.netloc == b"[::ffff:192.168.0.1]:1234"871    assert str(url) == "http://[::ffff:192.168.0.1]:1234"872873874# Test for deprecated API875876877def test_url_raw_compatibility():878    """879    Test case for the (to-be-deprecated) `url.raw` accessor.880    """881    url = httpx.URL("https://www.example.com/path")882    scheme, host, port, raw_path = url.raw883884    assert scheme == b"https"885    assert host == b"www.example.com"886    assert port is None887    assert raw_path == b"/path"