Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

801 lines · 26.0 KiB · Python

Last changed by

Merge pull request #5917 from nateprewitt/proxy_scheme_unknown_fixIan Stapleton Cordascobefore adoption28d537d

History of this file

Take it

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

Update index.rstKenneth Reitzbefore adoption3d968ff

lines 1–6why, one step back
1# -*- coding: utf-8 -*-
23import os4import copy5import filecmp6from io import BytesIO

Catch AttributeError in utils.super_len (#5239)David Hothambefore adoption2d2447e

line 7why, one step back
7import tarfile

Update index.rstKenneth Reitzbefore adoption3d968ff

lines 8–88why, one step back
8import zipfile
9from collections import deque1011import pytest12from requests import compat13from requests.cookies import RequestsCookieJar14from requests.structures import CaseInsensitiveDict15from requests.utils import (16 address_in_network, dotted_netmask, extract_zipped_paths,17 get_auth_from_url, _parse_content_type_header, get_encoding_from_headers,18 get_encodings_from_content, get_environ_proxies,19 guess_filename, guess_json_utf, is_ipv4_address,20 is_valid_cidr, iter_slices, parse_dict_header,21 parse_header_links, prepend_scheme_if_needed,22 requote_uri, select_proxy, should_bypass_proxies, super_len,23 to_key_val_list, to_native_string,24 unquote_header_value, unquote_unreserved,25 urldefragauth, add_dict_to_cookiejar, set_environ)26from requests._internal_utils import unicode_is_ascii2728from .compat import StringIO, cStringIO293031class TestSuperLen:3233 @pytest.mark.parametrize(34 'stream, value', (35 (StringIO.StringIO, 'Test'),36 (BytesIO, b'Test'),37 pytest.param(cStringIO, 'Test',38 marks=pytest.mark.skipif('cStringIO is None')),39 ))40 def test_io_streams(self, stream, value):41 """Ensures that we properly deal with different kinds of IO streams."""42 assert super_len(stream()) == 043 assert super_len(stream(value)) == 44445 def test_super_len_correctly_calculates_len_of_partially_read_file(self):46 """Ensure that we handle partially consumed file like objects."""47 s = StringIO.StringIO()48 s.write('foobarbogus')49 assert super_len(s) == 05051 @pytest.mark.parametrize('error', [IOError, OSError])52 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):53 """If tell() raises errors, assume the cursor is at position zero."""54 class BoomFile(object):55 def __len__(self):56 return 55758 def tell(self):59 raise error()6061 assert super_len(BoomFile()) == 06263 @pytest.mark.parametrize('error', [IOError, OSError])64 def test_super_len_tell_ioerror(self, error):65 """Ensure that if tell gives an IOError super_len doesn't fail"""66 class NoLenBoomFile(object):67 def tell(self):68 raise error()6970 def seek(self, offset, whence):71 pass7273 assert super_len(NoLenBoomFile()) == 07475 def test_string(self):76 assert super_len('Test') == 47778 @pytest.mark.parametrize(79 'mode, warnings_num', (80 ('r', 1),81 ('rb', 0),82 ))83 def test_file(self, tmpdir, mode, warnings_num, recwarn):84 file_obj = tmpdir.join('test.txt')85 file_obj.write('Test')86 with file_obj.open(mode) as fd:87 assert super_len(fd) == 488 assert len(recwarn) == warnings_num

Catch AttributeError in utils.super_len (#5239)David Hothambefore adoption2d2447e

lines 89–100why, one step back
89
90 def test_tarfile_member(self, tmpdir):91 file_obj = tmpdir.join('test.txt')92 file_obj.write('Test')9394 tar_obj = str(tmpdir.join('test.tar'))95 with tarfile.open(tar_obj, 'w') as tar:96 tar.add(str(file_obj), arcname='test.txt')9798 with tarfile.open(tar_obj) as tar:99 member = tar.extractfile('test.txt')100 assert super_len(member) == 4

Update index.rstKenneth Reitzbefore adoption3d968ff

lines 101–300why, one step back
101
102 def test_super_len_with__len__(self):103 foo = [1,2,3,4]104 len_foo = super_len(foo)105 assert len_foo == 4106107 def test_super_len_with_no__len__(self):108 class LenFile(object):109 def __init__(self):110 self.len = 5111112 assert super_len(LenFile()) == 5113114 def test_super_len_with_tell(self):115 foo = StringIO.StringIO('12345')116 assert super_len(foo) == 5117 foo.read(2)118 assert super_len(foo) == 3119120 def test_super_len_with_fileno(self):121 with open(__file__, 'rb') as f:122 length = super_len(f)123 file_data = f.read()124 assert length == len(file_data)125126 def test_super_len_with_no_matches(self):127 """Ensure that objects without any length methods default to 0"""128 assert super_len(object()) == 0129130131class TestToKeyValList:132133 @pytest.mark.parametrize(134 'value, expected', (135 ([('key', 'val')], [('key', 'val')]),136 ((('key', 'val'), ), [('key', 'val')]),137 ({'key': 'val'}, [('key', 'val')]),138 (None, None)139 ))140 def test_valid(self, value, expected):141 assert to_key_val_list(value) == expected142143 def test_invalid(self):144 with pytest.raises(ValueError):145 to_key_val_list('string')146147148class TestUnquoteHeaderValue:149150 @pytest.mark.parametrize(151 'value, expected', (152 (None, None),153 ('Test', 'Test'),154 ('"Test"', 'Test'),155 ('"Test\\\\"', 'Test\\'),156 ('"\\\\Comp\\Res"', '\\Comp\\Res'),157 ))158 def test_valid(self, value, expected):159 assert unquote_header_value(value) == expected160161 def test_is_filename(self):162 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'163164165class TestGetEnvironProxies:166 """Ensures that IP addresses are correctly matches with ranges167 in no_proxy variable.168 """169170 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])171 def no_proxy(self, request, monkeypatch):172 monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')173174 @pytest.mark.parametrize(175 'url', (176 'http://192.168.0.1:5000/',177 'http://192.168.0.1/',178 'http://172.16.1.1/',179 'http://172.16.1.1:5000/',180 'http://localhost.localdomain:5000/v1.0/',181 ))182 def test_bypass(self, url):183 assert get_environ_proxies(url, no_proxy=None) == {}184185 @pytest.mark.parametrize(186 'url', (187 'http://192.168.1.1:5000/',188 'http://192.168.1.1/',189 'http://www.requests.com/',190 ))191 def test_not_bypass(self, url):192 assert get_environ_proxies(url, no_proxy=None) != {}193194 @pytest.mark.parametrize(195 'url', (196 'http://192.168.1.1:5000/',197 'http://192.168.1.1/',198 'http://www.requests.com/',199 ))200 def test_bypass_no_proxy_keyword(self, url):201 no_proxy = '192.168.1.1,requests.com'202 assert get_environ_proxies(url, no_proxy=no_proxy) == {}203204 @pytest.mark.parametrize(205 'url', (206 'http://192.168.0.1:5000/',207 'http://192.168.0.1/',208 'http://172.16.1.1/',209 'http://172.16.1.1:5000/',210 'http://localhost.localdomain:5000/v1.0/',211 ))212 def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):213 # This is testing that the 'no_proxy' argument overrides the214 # environment variable 'no_proxy'215 monkeypatch.setenv('http_proxy', 'http://proxy.example.com:3128/')216 no_proxy = '192.168.1.1,requests.com'217 assert get_environ_proxies(url, no_proxy=no_proxy) != {}218219220class TestIsIPv4Address:221222 def test_valid(self):223 assert is_ipv4_address('8.8.8.8')224225 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))226 def test_invalid(self, value):227 assert not is_ipv4_address(value)228229230class TestIsValidCIDR:231232 def test_valid(self):233 assert is_valid_cidr('192.168.1.0/24')234235 @pytest.mark.parametrize(236 'value', (237 '8.8.8.8',238 '192.168.1.0/a',239 '192.168.1.0/128',240 '192.168.1.0/-1',241 '192.168.1.999/24',242 ))243 def test_invalid(self, value):244 assert not is_valid_cidr(value)245246247class TestAddressInNetwork:248249 def test_valid(self):250 assert address_in_network('192.168.1.1', '192.168.1.0/24')251252 def test_invalid(self):253 assert not address_in_network('172.16.0.1', '192.168.1.0/24')254255256class TestGuessFilename:257258 @pytest.mark.parametrize(259 'value', (1, type('Fake', (object,), {'name': 1})()),260 )261 def test_guess_filename_invalid(self, value):262 assert guess_filename(value) is None263264 @pytest.mark.parametrize(265 'value, expected_type', (266 (b'value', compat.bytes),267 (b'value'.decode('utf-8'), compat.str)268 ))269 def test_guess_filename_valid(self, value, expected_type):270 obj = type('Fake', (object,), {'name': value})()271 result = guess_filename(obj)272 assert result == value273 assert isinstance(result, expected_type)274275276class TestExtractZippedPaths:277278 @pytest.mark.parametrize(279 'path', (280 '/',281 __file__,282 pytest.__file__,283 '/etc/invalid/location',284 ))285 def test_unzipped_paths_unchanged(self, path):286 assert path == extract_zipped_paths(path)287288 def test_zipped_paths_extracted(self, tmpdir):289 zipped_py = tmpdir.join('test.zip')290 with zipfile.ZipFile(zipped_py.strpath, 'w') as f:291 f.write(__file__)292293 _, name = os.path.splitdrive(__file__)294 zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r'\/'))295 extracted_path = extract_zipped_paths(zipped_path)296297 assert extracted_path != zipped_path298 assert os.path.exists(extracted_path)299 assert filecmp.cmp(extracted_path, __file__)300

Fix extract_zipped_paths infinite loop when provided invalid unc path (#5851)Thomas Lambefore adoptiond8829f9

lines 301–304why, one step back
301 def test_invalid_unc_path(self):
302 path = r"\\localhost\invalid\location"303 assert extract_zipped_paths(path) == path304

Update index.rstKenneth Reitzbefore adoption3d968ff

lines 305–603why, one step back
305
306class TestContentEncodingDetection:307308 def test_none(self):309 encodings = get_encodings_from_content('')310 assert not len(encodings)311312 @pytest.mark.parametrize(313 'content', (314 # HTML5 meta charset attribute315 '<meta charset="UTF-8">',316 # HTML4 pragma directive317 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',318 # XHTML 1.x served with text/html MIME type319 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',320 # XHTML 1.x served as XML321 '<?xml version="1.0" encoding="UTF-8"?>',322 ))323 def test_pragmas(self, content):324 encodings = get_encodings_from_content(content)325 assert len(encodings) == 1326 assert encodings[0] == 'UTF-8'327328 def test_precedence(self):329 content = '''330 <?xml version="1.0" encoding="XML"?>331 <meta charset="HTML5">332 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />333 '''.strip()334 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']335336337class TestGuessJSONUTF:338339 @pytest.mark.parametrize(340 'encoding', (341 'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',342 'utf-32-be', 'utf-32-le'343 ))344 def test_encoded(self, encoding):345 data = '{}'.encode(encoding)346 assert guess_json_utf(data) == encoding347348 def test_bad_utf_like_encoding(self):349 assert guess_json_utf(b'\x00\x00\x00\x00') is None350351 @pytest.mark.parametrize(352 ('encoding', 'expected'), (353 ('utf-16-be', 'utf-16'),354 ('utf-16-le', 'utf-16'),355 ('utf-32-be', 'utf-32'),356 ('utf-32-le', 'utf-32')357 ))358 def test_guess_by_bom(self, encoding, expected):359 data = u'\ufeff{}'.encode(encoding)360 assert guess_json_utf(data) == expected361362363USER = PASSWORD = "%!*'();:@&=+$,/?#[] "364ENCODED_USER = compat.quote(USER, '')365ENCODED_PASSWORD = compat.quote(PASSWORD, '')366367368@pytest.mark.parametrize(369 'url, auth', (370 (371 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +372 'request.com/url.html#test',373 (USER, PASSWORD)374 ),375 (376 'http://user:pass@complex.url.com/path?query=yes',377 ('user', 'pass')378 ),379 (380 'http://user:pass%20pass@complex.url.com/path?query=yes',381 ('user', 'pass pass')382 ),383 (384 'http://user:pass pass@complex.url.com/path?query=yes',385 ('user', 'pass pass')386 ),387 (388 'http://user%25user:pass@complex.url.com/path?query=yes',389 ('user%user', 'pass')390 ),391 (392 'http://user:pass%23pass@complex.url.com/path?query=yes',393 ('user', 'pass#pass')394 ),395 (396 'http://complex.url.com/path?query=yes',397 ('', '')398 ),399 ))400def test_get_auth_from_url(url, auth):401 assert get_auth_from_url(url) == auth402403404@pytest.mark.parametrize(405 'uri, expected', (406 (407 # Ensure requoting doesn't break expectations408 'http://example.com/fiz?buz=%25ppicture',409 'http://example.com/fiz?buz=%25ppicture',410 ),411 (412 # Ensure we handle unquoted percent signs in redirects413 'http://example.com/fiz?buz=%ppicture',414 'http://example.com/fiz?buz=%25ppicture',415 ),416 ))417def test_requote_uri_with_unquoted_percents(uri, expected):418 """See: https://github.com/psf/requests/issues/2356"""419 assert requote_uri(uri) == expected420421422@pytest.mark.parametrize(423 'uri, expected', (424 (425 # Illegal bytes426 'http://example.com/?a=%--',427 'http://example.com/?a=%--',428 ),429 (430 # Reserved characters431 'http://example.com/?a=%300',432 'http://example.com/?a=00',433 )434 ))435def test_unquote_unreserved(uri, expected):436 assert unquote_unreserved(uri) == expected437438439@pytest.mark.parametrize(440 'mask, expected', (441 (8, '255.0.0.0'),442 (24, '255.255.255.0'),443 (25, '255.255.255.128'),444 ))445def test_dotted_netmask(mask, expected):446 assert dotted_netmask(mask) == expected447448449http_proxies = {'http': 'http://http.proxy',450 'http://some.host': 'http://some.host.proxy'}451all_proxies = {'all': 'socks5://http.proxy',452 'all://some.host': 'socks5://some.host.proxy'}453mixed_proxies = {'http': 'http://http.proxy',454 'http://some.host': 'http://some.host.proxy',455 'all': 'socks5://http.proxy'}456@pytest.mark.parametrize(457 'url, expected, proxies', (458 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),459 ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),460 ('hTTp:///path', 'http://http.proxy', http_proxies),461 ('hTTps://Other.Host', None, http_proxies),462 ('file:///etc/motd', None, http_proxies),463464 ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),465 ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),466 ('hTTp:///path', 'socks5://http.proxy', all_proxies),467 ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),468469 ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),470 ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),471 ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),472 ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),473 ('https://', 'socks5://http.proxy', mixed_proxies),474 # XXX: unsure whether this is reasonable behavior475 ('file:///etc/motd', 'socks5://http.proxy', all_proxies),476 ))477def test_select_proxies(url, expected, proxies):478 """Make sure we can select per-host proxies correctly."""479 assert select_proxy(url, proxies) == expected480481482@pytest.mark.parametrize(483 'value, expected', (484 ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),485 ('key_without_value', {'key_without_value': None})486 ))487def test_parse_dict_header(value, expected):488 assert parse_dict_header(value) == expected489490491@pytest.mark.parametrize(492 'value, expected', (493 (494 'application/xml',495 ('application/xml', {})496 ),497 (498 'application/json ; charset=utf-8',499 ('application/json', {'charset': 'utf-8'})500 ),501 (502 'application/json ; Charset=utf-8',503 ('application/json', {'charset': 'utf-8'})504 ),505 (506 'text/plain',507 ('text/plain', {})508 ),509 (510 'multipart/form-data; boundary = something ; boundary2=\'something_else\' ; no_equals ',511 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})512 ),513 (514 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',515 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})516 ),517 (518 'multipart/form-data; boundary = something ; \'boundary2=something_else\' ; no_equals ',519 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})520 ),521 (522 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',523 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})524 ),525 (526 'application/json ; ; ',527 ('application/json', {})528 )529 ))530def test__parse_content_type_header(value, expected):531 assert _parse_content_type_header(value) == expected532533534@pytest.mark.parametrize(535 'value, expected', (536 (537 CaseInsensitiveDict(),538 None539 ),540 (541 CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),542 'utf-8'543 ),544 (545 CaseInsensitiveDict({'content-type': 'text/plain'}),546 'ISO-8859-1'547 ),548 ))549def test_get_encoding_from_headers(value, expected):550 assert get_encoding_from_headers(value) == expected551552553@pytest.mark.parametrize(554 'value, length', (555 ('', 0),556 ('T', 1),557 ('Test', 4),558 ('Cont', 0),559 ('Other', -5),560 ('Content', None),561 ))562def test_iter_slices(value, length):563 if length is None or (length <= 0 and len(value) > 0):564 # Reads all content at once565 assert len(list(iter_slices(value, length))) == 1566 else:567 assert len(list(iter_slices(value, 1))) == length568569570@pytest.mark.parametrize(571 'value, expected', (572 (573 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',574 [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]575 ),576 (577 '<http:/.../front.jpeg>',578 [{'url': 'http:/.../front.jpeg'}]579 ),580 (581 '<http:/.../front.jpeg>;',582 [{'url': 'http:/.../front.jpeg'}]583 ),584 (585 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',586 [587 {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},588 {'url': 'http://.../back.jpeg'}589 ]590 ),591 (592 '',593 []594 ),595 ))596def test_parse_header_links(value, expected):597 assert parse_header_links(value) == expected598599600@pytest.mark.parametrize(601 'value, expected', (602 ('example.com/path', 'http://example.com/path'),603 ('//example.com/path', 'http://example.com/path'),

Merge pull request #5917 from nateprewitt/proxy_scheme_unknown_fixIan Stapleton Cordascobefore adoption28d537d

line 604why, one step back
604 ('example.com:80', 'http://example.com:80'),

Update index.rstKenneth Reitzbefore adoption3d968ff

lines 605–801why, one step back
605 ))
606def test_prepend_scheme_if_needed(value, expected):607 assert prepend_scheme_if_needed(value, 'http') == expected608609610@pytest.mark.parametrize(611 'value, expected', (612 ('T', 'T'),613 (b'T', 'T'),614 (u'T', 'T'),615 ))616def test_to_native_string(value, expected):617 assert to_native_string(value) == expected618619620@pytest.mark.parametrize(621 'url, expected', (622 ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),623 ('http://example.com/path', 'http://example.com/path'),624 ('//u:p@example.com/path', '//example.com/path'),625 ('//example.com/path', '//example.com/path'),626 ('example.com/path', '//example.com/path'),627 ('scheme:u:p@example.com/path', 'scheme://example.com/path'),628 ))629def test_urldefragauth(url, expected):630 assert urldefragauth(url) == expected631632633@pytest.mark.parametrize(634 'url, expected', (635 ('http://192.168.0.1:5000/', True),636 ('http://192.168.0.1/', True),637 ('http://172.16.1.1/', True),638 ('http://172.16.1.1:5000/', True),639 ('http://localhost.localdomain:5000/v1.0/', True),640 ('http://google.com:6000/', True),641 ('http://172.16.1.12/', False),642 ('http://172.16.1.12:5000/', False),643 ('http://google.com:5000/v1.0/', False),644 ('file:///some/path/on/disk', True),645 ))646def test_should_bypass_proxies(url, expected, monkeypatch):647 """Tests for function should_bypass_proxies to check if proxy648 can be bypassed or not649 """650 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')651 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')652 assert should_bypass_proxies(url, no_proxy=None) == expected653654655@pytest.mark.parametrize(656 'url, expected', (657 ('http://172.16.1.1/', '172.16.1.1'),658 ('http://172.16.1.1:5000/', '172.16.1.1'),659 ('http://user:pass@172.16.1.1', '172.16.1.1'),660 ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),661 ('http://hostname/', 'hostname'),662 ('http://hostname:5000/', 'hostname'),663 ('http://user:pass@hostname', 'hostname'),664 ('http://user:pass@hostname:5000', 'hostname'),665 ))666def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):667 """The proxy_bypass function should be called with a hostname or IP without668 a port number or auth credentials.669 """670 proxy_bypass = mocker.patch('requests.utils.proxy_bypass')671 should_bypass_proxies(url, no_proxy=None)672 proxy_bypass.assert_called_once_with(expected)673674675@pytest.mark.parametrize(676 'cookiejar', (677 compat.cookielib.CookieJar(),678 RequestsCookieJar()679 ))680def test_add_dict_to_cookiejar(cookiejar):681 """Ensure add_dict_to_cookiejar works for682 non-RequestsCookieJar CookieJars683 """684 cookiedict = {'test': 'cookies',685 'good': 'cookies'}686 cj = add_dict_to_cookiejar(cookiejar, cookiedict)687 cookies = {cookie.name: cookie.value for cookie in cj}688 assert cookiedict == cookies689690691@pytest.mark.parametrize(692 'value, expected', (693 (u'test', True),694 (u'æíöû', False),695 (u'ジェーピーニック', False),696 )697)698def test_unicode_is_ascii(value, expected):699 assert unicode_is_ascii(value) is expected700701702@pytest.mark.parametrize(703 'url, expected', (704 ('http://192.168.0.1:5000/', True),705 ('http://192.168.0.1/', True),706 ('http://172.16.1.1/', True),707 ('http://172.16.1.1:5000/', True),708 ('http://localhost.localdomain:5000/v1.0/', True),709 ('http://172.16.1.12/', False),710 ('http://172.16.1.12:5000/', False),711 ('http://google.com:5000/v1.0/', False),712 ))713def test_should_bypass_proxies_no_proxy(714 url, expected, monkeypatch):715 """Tests for function should_bypass_proxies to check if proxy716 can be bypassed or not using the 'no_proxy' argument717 """718 no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'719 # Test 'no_proxy' argument720 assert should_bypass_proxies(url, no_proxy=no_proxy) == expected721722723@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')724@pytest.mark.parametrize(725 'url, expected, override', (726 ('http://192.168.0.1:5000/', True, None),727 ('http://192.168.0.1/', True, None),728 ('http://172.16.1.1/', True, None),729 ('http://172.16.1.1:5000/', True, None),730 ('http://localhost.localdomain:5000/v1.0/', True, None),731 ('http://172.16.1.22/', False, None),732 ('http://172.16.1.22:5000/', False, None),733 ('http://google.com:5000/v1.0/', False, None),734 ('http://mylocalhostname:5000/v1.0/', True, '<local>'),735 ('http://192.168.0.1/', False, ''),736 ))737def test_should_bypass_proxies_win_registry(url, expected, override,738 monkeypatch):739 """Tests for function should_bypass_proxies to check if proxy740 can be bypassed or not with Windows registry settings741 """742 if override is None:743 override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'744 if compat.is_py3:745 import winreg746 else:747 import _winreg as winreg748749 class RegHandle:750 def Close(self):751 pass752753 ie_settings = RegHandle()754 proxyEnableValues = deque([1, "1"])755756 def OpenKey(key, subkey):757 return ie_settings758759 def QueryValueEx(key, value_name):760 if key is ie_settings:761 if value_name == 'ProxyEnable':762 # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)763 proxyEnableValues.rotate()764 return [proxyEnableValues[0]]765 elif value_name == 'ProxyOverride':766 return [override]767768 monkeypatch.setenv('http_proxy', '')769 monkeypatch.setenv('https_proxy', '')770 monkeypatch.setenv('ftp_proxy', '')771 monkeypatch.setenv('no_proxy', '')772 monkeypatch.setenv('NO_PROXY', '')773 monkeypatch.setattr(winreg, 'OpenKey', OpenKey)774 monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)775 assert should_bypass_proxies(url, None) == expected776777778@pytest.mark.parametrize(779 'env_name, value', (780 ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),781 ('no_proxy', None),782 ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),783 ('a_new_key', None),784 ))785def test_set_environ(env_name, value):786 """Tests set_environ will set environ values and will restore the environ."""787 environ_copy = copy.deepcopy(os.environ)788 with set_environ(env_name, value):789 assert os.environ.get(env_name) == value790791 assert os.environ == environ_copy792793794def test_set_environ_raises_exception():795 """Tests set_environ will raise exceptions in context when the796 value parameter is None."""797 with pytest.raises(Exception) as exception:798 with set_environ('test1', None):799 raise Exception('Expected exception')800801 assert 'Expected exception' in str(exception.value)