Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

287 lines · 8.8 KiB · Python

Last changed by

Switch to private module names (#785)Florimond Mancabefore adoption82dc6f3

History of this file

Take it

1import asyncio2import os34import pytest56import httpx7from httpx._utils import (8    ElapsedTimer,9    NetRCInfo,10    get_ca_bundle_from_env,11    get_environment_proxies,12    guess_json_utf,13    obfuscate_sensitive_headers,14    parse_header_links,15    should_not_be_proxied,16)17from tests.utils import override_log_level181920@pytest.mark.parametrize(21    "encoding",22    (23        "utf-32",24        "utf-8-sig",25        "utf-16",26        "utf-8",27        "utf-16-be",28        "utf-16-le",29        "utf-32-be",30        "utf-32-le",31    ),32)33def test_encoded(encoding):34    data = "{}".encode(encoding)35    assert guess_json_utf(data) == encoding363738def test_bad_utf_like_encoding():39    assert guess_json_utf(b"\x00\x00\x00\x00") is None404142@pytest.mark.parametrize(43    ("encoding", "expected"),44    (45        ("utf-16-be", "utf-16"),46        ("utf-16-le", "utf-16"),47        ("utf-32-be", "utf-32"),48        ("utf-32-le", "utf-32"),49    ),50)51def test_guess_by_bom(encoding, expected):52    data = "\ufeff{}".encode(encoding)53    assert guess_json_utf(data) == expected545556def test_bad_get_netrc_login():57    netrc_info = NetRCInfo(["tests/does-not-exist"])58    assert netrc_info.get_credentials("netrcexample.org") is None596061def test_get_netrc_login():62    netrc_info = NetRCInfo(["tests/.netrc"])63    expected_credentials = (64        "example-username",65        "example-password",66    )67    assert netrc_info.get_credentials("netrcexample.org") == expected_credentials686970@pytest.mark.parametrize(71    "value, expected",72    (73        (74            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',75            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],76        ),77        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),78        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),79        (80            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',81            [82                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},83                {"url": "http://.../back.jpeg"},84            ],85        ),86        ("", []),87    ),88)89def test_parse_header_links(value, expected):90    assert parse_header_links(value) == expected919293@pytest.mark.asyncio94async def test_logs_debug(server, capsys):95    with override_log_level("debug"):96        async with httpx.AsyncClient() as client:97            response = await client.get(server.url)98            assert response.status_code == 20099    stderr = capsys.readouterr().err100    assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr101    assert "httpx._dispatch.connection_pool" not in stderr102103104@pytest.mark.asyncio105async def test_logs_trace(server, capsys):106    with override_log_level("trace"):107        async with httpx.AsyncClient() as client:108            response = await client.get(server.url)109            assert response.status_code == 200110    stderr = capsys.readouterr().err111    assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr112    assert "httpx._dispatch.connection_pool" in stderr113114115@pytest.mark.asyncio116async def test_logs_redirect_chain(server, capsys):117    with override_log_level("debug"):118        async with httpx.AsyncClient() as client:119            response = await client.get(server.url.copy_with(path="/redirect_301"))120            assert response.status_code == 200121122    stderr = capsys.readouterr().err.strip()123    redirected_request_line, ok_request_line = stderr.split("\n")124    assert redirected_request_line.endswith(125        "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "126        '"HTTP/1.1 301 Moved Permanently"'127    )128    assert ok_request_line.endswith(129        'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'130    )131132133def test_get_ssl_cert_file():134    # Two environments is not set.135    assert get_ca_bundle_from_env() is None136137    os.environ["SSL_CERT_DIR"] = "tests/"138    # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.139    assert get_ca_bundle_from_env() == "tests"140141    del os.environ["SSL_CERT_DIR"]142    os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"143    # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.144    assert get_ca_bundle_from_env() == "tests/test_utils.py"145146    os.environ["SSL_CERT_FILE"] = "wrongfile"147    # SSL_CERT_FILE is set with wrong file,  SSL_CERT_DIR is not set.148    assert get_ca_bundle_from_env() is None149150    del os.environ["SSL_CERT_FILE"]151    os.environ["SSL_CERT_DIR"] = "wrongpath"152    # SSL_CERT_DIR is set with wrong path,  SSL_CERT_FILE is not set.153    assert get_ca_bundle_from_env() is None154155    os.environ["SSL_CERT_DIR"] = "tests/"156    os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"157    # Two environments is correctly set.158    assert get_ca_bundle_from_env() == "tests/test_utils.py"159160    os.environ["SSL_CERT_FILE"] = "wrongfile"161    # Two environments is set but SSL_CERT_FILE is not a file.162    assert get_ca_bundle_from_env() == "tests"163164    os.environ["SSL_CERT_DIR"] = "wrongpath"165    # Two environments is set but both are not correct.166    assert get_ca_bundle_from_env() is None167168169@pytest.mark.asyncio170async def test_elapsed_timer():171    with ElapsedTimer() as timer:172        assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)173        await asyncio.sleep(0.1)174    await asyncio.sleep(175        0.1176    )  # test to ensure time spent after timer exits isn't accounted for.177    assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)178179180@pytest.mark.parametrize(181    ["environment", "proxies"],182    [183        ({}, {}),184        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),185        (186            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},187            {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},188        ),189        ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),190        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),191    ],192)193def test_get_environment_proxies(environment, proxies):194    os.environ.update(environment)195196    assert get_environment_proxies() == proxies197198199@pytest.mark.parametrize(200    "headers, output",201    [202        ([("content-type", "text/html")], [("content-type", "text/html")]),203        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),204        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),205    ],206)207def test_obfuscate_sensitive_headers(headers, output):208    bytes_headers = [(k.encode(), v.encode()) for k, v in headers]209    bytes_output = [(k.encode(), v.encode()) for k, v in output]210    assert list(obfuscate_sensitive_headers(headers)) == output211    assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output212213214@pytest.mark.parametrize(215    ["url", "no_proxy", "expected"],216    [217        (218            "http://127.0.0.1",219            {"NO_PROXY": ""},220            False,221        ),  # everything proxied when no_proxy is empty/unset222        (223            "http://127.0.0.1",224            {"NO_PROXY": "127.0.0.1"},225            True,226        ),  # no_proxy as ip case is matched227        (228            "http://127.0.0.1",229            {"NO_PROXY": "https://127.0.0.1"},230            False,231        ),  # no_proxy with scheme is ignored232        (233            "http://127.0.0.1",234            {"NO_PROXY": "1.1.1.1"},235            False,236        ),  # different no_proxy means its proxied237        (238            "http://courses.mit.edu",239            {"NO_PROXY": "mit.edu"},240            True,241        ),  # no_proxy for sub-domain matches242        (243            "https://mit.edu.info",244            {"NO_PROXY": "mit.edu"},245            False,246        ),  # domain is actually edu.info, so should be proxied247        (248            "https://mit.edu.info",249            {"NO_PROXY": "mit.edu,edu.info"},250            True,251        ),  # list in no_proxy, matches second domain252        (253            "https://mit.edu.info",254            {"NO_PROXY": "mit.edu, edu.info"},255            True,256        ),  # list with spaces in no_proxy257        (258            "https://mit.edu.info",259            {"NO_PROXY": "mit.edu,mit.info"},260            False,261        ),  # list in no_proxy, without any domain matching262        (263            "https://foo.example.com",264            {"NO_PROXY": "www.example.com"},265            False,266        ),  # different subdomains foo vs www means we still proxy267        (268            "https://www.example1.com",269            {"NO_PROXY": ".example1.com"},270            True,271        ),  # no_proxy starting with dot272        (273            "https://www.example2.com",274            {"NO_PROXY": "ample2.com"},275            False,276        ),  # whole-domain matching277        (278            "https://www.example3.com",279            {"NO_PROXY": "*"},280            True,281        ),  # wildcard * means nothing proxied282    ],283)284def test_should_not_be_proxied(url, no_proxy, expected):285    os.environ.update(no_proxy)286    parsed_url = httpx.URL(url)287    assert should_not_be_proxied(parsed_url) == expected