Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

252 lines · 7.4 KiB · Python

Last changed by

Introduce new `SSLContext` API & escalate deprecations. (#3319)Tom Christiebefore adoption8e36f2b

History of this file

Take it

1import json2import logging3import os4import random56import pytest78import httpx9from httpx._utils import (10    URLPattern,11    get_environment_proxies,12)131415@pytest.mark.parametrize(16    "encoding",17    (18        "utf-32",19        "utf-8-sig",20        "utf-16",21        "utf-8",22        "utf-16-be",23        "utf-16-le",24        "utf-32-be",25        "utf-32-le",26    ),27)28def test_encoded(encoding):29    content = '{"abc": 123}'.encode(encoding)30    response = httpx.Response(200, content=content)31    assert response.json() == {"abc": 123}323334def test_bad_utf_like_encoding():35    content = b"\x00\x00\x00\x00"36    response = httpx.Response(200, content=content)37    with pytest.raises(json.decoder.JSONDecodeError):38        response.json()394041@pytest.mark.parametrize(42    ("encoding", "expected"),43    (44        ("utf-16-be", "utf-16"),45        ("utf-16-le", "utf-16"),46        ("utf-32-be", "utf-32"),47        ("utf-32-le", "utf-32"),48    ),49)50def test_guess_by_bom(encoding, expected):51    content = '\ufeff{"abc": 123}'.encode(encoding)52    response = httpx.Response(200, content=content)53    assert response.json() == {"abc": 123}545556@pytest.mark.parametrize(57    "value, expected",58    (59        (60            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',61            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],62        ),63        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),64        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),65        (66            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',67            [68                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},69                {"url": "http://.../back.jpeg"},70            ],71        ),72        ("", []),73    ),74)75def test_parse_header_links(value, expected):76    all_links = httpx.Response(200, headers={"link": value}).links.values()77    assert all(link in all_links for link in expected)787980def test_parse_header_links_no_link():81    all_links = httpx.Response(200).links82    assert all_links == {}838485def test_logging_request(server, caplog):86    caplog.set_level(logging.INFO)87    with httpx.Client() as client:88        response = client.get(server.url)89        assert response.status_code == 2009091    assert caplog.record_tuples == [92        (93            "httpx",94            logging.INFO,95            'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',96        )97    ]9899100def test_logging_redirect_chain(server, caplog):101    caplog.set_level(logging.INFO)102    with httpx.Client(follow_redirects=True) as client:103        response = client.get(server.url.copy_with(path="/redirect_301"))104        assert response.status_code == 200105106    assert caplog.record_tuples == [107        (108            "httpx",109            logging.INFO,110            "HTTP Request: GET http://127.0.0.1:8000/redirect_301"111            ' "HTTP/1.1 301 Moved Permanently"',112        ),113        (114            "httpx",115            logging.INFO,116            'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',117        ),118    ]119120121@pytest.mark.parametrize(122    ["environment", "proxies"],123    [124        ({}, {}),125        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http://": "http://127.0.0.1"}),126        (127            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},128            {"https://": "http://127.0.0.1", "http://": "https://127.0.0.1"},129        ),130        ({"all_proxy": "http://127.0.0.1"}, {"all://": "http://127.0.0.1"}),131        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),132        ({"no_proxy": "127.0.0.1"}, {"all://127.0.0.1": None}),133        ({"no_proxy": "192.168.0.0/16"}, {"all://192.168.0.0/16": None}),134        ({"no_proxy": "::1"}, {"all://[::1]": None}),135        ({"no_proxy": "localhost"}, {"all://localhost": None}),136        ({"no_proxy": "github.com"}, {"all://*github.com": None}),137        ({"no_proxy": ".github.com"}, {"all://*.github.com": None}),138        ({"no_proxy": "http://github.com"}, {"http://github.com": None}),139    ],140)141def test_get_environment_proxies(environment, proxies):142    os.environ.update(environment)143144    assert get_environment_proxies() == proxies145146147@pytest.mark.parametrize(148    "headers, output",149    [150        ([("content-type", "text/html")], [("content-type", "text/html")]),151        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),152        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),153    ],154)155def test_obfuscate_sensitive_headers(headers, output):156    as_dict = {k: v for k, v in output}157    headers_class = httpx.Headers({k: v for k, v in headers})158    assert repr(headers_class) == f"Headers({as_dict!r})"159160161def test_same_origin():162    origin = httpx.URL("https://example.com")163    request = httpx.Request("GET", "HTTPS://EXAMPLE.COM:443")164165    client = httpx.Client()166    headers = client._redirect_headers(request, origin, "GET")167168    assert headers["Host"] == request.url.netloc.decode("ascii")169170171def test_not_same_origin():172    origin = httpx.URL("https://example.com")173    request = httpx.Request("GET", "HTTP://EXAMPLE.COM:80")174175    client = httpx.Client()176    headers = client._redirect_headers(request, origin, "GET")177178    assert headers["Host"] == origin.netloc.decode("ascii")179180181def test_is_https_redirect():182    url = httpx.URL("https://example.com")183    request = httpx.Request(184        "GET", "http://example.com", headers={"Authorization": "empty"}185    )186187    client = httpx.Client()188    headers = client._redirect_headers(request, url, "GET")189190    assert "Authorization" in headers191192193def test_is_not_https_redirect():194    url = httpx.URL("https://www.example.com")195    request = httpx.Request(196        "GET", "http://example.com", headers={"Authorization": "empty"}197    )198199    client = httpx.Client()200    headers = client._redirect_headers(request, url, "GET")201202    assert "Authorization" not in headers203204205def test_is_not_https_redirect_if_not_default_ports():206    url = httpx.URL("https://example.com:1337")207    request = httpx.Request(208        "GET", "http://example.com:9999", headers={"Authorization": "empty"}209    )210211    client = httpx.Client()212    headers = client._redirect_headers(request, url, "GET")213214    assert "Authorization" not in headers215216217@pytest.mark.parametrize(218    ["pattern", "url", "expected"],219    [220        ("http://example.com", "http://example.com", True),221        ("http://example.com", "https://example.com", False),222        ("http://example.com", "http://other.com", False),223        ("http://example.com:123", "http://example.com:123", True),224        ("http://example.com:123", "http://example.com:456", False),225        ("http://example.com:123", "http://example.com", False),226        ("all://example.com", "http://example.com", True),227        ("all://example.com", "https://example.com", True),228        ("http://", "http://example.com", True),229        ("http://", "https://example.com", False),230        ("all://", "https://example.com:123", True),231        ("", "https://example.com:123", True),232    ],233)234def test_url_matches(pattern, url, expected):235    pattern = URLPattern(pattern)236    assert pattern.matches(httpx.URL(url)) == expected237238239def test_pattern_priority():240    matchers = [241        URLPattern("all://"),242        URLPattern("http://"),243        URLPattern("http://example.com"),244        URLPattern("http://example.com:123"),245    ]246    random.shuffle(matchers)247    assert sorted(matchers) == [248        URLPattern("http://example.com:123"),249        URLPattern("http://example.com"),250        URLPattern("http://"),251        URLPattern("all://"),252    ]