Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than e95111a point at it.

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 1–6why, one step back
1import asyncio
2import os34import pytest56import httpx

Switch to private module names (#785)Florimond Mancabefore adoption82dc6f3

line 7why, one step back
7from httpx._utils import (

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 8–18why, one step back
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_level18

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 19why, one step back
19from .common import FIXTURES_DIR, TESTS_DIR

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

line 20why, one step back
20

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 21why, one step back
21

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 22–58why, one step back
22@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():

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 59why, one step back
59 netrc_info = NetRCInfo([str(FIXTURES_DIR / "does-not-exist")])

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 60–63why, one step back
60 assert netrc_info.get_credentials("netrcexample.org") is None
616263def test_get_netrc_login():

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 64why, one step back
64 netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 65–71why, one step back
65 expected_credentials = (
66 "example-username",67 "example-password",68 )69 assert netrc_info.get_credentials("netrcexample.org") == expected_credentials7071

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

line 72why, one step back
72def test_get_netrc_unknown():

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 73why, one step back
73 netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])

Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067

lines 74–76why, one step back
74 assert netrc_info.get_credentials("nonexistant.org") is None
7576

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 77–102why, one step back
77@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"):

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 103why, one step back
103 async with httpx.AsyncClient() as client:

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 104–112why, one step back
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"):

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 113why, one step back
113 async with httpx.AsyncClient() as client:

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 114–122why, one step back
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"):

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 123why, one step back
123 async with httpx.AsyncClient() as client:

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 124–141why, one step back
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 None141

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 142why, one step back
142 os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

line 143why, one step back
143 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

lines 144–145why, one step back
144 ca_bundle = get_ca_bundle_from_env()
145 assert ca_bundle is not None and ca_bundle.endswith("tests")

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 146–147why, one step back
146
147 del os.environ["SSL_CERT_DIR"]

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

line 148why, one step back
148 os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

line 149why, one step back
149 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

lines 150–151why, one step back
150 ca_bundle = get_ca_bundle_from_env()
151 assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 152–161why, one step back
152
153 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 None161

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

lines 162–163why, one step back
162 os.environ["SSL_CERT_DIR"] = str(TESTS_DIR)
163 os.environ["SSL_CERT_FILE"] = str(TESTS_DIR / "test_utils.py")

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

line 164why, one step back
164 # Two environments is correctly set.

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

lines 165–166why, one step back
165 ca_bundle = get_ca_bundle_from_env()
166 assert ca_bundle is not None and ca_bundle.endswith("tests/test_utils.py")

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 167–169why, one step back
167
168 os.environ["SSL_CERT_FILE"] = "wrongfile"169 # Two environments is set but SSL_CERT_FILE is not a file.

Use relative tests directory references (#1052)Florimond Mancabefore adoption09672a9

lines 170–171why, one step back
170 ca_bundle = get_ca_bundle_from_env()
171 assert ca_bundle is not None and ca_bundle.endswith("tests")

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 172–294why, one step back
172
173 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)

Switch to private module names (#785)Florimond Mancabefore adoption82dc6f3

line 295why, one step back
295 parsed_url = httpx.URL(url)

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

line 296why, one step back
296 assert should_not_be_proxied(parsed_url) == expected