test_utils.py
This file
Path
tests/test_utils.py
285 lines · 8.7 KiB · Python
Last changed by
Httpcore interface (#804)Tom Christiebefore adoption3046e92
History of this fileTake it
The walk stopped after 200 commits: lines older than c033ed1 point at it.
TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
lines 1–6why, one step back1import asyncio2import os34import pytest56import httpxSwitch to private module names (#785)Florimond Mancabefore adoption82dc6f3
line 7why, one step back7from httpx._utils import (TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
lines 8–95why, one step back8 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_level181920@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 netrc_info = NetRCInfo(["tests/does-not-exist"])58 assert netrc_info.get_credentials("netrcexample.org") is None596061def test_get_netrc_login():62 netrc_info = NetRCInfo(["tests/.netrc"])63 expected_credentials = (64 "example-username",65 "example-password",66 )67 assert netrc_info.get_credentials("netrcexample.org") == expected_credentials686970@pytest.mark.parametrize(71 "value, expected",72 (73 (74 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',75 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],76 ),77 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),78 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),79 (80 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',81 [82 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},83 {"url": "http://.../back.jpeg"},84 ],85 ),86 ("", []),87 ),88)89def test_parse_header_links(value, expected):90 assert parse_header_links(value) == expected919293@pytest.mark.asyncio94async def test_logs_debug(server, capsys):95 with override_log_level("debug"):Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 96why, one step back96 async with httpx.AsyncClient() as client:TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
lines 97–105why, one step back97 response = await client.get(server.url)98 assert response.status_code == 20099 stderr = capsys.readouterr().err100 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr101102103@pytest.mark.asyncio104async def test_logs_trace(server, capsys):105 with override_log_level("trace"):Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 106why, one step back106 async with httpx.AsyncClient() as client:TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
lines 107–115why, one step back107 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_redirect_chain(server, capsys):115 with override_log_level("debug"):Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 116why, one step back116 async with httpx.AsyncClient() as client:TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
lines 117–283why, one step back117 response = await client.get(server.url.copy_with(path="/redirect_301"))118 assert response.status_code == 200119120 stderr = capsys.readouterr().err.strip()121 redirected_request_line, ok_request_line = stderr.split("\n")122 assert redirected_request_line.endswith(123 "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "124 '"HTTP/1.1 301 Moved Permanently"'125 )126 assert ok_request_line.endswith(127 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'128 )129130131def test_get_ssl_cert_file():132 # Two environments is not set.133 assert get_ca_bundle_from_env() is None134135 os.environ["SSL_CERT_DIR"] = "tests/"136 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.137 assert get_ca_bundle_from_env() == "tests"138139 del os.environ["SSL_CERT_DIR"]140 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"141 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.142 assert get_ca_bundle_from_env() == "tests/test_utils.py"143144 os.environ["SSL_CERT_FILE"] = "wrongfile"145 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.146 assert get_ca_bundle_from_env() is None147148 del os.environ["SSL_CERT_FILE"]149 os.environ["SSL_CERT_DIR"] = "wrongpath"150 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.151 assert get_ca_bundle_from_env() is None152153 os.environ["SSL_CERT_DIR"] = "tests/"154 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"155 # Two environments is correctly set.156 assert get_ca_bundle_from_env() == "tests/test_utils.py"157158 os.environ["SSL_CERT_FILE"] = "wrongfile"159 # Two environments is set but SSL_CERT_FILE is not a file.160 assert get_ca_bundle_from_env() == "tests"161162 os.environ["SSL_CERT_DIR"] = "wrongpath"163 # Two environments is set but both are not correct.164 assert get_ca_bundle_from_env() is None165166167@pytest.mark.asyncio168async def test_elapsed_timer():169 with ElapsedTimer() as timer:170 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)171 await asyncio.sleep(0.1)172 await asyncio.sleep(173 0.1174 ) # test to ensure time spent after timer exits isn't accounted for.175 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)176177178@pytest.mark.parametrize(179 ["environment", "proxies"],180 [181 ({}, {}),182 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),183 (184 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},185 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},186 ),187 ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),188 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),189 ],190)191def test_get_environment_proxies(environment, proxies):192 os.environ.update(environment)193194 assert get_environment_proxies() == proxies195196197@pytest.mark.parametrize(198 "headers, output",199 [200 ([("content-type", "text/html")], [("content-type", "text/html")]),201 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),202 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),203 ],204)205def test_obfuscate_sensitive_headers(headers, output):206 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]207 bytes_output = [(k.encode(), v.encode()) for k, v in output]208 assert list(obfuscate_sensitive_headers(headers)) == output209 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output210211212@pytest.mark.parametrize(213 ["url", "no_proxy", "expected"],214 [215 (216 "http://127.0.0.1",217 {"NO_PROXY": ""},218 False,219 ), # everything proxied when no_proxy is empty/unset220 (221 "http://127.0.0.1",222 {"NO_PROXY": "127.0.0.1"},223 True,224 ), # no_proxy as ip case is matched225 (226 "http://127.0.0.1",227 {"NO_PROXY": "https://127.0.0.1"},228 False,229 ), # no_proxy with scheme is ignored230 (231 "http://127.0.0.1",232 {"NO_PROXY": "1.1.1.1"},233 False,234 ), # different no_proxy means its proxied235 (236 "http://courses.mit.edu",237 {"NO_PROXY": "mit.edu"},238 True,239 ), # no_proxy for sub-domain matches240 (241 "https://mit.edu.info",242 {"NO_PROXY": "mit.edu"},243 False,244 ), # domain is actually edu.info, so should be proxied245 (246 "https://mit.edu.info",247 {"NO_PROXY": "mit.edu,edu.info"},248 True,249 ), # list in no_proxy, matches second domain250 (251 "https://mit.edu.info",252 {"NO_PROXY": "mit.edu, edu.info"},253 True,254 ), # list with spaces in no_proxy255 (256 "https://mit.edu.info",257 {"NO_PROXY": "mit.edu,mit.info"},258 False,259 ), # list in no_proxy, without any domain matching260 (261 "https://foo.example.com",262 {"NO_PROXY": "www.example.com"},263 False,264 ), # different subdomains foo vs www means we still proxy265 (266 "https://www.example1.com",267 {"NO_PROXY": ".example1.com"},268 True,269 ), # no_proxy starting with dot270 (271 "https://www.example2.com",272 {"NO_PROXY": "ample2.com"},273 False,274 ), # whole-domain matching275 (276 "https://www.example3.com",277 {"NO_PROXY": "*"},278 True,279 ), # wildcard * means nothing proxied280 ],281)282def test_should_not_be_proxied(url, no_proxy, expected):283 os.environ.update(no_proxy)Switch to private module names (#785)Florimond Mancabefore adoption82dc6f3
line 284why, one step back284 parsed_url = httpx.URL(url)TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 285why, one step back285 assert should_not_be_proxied(parsed_url) == expected