Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

292 lines · 8.9 KiB · Python

Last changed by

test `parse_header_links` via public api (#3061)T-256before adoption4f6edf3

History of this file

Take it

1import json2import logging3import os4import random56import certifi7import pytest89import httpx10from httpx._utils import (11    URLPattern,12    get_ca_bundle_from_env,13    get_environment_proxies,14    is_https_redirect,15    same_origin,16)1718from .common import TESTS_DIR192021@pytest.mark.parametrize(22    "encoding",23    (24        "utf-32",25        "utf-8-sig",26        "utf-16",27        "utf-8",28        "utf-16-be",29        "utf-16-le",30        "utf-32-be",31        "utf-32-le",32    ),33)34def test_encoded(encoding):35    content = '{"abc": 123}'.encode(encoding)36    response = httpx.Response(200, content=content)37    assert response.json() == {"abc": 123}383940def test_bad_utf_like_encoding():41    content = b"\x00\x00\x00\x00"42    response = httpx.Response(200, content=content)43    with pytest.raises(json.decoder.JSONDecodeError):44        response.json()454647@pytest.mark.parametrize(48    ("encoding", "expected"),49    (50        ("utf-16-be", "utf-16"),51        ("utf-16-le", "utf-16"),52        ("utf-32-be", "utf-32"),53        ("utf-32-le", "utf-32"),54    ),55)56def test_guess_by_bom(encoding, expected):57    content = '\ufeff{"abc": 123}'.encode(encoding)58    response = httpx.Response(200, content=content)59    assert response.json() == {"abc": 123}606162@pytest.mark.parametrize(63    "value, expected",64    (65        (66            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',67            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],68        ),69        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),70        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),71        (72            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',73            [74                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},75                {"url": "http://.../back.jpeg"},76            ],77        ),78        ("", []),79    ),80)81def test_parse_header_links(value, expected):82    all_links = httpx.Response(200, headers={"link": value}).links.values()83    assert all(link in all_links for link in expected)848586def test_parse_header_links_no_link():87    all_links = httpx.Response(200).links88    assert all_links == {}899091def test_logging_request(server, caplog):92    caplog.set_level(logging.INFO)93    with httpx.Client() as client:94        response = client.get(server.url)95        assert response.status_code == 2009697    assert caplog.record_tuples == [98        (99            "httpx",100            logging.INFO,101            'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',102        )103    ]104105106def test_logging_redirect_chain(server, caplog):107    caplog.set_level(logging.INFO)108    with httpx.Client(follow_redirects=True) as client:109        response = client.get(server.url.copy_with(path="/redirect_301"))110        assert response.status_code == 200111112    assert caplog.record_tuples == [113        (114            "httpx",115            logging.INFO,116            "HTTP Request: GET http://127.0.0.1:8000/redirect_301"117            ' "HTTP/1.1 301 Moved Permanently"',118        ),119        (120            "httpx",121            logging.INFO,122            'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',123        ),124    ]125126127def test_logging_ssl(caplog):128    caplog.set_level(logging.DEBUG)129    with httpx.Client():130        pass131132    cafile = certifi.where()133    assert caplog.record_tuples == [134        (135            "httpx",136            logging.DEBUG,137            "load_ssl_context verify=True cert=None trust_env=True http2=False",138        ),139        (140            "httpx",141            logging.DEBUG,142            f"load_verify_locations cafile='{cafile}'",143        ),144    ]145146147def test_get_ssl_cert_file():148    # Two environments is not set.149    assert get_ca_bundle_from_env() is None150151    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)152    # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.153    ca_bundle = get_ca_bundle_from_env()154    assert ca_bundle is not None and ca_bundle.endswith("tests")155156    del os.environ["SSL_CERT_DIR"]157    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")158    # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.159    ca_bundle = get_ca_bundle_from_env()160    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")161162    os.environ["SSL_CERT_FILE"] = "wrongfile"163    # SSL_CERT_FILE is set with wrong file,  SSL_CERT_DIR is not set.164    assert get_ca_bundle_from_env() is None165166    del os.environ["SSL_CERT_FILE"]167    os.environ["SSL_CERT_DIR"] = "wrongpath"168    # SSL_CERT_DIR is set with wrong path,  SSL_CERT_FILE is not set.169    assert get_ca_bundle_from_env() is None170171    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)172    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")173    # Two environments is correctly set.174    ca_bundle = get_ca_bundle_from_env()175    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")176177    os.environ["SSL_CERT_FILE"] = "wrongfile"178    # Two environments is set but SSL_CERT_FILE is not a file.179    ca_bundle = get_ca_bundle_from_env()180    assert ca_bundle is not None and ca_bundle.endswith("tests")181182    os.environ["SSL_CERT_DIR"] = "wrongpath"183    # Two environments is set but both are not correct.184    assert get_ca_bundle_from_env() is None185186187@pytest.mark.parametrize(188    ["environment", "proxies"],189    [190        ({}, {}),191        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http://": "http://127.0.0.1"}),192        (193            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},194            {"https://": "http://127.0.0.1", "http://": "https://127.0.0.1"},195        ),196        ({"all_proxy": "http://127.0.0.1"}, {"all://": "http://127.0.0.1"}),197        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),198        ({"no_proxy": "127.0.0.1"}, {"all://127.0.0.1": None}),199        ({"no_proxy": "192.168.0.0/16"}, {"all://192.168.0.0/16": None}),200        ({"no_proxy": "::1"}, {"all://[::1]": None}),201        ({"no_proxy": "localhost"}, {"all://localhost": None}),202        ({"no_proxy": "github.com"}, {"all://*github.com": None}),203        ({"no_proxy": ".github.com"}, {"all://*.github.com": None}),204        ({"no_proxy": "http://github.com"}, {"http://github.com": None}),205    ],206)207def test_get_environment_proxies(environment, proxies):208    os.environ.update(environment)209210    assert get_environment_proxies() == proxies211212213@pytest.mark.parametrize(214    "headers, output",215    [216        ([("content-type", "text/html")], [("content-type", "text/html")]),217        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),218        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),219    ],220)221def test_obfuscate_sensitive_headers(headers, output):222    as_dict = {k: v for k, v in output}223    headers_class = httpx.Headers({k: v for k, v in headers})224    assert repr(headers_class) == f"Headers({as_dict!r})"225226227def test_same_origin():228    origin1 = httpx.URL("https://example.com")229    origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")230    assert same_origin(origin1, origin2)231232233def test_not_same_origin():234    origin1 = httpx.URL("https://example.com")235    origin2 = httpx.URL("HTTP://EXAMPLE.COM")236    assert not same_origin(origin1, origin2)237238239def test_is_https_redirect():240    url = httpx.URL("http://example.com")241    location = httpx.URL("https://example.com")242    assert is_https_redirect(url, location)243244245def test_is_not_https_redirect():246    url = httpx.URL("http://example.com")247    location = httpx.URL("https://www.example.com")248    assert not is_https_redirect(url, location)249250251def test_is_not_https_redirect_if_not_default_ports():252    url = httpx.URL("http://example.com:9999")253    location = httpx.URL("https://example.com:1337")254    assert not is_https_redirect(url, location)255256257@pytest.mark.parametrize(258    ["pattern", "url", "expected"],259    [260        ("http://example.com", "http://example.com", True),261        ("http://example.com", "https://example.com", False),262        ("http://example.com", "http://other.com", False),263        ("http://example.com:123", "http://example.com:123", True),264        ("http://example.com:123", "http://example.com:456", False),265        ("http://example.com:123", "http://example.com", False),266        ("all://example.com", "http://example.com", True),267        ("all://example.com", "https://example.com", True),268        ("http://", "http://example.com", True),269        ("http://", "https://example.com", False),270        ("all://", "https://example.com:123", True),271        ("", "https://example.com:123", True),272    ],273)274def test_url_matches(pattern, url, expected):275    pattern = URLPattern(pattern)276    assert pattern.matches(httpx.URL(url)) == expected277278279def test_pattern_priority():280    matchers = [281        URLPattern("all://"),282        URLPattern("http://"),283        URLPattern("http://example.com"),284        URLPattern("http://example.com:123"),285    ]286    random.shuffle(matchers)287    assert sorted(matchers) == [288        URLPattern("http://example.com:123"),289        URLPattern("http://example.com"),290        URLPattern("http://"),291        URLPattern("all://"),292    ]