Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

287 lines · 8.7 KiB · Python

Last changed by

test `obfuscate_sensitive_headers` via public api (#3063)T-256before adoptionc7cd6aa

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    parse_header_links,16    same_origin,17)1819from .common import TESTS_DIR202122@pytest.mark.parametrize(23    "encoding",24    (25        "utf-32",26        "utf-8-sig",27        "utf-16",28        "utf-8",29        "utf-16-be",30        "utf-16-le",31        "utf-32-be",32        "utf-32-le",33    ),34)35def test_encoded(encoding):36    content = '{"abc": 123}'.encode(encoding)37    response = httpx.Response(200, content=content)38    assert response.json() == {"abc": 123}394041def test_bad_utf_like_encoding():42    content = b"\x00\x00\x00\x00"43    response = httpx.Response(200, content=content)44    with pytest.raises(json.decoder.JSONDecodeError):45        response.json()464748@pytest.mark.parametrize(49    ("encoding", "expected"),50    (51        ("utf-16-be", "utf-16"),52        ("utf-16-le", "utf-16"),53        ("utf-32-be", "utf-32"),54        ("utf-32-le", "utf-32"),55    ),56)57def test_guess_by_bom(encoding, expected):58    content = '\ufeff{"abc": 123}'.encode(encoding)59    response = httpx.Response(200, content=content)60    assert response.json() == {"abc": 123}616263@pytest.mark.parametrize(64    "value, expected",65    (66        (67            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',68            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],69        ),70        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),71        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),72        (73            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',74            [75                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},76                {"url": "http://.../back.jpeg"},77            ],78        ),79        ("", []),80    ),81)82def test_parse_header_links(value, expected):83    assert parse_header_links(value) == expected848586def test_logging_request(server, caplog):87    caplog.set_level(logging.INFO)88    with httpx.Client() as client:89        response = client.get(server.url)90        assert response.status_code == 2009192    assert caplog.record_tuples == [93        (94            "httpx",95            logging.INFO,96            'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',97        )98    ]99100101def test_logging_redirect_chain(server, caplog):102    caplog.set_level(logging.INFO)103    with httpx.Client(follow_redirects=True) as client:104        response = client.get(server.url.copy_with(path="/redirect_301"))105        assert response.status_code == 200106107    assert caplog.record_tuples == [108        (109            "httpx",110            logging.INFO,111            "HTTP Request: GET http://127.0.0.1:8000/redirect_301"112            ' "HTTP/1.1 301 Moved Permanently"',113        ),114        (115            "httpx",116            logging.INFO,117            'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',118        ),119    ]120121122def test_logging_ssl(caplog):123    caplog.set_level(logging.DEBUG)124    with httpx.Client():125        pass126127    cafile = certifi.where()128    assert caplog.record_tuples == [129        (130            "httpx",131            logging.DEBUG,132            "load_ssl_context verify=True cert=None trust_env=True http2=False",133        ),134        (135            "httpx",136            logging.DEBUG,137            f"load_verify_locations cafile='{cafile}'",138        ),139    ]140141142def test_get_ssl_cert_file():143    # Two environments is not set.144    assert get_ca_bundle_from_env() is None145146    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)147    # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.148    ca_bundle = get_ca_bundle_from_env()149    assert ca_bundle is not None and ca_bundle.endswith("tests")150151    del os.environ["SSL_CERT_DIR"]152    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")153    # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.154    ca_bundle = get_ca_bundle_from_env()155    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")156157    os.environ["SSL_CERT_FILE"] = "wrongfile"158    # SSL_CERT_FILE is set with wrong file,  SSL_CERT_DIR is not set.159    assert get_ca_bundle_from_env() is None160161    del os.environ["SSL_CERT_FILE"]162    os.environ["SSL_CERT_DIR"] = "wrongpath"163    # SSL_CERT_DIR is set with wrong path,  SSL_CERT_FILE is not set.164    assert get_ca_bundle_from_env() is None165166    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)167    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")168    # Two environments is correctly set.169    ca_bundle = get_ca_bundle_from_env()170    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")171172    os.environ["SSL_CERT_FILE"] = "wrongfile"173    # Two environments is set but SSL_CERT_FILE is not a file.174    ca_bundle = get_ca_bundle_from_env()175    assert ca_bundle is not None and ca_bundle.endswith("tests")176177    os.environ["SSL_CERT_DIR"] = "wrongpath"178    # Two environments is set but both are not correct.179    assert get_ca_bundle_from_env() is None180181182@pytest.mark.parametrize(183    ["environment", "proxies"],184    [185        ({}, {}),186        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http://": "http://127.0.0.1"}),187        (188            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},189            {"https://": "http://127.0.0.1", "http://": "https://127.0.0.1"},190        ),191        ({"all_proxy": "http://127.0.0.1"}, {"all://": "http://127.0.0.1"}),192        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),193        ({"no_proxy": "127.0.0.1"}, {"all://127.0.0.1": None}),194        ({"no_proxy": "192.168.0.0/16"}, {"all://192.168.0.0/16": None}),195        ({"no_proxy": "::1"}, {"all://[::1]": None}),196        ({"no_proxy": "localhost"}, {"all://localhost": None}),197        ({"no_proxy": "github.com"}, {"all://*github.com": None}),198        ({"no_proxy": ".github.com"}, {"all://*.github.com": None}),199        ({"no_proxy": "http://github.com"}, {"http://github.com": None}),200    ],201)202def test_get_environment_proxies(environment, proxies):203    os.environ.update(environment)204205    assert get_environment_proxies() == proxies206207208@pytest.mark.parametrize(209    "headers, output",210    [211        ([("content-type", "text/html")], [("content-type", "text/html")]),212        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),213        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),214    ],215)216def test_obfuscate_sensitive_headers(headers, output):217    as_dict = {k: v for k, v in output}218    headers_class = httpx.Headers({k: v for k, v in headers})219    assert repr(headers_class) == f"Headers({as_dict!r})"220221222def test_same_origin():223    origin1 = httpx.URL("https://example.com")224    origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")225    assert same_origin(origin1, origin2)226227228def test_not_same_origin():229    origin1 = httpx.URL("https://example.com")230    origin2 = httpx.URL("HTTP://EXAMPLE.COM")231    assert not same_origin(origin1, origin2)232233234def test_is_https_redirect():235    url = httpx.URL("http://example.com")236    location = httpx.URL("https://example.com")237    assert is_https_redirect(url, location)238239240def test_is_not_https_redirect():241    url = httpx.URL("http://example.com")242    location = httpx.URL("https://www.example.com")243    assert not is_https_redirect(url, location)244245246def test_is_not_https_redirect_if_not_default_ports():247    url = httpx.URL("http://example.com:9999")248    location = httpx.URL("https://example.com:1337")249    assert not is_https_redirect(url, location)250251252@pytest.mark.parametrize(253    ["pattern", "url", "expected"],254    [255        ("http://example.com", "http://example.com", True),256        ("http://example.com", "https://example.com", False),257        ("http://example.com", "http://other.com", False),258        ("http://example.com:123", "http://example.com:123", True),259        ("http://example.com:123", "http://example.com:456", False),260        ("http://example.com:123", "http://example.com", False),261        ("all://example.com", "http://example.com", True),262        ("all://example.com", "https://example.com", True),263        ("http://", "http://example.com", True),264        ("http://", "https://example.com", False),265        ("all://", "https://example.com:123", True),266        ("", "https://example.com:123", True),267    ],268)269def test_url_matches(pattern, url, expected):270    pattern = URLPattern(pattern)271    assert pattern.matches(httpx.URL(url)) == expected272273274def test_pattern_priority():275    matchers = [276        URLPattern("all://"),277        URLPattern("http://"),278        URLPattern("http://example.com"),279        URLPattern("http://example.com:123"),280    ]281    random.shuffle(matchers)282    assert sorted(matchers) == [283        URLPattern("http://example.com:123"),284        URLPattern("http://example.com"),285        URLPattern("http://"),286        URLPattern("all://"),287    ]