Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

287 lines · 8.8 KiB · Python

Last changed by

Refactor netrc handling (#558)Tom Christiebefore adoptionabe0799

History of this file

Take it

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

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 1why, one step back
1import asyncio

added netrc support (#177)Can Sarıgölbefore adoption919e8d3

lines 2–3why, one step back
2import os
3

Update README.mdTom Christiebefore adoptionedd7029

lines 4–5why, one step back
4import pytest
5

Add easier debug logging for users (#277)Seth Michael Larsonbefore adoption6f4f186

line 6why, one step back
6import httpx

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

lines 7–8why, one step back
7from httpx.utils import (
8 ElapsedTimer,

Refactor netrc handling (#558)Tom Christiebefore adoptionabe0799

line 9why, one step back
9 NetRCInfo,

Add support for SSL_CERT_FILE and SSL_CERT_DIR (#307)Can Sarıgölbefore adoptionc9810a7

line 10why, one step back
10 get_ca_bundle_from_env,

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

line 11why, one step back
11 get_environment_proxies,

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 12why, one step back
12 guess_json_utf,

Add debug logs to ASGIDispatch (#371)Florimond Mancabefore adoptione62e5c3

line 13why, one step back
13 obfuscate_sensitive_headers,

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 14why, one step back
14 parse_header_links,

Add logic for determining if a URL should be proxied (#472)mariaS210before adoption7200717

line 15why, one step back
15 should_not_be_proxied,

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 16why, one step back
16)

Refactor debug and trace log tests (#506)Florimond Mancabefore adoption2fcf23b

line 17why, one step back
17from tests.utils import override_log_level

Update README.mdTom Christiebefore adoptionedd7029

lines 18–51why, one step back
18
1920@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):

Use nox for automation and CI (#128)Seth Michael Larsonbefore adoption80dc3e2

line 52why, one step back
52 data = "\ufeff{}".encode(encoding)

Update README.mdTom Christiebefore adoptionedd7029

line 53why, one step back
53 assert guess_json_utf(data) == expected

added netrc support (#177)Can Sarıgölbefore adoption919e8d3

lines 54–56why, one step back
54
5556def test_bad_get_netrc_login():

Refactor netrc handling (#558)Tom Christiebefore adoptionabe0799

lines 57–58why, one step back
57 netrc_info = NetRCInfo(["tests/does-not-exist"])
58 assert netrc_info.get_credentials("netrcexample.org") is None

added netrc support (#177)Can Sarıgölbefore adoption919e8d3

line 59why, one step back
59

Fail unit tests without 100% coverage (#206)Can Sarıgölbefore adoption9536b76

line 60why, one step back
60

added netrc support (#177)Can Sarıgölbefore adoption919e8d3

line 61why, one step back
61def test_get_netrc_login():

Refactor netrc handling (#558)Tom Christiebefore adoptionabe0799

lines 62–63why, one step back
62 netrc_info = NetRCInfo(["tests/.netrc"])
63 expected_credentials = (

added netrc support (#177)Can Sarıgölbefore adoption919e8d3

lines 64–66why, one step back
64 "example-username",
65 "example-password",66 )

Refactor netrc handling (#558)Tom Christiebefore adoptionabe0799

line 67why, one step back
67 assert netrc_info.get_credentials("netrcexample.org") == expected_credentials

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 68–90why, one step back
68
6970@pytest.mark.parametrize(71 "value, expected",72 (73 (74 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',75 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],76 ),77 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),78 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),79 (80 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',81 [82 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},83 {"url": "http://.../back.jpeg"},84 ],85 ),86 ("", []),87 ),88)89def test_parse_header_links(value, expected):90 assert parse_header_links(value) == expected

Add easier debug logging for users (#277)Seth Michael Larsonbefore adoption6f4f186

lines 91–93why, one step back
91
9293@pytest.mark.asyncio

Refactor debug and trace log tests (#506)Florimond Mancabefore adoption2fcf23b

lines 94–95why, one step back
94async def test_logs_debug(server, capsys):
95 with override_log_level("debug"):

Drop sync (#544)Tom Christiebefore adoption206c537

line 96why, one step back
96 async with httpx.Client() as client:

Refactor debug and trace log tests (#506)Florimond Mancabefore adoption2fcf23b

lines 97–99why, one step back
97 response = await client.get(server.url)
98 assert response.status_code == 20099 stderr = capsys.readouterr().err

Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9

line 100why, one step back
100 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr

Refactor debug and trace log tests (#506)Florimond Mancabefore adoption2fcf23b

line 101why, one step back
101 assert "httpx.dispatch.connection_pool" not in stderr

Add easier debug logging for users (#277)Seth Michael Larsonbefore adoption6f4f186

lines 102–103why, one step back
102
103

Refactor debug and trace log tests (#506)Florimond Mancabefore adoption2fcf23b

lines 104–106why, one step back
104@pytest.mark.asyncio
105async def test_logs_trace(server, capsys):106 with override_log_level("trace"):

Drop sync (#544)Tom Christiebefore adoption206c537

line 107why, one step back
107 async with httpx.Client() as client:

Refactor debug and trace log tests (#506)Florimond Mancabefore adoption2fcf23b

lines 108–110why, one step back
108 response = await client.get(server.url)
109 assert response.status_code == 200110 stderr = capsys.readouterr().err

Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9

line 111why, one step back
111 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr

Refactor debug and trace log tests (#506)Florimond Mancabefore adoption2fcf23b

line 112why, one step back
112 assert "httpx.dispatch.connection_pool" in stderr

Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9

lines 113–117why, one step back
113
114115@pytest.mark.asyncio116async def test_logs_redirect_chain(server, capsys):117 with override_log_level("debug"):

Drop sync (#544)Tom Christiebefore adoption206c537

line 118why, one step back
118 async with httpx.Client() as client:

Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9

lines 119–130why, one step back
119 response = await client.get(server.url.copy_with(path="/redirect_301"))
120 assert response.status_code == 200121122 stderr = capsys.readouterr().err.strip()123 redirected_request_line, ok_request_line = stderr.split("\n")124 assert redirected_request_line.endswith(125 "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "126 '"HTTP/1.1 301 Moved Permanently"'127 )128 assert ok_request_line.endswith(129 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'130 )

Add support for SSL_CERT_FILE and SSL_CERT_DIR (#307)Can Sarıgölbefore adoptionc9810a7

lines 131–166why, one step back
131
132133def test_get_ssl_cert_file():134 # Two environments is not set.135 assert get_ca_bundle_from_env() is None136137 os.environ["SSL_CERT_DIR"] = "tests/"138 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.139 assert get_ca_bundle_from_env() == "tests"140141 del os.environ["SSL_CERT_DIR"]142 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"143 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.144 assert get_ca_bundle_from_env() == "tests/test_utils.py"145146 os.environ["SSL_CERT_FILE"] = "wrongfile"147 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.148 assert get_ca_bundle_from_env() is None149150 del os.environ["SSL_CERT_FILE"]151 os.environ["SSL_CERT_DIR"] = "wrongpath"152 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.153 assert get_ca_bundle_from_env() is None154155 os.environ["SSL_CERT_DIR"] = "tests/"156 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"157 # Two environments is correctly set.158 assert get_ca_bundle_from_env() == "tests/test_utils.py"159160 os.environ["SSL_CERT_FILE"] = "wrongfile"161 # Two environments is set but SSL_CERT_FILE is not a file.162 assert get_ca_bundle_from_env() == "tests"163164 os.environ["SSL_CERT_DIR"] = "wrongpath"165 # Two environments is set but both are not correct.166 assert get_ca_bundle_from_env() is None

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

lines 167–177why, one step back
167
168169@pytest.mark.asyncio170async def test_elapsed_timer():171 with ElapsedTimer() as timer:172 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)173 await asyncio.sleep(0.1)174 await asyncio.sleep(175 0.1176 ) # test to ensure time spent after timer exits isn't accounted for.177 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 178–188why, one step back
178
179180@pytest.mark.parametrize(181 ["environment", "proxies"],182 [183 ({}, {}),184 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),185 (186 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},187 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},188 ),

Rely on getproxies for all proxy environment variables (#470)camellia256before adoption49ed77a

line 189why, one step back
189 ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 190–196why, one step back
190 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),
191 ],192)193def test_get_environment_proxies(environment, proxies):194 os.environ.update(environment)195196 assert get_environment_proxies() == proxies

Add debug logs to ASGIDispatch (#371)Florimond Mancabefore adoptione62e5c3

lines 197–211why, one step back
197
198199@pytest.mark.parametrize(200 "headers, output",201 [202 ([("content-type", "text/html")], [("content-type", "text/html")]),203 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),204 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),205 ],206)207def test_obfuscate_sensitive_headers(headers, output):208 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]209 bytes_output = [(k.encode(), v.encode()) for k, v in output]210 assert list(obfuscate_sensitive_headers(headers)) == output211 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output

Add logic for determining if a URL should be proxied (#472)mariaS210before adoption7200717

lines 212–287why, one step back
212
213214@pytest.mark.parametrize(215 ["url", "no_proxy", "expected"],216 [217 (218 "http://127.0.0.1",219 {"NO_PROXY": ""},220 False,221 ), # everything proxied when no_proxy is empty/unset222 (223 "http://127.0.0.1",224 {"NO_PROXY": "127.0.0.1"},225 True,226 ), # no_proxy as ip case is matched227 (228 "http://127.0.0.1",229 {"NO_PROXY": "https://127.0.0.1"},230 False,231 ), # no_proxy with scheme is ignored232 (233 "http://127.0.0.1",234 {"NO_PROXY": "1.1.1.1"},235 False,236 ), # different no_proxy means its proxied237 (238 "http://courses.mit.edu",239 {"NO_PROXY": "mit.edu"},240 True,241 ), # no_proxy for sub-domain matches242 (243 "https://mit.edu.info",244 {"NO_PROXY": "mit.edu"},245 False,246 ), # domain is actually edu.info, so should be proxied247 (248 "https://mit.edu.info",249 {"NO_PROXY": "mit.edu,edu.info"},250 True,251 ), # list in no_proxy, matches second domain252 (253 "https://mit.edu.info",254 {"NO_PROXY": "mit.edu, edu.info"},255 True,256 ), # list with spaces in no_proxy257 (258 "https://mit.edu.info",259 {"NO_PROXY": "mit.edu,mit.info"},260 False,261 ), # list in no_proxy, without any domain matching262 (263 "https://foo.example.com",264 {"NO_PROXY": "www.example.com"},265 False,266 ), # different subdomains foo vs www means we still proxy267 (268 "https://www.example1.com",269 {"NO_PROXY": ".example1.com"},270 True,271 ), # no_proxy starting with dot272 (273 "https://www.example2.com",274 {"NO_PROXY": "ample2.com"},275 False,276 ), # whole-domain matching277 (278 "https://www.example3.com",279 {"NO_PROXY": "*"},280 True,281 ), # wildcard * means nothing proxied282 ],283)284def test_should_not_be_proxied(url, no_proxy, expected):285 os.environ.update(no_proxy)286 parsed_url = httpx.models.URL(url)287 assert should_not_be_proxied(parsed_url) == expected