Skip to content
Myr

test_url.py

This file

Path

tests/models/test_url.py

883 lines · 26.5 KiB · Python

Last changed by

Improve InvalidURL error message. (#3250)Tom Christiebefore adoption7c0cda1

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%20le.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) == (371        "Invalid non-printable ASCII character in URL, '\\n' at position 24."372    )373374375def test_url_non_printing_character_in_component():376    with pytest.raises(httpx.InvalidURL) as exc:377        httpx.URL("https://www.example.com", path="/\n")378    assert str(exc.value) == (379        "Invalid non-printable ASCII character in URL path component, "380        "'\\n' at position 1."381    )382383384# Test for url components385386387def test_url_with_components():388    url = httpx.URL(scheme="https", host="www.example.com", path="/")389390    assert url.scheme == "https"391    assert url.userinfo == b""392    assert url.host == "www.example.com"393    assert url.port is None394    assert url.path == "/"395    assert url.query == b""396    assert url.fragment == ""397398    assert str(url) == "https://www.example.com/"399400401def test_urlparse_with_invalid_component():402    with pytest.raises(TypeError) as exc:403        httpx.URL(scheme="https", host="www.example.com", incorrect="/")404    assert str(exc.value) == "'incorrect' is an invalid keyword argument for URL()"405406407def test_urlparse_with_invalid_scheme():408    with pytest.raises(httpx.InvalidURL) as exc:409        httpx.URL(scheme="~", host="www.example.com", path="/")410    assert str(exc.value) == "Invalid URL component 'scheme'"411412413def test_urlparse_with_invalid_path():414    with pytest.raises(httpx.InvalidURL) as exc:415        httpx.URL(scheme="https", host="www.example.com", path="abc")416    assert str(exc.value) == "For absolute URLs, path must be empty or begin with '/'"417418    with pytest.raises(httpx.InvalidURL) as exc:419        httpx.URL(path="//abc")420    assert str(exc.value) == "Relative URLs cannot have a path starting with '//'"421422    with pytest.raises(httpx.InvalidURL) as exc:423        httpx.URL(path=":abc")424    assert str(exc.value) == "Relative URLs cannot have a path starting with ':'"425426427def test_url_with_relative_path():428    # This path would be invalid for an absolute URL, but is valid as a relative URL.429    url = httpx.URL(path="abc")430    assert url.path == "abc"431432433# Tests for `httpx.URL` python built-in operators.434435436def test_url_eq_str():437    """438    Ensure that `httpx.URL` supports the equality operator.439    """440    url = httpx.URL("https://example.org:123/path/to/somewhere?abc=123#anchor")441    assert url == "https://example.org:123/path/to/somewhere?abc=123#anchor"442    assert str(url) == url443444445def test_url_set():446    """447    Ensure that `httpx.URL` instances can be used in sets.448    """449    urls = (450        httpx.URL("http://example.org:123/path/to/somewhere"),451        httpx.URL("http://example.org:123/path/to/somewhere/else"),452    )453454    url_set = set(urls)455456    assert all(url in urls for url in url_set)457458459# Tests for TypeErrors when instantiating `httpx.URL`.460461462def test_url_invalid_type():463    """464    Ensure that invalid types on `httpx.URL()` raise a `TypeError`.465    """466467    class ExternalURLClass:  # representing external URL class468        pass469470    with pytest.raises(TypeError):471        httpx.URL(ExternalURLClass())  # type: ignore472473474def test_url_with_invalid_component():475    with pytest.raises(TypeError) as exc:476        httpx.URL(scheme="https", host="www.example.com", incorrect="/")477    assert str(exc.value) == "'incorrect' is an invalid keyword argument for URL()"478479480# Tests for `URL.join()`.481482483def test_url_join():484    """485    Some basic URL joining tests.486    """487    url = httpx.URL("https://example.org:123/path/to/somewhere")488    assert url.join("/somewhere-else") == "https://example.org:123/somewhere-else"489    assert (490        url.join("somewhere-else") == "https://example.org:123/path/to/somewhere-else"491    )492    assert (493        url.join("../somewhere-else") == "https://example.org:123/path/somewhere-else"494    )495    assert url.join("../../somewhere-else") == "https://example.org:123/somewhere-else"496497498def test_relative_url_join():499    url = httpx.URL("/path/to/somewhere")500    assert url.join("/somewhere-else") == "/somewhere-else"501    assert url.join("somewhere-else") == "/path/to/somewhere-else"502    assert url.join("../somewhere-else") == "/path/somewhere-else"503    assert url.join("../../somewhere-else") == "/somewhere-else"504505506def test_url_join_rfc3986():507    """508    URL joining tests, as-per reference examples in RFC 3986.509510    https://tools.ietf.org/html/rfc3986#section-5.4511    """512513    url = httpx.URL("http://example.com/b/c/d;p?q")514515    assert url.join("g") == "http://example.com/b/c/g"516    assert url.join("./g") == "http://example.com/b/c/g"517    assert url.join("g/") == "http://example.com/b/c/g/"518    assert url.join("/g") == "http://example.com/g"519    assert url.join("//g") == "http://g"520    assert url.join("?y") == "http://example.com/b/c/d;p?y"521    assert url.join("g?y") == "http://example.com/b/c/g?y"522    assert url.join("#s") == "http://example.com/b/c/d;p?q#s"523    assert url.join("g#s") == "http://example.com/b/c/g#s"524    assert url.join("g?y#s") == "http://example.com/b/c/g?y#s"525    assert url.join(";x") == "http://example.com/b/c/;x"526    assert url.join("g;x") == "http://example.com/b/c/g;x"527    assert url.join("g;x?y#s") == "http://example.com/b/c/g;x?y#s"528    assert url.join("") == "http://example.com/b/c/d;p?q"529    assert url.join(".") == "http://example.com/b/c/"530    assert url.join("./") == "http://example.com/b/c/"531    assert url.join("..") == "http://example.com/b/"532    assert url.join("../") == "http://example.com/b/"533    assert url.join("../g") == "http://example.com/b/g"534    assert url.join("../..") == "http://example.com/"535    assert url.join("../../") == "http://example.com/"536    assert url.join("../../g") == "http://example.com/g"537538    assert url.join("../../../g") == "http://example.com/g"539    assert url.join("../../../../g") == "http://example.com/g"540541    assert url.join("/./g") == "http://example.com/g"542    assert url.join("/../g") == "http://example.com/g"543    assert url.join("g.") == "http://example.com/b/c/g."544    assert url.join(".g") == "http://example.com/b/c/.g"545    assert url.join("g..") == "http://example.com/b/c/g.."546    assert url.join("..g") == "http://example.com/b/c/..g"547548    assert url.join("./../g") == "http://example.com/b/g"549    assert url.join("./g/.") == "http://example.com/b/c/g/"550    assert url.join("g/./h") == "http://example.com/b/c/g/h"551    assert url.join("g/../h") == "http://example.com/b/c/h"552    assert url.join("g;x=1/./y") == "http://example.com/b/c/g;x=1/y"553    assert url.join("g;x=1/../y") == "http://example.com/b/c/y"554555    assert url.join("g?y/./x") == "http://example.com/b/c/g?y/./x"556    assert url.join("g?y/../x") == "http://example.com/b/c/g?y/../x"557    assert url.join("g#s/./x") == "http://example.com/b/c/g#s/./x"558    assert url.join("g#s/../x") == "http://example.com/b/c/g#s/../x"559560561def test_resolution_error_1833():562    """563    See https://github.com/encode/httpx/issues/1833564    """565    url = httpx.URL("https://example.com/?[]")566    assert url.join("/") == "https://example.com/"567568569# Tests for `URL.copy_with()`.570571572def test_copy_with():573    url = httpx.URL("https://www.example.com/")574    assert str(url) == "https://www.example.com/"575576    url = url.copy_with()577    assert str(url) == "https://www.example.com/"578579    url = url.copy_with(scheme="http")580    assert str(url) == "http://www.example.com/"581582    url = url.copy_with(netloc=b"example.com")583    assert str(url) == "http://example.com/"584585    url = url.copy_with(path="/abc")586    assert str(url) == "http://example.com/abc"587588589def test_url_copywith_authority_subcomponents():590    copy_with_kwargs = {591        "username": "username",592        "password": "password",593        "port": 444,594        "host": "example.net",595    }596    url = httpx.URL("https://example.org")597    new = url.copy_with(**copy_with_kwargs)598    assert str(new) == "https://username:password@example.net:444"599600601def test_url_copywith_netloc():602    copy_with_kwargs = {603        "netloc": b"example.net:444",604    }605    url = httpx.URL("https://example.org")606    new = url.copy_with(**copy_with_kwargs)607    assert str(new) == "https://example.net:444"608609610def test_url_copywith_userinfo_subcomponents():611    copy_with_kwargs = {612        "username": "tom@example.org",613        "password": "abc123@ %",614    }615    url = httpx.URL("https://example.org")616    new = url.copy_with(**copy_with_kwargs)617    assert str(new) == "https://tom%40example.org:abc123%40%20%25@example.org"618    assert new.username == "tom@example.org"619    assert new.password == "abc123@ %"620    assert new.userinfo == b"tom%40example.org:abc123%40%20%25"621622623def test_url_copywith_invalid_component():624    url = httpx.URL("https://example.org")625    with pytest.raises(TypeError):626        url.copy_with(pathh="/incorrect-spelling")627    with pytest.raises(TypeError):628        url.copy_with(userinfo="should be bytes")629630631def test_url_copywith_urlencoded_path():632    url = httpx.URL("https://example.org")633    url = url.copy_with(path="/path to somewhere")634    assert url.path == "/path to somewhere"635    assert url.query == b""636    assert url.raw_path == b"/path%20to%20somewhere"637638639def test_url_copywith_query():640    url = httpx.URL("https://example.org")641    url = url.copy_with(query=b"a=123")642    assert url.path == "/"643    assert url.query == b"a=123"644    assert url.raw_path == b"/?a=123"645646647def test_url_copywith_raw_path():648    url = httpx.URL("https://example.org")649    url = url.copy_with(raw_path=b"/some/path")650    assert url.path == "/some/path"651    assert url.query == b""652    assert url.raw_path == b"/some/path"653654    url = httpx.URL("https://example.org")655    url = url.copy_with(raw_path=b"/some/path?")656    assert url.path == "/some/path"657    assert url.query == b""658    assert url.raw_path == b"/some/path?"659660    url = httpx.URL("https://example.org")661    url = url.copy_with(raw_path=b"/some/path?a=123")662    assert url.path == "/some/path"663    assert url.query == b"a=123"664    assert url.raw_path == b"/some/path?a=123"665666667def test_url_copywith_security():668    """669    Prevent unexpected changes on URL after calling copy_with (CVE-2021-41945)670    """671    with pytest.raises(httpx.InvalidURL):672        httpx.URL("https://u:p@[invalid!]//evilHost/path?t=w#tw")673674    url = httpx.URL("https://example.com/path?t=w#tw")675    bad = "https://xxxx:xxxx@xxxxxxx/xxxxx/xxx?x=x#xxxxx"676    with pytest.raises(httpx.InvalidURL):677        url.copy_with(scheme=bad)678679680# Tests for copy-modifying-parameters methods.681#682# `URL.copy_set_param()`683# `URL.copy_add_param()`684# `URL.copy_remove_param()`685# `URL.copy_merge_params()`686687688def test_url_set_param_manipulation():689    """690    Some basic URL query parameter manipulation.691    """692    url = httpx.URL("https://example.org:123/?a=123")693    assert url.copy_set_param("a", "456") == "https://example.org:123/?a=456"694695696def test_url_add_param_manipulation():697    """698    Some basic URL query parameter manipulation.699    """700    url = httpx.URL("https://example.org:123/?a=123")701    assert url.copy_add_param("a", "456") == "https://example.org:123/?a=123&a=456"702703704def test_url_remove_param_manipulation():705    """706    Some basic URL query parameter manipulation.707    """708    url = httpx.URL("https://example.org:123/?a=123")709    assert url.copy_remove_param("a") == "https://example.org:123/"710711712def test_url_merge_params_manipulation():713    """714    Some basic URL query parameter manipulation.715    """716    url = httpx.URL("https://example.org:123/?a=123")717    assert url.copy_merge_params({"b": "456"}) == "https://example.org:123/?a=123&b=456"718719720# Tests for IDNA hostname support.721722723@pytest.mark.parametrize(724    "given,idna,host,raw_host,scheme,port",725    [726        (727            "http://中国.icom.museum:80/",728            "http://xn--fiqs8s.icom.museum:80/",729            "中国.icom.museum",730            b"xn--fiqs8s.icom.museum",731            "http",732            None,733        ),734        (735            "http://Königsgäßchen.de",736            "http://xn--knigsgchen-b4a3dun.de",737            "königsgäßchen.de",738            b"xn--knigsgchen-b4a3dun.de",739            "http",740            None,741        ),742        (743            "https://faß.de",744            "https://xn--fa-hia.de",745            "faß.de",746            b"xn--fa-hia.de",747            "https",748            None,749        ),750        (751            "https://βόλος.com:443",752            "https://xn--nxasmm1c.com:443",753            "βόλος.com",754            b"xn--nxasmm1c.com",755            "https",756            None,757        ),758        (759            "http://ශ්‍රී.com:444",760            "http://xn--10cl1a0b660p.com:444",761            "ශ්‍රී.com",762            b"xn--10cl1a0b660p.com",763            "http",764            444,765        ),766        (767            "https://نامه‌ای.com:4433",768            "https://xn--mgba3gch31f060k.com:4433",769            "نامه‌ای.com",770            b"xn--mgba3gch31f060k.com",771            "https",772            4433,773        ),774    ],775    ids=[776        "http_with_port",777        "unicode_tr46_compat",778        "https_without_port",779        "https_with_port",780        "http_with_custom_port",781        "https_with_custom_port",782    ],783)784def test_idna_url(given, idna, host, raw_host, scheme, port):785    url = httpx.URL(given)786    assert url == httpx.URL(idna)787    assert url.host == host788    assert url.raw_host == raw_host789    assert url.scheme == scheme790    assert url.port == port791792793def test_url_unescaped_idna_host():794    url = httpx.URL("https://中国.icom.museum/")795    assert url.raw_host == b"xn--fiqs8s.icom.museum"796797798def test_url_escaped_idna_host():799    url = httpx.URL("https://xn--fiqs8s.icom.museum/")800    assert url.raw_host == b"xn--fiqs8s.icom.museum"801802803def test_url_invalid_idna_host():804    with pytest.raises(httpx.InvalidURL) as exc:805        httpx.URL("https://☃.com/")806    assert str(exc.value) == "Invalid IDNA hostname: '☃.com'"807808809# Tests for IPv4 hostname support.810811812def test_url_valid_ipv4():813    url = httpx.URL("https://1.2.3.4/")814    assert url.host == "1.2.3.4"815816817def test_url_invalid_ipv4():818    with pytest.raises(httpx.InvalidURL) as exc:819        httpx.URL("https://999.999.999.999/")820    assert str(exc.value) == "Invalid IPv4 address: '999.999.999.999'"821822823# Tests for IPv6 hostname support.824825826def test_ipv6_url():827    url = httpx.URL("http://[::ffff:192.168.0.1]:5678/")828829    assert url.host == "::ffff:192.168.0.1"830    assert url.netloc == b"[::ffff:192.168.0.1]:5678"831832833def test_url_valid_ipv6():834    url = httpx.URL("https://[2001:db8::ff00:42:8329]/")835    assert url.host == "2001:db8::ff00:42:8329"836837838def test_url_invalid_ipv6():839    with pytest.raises(httpx.InvalidURL) as exc:840        httpx.URL("https://[2001]/")841    assert str(exc.value) == "Invalid IPv6 address: '[2001]'"842843844@pytest.mark.parametrize("host", ["[::ffff:192.168.0.1]", "::ffff:192.168.0.1"])845def test_ipv6_url_from_raw_url(host):846    url = httpx.URL(scheme="https", host=host, port=443, path="/")847848    assert url.host == "::ffff:192.168.0.1"849    assert url.netloc == b"[::ffff:192.168.0.1]"850    assert str(url) == "https://[::ffff:192.168.0.1]/"851852853@pytest.mark.parametrize(854    "url_str",855    [856        "http://127.0.0.1:1234",857        "http://example.com:1234",858        "http://[::ffff:127.0.0.1]:1234",859    ],860)861@pytest.mark.parametrize("new_host", ["[::ffff:192.168.0.1]", "::ffff:192.168.0.1"])862def test_ipv6_url_copy_with_host(url_str, new_host):863    url = httpx.URL(url_str).copy_with(host=new_host)864865    assert url.host == "::ffff:192.168.0.1"866    assert url.netloc == b"[::ffff:192.168.0.1]:1234"867    assert str(url) == "http://[::ffff:192.168.0.1]:1234"868869870# Test for deprecated API871872873def test_url_raw_compatibility():874    """875    Test case for the (to-be-deprecated) `url.raw` accessor.876    """877    url = httpx.URL("https://www.example.com/path")878    scheme, host, port, raw_path = url.raw879880    assert scheme == b"https"881    assert host == b"www.example.com"882    assert port is None883    assert raw_path == b"/path"