test_utils.py
This file
Path
tests/test_utils.py
777 lines · 25.2 KiB · Python
Last changed by
Merge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption3c1d36b
History of this fileTake it
1# -*- coding: utf-8 -*-23import os4import copy5import filecmp6from io import BytesIO7import zipfile8from collections import deque910import pytest11from requests import compat12from requests.cookies import RequestsCookieJar13from requests.structures import CaseInsensitiveDict14from requests.utils import (15 address_in_network, dotted_netmask, extract_zipped_paths,16 get_auth_from_url, _parse_content_type_header, get_encoding_from_headers,17 get_encodings_from_content, get_environ_proxies,18 guess_filename, guess_json_utf, is_ipv4_address,19 is_valid_cidr, iter_slices, parse_dict_header,20 parse_header_links, prepend_scheme_if_needed,21 requote_uri, select_proxy, should_bypass_proxies, super_len,22 to_key_val_list, to_native_string,23 unquote_header_value, unquote_unreserved,24 urldefragauth, add_dict_to_cookiejar, set_environ)25from requests._internal_utils import unicode_is_ascii2627from .compat import StringIO, cStringIO282930class TestSuperLen:3132 @pytest.mark.parametrize(33 'stream, value', (34 (StringIO.StringIO, 'Test'),35 (BytesIO, b'Test'),36 pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),37 ))38 def test_io_streams(self, stream, value):39 """Ensures that we properly deal with different kinds of IO streams."""40 assert super_len(stream()) == 041 assert super_len(stream(value)) == 44243 def test_super_len_correctly_calculates_len_of_partially_read_file(self):44 """Ensure that we handle partially consumed file like objects."""45 s = StringIO.StringIO()46 s.write('foobarbogus')47 assert super_len(s) == 04849 @pytest.mark.parametrize('error', [IOError, OSError])50 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):51 """If tell() raises errors, assume the cursor is at position zero."""52 class BoomFile(object):53 def __len__(self):54 return 55556 def tell(self):57 raise error()5859 assert super_len(BoomFile()) == 06061 @pytest.mark.parametrize('error', [IOError, OSError])62 def test_super_len_tell_ioerror(self, error):63 """Ensure that if tell gives an IOError super_len doesn't fail"""64 class NoLenBoomFile(object):65 def tell(self):66 raise error()6768 def seek(self, offset, whence):69 pass7071 assert super_len(NoLenBoomFile()) == 07273 def test_string(self):74 assert super_len('Test') == 47576 @pytest.mark.parametrize(77 'mode, warnings_num', (78 ('r', 1),79 ('rb', 0),80 ))81 def test_file(self, tmpdir, mode, warnings_num, recwarn):82 file_obj = tmpdir.join('test.txt')83 file_obj.write('Test')84 with file_obj.open(mode) as fd:85 assert super_len(fd) == 486 assert len(recwarn) == warnings_num8788 def test_super_len_with__len__(self):89 foo = [1,2,3,4]90 len_foo = super_len(foo)91 assert len_foo == 49293 def test_super_len_with_no__len__(self):94 class LenFile(object):95 def __init__(self):96 self.len = 59798 assert super_len(LenFile()) == 599100 def test_super_len_with_tell(self):101 foo = StringIO.StringIO('12345')102 assert super_len(foo) == 5103 foo.read(2)104 assert super_len(foo) == 3105106 def test_super_len_with_fileno(self):107 with open(__file__, 'rb') as f:108 length = super_len(f)109 file_data = f.read()110 assert length == len(file_data)111112 def test_super_len_with_no_matches(self):113 """Ensure that objects without any length methods default to 0"""114 assert super_len(object()) == 0115116117class TestToKeyValList:118119 @pytest.mark.parametrize(120 'value, expected', (121 ([('key', 'val')], [('key', 'val')]),122 ((('key', 'val'), ), [('key', 'val')]),123 ({'key': 'val'}, [('key', 'val')]),124 (None, None)125 ))126 def test_valid(self, value, expected):127 assert to_key_val_list(value) == expected128129 def test_invalid(self):130 with pytest.raises(ValueError):131 to_key_val_list('string')132133134class TestUnquoteHeaderValue:135136 @pytest.mark.parametrize(137 'value, expected', (138 (None, None),139 ('Test', 'Test'),140 ('"Test"', 'Test'),141 ('"Test\\\\"', 'Test\\'),142 ('"\\\\Comp\\Res"', '\\Comp\\Res'),143 ))144 def test_valid(self, value, expected):145 assert unquote_header_value(value) == expected146147 def test_is_filename(self):148 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'149150151class TestGetEnvironProxies:152 """Ensures that IP addresses are correctly matches with ranges153 in no_proxy variable.154 """155156 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])157 def no_proxy(self, request, monkeypatch):158 monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')159160 @pytest.mark.parametrize(161 'url', (162 'http://192.168.0.1:5000/',163 'http://192.168.0.1/',164 'http://172.16.1.1/',165 'http://172.16.1.1:5000/',166 'http://localhost.localdomain:5000/v1.0/',167 ))168 def test_bypass(self, url):169 assert get_environ_proxies(url, no_proxy=None) == {}170171 @pytest.mark.parametrize(172 'url', (173 'http://192.168.1.1:5000/',174 'http://192.168.1.1/',175 'http://www.requests.com/',176 ))177 def test_not_bypass(self, url):178 assert get_environ_proxies(url, no_proxy=None) != {}179180 @pytest.mark.parametrize(181 'url', (182 'http://192.168.1.1:5000/',183 'http://192.168.1.1/',184 'http://www.requests.com/',185 ))186 def test_bypass_no_proxy_keyword(self, url):187 no_proxy = '192.168.1.1,requests.com'188 assert get_environ_proxies(url, no_proxy=no_proxy) == {}189190 @pytest.mark.parametrize(191 'url', (192 'http://192.168.0.1:5000/',193 'http://192.168.0.1/',194 'http://172.16.1.1/',195 'http://172.16.1.1:5000/',196 'http://localhost.localdomain:5000/v1.0/',197 ))198 def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):199 # This is testing that the 'no_proxy' argument overrides the200 # environment variable 'no_proxy'201 monkeypatch.setenv('http_proxy', 'http://proxy.example.com:3128/')202 no_proxy = '192.168.1.1,requests.com'203 assert get_environ_proxies(url, no_proxy=no_proxy) != {}204205206class TestIsIPv4Address:207208 def test_valid(self):209 assert is_ipv4_address('8.8.8.8')210211 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))212 def test_invalid(self, value):213 assert not is_ipv4_address(value)214215216class TestIsValidCIDR:217218 def test_valid(self):219 assert is_valid_cidr('192.168.1.0/24')220221 @pytest.mark.parametrize(222 'value', (223 '8.8.8.8',224 '192.168.1.0/a',225 '192.168.1.0/128',226 '192.168.1.0/-1',227 '192.168.1.999/24',228 ))229 def test_invalid(self, value):230 assert not is_valid_cidr(value)231232233class TestAddressInNetwork:234235 def test_valid(self):236 assert address_in_network('192.168.1.1', '192.168.1.0/24')237238 def test_invalid(self):239 assert not address_in_network('172.16.0.1', '192.168.1.0/24')240241242class TestGuessFilename:243244 @pytest.mark.parametrize(245 'value', (1, type('Fake', (object,), {'name': 1})()),246 )247 def test_guess_filename_invalid(self, value):248 assert guess_filename(value) is None249250 @pytest.mark.parametrize(251 'value, expected_type', (252 (b'value', compat.bytes),253 (b'value'.decode('utf-8'), compat.str)254 ))255 def test_guess_filename_valid(self, value, expected_type):256 obj = type('Fake', (object,), {'name': value})()257 result = guess_filename(obj)258 assert result == value259 assert isinstance(result, expected_type)260261262class TestExtractZippedPaths:263264 @pytest.mark.parametrize(265 'path', (266 '/',267 __file__,268 pytest.__file__,269 '/etc/invalid/location',270 ))271 def test_unzipped_paths_unchanged(self, path):272 assert path == extract_zipped_paths(path)273274 def test_zipped_paths_extracted(self, tmpdir):275 zipped_py = tmpdir.join('test.zip')276 with zipfile.ZipFile(zipped_py.strpath, 'w') as f:277 f.write(__file__)278279 _, name = os.path.splitdrive(__file__)280 zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r'\/'))281 extracted_path = extract_zipped_paths(zipped_path)282283 assert extracted_path != zipped_path284 assert os.path.exists(extracted_path)285 assert filecmp.cmp(extracted_path, __file__)286287288class TestContentEncodingDetection:289290 def test_none(self):291 encodings = get_encodings_from_content('')292 assert not len(encodings)293294 @pytest.mark.parametrize(295 'content', (296 # HTML5 meta charset attribute297 '<meta charset="UTF-8">',298 # HTML4 pragma directive299 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',300 # XHTML 1.x served with text/html MIME type301 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',302 # XHTML 1.x served as XML303 '<?xml version="1.0" encoding="UTF-8"?>',304 ))305 def test_pragmas(self, content):306 encodings = get_encodings_from_content(content)307 assert len(encodings) == 1308 assert encodings[0] == 'UTF-8'309310 def test_precedence(self):311 content = '''312 <?xml version="1.0" encoding="XML"?>313 <meta charset="HTML5">314 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />315 '''.strip()316 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']317318319class TestGuessJSONUTF:320321 @pytest.mark.parametrize(322 'encoding', (323 'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',324 'utf-32-be', 'utf-32-le'325 ))326 def test_encoded(self, encoding):327 data = '{}'.encode(encoding)328 assert guess_json_utf(data) == encoding329330 def test_bad_utf_like_encoding(self):331 assert guess_json_utf(b'\x00\x00\x00\x00') is None332333 @pytest.mark.parametrize(334 ('encoding', 'expected'), (335 ('utf-16-be', 'utf-16'),336 ('utf-16-le', 'utf-16'),337 ('utf-32-be', 'utf-32'),338 ('utf-32-le', 'utf-32')339 ))340 def test_guess_by_bom(self, encoding, expected):341 data = u'\ufeff{}'.encode(encoding)342 assert guess_json_utf(data) == expected343344345USER = PASSWORD = "%!*'();:@&=+$,/?#[] "346ENCODED_USER = compat.quote(USER, '')347ENCODED_PASSWORD = compat.quote(PASSWORD, '')348349350@pytest.mark.parametrize(351 'url, auth', (352 (353 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +354 'request.com/url.html#test',355 (USER, PASSWORD)356 ),357 (358 'http://user:pass@complex.url.com/path?query=yes',359 ('user', 'pass')360 ),361 (362 'http://user:pass%20pass@complex.url.com/path?query=yes',363 ('user', 'pass pass')364 ),365 (366 'http://user:pass pass@complex.url.com/path?query=yes',367 ('user', 'pass pass')368 ),369 (370 'http://user%25user:pass@complex.url.com/path?query=yes',371 ('user%user', 'pass')372 ),373 (374 'http://user:pass%23pass@complex.url.com/path?query=yes',375 ('user', 'pass#pass')376 ),377 (378 'http://complex.url.com/path?query=yes',379 ('', '')380 ),381 ))382def test_get_auth_from_url(url, auth):383 assert get_auth_from_url(url) == auth384385386@pytest.mark.parametrize(387 'uri, expected', (388 (389 # Ensure requoting doesn't break expectations390 'http://example.com/fiz?buz=%25ppicture',391 'http://example.com/fiz?buz=%25ppicture',392 ),393 (394 # Ensure we handle unquoted percent signs in redirects395 'http://example.com/fiz?buz=%ppicture',396 'http://example.com/fiz?buz=%25ppicture',397 ),398 ))399def test_requote_uri_with_unquoted_percents(uri, expected):400 """See: https://github.com/requests/requests/issues/2356"""401 assert requote_uri(uri) == expected402403404@pytest.mark.parametrize(405 'uri, expected', (406 (407 # Illegal bytes408 'http://example.com/?a=%--',409 'http://example.com/?a=%--',410 ),411 (412 # Reserved characters413 'http://example.com/?a=%300',414 'http://example.com/?a=00',415 )416 ))417def test_unquote_unreserved(uri, expected):418 assert unquote_unreserved(uri) == expected419420421@pytest.mark.parametrize(422 'mask, expected', (423 (8, '255.0.0.0'),424 (24, '255.255.255.0'),425 (25, '255.255.255.128'),426 ))427def test_dotted_netmask(mask, expected):428 assert dotted_netmask(mask) == expected429430431http_proxies = {'http': 'http://http.proxy',432 'http://some.host': 'http://some.host.proxy'}433all_proxies = {'all': 'socks5://http.proxy',434 'all://some.host': 'socks5://some.host.proxy'}435mixed_proxies = {'http': 'http://http.proxy',436 'http://some.host': 'http://some.host.proxy',437 'all': 'socks5://http.proxy'}438@pytest.mark.parametrize(439 'url, expected, proxies', (440 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),441 ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),442 ('hTTp:///path', 'http://http.proxy', http_proxies),443 ('hTTps://Other.Host', None, http_proxies),444 ('file:///etc/motd', None, http_proxies),445446 ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),447 ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),448 ('hTTp:///path', 'socks5://http.proxy', all_proxies),449 ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),450451 ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),452 ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),453 ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),454 ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),455 ('https://', 'socks5://http.proxy', mixed_proxies),456 # XXX: unsure whether this is reasonable behavior457 ('file:///etc/motd', 'socks5://http.proxy', all_proxies),458 ))459def test_select_proxies(url, expected, proxies):460 """Make sure we can select per-host proxies correctly."""461 assert select_proxy(url, proxies) == expected462463464@pytest.mark.parametrize(465 'value, expected', (466 ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),467 ('key_without_value', {'key_without_value': None})468 ))469def test_parse_dict_header(value, expected):470 assert parse_dict_header(value) == expected471472473@pytest.mark.parametrize(474 'value, expected', (475 (476 'application/xml',477 ('application/xml', {})478 ),479 (480 'application/json ; charset=utf-8',481 ('application/json', {'charset': 'utf-8'})482 ),483 (484 'text/plain',485 ('text/plain', {})486 ),487 (488 'multipart/form-data; boundary = something ; boundary2=\'something_else\' ; no_equals ',489 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})490 ),491 (492 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',493 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})494 ),495 (496 'multipart/form-data; boundary = something ; \'boundary2=something_else\' ; no_equals ',497 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})498 ),499 (500 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',501 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})502 ),503 (504 'application/json ; ; ',505 ('application/json', {})506 )507 ))508def test__parse_content_type_header(value, expected):509 assert _parse_content_type_header(value) == expected510511512@pytest.mark.parametrize(513 'value, expected', (514 (515 CaseInsensitiveDict(),516 None517 ),518 (519 CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),520 'utf-8'521 ),522 (523 CaseInsensitiveDict({'content-type': 'text/plain'}),524 'ISO-8859-1'525 ),526 ))527def test_get_encoding_from_headers(value, expected):528 assert get_encoding_from_headers(value) == expected529530531@pytest.mark.parametrize(532 'value, length', (533 ('', 0),534 ('T', 1),535 ('Test', 4),536 ('Cont', 0),537 ('Other', -5),538 ('Content', None),539 ))540def test_iter_slices(value, length):541 if length is None or (length <= 0 and len(value) > 0):542 # Reads all content at once543 assert len(list(iter_slices(value, length))) == 1544 else:545 assert len(list(iter_slices(value, 1))) == length546547548@pytest.mark.parametrize(549 'value, expected', (550 (551 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',552 [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]553 ),554 (555 '<http:/.../front.jpeg>',556 [{'url': 'http:/.../front.jpeg'}]557 ),558 (559 '<http:/.../front.jpeg>;',560 [{'url': 'http:/.../front.jpeg'}]561 ),562 (563 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',564 [565 {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},566 {'url': 'http://.../back.jpeg'}567 ]568 ),569 (570 '',571 []572 ),573 ))574def test_parse_header_links(value, expected):575 assert parse_header_links(value) == expected576577578@pytest.mark.parametrize(579 'value, expected', (580 ('example.com/path', 'http://example.com/path'),581 ('//example.com/path', 'http://example.com/path'),582 ))583def test_prepend_scheme_if_needed(value, expected):584 assert prepend_scheme_if_needed(value, 'http') == expected585586587@pytest.mark.parametrize(588 'value, expected', (589 ('T', 'T'),590 (b'T', 'T'),591 (u'T', 'T'),592 ))593def test_to_native_string(value, expected):594 assert to_native_string(value) == expected595596597@pytest.mark.parametrize(598 'url, expected', (599 ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),600 ('http://example.com/path', 'http://example.com/path'),601 ('//u:p@example.com/path', '//example.com/path'),602 ('//example.com/path', '//example.com/path'),603 ('example.com/path', '//example.com/path'),604 ('scheme:u:p@example.com/path', 'scheme://example.com/path'),605 ))606def test_urldefragauth(url, expected):607 assert urldefragauth(url) == expected608609610@pytest.mark.parametrize(611 'url, expected', (612 ('http://192.168.0.1:5000/', True),613 ('http://192.168.0.1/', True),614 ('http://172.16.1.1/', True),615 ('http://172.16.1.1:5000/', True),616 ('http://localhost.localdomain:5000/v1.0/', True),617 ('http://google.com:6000/', True),618 ('http://172.16.1.12/', False),619 ('http://172.16.1.12:5000/', False),620 ('http://google.com:5000/v1.0/', False),621 ))622def test_should_bypass_proxies(url, expected, monkeypatch):623 """Tests for function should_bypass_proxies to check if proxy624 can be bypassed or not625 """626 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')627 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')628 assert should_bypass_proxies(url, no_proxy=None) == expected629630631@pytest.mark.parametrize(632 'url, expected', (633 ('http://172.16.1.1/', '172.16.1.1'),634 ('http://172.16.1.1:5000/', '172.16.1.1'),635 ('http://user:pass@172.16.1.1', '172.16.1.1'),636 ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),637 ('http://hostname/', 'hostname'),638 ('http://hostname:5000/', 'hostname'),639 ('http://user:pass@hostname', 'hostname'),640 ('http://user:pass@hostname:5000', 'hostname'),641 ))642def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):643 """The proxy_bypass function should be called with a hostname or IP without644 a port number or auth credentials.645 """646 proxy_bypass = mocker.patch('requests.utils.proxy_bypass')647 should_bypass_proxies(url, no_proxy=None)648 proxy_bypass.assert_called_once_with(expected)649650651@pytest.mark.parametrize(652 'cookiejar', (653 compat.cookielib.CookieJar(),654 RequestsCookieJar()655 ))656def test_add_dict_to_cookiejar(cookiejar):657 """Ensure add_dict_to_cookiejar works for658 non-RequestsCookieJar CookieJars659 """660 cookiedict = {'test': 'cookies',661 'good': 'cookies'}662 cj = add_dict_to_cookiejar(cookiejar, cookiedict)663 cookies = dict((cookie.name, cookie.value) for cookie in cj)664 assert cookiedict == cookies665666667@pytest.mark.parametrize(668 'value, expected', (669 (u'test', True),670 (u'æíöû', False),671 (u'ジェーピーニック', False),672 )673)674def test_unicode_is_ascii(value, expected):675 assert unicode_is_ascii(value) is expected676677678@pytest.mark.parametrize(679 'url, expected', (680 ('http://192.168.0.1:5000/', True),681 ('http://192.168.0.1/', True),682 ('http://172.16.1.1/', True),683 ('http://172.16.1.1:5000/', True),684 ('http://localhost.localdomain:5000/v1.0/', True),685 ('http://172.16.1.12/', False),686 ('http://172.16.1.12:5000/', False),687 ('http://google.com:5000/v1.0/', False),688 ))689def test_should_bypass_proxies_no_proxy(690 url, expected, monkeypatch):691 """Tests for function should_bypass_proxies to check if proxy692 can be bypassed or not using the 'no_proxy' argument693 """694 no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'695 # Test 'no_proxy' argument696 assert should_bypass_proxies(url, no_proxy=no_proxy) == expected697698699@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')700@pytest.mark.parametrize(701 'url, expected, override', (702 ('http://192.168.0.1:5000/', True, None),703 ('http://192.168.0.1/', True, None),704 ('http://172.16.1.1/', True, None),705 ('http://172.16.1.1:5000/', True, None),706 ('http://localhost.localdomain:5000/v1.0/', True, None),707 ('http://172.16.1.22/', False, None),708 ('http://172.16.1.22:5000/', False, None),709 ('http://google.com:5000/v1.0/', False, None),710 ('http://mylocalhostname:5000/v1.0/', True, '<local>'),711 ('http://192.168.0.1/', False, ''),712 ))713def test_should_bypass_proxies_win_registry(url, expected, override,714 monkeypatch):715 """Tests for function should_bypass_proxies to check if proxy716 can be bypassed or not with Windows registry settings717 """718 if override is None:719 override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'720 if compat.is_py3:721 import winreg722 else:723 import _winreg as winreg724725 class RegHandle:726 def Close(self):727 pass728729 ie_settings = RegHandle()730 proxyEnableValues = deque([1, "1"])731732 def OpenKey(key, subkey):733 return ie_settings734735 def QueryValueEx(key, value_name):736 if key is ie_settings:737 if value_name == 'ProxyEnable':738 # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)739 proxyEnableValues.rotate()740 return [proxyEnableValues[0]]741 elif value_name == 'ProxyOverride':742 return [override]743744 monkeypatch.setenv('http_proxy', '')745 monkeypatch.setenv('https_proxy', '')746 monkeypatch.setenv('ftp_proxy', '')747 monkeypatch.setenv('no_proxy', '')748 monkeypatch.setenv('NO_PROXY', '')749 monkeypatch.setattr(winreg, 'OpenKey', OpenKey)750 monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)751 assert should_bypass_proxies(url, None) == expected752753754@pytest.mark.parametrize(755 'env_name, value', (756 ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),757 ('no_proxy', None),758 ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),759 ('a_new_key', None),760 ))761def test_set_environ(env_name, value):762 """Tests set_environ will set environ values and will restore the environ."""763 environ_copy = copy.deepcopy(os.environ)764 with set_environ(env_name, value):765 assert os.environ.get(env_name) == value766767 assert os.environ == environ_copy768769770def test_set_environ_raises_exception():771 """Tests set_environ will raise exceptions in context when the772 value parameter is None."""773 with pytest.raises(Exception) as exception:774 with set_environ('test1', None):775 raise Exception('Expected exception')776777 assert 'Expected exception' in str(exception.value)