Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

290 lines · 8.8 KiB · Python

Last changed by

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

History of this file

Take it

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

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 1–6why, one step back
1import asyncio
2import os34import pytest56import httpx

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

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

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 8–69why, one step back
8 ElapsedTimer,
9 NetRCInfo,10 get_ca_bundle_from_env,11 get_environment_proxies,12 guess_json_utf,13 obfuscate_sensitive_headers,14 parse_header_links,15 should_not_be_proxied,16)17from tests.utils import override_log_level181920@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):52 data = "\ufeff{}".encode(encoding)53 assert guess_json_utf(data) == expected545556def test_bad_get_netrc_login():57 netrc_info = NetRCInfo(["tests/does-not-exist"])58 assert netrc_info.get_credentials("netrcexample.org") is None596061def test_get_netrc_login():62 netrc_info = NetRCInfo(["tests/.netrc"])63 expected_credentials = (64 "example-username",65 "example-password",66 )67 assert netrc_info.get_credentials("netrcexample.org") == expected_credentials6869

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

lines 70–74why, one step back
70def test_get_netrc_unknown():
71 netrc_info = NetRCInfo(["tests/.netrc"])72 assert netrc_info.get_credentials("nonexistant.org") is None7374

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

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

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

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

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 102–110why, one step back
102 response = await client.get(server.url)
103 assert response.status_code == 200104 stderr = capsys.readouterr().err105 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr106107108@pytest.mark.asyncio109async def test_logs_trace(server, capsys):110 with override_log_level("trace"):

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

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

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 112–120why, one step back
112 response = await client.get(server.url)
113 assert response.status_code == 200114 stderr = capsys.readouterr().err115 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr116117118@pytest.mark.asyncio119async def test_logs_redirect_chain(server, capsys):120 with override_log_level("debug"):

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

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

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

lines 122–288why, one step back
122 response = await client.get(server.url.copy_with(path="/redirect_301"))
123 assert response.status_code == 200124125 stderr = capsys.readouterr().err.strip()126 redirected_request_line, ok_request_line = stderr.split("\n")127 assert redirected_request_line.endswith(128 "HTTP Request: GET http://127.0.0.1:8000/redirect_301 "129 '"HTTP/1.1 301 Moved Permanently"'130 )131 assert ok_request_line.endswith(132 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"'133 )134135136def test_get_ssl_cert_file():137 # Two environments is not set.138 assert get_ca_bundle_from_env() is None139140 os.environ["SSL_CERT_DIR"] = "tests/"141 # SSL_CERT_DIR is correctly set, SSL_CERT_FILE is not set.142 assert get_ca_bundle_from_env() == "tests"143144 del os.environ["SSL_CERT_DIR"]145 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"146 # SSL_CERT_FILE is correctly set, SSL_CERT_DIR is not set.147 assert get_ca_bundle_from_env() == "tests/test_utils.py"148149 os.environ["SSL_CERT_FILE"] = "wrongfile"150 # SSL_CERT_FILE is set with wrong file, SSL_CERT_DIR is not set.151 assert get_ca_bundle_from_env() is None152153 del os.environ["SSL_CERT_FILE"]154 os.environ["SSL_CERT_DIR"] = "wrongpath"155 # SSL_CERT_DIR is set with wrong path, SSL_CERT_FILE is not set.156 assert get_ca_bundle_from_env() is None157158 os.environ["SSL_CERT_DIR"] = "tests/"159 os.environ["SSL_CERT_FILE"] = "tests/test_utils.py"160 # Two environments is correctly set.161 assert get_ca_bundle_from_env() == "tests/test_utils.py"162163 os.environ["SSL_CERT_FILE"] = "wrongfile"164 # Two environments is set but SSL_CERT_FILE is not a file.165 assert get_ca_bundle_from_env() == "tests"166167 os.environ["SSL_CERT_DIR"] = "wrongpath"168 # Two environments is set but both are not correct.169 assert get_ca_bundle_from_env() is None170171172@pytest.mark.asyncio173async def test_elapsed_timer():174 with ElapsedTimer() as timer:175 assert timer.elapsed.total_seconds() == pytest.approx(0, abs=0.05)176 await asyncio.sleep(0.1)177 await asyncio.sleep(178 0.1179 ) # test to ensure time spent after timer exits isn't accounted for.180 assert timer.elapsed.total_seconds() == pytest.approx(0.1, abs=0.05)181182183@pytest.mark.parametrize(184 ["environment", "proxies"],185 [186 ({}, {}),187 ({"HTTP_PROXY": "http://127.0.0.1"}, {"http": "http://127.0.0.1"}),188 (189 {"https_proxy": "http://127.0.0.1", "HTTP_PROXY": "https://127.0.0.1"},190 {"https": "http://127.0.0.1", "http": "https://127.0.0.1"},191 ),192 ({"all_proxy": "http://127.0.0.1"}, {"all": "http://127.0.0.1"}),193 ({"TRAVIS_APT_PROXY": "http://127.0.0.1"}, {}),194 ],195)196def test_get_environment_proxies(environment, proxies):197 os.environ.update(environment)198199 assert get_environment_proxies() == proxies200201202@pytest.mark.parametrize(203 "headers, output",204 [205 ([("content-type", "text/html")], [("content-type", "text/html")]),206 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),207 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),208 ],209)210def test_obfuscate_sensitive_headers(headers, output):211 bytes_headers = [(k.encode(), v.encode()) for k, v in headers]212 bytes_output = [(k.encode(), v.encode()) for k, v in output]213 assert list(obfuscate_sensitive_headers(headers)) == output214 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output215216217@pytest.mark.parametrize(218 ["url", "no_proxy", "expected"],219 [220 (221 "http://127.0.0.1",222 {"NO_PROXY": ""},223 False,224 ), # everything proxied when no_proxy is empty/unset225 (226 "http://127.0.0.1",227 {"NO_PROXY": "127.0.0.1"},228 True,229 ), # no_proxy as ip case is matched230 (231 "http://127.0.0.1",232 {"NO_PROXY": "https://127.0.0.1"},233 False,234 ), # no_proxy with scheme is ignored235 (236 "http://127.0.0.1",237 {"NO_PROXY": "1.1.1.1"},238 False,239 ), # different no_proxy means its proxied240 (241 "http://courses.mit.edu",242 {"NO_PROXY": "mit.edu"},243 True,244 ), # no_proxy for sub-domain matches245 (246 "https://mit.edu.info",247 {"NO_PROXY": "mit.edu"},248 False,249 ), # domain is actually edu.info, so should be proxied250 (251 "https://mit.edu.info",252 {"NO_PROXY": "mit.edu,edu.info"},253 True,254 ), # list in no_proxy, matches second domain255 (256 "https://mit.edu.info",257 {"NO_PROXY": "mit.edu, edu.info"},258 True,259 ), # list with spaces in no_proxy260 (261 "https://mit.edu.info",262 {"NO_PROXY": "mit.edu,mit.info"},263 False,264 ), # list in no_proxy, without any domain matching265 (266 "https://foo.example.com",267 {"NO_PROXY": "www.example.com"},268 False,269 ), # different subdomains foo vs www means we still proxy270 (271 "https://www.example1.com",272 {"NO_PROXY": ".example1.com"},273 True,274 ), # no_proxy starting with dot275 (276 "https://www.example2.com",277 {"NO_PROXY": "ample2.com"},278 False,279 ), # whole-domain matching280 (281 "https://www.example3.com",282 {"NO_PROXY": "*"},283 True,284 ), # wildcard * means nothing proxied285 ],286)287def test_should_not_be_proxied(url, no_proxy, expected):288 os.environ.update(no_proxy)

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

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

Add OpenConnection base class (#616)Florimond Mancabefore adoptione95111a

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