Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

309 lines · 9.5 KiB · Python

Last changed by

Drop private Origin model (#1070)Tom Christiebefore adoption247ee0d

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    same_origin,16    should_not_be_proxied,17)18from tests.utils import override_log_level1920from .common import FIXTURES_DIR, TESTS_DIR212223@pytest.mark.parametrize(24    "encoding",25    (26        "utf-32",27        "utf-8-sig",28        "utf-16",29        "utf-8",30        "utf-16-be",31        "utf-16-le",32        "utf-32-be",33        "utf-32-le",34    ),35)36def test_encoded(encoding):37    data = "{}".encode(encoding)38    assert guess_json_utf(data) == encoding394041def test_bad_utf_like_encoding():42    assert guess_json_utf(b"\x00\x00\x00\x00") is None434445@pytest.mark.parametrize(46    ("encoding", "expected"),47    (48        ("utf-16-be", "utf-16"),49        ("utf-16-le", "utf-16"),50        ("utf-32-be", "utf-32"),51        ("utf-32-le", "utf-32"),52    ),53)54def test_guess_by_bom(encoding, expected):55    data = "\ufeff{}".encode(encoding)56    assert guess_json_utf(data) == expected575859def test_bad_get_netrc_login():60    netrc_info = NetRCInfo([str(FIXTURES_DIR / "does-not-exist")])61    assert netrc_info.get_credentials("netrcexample.org") is None626364def test_get_netrc_login():65    netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])66    expected_credentials = (67        "example-username",68        "example-password",69    )70    assert netrc_info.get_credentials("netrcexample.org") == expected_credentials717273def test_get_netrc_unknown():74    netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])75    assert netrc_info.get_credentials("nonexistant.org") is None767778@pytest.mark.parametrize(79    "value, expected",80    (81        (82            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',83            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],84        ),85        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),86        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),87        (88            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',89            [90                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},91                {"url": "http://.../back.jpeg"},92            ],93        ),94        ("", []),95    ),96)97def test_parse_header_links(value, expected):98    assert parse_header_links(value) == expected99100101@pytest.mark.asyncio102async def test_logs_debug(server, capsys):103    with override_log_level("debug"):104        async with httpx.AsyncClient() as client:105            response = await client.get(server.url)106            assert response.status_code == 200107    stderr = capsys.readouterr().err108    assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr109110111@pytest.mark.asyncio112async def test_logs_trace(server, capsys):113    with override_log_level("trace"):114        async with httpx.AsyncClient() as client:115            response = await client.get(server.url)116            assert response.status_code == 200117    stderr = capsys.readouterr().err118    assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr119120121@pytest.mark.asyncio122async def test_logs_redirect_chain(server, capsys):123    with override_log_level("debug"):124        async with httpx.AsyncClient() as client:125            response = await client.get(server.url.copy_with(path="/redirect_301"))126            assert response.status_code == 200127128    stderr = capsys.readouterr().err.strip()129    redirected_request_line, ok_request_line = stderr.split("\n")130    assert redirected_request_line.endswith(131        "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "132        '"HTTP/1.1 301 Moved Permanently"'133    )134    assert ok_request_line.endswith(135        'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'136    )137138139def test_get_ssl_cert_file():140    # Two environments is not set.141    assert get_ca_bundle_from_env() is None142143    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)144    # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.145    ca_bundle = get_ca_bundle_from_env()146    assert ca_bundle is not None and ca_bundle.endswith("tests")147148    del os.environ["SSL_CERT_DIR"]149    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")150    # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.151    ca_bundle = get_ca_bundle_from_env()152    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")153154    os.environ["SSL_CERT_FILE"] = "wrongfile"155    # SSL_CERT_FILE is set with wrong file,  SSL_CERT_DIR is not set.156    assert get_ca_bundle_from_env() is None157158    del os.environ["SSL_CERT_FILE"]159    os.environ["SSL_CERT_DIR"] = "wrongpath"160    # SSL_CERT_DIR is set with wrong path,  SSL_CERT_FILE is not set.161    assert get_ca_bundle_from_env() is None162163    os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)164    os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")165    # Two environments is correctly set.166    ca_bundle = get_ca_bundle_from_env()167    assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")168169    os.environ["SSL_CERT_FILE"] = "wrongfile"170    # Two environments is set but SSL_CERT_FILE is not a file.171    ca_bundle = get_ca_bundle_from_env()172    assert ca_bundle is not None and ca_bundle.endswith("tests")173174    os.environ["SSL_CERT_DIR"] = "wrongpath"175    # Two environments is set but both are not correct.176    assert get_ca_bundle_from_env() is None177178179@pytest.mark.asyncio180async def test_elapsed_timer():181    with ElapsedTimer() as timer:182        assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)183        await asyncio.sleep(0.1)184    await asyncio.sleep(185        0.1186    )  # test to ensure time spent after timer exits isn't accounted for.187    assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)188189190@pytest.mark.parametrize(191    ["environment", "proxies"],192    [193        ({}, {}),194        ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),195        (196            {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},197            {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},198        ),199        ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),200        ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),201    ],202)203def test_get_environment_proxies(environment, proxies):204    os.environ.update(environment)205206    assert get_environment_proxies() == proxies207208209@pytest.mark.parametrize(210    "headers, output",211    [212        ([("content-type", "text/html")], [("content-type", "text/html")]),213        ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),214        ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),215    ],216)217def test_obfuscate_sensitive_headers(headers, output):218    bytes_headers = [(k.encode(), v.encode()) for k, v in headers]219    bytes_output = [(k.encode(), v.encode()) for k, v in output]220    assert list(obfuscate_sensitive_headers(headers)) == output221    assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output222223224@pytest.mark.parametrize(225    ["url", "no_proxy", "expected"],226    [227        (228            "http://127.0.0.1",229            {"NO_PROXY": ""},230            False,231        ),  # everything proxied when no_proxy is empty/unset232        (233            "http://127.0.0.1",234            {"NO_PROXY": "127.0.0.1"},235            True,236        ),  # no_proxy as ip case is matched237        (238            "http://127.0.0.1",239            {"NO_PROXY": "https://127.0.0.1"},240            False,241        ),  # no_proxy with scheme is ignored242        (243            "http://127.0.0.1",244            {"NO_PROXY": "1.1.1.1"},245            False,246        ),  # different no_proxy means its proxied247        (248            "http://courses.mit.edu",249            {"NO_PROXY": "mit.edu"},250            True,251        ),  # no_proxy for sub-domain matches252        (253            "https://mit.edu.info",254            {"NO_PROXY": "mit.edu"},255            False,256        ),  # domain is actually edu.info, so should be proxied257        (258            "https://mit.edu.info",259            {"NO_PROXY": "mit.edu,edu.info"},260            True,261        ),  # list in no_proxy, matches second domain262        (263            "https://mit.edu.info",264            {"NO_PROXY": "mit.edu, edu.info"},265            True,266        ),  # list with spaces in no_proxy267        (268            "https://mit.edu.info",269            {"NO_PROXY": "mit.edu,mit.info"},270            False,271        ),  # list in no_proxy, without any domain matching272        (273            "https://foo.example.com",274            {"NO_PROXY": "www.example.com"},275            False,276        ),  # different subdomains foo vs www means we still proxy277        (278            "https://www.example1.com",279            {"NO_PROXY": ".example1.com"},280            True,281        ),  # no_proxy starting with dot282        (283            "https://www.example2.com",284            {"NO_PROXY": "ample2.com"},285            False,286        ),  # whole-domain matching287        (288            "https://www.example3.com",289            {"NO_PROXY": "*"},290            True,291        ),  # wildcard * means nothing proxied292    ],293)294def test_should_not_be_proxied(url, no_proxy, expected):295    os.environ.update(no_proxy)296    parsed_url = httpx.URL(url)297    assert should_not_be_proxied(parsed_url) == expected298299300def test_same_origin():301    origin1 = httpx.URL("https://example.com")302    origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")303    assert same_origin(origin1, origin2)304305306def test_not_same_origin():307    origin1 = httpx.URL("https://example.com")308    origin2 = httpx.URL("HTTP://EXAMPLE.COM")309    assert not same_origin(origin1, origin2)