test_utils.py
This file
Path
tests/test_utils.py
296 lines · 9.2 KiB · Python
Last changed by
Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9
History of this fileTake 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 should_not_be_proxied,16)17from tests.utils import override_log_level1819from .common import FIXTURES_DIR, TESTS_DIR202122@pytest.mark.parametrize(23 "encoding",24 (25 "utf-32",26 "utf-8-sig",27 "utf-16",28 "utf-8",29 "utf-16-be",30 "utf-16-le",31 "utf-32-be",32 "utf-32-le",33 ),34)35def test_encoded(encoding):36 data = "{}".encode(encoding)37 assert guess_json_utf(data) == encoding383940def test_bad_utf_like_encoding():41 assert guess_json_utf(b"\x00\x00\x00\x00") is None424344@pytest.mark.parametrize(45 ("encoding", "expected"),46 (47 ("utf-16-be", "utf-16"),48 ("utf-16-le", "utf-16"),49 ("utf-32-be", "utf-32"),50 ("utf-32-le", "utf-32"),51 ),52)53def test_guess_by_bom(encoding, expected):54 data = "\ufeff{}".encode(encoding)55 assert guess_json_utf(data) == expected565758def test_bad_get_netrc_login():59 netrc_info = NetRCInfo([str(FIXTURES_DIR / "does-not-exist")])60 assert netrc_info.get_credentials("netrcexample.org") is None616263def test_get_netrc_login():64 netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])65 expected_credentials = (66 "example-username",67 "example-password",68 )69 assert netrc_info.get_credentials("netrcexample.org") == expected_credentials707172def test_get_netrc_unknown():73 netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])74 assert netrc_info.get_credentials("nonexistant.org") is None757677@pytest.mark.parametrize(78 "value, expected",79 (80 (81 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',82 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],83 ),84 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),85 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),86 (87 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',88 [89 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},90 {"url": "http://.../back.jpeg"},91 ],92 ),93 ("", []),94 ),95)96def test_parse_header_links(value, expected):97 assert parse_header_links(value) == expected9899100@pytest.mark.asyncio101async def test_logs_debug(server, capsys):102 with override_log_level("debug"):103 async with httpx.AsyncClient() as client:104 response = await client.get(server.url)105 assert response.status_code == 200106 stderr = capsys.readouterr().err107 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr108109110@pytest.mark.asyncio111async def test_logs_trace(server, capsys):112 with override_log_level("trace"):113 async with httpx.AsyncClient() as client:114 response = await client.get(server.url)115 assert response.status_code == 200116 stderr = capsys.readouterr().err117 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr118119120@pytest.mark.asyncio121async def test_logs_redirect_chain(server, capsys):122 with override_log_level("debug"):123 async with httpx.AsyncClient() as client:124 response = await client.get(server.url.copy_with(path="/redirect_301"))125 assert response.status_code == 200126127 stderr = capsys.readouterr().err.strip()128 redirected_request_line, ok_request_line = stderr.split("\n")129 assert redirected_request_line.endswith(130 "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "131 '"HTTP/1.1 301 Moved Permanently"'132 )133 assert ok_request_line.endswith(134 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'135 )136137138def test_get_ssl_cert_file():139 # Two environments is not set.140 assert get_ca_bundle_from_env() is None141142 os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)143 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.144 ca_bundle = get_ca_bundle_from_env()145 assert ca_bundle is not None and ca_bundle.endswith("tests")146147 del os.environ["SSL_CERT_DIR"]148 os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")149 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.150 ca_bundle = get_ca_bundle_from_env()151 assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")152153 os.environ["SSL_CERT_FILE"] = "wrongfile"154 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.155 assert get_ca_bundle_from_env() is None156157 del os.environ["SSL_CERT_FILE"]158 os.environ["SSL_CERT_DIR"] = "wrongpath"159 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.160 assert get_ca_bundle_from_env() is None161162 os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)163 os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")164 # Two environments is correctly set.165 ca_bundle = get_ca_bundle_from_env()166 assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")167168 os.environ["SSL_CERT_FILE"] = "wrongfile"169 # Two environments is set but SSL_CERT_FILE is not a file.170 ca_bundle = get_ca_bundle_from_env()171 assert ca_bundle is not None and ca_bundle.endswith("tests")172173 os.environ["SSL_CERT_DIR"] = "wrongpath"174 # Two environments is set but both are not correct.175 assert get_ca_bundle_from_env() is None176177178@pytest.mark.asyncio179async def test_elapsed_timer():180 with ElapsedTimer() as timer:181 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)182 await asyncio.sleep(0.1)183 await asyncio.sleep(184 0.1185 ) # test to ensure time spent after timer exits isn't accounted for.186 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)187188189@pytest.mark.parametrize(190 ["environment", "proxies"],191 [192 ({}, {}),193 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),194 (195 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},196 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},197 ),198 ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),199 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),200 ],201)202def test_get_environment_proxies(environment, proxies):203 os.environ.update(environment)204205 assert get_environment_proxies() == proxies206207208@pytest.mark.parametrize(209 "headers, output",210 [211 ([("content-type", "text/html")], [("content-type", "text/html")]),212 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),213 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),214 ],215)216def test_obfuscate_sensitive_headers(headers, output):217 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]218 bytes_output = [(k.encode(), v.encode()) for k, v in output]219 assert list(obfuscate_sensitive_headers(headers)) == output220 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output221222223@pytest.mark.parametrize(224 ["url", "no_proxy", "expected"],225 [226 (227 "http://127.0.0.1",228 {"NO_PROXY": ""},229 False,230 ), # everything proxied when no_proxy is empty/unset231 (232 "http://127.0.0.1",233 {"NO_PROXY": "127.0.0.1"},234 True,235 ), # no_proxy as ip case is matched236 (237 "http://127.0.0.1",238 {"NO_PROXY": "https://127.0.0.1"},239 False,240 ), # no_proxy with scheme is ignored241 (242 "http://127.0.0.1",243 {"NO_PROXY": "1.1.1.1"},244 False,245 ), # different no_proxy means its proxied246 (247 "http://courses.mit.edu",248 {"NO_PROXY": "mit.edu"},249 True,250 ), # no_proxy for sub-domain matches251 (252 "https://mit.edu.info",253 {"NO_PROXY": "mit.edu"},254 False,255 ), # domain is actually edu.info, so should be proxied256 (257 "https://mit.edu.info",258 {"NO_PROXY": "mit.edu,edu.info"},259 True,260 ), # list in no_proxy, matches second domain261 (262 "https://mit.edu.info",263 {"NO_PROXY": "mit.edu, edu.info"},264 True,265 ), # list with spaces in no_proxy266 (267 "https://mit.edu.info",268 {"NO_PROXY": "mit.edu,mit.info"},269 False,270 ), # list in no_proxy, without any domain matching271 (272 "https://foo.example.com",273 {"NO_PROXY": "www.example.com"},274 False,275 ), # different subdomains foo vs www means we still proxy276 (277 "https://www.example1.com",278 {"NO_PROXY": ".example1.com"},279 True,280 ), # no_proxy starting with dot281 (282 "https://www.example2.com",283 {"NO_PROXY": "ample2.com"},284 False,285 ), # whole-domain matching286 (287 "https://www.example3.com",288 {"NO_PROXY": "*"},289 True,290 ), # wildcard * means nothing proxied291 ],292)293def test_should_not_be_proxied(url, no_proxy, expected):294 os.environ.update(no_proxy)295 parsed_url = httpx.URL(url)296 assert should_not_be_proxied(parsed_url) == expected