Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

259 lines · 8.2 KiB · Python

Last changed by

Drop `request.timer` attribute. (#1249)Tom Christiebefore adoptiona783fe5

History of this file

Take it

1import os2import random34import pytest56import httpx7from httpx._utils import (8    NetRCInfo,9    URLPattern,10    get_ca_bundle_from_env,11    get_environment_proxies,12    guess_json_utf,13    obfuscate_sensitive_headers,14    parse_header_links,15    same_origin,16)17from tests.utils import override_log_level1819from .common import FIXTURES_DIR, 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) == expected565758def test_bad_get_netrc_login():59    netrc_info = NetRCInfo([str(FIXTURES_DIR / "does-not-exist")])60    assert netrc_info.get_credentials("netrcexample.org") is None616263def test_get_netrc_login():64    netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])65    expected_credentials = (66        "example-username",67        "example-password",68    )69    assert netrc_info.get_credentials("netrcexample.org") == expected_credentials707172def test_get_netrc_unknown():73    netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])74    assert netrc_info.get_credentials("nonexistant.org") is None757677@pytest.mark.parametrize(78    "value, expected",79    (80        (81            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',82            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],83        ),84        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),85        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),86        (87            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',88            [89                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},90                {"url": "http://.../back.jpeg"},91            ],92        ),93        ("", []),94    ),95)96def test_parse_header_links(value, expected):97    assert parse_header_links(value) == expected9899100@pytest.mark.asyncio101async def test_logs_debug(server, capsys):102    with override_log_level("debug"):103        async with httpx.AsyncClient() as client:104            response = await client.get(server.url)105            assert response.status_code == 200106    stderr = capsys.readouterr().err107    assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr108109110@pytest.mark.asyncio111async def test_logs_trace(server, capsys):112    with override_log_level("trace"):113        async with httpx.AsyncClient() as client:114            response = await client.get(server.url)115            assert response.status_code == 200116    stderr = capsys.readouterr().err117    assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr118119120@pytest.mark.asyncio121async def test_logs_redirect_chain(server, capsys):122    with override_log_level("debug"):123        async with httpx.AsyncClient() as client:124            response = await client.get(server.url.copy_with(path="/redirect_301"))125            assert response.status_code == 200126127    stderr = capsys.readouterr().err.strip()128    redirected_request_line, ok_request_line = stderr.split("\n")129    assert redirected_request_line.endswith(130        "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "131        '"HTTP/1.1 301 Moved Permanently"'132    )133    assert ok_request_line.endswith(134        'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'135    )136137138def test_get_ssl_cert_file():139    # Two environments is not set.140    assert get_ca_bundle_from_env() is None141142    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)143    # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.144    ca_bundle = get_ca_bundle_from_env()145    assert ca_bundle is not None and ca_bundle.endswith("tests")146147    del os.environ["SSL_CERT_DIR"]148    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")149    # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.150    ca_bundle = get_ca_bundle_from_env()151    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")152153    os.environ["SSL_CERT_FILE"] = "wrongfile"154    # SSL_CERT_FILE is set with wrong file,  SSL_CERT_DIR is not set.155    assert get_ca_bundle_from_env() is None156157    del os.environ["SSL_CERT_FILE"]158    os.environ["SSL_CERT_DIR"] = "wrongpath"159    # SSL_CERT_DIR is set with wrong path,  SSL_CERT_FILE is not set.160    assert get_ca_bundle_from_env() is None161162    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)163    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")164    # Two environments is correctly set.165    ca_bundle = get_ca_bundle_from_env()166    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")167168    os.environ["SSL_CERT_FILE"] = "wrongfile"169    # Two environments is set but SSL_CERT_FILE is not a file.170    ca_bundle = get_ca_bundle_from_env()171    assert ca_bundle is not None and ca_bundle.endswith("tests")172173    os.environ["SSL_CERT_DIR"] = "wrongpath"174    # Two environments is set but both are not correct.175    assert get_ca_bundle_from_env() is None176177178@pytest.mark.parametrize(179    ["environment", "proxies"],180    [181        ({}, {}),182        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http://": "http://127.0.0.1"}),183        (184            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},185            {"https://": "http://127.0.0.1", "http://": "https://127.0.0.1"},186        ),187        ({"all_proxy": "http://127.0.0.1"}, {"all://": "http://127.0.0.1"}),188        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),189    ],190)191def test_get_environment_proxies(environment, proxies):192    os.environ.update(environment)193194    assert get_environment_proxies() == proxies195196197@pytest.mark.parametrize(198    "headers, output",199    [200        ([("content-type", "text/html")], [("content-type", "text/html")]),201        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),202        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),203    ],204)205def test_obfuscate_sensitive_headers(headers, output):206    bytes_headers = [(k.encode(), v.encode()) for k, v in headers]207    bytes_output = [(k.encode(), v.encode()) for k, v in output]208    assert list(obfuscate_sensitive_headers(headers)) == output209    assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output210211212def test_same_origin():213    origin1 = httpx.URL("https://example.com")214    origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")215    assert same_origin(origin1, origin2)216217218def test_not_same_origin():219    origin1 = httpx.URL("https://example.com")220    origin2 = httpx.URL("HTTP://EXAMPLE.COM")221    assert not same_origin(origin1, origin2)222223224@pytest.mark.parametrize(225    ["pattern", "url", "expected"],226    [227        ("http://example.com", "http://example.com", True),228        ("http://example.com", "https://example.com", False),229        ("http://example.com", "http://other.com", False),230        ("http://example.com:123", "http://example.com:123", True),231        ("http://example.com:123", "http://example.com:456", False),232        ("http://example.com:123", "http://example.com", False),233        ("all://example.com", "http://example.com", True),234        ("all://example.com", "https://example.com", True),235        ("http://", "http://example.com", True),236        ("http://", "https://example.com", False),237        ("all://", "https://example.com:123", True),238        ("", "https://example.com:123", True),239    ],240)241def test_url_matches(pattern, url, expected):242    pattern = URLPattern(pattern)243    assert pattern.matches(httpx.URL(url)) == expected244245246def test_pattern_priority():247    matchers = [248        URLPattern("all://"),249        URLPattern("http://"),250        URLPattern("http://example.com"),251        URLPattern("http://example.com:123"),252    ]253    random.shuffle(matchers)254    assert sorted(matchers) == [255        URLPattern("http://example.com:123"),256        URLPattern("http://example.com"),257        URLPattern("http://"),258        URLPattern("all://"),259    ]