Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

258 lines · 8.2 KiB · Python

Last changed by

Add `NetRCAuth()` class. (#2535)Tom Christiebefore adoption59914c7

History of this file

Take it

1import os2import random34import pytest56import httpx7from httpx._utils import (8    URLPattern,9    get_ca_bundle_from_env,10    get_environment_proxies,11    guess_json_utf,12    is_https_redirect,13    obfuscate_sensitive_headers,14    parse_header_links,15    same_origin,16)17from tests.utils import override_log_level1819from .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    data = "{}".encode(encoding)37    assert guess_json_utf(data) == encoding383940def test_bad_utf_like_encoding():41    assert guess_json_utf(b"\x00\x00\x00\x00") is None424344@pytest.mark.parametrize(45    ("encoding", "expected"),46    (47        ("utf-16-be", "utf-16"),48        ("utf-16-le", "utf-16"),49        ("utf-32-be", "utf-32"),50        ("utf-32-le", "utf-32"),51    ),52)53def test_guess_by_bom(encoding, expected):54    data = "\ufeff{}".encode(encoding)55    assert guess_json_utf(data) == expected565758@pytest.mark.parametrize(59    "value, expected",60    (61        (62            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',63            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],64        ),65        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),66        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),67        (68            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',69            [70                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},71                {"url": "http://.../back.jpeg"},72            ],73        ),74        ("", []),75    ),76)77def test_parse_header_links(value, expected):78    assert parse_header_links(value) == expected798081@pytest.mark.anyio82async def test_logs_debug(server, capsys):83    with override_log_level("debug"):84        async with httpx.AsyncClient() as client:85            response = await client.get(server.url)86            assert response.status_code == 20087    stderr = capsys.readouterr().err88    assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr899091@pytest.mark.anyio92async def test_logs_trace(server, capsys):93    with override_log_level("trace"):94        async with httpx.AsyncClient() as client:95            response = await client.get(server.url)96            assert response.status_code == 20097    stderr = capsys.readouterr().err98    assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr99100101@pytest.mark.anyio102async def test_logs_redirect_chain(server, capsys):103    with override_log_level("debug"):104        async with httpx.AsyncClient(follow_redirects=True) as client:105            response = await client.get(server.url.copy_with(path="/redirect_301"))106            assert response.status_code == 200107108    stderr = capsys.readouterr().err.strip()109    redirected_request_line, ok_request_line = stderr.split("\n")110    assert redirected_request_line.endswith(111        "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "112        '"HTTP/1.1 301 Moved Permanently"'113    )114    assert ok_request_line.endswith(115        'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'116    )117118119def test_get_ssl_cert_file():120    # Two environments is not set.121    assert get_ca_bundle_from_env() is None122123    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)124    # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.125    ca_bundle = get_ca_bundle_from_env()126    assert ca_bundle is not None and ca_bundle.endswith("tests")127128    del os.environ["SSL_CERT_DIR"]129    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")130    # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.131    ca_bundle = get_ca_bundle_from_env()132    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")133134    os.environ["SSL_CERT_FILE"] = "wrongfile"135    # SSL_CERT_FILE is set with wrong file,  SSL_CERT_DIR is not set.136    assert get_ca_bundle_from_env() is None137138    del os.environ["SSL_CERT_FILE"]139    os.environ["SSL_CERT_DIR"] = "wrongpath"140    # SSL_CERT_DIR is set with wrong path,  SSL_CERT_FILE is not set.141    assert get_ca_bundle_from_env() is None142143    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)144    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")145    # Two environments is correctly set.146    ca_bundle = get_ca_bundle_from_env()147    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")148149    os.environ["SSL_CERT_FILE"] = "wrongfile"150    # Two environments is set but SSL_CERT_FILE is not a file.151    ca_bundle = get_ca_bundle_from_env()152    assert ca_bundle is not None and ca_bundle.endswith("tests")153154    os.environ["SSL_CERT_DIR"] = "wrongpath"155    # Two environments is set but both are not correct.156    assert get_ca_bundle_from_env() is None157158159@pytest.mark.parametrize(160    ["environment", "proxies"],161    [162        ({}, {}),163        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http://": "http://127.0.0.1"}),164        (165            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},166            {"https://": "http://127.0.0.1", "http://": "https://127.0.0.1"},167        ),168        ({"all_proxy": "http://127.0.0.1"}, {"all://": "http://127.0.0.1"}),169        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),170    ],171)172def test_get_environment_proxies(environment, proxies):173    os.environ.update(environment)174175    assert get_environment_proxies() == proxies176177178@pytest.mark.parametrize(179    "headers, output",180    [181        ([("content-type", "text/html")], [("content-type", "text/html")]),182        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),183        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),184    ],185)186def test_obfuscate_sensitive_headers(headers, output):187    bytes_headers = [(k.encode(), v.encode()) for k, v in headers]188    bytes_output = [(k.encode(), v.encode()) for k, v in output]189    assert list(obfuscate_sensitive_headers(headers)) == output190    assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output191192193def test_same_origin():194    origin1 = httpx.URL("https://example.com")195    origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")196    assert same_origin(origin1, origin2)197198199def test_not_same_origin():200    origin1 = httpx.URL("https://example.com")201    origin2 = httpx.URL("HTTP://EXAMPLE.COM")202    assert not same_origin(origin1, origin2)203204205def test_is_https_redirect():206    url = httpx.URL("http://example.com")207    location = httpx.URL("https://example.com")208    assert is_https_redirect(url, location)209210211def test_is_not_https_redirect():212    url = httpx.URL("http://example.com")213    location = httpx.URL("https://www.example.com")214    assert not is_https_redirect(url, location)215216217def test_is_not_https_redirect_if_not_default_ports():218    url = httpx.URL("http://example.com:9999")219    location = httpx.URL("https://example.com:1337")220    assert not is_https_redirect(url, location)221222223@pytest.mark.parametrize(224    ["pattern", "url", "expected"],225    [226        ("http://example.com", "http://example.com", True),227        ("http://example.com", "https://example.com", False),228        ("http://example.com", "http://other.com", False),229        ("http://example.com:123", "http://example.com:123", True),230        ("http://example.com:123", "http://example.com:456", False),231        ("http://example.com:123", "http://example.com", False),232        ("all://example.com", "http://example.com", True),233        ("all://example.com", "https://example.com", True),234        ("http://", "http://example.com", True),235        ("http://", "https://example.com", False),236        ("all://", "https://example.com:123", True),237        ("", "https://example.com:123", True),238    ],239)240def test_url_matches(pattern, url, expected):241    pattern = URLPattern(pattern)242    assert pattern.matches(httpx.URL(url)) == expected243244245def test_pattern_priority():246    matchers = [247        URLPattern("all://"),248        URLPattern("http://"),249        URLPattern("http://example.com"),250        URLPattern("http://example.com:123"),251    ]252    random.shuffle(matchers)253    assert sorted(matchers) == [254        URLPattern("http://example.com:123"),255        URLPattern("http://example.com"),256        URLPattern("http://"),257        URLPattern("all://"),258    ]