Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

274 lines · 8.7 KiB · Python

Last changed by

Cleaner no proxy support (#1103)Tom Christiebefore adoption682cad3

History of this file

Take it

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 1–2why, one step back
1import asyncio
2import os

URL matching (#1098)Tom Christiebefore adoptiondf54890

line 3why, one step back
3import random

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 4–7why, one step back
4
5import pytest67import httpx

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 9–10why, one step back
9 ElapsedTimer,
10 NetRCInfo,

Rename URLMatcher -> URLPattern (#1109)Florimond Mancabefore adoption71d5234

line 11why, one step back
11 URLPattern,

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 12–16why, one step back
12 get_ca_bundle_from_env,
13 get_environment_proxies,14 guess_json_utf,15 obfuscate_sensitive_headers,16 parse_header_links,

Drop private Origin model (#1070)Tom Christiebefore adoption247ee0d

line 17why, one step back
17 same_origin,

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 18–20why, one step back
18)
19from tests.utils import override_log_level20

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

line 22why, one step back
22

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

line 23why, one step back
23

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 24–60why, one step back
24@pytest.mark.parametrize(
25 "encoding",26 (27 "utf-32",28 "utf-8-sig",29 "utf-16",30 "utf-8",31 "utf-16-be",32 "utf-16-le",33 "utf-32-be",34 "utf-32-le",35 ),36)37def test_encoded(encoding):38 data = "{}".encode(encoding)39 assert guess_json_utf(data) == encoding404142def test_bad_utf_like_encoding():43 assert guess_json_utf(b"\x00\x00\x00\x00") is None444546@pytest.mark.parametrize(47 ("encoding", "expected"),48 (49 ("utf-16-be", "utf-16"),50 ("utf-16-le", "utf-16"),51 ("utf-32-be", "utf-32"),52 ("utf-32-le", "utf-32"),53 ),54)55def test_guess_by_bom(encoding, expected):56 data = "\ufeff{}".encode(encoding)57 assert guess_json_utf(data) == expected585960def test_bad_get_netrc_login():

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 62–65why, one step back
62 assert netrc_info.get_credentials("netrcexample.org") is None
636465def test_get_netrc_login():

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

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

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

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

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

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

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

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

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 106–114why, one step back
106 response = await client.get(server.url)
107 assert response.status_code == 200108 stderr = capsys.readouterr().err109 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr110111112@pytest.mark.asyncio113async def test_logs_trace(server, capsys):114 with override_log_level("trace"):

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 116–124why, one step back
116 response = await client.get(server.url)
117 assert response.status_code == 200118 stderr = capsys.readouterr().err119 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr120121122@pytest.mark.asyncio123async def test_logs_redirect_chain(server, capsys):124 with override_log_level("debug"):

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 126–143why, one step back
126 response = await client.get(server.url.copy_with(path="/redirect_301"))
127 assert response.status_code == 200128129 stderr = capsys.readouterr().err.strip()130 redirected_request_line, ok_request_line = stderr.split("\n")131 assert redirected_request_line.endswith(132 "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "133 '"HTTP/1.1 301 Moved Permanently"'134 )135 assert ok_request_line.endswith(136 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'137 )138139140def test_get_ssl_cert_file():141 # Two environments is not set.142 assert get_ca_bundle_from_env() is None143

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

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

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

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

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

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

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 154–163why, one step back
154
155 os.environ["SSL_CERT_FILE"] = "wrongfile"156 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.157 assert get_ca_bundle_from_env() is None158159 del os.environ["SSL_CERT_FILE"]160 os.environ["SSL_CERT_DIR"] = "wrongpath"161 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.162 assert get_ca_bundle_from_env() is None163

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

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

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

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

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

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

Drop Request.read() (#679)Tom Christiebefore adoption25b40db

lines 174–222why, one step back
174
175 os.environ["SSL_CERT_DIR"] = "wrongpath"176 # Two environments is set but both are not correct.177 assert get_ca_bundle_from_env() is None178179180@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)189190191@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 ),200 ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),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() == proxies208209210@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

Drop private Origin model (#1070)Tom Christiebefore adoption247ee0d

lines 223–234why, one step back
223
224225def test_same_origin():226 origin1 = httpx.URL("https://example.com")227 origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")228 assert same_origin(origin1, origin2)229230231def test_not_same_origin():232 origin1 = httpx.URL("https://example.com")233 origin2 = httpx.URL("HTTP://EXAMPLE.COM")234 assert not same_origin(origin1, origin2)

URL matching (#1098)Tom Christiebefore adoptiondf54890

lines 235–256why, one step back
235
236237@pytest.mark.parametrize(238 ["pattern", "url", "expected"],239 [240 ("http://example.com", "http://example.com", True,),241 ("http://example.com", "https://example.com", False,),242 ("http://example.com", "http://other.com", False,),243 ("http://example.com:123", "http://example.com:123", True,),244 ("http://example.com:123", "http://example.com:456", False,),245 ("http://example.com:123", "http://example.com", False,),246 ("all://example.com", "http://example.com", True,),247 ("all://example.com", "https://example.com", True,),248 ("http://", "http://example.com", True,),249 ("http://", "https://example.com", False,),250 ("http", "http://example.com", True,),251 ("http", "https://example.com", False,),252 ("all", "https://example.com:123", True,),253 ("", "https://example.com:123", True,),254 ],255)256def test_url_matches(pattern, url, expected):

Rename URLMatcher -> URLPattern (#1109)Florimond Mancabefore adoption71d5234

lines 257–258why, one step back
257 pattern = URLPattern(pattern)
258 assert pattern.matches(httpx.URL(url)) == expected

URL matching (#1098)Tom Christiebefore adoptiondf54890

lines 259–260why, one step back
259
260

Rename URLMatcher -> URLPattern (#1109)Florimond Mancabefore adoption71d5234

line 261why, one step back
261def test_pattern_priority():

URL matching (#1098)Tom Christiebefore adoptiondf54890

line 262why, one step back
262 matchers = [

Rename URLMatcher -> URLPattern (#1109)Florimond Mancabefore adoption71d5234

lines 263–266why, one step back
263 URLPattern("all://"),
264 URLPattern("http://"),265 URLPattern("http://example.com"),266 URLPattern("http://example.com:123"),

URL matching (#1098)Tom Christiebefore adoptiondf54890

lines 267–269why, one step back
267 ]
268 random.shuffle(matchers)269 assert sorted(matchers) == [

Rename URLMatcher -> URLPattern (#1109)Florimond Mancabefore adoption71d5234

lines 270–273why, one step back
270 URLPattern("http://example.com:123"),
271 URLPattern("http://example.com"),272 URLPattern("http://"),273 URLPattern("all://"),

URL matching (#1098)Tom Christiebefore adoptiondf54890

line 274why, one step back
274 ]