test_utils.py
This file
Path
tests/test_utils.py
280 lines · 8.2 KiB · Python
Last changed by
Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
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,14 guess_json_utf,15 obfuscate_sensitive_headers,16 parse_header_links,17 should_not_be_proxied,18)192021@pytest.mark.parametrize(22 "encoding",23 (24 "utf-32",25 "utf-8-sig",26 "utf-16",27 "utf-8",28 "utf-16-be",29 "utf-16-le",30 "utf-32-be",31 "utf-32-le",32 ),33)34def test_encoded(encoding):35 data = "{}".encode(encoding)36 assert guess_json_utf(data) == encoding373839def test_bad_utf_like_encoding():40 assert guess_json_utf(b"\x00\x00\x00\x00") is None414243@pytest.mark.parametrize(44 ("encoding", "expected"),45 (46 ("utf-16-be", "utf-16"),47 ("utf-16-le", "utf-16"),48 ("utf-32-be", "utf-32"),49 ("utf-32-le", "utf-32"),50 ),51)52def test_guess_by_bom(encoding, expected):53 data = "\ufeff{}".encode(encoding)54 assert guess_json_utf(data) == expected555657def test_bad_get_netrc_login():58 os.environ["NETRC"] = "tests/.netrc"59 assert str(get_netrc()) is not None6061 from httpx import utils6263 utils.NETRC_STATIC_FILES = ()6465 os.environ["NETRC"] = "wrongpath"66 assert utils.get_netrc() is None6768 os.environ["NETRC"] = ""69 assert utils.get_netrc() is None707172def test_get_netrc_login():73 os.environ["NETRC"] = "tests/.netrc"74 netrc = get_netrc()75 assert netrc.authenticators("netrcexample.org") == (76 "example-username",77 None,78 "example-password",79 )808182@pytest.mark.parametrize(83 "value, expected",84 (85 (86 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',87 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],88 ),89 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),90 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),91 (92 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',93 [94 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},95 {"url": "http://.../back.jpeg"},96 ],97 ),98 ("", []),99 ),100)101def test_parse_header_links(value, expected):102 assert parse_header_links(value) == expected103104105@pytest.mark.asyncio106@pytest.mark.parametrize("httpx_log_level", ["trace", "debug"])107async def test_httpx_log_level_enabled_stderr_logging(server, capsys, httpx_log_level):108 os.environ["HTTPX_LOG_LEVEL"] = httpx_log_level109110 # Force a reload on the logging handlers111 utils._LOGGER_INITIALIZED = False112 utils.get_logger("httpx")113114 async with httpx.AsyncClient() as client:115 await client.get(server.url)116117 if httpx_log_level == "trace":118 assert "httpx.dispatch.connection_pool" in capsys.readouterr().err119 else:120 assert "httpx.dispatch.connection_pool" not in capsys.readouterr().err121122 # Reset the logger so we don't have verbose output in all unit tests123 logging.getLogger("httpx").handlers = []124125126def test_get_ssl_cert_file():127 # Two environments is not set.128 assert get_ca_bundle_from_env() is None129130 os.environ["SSL_CERT_DIR"] = "tests/"131 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.132 assert get_ca_bundle_from_env() == "tests"133134 del os.environ["SSL_CERT_DIR"]135 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"136 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.137 assert get_ca_bundle_from_env() == "tests/test_utils.py"138139 os.environ["SSL_CERT_FILE"] = "wrongfile"140 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.141 assert get_ca_bundle_from_env() is None142143 del os.environ["SSL_CERT_FILE"]144 os.environ["SSL_CERT_DIR"] = "wrongpath"145 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.146 assert get_ca_bundle_from_env() is None147148 os.environ["SSL_CERT_DIR"] = "tests/"149 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"150 # Two environments is correctly set.151 assert get_ca_bundle_from_env() == "tests/test_utils.py"152153 os.environ["SSL_CERT_FILE"] = "wrongfile"154 # Two environments is set but SSL_CERT_FILE is not a file.155 assert get_ca_bundle_from_env() == "tests"156157 os.environ["SSL_CERT_DIR"] = "wrongpath"158 # Two environments is set but both are not correct.159 assert get_ca_bundle_from_env() is None160161162@pytest.mark.asyncio163async def test_elapsed_timer():164 with ElapsedTimer() as timer:165 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)166 await asyncio.sleep(0.1)167 await asyncio.sleep(168 0.1169 ) # test to ensure time spent after timer exits isn't accounted for.170 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)171172173@pytest.mark.parametrize(174 ["environment", "proxies"],175 [176 ({}, {}),177 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),178 (179 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},180 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},181 ),182 ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),183 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),184 ],185)186def test_get_environment_proxies(environment, proxies):187 os.environ.update(environment)188189 assert get_environment_proxies() == proxies190191192@pytest.mark.parametrize(193 "headers, output",194 [195 ([("content-type", "text/html")], [("content-type", "text/html")]),196 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),197 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),198 ],199)200def test_obfuscate_sensitive_headers(headers, output):201 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]202 bytes_output = [(k.encode(), v.encode()) for k, v in output]203 assert list(obfuscate_sensitive_headers(headers)) == output204 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output205206207@pytest.mark.parametrize(208 ["url", "no_proxy", "expected"],209 [210 (211 "http://127.0.0.1",212 {"NO_PROXY": ""},213 False,214 ), # everything proxied when no_proxy is empty/unset215 (216 "http://127.0.0.1",217 {"NO_PROXY": "127.0.0.1"},218 True,219 ), # no_proxy as ip case is matched220 (221 "http://127.0.0.1",222 {"NO_PROXY": "https://127.0.0.1"},223 False,224 ), # no_proxy with scheme is ignored225 (226 "http://127.0.0.1",227 {"NO_PROXY": "1.1.1.1"},228 False,229 ), # different no_proxy means its proxied230 (231 "http://courses.mit.edu",232 {"NO_PROXY": "mit.edu"},233 True,234 ), # no_proxy for sub-domain matches235 (236 "https://mit.edu.info",237 {"NO_PROXY": "mit.edu"},238 False,239 ), # domain is actually edu.info, so should be proxied240 (241 "https://mit.edu.info",242 {"NO_PROXY": "mit.edu,edu.info"},243 True,244 ), # list in no_proxy, matches second domain245 (246 "https://mit.edu.info",247 {"NO_PROXY": "mit.edu, edu.info"},248 True,249 ), # list with spaces in no_proxy250 (251 "https://mit.edu.info",252 {"NO_PROXY": "mit.edu,mit.info"},253 False,254 ), # list in no_proxy, without any domain matching255 (256 "https://foo.example.com",257 {"NO_PROXY": "www.example.com"},258 False,259 ), # different subdomains foo vs www means we still proxy260 (261 "https://www.example1.com",262 {"NO_PROXY": ".example1.com"},263 True,264 ), # no_proxy starting with dot265 (266 "https://www.example2.com",267 {"NO_PROXY": "ample2.com"},268 False,269 ), # whole-domain matching270 (271 "https://www.example3.com",272 {"NO_PROXY": "*"},273 True,274 ), # wildcard * means nothing proxied275 ],276)277def test_should_not_be_proxied(url, no_proxy, expected):278 os.environ.update(no_proxy)279 parsed_url = httpx.models.URL(url)280 assert should_not_be_proxied(parsed_url) == expected