test_utils.py
This file
Path
tests/test_utils.py
531 lines · 16.5 KiB · Python
Last changed by
Merge pull request #3627 from nateprewitt/remove_update_callCory Benfieldbefore adoption595a409
History of this fileTake it
1# -*- coding: utf-8 -*-23from io import BytesIO45import pytest6from requests import compat7from requests.cookies import RequestsCookieJar, cookiejar_from_dict8from requests.structures import CaseInsensitiveDict9from requests.utils import (10 address_in_network, dotted_netmask,11 get_auth_from_url, get_encoding_from_headers,12 get_encodings_from_content, get_environ_proxies,13 guess_filename, guess_json_utf, is_ipv4_address,14 is_valid_cidr, iter_slices, parse_dict_header,15 parse_header_links, prepend_scheme_if_needed,16 requote_uri, select_proxy, should_bypass_proxies, super_len,17 to_key_val_list, to_native_string,18 unquote_header_value, unquote_unreserved,19 urldefragauth, add_dict_to_cookiejar)2021from .compat import StringIO, cStringIO222324class TestSuperLen:2526 @pytest.mark.parametrize(27 'stream, value', (28 (StringIO.StringIO, 'Test'),29 (BytesIO, b'Test'),30 pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),31 ))32 def test_io_streams(self, stream, value):33 """Ensures that we properly deal with different kinds of IO streams."""34 assert super_len(stream()) == 035 assert super_len(stream(value)) == 43637 def test_super_len_correctly_calculates_len_of_partially_read_file(self):38 """Ensure that we handle partially consumed file like objects."""39 s = StringIO.StringIO()40 s.write('foobarbogus')41 assert super_len(s) == 04243 @pytest.mark.parametrize('error', [IOError, OSError])44 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):45 """If tell() raises errors, assume the cursor is at position zero."""46 class BoomFile(object):47 def __len__(self):48 return 54950 def tell(self):51 raise error()5253 assert super_len(BoomFile()) == 05455 @pytest.mark.parametrize('error', [IOError, OSError])56 def test_super_len_tell_ioerror(self, error):57 """Ensure that if tell gives an IOError super_len doesn't fail"""58 class NoLenBoomFile(object):59 def tell(self):60 raise error()6162 def seek(self, offset, whence):63 pass6465 assert super_len(NoLenBoomFile()) == 06667 def test_string(self):68 assert super_len('Test') == 46970 @pytest.mark.parametrize(71 'mode, warnings_num', (72 ('r', 1),73 ('rb', 0),74 ))75 def test_file(self, tmpdir, mode, warnings_num, recwarn):76 file_obj = tmpdir.join('test.txt')77 file_obj.write('Test')78 with file_obj.open(mode) as fd:79 assert super_len(fd) == 480 assert len(recwarn) == warnings_num8182 def test_super_len_with__len__(self):83 foo = [1,2,3,4]84 len_foo = super_len(foo)85 assert len_foo == 48687 def test_super_len_with_no__len__(self):88 class LenFile(object):89 def __init__(self):90 self.len = 59192 assert super_len(LenFile()) == 59394 def test_super_len_with_tell(self):95 foo = StringIO.StringIO('12345')96 assert super_len(foo) == 597 foo.read(2)98 assert super_len(foo) == 399100 def test_super_len_with_fileno(self):101 with open(__file__, 'rb') as f:102 length = super_len(f)103 file_data = f.read()104 assert length == len(file_data)105106 def test_super_len_with_no_matches(self):107 """Ensure that objects without any length methods default to 0"""108 assert super_len(object()) == 0109110111class TestToKeyValList:112113 @pytest.mark.parametrize(114 'value, expected', (115 ([('key', 'val')], [('key', 'val')]),116 ((('key', 'val'), ), [('key', 'val')]),117 ({'key': 'val'}, [('key', 'val')]),118 (None, None)119 ))120 def test_valid(self, value, expected):121 assert to_key_val_list(value) == expected122123 def test_invalid(self):124 with pytest.raises(ValueError):125 to_key_val_list('string')126127128class TestUnquoteHeaderValue:129130 @pytest.mark.parametrize(131 'value, expected', (132 (None, None),133 ('Test', 'Test'),134 ('"Test"', 'Test'),135 ('"Test\\\\"', 'Test\\'),136 ('"\\\\Comp\\Res"', '\\Comp\\Res'),137 ))138 def test_valid(self, value, expected):139 assert unquote_header_value(value) == expected140141 def test_is_filename(self):142 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'143144145class TestGetEnvironProxies:146 """Ensures that IP addresses are correctly matches with ranges147 in no_proxy variable.148 """149150 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])151 def no_proxy(self, request, monkeypatch):152 monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')153154 @pytest.mark.parametrize(155 'url', (156 'http://192.168.0.1:5000/',157 'http://192.168.0.1/',158 'http://172.16.1.1/',159 'http://172.16.1.1:5000/',160 'http://localhost.localdomain:5000/v1.0/',161 ))162 def test_bypass(self, url):163 assert get_environ_proxies(url) == {}164165 @pytest.mark.parametrize(166 'url', (167 'http://192.168.1.1:5000/',168 'http://192.168.1.1/',169 'http://www.requests.com/',170 ))171 def test_not_bypass(self, url):172 assert get_environ_proxies(url) != {}173174175class TestIsIPv4Address:176177 def test_valid(self):178 assert is_ipv4_address('8.8.8.8')179180 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))181 def test_invalid(self, value):182 assert not is_ipv4_address(value)183184185class TestIsValidCIDR:186187 def test_valid(self):188 assert is_valid_cidr('192.168.1.0/24')189190 @pytest.mark.parametrize(191 'value', (192 '8.8.8.8',193 '192.168.1.0/a',194 '192.168.1.0/128',195 '192.168.1.0/-1',196 '192.168.1.999/24',197 ))198 def test_invalid(self, value):199 assert not is_valid_cidr(value)200201202class TestAddressInNetwork:203204 def test_valid(self):205 assert address_in_network('192.168.1.1', '192.168.1.0/24')206207 def test_invalid(self):208 assert not address_in_network('172.16.0.1', '192.168.1.0/24')209210211class TestGuessFilename:212213 @pytest.mark.parametrize(214 'value', (1, type('Fake', (object,), {'name': 1})()),215 )216 def test_guess_filename_invalid(self, value):217 assert guess_filename(value) is None218219 @pytest.mark.parametrize(220 'value, expected_type', (221 (b'value', compat.bytes),222 (b'value'.decode('utf-8'), compat.str)223 ))224 def test_guess_filename_valid(self, value, expected_type):225 obj = type('Fake', (object,), {'name': value})()226 result = guess_filename(obj)227 assert result == value228 assert isinstance(result, expected_type)229230231class TestContentEncodingDetection:232233 def test_none(self):234 encodings = get_encodings_from_content('')235 assert not len(encodings)236237 @pytest.mark.parametrize(238 'content', (239 # HTML5 meta charset attribute240 '<meta charset="UTF-8">',241 # HTML4 pragma directive242 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',243 # XHTML 1.x served with text/html MIME type244 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',245 # XHTML 1.x served as XML246 '<?xml version="1.0" encoding="UTF-8"?>',247 ))248 def test_pragmas(self, content):249 encodings = get_encodings_from_content(content)250 assert len(encodings) == 1251 assert encodings[0] == 'UTF-8'252253 def test_precedence(self):254 content = '''255 <?xml version="1.0" encoding="XML"?>256 <meta charset="HTML5">257 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />258 '''.strip()259 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']260261262class TestGuessJSONUTF:263264 @pytest.mark.parametrize(265 'encoding', (266 'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',267 'utf-32-be', 'utf-32-le'268 ))269 def test_encoded(self, encoding):270 data = '{}'.encode(encoding)271 assert guess_json_utf(data) == encoding272273 def test_bad_utf_like_encoding(self):274 assert guess_json_utf(b'\x00\x00\x00\x00') is None275276277USER = PASSWORD = "%!*'();:@&=+$,/?#[] "278ENCODED_USER = compat.quote(USER, '')279ENCODED_PASSWORD = compat.quote(PASSWORD, '')280281282@pytest.mark.parametrize(283 'url, auth', (284 (285 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +286 'request.com/url.html#test',287 (USER, PASSWORD)288 ),289 (290 'http://user:pass@complex.url.com/path?query=yes',291 ('user', 'pass')292 ),293 (294 'http://user:pass%20pass@complex.url.com/path?query=yes',295 ('user', 'pass pass')296 ),297 (298 'http://user:pass pass@complex.url.com/path?query=yes',299 ('user', 'pass pass')300 ),301 (302 'http://user%25user:pass@complex.url.com/path?query=yes',303 ('user%user', 'pass')304 ),305 (306 'http://user:pass%23pass@complex.url.com/path?query=yes',307 ('user', 'pass#pass')308 ),309 (310 'http://complex.url.com/path?query=yes',311 ('', '')312 ),313 ))314def test_get_auth_from_url(url, auth):315 assert get_auth_from_url(url) == auth316317318@pytest.mark.parametrize(319 'uri, expected', (320 (321 # Ensure requoting doesn't break expectations322 'http://example.com/fiz?buz=%25ppicture',323 'http://example.com/fiz?buz=%25ppicture',324 ),325 (326 # Ensure we handle unquoted percent signs in redirects327 'http://example.com/fiz?buz=%ppicture',328 'http://example.com/fiz?buz=%25ppicture',329 ),330 ))331def test_requote_uri_with_unquoted_percents(uri, expected):332 """See: https://github.com/kennethreitz/requests/issues/2356"""333 assert requote_uri(uri) == expected334335336@pytest.mark.parametrize(337 'uri, expected', (338 (339 # Illegal bytes340 'http://example.com/?a=%--',341 'http://example.com/?a=%--',342 ),343 (344 # Reserved characters345 'http://example.com/?a=%300',346 'http://example.com/?a=00',347 )348 ))349def test_unquote_unreserved(uri, expected):350 assert unquote_unreserved(uri) == expected351352353@pytest.mark.parametrize(354 'mask, expected', (355 (8, '255.0.0.0'),356 (24, '255.255.255.0'),357 (25, '255.255.255.128'),358 ))359def test_dotted_netmask(mask, expected):360 assert dotted_netmask(mask) == expected361362363http_proxies = {'http': 'http://http.proxy',364 'http://some.host': 'http://some.host.proxy'}365all_proxies = {'all': 'socks5://http.proxy',366 'all://some.host': 'socks5://some.host.proxy'}367mixed_proxies = {'http': 'http://http.proxy',368 'http://some.host': 'http://some.host.proxy',369 'all': 'socks5://http.proxy'}370@pytest.mark.parametrize(371 'url, expected, proxies', (372 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),373 ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),374 ('hTTp:///path', 'http://http.proxy', http_proxies),375 ('hTTps://Other.Host', None, http_proxies),376 ('file:///etc/motd', None, http_proxies),377378 ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),379 ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),380 ('hTTp:///path', 'socks5://http.proxy', all_proxies),381 ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),382383 ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),384 ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),385 ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),386 ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),387 ('https://', 'socks5://http.proxy', mixed_proxies),388 # XXX: unsure whether this is reasonable behavior389 ('file:///etc/motd', 'socks5://http.proxy', all_proxies),390 ))391def test_select_proxies(url, expected, proxies):392 """Make sure we can select per-host proxies correctly."""393 assert select_proxy(url, proxies) == expected394395396@pytest.mark.parametrize(397 'value, expected', (398 ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),399 ('key_without_value', {'key_without_value': None})400 ))401def test_parse_dict_header(value, expected):402 assert parse_dict_header(value) == expected403404405@pytest.mark.parametrize(406 'value, expected', (407 (408 CaseInsensitiveDict(),409 None410 ),411 (412 CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),413 'utf-8'414 ),415 (416 CaseInsensitiveDict({'content-type': 'text/plain'}),417 'ISO-8859-1'418 ),419 ))420def test_get_encoding_from_headers(value, expected):421 assert get_encoding_from_headers(value) == expected422423424@pytest.mark.parametrize(425 'value, length', (426 ('', 0),427 ('T', 1),428 ('Test', 4),429 ('Cont', 0),430 ('Other', -5),431 ('Content', None),432 ))433def test_iter_slices(value, length):434 if length is None or (length <= 0 and len(value) > 0):435 # Reads all content at once436 assert len(list(iter_slices(value, length))) == 1437 else:438 assert len(list(iter_slices(value, 1))) == length439440441@pytest.mark.parametrize(442 'value, expected', (443 (444 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',445 [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]446 ),447 (448 '<http:/.../front.jpeg>',449 [{'url': 'http:/.../front.jpeg'}]450 ),451 (452 '<http:/.../front.jpeg>;',453 [{'url': 'http:/.../front.jpeg'}]454 ),455 (456 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',457 [458 {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},459 {'url': 'http://.../back.jpeg'}460 ]461 ),462 ))463def test_parse_header_links(value, expected):464 assert parse_header_links(value) == expected465466467@pytest.mark.parametrize(468 'value, expected', (469 ('example.com/path', 'http://example.com/path'),470 ('//example.com/path', 'http://example.com/path'),471 ))472def test_prepend_scheme_if_needed(value, expected):473 assert prepend_scheme_if_needed(value, 'http') == expected474475476@pytest.mark.parametrize(477 'value, expected', (478 ('T', 'T'),479 (b'T', 'T'),480 (u'T', 'T'),481 ))482def test_to_native_string(value, expected):483 assert to_native_string(value) == expected484485486@pytest.mark.parametrize(487 'url, expected', (488 ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),489 ('http://example.com/path', 'http://example.com/path'),490 ('//u:p@example.com/path', '//example.com/path'),491 ('//example.com/path', '//example.com/path'),492 ('example.com/path', '//example.com/path'),493 ('scheme:u:p@example.com/path', 'scheme://example.com/path'),494 ))495def test_urldefragauth(url, expected):496 assert urldefragauth(url) == expected497498499@pytest.mark.parametrize(500 'url, expected', (501 ('http://192.168.0.1:5000/', True),502 ('http://192.168.0.1/', True),503 ('http://172.16.1.1/', True),504 ('http://172.16.1.1:5000/', True),505 ('http://localhost.localdomain:5000/v1.0/', True),506 ('http://172.16.1.12/', False),507 ('http://172.16.1.12:5000/', False),508 ('http://google.com:5000/v1.0/', False),509 ))510def test_should_bypass_proxies(url, expected, monkeypatch):511 """Tests for function should_bypass_proxies to check if proxy512 can be bypassed or not513 """514 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')515 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')516 assert should_bypass_proxies(url) == expected517518@pytest.mark.parametrize(519 'cookiejar', (520 compat.cookielib.CookieJar(),521 RequestsCookieJar()522 ))523def test_add_dict_to_cookiejar(cookiejar):524 """Ensure add_dict_to_cookiejar works for525 non-RequestsCookieJar CookieJars526 """527 cookiedict = {'test': 'cookies',528 'good': 'cookies'}529 cj = add_dict_to_cookiejar(cookiejar, cookiedict)530 cookies = dict((cookie.name, cookie.value) for cookie in cj)531 assert cookiedict == cookies