test_utils.py
This file
Path
tests/test_utils.py
298 lines · 8.9 KiB · Python
Last changed by
Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
History of this fileTake it
1import asyncio2import os34import pytest56import httpx7from httpx.utils import (8 ElapsedTimer,9 get_ca_bundle_from_env,10 get_environment_proxies,11 get_netrc,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 os.environ["NETRC"] = "tests/.netrc"58 assert str(get_netrc()) is not None5960 from httpx import utils6162 utils.NETRC_STATIC_FILES = ()6364 os.environ["NETRC"] = "wrongpath"65 assert utils.get_netrc() is None6667 os.environ["NETRC"] = ""68 assert utils.get_netrc() is None697071def test_get_netrc_login():72 os.environ["NETRC"] = "tests/.netrc"73 netrc = get_netrc()74 assert netrc.authenticators("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.asyncio105async def test_logs_debug(server, capsys):106 with override_log_level("debug"):107 async with httpx.AsyncClient() as client:108 response = await client.get(server.url)109 assert response.status_code == 200110 stderr = capsys.readouterr().err111 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr112 assert "httpx.dispatch.connection_pool" not in stderr113114115@pytest.mark.asyncio116async def test_logs_trace(server, capsys):117 with override_log_level("trace"):118 async with httpx.AsyncClient() as client:119 response = await client.get(server.url)120 assert response.status_code == 200121 stderr = capsys.readouterr().err122 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr123 assert "httpx.dispatch.connection_pool" in stderr124125126@pytest.mark.asyncio127async def test_logs_redirect_chain(server, capsys):128 with override_log_level("debug"):129 async with httpx.AsyncClient() as client:130 response = await client.get(server.url.copy_with(path="/redirect_301"))131 assert response.status_code == 200132133 stderr = capsys.readouterr().err.strip()134 redirected_request_line, ok_request_line = stderr.split("\n")135 assert redirected_request_line.endswith(136 "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "137 '"HTTP/1.1 301 Moved Permanently"'138 )139 assert ok_request_line.endswith(140 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'141 )142143144def test_get_ssl_cert_file():145 # Two environments is not set.146 assert get_ca_bundle_from_env() is None147148 os.environ["SSL_CERT_DIR"] = "tests/"149 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.150 assert get_ca_bundle_from_env() == "tests"151152 del os.environ["SSL_CERT_DIR"]153 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"154 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.155 assert get_ca_bundle_from_env() == "tests/test_utils.py"156157 os.environ["SSL_CERT_FILE"] = "wrongfile"158 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.159 assert get_ca_bundle_from_env() is None160161 del os.environ["SSL_CERT_FILE"]162 os.environ["SSL_CERT_DIR"] = "wrongpath"163 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.164 assert get_ca_bundle_from_env() is None165166 os.environ["SSL_CERT_DIR"] = "tests/"167 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"168 # Two environments is correctly set.169 assert get_ca_bundle_from_env() == "tests/test_utils.py"170171 os.environ["SSL_CERT_FILE"] = "wrongfile"172 # Two environments is set but SSL_CERT_FILE is not a file.173 assert get_ca_bundle_from_env() == "tests"174175 os.environ["SSL_CERT_DIR"] = "wrongpath"176 # Two environments is set but both are not correct.177 assert get_ca_bundle_from_env() is None178179180@pytest.mark.asyncio181async def test_elapsed_timer():182 with ElapsedTimer() as timer:183 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)184 await asyncio.sleep(0.1)185 await asyncio.sleep(186 0.1187 ) # test to ensure time spent after timer exits isn't accounted for.188 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)189190191@pytest.mark.parametrize(192 ["environment", "proxies"],193 [194 ({}, {}),195 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),196 (197 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},198 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},199 ),200 ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),201 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),202 ],203)204def test_get_environment_proxies(environment, proxies):205 os.environ.update(environment)206207 assert get_environment_proxies() == proxies208209210@pytest.mark.parametrize(211 "headers, output",212 [213 ([("content-type", "text/html")], [("content-type", "text/html")]),214 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),215 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),216 ],217)218def test_obfuscate_sensitive_headers(headers, output):219 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]220 bytes_output = [(k.encode(), v.encode()) for k, v in output]221 assert list(obfuscate_sensitive_headers(headers)) == output222 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output223224225@pytest.mark.parametrize(226 ["url", "no_proxy", "expected"],227 [228 (229 "http://127.0.0.1",230 {"NO_PROXY": ""},231 False,232 ), # everything proxied when no_proxy is empty/unset233 (234 "http://127.0.0.1",235 {"NO_PROXY": "127.0.0.1"},236 True,237 ), # no_proxy as ip case is matched238 (239 "http://127.0.0.1",240 {"NO_PROXY": "https://127.0.0.1"},241 False,242 ), # no_proxy with scheme is ignored243 (244 "http://127.0.0.1",245 {"NO_PROXY": "1.1.1.1"},246 False,247 ), # different no_proxy means its proxied248 (249 "http://courses.mit.edu",250 {"NO_PROXY": "mit.edu"},251 True,252 ), # no_proxy for sub-domain matches253 (254 "https://mit.edu.info",255 {"NO_PROXY": "mit.edu"},256 False,257 ), # domain is actually edu.info, so should be proxied258 (259 "https://mit.edu.info",260 {"NO_PROXY": "mit.edu,edu.info"},261 True,262 ), # list in no_proxy, matches second domain263 (264 "https://mit.edu.info",265 {"NO_PROXY": "mit.edu, edu.info"},266 True,267 ), # list with spaces in no_proxy268 (269 "https://mit.edu.info",270 {"NO_PROXY": "mit.edu,mit.info"},271 False,272 ), # list in no_proxy, without any domain matching273 (274 "https://foo.example.com",275 {"NO_PROXY": "www.example.com"},276 False,277 ), # different subdomains foo vs www means we still proxy278 (279 "https://www.example1.com",280 {"NO_PROXY": ".example1.com"},281 True,282 ), # no_proxy starting with dot283 (284 "https://www.example2.com",285 {"NO_PROXY": "ample2.com"},286 False,287 ), # whole-domain matching288 (289 "https://www.example3.com",290 {"NO_PROXY": "*"},291 True,292 ), # wildcard * means nothing proxied293 ],294)295def test_should_not_be_proxied(url, no_proxy, expected):296 os.environ.update(no_proxy)297 parsed_url = httpx.models.URL(url)298 assert should_not_be_proxied(parsed_url) == expected