test_utils.py
This file
Path
tests/test_utils.py
210 lines · 6.1 KiB · Python
Last changed by
Add debug logs to ASGIDispatch (#371)Florimond Mancabefore adoptione62e5c3
History of this fileTake it
1import asyncio2import logging3import os45import pytest67import httpx8from httpx import utils9from httpx.utils import (10 ElapsedTimer,11 get_ca_bundle_from_env,12 get_environment_proxies,13 get_netrc_login,14 guess_json_utf,15 obfuscate_sensitive_headers,16 parse_header_links,17)181920@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 assert get_netrc_login("url") is None5859 os.environ["NETRC"] = "tests/.netrc"60 assert get_netrc_login("url") is None6162 os.environ["NETRC"] = "wrongpath"63 assert get_netrc_login("url") is None6465 from httpx import utils6667 utils.NETRC_STATIC_FILES = ()68 os.environ["NETRC"] = ""69 assert utils.get_netrc_login("url") is None707172def test_get_netrc_login():73 os.environ["NETRC"] = "tests/.netrc"74 assert get_netrc_login("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.asyncio105@pytest.mark.parametrize("httpx_debug", ["0", "1", "True", "False"])106async def test_httpx_debug_enabled_stderr_logging(server, capsys, httpx_debug):107 os.environ["HTTPX_DEBUG"] = httpx_debug108109 # Force a reload on the logging handlers110 utils._LOGGER_INITIALIZED = False111 utils.get_logger("httpx")112113 async with httpx.AsyncClient() as client:114 await client.get(server.url)115116 if httpx_debug in ("1", "True"):117 assert "httpx.dispatch.connection_pool" in capsys.readouterr().err118 else:119 assert "httpx.dispatch.connection_pool" not in capsys.readouterr().err120121 # Reset the logger so we don't have verbose output in all unit tests122 logging.getLogger("httpx").handlers = []123124125def test_get_ssl_cert_file():126 # Two environments is not set.127 assert get_ca_bundle_from_env() is None128129 os.environ["SSL_CERT_DIR"] = "tests/"130 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.131 assert get_ca_bundle_from_env() == "tests"132133 del os.environ["SSL_CERT_DIR"]134 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"135 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.136 assert get_ca_bundle_from_env() == "tests/test_utils.py"137138 os.environ["SSL_CERT_FILE"] = "wrongfile"139 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.140 assert get_ca_bundle_from_env() is None141142 del os.environ["SSL_CERT_FILE"]143 os.environ["SSL_CERT_DIR"] = "wrongpath"144 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.145 assert get_ca_bundle_from_env() is None146147 os.environ["SSL_CERT_DIR"] = "tests/"148 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"149 # Two environments is correctly set.150 assert get_ca_bundle_from_env() == "tests/test_utils.py"151152 os.environ["SSL_CERT_FILE"] = "wrongfile"153 # Two environments is set but SSL_CERT_FILE is not a file.154 assert get_ca_bundle_from_env() == "tests"155156 os.environ["SSL_CERT_DIR"] = "wrongpath"157 # Two environments is set but both are not correct.158 assert get_ca_bundle_from_env() is None159160161@pytest.mark.asyncio162async def test_elapsed_timer():163 with ElapsedTimer() as timer:164 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)165 await asyncio.sleep(0.1)166 await asyncio.sleep(167 0.1168 ) # test to ensure time spent after timer exits isn't accounted for.169 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)170171172@pytest.mark.parametrize(173 ["environment", "proxies"],174 [175 ({}, {}),176 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),177 (178 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},179 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},180 ),181 (182 {"all_proxy": "http://127.0.0.1", "ALL_PROXY": "https://1.1.1.1"},183 {"all": "http://127.0.0.1"},184 ),185 (186 {"https_proxy": "http://127.0.0.1", "HTTPS_PROXY": "https://1.1.1.1"},187 {"https": "http://127.0.0.1"},188 ),189 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),190 ],191)192def test_get_environment_proxies(environment, proxies):193 os.environ.update(environment)194195 assert get_environment_proxies() == proxies196197198@pytest.mark.parametrize(199 "headers, output",200 [201 ([("content-type", "text/html")], [("content-type", "text/html")]),202 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),203 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),204 ],205)206def test_obfuscate_sensitive_headers(headers, output):207 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]208 bytes_output = [(k.encode(), v.encode()) for k, v in output]209 assert list(obfuscate_sensitive_headers(headers)) == output210 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output