Skip to content
Myr

test_proxies.py

This file

Path

tests/client/test_proxies.py

338 lines · 12.0 KiB · Python

Last changed by

Add the 'proxy' parameter and deprecate 'proxies'. (#2879)Kar Petrosyanbefore adoptionf8981f3

History of this file

Take it

1import httpcore2import pytest34import httpx567def url_to_origin(url: str) -> httpcore.URL:8    """9    Given a URL string, return the origin in the raw tuple format that10    `httpcore` uses for it's representation.11    """12    u = httpx.URL(url)13    return httpcore.URL(scheme=u.raw_scheme, host=u.raw_host, port=u.port, target="/")141516@pytest.mark.parametrize(17    ["proxies", "expected_proxies"],18    [19        ("http://127.0.0.1", [("all://", "http://127.0.0.1")]),20        ({"all://": "http://127.0.0.1"}, [("all://", "http://127.0.0.1")]),21        (22            {"http://": "http://127.0.0.1", "https://": "https://127.0.0.1"},23            [("http://", "http://127.0.0.1"), ("https://", "https://127.0.0.1")],24        ),25        (httpx.Proxy("http://127.0.0.1"), [("all://", "http://127.0.0.1")]),26        (27            {28                "https://": httpx.Proxy("https://127.0.0.1"),29                "all://": "http://127.0.0.1",30            },31            [("all://", "http://127.0.0.1"), ("https://", "https://127.0.0.1")],32        ),33    ],34)35def test_proxies_parameter(proxies, expected_proxies):36    with pytest.warns(DeprecationWarning):37        client = httpx.Client(proxies=proxies)38    client_patterns = [p.pattern for p in client._mounts.keys()]39    client_proxies = list(client._mounts.values())4041    for proxy_key, url in expected_proxies:42        assert proxy_key in client_patterns43        proxy = client_proxies[client_patterns.index(proxy_key)]44        assert isinstance(proxy, httpx.HTTPTransport)45        assert isinstance(proxy._pool, httpcore.HTTPProxy)46        assert proxy._pool._proxy_url == url_to_origin(url)4748    assert len(expected_proxies) == len(client._mounts)495051def test_socks_proxy_deprecated():52    url = httpx.URL("http://www.example.com")5354    with pytest.warns(DeprecationWarning):55        client = httpx.Client(proxies="socks5://localhost/")56    transport = client._transport_for_url(url)57    assert isinstance(transport, httpx.HTTPTransport)58    assert isinstance(transport._pool, httpcore.SOCKSProxy)5960    with pytest.warns(DeprecationWarning):61        async_client = httpx.AsyncClient(proxies="socks5://localhost/")62    async_transport = async_client._transport_for_url(url)63    assert isinstance(async_transport, httpx.AsyncHTTPTransport)64    assert isinstance(async_transport._pool, httpcore.AsyncSOCKSProxy)656667def test_socks_proxy():68    url = httpx.URL("http://www.example.com")6970    client = httpx.Client(proxy="socks5://localhost/")71    transport = client._transport_for_url(url)72    assert isinstance(transport, httpx.HTTPTransport)73    assert isinstance(transport._pool, httpcore.SOCKSProxy)7475    async_client = httpx.AsyncClient(proxy="socks5://localhost/")76    async_transport = async_client._transport_for_url(url)77    assert isinstance(async_transport, httpx.AsyncHTTPTransport)78    assert isinstance(async_transport._pool, httpcore.AsyncSOCKSProxy)798081PROXY_URL = "http://[::1]"828384@pytest.mark.parametrize(85    ["url", "proxies", "expected"],86    [87        ("http://example.com", None, None),88        ("http://example.com", {}, None),89        ("http://example.com", {"https://": PROXY_URL}, None),90        ("http://example.com", {"http://example.net": PROXY_URL}, None),91        # Using "*" should match any domain name.92        ("http://example.com", {"http://*": PROXY_URL}, PROXY_URL),93        ("https://example.com", {"http://*": PROXY_URL}, None),94        # Using "example.com" should match example.com, but not www.example.com95        ("http://example.com", {"http://example.com": PROXY_URL}, PROXY_URL),96        ("http://www.example.com", {"http://example.com": PROXY_URL}, None),97        # Using "*.example.com" should match www.example.com, but not example.com98        ("http://example.com", {"http://*.example.com": PROXY_URL}, None),99        ("http://www.example.com", {"http://*.example.com": PROXY_URL}, PROXY_URL),100        # Using "*example.com" should match example.com and www.example.com101        ("http://example.com", {"http://*example.com": PROXY_URL}, PROXY_URL),102        ("http://www.example.com", {"http://*example.com": PROXY_URL}, PROXY_URL),103        ("http://wwwexample.com", {"http://*example.com": PROXY_URL}, None),104        # ...105        ("http://example.com:443", {"http://example.com": PROXY_URL}, PROXY_URL),106        ("http://example.com", {"all://": PROXY_URL}, PROXY_URL),107        ("http://example.com", {"all://": PROXY_URL, "http://example.com": None}, None),108        ("http://example.com", {"http://": PROXY_URL}, PROXY_URL),109        ("http://example.com", {"all://example.com": PROXY_URL}, PROXY_URL),110        ("http://example.com", {"http://example.com": PROXY_URL}, PROXY_URL),111        ("http://example.com", {"http://example.com:80": PROXY_URL}, PROXY_URL),112        ("http://example.com:8080", {"http://example.com:8080": PROXY_URL}, PROXY_URL),113        ("http://example.com:8080", {"http://example.com": PROXY_URL}, PROXY_URL),114        (115            "http://example.com",116            {117                "all://": PROXY_URL + ":1",118                "http://": PROXY_URL + ":2",119                "all://example.com": PROXY_URL + ":3",120                "http://example.com": PROXY_URL + ":4",121            },122            PROXY_URL + ":4",123        ),124        (125            "http://example.com",126            {127                "all://": PROXY_URL + ":1",128                "http://": PROXY_URL + ":2",129                "all://example.com": PROXY_URL + ":3",130            },131            PROXY_URL + ":3",132        ),133        (134            "http://example.com",135            {"all://": PROXY_URL + ":1", "http://": PROXY_URL + ":2"},136            PROXY_URL + ":2",137        ),138    ],139)140def test_transport_for_request(url, proxies, expected):141    if proxies:142        with pytest.warns(DeprecationWarning):143            client = httpx.Client(proxies=proxies)144    else:145        client = httpx.Client(proxies=proxies)146147    transport = client._transport_for_url(httpx.URL(url))148149    if expected is None:150        assert transport is client._transport151    else:152        assert isinstance(transport, httpx.HTTPTransport)153        assert isinstance(transport._pool, httpcore.HTTPProxy)154        assert transport._pool._proxy_url == url_to_origin(expected)155156157@pytest.mark.anyio158@pytest.mark.network159async def test_async_proxy_close():160    try:161        with pytest.warns(DeprecationWarning):162            client = httpx.AsyncClient(proxies={"https://": PROXY_URL})163        await client.get("http://example.com")164    finally:165        await client.aclose()166167168@pytest.mark.network169def test_sync_proxy_close():170    try:171        with pytest.warns(DeprecationWarning):172            client = httpx.Client(proxies={"https://": PROXY_URL})173        client.get("http://example.com")174    finally:175        client.close()176177178def test_unsupported_proxy_scheme_deprecated():179    with pytest.warns(DeprecationWarning), pytest.raises(ValueError):180        httpx.Client(proxies="ftp://127.0.0.1")181182183def test_unsupported_proxy_scheme():184    with pytest.raises(ValueError):185        httpx.Client(proxy="ftp://127.0.0.1")186187188@pytest.mark.parametrize(189    ["url", "env", "expected"],190    [191        ("http://google.com", {}, None),192        (193            "http://google.com",194            {"HTTP_PROXY": "http://example.com"},195            "http://example.com",196        ),197        # Auto prepend http scheme198        ("http://google.com", {"HTTP_PROXY": "example.com"}, "http://example.com"),199        (200            "http://google.com",201            {"HTTP_PROXY": "http://example.com", "NO_PROXY": "google.com"},202            None,203        ),204        # Everything proxied when NO_PROXY is empty/unset205        (206            "http://127.0.0.1",207            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": ""},208            "http://localhost:123",209        ),210        # Not proxied if NO_PROXY matches URL.211        (212            "http://127.0.0.1",213            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "127.0.0.1"},214            None,215        ),216        # Proxied if NO_PROXY scheme does not match URL.217        (218            "http://127.0.0.1",219            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "https://127.0.0.1"},220            "http://localhost:123",221        ),222        # Proxied if NO_PROXY scheme does not match host.223        (224            "http://127.0.0.1",225            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "1.1.1.1"},226            "http://localhost:123",227        ),228        # Not proxied if NO_PROXY matches host domain suffix.229        (230            "http://courses.mit.edu",231            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu"},232            None,233        ),234        # Proxied even though NO_PROXY matches host domain *prefix*.235        (236            "https://mit.edu.info",237            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu"},238            "http://localhost:123",239        ),240        # Not proxied if one item in NO_PROXY case matches host domain suffix.241        (242            "https://mit.edu.info",243            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu,edu.info"},244            None,245        ),246        # Not proxied if one item in NO_PROXY case matches host domain suffix.247        # May include whitespace.248        (249            "https://mit.edu.info",250            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu, edu.info"},251            None,252        ),253        # Proxied if no items in NO_PROXY match.254        (255            "https://mit.edu.info",256            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu,mit.info"},257            "http://localhost:123",258        ),259        # Proxied if NO_PROXY domain doesn't match.260        (261            "https://foo.example.com",262            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "www.example.com"},263            "http://localhost:123",264        ),265        # Not proxied for subdomains matching NO_PROXY, with a leading ".".266        (267            "https://www.example1.com",268            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": ".example1.com"},269            None,270        ),271        # Proxied, because NO_PROXY subdomains only match if "." separated.272        (273            "https://www.example2.com",274            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "ample2.com"},275            "http://localhost:123",276        ),277        # No requests are proxied if NO_PROXY="*" is set.278        (279            "https://www.example3.com",280            {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "*"},281            None,282        ),283    ],284)285@pytest.mark.parametrize("client_class", [httpx.Client, httpx.AsyncClient])286def test_proxies_environ(monkeypatch, client_class, url, env, expected):287    for name, value in env.items():288        monkeypatch.setenv(name, value)289290    client = client_class()291    transport = client._transport_for_url(httpx.URL(url))292293    if expected is None:294        assert transport == client._transport295    else:296        assert transport._pool._proxy_url == url_to_origin(expected)297298299@pytest.mark.parametrize(300    ["proxies", "is_valid"],301    [302        ({"http": "http://127.0.0.1"}, False),303        ({"https": "http://127.0.0.1"}, False),304        ({"all": "http://127.0.0.1"}, False),305        ({"http://": "http://127.0.0.1"}, True),306        ({"https://": "http://127.0.0.1"}, True),307        ({"all://": "http://127.0.0.1"}, True),308    ],309)310def test_for_deprecated_proxy_params(proxies, is_valid):311    with pytest.warns(DeprecationWarning):312        if not is_valid:313            with pytest.raises(ValueError):314                httpx.Client(proxies=proxies)315        else:316            httpx.Client(proxies=proxies)317318319def test_proxy_and_proxies_together():320    with pytest.warns(DeprecationWarning), pytest.raises(321        RuntimeError,322    ):323        httpx.Client(proxies={"all://": "http://127.0.0.1"}, proxy="http://127.0.0.1")324325    with pytest.warns(DeprecationWarning), pytest.raises(326        RuntimeError,327    ):328        httpx.AsyncClient(329            proxies={"all://": "http://127.0.0.1"}, proxy="http://127.0.0.1"330        )331332333def test_proxy_with_mounts():334    proxy_transport = httpx.HTTPTransport(proxy="http://127.0.0.1")335    client = httpx.Client(mounts={"http://": proxy_transport})336337    transport = client._transport_for_url(httpx.URL("http://example.com"))338    assert transport == proxy_transport