Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

298 lines · 8.9 KiB · Python

Last changed by

Drop sync (#544)Tom Christiebefore adoption206c537

History of this file

Take 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

Encoding detection in Response.json (#116)Yeray Diaz Diazbefore adoption5442006

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,

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

line 9why, one step back
9 get_ca_bundle_from_env,

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

line 10why, one step back
10 get_environment_proxies,

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

line 11why, one step back
11 get_netrc,

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

Encoding detection in Response.json (#116)Yeray Diaz Diazbefore adoption5442006

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)

Encoding detection in Response.json (#116)Yeray Diaz Diazbefore adoption5442006

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

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

lines 54–57why, one step back
54
5556def test_bad_get_netrc_login():57 os.environ["NETRC"] = "tests/.netrc"

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

line 58why, one step back
58 assert str(get_netrc()) is not 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

lines 60–62why, one step back
60 from httpx import utils
6162 utils.NETRC_STATIC_FILES = ()

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

lines 63–66why, one step back
63
64 os.environ["NETRC"] = "wrongpath"65 assert utils.get_netrc() is None66

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

line 67why, one step back
67 os.environ["NETRC"] = ""

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

line 68why, one step back
68 assert utils.get_netrc() is None

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

line 69why, one step back
69

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

lines 70–72why, one step back
70
71def test_get_netrc_login():72 os.environ["NETRC"] = "tests/.netrc"

Cache netrc authentication per-client (#400)Can Sarıgölbefore adoption84731c8

lines 73–74why, one step back
73 netrc = get_netrc()
74 assert netrc.authenticators("netrcexample.org") == (

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

lines 75–78why, one step back
75 "example-username",
76 None,77 "example-password",78 )

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 79–101why, one step back
79
8081@pytest.mark.parametrize(82 "value, expected",83 (84 (85 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',86 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],87 ),88 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),89 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),90 (91 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',92 [93 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},94 {"url": "http://.../back.jpeg"},95 ],96 ),97 ("", []),98 ),99)100def test_parse_header_links(value, expected):101 assert parse_header_links(value) == expected

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

lines 102–104why, one step back
102
103104@pytest.mark.asyncio

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

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

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" not in stderr

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

lines 113–114why, one step back
113
114

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

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

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

lines 119–121why, one step back
119 response = await client.get(server.url)
120 assert response.status_code == 200121 stderr = capsys.readouterr().err

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

line 122why, one step back
122 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 123why, one step back
123 assert "httpx.dispatch.connection_pool" in stderr

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

lines 124–128why, one step back
124
125126@pytest.mark.asyncio127async def test_logs_redirect_chain(server, capsys):128 with override_log_level("debug"):

Drop sync (#544)Tom Christiebefore adoption206c537

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

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

lines 130–141why, one step back
130 response = await client.get(server.url.copy_with(path="/redirect_301"))
131 assert response.status_code == 200132133 stderr = capsys.readouterr().err.strip()134 redirected_request_line, ok_request_line = stderr.split("\n")135 assert redirected_request_line.endswith(136 "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "137 '"HTTP/1.1 301 Moved Permanently"'138 )139 assert ok_request_line.endswith(140 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'141 )

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

lines 142–177why, one step back
142
143144def test_get_ssl_cert_file():145 # Two environments is not set.146 assert get_ca_bundle_from_env() is None147148 os.environ["SSL_CERT_DIR"] = "tests/"149 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.150 assert get_ca_bundle_from_env() == "tests"151152 del os.environ["SSL_CERT_DIR"]153 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"154 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.155 assert get_ca_bundle_from_env() == "tests/test_utils.py"156157 os.environ["SSL_CERT_FILE"] = "wrongfile"158 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.159 assert get_ca_bundle_from_env() is None160161 del os.environ["SSL_CERT_FILE"]162 os.environ["SSL_CERT_DIR"] = "wrongpath"163 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.164 assert get_ca_bundle_from_env() is None165166 os.environ["SSL_CERT_DIR"] = "tests/"167 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"168 # Two environments is correctly set.169 assert get_ca_bundle_from_env() == "tests/test_utils.py"170171 os.environ["SSL_CERT_FILE"] = "wrongfile"172 # Two environments is set but SSL_CERT_FILE is not a file.173 assert get_ca_bundle_from_env() == "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 None

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

lines 178–188why, one step back
178
179180@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)

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

lines 189–199why, one step back
189
190191@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 ),

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

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

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

lines 201–207why, one step back
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() == proxies

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

lines 208–222why, one step back
208
209210@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_output

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

lines 223–298why, one step back
223
224225@pytest.mark.parametrize(226 ["url", "no_proxy", "expected"],227 [228 (229 "http://127.0.0.1",230 {"NO_PROXY": ""},231 False,232 ), # everything proxied when no_proxy is empty/unset233 (234 "http://127.0.0.1",235 {"NO_PROXY": "127.0.0.1"},236 True,237 ), # no_proxy as ip case is matched238 (239 "http://127.0.0.1",240 {"NO_PROXY": "https://127.0.0.1"},241 False,242 ), # no_proxy with scheme is ignored243 (244 "http://127.0.0.1",245 {"NO_PROXY": "1.1.1.1"},246 False,247 ), # different no_proxy means its proxied248 (249 "http://courses.mit.edu",250 {"NO_PROXY": "mit.edu"},251 True,252 ), # no_proxy for sub-domain matches253 (254 "https://mit.edu.info",255 {"NO_PROXY": "mit.edu"},256 False,257 ), # domain is actually edu.info, so should be proxied258 (259 "https://mit.edu.info",260 {"NO_PROXY": "mit.edu,edu.info"},261 True,262 ), # list in no_proxy, matches second domain263 (264 "https://mit.edu.info",265 {"NO_PROXY": "mit.edu, edu.info"},266 True,267 ), # list with spaces in no_proxy268 (269 "https://mit.edu.info",270 {"NO_PROXY": "mit.edu,mit.info"},271 False,272 ), # list in no_proxy, without any domain matching273 (274 "https://foo.example.com",275 {"NO_PROXY": "www.example.com"},276 False,277 ), # different subdomains foo vs www means we still proxy278 (279 "https://www.example1.com",280 {"NO_PROXY": ".example1.com"},281 True,282 ), # no_proxy starting with dot283 (284 "https://www.example2.com",285 {"NO_PROXY": "ample2.com"},286 False,287 ), # whole-domain matching288 (289 "https://www.example3.com",290 {"NO_PROXY": "*"},291 True,292 ), # wildcard * means nothing proxied293 ],294)295def test_should_not_be_proxied(url, no_proxy, expected):296 os.environ.update(no_proxy)297 parsed_url = httpx.models.URL(url)298 assert should_not_be_proxied(parsed_url) == expected