test_utils.py
This file
Path
tests/test_utils.py
925 lines · 27.6 KiB · Python
Last changed by
Tolerate bad registry entries in Windows proxy settings (#6149)Nate Prewittbefore adoption210095f
History of this fileTake it
1import copy2import filecmp3import os4import tarfile5import zipfile6from collections import deque7from io import BytesIO89import pytest1011from requests import compat12from requests._internal_utils import unicode_is_ascii13from requests.cookies import RequestsCookieJar14from requests.structures import CaseInsensitiveDict15from requests.utils import (16 _parse_content_type_header,17 add_dict_to_cookiejar,18 address_in_network,19 dotted_netmask,20 extract_zipped_paths,21 get_auth_from_url,22 get_encoding_from_headers,23 get_encodings_from_content,24 get_environ_proxies,25 guess_filename,26 guess_json_utf,27 is_ipv4_address,28 is_valid_cidr,29 iter_slices,30 parse_dict_header,31 parse_header_links,32 prepend_scheme_if_needed,33 requote_uri,34 select_proxy,35 set_environ,36 should_bypass_proxies,37 super_len,38 to_key_val_list,39 to_native_string,40 unquote_header_value,41 unquote_unreserved,42 urldefragauth,43)4445from .compat import StringIO, cStringIO464748class TestSuperLen:49 @pytest.mark.parametrize(50 "stream, value",51 (52 (StringIO.StringIO, "Test"),53 (BytesIO, b"Test"),54 pytest.param(55 cStringIO, "Test", marks=pytest.mark.skipif("cStringIO is None")56 ),57 ),58 )59 def test_io_streams(self, stream, value):60 """Ensures that we properly deal with different kinds of IO streams."""61 assert super_len(stream()) == 062 assert super_len(stream(value)) == 46364 def test_super_len_correctly_calculates_len_of_partially_read_file(self):65 """Ensure that we handle partially consumed file like objects."""66 s = StringIO.StringIO()67 s.write("foobarbogus")68 assert super_len(s) == 06970 @pytest.mark.parametrize("error", [IOError, OSError])71 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):72 """If tell() raises errors, assume the cursor is at position zero."""7374 class BoomFile:75 def __len__(self):76 return 57778 def tell(self):79 raise error()8081 assert super_len(BoomFile()) == 08283 @pytest.mark.parametrize("error", [IOError, OSError])84 def test_super_len_tell_ioerror(self, error):85 """Ensure that if tell gives an IOError super_len doesn't fail"""8687 class NoLenBoomFile:88 def tell(self):89 raise error()9091 def seek(self, offset, whence):92 pass9394 assert super_len(NoLenBoomFile()) == 09596 def test_string(self):97 assert super_len("Test") == 49899 @pytest.mark.parametrize(100 "mode, warnings_num",101 (102 ("r", 1),103 ("rb", 0),104 ),105 )106 def test_file(self, tmpdir, mode, warnings_num, recwarn):107 file_obj = tmpdir.join("test.txt")108 file_obj.write("Test")109 with file_obj.open(mode) as fd:110 assert super_len(fd) == 4111 assert len(recwarn) == warnings_num112113 def test_tarfile_member(self, tmpdir):114 file_obj = tmpdir.join("test.txt")115 file_obj.write("Test")116117 tar_obj = str(tmpdir.join("test.tar"))118 with tarfile.open(tar_obj, "w") as tar:119 tar.add(str(file_obj), arcname="test.txt")120121 with tarfile.open(tar_obj) as tar:122 member = tar.extractfile("test.txt")123 assert super_len(member) == 4124125 def test_super_len_with__len__(self):126 foo = [1, 2, 3, 4]127 len_foo = super_len(foo)128 assert len_foo == 4129130 def test_super_len_with_no__len__(self):131 class LenFile:132 def __init__(self):133 self.len = 5134135 assert super_len(LenFile()) == 5136137 def test_super_len_with_tell(self):138 foo = StringIO.StringIO("12345")139 assert super_len(foo) == 5140 foo.read(2)141 assert super_len(foo) == 3142143 def test_super_len_with_fileno(self):144 with open(__file__, "rb") as f:145 length = super_len(f)146 file_data = f.read()147 assert length == len(file_data)148149 def test_super_len_with_no_matches(self):150 """Ensure that objects without any length methods default to 0"""151 assert super_len(object()) == 0152153154class TestToKeyValList:155 @pytest.mark.parametrize(156 "value, expected",157 (158 ([("key", "val")], [("key", "val")]),159 ((("key", "val"),), [("key", "val")]),160 ({"key": "val"}, [("key", "val")]),161 (None, None),162 ),163 )164 def test_valid(self, value, expected):165 assert to_key_val_list(value) == expected166167 def test_invalid(self):168 with pytest.raises(ValueError):169 to_key_val_list("string")170171172class TestUnquoteHeaderValue:173 @pytest.mark.parametrize(174 "value, expected",175 (176 (None, None),177 ("Test", "Test"),178 ('"Test"', "Test"),179 ('"Test\\\\"', "Test\\"),180 ('"\\\\Comp\\Res"', "\\Comp\\Res"),181 ),182 )183 def test_valid(self, value, expected):184 assert unquote_header_value(value) == expected185186 def test_is_filename(self):187 assert unquote_header_value('"\\\\Comp\\Res"', True) == "\\\\Comp\\Res"188189190class TestGetEnvironProxies:191 """Ensures that IP addresses are correctly matches with ranges192 in no_proxy variable.193 """194195 @pytest.fixture(autouse=True, params=["no_proxy", "NO_PROXY"])196 def no_proxy(self, request, monkeypatch):197 monkeypatch.setenv(198 request.param, "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"199 )200201 @pytest.mark.parametrize(202 "url",203 (204 "http://192.168.0.1:5000/",205 "http://192.168.0.1/",206 "http://172.16.1.1/",207 "http://172.16.1.1:5000/",208 "http://localhost.localdomain:5000/v1.0/",209 ),210 )211 def test_bypass(self, url):212 assert get_environ_proxies(url, no_proxy=None) == {}213214 @pytest.mark.parametrize(215 "url",216 (217 "http://192.168.1.1:5000/",218 "http://192.168.1.1/",219 "http://www.requests.com/",220 ),221 )222 def test_not_bypass(self, url):223 assert get_environ_proxies(url, no_proxy=None) != {}224225 @pytest.mark.parametrize(226 "url",227 (228 "http://192.168.1.1:5000/",229 "http://192.168.1.1/",230 "http://www.requests.com/",231 ),232 )233 def test_bypass_no_proxy_keyword(self, url):234 no_proxy = "192.168.1.1,requests.com"235 assert get_environ_proxies(url, no_proxy=no_proxy) == {}236237 @pytest.mark.parametrize(238 "url",239 (240 "http://192.168.0.1:5000/",241 "http://192.168.0.1/",242 "http://172.16.1.1/",243 "http://172.16.1.1:5000/",244 "http://localhost.localdomain:5000/v1.0/",245 ),246 )247 def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):248 # This is testing that the 'no_proxy' argument overrides the249 # environment variable 'no_proxy'250 monkeypatch.setenv("http_proxy", "http://proxy.example.com:3128/")251 no_proxy = "192.168.1.1,requests.com"252 assert get_environ_proxies(url, no_proxy=no_proxy) != {}253254255class TestIsIPv4Address:256 def test_valid(self):257 assert is_ipv4_address("8.8.8.8")258259 @pytest.mark.parametrize("value", ("8.8.8.8.8", "localhost.localdomain"))260 def test_invalid(self, value):261 assert not is_ipv4_address(value)262263264class TestIsValidCIDR:265 def test_valid(self):266 assert is_valid_cidr("192.168.1.0/24")267268 @pytest.mark.parametrize(269 "value",270 (271 "8.8.8.8",272 "192.168.1.0/a",273 "192.168.1.0/128",274 "192.168.1.0/-1",275 "192.168.1.999/24",276 ),277 )278 def test_invalid(self, value):279 assert not is_valid_cidr(value)280281282class TestAddressInNetwork:283 def test_valid(self):284 assert address_in_network("192.168.1.1", "192.168.1.0/24")285286 def test_invalid(self):287 assert not address_in_network("172.16.0.1", "192.168.1.0/24")288289290class TestGuessFilename:291 @pytest.mark.parametrize(292 "value",293 (1, type("Fake", (object,), {"name": 1})()),294 )295 def test_guess_filename_invalid(self, value):296 assert guess_filename(value) is None297298 @pytest.mark.parametrize(299 "value, expected_type",300 (301 (b"value", compat.bytes),302 (b"value".decode("utf-8"), compat.str),303 ),304 )305 def test_guess_filename_valid(self, value, expected_type):306 obj = type("Fake", (object,), {"name": value})()307 result = guess_filename(obj)308 assert result == value309 assert isinstance(result, expected_type)310311312class TestExtractZippedPaths:313 @pytest.mark.parametrize(314 "path",315 (316 "/",317 __file__,318 pytest.__file__,319 "/etc/invalid/location",320 ),321 )322 def test_unzipped_paths_unchanged(self, path):323 assert path == extract_zipped_paths(path)324325 def test_zipped_paths_extracted(self, tmpdir):326 zipped_py = tmpdir.join("test.zip")327 with zipfile.ZipFile(zipped_py.strpath, "w") as f:328 f.write(__file__)329330 _, name = os.path.splitdrive(__file__)331 zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r"\/"))332 extracted_path = extract_zipped_paths(zipped_path)333334 assert extracted_path != zipped_path335 assert os.path.exists(extracted_path)336 assert filecmp.cmp(extracted_path, __file__)337338 def test_invalid_unc_path(self):339 path = r"\\localhost\invalid\location"340 assert extract_zipped_paths(path) == path341342343class TestContentEncodingDetection:344 def test_none(self):345 encodings = get_encodings_from_content("")346 assert not len(encodings)347348 @pytest.mark.parametrize(349 "content",350 (351 # HTML5 meta charset attribute352 '<meta charset="UTF-8">',353 # HTML4 pragma directive354 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',355 # XHTML 1.x served with text/html MIME type356 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',357 # XHTML 1.x served as XML358 '<?xml version="1.0" encoding="UTF-8"?>',359 ),360 )361 def test_pragmas(self, content):362 encodings = get_encodings_from_content(content)363 assert len(encodings) == 1364 assert encodings[0] == "UTF-8"365366 def test_precedence(self):367 content = """368 <?xml version="1.0" encoding="XML"?>369 <meta charset="HTML5">370 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />371 """.strip()372 assert get_encodings_from_content(content) == ["HTML5", "HTML4", "XML"]373374375class TestGuessJSONUTF:376 @pytest.mark.parametrize(377 "encoding",378 (379 "utf-32",380 "utf-8-sig",381 "utf-16",382 "utf-8",383 "utf-16-be",384 "utf-16-le",385 "utf-32-be",386 "utf-32-le",387 ),388 )389 def test_encoded(self, encoding):390 data = "{}".encode(encoding)391 assert guess_json_utf(data) == encoding392393 def test_bad_utf_like_encoding(self):394 assert guess_json_utf(b"\x00\x00\x00\x00") is None395396 @pytest.mark.parametrize(397 ("encoding", "expected"),398 (399 ("utf-16-be", "utf-16"),400 ("utf-16-le", "utf-16"),401 ("utf-32-be", "utf-32"),402 ("utf-32-le", "utf-32"),403 ),404 )405 def test_guess_by_bom(self, encoding, expected):406 data = "\ufeff{}".encode(encoding)407 assert guess_json_utf(data) == expected408409410USER = PASSWORD = "%!*'();:@&=+$,/?#[] "411ENCODED_USER = compat.quote(USER, "")412ENCODED_PASSWORD = compat.quote(PASSWORD, "")413414415@pytest.mark.parametrize(416 "url, auth",417 (418 (419 f"http://{ENCODED_USER}:{ENCODED_PASSWORD}@request.com/url.html#test",420 (USER, PASSWORD),421 ),422 ("http://user:pass@complex.url.com/path?query=yes", ("user", "pass")),423 (424 "http://user:pass%20pass@complex.url.com/path?query=yes",425 ("user", "pass pass"),426 ),427 ("http://user:pass pass@complex.url.com/path?query=yes", ("user", "pass pass")),428 (429 "http://user%25user:pass@complex.url.com/path?query=yes",430 ("user%user", "pass"),431 ),432 (433 "http://user:pass%23pass@complex.url.com/path?query=yes",434 ("user", "pass#pass"),435 ),436 ("http://complex.url.com/path?query=yes", ("", "")),437 ),438)439def test_get_auth_from_url(url, auth):440 assert get_auth_from_url(url) == auth441442443@pytest.mark.parametrize(444 "uri, expected",445 (446 (447 # Ensure requoting doesn't break expectations448 "http://example.com/fiz?buz=%25ppicture",449 "http://example.com/fiz?buz=%25ppicture",450 ),451 (452 # Ensure we handle unquoted percent signs in redirects453 "http://example.com/fiz?buz=%ppicture",454 "http://example.com/fiz?buz=%25ppicture",455 ),456 ),457)458def test_requote_uri_with_unquoted_percents(uri, expected):459 """See: https://github.com/psf/requests/issues/2356"""460 assert requote_uri(uri) == expected461462463@pytest.mark.parametrize(464 "uri, expected",465 (466 (467 # Illegal bytes468 "http://example.com/?a=%--",469 "http://example.com/?a=%--",470 ),471 (472 # Reserved characters473 "http://example.com/?a=%300",474 "http://example.com/?a=00",475 ),476 ),477)478def test_unquote_unreserved(uri, expected):479 assert unquote_unreserved(uri) == expected480481482@pytest.mark.parametrize(483 "mask, expected",484 (485 (8, "255.0.0.0"),486 (24, "255.255.255.0"),487 (25, "255.255.255.128"),488 ),489)490def test_dotted_netmask(mask, expected):491 assert dotted_netmask(mask) == expected492493494http_proxies = {495 "http": "http://http.proxy",496 "http://some.host": "http://some.host.proxy",497}498all_proxies = {499 "all": "socks5://http.proxy",500 "all://some.host": "socks5://some.host.proxy",501}502mixed_proxies = {503 "http": "http://http.proxy",504 "http://some.host": "http://some.host.proxy",505 "all": "socks5://http.proxy",506}507508509@pytest.mark.parametrize(510 "url, expected, proxies",511 (512 ("hTTp://u:p@Some.Host/path", "http://some.host.proxy", http_proxies),513 ("hTTp://u:p@Other.Host/path", "http://http.proxy", http_proxies),514 ("hTTp:///path", "http://http.proxy", http_proxies),515 ("hTTps://Other.Host", None, http_proxies),516 ("file:///etc/motd", None, http_proxies),517 ("hTTp://u:p@Some.Host/path", "socks5://some.host.proxy", all_proxies),518 ("hTTp://u:p@Other.Host/path", "socks5://http.proxy", all_proxies),519 ("hTTp:///path", "socks5://http.proxy", all_proxies),520 ("hTTps://Other.Host", "socks5://http.proxy", all_proxies),521 ("http://u:p@other.host/path", "http://http.proxy", mixed_proxies),522 ("http://u:p@some.host/path", "http://some.host.proxy", mixed_proxies),523 ("https://u:p@other.host/path", "socks5://http.proxy", mixed_proxies),524 ("https://u:p@some.host/path", "socks5://http.proxy", mixed_proxies),525 ("https://", "socks5://http.proxy", mixed_proxies),526 # XXX: unsure whether this is reasonable behavior527 ("file:///etc/motd", "socks5://http.proxy", all_proxies),528 ),529)530def test_select_proxies(url, expected, proxies):531 """Make sure we can select per-host proxies correctly."""532 assert select_proxy(url, proxies) == expected533534535@pytest.mark.parametrize(536 "value, expected",537 (538 ('foo="is a fish", bar="as well"', {"foo": "is a fish", "bar": "as well"}),539 ("key_without_value", {"key_without_value": None}),540 ),541)542def test_parse_dict_header(value, expected):543 assert parse_dict_header(value) == expected544545546@pytest.mark.parametrize(547 "value, expected",548 (549 ("application/xml", ("application/xml", {})),550 (551 "application/json ; charset=utf-8",552 ("application/json", {"charset": "utf-8"}),553 ),554 (555 "application/json ; Charset=utf-8",556 ("application/json", {"charset": "utf-8"}),557 ),558 ("text/plain", ("text/plain", {})),559 (560 "multipart/form-data; boundary = something ; boundary2='something_else' ; no_equals ",561 (562 "multipart/form-data",563 {564 "boundary": "something",565 "boundary2": "something_else",566 "no_equals": True,567 },568 ),569 ),570 (571 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',572 (573 "multipart/form-data",574 {575 "boundary": "something",576 "boundary2": "something_else",577 "no_equals": True,578 },579 ),580 ),581 (582 "multipart/form-data; boundary = something ; 'boundary2=something_else' ; no_equals ",583 (584 "multipart/form-data",585 {586 "boundary": "something",587 "boundary2": "something_else",588 "no_equals": True,589 },590 ),591 ),592 (593 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',594 (595 "multipart/form-data",596 {597 "boundary": "something",598 "boundary2": "something_else",599 "no_equals": True,600 },601 ),602 ),603 ("application/json ; ; ", ("application/json", {})),604 ),605)606def test__parse_content_type_header(value, expected):607 assert _parse_content_type_header(value) == expected608609610@pytest.mark.parametrize(611 "value, expected",612 (613 (CaseInsensitiveDict(), None),614 (615 CaseInsensitiveDict({"content-type": "application/json; charset=utf-8"}),616 "utf-8",617 ),618 (CaseInsensitiveDict({"content-type": "text/plain"}), "ISO-8859-1"),619 ),620)621def test_get_encoding_from_headers(value, expected):622 assert get_encoding_from_headers(value) == expected623624625@pytest.mark.parametrize(626 "value, length",627 (628 ("", 0),629 ("T", 1),630 ("Test", 4),631 ("Cont", 0),632 ("Other", -5),633 ("Content", None),634 ),635)636def test_iter_slices(value, length):637 if length is None or (length <= 0 and len(value) > 0):638 # Reads all content at once639 assert len(list(iter_slices(value, length))) == 1640 else:641 assert len(list(iter_slices(value, 1))) == length642643644@pytest.mark.parametrize(645 "value, expected",646 (647 (648 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',649 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],650 ),651 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),652 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),653 (654 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',655 [656 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},657 {"url": "http://.../back.jpeg"},658 ],659 ),660 ("", []),661 ),662)663def test_parse_header_links(value, expected):664 assert parse_header_links(value) == expected665666667@pytest.mark.parametrize(668 "value, expected",669 (670 ("example.com/path", "http://example.com/path"),671 ("//example.com/path", "http://example.com/path"),672 ("example.com:80", "http://example.com:80"),673 (674 "http://user:pass@example.com/path?query",675 "http://user:pass@example.com/path?query",676 ),677 ("http://user@example.com/path?query", "http://user@example.com/path?query"),678 ),679)680def test_prepend_scheme_if_needed(value, expected):681 assert prepend_scheme_if_needed(value, "http") == expected682683684@pytest.mark.parametrize(685 "value, expected",686 (687 ("T", "T"),688 (b"T", "T"),689 ("T", "T"),690 ),691)692def test_to_native_string(value, expected):693 assert to_native_string(value) == expected694695696@pytest.mark.parametrize(697 "url, expected",698 (699 ("http://u:p@example.com/path?a=1#test", "http://example.com/path?a=1"),700 ("http://example.com/path", "http://example.com/path"),701 ("//u:p@example.com/path", "//example.com/path"),702 ("//example.com/path", "//example.com/path"),703 ("example.com/path", "//example.com/path"),704 ("scheme:u:p@example.com/path", "scheme://example.com/path"),705 ),706)707def test_urldefragauth(url, expected):708 assert urldefragauth(url) == expected709710711@pytest.mark.parametrize(712 "url, expected",713 (714 ("http://192.168.0.1:5000/", True),715 ("http://192.168.0.1/", True),716 ("http://172.16.1.1/", True),717 ("http://172.16.1.1:5000/", True),718 ("http://localhost.localdomain:5000/v1.0/", True),719 ("http://google.com:6000/", True),720 ("http://172.16.1.12/", False),721 ("http://172.16.1.12:5000/", False),722 ("http://google.com:5000/v1.0/", False),723 ("file:///some/path/on/disk", True),724 ),725)726def test_should_bypass_proxies(url, expected, monkeypatch):727 """Tests for function should_bypass_proxies to check if proxy728 can be bypassed or not729 """730 monkeypatch.setenv(731 "no_proxy",732 "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000",733 )734 monkeypatch.setenv(735 "NO_PROXY",736 "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000",737 )738 assert should_bypass_proxies(url, no_proxy=None) == expected739740741@pytest.mark.parametrize(742 "url, expected",743 (744 ("http://172.16.1.1/", "172.16.1.1"),745 ("http://172.16.1.1:5000/", "172.16.1.1"),746 ("http://user:pass@172.16.1.1", "172.16.1.1"),747 ("http://user:pass@172.16.1.1:5000", "172.16.1.1"),748 ("http://hostname/", "hostname"),749 ("http://hostname:5000/", "hostname"),750 ("http://user:pass@hostname", "hostname"),751 ("http://user:pass@hostname:5000", "hostname"),752 ),753)754def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):755 """The proxy_bypass function should be called with a hostname or IP without756 a port number or auth credentials.757 """758 proxy_bypass = mocker.patch("requests.utils.proxy_bypass")759 should_bypass_proxies(url, no_proxy=None)760 proxy_bypass.assert_called_once_with(expected)761762763@pytest.mark.parametrize(764 "cookiejar",765 (766 compat.cookielib.CookieJar(),767 RequestsCookieJar(),768 ),769)770def test_add_dict_to_cookiejar(cookiejar):771 """Ensure add_dict_to_cookiejar works for772 non-RequestsCookieJar CookieJars773 """774 cookiedict = {"test": "cookies", "good": "cookies"}775 cj = add_dict_to_cookiejar(cookiejar, cookiedict)776 cookies = {cookie.name: cookie.value for cookie in cj}777 assert cookiedict == cookies778779780@pytest.mark.parametrize(781 "value, expected",782 (783 ("test", True),784 ("æíöû", False),785 ("ジェーピーニック", False),786 ),787)788def test_unicode_is_ascii(value, expected):789 assert unicode_is_ascii(value) is expected790791792@pytest.mark.parametrize(793 "url, expected",794 (795 ("http://192.168.0.1:5000/", True),796 ("http://192.168.0.1/", True),797 ("http://172.16.1.1/", True),798 ("http://172.16.1.1:5000/", True),799 ("http://localhost.localdomain:5000/v1.0/", True),800 ("http://172.16.1.12/", False),801 ("http://172.16.1.12:5000/", False),802 ("http://google.com:5000/v1.0/", False),803 ),804)805def test_should_bypass_proxies_no_proxy(url, expected, monkeypatch):806 """Tests for function should_bypass_proxies to check if proxy807 can be bypassed or not using the 'no_proxy' argument808 """809 no_proxy = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"810 # Test 'no_proxy' argument811 assert should_bypass_proxies(url, no_proxy=no_proxy) == expected812813814@pytest.mark.skipif(os.name != "nt", reason="Test only on Windows")815@pytest.mark.parametrize(816 "url, expected, override",817 (818 ("http://192.168.0.1:5000/", True, None),819 ("http://192.168.0.1/", True, None),820 ("http://172.16.1.1/", True, None),821 ("http://172.16.1.1:5000/", True, None),822 ("http://localhost.localdomain:5000/v1.0/", True, None),823 ("http://172.16.1.22/", False, None),824 ("http://172.16.1.22:5000/", False, None),825 ("http://google.com:5000/v1.0/", False, None),826 ("http://mylocalhostname:5000/v1.0/", True, "<local>"),827 ("http://192.168.0.1/", False, ""),828 ),829)830def test_should_bypass_proxies_win_registry(url, expected, override, monkeypatch):831 """Tests for function should_bypass_proxies to check if proxy832 can be bypassed or not with Windows registry settings833 """834 if override is None:835 override = "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"836 import winreg837838 class RegHandle:839 def Close(self):840 pass841842 ie_settings = RegHandle()843 proxyEnableValues = deque([1, "1"])844845 def OpenKey(key, subkey):846 return ie_settings847848 def QueryValueEx(key, value_name):849 if key is ie_settings:850 if value_name == "ProxyEnable":851 # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)852 proxyEnableValues.rotate()853 return [proxyEnableValues[0]]854 elif value_name == "ProxyOverride":855 return [override]856857 monkeypatch.setenv("http_proxy", "")858 monkeypatch.setenv("https_proxy", "")859 monkeypatch.setenv("ftp_proxy", "")860 monkeypatch.setenv("no_proxy", "")861 monkeypatch.setenv("NO_PROXY", "")862 monkeypatch.setattr(winreg, "OpenKey", OpenKey)863 monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx)864 assert should_bypass_proxies(url, None) == expected865866867@pytest.mark.skipif(os.name != "nt", reason="Test only on Windows")868def test_should_bypass_proxies_win_registry_bad_values(monkeypatch):869 """Tests for function should_bypass_proxies to check if proxy870 can be bypassed or not with Windows invalid registry settings.871 """872 import winreg873874 class RegHandle:875 def Close(self):876 pass877878 ie_settings = RegHandle()879880 def OpenKey(key, subkey):881 return ie_settings882883 def QueryValueEx(key, value_name):884 if key is ie_settings:885 if value_name == "ProxyEnable":886 # Invalid response; Should be an int or int-y value887 return [""]888 elif value_name == "ProxyOverride":889 return ["192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"]890891 monkeypatch.setenv("http_proxy", "")892 monkeypatch.setenv("https_proxy", "")893 monkeypatch.setenv("no_proxy", "")894 monkeypatch.setenv("NO_PROXY", "")895 monkeypatch.setattr(winreg, "OpenKey", OpenKey)896 monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx)897 assert should_bypass_proxies("http://172.16.1.1/", None) is False898899900@pytest.mark.parametrize(901 "env_name, value",902 (903 ("no_proxy", "192.168.0.0/24,127.0.0.1,localhost.localdomain"),904 ("no_proxy", None),905 ("a_new_key", "192.168.0.0/24,127.0.0.1,localhost.localdomain"),906 ("a_new_key", None),907 ),908)909def test_set_environ(env_name, value):910 """Tests set_environ will set environ values and will restore the environ."""911 environ_copy = copy.deepcopy(os.environ)912 with set_environ(env_name, value):913 assert os.environ.get(env_name) == value914915 assert os.environ == environ_copy916917918def test_set_environ_raises_exception():919 """Tests set_environ will raise exceptions in context when the920 value parameter is None."""921 with pytest.raises(Exception) as exception:922 with set_environ("test1", None):923 raise Exception("Expected exception")924925 assert "Expected exception" in str(exception.value)