Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

782 lines · 25.4 KiB · Python

Last changed by

Merge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f

History of this file

Take it

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

#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645

lines 1–15why, one step back
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,

Merge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption3c1d36b

line 16why, one step back
16 get_auth_from_url, _parse_content_type_header, get_encoding_from_headers,

#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645

lines 17–399why, one step back
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):

Merge pull request #5160 from OrangutanGaming/change-githubNate Prewittbefore adoptiond79024f

line 400why, one step back
400 """See: https://github.com/psf/requests/issues/2356"""

#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645

lines 401–475why, one step back
401 assert requote_uri(uri) == expected
402403404@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 back
476 '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 back
484 '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 back
488 '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 (

#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645

lines 519–620why, one step back
519 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 ),573 (574 '',575 []576 ),577 ))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 back
621 ('http://google.com:6000/', True),

#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645

lines 622–624why, one step back
622 ('http://172.16.1.12/', False),
623 ('http://172.16.1.12:5000/', False),624 ('http://google.com:5000/v1.0/', False),

Merge pull request #4723 from kalefranz/fix-no_proxy-file-urlNate Prewittbefore adoption9cfd292

line 625why, one step back
625 ('file:///some/path/on/disk', True),

#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645

lines 626–630why, one step back
626 ))
627def test_should_bypass_proxies(url, expected, monkeypatch):628 """Tests for function should_bypass_proxies to check if proxy629 can be bypassed or not630 """

Merge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption3c1d36b

lines 631–632why, one step back
631 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')
632 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')

#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645

line 633why, one step back
633 assert should_bypass_proxies(url, no_proxy=None) == expected

Merge branch 'master' of github.com:requests/requestsKenneth Reitzbefore adoption3c1d36b

lines 634–653why, one step back
634
635636@pytest.mark.parametrize(637 'url, expected', (638 ('http://172.16.1.1/', '172.16.1.1'),639 ('http://172.16.1.1:5000/', '172.16.1.1'),640 ('http://user:pass@172.16.1.1', '172.16.1.1'),641 ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),642 ('http://hostname/', 'hostname'),643 ('http://hostname:5000/', 'hostname'),644 ('http://user:pass@hostname', 'hostname'),645 ('http://user:pass@hostname:5000', 'hostname'),646 ))647def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):648 """The proxy_bypass function should be called with a hostname or IP without649 a port number or auth credentials.650 """651 proxy_bypass = mocker.patch('requests.utils.proxy_bypass')652 should_bypass_proxies(url, no_proxy=None)653 proxy_bypass.assert_called_once_with(expected)

#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645

lines 654–667why, one step back
654
655656@pytest.mark.parametrize(657 'cookiejar', (658 compat.cookielib.CookieJar(),659 RequestsCookieJar()660 ))661def test_add_dict_to_cookiejar(cookiejar):662 """Ensure add_dict_to_cookiejar works for663 non-RequestsCookieJar CookieJars664 """665 cookiedict = {'test': 'cookies',666 'good': 'cookies'}667 cj = add_dict_to_cookiejar(cookiejar, cookiedict)

Merge pull request #4835 from requests/2.20.0Nate Prewittbefore adoption75bdc99

line 668why, one step back
668 cookies = {cookie.name: cookie.value for cookie in cj}

#4373, fix possible winreg value type difference (#4377)Mingyuan Xiabefore adoptionacd2645

lines 669–782why, one step back
669 assert cookiedict == cookies
670671672@pytest.mark.parametrize(673 'value, expected', (674 (u'test', True),675 (u'æíöû', False),676 (u'ジェーピーニック', False),677 )678)679def test_unicode_is_ascii(value, expected):680 assert unicode_is_ascii(value) is expected681682683@pytest.mark.parametrize(684 'url, expected', (685 ('http://192.168.0.1:5000/', True),686 ('http://192.168.0.1/', True),687 ('http://172.16.1.1/', True),688 ('http://172.16.1.1:5000/', True),689 ('http://localhost.localdomain:5000/v1.0/', True),690 ('http://172.16.1.12/', False),691 ('http://172.16.1.12:5000/', False),692 ('http://google.com:5000/v1.0/', False),693 ))694def test_should_bypass_proxies_no_proxy(695 url, expected, monkeypatch):696 """Tests for function should_bypass_proxies to check if proxy697 can be bypassed or not using the 'no_proxy' argument698 """699 no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'700 # Test 'no_proxy' argument701 assert should_bypass_proxies(url, no_proxy=no_proxy) == expected702703704@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')705@pytest.mark.parametrize(706 'url, expected, override', (707 ('http://192.168.0.1:5000/', True, None),708 ('http://192.168.0.1/', True, None),709 ('http://172.16.1.1/', True, None),710 ('http://172.16.1.1:5000/', True, None),711 ('http://localhost.localdomain:5000/v1.0/', True, None),712 ('http://172.16.1.22/', False, None),713 ('http://172.16.1.22:5000/', False, None),714 ('http://google.com:5000/v1.0/', False, None),715 ('http://mylocalhostname:5000/v1.0/', True, '<local>'),716 ('http://192.168.0.1/', False, ''),717 ))718def test_should_bypass_proxies_win_registry(url, expected, override,719 monkeypatch):720 """Tests for function should_bypass_proxies to check if proxy721 can be bypassed or not with Windows registry settings722 """723 if override is None:724 override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'725 if compat.is_py3:726 import winreg727 else:728 import _winreg as winreg729730 class RegHandle:731 def Close(self):732 pass733734 ie_settings = RegHandle()735 proxyEnableValues = deque([1, "1"])736737 def OpenKey(key, subkey):738 return ie_settings739740 def QueryValueEx(key, value_name):741 if key is ie_settings:742 if value_name == 'ProxyEnable':743 # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)744 proxyEnableValues.rotate()745 return [proxyEnableValues[0]]746 elif value_name == 'ProxyOverride':747 return [override]748749 monkeypatch.setenv('http_proxy', '')750 monkeypatch.setenv('https_proxy', '')751 monkeypatch.setenv('ftp_proxy', '')752 monkeypatch.setenv('no_proxy', '')753 monkeypatch.setenv('NO_PROXY', '')754 monkeypatch.setattr(winreg, 'OpenKey', OpenKey)755 monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)756 assert should_bypass_proxies(url, None) == expected757758759@pytest.mark.parametrize(760 'env_name, value', (761 ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),762 ('no_proxy', None),763 ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),764 ('a_new_key', None),765 ))766def test_set_environ(env_name, value):767 """Tests set_environ will set environ values and will restore the environ."""768 environ_copy = copy.deepcopy(os.environ)769 with set_environ(env_name, value):770 assert os.environ.get(env_name) == value771772 assert os.environ == environ_copy773774775def test_set_environ_raises_exception():776 """Tests set_environ will raise exceptions in context when the777 value parameter is None."""778 with pytest.raises(Exception) as exception:779 with set_environ('test1', None):780 raise Exception('Expected exception')781782 assert 'Expected exception' in str(exception.value)