Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

351 lines · 10.9 KiB · Python

Last changed by

URL matching (#1098)Tom Christiebefore adoptiondf54890

History of this file

Take it

1import asyncio2import os3import random45import pytest67import httpx8from httpx._utils import (9    ElapsedTimer,10    NetRCInfo,11    URLMatcher,12    get_ca_bundle_from_env,13    get_environment_proxies,14    guess_json_utf,15    obfuscate_sensitive_headers,16    parse_header_links,17    same_origin,18    should_not_be_proxied,19)20from tests.utils import override_log_level2122from .common import FIXTURES_DIR, TESTS_DIR232425@pytest.mark.parametrize(26    "encoding",27    (28        "utf-32",29        "utf-8-sig",30        "utf-16",31        "utf-8",32        "utf-16-be",33        "utf-16-le",34        "utf-32-be",35        "utf-32-le",36    ),37)38def test_encoded(encoding):39    data = "{}".encode(encoding)40    assert guess_json_utf(data) == encoding414243def test_bad_utf_like_encoding():44    assert guess_json_utf(b"\x00\x00\x00\x00") is None454647@pytest.mark.parametrize(48    ("encoding", "expected"),49    (50        ("utf-16-be", "utf-16"),51        ("utf-16-le", "utf-16"),52        ("utf-32-be", "utf-32"),53        ("utf-32-le", "utf-32"),54    ),55)56def test_guess_by_bom(encoding, expected):57    data = "\ufeff{}".encode(encoding)58    assert guess_json_utf(data) == expected596061def test_bad_get_netrc_login():62    netrc_info = NetRCInfo([str(FIXTURES_DIR / "does-not-exist")])63    assert netrc_info.get_credentials("netrcexample.org") is None646566def test_get_netrc_login():67    netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])68    expected_credentials = (69        "example-username",70        "example-password",71    )72    assert netrc_info.get_credentials("netrcexample.org") == expected_credentials737475def test_get_netrc_unknown():76    netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])77    assert netrc_info.get_credentials("nonexistant.org") is None787980@pytest.mark.parametrize(81    "value, expected",82    (83        (84            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',85            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],86        ),87        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),88        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),89        (90            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',91            [92                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},93                {"url": "http://.../back.jpeg"},94            ],95        ),96        ("", []),97    ),98)99def test_parse_header_links(value, expected):100    assert parse_header_links(value) == expected101102103@pytest.mark.asyncio104async def test_logs_debug(server, capsys):105    with override_log_level("debug"):106        async with httpx.AsyncClient() as client:107            response = await client.get(server.url)108            assert response.status_code == 200109    stderr = capsys.readouterr().err110    assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr111112113@pytest.mark.asyncio114async def test_logs_trace(server, capsys):115    with override_log_level("trace"):116        async with httpx.AsyncClient() as client:117            response = await client.get(server.url)118            assert response.status_code == 200119    stderr = capsys.readouterr().err120    assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr121122123@pytest.mark.asyncio124async def test_logs_redirect_chain(server, capsys):125    with override_log_level("debug"):126        async with httpx.AsyncClient() as client:127            response = await client.get(server.url.copy_with(path="/redirect_301"))128            assert response.status_code == 200129130    stderr = capsys.readouterr().err.strip()131    redirected_request_line, ok_request_line = stderr.split("\n")132    assert redirected_request_line.endswith(133        "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "134        '"HTTP/1.1 301 Moved Permanently"'135    )136    assert ok_request_line.endswith(137        'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'138    )139140141def test_get_ssl_cert_file():142    # Two environments is not set.143    assert get_ca_bundle_from_env() is None144145    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)146    # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.147    ca_bundle = get_ca_bundle_from_env()148    assert ca_bundle is not None and ca_bundle.endswith("tests")149150    del os.environ["SSL_CERT_DIR"]151    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")152    # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.153    ca_bundle = get_ca_bundle_from_env()154    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")155156    os.environ["SSL_CERT_FILE"] = "wrongfile"157    # SSL_CERT_FILE is set with wrong file,  SSL_CERT_DIR is not set.158    assert get_ca_bundle_from_env() is None159160    del os.environ["SSL_CERT_FILE"]161    os.environ["SSL_CERT_DIR"] = "wrongpath"162    # SSL_CERT_DIR is set with wrong path,  SSL_CERT_FILE is not set.163    assert get_ca_bundle_from_env() is None164165    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)166    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")167    # Two environments is correctly set.168    ca_bundle = get_ca_bundle_from_env()169    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")170171    os.environ["SSL_CERT_FILE"] = "wrongfile"172    # Two environments is set but SSL_CERT_FILE is not a file.173    ca_bundle = get_ca_bundle_from_env()174    assert ca_bundle is not None and ca_bundle.endswith("tests")175176    os.environ["SSL_CERT_DIR"] = "wrongpath"177    # Two environments is set but both are not correct.178    assert get_ca_bundle_from_env() is None179180181@pytest.mark.asyncio182async def test_elapsed_timer():183    with ElapsedTimer() as timer:184        assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)185        await asyncio.sleep(0.1)186    await asyncio.sleep(187        0.1188    )  # test to ensure time spent after timer exits isn't accounted for.189    assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)190191192@pytest.mark.parametrize(193    ["environment", "proxies"],194    [195        ({}, {}),196        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),197        (198            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},199            {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},200        ),201        ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),202        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),203    ],204)205def test_get_environment_proxies(environment, proxies):206    os.environ.update(environment)207208    assert get_environment_proxies() == proxies209210211@pytest.mark.parametrize(212    "headers, output",213    [214        ([("content-type", "text/html")], [("content-type", "text/html")]),215        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),216        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),217    ],218)219def test_obfuscate_sensitive_headers(headers, output):220    bytes_headers = [(k.encode(), v.encode()) for k, v in headers]221    bytes_output = [(k.encode(), v.encode()) for k, v in output]222    assert list(obfuscate_sensitive_headers(headers)) == output223    assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output224225226@pytest.mark.parametrize(227    ["url", "no_proxy", "expected"],228    [229        (230            "http://127.0.0.1",231            {"NO_PROXY": ""},232            False,233        ),  # everything proxied when no_proxy is empty/unset234        (235            "http://127.0.0.1",236            {"NO_PROXY": "127.0.0.1"},237            True,238        ),  # no_proxy as ip case is matched239        (240            "http://127.0.0.1",241            {"NO_PROXY": "https://127.0.0.1"},242            False,243        ),  # no_proxy with scheme is ignored244        (245            "http://127.0.0.1",246            {"NO_PROXY": "1.1.1.1"},247            False,248        ),  # different no_proxy means its proxied249        (250            "http://courses.mit.edu",251            {"NO_PROXY": "mit.edu"},252            True,253        ),  # no_proxy for sub-domain matches254        (255            "https://mit.edu.info",256            {"NO_PROXY": "mit.edu"},257            False,258        ),  # domain is actually edu.info, so should be proxied259        (260            "https://mit.edu.info",261            {"NO_PROXY": "mit.edu,edu.info"},262            True,263        ),  # list in no_proxy, matches second domain264        (265            "https://mit.edu.info",266            {"NO_PROXY": "mit.edu, edu.info"},267            True,268        ),  # list with spaces in no_proxy269        (270            "https://mit.edu.info",271            {"NO_PROXY": "mit.edu,mit.info"},272            False,273        ),  # list in no_proxy, without any domain matching274        (275            "https://foo.example.com",276            {"NO_PROXY": "www.example.com"},277            False,278        ),  # different subdomains foo vs www means we still proxy279        (280            "https://www.example1.com",281            {"NO_PROXY": ".example1.com"},282            True,283        ),  # no_proxy starting with dot284        (285            "https://www.example2.com",286            {"NO_PROXY": "ample2.com"},287            False,288        ),  # whole-domain matching289        (290            "https://www.example3.com",291            {"NO_PROXY": "*"},292            True,293        ),  # wildcard * means nothing proxied294    ],295)296def test_should_not_be_proxied(url, no_proxy, expected):297    os.environ.update(no_proxy)298    parsed_url = httpx.URL(url)299    assert should_not_be_proxied(parsed_url) == expected300301302def test_same_origin():303    origin1 = httpx.URL("https://example.com")304    origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")305    assert same_origin(origin1, origin2)306307308def test_not_same_origin():309    origin1 = httpx.URL("https://example.com")310    origin2 = httpx.URL("HTTP://EXAMPLE.COM")311    assert not same_origin(origin1, origin2)312313314@pytest.mark.parametrize(315    ["pattern", "url", "expected"],316    [317        ("http://example.com", "http://example.com", True,),318        ("http://example.com", "https://example.com", False,),319        ("http://example.com", "http://other.com", False,),320        ("http://example.com:123", "http://example.com:123", True,),321        ("http://example.com:123", "http://example.com:456", False,),322        ("http://example.com:123", "http://example.com", False,),323        ("all://example.com", "http://example.com", True,),324        ("all://example.com", "https://example.com", True,),325        ("http://", "http://example.com", True,),326        ("http://", "https://example.com", False,),327        ("http", "http://example.com", True,),328        ("http", "https://example.com", False,),329        ("all", "https://example.com:123", True,),330        ("", "https://example.com:123", True,),331    ],332)333def test_url_matches(pattern, url, expected):334    matcher = URLMatcher(pattern)335    assert matcher.matches(httpx.URL(url)) == expected336337338def test_matcher_priority():339    matchers = [340        URLMatcher("all://"),341        URLMatcher("http://"),342        URLMatcher("http://example.com"),343        URLMatcher("http://example.com:123"),344    ]345    random.shuffle(matchers)346    assert sorted(matchers) == [347        URLMatcher("http://example.com:123"),348        URLMatcher("http://example.com"),349        URLMatcher("http://"),350        URLMatcher("all://"),351    ]