test_utils.py
This file
Path
tests/test_utils.py
926 lines · 27.6 KiB · Python
Last changed by
Remove pytest-mock requirement (#6505)Nate Prewittbefore adoption005571d
History of this fileTake it
1import copy2import filecmp3import os4import tarfile5import zipfile6from collections import deque7from io import BytesIO8from unittest import mock910import pytest1112from requests import compat13from requests._internal_utils import unicode_is_ascii14from requests.cookies import RequestsCookieJar15from requests.structures import CaseInsensitiveDict16from requests.utils import (17 _parse_content_type_header,18 add_dict_to_cookiejar,19 address_in_network,20 dotted_netmask,21 extract_zipped_paths,22 get_auth_from_url,23 get_encoding_from_headers,24 get_encodings_from_content,25 get_environ_proxies,26 guess_filename,27 guess_json_utf,28 is_ipv4_address,29 is_valid_cidr,30 iter_slices,31 parse_dict_header,32 parse_header_links,33 prepend_scheme_if_needed,34 requote_uri,35 select_proxy,36 set_environ,37 should_bypass_proxies,38 super_len,39 to_key_val_list,40 to_native_string,41 unquote_header_value,42 unquote_unreserved,43 urldefragauth,44)4546from .compat import StringIO, cStringIO474849class TestSuperLen:50 @pytest.mark.parametrize(51 "stream, value",52 (53 (StringIO.StringIO, "Test"),54 (BytesIO, b"Test"),55 pytest.param(56 cStringIO, "Test", marks=pytest.mark.skipif("cStringIO is None")57 ),58 ),59 )60 def test_io_streams(self, stream, value):61 """Ensures that we properly deal with different kinds of IO streams."""62 assert super_len(stream()) == 063 assert super_len(stream(value)) == 46465 def test_super_len_correctly_calculates_len_of_partially_read_file(self):66 """Ensure that we handle partially consumed file like objects."""67 s = StringIO.StringIO()68 s.write("foobarbogus")69 assert super_len(s) == 07071 @pytest.mark.parametrize("error", [IOError, OSError])72 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):73 """If tell() raises errors, assume the cursor is at position zero."""7475 class BoomFile:76 def __len__(self):77 return 57879 def tell(self):80 raise error()8182 assert super_len(BoomFile()) == 08384 @pytest.mark.parametrize("error", [IOError, OSError])85 def test_super_len_tell_ioerror(self, error):86 """Ensure that if tell gives an IOError super_len doesn't fail"""8788 class NoLenBoomFile:89 def tell(self):90 raise error()9192 def seek(self, offset, whence):93 pass9495 assert super_len(NoLenBoomFile()) == 09697 def test_string(self):98 assert super_len("Test") == 499100 @pytest.mark.parametrize(101 "mode, warnings_num",102 (103 ("r", 1),104 ("rb", 0),105 ),106 )107 def test_file(self, tmpdir, mode, warnings_num, recwarn):108 file_obj = tmpdir.join("test.txt")109 file_obj.write("Test")110 with file_obj.open(mode) as fd:111 assert super_len(fd) == 4112 assert len(recwarn) == warnings_num113114 def test_tarfile_member(self, tmpdir):115 file_obj = tmpdir.join("test.txt")116 file_obj.write("Test")117118 tar_obj = str(tmpdir.join("test.tar"))119 with tarfile.open(tar_obj, "w") as tar:120 tar.add(str(file_obj), arcname="test.txt")121122 with tarfile.open(tar_obj) as tar:123 member = tar.extractfile("test.txt")124 assert super_len(member) == 4125126 def test_super_len_with__len__(self):127 foo = [1, 2, 3, 4]128 len_foo = super_len(foo)129 assert len_foo == 4130131 def test_super_len_with_no__len__(self):132 class LenFile:133 def __init__(self):134 self.len = 5135136 assert super_len(LenFile()) == 5137138 def test_super_len_with_tell(self):139 foo = StringIO.StringIO("12345")140 assert super_len(foo) == 5141 foo.read(2)142 assert super_len(foo) == 3143144 def test_super_len_with_fileno(self):145 with open(__file__, "rb") as f:146 length = super_len(f)147 file_data = f.read()148 assert length == len(file_data)149150 def test_super_len_with_no_matches(self):151 """Ensure that objects without any length methods default to 0"""152 assert super_len(object()) == 0153154155class TestToKeyValList:156 @pytest.mark.parametrize(157 "value, expected",158 (159 ([("key", "val")], [("key", "val")]),160 ((("key", "val"),), [("key", "val")]),161 ({"key": "val"}, [("key", "val")]),162 (None, None),163 ),164 )165 def test_valid(self, value, expected):166 assert to_key_val_list(value) == expected167168 def test_invalid(self):169 with pytest.raises(ValueError):170 to_key_val_list("string")171172173class TestUnquoteHeaderValue:174 @pytest.mark.parametrize(175 "value, expected",176 (177 (None, None),178 ("Test", "Test"),179 ('"Test"', "Test"),180 ('"Test\\\\"', "Test\\"),181 ('"\\\\Comp\\Res"', "\\Comp\\Res"),182 ),183 )184 def test_valid(self, value, expected):185 assert unquote_header_value(value) == expected186187 def test_is_filename(self):188 assert unquote_header_value('"\\\\Comp\\Res"', True) == "\\\\Comp\\Res"189190191class TestGetEnvironProxies:192 """Ensures that IP addresses are correctly matches with ranges193 in no_proxy variable.194 """195196 @pytest.fixture(autouse=True, params=["no_proxy", "NO_PROXY"])197 def no_proxy(self, request, monkeypatch):198 monkeypatch.setenv(199 request.param, "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"200 )201202 @pytest.mark.parametrize(203 "url",204 (205 "http://192.168.0.1:5000/",206 "http://192.168.0.1/",207 "http://172.16.1.1/",208 "http://172.16.1.1:5000/",209 "http://localhost.localdomain:5000/v1.0/",210 ),211 )212 def test_bypass(self, url):213 assert get_environ_proxies(url, no_proxy=None) == {}214215 @pytest.mark.parametrize(216 "url",217 (218 "http://192.168.1.1:5000/",219 "http://192.168.1.1/",220 "http://www.requests.com/",221 ),222 )223 def test_not_bypass(self, url):224 assert get_environ_proxies(url, no_proxy=None) != {}225226 @pytest.mark.parametrize(227 "url",228 (229 "http://192.168.1.1:5000/",230 "http://192.168.1.1/",231 "http://www.requests.com/",232 ),233 )234 def test_bypass_no_proxy_keyword(self, url):235 no_proxy = "192.168.1.1,requests.com"236 assert get_environ_proxies(url, no_proxy=no_proxy) == {}237238 @pytest.mark.parametrize(239 "url",240 (241 "http://192.168.0.1:5000/",242 "http://192.168.0.1/",243 "http://172.16.1.1/",244 "http://172.16.1.1:5000/",245 "http://localhost.localdomain:5000/v1.0/",246 ),247 )248 def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):249 # This is testing that the 'no_proxy' argument overrides the250 # environment variable 'no_proxy'251 monkeypatch.setenv("http_proxy", "http://proxy.example.com:3128/")252 no_proxy = "192.168.1.1,requests.com"253 assert get_environ_proxies(url, no_proxy=no_proxy) != {}254255256class TestIsIPv4Address:257 def test_valid(self):258 assert is_ipv4_address("8.8.8.8")259260 @pytest.mark.parametrize("value", ("8.8.8.8.8", "localhost.localdomain"))261 def test_invalid(self, value):262 assert not is_ipv4_address(value)263264265class TestIsValidCIDR:266 def test_valid(self):267 assert is_valid_cidr("192.168.1.0/24")268269 @pytest.mark.parametrize(270 "value",271 (272 "8.8.8.8",273 "192.168.1.0/a",274 "192.168.1.0/128",275 "192.168.1.0/-1",276 "192.168.1.999/24",277 ),278 )279 def test_invalid(self, value):280 assert not is_valid_cidr(value)281282283class TestAddressInNetwork:284 def test_valid(self):285 assert address_in_network("192.168.1.1", "192.168.1.0/24")286287 def test_invalid(self):288 assert not address_in_network("172.16.0.1", "192.168.1.0/24")289290291class TestGuessFilename:292 @pytest.mark.parametrize(293 "value",294 (1, type("Fake", (object,), {"name": 1})()),295 )296 def test_guess_filename_invalid(self, value):297 assert guess_filename(value) is None298299 @pytest.mark.parametrize(300 "value, expected_type",301 (302 (b"value", compat.bytes),303 (b"value".decode("utf-8"), compat.str),304 ),305 )306 def test_guess_filename_valid(self, value, expected_type):307 obj = type("Fake", (object,), {"name": value})()308 result = guess_filename(obj)309 assert result == value310 assert isinstance(result, expected_type)311312313class TestExtractZippedPaths:314 @pytest.mark.parametrize(315 "path",316 (317 "/",318 __file__,319 pytest.__file__,320 "/etc/invalid/location",321 ),322 )323 def test_unzipped_paths_unchanged(self, path):324 assert path == extract_zipped_paths(path)325326 def test_zipped_paths_extracted(self, tmpdir):327 zipped_py = tmpdir.join("test.zip")328 with zipfile.ZipFile(zipped_py.strpath, "w") as f:329 f.write(__file__)330331 _, name = os.path.splitdrive(__file__)332 zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r"\/"))333 extracted_path = extract_zipped_paths(zipped_path)334335 assert extracted_path != zipped_path336 assert os.path.exists(extracted_path)337 assert filecmp.cmp(extracted_path, __file__)338339 def test_invalid_unc_path(self):340 path = r"\\localhost\invalid\location"341 assert extract_zipped_paths(path) == path342343344class TestContentEncodingDetection:345 def test_none(self):346 encodings = get_encodings_from_content("")347 assert not len(encodings)348349 @pytest.mark.parametrize(350 "content",351 (352 # HTML5 meta charset attribute353 '<meta charset="UTF-8">',354 # HTML4 pragma directive355 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',356 # XHTML 1.x served with text/html MIME type357 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',358 # XHTML 1.x served as XML359 '<?xml version="1.0" encoding="UTF-8"?>',360 ),361 )362 def test_pragmas(self, content):363 encodings = get_encodings_from_content(content)364 assert len(encodings) == 1365 assert encodings[0] == "UTF-8"366367 def test_precedence(self):368 content = """369 <?xml version="1.0" encoding="XML"?>370 <meta charset="HTML5">371 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />372 """.strip()373 assert get_encodings_from_content(content) == ["HTML5", "HTML4", "XML"]374375376class TestGuessJSONUTF:377 @pytest.mark.parametrize(378 "encoding",379 (380 "utf-32",381 "utf-8-sig",382 "utf-16",383 "utf-8",384 "utf-16-be",385 "utf-16-le",386 "utf-32-be",387 "utf-32-le",388 ),389 )390 def test_encoded(self, encoding):391 data = "{}".encode(encoding)392 assert guess_json_utf(data) == encoding393394 def test_bad_utf_like_encoding(self):395 assert guess_json_utf(b"\x00\x00\x00\x00") is None396397 @pytest.mark.parametrize(398 ("encoding", "expected"),399 (400 ("utf-16-be", "utf-16"),401 ("utf-16-le", "utf-16"),402 ("utf-32-be", "utf-32"),403 ("utf-32-le", "utf-32"),404 ),405 )406 def test_guess_by_bom(self, encoding, expected):407 data = "\ufeff{}".encode(encoding)408 assert guess_json_utf(data) == expected409410411USER = PASSWORD = "%!*'();:@&=+$,/?#[] "412ENCODED_USER = compat.quote(USER, "")413ENCODED_PASSWORD = compat.quote(PASSWORD, "")414415416@pytest.mark.parametrize(417 "url, auth",418 (419 (420 f"http://{ENCODED_USER}:{ENCODED_PASSWORD}@request.com/url.html#test",421 (USER, PASSWORD),422 ),423 ("http://user:pass@complex.url.com/path?query=yes", ("user", "pass")),424 (425 "http://user:pass%20pass@complex.url.com/path?query=yes",426 ("user", "pass pass"),427 ),428 ("http://user:pass pass@complex.url.com/path?query=yes", ("user", "pass pass")),429 (430 "http://user%25user:pass@complex.url.com/path?query=yes",431 ("user%user", "pass"),432 ),433 (434 "http://user:pass%23pass@complex.url.com/path?query=yes",435 ("user", "pass#pass"),436 ),437 ("http://complex.url.com/path?query=yes", ("", "")),438 ),439)440def test_get_auth_from_url(url, auth):441 assert get_auth_from_url(url) == auth442443444@pytest.mark.parametrize(445 "uri, expected",446 (447 (448 # Ensure requoting doesn't break expectations449 "http://example.com/fiz?buz=%25ppicture",450 "http://example.com/fiz?buz=%25ppicture",451 ),452 (453 # Ensure we handle unquoted percent signs in redirects454 "http://example.com/fiz?buz=%ppicture",455 "http://example.com/fiz?buz=%25ppicture",456 ),457 ),458)459def test_requote_uri_with_unquoted_percents(uri, expected):460 """See: https://github.com/psf/requests/issues/2356"""461 assert requote_uri(uri) == expected462463464@pytest.mark.parametrize(465 "uri, expected",466 (467 (468 # Illegal bytes469 "http://example.com/?a=%--",470 "http://example.com/?a=%--",471 ),472 (473 # Reserved characters474 "http://example.com/?a=%300",475 "http://example.com/?a=00",476 ),477 ),478)479def test_unquote_unreserved(uri, expected):480 assert unquote_unreserved(uri) == expected481482483@pytest.mark.parametrize(484 "mask, expected",485 (486 (8, "255.0.0.0"),487 (24, "255.255.255.0"),488 (25, "255.255.255.128"),489 ),490)491def test_dotted_netmask(mask, expected):492 assert dotted_netmask(mask) == expected493494495http_proxies = {496 "http": "http://http.proxy",497 "http://some.host": "http://some.host.proxy",498}499all_proxies = {500 "all": "socks5://http.proxy",501 "all://some.host": "socks5://some.host.proxy",502}503mixed_proxies = {504 "http": "http://http.proxy",505 "http://some.host": "http://some.host.proxy",506 "all": "socks5://http.proxy",507}508509510@pytest.mark.parametrize(511 "url, expected, proxies",512 (513 ("hTTp://u:p@Some.Host/path", "http://some.host.proxy", http_proxies),514 ("hTTp://u:p@Other.Host/path", "http://http.proxy", http_proxies),515 ("hTTp:///path", "http://http.proxy", http_proxies),516 ("hTTps://Other.Host", None, http_proxies),517 ("file:///etc/motd", None, http_proxies),518 ("hTTp://u:p@Some.Host/path", "socks5://some.host.proxy", all_proxies),519 ("hTTp://u:p@Other.Host/path", "socks5://http.proxy", all_proxies),520 ("hTTp:///path", "socks5://http.proxy", all_proxies),521 ("hTTps://Other.Host", "socks5://http.proxy", all_proxies),522 ("http://u:p@other.host/path", "http://http.proxy", mixed_proxies),523 ("http://u:p@some.host/path", "http://some.host.proxy", mixed_proxies),524 ("https://u:p@other.host/path", "socks5://http.proxy", mixed_proxies),525 ("https://u:p@some.host/path", "socks5://http.proxy", mixed_proxies),526 ("https://", "socks5://http.proxy", mixed_proxies),527 # XXX: unsure whether this is reasonable behavior528 ("file:///etc/motd", "socks5://http.proxy", all_proxies),529 ),530)531def test_select_proxies(url, expected, proxies):532 """Make sure we can select per-host proxies correctly."""533 assert select_proxy(url, proxies) == expected534535536@pytest.mark.parametrize(537 "value, expected",538 (539 ('foo="is a fish", bar="as well"', {"foo": "is a fish", "bar": "as well"}),540 ("key_without_value", {"key_without_value": None}),541 ),542)543def test_parse_dict_header(value, expected):544 assert parse_dict_header(value) == expected545546547@pytest.mark.parametrize(548 "value, expected",549 (550 ("application/xml", ("application/xml", {})),551 (552 "application/json ; charset=utf-8",553 ("application/json", {"charset": "utf-8"}),554 ),555 (556 "application/json ; Charset=utf-8",557 ("application/json", {"charset": "utf-8"}),558 ),559 ("text/plain", ("text/plain", {})),560 (561 "multipart/form-data; boundary = something ; boundary2='something_else' ; no_equals ",562 (563 "multipart/form-data",564 {565 "boundary": "something",566 "boundary2": "something_else",567 "no_equals": True,568 },569 ),570 ),571 (572 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',573 (574 "multipart/form-data",575 {576 "boundary": "something",577 "boundary2": "something_else",578 "no_equals": True,579 },580 ),581 ),582 (583 "multipart/form-data; boundary = something ; 'boundary2=something_else' ; no_equals ",584 (585 "multipart/form-data",586 {587 "boundary": "something",588 "boundary2": "something_else",589 "no_equals": True,590 },591 ),592 ),593 (594 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',595 (596 "multipart/form-data",597 {598 "boundary": "something",599 "boundary2": "something_else",600 "no_equals": True,601 },602 ),603 ),604 ("application/json ; ; ", ("application/json", {})),605 ),606)607def test__parse_content_type_header(value, expected):608 assert _parse_content_type_header(value) == expected609610611@pytest.mark.parametrize(612 "value, expected",613 (614 (CaseInsensitiveDict(), None),615 (616 CaseInsensitiveDict({"content-type": "application/json; charset=utf-8"}),617 "utf-8",618 ),619 (CaseInsensitiveDict({"content-type": "text/plain"}), "ISO-8859-1"),620 ),621)622def test_get_encoding_from_headers(value, expected):623 assert get_encoding_from_headers(value) == expected624625626@pytest.mark.parametrize(627 "value, length",628 (629 ("", 0),630 ("T", 1),631 ("Test", 4),632 ("Cont", 0),633 ("Other", -5),634 ("Content", None),635 ),636)637def test_iter_slices(value, length):638 if length is None or (length <= 0 and len(value) > 0):639 # Reads all content at once640 assert len(list(iter_slices(value, length))) == 1641 else:642 assert len(list(iter_slices(value, 1))) == length643644645@pytest.mark.parametrize(646 "value, expected",647 (648 (649 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',650 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],651 ),652 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),653 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),654 (655 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',656 [657 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},658 {"url": "http://.../back.jpeg"},659 ],660 ),661 ("", []),662 ),663)664def test_parse_header_links(value, expected):665 assert parse_header_links(value) == expected666667668@pytest.mark.parametrize(669 "value, expected",670 (671 ("example.com/path", "http://example.com/path"),672 ("//example.com/path", "http://example.com/path"),673 ("example.com:80", "http://example.com:80"),674 (675 "http://user:pass@example.com/path?query",676 "http://user:pass@example.com/path?query",677 ),678 ("http://user@example.com/path?query", "http://user@example.com/path?query"),679 ),680)681def test_prepend_scheme_if_needed(value, expected):682 assert prepend_scheme_if_needed(value, "http") == expected683684685@pytest.mark.parametrize(686 "value, expected",687 (688 ("T", "T"),689 (b"T", "T"),690 ("T", "T"),691 ),692)693def test_to_native_string(value, expected):694 assert to_native_string(value) == expected695696697@pytest.mark.parametrize(698 "url, expected",699 (700 ("http://u:p@example.com/path?a=1#test", "http://example.com/path?a=1"),701 ("http://example.com/path", "http://example.com/path"),702 ("//u:p@example.com/path", "//example.com/path"),703 ("//example.com/path", "//example.com/path"),704 ("example.com/path", "//example.com/path"),705 ("scheme:u:p@example.com/path", "scheme://example.com/path"),706 ),707)708def test_urldefragauth(url, expected):709 assert urldefragauth(url) == expected710711712@pytest.mark.parametrize(713 "url, expected",714 (715 ("http://192.168.0.1:5000/", True),716 ("http://192.168.0.1/", True),717 ("http://172.16.1.1/", True),718 ("http://172.16.1.1:5000/", True),719 ("http://localhost.localdomain:5000/v1.0/", True),720 ("http://google.com:6000/", True),721 ("http://172.16.1.12/", False),722 ("http://172.16.1.12:5000/", False),723 ("http://google.com:5000/v1.0/", False),724 ("file:///some/path/on/disk", True),725 ),726)727def test_should_bypass_proxies(url, expected, monkeypatch):728 """Tests for function should_bypass_proxies to check if proxy729 can be bypassed or not730 """731 monkeypatch.setenv(732 "no_proxy",733 "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000",734 )735 monkeypatch.setenv(736 "NO_PROXY",737 "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000",738 )739 assert should_bypass_proxies(url, no_proxy=None) == expected740741742@pytest.mark.parametrize(743 "url, expected",744 (745 ("http://172.16.1.1/", "172.16.1.1"),746 ("http://172.16.1.1:5000/", "172.16.1.1"),747 ("http://user:pass@172.16.1.1", "172.16.1.1"),748 ("http://user:pass@172.16.1.1:5000", "172.16.1.1"),749 ("http://hostname/", "hostname"),750 ("http://hostname:5000/", "hostname"),751 ("http://user:pass@hostname", "hostname"),752 ("http://user:pass@hostname:5000", "hostname"),753 ),754)755def test_should_bypass_proxies_pass_only_hostname(url, expected):756 """The proxy_bypass function should be called with a hostname or IP without757 a port number or auth credentials.758 """759 with mock.patch("requests.utils.proxy_bypass") as proxy_bypass:760 should_bypass_proxies(url, no_proxy=None)761 proxy_bypass.assert_called_once_with(expected)762763764@pytest.mark.parametrize(765 "cookiejar",766 (767 compat.cookielib.CookieJar(),768 RequestsCookieJar(),769 ),770)771def test_add_dict_to_cookiejar(cookiejar):772 """Ensure add_dict_to_cookiejar works for773 non-RequestsCookieJar CookieJars774 """775 cookiedict = {"test": "cookies", "good": "cookies"}776 cj = add_dict_to_cookiejar(cookiejar, cookiedict)777 cookies = {cookie.name: cookie.value for cookie in cj}778 assert cookiedict == cookies779780781@pytest.mark.parametrize(782 "value, expected",783 (784 ("test", True),785 ("æíöû", False),786 ("ジェーピーニック", False),787 ),788)789def test_unicode_is_ascii(value, expected):790 assert unicode_is_ascii(value) is expected791792793@pytest.mark.parametrize(794 "url, expected",795 (796 ("http://192.168.0.1:5000/", True),797 ("http://192.168.0.1/", True),798 ("http://172.16.1.1/", True),799 ("http://172.16.1.1:5000/", True),800 ("http://localhost.localdomain:5000/v1.0/", True),801 ("http://172.16.1.12/", False),802 ("http://172.16.1.12:5000/", False),803 ("http://google.com:5000/v1.0/", False),804 ),805)806def test_should_bypass_proxies_no_proxy(url, expected, monkeypatch):807 """Tests for function should_bypass_proxies to check if proxy808 can be bypassed or not using the 'no_proxy' argument809 """810 no_proxy = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"811 # Test 'no_proxy' argument812 assert should_bypass_proxies(url, no_proxy=no_proxy) == expected813814815@pytest.mark.skipif(os.name != "nt", reason="Test only on Windows")816@pytest.mark.parametrize(817 "url, expected, override",818 (819 ("http://192.168.0.1:5000/", True, None),820 ("http://192.168.0.1/", True, None),821 ("http://172.16.1.1/", True, None),822 ("http://172.16.1.1:5000/", True, None),823 ("http://localhost.localdomain:5000/v1.0/", True, None),824 ("http://172.16.1.22/", False, None),825 ("http://172.16.1.22:5000/", False, None),826 ("http://google.com:5000/v1.0/", False, None),827 ("http://mylocalhostname:5000/v1.0/", True, "<local>"),828 ("http://192.168.0.1/", False, ""),829 ),830)831def test_should_bypass_proxies_win_registry(url, expected, override, monkeypatch):832 """Tests for function should_bypass_proxies to check if proxy833 can be bypassed or not with Windows registry settings834 """835 if override is None:836 override = "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"837 import winreg838839 class RegHandle:840 def Close(self):841 pass842843 ie_settings = RegHandle()844 proxyEnableValues = deque([1, "1"])845846 def OpenKey(key, subkey):847 return ie_settings848849 def QueryValueEx(key, value_name):850 if key is ie_settings:851 if value_name == "ProxyEnable":852 # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)853 proxyEnableValues.rotate()854 return [proxyEnableValues[0]]855 elif value_name == "ProxyOverride":856 return [override]857858 monkeypatch.setenv("http_proxy", "")859 monkeypatch.setenv("https_proxy", "")860 monkeypatch.setenv("ftp_proxy", "")861 monkeypatch.setenv("no_proxy", "")862 monkeypatch.setenv("NO_PROXY", "")863 monkeypatch.setattr(winreg, "OpenKey", OpenKey)864 monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx)865 assert should_bypass_proxies(url, None) == expected866867868@pytest.mark.skipif(os.name != "nt", reason="Test only on Windows")869def test_should_bypass_proxies_win_registry_bad_values(monkeypatch):870 """Tests for function should_bypass_proxies to check if proxy871 can be bypassed or not with Windows invalid registry settings.872 """873 import winreg874875 class RegHandle:876 def Close(self):877 pass878879 ie_settings = RegHandle()880881 def OpenKey(key, subkey):882 return ie_settings883884 def QueryValueEx(key, value_name):885 if key is ie_settings:886 if value_name == "ProxyEnable":887 # Invalid response; Should be an int or int-y value888 return [""]889 elif value_name == "ProxyOverride":890 return ["192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"]891892 monkeypatch.setenv("http_proxy", "")893 monkeypatch.setenv("https_proxy", "")894 monkeypatch.setenv("no_proxy", "")895 monkeypatch.setenv("NO_PROXY", "")896 monkeypatch.setattr(winreg, "OpenKey", OpenKey)897 monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx)898 assert should_bypass_proxies("http://172.16.1.1/", None) is False899900901@pytest.mark.parametrize(902 "env_name, value",903 (904 ("no_proxy", "192.168.0.0/24,127.0.0.1,localhost.localdomain"),905 ("no_proxy", None),906 ("a_new_key", "192.168.0.0/24,127.0.0.1,localhost.localdomain"),907 ("a_new_key", None),908 ),909)910def test_set_environ(env_name, value):911 """Tests set_environ will set environ values and will restore the environ."""912 environ_copy = copy.deepcopy(os.environ)913 with set_environ(env_name, value):914 assert os.environ.get(env_name) == value915916 assert os.environ == environ_copy917918919def test_set_environ_raises_exception():920 """Tests set_environ will raise exceptions in context when the921 value parameter is None."""922 with pytest.raises(Exception) as exception:923 with set_environ("test1", None):924 raise Exception("Expected exception")925926 assert "Expected exception" in str(exception.value)