test_utils.py
This file
Path
tests/test_utils.py
654 lines · 20.8 KiB · Python
Last changed by
Merge pull request #3979 from schlamar/bypass-proxyCory Benfieldbefore adoption216aee4
History of this fileTake it
1# -*- coding: utf-8 -*-23import os4from io import BytesIO56import pytest7from requests import compat8from requests.cookies import RequestsCookieJar9from requests.structures import CaseInsensitiveDict10from requests.utils import (11 address_in_network, dotted_netmask,12 get_auth_from_url, get_encoding_from_headers,13 get_encodings_from_content, get_environ_proxies,14 guess_filename, guess_json_utf, is_ipv4_address,15 is_valid_cidr, iter_slices, parse_dict_header,16 parse_header_links, prepend_scheme_if_needed,17 requote_uri, select_proxy, should_bypass_proxies, super_len,18 to_key_val_list, to_native_string,19 unquote_header_value, unquote_unreserved,20 urldefragauth, add_dict_to_cookiejar)21from requests._internal_utils import unicode_is_ascii2223from .compat import StringIO, cStringIO242526class TestSuperLen:2728 @pytest.mark.parametrize(29 'stream, value', (30 (StringIO.StringIO, 'Test'),31 (BytesIO, b'Test'),32 pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),33 ))34 def test_io_streams(self, stream, value):35 """Ensures that we properly deal with different kinds of IO streams."""36 assert super_len(stream()) == 037 assert super_len(stream(value)) == 43839 def test_super_len_correctly_calculates_len_of_partially_read_file(self):40 """Ensure that we handle partially consumed file like objects."""41 s = StringIO.StringIO()42 s.write('foobarbogus')43 assert super_len(s) == 04445 @pytest.mark.parametrize('error', [IOError, OSError])46 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):47 """If tell() raises errors, assume the cursor is at position zero."""48 class BoomFile(object):49 def __len__(self):50 return 55152 def tell(self):53 raise error()5455 assert super_len(BoomFile()) == 05657 @pytest.mark.parametrize('error', [IOError, OSError])58 def test_super_len_tell_ioerror(self, error):59 """Ensure that if tell gives an IOError super_len doesn't fail"""60 class NoLenBoomFile(object):61 def tell(self):62 raise error()6364 def seek(self, offset, whence):65 pass6667 assert super_len(NoLenBoomFile()) == 06869 def test_string(self):70 assert super_len('Test') == 47172 @pytest.mark.parametrize(73 'mode, warnings_num', (74 ('r', 1),75 ('rb', 0),76 ))77 def test_file(self, tmpdir, mode, warnings_num, recwarn):78 file_obj = tmpdir.join('test.txt')79 file_obj.write('Test')80 with file_obj.open(mode) as fd:81 assert super_len(fd) == 482 assert len(recwarn) == warnings_num8384 def test_super_len_with__len__(self):85 foo = [1,2,3,4]86 len_foo = super_len(foo)87 assert len_foo == 48889 def test_super_len_with_no__len__(self):90 class LenFile(object):91 def __init__(self):92 self.len = 59394 assert super_len(LenFile()) == 59596 def test_super_len_with_tell(self):97 foo = StringIO.StringIO('12345')98 assert super_len(foo) == 599 foo.read(2)100 assert super_len(foo) == 3101102 def test_super_len_with_fileno(self):103 with open(__file__, 'rb') as f:104 length = super_len(f)105 file_data = f.read()106 assert length == len(file_data)107108 def test_super_len_with_no_matches(self):109 """Ensure that objects without any length methods default to 0"""110 assert super_len(object()) == 0111112113class TestToKeyValList:114115 @pytest.mark.parametrize(116 'value, expected', (117 ([('key', 'val')], [('key', 'val')]),118 ((('key', 'val'), ), [('key', 'val')]),119 ({'key': 'val'}, [('key', 'val')]),120 (None, None)121 ))122 def test_valid(self, value, expected):123 assert to_key_val_list(value) == expected124125 def test_invalid(self):126 with pytest.raises(ValueError):127 to_key_val_list('string')128129130class TestUnquoteHeaderValue:131132 @pytest.mark.parametrize(133 'value, expected', (134 (None, None),135 ('Test', 'Test'),136 ('"Test"', 'Test'),137 ('"Test\\\\"', 'Test\\'),138 ('"\\\\Comp\\Res"', '\\Comp\\Res'),139 ))140 def test_valid(self, value, expected):141 assert unquote_header_value(value) == expected142143 def test_is_filename(self):144 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'145146147class TestGetEnvironProxies:148 """Ensures that IP addresses are correctly matches with ranges149 in no_proxy variable.150 """151152 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])153 def no_proxy(self, request, monkeypatch):154 monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')155156 @pytest.mark.parametrize(157 'url', (158 'http://192.168.0.1:5000/',159 'http://192.168.0.1/',160 'http://172.16.1.1/',161 'http://172.16.1.1:5000/',162 'http://localhost.localdomain:5000/v1.0/',163 ))164 def test_bypass(self, url):165 assert get_environ_proxies(url, no_proxy=None) == {}166167 @pytest.mark.parametrize(168 'url', (169 'http://192.168.1.1:5000/',170 'http://192.168.1.1/',171 'http://www.requests.com/',172 ))173 def test_not_bypass(self, url):174 assert get_environ_proxies(url, no_proxy=None) != {}175176 @pytest.mark.parametrize(177 'url', (178 'http://192.168.1.1:5000/',179 'http://192.168.1.1/',180 'http://www.requests.com/',181 ))182 def test_bypass_no_proxy_keyword(self, url):183 no_proxy = '192.168.1.1,requests.com'184 assert get_environ_proxies(url, no_proxy=no_proxy) == {}185186 @pytest.mark.parametrize(187 'url', (188 'http://192.168.0.1:5000/',189 'http://192.168.0.1/',190 'http://172.16.1.1/',191 'http://172.16.1.1:5000/',192 'http://localhost.localdomain:5000/v1.0/',193 ))194 def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):195 # This is testing that the 'no_proxy' argument overrides the196 # environment variable 'no_proxy'197 monkeypatch.setenv('http_proxy', 'http://proxy.example.com:3128/')198 no_proxy = '192.168.1.1,requests.com'199 assert get_environ_proxies(url, no_proxy=no_proxy) != {}200201202class TestIsIPv4Address:203204 def test_valid(self):205 assert is_ipv4_address('8.8.8.8')206207 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))208 def test_invalid(self, value):209 assert not is_ipv4_address(value)210211212class TestIsValidCIDR:213214 def test_valid(self):215 assert is_valid_cidr('192.168.1.0/24')216217 @pytest.mark.parametrize(218 'value', (219 '8.8.8.8',220 '192.168.1.0/a',221 '192.168.1.0/128',222 '192.168.1.0/-1',223 '192.168.1.999/24',224 ))225 def test_invalid(self, value):226 assert not is_valid_cidr(value)227228229class TestAddressInNetwork:230231 def test_valid(self):232 assert address_in_network('192.168.1.1', '192.168.1.0/24')233234 def test_invalid(self):235 assert not address_in_network('172.16.0.1', '192.168.1.0/24')236237238class TestGuessFilename:239240 @pytest.mark.parametrize(241 'value', (1, type('Fake', (object,), {'name': 1})()),242 )243 def test_guess_filename_invalid(self, value):244 assert guess_filename(value) is None245246 @pytest.mark.parametrize(247 'value, expected_type', (248 (b'value', compat.bytes),249 (b'value'.decode('utf-8'), compat.str)250 ))251 def test_guess_filename_valid(self, value, expected_type):252 obj = type('Fake', (object,), {'name': value})()253 result = guess_filename(obj)254 assert result == value255 assert isinstance(result, expected_type)256257258class TestContentEncodingDetection:259260 def test_none(self):261 encodings = get_encodings_from_content('')262 assert not len(encodings)263264 @pytest.mark.parametrize(265 'content', (266 # HTML5 meta charset attribute267 '<meta charset="UTF-8">',268 # HTML4 pragma directive269 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',270 # XHTML 1.x served with text/html MIME type271 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',272 # XHTML 1.x served as XML273 '<?xml version="1.0" encoding="UTF-8"?>',274 ))275 def test_pragmas(self, content):276 encodings = get_encodings_from_content(content)277 assert len(encodings) == 1278 assert encodings[0] == 'UTF-8'279280 def test_precedence(self):281 content = '''282 <?xml version="1.0" encoding="XML"?>283 <meta charset="HTML5">284 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />285 '''.strip()286 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']287288289class TestGuessJSONUTF:290291 @pytest.mark.parametrize(292 'encoding', (293 'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',294 'utf-32-be', 'utf-32-le'295 ))296 def test_encoded(self, encoding):297 data = '{}'.encode(encoding)298 assert guess_json_utf(data) == encoding299300 def test_bad_utf_like_encoding(self):301 assert guess_json_utf(b'\x00\x00\x00\x00') is None302303 @pytest.mark.parametrize(304 ('encoding', 'expected'), (305 ('utf-16-be', 'utf-16'),306 ('utf-16-le', 'utf-16'),307 ('utf-32-be', 'utf-32'),308 ('utf-32-le', 'utf-32')309 ))310 def test_guess_by_bom(self, encoding, expected):311 data = u'\ufeff{}'.encode(encoding)312 assert guess_json_utf(data) == expected313314315USER = PASSWORD = "%!*'();:@&=+$,/?#[] "316ENCODED_USER = compat.quote(USER, '')317ENCODED_PASSWORD = compat.quote(PASSWORD, '')318319320@pytest.mark.parametrize(321 'url, auth', (322 (323 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +324 'request.com/url.html#test',325 (USER, PASSWORD)326 ),327 (328 'http://user:pass@complex.url.com/path?query=yes',329 ('user', 'pass')330 ),331 (332 'http://user:pass%20pass@complex.url.com/path?query=yes',333 ('user', 'pass pass')334 ),335 (336 'http://user:pass pass@complex.url.com/path?query=yes',337 ('user', 'pass pass')338 ),339 (340 'http://user%25user:pass@complex.url.com/path?query=yes',341 ('user%user', 'pass')342 ),343 (344 'http://user:pass%23pass@complex.url.com/path?query=yes',345 ('user', 'pass#pass')346 ),347 (348 'http://complex.url.com/path?query=yes',349 ('', '')350 ),351 ))352def test_get_auth_from_url(url, auth):353 assert get_auth_from_url(url) == auth354355356@pytest.mark.parametrize(357 'uri, expected', (358 (359 # Ensure requoting doesn't break expectations360 'http://example.com/fiz?buz=%25ppicture',361 'http://example.com/fiz?buz=%25ppicture',362 ),363 (364 # Ensure we handle unquoted percent signs in redirects365 'http://example.com/fiz?buz=%ppicture',366 'http://example.com/fiz?buz=%25ppicture',367 ),368 ))369def test_requote_uri_with_unquoted_percents(uri, expected):370 """See: https://github.com/kennethreitz/requests/issues/2356"""371 assert requote_uri(uri) == expected372373374@pytest.mark.parametrize(375 'uri, expected', (376 (377 # Illegal bytes378 'http://example.com/?a=%--',379 'http://example.com/?a=%--',380 ),381 (382 # Reserved characters383 'http://example.com/?a=%300',384 'http://example.com/?a=00',385 )386 ))387def test_unquote_unreserved(uri, expected):388 assert unquote_unreserved(uri) == expected389390391@pytest.mark.parametrize(392 'mask, expected', (393 (8, '255.0.0.0'),394 (24, '255.255.255.0'),395 (25, '255.255.255.128'),396 ))397def test_dotted_netmask(mask, expected):398 assert dotted_netmask(mask) == expected399400401http_proxies = {'http': 'http://http.proxy',402 'http://some.host': 'http://some.host.proxy'}403all_proxies = {'all': 'socks5://http.proxy',404 'all://some.host': 'socks5://some.host.proxy'}405mixed_proxies = {'http': 'http://http.proxy',406 'http://some.host': 'http://some.host.proxy',407 'all': 'socks5://http.proxy'}408@pytest.mark.parametrize(409 'url, expected, proxies', (410 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),411 ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),412 ('hTTp:///path', 'http://http.proxy', http_proxies),413 ('hTTps://Other.Host', None, http_proxies),414 ('file:///etc/motd', None, http_proxies),415416 ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),417 ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),418 ('hTTp:///path', 'socks5://http.proxy', all_proxies),419 ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),420421 ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),422 ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),423 ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),424 ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),425 ('https://', 'socks5://http.proxy', mixed_proxies),426 # XXX: unsure whether this is reasonable behavior427 ('file:///etc/motd', 'socks5://http.proxy', all_proxies),428 ))429def test_select_proxies(url, expected, proxies):430 """Make sure we can select per-host proxies correctly."""431 assert select_proxy(url, proxies) == expected432433434@pytest.mark.parametrize(435 'value, expected', (436 ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),437 ('key_without_value', {'key_without_value': None})438 ))439def test_parse_dict_header(value, expected):440 assert parse_dict_header(value) == expected441442443@pytest.mark.parametrize(444 'value, expected', (445 (446 CaseInsensitiveDict(),447 None448 ),449 (450 CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),451 'utf-8'452 ),453 (454 CaseInsensitiveDict({'content-type': 'text/plain'}),455 'ISO-8859-1'456 ),457 ))458def test_get_encoding_from_headers(value, expected):459 assert get_encoding_from_headers(value) == expected460461462@pytest.mark.parametrize(463 'value, length', (464 ('', 0),465 ('T', 1),466 ('Test', 4),467 ('Cont', 0),468 ('Other', -5),469 ('Content', None),470 ))471def test_iter_slices(value, length):472 if length is None or (length <= 0 and len(value) > 0):473 # Reads all content at once474 assert len(list(iter_slices(value, length))) == 1475 else:476 assert len(list(iter_slices(value, 1))) == length477478479@pytest.mark.parametrize(480 'value, expected', (481 (482 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',483 [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]484 ),485 (486 '<http:/.../front.jpeg>',487 [{'url': 'http:/.../front.jpeg'}]488 ),489 (490 '<http:/.../front.jpeg>;',491 [{'url': 'http:/.../front.jpeg'}]492 ),493 (494 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',495 [496 {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},497 {'url': 'http://.../back.jpeg'}498 ]499 ),500 ))501def test_parse_header_links(value, expected):502 assert parse_header_links(value) == expected503504505@pytest.mark.parametrize(506 'value, expected', (507 ('example.com/path', 'http://example.com/path'),508 ('//example.com/path', 'http://example.com/path'),509 ))510def test_prepend_scheme_if_needed(value, expected):511 assert prepend_scheme_if_needed(value, 'http') == expected512513514@pytest.mark.parametrize(515 'value, expected', (516 ('T', 'T'),517 (b'T', 'T'),518 (u'T', 'T'),519 ))520def test_to_native_string(value, expected):521 assert to_native_string(value) == expected522523524@pytest.mark.parametrize(525 'url, expected', (526 ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),527 ('http://example.com/path', 'http://example.com/path'),528 ('//u:p@example.com/path', '//example.com/path'),529 ('//example.com/path', '//example.com/path'),530 ('example.com/path', '//example.com/path'),531 ('scheme:u:p@example.com/path', 'scheme://example.com/path'),532 ))533def test_urldefragauth(url, expected):534 assert urldefragauth(url) == expected535536537@pytest.mark.parametrize(538 'url, expected', (539 ('http://192.168.0.1:5000/', True),540 ('http://192.168.0.1/', True),541 ('http://172.16.1.1/', True),542 ('http://172.16.1.1:5000/', True),543 ('http://localhost.localdomain:5000/v1.0/', True),544 ('http://172.16.1.12/', False),545 ('http://172.16.1.12:5000/', False),546 ('http://google.com:5000/v1.0/', False),547 ))548def test_should_bypass_proxies(url, expected, monkeypatch):549 """Tests for function should_bypass_proxies to check if proxy550 can be bypassed or not551 """552 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')553 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')554 assert should_bypass_proxies(url, no_proxy=None) == expected555556557@pytest.mark.parametrize(558 'cookiejar', (559 compat.cookielib.CookieJar(),560 RequestsCookieJar()561 ))562def test_add_dict_to_cookiejar(cookiejar):563 """Ensure add_dict_to_cookiejar works for564 non-RequestsCookieJar CookieJars565 """566 cookiedict = {'test': 'cookies',567 'good': 'cookies'}568 cj = add_dict_to_cookiejar(cookiejar, cookiedict)569 cookies = dict((cookie.name, cookie.value) for cookie in cj)570 assert cookiedict == cookies571572573@pytest.mark.parametrize(574 'value, expected', (575 (u'test', True),576 (u'æíöû', False),577 (u'ジェーピーニック', False),578 )579)580def test_unicode_is_ascii(value, expected):581 assert unicode_is_ascii(value) is expected582583584@pytest.mark.parametrize(585 'url, expected', (586 ('http://192.168.0.1:5000/', True),587 ('http://192.168.0.1/', True),588 ('http://172.16.1.1/', True),589 ('http://172.16.1.1:5000/', True),590 ('http://localhost.localdomain:5000/v1.0/', True),591 ('http://172.16.1.12/', False),592 ('http://172.16.1.12:5000/', False),593 ('http://google.com:5000/v1.0/', False),594 ))595def test_should_bypass_proxies_no_proxy(596 url, expected, monkeypatch):597 """Tests for function should_bypass_proxies to check if proxy598 can be bypassed or not using the 'no_proxy' argument599 """600 no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'601 # Test 'no_proxy' argument602 assert should_bypass_proxies(url, no_proxy=no_proxy) == expected603604605@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')606@pytest.mark.parametrize(607 'url, expected, override', (608 ('http://192.168.0.1:5000/', True, None),609 ('http://192.168.0.1/', True, None),610 ('http://172.16.1.1/', True, None),611 ('http://172.16.1.1:5000/', True, None),612 ('http://localhost.localdomain:5000/v1.0/', True, None),613 ('http://172.16.1.22/', False, None),614 ('http://172.16.1.22:5000/', False, None),615 ('http://google.com:5000/v1.0/', False, None),616 ('http://mylocalhostname:5000/v1.0/', True, '<local>'),617 ('http://192.168.0.1/', False, ''),618 ))619def test_should_bypass_proxies_win_registry(url, expected, override,620 monkeypatch):621 """Tests for function should_bypass_proxies to check if proxy622 can be bypassed or not with Windows registry settings623 """624 if override is None:625 override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'626 if compat.is_py3:627 import winreg628 else:629 import _winreg as winreg630631 class RegHandle:632 def Close(self):633 pass634635 ie_settings = RegHandle()636637 def OpenKey(key, subkey):638 return ie_settings639640 def QueryValueEx(key, value_name):641 if key is ie_settings:642 if value_name == 'ProxyEnable':643 return [1]644 elif value_name == 'ProxyOverride':645 return [override]646647 monkeypatch.setenv('http_proxy', '')648 monkeypatch.setenv('https_proxy', '')649 monkeypatch.setenv('ftp_proxy', '')650 monkeypatch.setenv('no_proxy', '')651 monkeypatch.setenv('NO_PROXY', '')652 monkeypatch.setattr(winreg, 'OpenKey', OpenKey)653 monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)654 assert should_bypass_proxies(url, no_proxy=None) == expected