Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

287 lines · 8.8 KiB · Python

Last changed by

Cleanup response.json() method (#2911)Tom Christiebefore adoption1d73150

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    obfuscate_sensitive_headers,16    parse_header_links,17    same_origin,18)1920from .common import TESTS_DIR212223@pytest.mark.parametrize(24    "encoding",25    (26        "utf-32",27        "utf-8-sig",28        "utf-16",29        "utf-8",30        "utf-16-be",31        "utf-16-le",32        "utf-32-be",33        "utf-32-le",34    ),35)36def test_encoded(encoding):37    content = '{"abc": 123}'.encode(encoding)38    response = httpx.Response(200, content=content)39    assert response.json() == {"abc": 123}404142def test_bad_utf_like_encoding():43    content = b"\x00\x00\x00\x00"44    response = httpx.Response(200, content=content)45    with pytest.raises(json.decoder.JSONDecodeError):46        response.json()474849@pytest.mark.parametrize(50    ("encoding", "expected"),51    (52        ("utf-16-be", "utf-16"),53        ("utf-16-le", "utf-16"),54        ("utf-32-be", "utf-32"),55        ("utf-32-le", "utf-32"),56    ),57)58def test_guess_by_bom(encoding, expected):59    content = '\ufeff{"abc": 123}'.encode(encoding)60    response = httpx.Response(200, content=content)61    assert response.json() == {"abc": 123}626364@pytest.mark.parametrize(65    "value, expected",66    (67        (68            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',69            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],70        ),71        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),72        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),73        (74            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',75            [76                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},77                {"url": "http://.../back.jpeg"},78            ],79        ),80        ("", []),81    ),82)83def test_parse_header_links(value, expected):84    assert parse_header_links(value) == expected858687def test_logging_request(server, caplog):88    caplog.set_level(logging.INFO)89    with httpx.Client() as client:90        response = client.get(server.url)91        assert response.status_code == 2009293    assert caplog.record_tuples == [94        (95            "httpx",96            logging.INFO,97            'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',98        )99    ]100101102def test_logging_redirect_chain(server, caplog):103    caplog.set_level(logging.INFO)104    with httpx.Client(follow_redirects=True) as client:105        response = client.get(server.url.copy_with(path="/redirect_301"))106        assert response.status_code == 200107108    assert caplog.record_tuples == [109        (110            "httpx",111            logging.INFO,112            'HTTP Request: GET http://127.0.0.1:8000/redirect_301 "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    ],200)201def test_get_environment_proxies(environment, proxies):202    os.environ.update(environment)203204    assert get_environment_proxies() == proxies205206207@pytest.mark.parametrize(208    "headers, output",209    [210        ([("content-type", "text/html")], [("content-type", "text/html")]),211        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),212        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),213    ],214)215def test_obfuscate_sensitive_headers(headers, output):216    bytes_headers = [(k.encode(), v.encode()) for k, v in headers]217    bytes_output = [(k.encode(), v.encode()) for k, v in output]218    assert list(obfuscate_sensitive_headers(headers)) == output219    assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output220221222def 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    ]