Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

309 lines · 9.5 KiB · Python

Last changed by

Drop private Origin model (#1070)Tom Christiebefore adoption247ee0d

History of this file

Take it

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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 (

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

lines 8–14why, 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,

Drop private Origin model (#1070)Tom Christiebefore adoption247ee0d

line 15why, one step back
15 same_origin,

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

lines 16–19why, one step back
16 should_not_be_proxied,
17)18from tests.utils import override_log_level19

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

line 21why, one step back
21

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

line 22why, one step back
22

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

lines 61–64why, one step back
61 assert netrc_info.get_credentials("netrcexample.org") is None
626364def test_get_netrc_login():

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

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

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

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

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

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

lines 75–77why, one step back
75 assert netrc_info.get_credentials("nonexistant.org") is None
7677

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

lines 125–142why, one step back
125 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 None142

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

lines 153–162why, one step back
153
154 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 None162

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

lines 173–295why, one step back
173
174 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.asyncio180async def test_elapsed_timer():181 with ElapsedTimer() as timer:182 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)183 await asyncio.sleep(0.1)184 await asyncio.sleep(185 0.1186 ) # test to ensure time spent after timer exits isn't accounted for.187 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)188189190@pytest.mark.parametrize(191 ["environment", "proxies"],192 [193 ({}, {}),194 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),195 (196 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},197 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},198 ),199 ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),200 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),201 ],202)203def test_get_environment_proxies(environment, proxies):204 os.environ.update(environment)205206 assert get_environment_proxies() == proxies207208209@pytest.mark.parametrize(210 "headers, output",211 [212 ([("content-type", "text/html")], [("content-type", "text/html")]),213 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),214 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),215 ],216)217def test_obfuscate_sensitive_headers(headers, output):218 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]219 bytes_output = [(k.encode(), v.encode()) for k, v in output]220 assert list(obfuscate_sensitive_headers(headers)) == output221 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output222223224@pytest.mark.parametrize(225 ["url", "no_proxy", "expected"],226 [227 (228 "http://127.0.0.1",229 {"NO_PROXY": ""},230 False,231 ), # everything proxied when no_proxy is empty/unset232 (233 "http://127.0.0.1",234 {"NO_PROXY": "127.0.0.1"},235 True,236 ), # no_proxy as ip case is matched237 (238 "http://127.0.0.1",239 {"NO_PROXY": "https://127.0.0.1"},240 False,241 ), # no_proxy with scheme is ignored242 (243 "http://127.0.0.1",244 {"NO_PROXY": "1.1.1.1"},245 False,246 ), # different no_proxy means its proxied247 (248 "http://courses.mit.edu",249 {"NO_PROXY": "mit.edu"},250 True,251 ), # no_proxy for sub-domain matches252 (253 "https://mit.edu.info",254 {"NO_PROXY": "mit.edu"},255 False,256 ), # domain is actually edu.info, so should be proxied257 (258 "https://mit.edu.info",259 {"NO_PROXY": "mit.edu,edu.info"},260 True,261 ), # list in no_proxy, matches second domain262 (263 "https://mit.edu.info",264 {"NO_PROXY": "mit.edu, edu.info"},265 True,266 ), # list with spaces in no_proxy267 (268 "https://mit.edu.info",269 {"NO_PROXY": "mit.edu,mit.info"},270 False,271 ), # list in no_proxy, without any domain matching272 (273 "https://foo.example.com",274 {"NO_PROXY": "www.example.com"},275 False,276 ), # different subdomains foo vs www means we still proxy277 (278 "https://www.example1.com",279 {"NO_PROXY": ".example1.com"},280 True,281 ), # no_proxy starting with dot282 (283 "https://www.example2.com",284 {"NO_PROXY": "ample2.com"},285 False,286 ), # whole-domain matching287 (288 "https://www.example3.com",289 {"NO_PROXY": "*"},290 True,291 ), # wildcard * means nothing proxied292 ],293)294def test_should_not_be_proxied(url, no_proxy, expected):295 os.environ.update(no_proxy)

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

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

Allow explicit Content-Type to take precedence (#633)Arkiebefore adoption4bb69e3

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

Drop private Origin model (#1070)Tom Christiebefore adoption247ee0d

lines 298–309why, one step back
298
299300def test_same_origin():301 origin1 = httpx.URL("https://example.com")302 origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")303 assert same_origin(origin1, origin2)304305306def test_not_same_origin():307 origin1 = httpx.URL("https://example.com")308 origin2 = httpx.URL("HTTP://EXAMPLE.COM")309 assert not same_origin(origin1, origin2)