Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

278 lines · 8.1 KiB · Python

Last changed by

Refactor debug and trace log tests (#506)Florimond Mancabefore adoption2fcf23b

History of this file

Take it

1import asyncio2import os34import pytest56import httpx7from httpx.utils import (8    ElapsedTimer,9    get_ca_bundle_from_env,10    get_environment_proxies,11    get_netrc,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    os.environ["NETRC"] = "tests/.netrc"58    assert str(get_netrc()) is not None5960    from httpx import utils6162    utils.NETRC_STATIC_FILES = ()6364    os.environ["NETRC"] = "wrongpath"65    assert utils.get_netrc() is None6667    os.environ["NETRC"] = ""68    assert utils.get_netrc() is None697071def test_get_netrc_login():72    os.environ["NETRC"] = "tests/.netrc"73    netrc = get_netrc()74    assert netrc.authenticators("netrcexample.org") == (75        "example-username",76        None,77        "example-password",78    )798081@pytest.mark.parametrize(82    "value, expected",83    (84        (85            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',86            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],87        ),88        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),89        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),90        (91            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',92            [93                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},94                {"url": "http://.../back.jpeg"},95            ],96        ),97        ("", []),98    ),99)100def test_parse_header_links(value, expected):101    assert parse_header_links(value) == expected102103104@pytest.mark.asyncio105async def test_logs_debug(server, capsys):106    with override_log_level("debug"):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 "httpx.dispatch.connection_pool" not in stderr112113114@pytest.mark.asyncio115async def test_logs_trace(server, capsys):116    with override_log_level("trace"):117        async with httpx.AsyncClient() as client:118            response = await client.get(server.url)119            assert response.status_code == 200120    stderr = capsys.readouterr().err121    assert "httpx.dispatch.connection_pool" in stderr122123124def test_get_ssl_cert_file():125    # Two environments is not set.126    assert get_ca_bundle_from_env() is None127128    os.environ["SSL_CERT_DIR"] = "tests/"129    # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.130    assert get_ca_bundle_from_env() == "tests"131132    del os.environ["SSL_CERT_DIR"]133    os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"134    # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.135    assert get_ca_bundle_from_env() == "tests/test_utils.py"136137    os.environ["SSL_CERT_FILE"] = "wrongfile"138    # SSL_CERT_FILE is set with wrong file,  SSL_CERT_DIR is not set.139    assert get_ca_bundle_from_env() is None140141    del os.environ["SSL_CERT_FILE"]142    os.environ["SSL_CERT_DIR"] = "wrongpath"143    # SSL_CERT_DIR is set with wrong path,  SSL_CERT_FILE is not set.144    assert get_ca_bundle_from_env() is None145146    os.environ["SSL_CERT_DIR"] = "tests/"147    os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"148    # Two environments is correctly set.149    assert get_ca_bundle_from_env() == "tests/test_utils.py"150151    os.environ["SSL_CERT_FILE"] = "wrongfile"152    # Two environments is set but SSL_CERT_FILE is not a file.153    assert get_ca_bundle_from_env() == "tests"154155    os.environ["SSL_CERT_DIR"] = "wrongpath"156    # Two environments is set but both are not correct.157    assert get_ca_bundle_from_env() is None158159160@pytest.mark.asyncio161async def test_elapsed_timer():162    with ElapsedTimer() as timer:163        assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)164        await asyncio.sleep(0.1)165    await asyncio.sleep(166        0.1167    )  # test to ensure time spent after timer exits isn't accounted for.168    assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)169170171@pytest.mark.parametrize(172    ["environment", "proxies"],173    [174        ({}, {}),175        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),176        (177            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},178            {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},179        ),180        ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),181        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),182    ],183)184def test_get_environment_proxies(environment, proxies):185    os.environ.update(environment)186187    assert get_environment_proxies() == proxies188189190@pytest.mark.parametrize(191    "headers, output",192    [193        ([("content-type", "text/html")], [("content-type", "text/html")]),194        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),195        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),196    ],197)198def test_obfuscate_sensitive_headers(headers, output):199    bytes_headers = [(k.encode(), v.encode()) for k, v in headers]200    bytes_output = [(k.encode(), v.encode()) for k, v in output]201    assert list(obfuscate_sensitive_headers(headers)) == output202    assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output203204205@pytest.mark.parametrize(206    ["url", "no_proxy", "expected"],207    [208        (209            "http://127.0.0.1",210            {"NO_PROXY": ""},211            False,212        ),  # everything proxied when no_proxy is empty/unset213        (214            "http://127.0.0.1",215            {"NO_PROXY": "127.0.0.1"},216            True,217        ),  # no_proxy as ip case is matched218        (219            "http://127.0.0.1",220            {"NO_PROXY": "https://127.0.0.1"},221            False,222        ),  # no_proxy with scheme is ignored223        (224            "http://127.0.0.1",225            {"NO_PROXY": "1.1.1.1"},226            False,227        ),  # different no_proxy means its proxied228        (229            "http://courses.mit.edu",230            {"NO_PROXY": "mit.edu"},231            True,232        ),  # no_proxy for sub-domain matches233        (234            "https://mit.edu.info",235            {"NO_PROXY": "mit.edu"},236            False,237        ),  # domain is actually edu.info, so should be proxied238        (239            "https://mit.edu.info",240            {"NO_PROXY": "mit.edu,edu.info"},241            True,242        ),  # list in no_proxy, matches second domain243        (244            "https://mit.edu.info",245            {"NO_PROXY": "mit.edu, edu.info"},246            True,247        ),  # list with spaces in no_proxy248        (249            "https://mit.edu.info",250            {"NO_PROXY": "mit.edu,mit.info"},251            False,252        ),  # list in no_proxy, without any domain matching253        (254            "https://foo.example.com",255            {"NO_PROXY": "www.example.com"},256            False,257        ),  # different subdomains foo vs www means we still proxy258        (259            "https://www.example1.com",260            {"NO_PROXY": ".example1.com"},261            True,262        ),  # no_proxy starting with dot263        (264            "https://www.example2.com",265            {"NO_PROXY": "ample2.com"},266            False,267        ),  # whole-domain matching268        (269            "https://www.example3.com",270            {"NO_PROXY": "*"},271            True,272        ),  # wildcard * means nothing proxied273    ],274)275def test_should_not_be_proxied(url, no_proxy, expected):276    os.environ.update(no_proxy)277    parsed_url = httpx.models.URL(url)278    assert should_not_be_proxied(parsed_url) == expected