Skip to content
Myr

test_proxies.py

This file

Path

tests/client/test_proxies.py

286 lines · 10.1 KiB · Python

Last changed by

Drop RawURL (#2241)Tom Christiebefore adoption9baf3a6

History of this file

Take it

1import httpcore2import pytest34import httpx5from httpx._utils import URLPattern678def url_to_origin(url: str):9    """10    Given a URL string, return the origin in the raw tuple format that11    `httpcore` uses for it's representation.12    """13    u = httpx.URL(url)14    return httpcore.URL(scheme=u.raw_scheme, host=u.raw_host, port=u.port, target="/")151617@pytest.mark.parametrize(18    ["proxies", "expected_proxies"],19    [20        ("http://127.0.0.1", [("all://", "http://127.0.0.1")]),21        ({"all://": "http://127.0.0.1"}, [("all://", "http://127.0.0.1")]),22        (23            {"http://": "http://127.0.0.1", "https://": "https://127.0.0.1"},24            [("http://", "http://127.0.0.1"), ("https://", "https://127.0.0.1")],25        ),26        (httpx.Proxy("http://127.0.0.1"), [("all://", "http://127.0.0.1")]),27        (28            {29                "https://": httpx.Proxy("https://127.0.0.1"),30                "all://": "http://127.0.0.1",31            },32            [("all://", "http://127.0.0.1"), ("https://", "https://127.0.0.1")],33        ),34    ],35)36def test_proxies_parameter(proxies, expected_proxies):37    client = httpx.Client(proxies=proxies)3839    for proxy_key, url in expected_proxies:40        pattern = URLPattern(proxy_key)41        assert pattern in client._mounts42        proxy = client._mounts[pattern]43        assert isinstance(proxy, httpx.HTTPTransport)44        assert isinstance(proxy._pool, httpcore.HTTPProxy)45        assert proxy._pool._proxy_url == url_to_origin(url)4647    assert len(expected_proxies) == len(client._mounts)484950def test_socks_proxy():51    url = httpx.URL("http://www.example.com")5253    client = httpx.Client(proxies="socks5://localhost/")54    transport = client._transport_for_url(url)55    assert isinstance(transport, httpx.HTTPTransport)56    assert isinstance(transport._pool, httpcore.SOCKSProxy)5758    async_client = httpx.AsyncClient(proxies="socks5://localhost/")59    async_transport = async_client._transport_for_url(url)60    assert isinstance(async_transport, httpx.AsyncHTTPTransport)61    assert isinstance(async_transport._pool, httpcore.AsyncSOCKSProxy)626364PROXY_URL = "http://[::1]"656667@pytest.mark.parametrize(68    ["url", "proxies", "expected"],69    [70        ("http://example.com", None, None),71        ("http://example.com", {}, None),72        ("http://example.com", {"https://": PROXY_URL}, None),73        ("http://example.com", {"http://example.net": PROXY_URL}, None),74        # Using "*" should match any domain name.75        ("http://example.com", {"http://*": PROXY_URL}, PROXY_URL),76        ("https://example.com", {"http://*": PROXY_URL}, None),77        # Using "example.com" should match example.com, but not www.example.com78        ("http://example.com", {"http://example.com": PROXY_URL}, PROXY_URL),79        ("http://www.example.com", {"http://example.com": PROXY_URL}, None),80        # Using "*.example.com" should match www.example.com, but not example.com81        ("http://example.com", {"http://*.example.com": PROXY_URL}, None),82        ("http://www.example.com", {"http://*.example.com": PROXY_URL}, PROXY_URL),83        # Using "*example.com" should match example.com and www.example.com84        ("http://example.com", {"http://*example.com": PROXY_URL}, PROXY_URL),85        ("http://www.example.com", {"http://*example.com": PROXY_URL}, PROXY_URL),86        ("http://wwwexample.com", {"http://*example.com": PROXY_URL}, None),87        # ...88        ("http://example.com:443", {"http://example.com": PROXY_URL}, PROXY_URL),89        ("http://example.com", {"all://": PROXY_URL}, PROXY_URL),90        ("http://example.com", {"all://": PROXY_URL, "http://example.com": None}, None),91        ("http://example.com", {"http://": PROXY_URL}, PROXY_URL),92        ("http://example.com", {"all://example.com": PROXY_URL}, PROXY_URL),93        ("http://example.com", {"http://example.com": PROXY_URL}, PROXY_URL),94        ("http://example.com", {"http://example.com:80": PROXY_URL}, PROXY_URL),95        ("http://example.com:8080", {"http://example.com:8080": PROXY_URL}, PROXY_URL),96        ("http://example.com:8080", {"http://example.com": PROXY_URL}, PROXY_URL),97        (98            "http://example.com",99            {100                "all://": PROXY_URL + ":1",101                "http://": PROXY_URL + ":2",102                "all://example.com": PROXY_URL + ":3",103                "http://example.com": PROXY_URL + ":4",104            },105            PROXY_URL + ":4",106        ),107        (108            "http://example.com",109            {110                "all://": PROXY_URL + ":1",111                "http://": PROXY_URL + ":2",112                "all://example.com": PROXY_URL + ":3",113            },114            PROXY_URL + ":3",115        ),116        (117            "http://example.com",118            {"all://": PROXY_URL + ":1", "http://": PROXY_URL + ":2"},119            PROXY_URL + ":2",120        ),121    ],122)123def test_transport_for_request(url, proxies, expected):124    client = httpx.Client(proxies=proxies)125    transport = client._transport_for_url(httpx.URL(url))126127    if expected is None:128        assert transport is client._transport129    else:130        assert isinstance(transport, httpx.HTTPTransport)131        assert isinstance(transport._pool, httpcore.HTTPProxy)132        assert transport._pool._proxy_url == url_to_origin(expected)133134135@pytest.mark.asyncio136@pytest.mark.network137async def test_async_proxy_close():138    try:139        client = httpx.AsyncClient(proxies={"https://": PROXY_URL})140        await client.get("http://example.com")141    finally:142        await client.aclose()143144145@pytest.mark.network146def test_sync_proxy_close():147    try:148        client = httpx.Client(proxies={"https://": PROXY_URL})149        client.get("http://example.com")150    finally:151        client.close()152153154def test_unsupported_proxy_scheme():155    with pytest.raises(ValueError):156        httpx.Client(proxies="ftp://127.0.0.1")157158159@pytest.mark.parametrize(160    ["url", "env", "expected"],161    [162        ("http://google.com", {}, None),163        (164            "http://google.com",165            {"HTTP_PROXY": "http://example.com"},166            "http://example.com",167        ),168        # Auto prepend http scheme169        ("http://google.com", {"HTTP_PROXY": "example.com"}, "http://example.com"),170        (171            "http://google.com",172            {"HTTP_PROXY": "http://example.com", "NO_PROXY": "google.com"},173            None,174        ),175        # Everything proxied when NO_PROXY is empty/unset176        (177            "http://127.0.0.1",178            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": ""},179            "http://localhost:123",180        ),181        # Not proxied if NO_PROXY matches URL.182        (183            "http://127.0.0.1",184            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "127.0.0.1"},185            None,186        ),187        # Proxied if NO_PROXY scheme does not match URL.188        (189            "http://127.0.0.1",190            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "https://127.0.0.1"},191            "http://localhost:123",192        ),193        # Proxied if NO_PROXY scheme does not match host.194        (195            "http://127.0.0.1",196            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "1.1.1.1"},197            "http://localhost:123",198        ),199        # Not proxied if NO_PROXY matches host domain suffix.200        (201            "http://courses.mit.edu",202            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu"},203            None,204        ),205        # Proxied even though NO_PROXY matches host domain *prefix*.206        (207            "https://mit.edu.info",208            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu"},209            "http://localhost:123",210        ),211        # Not proxied if one item in NO_PROXY case matches host domain suffix.212        (213            "https://mit.edu.info",214            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu,edu.info"},215            None,216        ),217        # Not proxied if one item in NO_PROXY case matches host domain suffix.218        # May include whitespace.219        (220            "https://mit.edu.info",221            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu, edu.info"},222            None,223        ),224        # Proxied if no items in NO_PROXY match.225        (226            "https://mit.edu.info",227            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu,mit.info"},228            "http://localhost:123",229        ),230        # Proxied if NO_PROXY domain doesn't match.231        (232            "https://foo.example.com",233            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "www.example.com"},234            "http://localhost:123",235        ),236        # Not proxied for subdomains matching NO_PROXY, with a leading ".".237        (238            "https://www.example1.com",239            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": ".example1.com"},240            None,241        ),242        # Proxied, because NO_PROXY subdomains only match if "." separated.243        (244            "https://www.example2.com",245            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "ample2.com"},246            "http://localhost:123",247        ),248        # No requests are proxied if NO_PROXY="*" is set.249        (250            "https://www.example3.com",251            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "*"},252            None,253        ),254    ],255)256@pytest.mark.parametrize("client_class", [httpx.Client, httpx.AsyncClient])257def test_proxies_environ(monkeypatch, client_class, url, env, expected):258    for name, value in env.items():259        monkeypatch.setenv(name, value)260261    client = client_class()262    transport = client._transport_for_url(httpx.URL(url))263264    if expected is None:265        assert transport == client._transport266    else:267        assert transport._pool._proxy_url == url_to_origin(expected)268269270@pytest.mark.parametrize(271    ["proxies", "is_valid"],272    [273        ({"http": "http://127.0.0.1"}, False),274        ({"https": "http://127.0.0.1"}, False),275        ({"all": "http://127.0.0.1"}, False),276        ({"http://": "http://127.0.0.1"}, True),277        ({"https://": "http://127.0.0.1"}, True),278        ({"all://": "http://127.0.0.1"}, True),279    ],280)281def test_for_deprecated_proxy_params(proxies, is_valid):282    if not is_valid:283        with pytest.raises(ValueError):284            httpx.Client(proxies=proxies)285    else:286        httpx.Client(proxies=proxies)