test_utils.py
This file
Path
tests/test_utils.py
781 lines · 25.4 KiB · Python
Last changed by
Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d
History of this fileTake it
The walk stopped after 200 commits: lines older than 3ca2722 point at it.
improve development instructionsKenneth Reitzbefore adoption3ca2722
lines 1–3why, one step back1# -*- coding: utf-8 -*-23import osMerge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoptiona5b8f8d
line 4why, one step back4import copyMerge pull request #4371 from Twistbioscience/zipfile_compatCory Benfieldbefore adoption234f80a
line 5why, one step back5import filecmpimprove development instructionsKenneth Reitzbefore adoption3ca2722
line 6why, one step back6from io import BytesIOMerge pull request #4371 from Twistbioscience/zipfile_compatCory Benfieldbefore adoption234f80a
line 7why, one step back7import zipfile#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645
line 8why, one step back8from collections import dequeimprove development instructionsKenneth Reitzbefore adoption3ca2722
lines 9–14why, one step back910import pytest11from requests import compat12from requests.cookies import RequestsCookieJar13from requests.structures import CaseInsensitiveDict14from requests.utils import (Merge pull request #4371 from Twistbioscience/zipfile_compatCory Benfieldbefore adoption234f80a
line 15why, one step back15 address_in_network, dotted_netmask, extract_zipped_paths,Merge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption3c1d36b
line 16why, one step back16 get_auth_from_url, _parse_content_type_header, get_encoding_from_headers,improve development instructionsKenneth Reitzbefore adoption3ca2722
lines 17–23why, one step back17 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,Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoptiona5b8f8d
line 24why, one step back24 urldefragauth, add_dict_to_cookiejar, set_environ)improve development instructionsKenneth Reitzbefore adoption3ca2722
lines 25–259why, one step back25from 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)Merge pull request #4371 from Twistbioscience/zipfile_compatCory Benfieldbefore adoption234f80a
lines 260–285why, one step back260261262class 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__)improve development instructionsKenneth Reitzbefore adoption3ca2722
lines 286–475why, one step back286287288class 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 (Merge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption3c1d36b
lines 476–483why, one step back476 'application/xml',477 ('application/xml', {})478 ),479 (480 'application/json ; charset=utf-8',481 ('application/json', {'charset': 'utf-8'})482 ),483 (Merge pull request #4749 from derlin/masterNate Prewittbefore adoptione4d214d
lines 484–487why, one step back484 'application/json ; Charset=utf-8',485 ('application/json', {'charset': 'utf-8'})486 ),487 (Merge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption3c1d36b
lines 488–518why, one step back488 'text/plain',489 ('text/plain', {})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 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',505 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})506 ),507 (508 'application/json ; ; ',509 ('application/json', {})510 )511 ))512def test__parse_content_type_header(value, expected):513 assert _parse_content_type_header(value) == expected514515516@pytest.mark.parametrize(517 'value, expected', (518 (improve development instructionsKenneth Reitzbefore adoption3ca2722
lines 519–572why, one step back519 CaseInsensitiveDict(),520 None521 ),522 (523 CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),524 'utf-8'525 ),526 (527 CaseInsensitiveDict({'content-type': 'text/plain'}),528 'ISO-8859-1'529 ),530 ))531def test_get_encoding_from_headers(value, expected):532 assert get_encoding_from_headers(value) == expected533534535@pytest.mark.parametrize(536 'value, length', (537 ('', 0),538 ('T', 1),539 ('Test', 4),540 ('Cont', 0),541 ('Other', -5),542 ('Content', None),543 ))544def test_iter_slices(value, length):545 if length is None or (length <= 0 and len(value) > 0):546 # Reads all content at once547 assert len(list(iter_slices(value, length))) == 1548 else:549 assert len(list(iter_slices(value, 1))) == length550551552@pytest.mark.parametrize(553 'value, expected', (554 (555 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',556 [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]557 ),558 (559 '<http:/.../front.jpeg>',560 [{'url': 'http:/.../front.jpeg'}]561 ),562 (563 '<http:/.../front.jpeg>;',564 [{'url': 'http:/.../front.jpeg'}]565 ),566 (567 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',568 [569 {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},570 {'url': 'http://.../back.jpeg'}571 ]572 ),Merge branch 'master' of https://github.com/requests/requestsKenneth Reitzbefore adoption88dc335
lines 573–576why, one step back573 (574 '',575 []576 ),improve development instructionsKenneth Reitzbefore adoption3ca2722
lines 577–620why, one step back577 ))578def test_parse_header_links(value, expected):579 assert parse_header_links(value) == expected580581582@pytest.mark.parametrize(583 'value, expected', (584 ('example.com/path', 'http://example.com/path'),585 ('//example.com/path', 'http://example.com/path'),586 ))587def test_prepend_scheme_if_needed(value, expected):588 assert prepend_scheme_if_needed(value, 'http') == expected589590591@pytest.mark.parametrize(592 'value, expected', (593 ('T', 'T'),594 (b'T', 'T'),595 (u'T', 'T'),596 ))597def test_to_native_string(value, expected):598 assert to_native_string(value) == expected599600601@pytest.mark.parametrize(602 'url, expected', (603 ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),604 ('http://example.com/path', 'http://example.com/path'),605 ('//u:p@example.com/path', '//example.com/path'),606 ('//example.com/path', '//example.com/path'),607 ('example.com/path', '//example.com/path'),608 ('scheme:u:p@example.com/path', 'scheme://example.com/path'),609 ))610def test_urldefragauth(url, expected):611 assert urldefragauth(url) == expected612613614@pytest.mark.parametrize(615 'url, expected', (616 ('http://192.168.0.1:5000/', True),617 ('http://192.168.0.1/', True),618 ('http://172.16.1.1/', True),619 ('http://172.16.1.1:5000/', True),620 ('http://localhost.localdomain:5000/v1.0/', True),Merge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption3c1d36b
line 621why, one step back621 ('http://google.com:6000/', True),improve development instructionsKenneth Reitzbefore adoption3ca2722
lines 622–629why, one step back622 ('http://172.16.1.12/', False),623 ('http://172.16.1.12:5000/', False),624 ('http://google.com:5000/v1.0/', False),625 ))626def test_should_bypass_proxies(url, expected, monkeypatch):627 """Tests for function should_bypass_proxies to check if proxy628 can be bypassed or not629 """Merge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption3c1d36b
lines 630–631why, one step back630 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')631 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')improve development instructionsKenneth Reitzbefore adoption3ca2722
line 632why, one step back632 assert should_bypass_proxies(url, no_proxy=None) == expectedMerge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption3c1d36b
lines 633–652why, one step back633634635@pytest.mark.parametrize(636 'url, expected', (637 ('http://172.16.1.1/', '172.16.1.1'),638 ('http://172.16.1.1:5000/', '172.16.1.1'),639 ('http://user:pass@172.16.1.1', '172.16.1.1'),640 ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),641 ('http://hostname/', 'hostname'),642 ('http://hostname:5000/', 'hostname'),643 ('http://user:pass@hostname', 'hostname'),644 ('http://user:pass@hostname:5000', 'hostname'),645 ))646def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):647 """The proxy_bypass function should be called with a hostname or IP without648 a port number or auth credentials.649 """650 proxy_bypass = mocker.patch('requests.utils.proxy_bypass')651 should_bypass_proxies(url, no_proxy=None)652 proxy_bypass.assert_called_once_with(expected)improve development instructionsKenneth Reitzbefore adoption3ca2722
lines 653–733why, one step back653654655@pytest.mark.parametrize(656 'cookiejar', (657 compat.cookielib.CookieJar(),658 RequestsCookieJar()659 ))660def test_add_dict_to_cookiejar(cookiejar):661 """Ensure add_dict_to_cookiejar works for662 non-RequestsCookieJar CookieJars663 """664 cookiedict = {'test': 'cookies',665 'good': 'cookies'}666 cj = add_dict_to_cookiejar(cookiejar, cookiedict)667 cookies = dict((cookie.name, cookie.value) for cookie in cj)668 assert cookiedict == cookies669670671@pytest.mark.parametrize(672 'value, expected', (673 (u'test', True),674 (u'æíöû', False),675 (u'ジェーピーニック', False),676 )677)678def test_unicode_is_ascii(value, expected):679 assert unicode_is_ascii(value) is expected680681682@pytest.mark.parametrize(683 'url, expected', (684 ('http://192.168.0.1:5000/', True),685 ('http://192.168.0.1/', True),686 ('http://172.16.1.1/', True),687 ('http://172.16.1.1:5000/', True),688 ('http://localhost.localdomain:5000/v1.0/', True),689 ('http://172.16.1.12/', False),690 ('http://172.16.1.12:5000/', False),691 ('http://google.com:5000/v1.0/', False),692 ))693def test_should_bypass_proxies_no_proxy(694 url, expected, monkeypatch):695 """Tests for function should_bypass_proxies to check if proxy696 can be bypassed or not using the 'no_proxy' argument697 """698 no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'699 # Test 'no_proxy' argument700 assert should_bypass_proxies(url, no_proxy=no_proxy) == expected701702703@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')704@pytest.mark.parametrize(705 'url, expected, override', (706 ('http://192.168.0.1:5000/', True, None),707 ('http://192.168.0.1/', True, None),708 ('http://172.16.1.1/', True, None),709 ('http://172.16.1.1:5000/', True, None),710 ('http://localhost.localdomain:5000/v1.0/', True, None),711 ('http://172.16.1.22/', False, None),712 ('http://172.16.1.22:5000/', False, None),713 ('http://google.com:5000/v1.0/', False, None),714 ('http://mylocalhostname:5000/v1.0/', True, '<local>'),715 ('http://192.168.0.1/', False, ''),716 ))717def test_should_bypass_proxies_win_registry(url, expected, override,718 monkeypatch):719 """Tests for function should_bypass_proxies to check if proxy720 can be bypassed or not with Windows registry settings721 """722 if override is None:723 override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'724 if compat.is_py3:725 import winreg726 else:727 import _winreg as winreg728729 class RegHandle:730 def Close(self):731 pass732733 ie_settings = RegHandle()#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645
line 734why, one step back734 proxyEnableValues = deque([1, "1"])improve development instructionsKenneth Reitzbefore adoption3ca2722
lines 735–741why, one step back735736 def OpenKey(key, subkey):737 return ie_settings738739 def QueryValueEx(key, value_name):740 if key is ie_settings:741 if value_name == 'ProxyEnable':#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645
lines 742–744why, one step back742 # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)743 proxyEnableValues.rotate()744 return [proxyEnableValues[0]]improve development instructionsKenneth Reitzbefore adoption3ca2722
lines 745–754why, one step back745 elif value_name == 'ProxyOverride':746 return [override]747748 monkeypatch.setenv('http_proxy', '')749 monkeypatch.setenv('https_proxy', '')750 monkeypatch.setenv('ftp_proxy', '')751 monkeypatch.setenv('no_proxy', '')752 monkeypatch.setenv('NO_PROXY', '')753 monkeypatch.setattr(winreg, 'OpenKey', OpenKey)754 monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645
line 755why, one step back755 assert should_bypass_proxies(url, None) == expectedMerge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoptiona5b8f8d
lines 756–781why, one step back756757758@pytest.mark.parametrize(759 'env_name, value', (760 ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),761 ('no_proxy', None),762 ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),763 ('a_new_key', None),764 ))765def test_set_environ(env_name, value):766 """Tests set_environ will set environ values and will restore the environ."""767 environ_copy = copy.deepcopy(os.environ)768 with set_environ(env_name, value):769 assert os.environ.get(env_name) == value770771 assert os.environ == environ_copy772773774def test_set_environ_raises_exception():775 """Tests set_environ will raise exceptions in context when the776 value parameter is None."""777 with pytest.raises(Exception) as exception:778 with set_environ('test1', None):779 raise Exception('Expected exception')780781 assert 'Expected exception' in str(exception.value)