Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

157 lines · 4.2 KiB · Python

Last changed by

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

History of this file

Take it

1import asyncio2import logging3import os45import pytest67import httpx8from httpx import utils9from httpx.utils import (10    ElapsedTimer,11    get_environment_proxies,12    get_netrc_login,13    guess_json_utf,14    parse_header_links,15)161718@pytest.mark.parametrize(19    "encoding",20    (21        "utf-32",22        "utf-8-sig",23        "utf-16",24        "utf-8",25        "utf-16-be",26        "utf-16-le",27        "utf-32-be",28        "utf-32-le",29    ),30)31def test_encoded(encoding):32    data = "{}".encode(encoding)33    assert guess_json_utf(data) == encoding343536def test_bad_utf_like_encoding():37    assert guess_json_utf(b"\x00\x00\x00\x00") is None383940@pytest.mark.parametrize(41    ("encoding", "expected"),42    (43        ("utf-16-be", "utf-16"),44        ("utf-16-le", "utf-16"),45        ("utf-32-be", "utf-32"),46        ("utf-32-le", "utf-32"),47    ),48)49def test_guess_by_bom(encoding, expected):50    data = "\ufeff{}".encode(encoding)51    assert guess_json_utf(data) == expected525354def test_bad_get_netrc_login():55    assert get_netrc_login("url") is None5657    os.environ["NETRC"] = "tests/.netrc"58    assert get_netrc_login("url") is None5960    os.environ["NETRC"] = "wrongpath"61    assert get_netrc_login("url") is None6263    from httpx import utils6465    utils.NETRC_STATIC_FILES = ()66    os.environ["NETRC"] = ""67    assert utils.get_netrc_login("url") is None686970def test_get_netrc_login():71    os.environ["NETRC"] = "tests/.netrc"72    assert get_netrc_login("netrcexample.org") == (73        "example-username",74        None,75        "example-password",76    )777879@pytest.mark.parametrize(80    "value, expected",81    (82        (83            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',84            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],85        ),86        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),87        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),88        (89            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',90            [91                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},92                {"url": "http://.../back.jpeg"},93            ],94        ),95        ("", []),96    ),97)98def test_parse_header_links(value, expected):99    assert parse_header_links(value) == expected100101102@pytest.mark.asyncio103@pytest.mark.parametrize("httpx_debug", ["0", "1", "True", "False"])104async def test_httpx_debug_enabled_stderr_logging(server, capsys, httpx_debug):105    os.environ["HTTPX_DEBUG"] = httpx_debug106107    # Force a reload on the logging handlers108    utils._LOGGER_INITIALIZED = False109    utils.get_logger("httpx")110111    async with httpx.AsyncClient() as client:112        await client.get(server.url)113114    if httpx_debug in ("1", "True"):115        assert "httpx.dispatch.connection_pool" in capsys.readouterr().err116    else:117        assert "httpx.dispatch.connection_pool" not in capsys.readouterr().err118119    # Reset the logger so we don't have verbose output in all unit tests120    logging.getLogger("httpx").handlers = []121122123@pytest.mark.asyncio124async def test_elapsed_timer():125    with ElapsedTimer() as timer:126        assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)127        await asyncio.sleep(0.1)128    await asyncio.sleep(129        0.1130    )  # test to ensure time spent after timer exits isn't accounted for.131    assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)132133134@pytest.mark.parametrize(135    ["environment", "proxies"],136    [137        ({}, {}),138        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),139        (140            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},141            {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},142        ),143        (144            {"all_proxy": "http://127.0.0.1", "ALL_PROXY": "https://1.1.1.1"},145            {"all": "http://127.0.0.1"},146        ),147        (148            {"https_proxy": "http://127.0.0.1", "HTTPS_PROXY": "https://1.1.1.1"},149            {"https": "http://127.0.0.1"},150        ),151        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),152    ],153)154def test_get_environment_proxies(environment, proxies):155    os.environ.update(environment)156157    assert get_environment_proxies() == proxies