Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

316 lines · 9.5 KiB · Python

Last changed by

test `same_origin` via public api (#3062)T-256before adoptionfc84f7f

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)1516from .common import TESTS_DIR171819@pytest.mark.parametrize(20    "encoding",21    (22        "utf-32",23        "utf-8-sig",24        "utf-16",25        "utf-8",26        "utf-16-be",27        "utf-16-le",28        "utf-32-be",29        "utf-32-le",30    ),31)32def test_encoded(encoding):33    content = '{"abc": 123}'.encode(encoding)34    response = httpx.Response(200, content=content)35    assert response.json() == {"abc": 123}363738def test_bad_utf_like_encoding():39    content = b"\x00\x00\x00\x00"40    response = httpx.Response(200, content=content)41    with pytest.raises(json.decoder.JSONDecodeError):42        response.json()434445@pytest.mark.parametrize(46    ("encoding", "expected"),47    (48        ("utf-16-be", "utf-16"),49        ("utf-16-le", "utf-16"),50        ("utf-32-be", "utf-32"),51        ("utf-32-le", "utf-32"),52    ),53)54def test_guess_by_bom(encoding, expected):55    content = '\ufeff{"abc": 123}'.encode(encoding)56    response = httpx.Response(200, content=content)57    assert response.json() == {"abc": 123}585960@pytest.mark.parametrize(61    "value, expected",62    (63        (64            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',65            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],66        ),67        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),68        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),69        (70            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',71            [72                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},73                {"url": "http://.../back.jpeg"},74            ],75        ),76        ("", []),77    ),78)79def test_parse_header_links(value, expected):80    all_links = httpx.Response(200, headers={"link": value}).links.values()81    assert all(link in all_links for link in expected)828384def test_parse_header_links_no_link():85    all_links = httpx.Response(200).links86    assert all_links == {}878889def test_logging_request(server, caplog):90    caplog.set_level(logging.INFO)91    with httpx.Client() as client:92        response = client.get(server.url)93        assert response.status_code == 2009495    assert caplog.record_tuples == [96        (97            "httpx",98            logging.INFO,99            'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',100        )101    ]102103104def test_logging_redirect_chain(server, caplog):105    caplog.set_level(logging.INFO)106    with httpx.Client(follow_redirects=True) as client:107        response = client.get(server.url.copy_with(path="/redirect_301"))108        assert response.status_code == 200109110    assert caplog.record_tuples == [111        (112            "httpx",113            logging.INFO,114            "HTTP Request: GET http://127.0.0.1:8000/redirect_301"115            ' "HTTP/1.1 301 Moved Permanently"',116        ),117        (118            "httpx",119            logging.INFO,120            'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"',121        ),122    ]123124125def test_logging_ssl(caplog):126    caplog.set_level(logging.DEBUG)127    with httpx.Client():128        pass129130    cafile = certifi.where()131    assert caplog.record_tuples == [132        (133            "httpx",134            logging.DEBUG,135            "load_ssl_context verify=True cert=None trust_env=True http2=False",136        ),137        (138            "httpx",139            logging.DEBUG,140            f"load_verify_locations cafile='{cafile}'",141        ),142    ]143144145def test_get_ssl_cert_file():146    # Two environments is not set.147    assert get_ca_bundle_from_env() is None148149    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)150    # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.151    ca_bundle = get_ca_bundle_from_env()152    assert ca_bundle is not None and ca_bundle.endswith("tests")153154    del os.environ["SSL_CERT_DIR"]155    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")156    # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.157    ca_bundle = get_ca_bundle_from_env()158    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")159160    os.environ["SSL_CERT_FILE"] = "wrongfile"161    # SSL_CERT_FILE is set with wrong file,  SSL_CERT_DIR is not set.162    assert get_ca_bundle_from_env() is None163164    del os.environ["SSL_CERT_FILE"]165    os.environ["SSL_CERT_DIR"] = "wrongpath"166    # SSL_CERT_DIR is set with wrong path,  SSL_CERT_FILE is not set.167    assert get_ca_bundle_from_env() is None168169    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)170    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")171    # Two environments is correctly set.172    ca_bundle = get_ca_bundle_from_env()173    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")174175    os.environ["SSL_CERT_FILE"] = "wrongfile"176    # Two environments is set but SSL_CERT_FILE is not a file.177    ca_bundle = get_ca_bundle_from_env()178    assert ca_bundle is not None and ca_bundle.endswith("tests")179180    os.environ["SSL_CERT_DIR"] = "wrongpath"181    # Two environments is set but both are not correct.182    assert get_ca_bundle_from_env() is None183184185@pytest.mark.parametrize(186    ["environment", "proxies"],187    [188        ({}, {}),189        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http://": "http://127.0.0.1"}),190        (191            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},192            {"https://": "http://127.0.0.1", "http://": "https://127.0.0.1"},193        ),194        ({"all_proxy": "http://127.0.0.1"}, {"all://": "http://127.0.0.1"}),195        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),196        ({"no_proxy": "127.0.0.1"}, {"all://127.0.0.1": None}),197        ({"no_proxy": "192.168.0.0/16"}, {"all://192.168.0.0/16": None}),198        ({"no_proxy": "::1"}, {"all://[::1]": None}),199        ({"no_proxy": "localhost"}, {"all://localhost": None}),200        ({"no_proxy": "github.com"}, {"all://*github.com": None}),201        ({"no_proxy": ".github.com"}, {"all://*.github.com": None}),202        ({"no_proxy": "http://github.com"}, {"http://github.com": None}),203    ],204)205def test_get_environment_proxies(environment, proxies):206    os.environ.update(environment)207208    assert get_environment_proxies() == proxies209210211@pytest.mark.parametrize(212    "headers, output",213    [214        ([("content-type", "text/html")], [("content-type", "text/html")]),215        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),216        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),217    ],218)219def test_obfuscate_sensitive_headers(headers, output):220    as_dict = {k: v for k, v in output}221    headers_class = httpx.Headers({k: v for k, v in headers})222    assert repr(headers_class) == f"Headers({as_dict!r})"223224225def test_same_origin():226    origin = httpx.URL("https://example.com")227    request = httpx.Request("GET", "HTTPS://EXAMPLE.COM:443")228229    client = httpx.Client()230    headers = client._redirect_headers(request, origin, "GET")231232    assert headers["Host"] == request.url.netloc.decode("ascii")233234235def test_not_same_origin():236    origin = httpx.URL("https://example.com")237    request = httpx.Request("GET", "HTTP://EXAMPLE.COM:80")238239    client = httpx.Client()240    headers = client._redirect_headers(request, origin, "GET")241242    assert headers["Host"] == origin.netloc.decode("ascii")243244245def test_is_https_redirect():246    url = httpx.URL("https://example.com")247    request = httpx.Request(248        "GET", "http://example.com", headers={"Authorization": "empty"}249    )250251    client = httpx.Client()252    headers = client._redirect_headers(request, url, "GET")253254    assert "Authorization" in headers255256257def test_is_not_https_redirect():258    url = httpx.URL("https://www.example.com")259    request = httpx.Request(260        "GET", "http://example.com", headers={"Authorization": "empty"}261    )262263    client = httpx.Client()264    headers = client._redirect_headers(request, url, "GET")265266    assert "Authorization" not in headers267268269def test_is_not_https_redirect_if_not_default_ports():270    url = httpx.URL("https://example.com:1337")271    request = httpx.Request(272        "GET", "http://example.com:9999", headers={"Authorization": "empty"}273    )274275    client = httpx.Client()276    headers = client._redirect_headers(request, url, "GET")277278    assert "Authorization" not in headers279280281@pytest.mark.parametrize(282    ["pattern", "url", "expected"],283    [284        ("http://example.com", "http://example.com", True),285        ("http://example.com", "https://example.com", False),286        ("http://example.com", "http://other.com", False),287        ("http://example.com:123", "http://example.com:123", True),288        ("http://example.com:123", "http://example.com:456", False),289        ("http://example.com:123", "http://example.com", False),290        ("all://example.com", "http://example.com", True),291        ("all://example.com", "https://example.com", True),292        ("http://", "http://example.com", True),293        ("http://", "https://example.com", False),294        ("all://", "https://example.com:123", True),295        ("", "https://example.com:123", True),296    ],297)298def test_url_matches(pattern, url, expected):299    pattern = URLPattern(pattern)300    assert pattern.matches(httpx.URL(url)) == expected301302303def test_pattern_priority():304    matchers = [305        URLPattern("all://"),306        URLPattern("http://"),307        URLPattern("http://example.com"),308        URLPattern("http://example.com:123"),309    ]310    random.shuffle(matchers)311    assert sorted(matchers) == [312        URLPattern("http://example.com:123"),313        URLPattern("http://example.com"),314        URLPattern("http://"),315        URLPattern("all://"),316    ]