Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

351 lines · 10.9 KiB · Python

Last changed by

URL matching (#1098)Tom Christiebefore adoptiondf54890

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–2why, one step back
1import asyncio
2import os

URL matching (#1098)Tom Christiebefore adoptiondf54890

line 3why, one step back
3import random

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

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 (

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

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

URL matching (#1098)Tom Christiebefore adoptiondf54890

line 11why, one step back
11 URLMatcher,

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

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,

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

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

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

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

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

line 23why, one step back
23

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

line 24why, one step back
24

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

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

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

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

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

lines 63–66why, one step back
63 assert netrc_info.get_credentials("netrcexample.org") is None
646566def test_get_netrc_login():

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lines 107–115why, one step back
107 response = await client.get(server.url)
108 assert response.status_code == 200109 stderr = capsys.readouterr().err110 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr111112113@pytest.mark.asyncio114async def test_logs_trace(server, capsys):115 with override_log_level("trace"):

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

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

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

lines 117–125why, one step back
117 response = await client.get(server.url)
118 assert response.status_code == 200119 stderr = capsys.readouterr().err120 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr121122123@pytest.mark.asyncio124async def test_logs_redirect_chain(server, capsys):125 with override_log_level("debug"):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lines 153–154why, one step back
153 ca_bundle = get_ca_bundle_from_env()
154 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 155–164why, one step back
155
156 os.environ["SSL_CERT_FILE"] = "wrongfile"157 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.158 assert get_ca_bundle_from_env() is None159160 del os.environ["SSL_CERT_FILE"]161 os.environ["SSL_CERT_DIR"] = "wrongpath"162 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.163 assert get_ca_bundle_from_env() is None164

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

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

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

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

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

lines 168–169why, one step back
168 ca_bundle = get_ca_bundle_from_env()
169 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 170–172why, one step back
170
171 os.environ["SSL_CERT_FILE"] = "wrongfile"172 # Two environments is set but SSL_CERT_FILE is not a file.

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

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

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

lines 175–297why, one step back
175
176 os.environ["SSL_CERT_DIR"] = "wrongpath"177 # Two environments is set but both are not correct.178 assert get_ca_bundle_from_env() is None179180181@pytest.mark.asyncio182async def test_elapsed_timer():183 with ElapsedTimer() as timer:184 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)185 await asyncio.sleep(0.1)186 await asyncio.sleep(187 0.1188 ) # test to ensure time spent after timer exits isn't accounted for.189 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)190191192@pytest.mark.parametrize(193 ["environment", "proxies"],194 [195 ({}, {}),196 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),197 (198 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},199 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},200 ),201 ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),202 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),203 ],204)205def test_get_environment_proxies(environment, proxies):206 os.environ.update(environment)207208 assert get_environment_proxies() == proxies209210211@pytest.mark.parametrize(212 "headers, output",213 [214 ([("content-type", "text/html")], [("content-type", "text/html")]),215 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),216 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),217 ],218)219def test_obfuscate_sensitive_headers(headers, output):220 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]221 bytes_output = [(k.encode(), v.encode()) for k, v in output]222 assert list(obfuscate_sensitive_headers(headers)) == output223 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output224225226@pytest.mark.parametrize(227 ["url", "no_proxy", "expected"],228 [229 (230 "http://127.0.0.1",231 {"NO_PROXY": ""},232 False,233 ), # everything proxied when no_proxy is empty/unset234 (235 "http://127.0.0.1",236 {"NO_PROXY": "127.0.0.1"},237 True,238 ), # no_proxy as ip case is matched239 (240 "http://127.0.0.1",241 {"NO_PROXY": "https://127.0.0.1"},242 False,243 ), # no_proxy with scheme is ignored244 (245 "http://127.0.0.1",246 {"NO_PROXY": "1.1.1.1"},247 False,248 ), # different no_proxy means its proxied249 (250 "http://courses.mit.edu",251 {"NO_PROXY": "mit.edu"},252 True,253 ), # no_proxy for sub-domain matches254 (255 "https://mit.edu.info",256 {"NO_PROXY": "mit.edu"},257 False,258 ), # domain is actually edu.info, so should be proxied259 (260 "https://mit.edu.info",261 {"NO_PROXY": "mit.edu,edu.info"},262 True,263 ), # list in no_proxy, matches second domain264 (265 "https://mit.edu.info",266 {"NO_PROXY": "mit.edu, edu.info"},267 True,268 ), # list with spaces in no_proxy269 (270 "https://mit.edu.info",271 {"NO_PROXY": "mit.edu,mit.info"},272 False,273 ), # list in no_proxy, without any domain matching274 (275 "https://foo.example.com",276 {"NO_PROXY": "www.example.com"},277 False,278 ), # different subdomains foo vs www means we still proxy279 (280 "https://www.example1.com",281 {"NO_PROXY": ".example1.com"},282 True,283 ), # no_proxy starting with dot284 (285 "https://www.example2.com",286 {"NO_PROXY": "ample2.com"},287 False,288 ), # whole-domain matching289 (290 "https://www.example3.com",291 {"NO_PROXY": "*"},292 True,293 ), # wildcard * means nothing proxied294 ],295)296def test_should_not_be_proxied(url, no_proxy, expected):297 os.environ.update(no_proxy)

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

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

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

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

Drop private Origin model (#1070)Tom Christiebefore adoption247ee0d

lines 300–311why, one step back
300
301302def test_same_origin():303 origin1 = httpx.URL("https://example.com")304 origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")305 assert same_origin(origin1, origin2)306307308def test_not_same_origin():309 origin1 = httpx.URL("https://example.com")310 origin2 = httpx.URL("HTTP://EXAMPLE.COM")311 assert not same_origin(origin1, origin2)

URL matching (#1098)Tom Christiebefore adoptiondf54890

lines 312–351why, one step back
312
313314@pytest.mark.parametrize(315 ["pattern", "url", "expected"],316 [317 ("http://example.com", "http://example.com", True,),318 ("http://example.com", "https://example.com", False,),319 ("http://example.com", "http://other.com", False,),320 ("http://example.com:123", "http://example.com:123", True,),321 ("http://example.com:123", "http://example.com:456", False,),322 ("http://example.com:123", "http://example.com", False,),323 ("all://example.com", "http://example.com", True,),324 ("all://example.com", "https://example.com", True,),325 ("http://", "http://example.com", True,),326 ("http://", "https://example.com", False,),327 ("http", "http://example.com", True,),328 ("http", "https://example.com", False,),329 ("all", "https://example.com:123", True,),330 ("", "https://example.com:123", True,),331 ],332)333def test_url_matches(pattern, url, expected):334 matcher = URLMatcher(pattern)335 assert matcher.matches(httpx.URL(url)) == expected336337338def test_matcher_priority():339 matchers = [340 URLMatcher("all://"),341 URLMatcher("http://"),342 URLMatcher("http://example.com"),343 URLMatcher("http://example.com:123"),344 ]345 random.shuffle(matchers)346 assert sorted(matchers) == [347 URLMatcher("http://example.com:123"),348 URLMatcher("http://example.com"),349 URLMatcher("http://"),350 URLMatcher("all://"),351 ]