test_utils.py
This file
Path
tests/test_utils.py
274 lines · 8.7 KiB · Python
Last changed by
Cleaner no proxy support (#1103)Tom Christiebefore adoption682cad3
History of this fileTake it
1import asyncio2import os3import random45import pytest67import httpx8from httpx._utils import (9 ElapsedTimer,10 NetRCInfo,11 URLPattern,12 get_ca_bundle_from_env,13 get_environment_proxies,14 guess_json_utf,15 obfuscate_sensitive_headers,16 parse_header_links,17 same_origin,18)19from tests.utils import override_log_level2021from .common import FIXTURES_DIR, TESTS_DIR222324@pytest.mark.parametrize(25 "encoding",26 (27 "utf-32",28 "utf-8-sig",29 "utf-16",30 "utf-8",31 "utf-16-be",32 "utf-16-le",33 "utf-32-be",34 "utf-32-le",35 ),36)37def test_encoded(encoding):38 data = "{}".encode(encoding)39 assert guess_json_utf(data) == encoding404142def test_bad_utf_like_encoding():43 assert guess_json_utf(b"\x00\x00\x00\x00") is None444546@pytest.mark.parametrize(47 ("encoding", "expected"),48 (49 ("utf-16-be", "utf-16"),50 ("utf-16-le", "utf-16"),51 ("utf-32-be", "utf-32"),52 ("utf-32-le", "utf-32"),53 ),54)55def test_guess_by_bom(encoding, expected):56 data = "\ufeff{}".encode(encoding)57 assert guess_json_utf(data) == expected585960def test_bad_get_netrc_login():61 netrc_info = NetRCInfo([str(FIXTURES_DIR / "does-not-exist")])62 assert netrc_info.get_credentials("netrcexample.org") is None636465def test_get_netrc_login():66 netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])67 expected_credentials = (68 "example-username",69 "example-password",70 )71 assert netrc_info.get_credentials("netrcexample.org") == expected_credentials727374def test_get_netrc_unknown():75 netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])76 assert netrc_info.get_credentials("nonexistant.org") is None777879@pytest.mark.parametrize(80 "value, expected",81 (82 (83 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',84 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],85 ),86 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),87 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),88 (89 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',90 [91 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},92 {"url": "http://.../back.jpeg"},93 ],94 ),95 ("", []),96 ),97)98def test_parse_header_links(value, expected):99 assert parse_header_links(value) == expected100101102@pytest.mark.asyncio103async def test_logs_debug(server, capsys):104 with override_log_level("debug"):105 async with httpx.AsyncClient() as client:106 response = await client.get(server.url)107 assert response.status_code == 200108 stderr = capsys.readouterr().err109 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr110111112@pytest.mark.asyncio113async def test_logs_trace(server, capsys):114 with override_log_level("trace"):115 async with httpx.AsyncClient() as client:116 response = await client.get(server.url)117 assert response.status_code == 200118 stderr = capsys.readouterr().err119 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr120121122@pytest.mark.asyncio123async def test_logs_redirect_chain(server, capsys):124 with override_log_level("debug"):125 async with httpx.AsyncClient() as client:126 response = await client.get(server.url.copy_with(path="/redirect_301"))127 assert response.status_code == 200128129 stderr = capsys.readouterr().err.strip()130 redirected_request_line, ok_request_line = stderr.split("\n")131 assert redirected_request_line.endswith(132 "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "133 '"HTTP/1.1 301 Moved Permanently"'134 )135 assert ok_request_line.endswith(136 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'137 )138139140def test_get_ssl_cert_file():141 # Two environments is not set.142 assert get_ca_bundle_from_env() is None143144 os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)145 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.146 ca_bundle = get_ca_bundle_from_env()147 assert ca_bundle is not None and ca_bundle.endswith("tests")148149 del os.environ["SSL_CERT_DIR"]150 os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")151 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.152 ca_bundle = get_ca_bundle_from_env()153 assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")154155 os.environ["SSL_CERT_FILE"] = "wrongfile"156 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.157 assert get_ca_bundle_from_env() is None158159 del os.environ["SSL_CERT_FILE"]160 os.environ["SSL_CERT_DIR"] = "wrongpath"161 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.162 assert get_ca_bundle_from_env() is None163164 os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)165 os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")166 # Two environments is correctly set.167 ca_bundle = get_ca_bundle_from_env()168 assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")169170 os.environ["SSL_CERT_FILE"] = "wrongfile"171 # Two environments is set but SSL_CERT_FILE is not a file.172 ca_bundle = get_ca_bundle_from_env()173 assert ca_bundle is not None and ca_bundle.endswith("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_output223224225def test_same_origin():226 origin1 = httpx.URL("https://example.com")227 origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")228 assert same_origin(origin1, origin2)229230231def test_not_same_origin():232 origin1 = httpx.URL("https://example.com")233 origin2 = httpx.URL("HTTP://EXAMPLE.COM")234 assert not same_origin(origin1, origin2)235236237@pytest.mark.parametrize(238 ["pattern", "url", "expected"],239 [240 ("http://example.com", "http://example.com", True,),241 ("http://example.com", "https://example.com", False,),242 ("http://example.com", "http://other.com", False,),243 ("http://example.com:123", "http://example.com:123", True,),244 ("http://example.com:123", "http://example.com:456", False,),245 ("http://example.com:123", "http://example.com", False,),246 ("all://example.com", "http://example.com", True,),247 ("all://example.com", "https://example.com", True,),248 ("http://", "http://example.com", True,),249 ("http://", "https://example.com", False,),250 ("http", "http://example.com", True,),251 ("http", "https://example.com", False,),252 ("all", "https://example.com:123", True,),253 ("", "https://example.com:123", True,),254 ],255)256def test_url_matches(pattern, url, expected):257 pattern = URLPattern(pattern)258 assert pattern.matches(httpx.URL(url)) == expected259260261def test_pattern_priority():262 matchers = [263 URLPattern("all://"),264 URLPattern("http://"),265 URLPattern("http://example.com"),266 URLPattern("http://example.com:123"),267 ]268 random.shuffle(matchers)269 assert sorted(matchers) == [270 URLPattern("http://example.com:123"),271 URLPattern("http://example.com"),272 URLPattern("http://"),273 URLPattern("all://"),274 ]