test_utils.py
This file
Path
tests/test_utils.py
278 lines · 8.8 KiB · Python
Last changed by
Preserve Authorization header on HTTPS redirect (#1850) (#2074)waterfountain1996before adoption4401d55
History of this fileTake it
The walk stopped after 200 commits: lines older than 52dd95f point at it.
Fix extenstions typo in AsyncHTTPTransport (#1549)Jonas Lundbergbefore adoption52dd95f
lines 1–12why, one step back1import os2import random34import pytest56import httpx7from httpx._utils import (8 NetRCInfo,9 URLPattern,10 get_ca_bundle_from_env,11 get_environment_proxies,12 guess_json_utf,Preserve Authorization header on HTTPS redirect (#1850) (#2074)waterfountain1996before adoption4401d55
line 13why, one step back13 is_https_redirect,Fix extenstions typo in AsyncHTTPTransport (#1549)Jonas Lundbergbefore adoption52dd95f
lines 14–74why, one step back14 obfuscate_sensitive_headers,15 parse_header_links,16 same_origin,17)18from tests.utils import override_log_level1920from .common import FIXTURES_DIR, TESTS_DIR212223@pytest.mark.parametrize(24 "encoding",25 (26 "utf-32",27 "utf-8-sig",28 "utf-16",29 "utf-8",30 "utf-16-be",31 "utf-16-le",32 "utf-32-be",33 "utf-32-le",34 ),35)36def test_encoded(encoding):37 data = "{}".encode(encoding)38 assert guess_json_utf(data) == encoding394041def test_bad_utf_like_encoding():42 assert guess_json_utf(b"\x00\x00\x00\x00") is None434445@pytest.mark.parametrize(46 ("encoding", "expected"),47 (48 ("utf-16-be", "utf-16"),49 ("utf-16-le", "utf-16"),50 ("utf-32-be", "utf-32"),51 ("utf-32-le", "utf-32"),52 ),53)54def test_guess_by_bom(encoding, expected):55 data = "\ufeff{}".encode(encoding)56 assert guess_json_utf(data) == expected575859def test_bad_get_netrc_login():60 netrc_info = NetRCInfo([str(FIXTURES_DIR / "does-not-exist")])61 assert netrc_info.get_credentials("netrcexample.org") is None626364def test_get_netrc_login():65 netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])66 expected_credentials = (67 "example-username",68 "example-password",69 )70 assert netrc_info.get_credentials("netrcexample.org") == expected_credentials717273def test_get_netrc_unknown():74 netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])Fix typos (#1968)Kian Meng, Angbefore adoption82ba15b
line 75why, one step back75 assert netrc_info.get_credentials("nonexistent.org") is NoneFix extenstions typo in AsyncHTTPTransport (#1549)Jonas Lundbergbefore adoption52dd95f
lines 76–123why, one step back767778@pytest.mark.parametrize(79 "value, expected",80 (81 (82 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',83 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],84 ),85 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),86 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),87 (88 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',89 [90 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},91 {"url": "http://.../back.jpeg"},92 ],93 ),94 ("", []),95 ),96)97def test_parse_header_links(value, expected):98 assert parse_header_links(value) == expected99100101@pytest.mark.asyncio102async def test_logs_debug(server, capsys):103 with override_log_level("debug"):104 async with httpx.AsyncClient() as client:105 response = await client.get(server.url)106 assert response.status_code == 200107 stderr = capsys.readouterr().err108 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr109110111@pytest.mark.asyncio112async def test_logs_trace(server, capsys):113 with override_log_level("trace"):114 async with httpx.AsyncClient() as client:115 response = await client.get(server.url)116 assert response.status_code == 200117 stderr = capsys.readouterr().err118 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr119120121@pytest.mark.asyncio122async def test_logs_redirect_chain(server, capsys):123 with override_log_level("debug"):Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 124why, one step back124 async with httpx.AsyncClient(follow_redirects=True) as client:Fix extenstions typo in AsyncHTTPTransport (#1549)Jonas Lundbergbefore adoption52dd95f
lines 125–222why, one step back125 response = await client.get(server.url.copy_with(path="/redirect_301"))126 assert response.status_code == 200127128 stderr = capsys.readouterr().err.strip()129 redirected_request_line, ok_request_line = stderr.split("\n")130 assert redirected_request_line.endswith(131 "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "132 '"HTTP/1.1 301 Moved Permanently"'133 )134 assert ok_request_line.endswith(135 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'136 )137138139def test_get_ssl_cert_file():140 # Two environments is not set.141 assert get_ca_bundle_from_env() is None142143 os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)144 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.145 ca_bundle = get_ca_bundle_from_env()146 assert ca_bundle is not None and ca_bundle.endswith("tests")147148 del os.environ["SSL_CERT_DIR"]149 os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")150 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.151 ca_bundle = get_ca_bundle_from_env()152 assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")153154 os.environ["SSL_CERT_FILE"] = "wrongfile"155 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.156 assert get_ca_bundle_from_env() is None157158 del os.environ["SSL_CERT_FILE"]159 os.environ["SSL_CERT_DIR"] = "wrongpath"160 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.161 assert get_ca_bundle_from_env() is None162163 os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)164 os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")165 # Two environments is correctly set.166 ca_bundle = get_ca_bundle_from_env()167 assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")168169 os.environ["SSL_CERT_FILE"] = "wrongfile"170 # Two environments is set but SSL_CERT_FILE is not a file.171 ca_bundle = get_ca_bundle_from_env()172 assert ca_bundle is not None and ca_bundle.endswith("tests")173174 os.environ["SSL_CERT_DIR"] = "wrongpath"175 # Two environments is set but both are not correct.176 assert get_ca_bundle_from_env() is None177178179@pytest.mark.parametrize(180 ["environment", "proxies"],181 [182 ({}, {}),183 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http://": "http://127.0.0.1"}),184 (185 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},186 {"https://": "http://127.0.0.1", "http://": "https://127.0.0.1"},187 ),188 ({"all_proxy": "http://127.0.0.1"}, {"all://": "http://127.0.0.1"}),189 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),190 ],191)192def test_get_environment_proxies(environment, proxies):193 os.environ.update(environment)194195 assert get_environment_proxies() == proxies196197198@pytest.mark.parametrize(199 "headers, output",200 [201 ([("content-type", "text/html")], [("content-type", "text/html")]),202 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),203 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),204 ],205)206def test_obfuscate_sensitive_headers(headers, output):207 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]208 bytes_output = [(k.encode(), v.encode()) for k, v in output]209 assert list(obfuscate_sensitive_headers(headers)) == output210 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output211212213def test_same_origin():214 origin1 = httpx.URL("https://example.com")215 origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")216 assert same_origin(origin1, origin2)217218219def test_not_same_origin():220 origin1 = httpx.URL("https://example.com")221 origin2 = httpx.URL("HTTP://EXAMPLE.COM")222 assert not same_origin(origin1, origin2)Preserve Authorization header on HTTPS redirect (#1850) (#2074)waterfountain1996before adoption4401d55
lines 223–240why, one step back223224225def test_is_https_redirect():226 url = httpx.URL("http://example.com")227 location = httpx.URL("https://example.com")228 assert is_https_redirect(url, location)229230231def test_is_not_https_redirect():232 url = httpx.URL("http://example.com")233 location = httpx.URL("https://www.example.com")234 assert not is_https_redirect(url, location)235236237def test_is_not_https_redirect_if_not_default_ports():238 url = httpx.URL("http://example.com:9999")239 location = httpx.URL("https://example.com:1337")240 assert not is_https_redirect(url, location)Fix extenstions typo in AsyncHTTPTransport (#1549)Jonas Lundbergbefore adoption52dd95f
lines 241–278why, one step back241242243@pytest.mark.parametrize(244 ["pattern", "url", "expected"],245 [246 ("http://example.com", "http://example.com", True),247 ("http://example.com", "https://example.com", False),248 ("http://example.com", "http://other.com", False),249 ("http://example.com:123", "http://example.com:123", True),250 ("http://example.com:123", "http://example.com:456", False),251 ("http://example.com:123", "http://example.com", False),252 ("all://example.com", "http://example.com", True),253 ("all://example.com", "https://example.com", True),254 ("http://", "http://example.com", True),255 ("http://", "https://example.com", False),256 ("all://", "https://example.com:123", True),257 ("", "https://example.com:123", True),258 ],259)260def test_url_matches(pattern, url, expected):261 pattern = URLPattern(pattern)262 assert pattern.matches(httpx.URL(url)) == expected263264265def test_pattern_priority():266 matchers = [267 URLPattern("all://"),268 URLPattern("http://"),269 URLPattern("http://example.com"),270 URLPattern("http://example.com:123"),271 ]272 random.shuffle(matchers)273 assert sorted(matchers) == [274 URLPattern("http://example.com:123"),275 URLPattern("http://example.com"),276 URLPattern("http://"),277 URLPattern("all://"),278 ]