Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

278 lines · 8.1 KiB · Python

Last changed by

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

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–111why, one step back
105async def test_logs_debug(server, capsys):
106 with override_log_level("debug"):107 async with httpx.AsyncClient() as client:108 response = await client.get(server.url)109 assert response.status_code == 200110 stderr = capsys.readouterr().err111 assert "httpx.dispatch.connection_pool" not in stderr

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

lines 112–113why, one step back
112
113

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

lines 114–121why, one step back
114@pytest.mark.asyncio
115async def test_logs_trace(server, capsys):116 with override_log_level("trace"):117 async with httpx.AsyncClient() as client:118 response = await client.get(server.url)119 assert response.status_code == 200120 stderr = capsys.readouterr().err121 assert "httpx.dispatch.connection_pool" in stderr

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

lines 122–157why, one step back
122
123124def test_get_ssl_cert_file():125 # Two environments is not set.126 assert get_ca_bundle_from_env() is None127128 os.environ["SSL_CERT_DIR"] = "tests/"129 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.130 assert get_ca_bundle_from_env() == "tests"131132 del os.environ["SSL_CERT_DIR"]133 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"134 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.135 assert get_ca_bundle_from_env() == "tests/test_utils.py"136137 os.environ["SSL_CERT_FILE"] = "wrongfile"138 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.139 assert get_ca_bundle_from_env() is None140141 del os.environ["SSL_CERT_FILE"]142 os.environ["SSL_CERT_DIR"] = "wrongpath"143 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.144 assert get_ca_bundle_from_env() is None145146 os.environ["SSL_CERT_DIR"] = "tests/"147 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"148 # Two environments is correctly set.149 assert get_ca_bundle_from_env() == "tests/test_utils.py"150151 os.environ["SSL_CERT_FILE"] = "wrongfile"152 # Two environments is set but SSL_CERT_FILE is not a file.153 assert get_ca_bundle_from_env() == "tests"154155 os.environ["SSL_CERT_DIR"] = "wrongpath"156 # Two environments is set but both are not correct.157 assert get_ca_bundle_from_env() is None

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

lines 158–168why, one step back
158
159160@pytest.mark.asyncio161async def test_elapsed_timer():162 with ElapsedTimer() as timer:163 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)164 await asyncio.sleep(0.1)165 await asyncio.sleep(166 0.1167 ) # test to ensure time spent after timer exits isn't accounted for.168 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)

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

lines 169–179why, one step back
169
170171@pytest.mark.parametrize(172 ["environment", "proxies"],173 [174 ({}, {}),175 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),176 (177 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},178 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},179 ),

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

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

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

lines 181–187why, one step back
181 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),
182 ],183)184def test_get_environment_proxies(environment, proxies):185 os.environ.update(environment)186187 assert get_environment_proxies() == proxies

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

lines 188–202why, one step back
188
189190@pytest.mark.parametrize(191 "headers, output",192 [193 ([("content-type", "text/html")], [("content-type", "text/html")]),194 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),195 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),196 ],197)198def test_obfuscate_sensitive_headers(headers, output):199 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]200 bytes_output = [(k.encode(), v.encode()) for k, v in output]201 assert list(obfuscate_sensitive_headers(headers)) == output202 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output

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

lines 203–278why, one step back
203
204205@pytest.mark.parametrize(206 ["url", "no_proxy", "expected"],207 [208 (209 "http://127.0.0.1",210 {"NO_PROXY": ""},211 False,212 ), # everything proxied when no_proxy is empty/unset213 (214 "http://127.0.0.1",215 {"NO_PROXY": "127.0.0.1"},216 True,217 ), # no_proxy as ip case is matched218 (219 "http://127.0.0.1",220 {"NO_PROXY": "https://127.0.0.1"},221 False,222 ), # no_proxy with scheme is ignored223 (224 "http://127.0.0.1",225 {"NO_PROXY": "1.1.1.1"},226 False,227 ), # different no_proxy means its proxied228 (229 "http://courses.mit.edu",230 {"NO_PROXY": "mit.edu"},231 True,232 ), # no_proxy for sub-domain matches233 (234 "https://mit.edu.info",235 {"NO_PROXY": "mit.edu"},236 False,237 ), # domain is actually edu.info, so should be proxied238 (239 "https://mit.edu.info",240 {"NO_PROXY": "mit.edu,edu.info"},241 True,242 ), # list in no_proxy, matches second domain243 (244 "https://mit.edu.info",245 {"NO_PROXY": "mit.edu, edu.info"},246 True,247 ), # list with spaces in no_proxy248 (249 "https://mit.edu.info",250 {"NO_PROXY": "mit.edu,mit.info"},251 False,252 ), # list in no_proxy, without any domain matching253 (254 "https://foo.example.com",255 {"NO_PROXY": "www.example.com"},256 False,257 ), # different subdomains foo vs www means we still proxy258 (259 "https://www.example1.com",260 {"NO_PROXY": ".example1.com"},261 True,262 ), # no_proxy starting with dot263 (264 "https://www.example2.com",265 {"NO_PROXY": "ample2.com"},266 False,267 ), # whole-domain matching268 (269 "https://www.example3.com",270 {"NO_PROXY": "*"},271 True,272 ), # wildcard * means nothing proxied273 ],274)275def test_should_not_be_proxied(url, no_proxy, expected):276 os.environ.update(no_proxy)277 parsed_url = httpx.models.URL(url)278 assert should_not_be_proxied(parsed_url) == expected