test_utils.py
This file
Path
tests/test_utils.py
503 lines · 15.6 KiB · Python
Last changed by
Merge pull request #3535 from nateprewitt/3339_avoid_getvaluesCory Benfieldbefore adoption5524472
History of this fileTake it
Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
lines 1–2why, one step back1# -*- coding: utf-8 -*-2Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 3–6why, one step back3from io import BytesIO45import pytest6from requests import compatMerge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
line 7why, one step back7from requests.structures import CaseInsensitiveDictAdded tests module.Dmitry Dygalobefore adoption18b26d2
lines 8–9why, one step back8from requests.utils import (9 address_in_network, dotted_netmask,Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 10–14why, one step back10 get_auth_from_url, get_encoding_from_headers,11 get_encodings_from_content, get_environ_proxies,12 guess_filename, guess_json_utf, is_ipv4_address,13 is_valid_cidr, iter_slices, parse_dict_header,14 parse_header_links, prepend_scheme_if_needed,Merge pull request #3195 from kumarvaradarajulu/no_proxy_fixIan Cordascobefore adoption12e3631
line 15why, one step back15 requote_uri, select_proxy, should_bypass_proxies, super_len,Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 16–18why, one step back16 to_key_val_list, to_native_string,17 unquote_header_value, unquote_unreserved,18 urldefragauth)Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 19–23why, one step back1920from .compat import StringIO, cStringIO212223class TestSuperLen:Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
line 24why, one step back24Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 25–28why, one step back25 @pytest.mark.parametrize(26 'stream, value', (27 (StringIO.StringIO, 'Test'),28 (BytesIO, b'Test'),syntax changesKenneth Reitzbefore adoptionbbadf47
line 29why, one step back29 pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 30–31why, one step back30 ))31 def test_io_streams(self, stream, value):syntax changesKenneth Reitzbefore adoptionbbadf47
line 32why, one step back32 """Ensures that we properly deal with different kinds of IO streams."""Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 33–40why, one step back33 assert super_len(stream()) == 034 assert super_len(stream(value)) == 43536 def test_super_len_correctly_calculates_len_of_partially_read_file(self):37 """Ensure that we handle partially consumed file like objects."""38 s = StringIO.StringIO()39 s.write('foobarbogus')40 assert super_len(s) == 0Merge pull request #3036 from Lukasa/issue/3035Ian Cordascobefore adoption190cddd
lines 41–43why, one step back4142 @pytest.mark.parametrize('error', [IOError, OSError])43 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
line 44why, one step back44 """If tell() raises errors, assume the cursor is at position zero."""Merge pull request #3036 from Lukasa/issue/3035Ian Cordascobefore adoption190cddd
lines 45–52why, one step back45 class BoomFile(object):46 def __len__(self):47 return 54849 def tell(self):50 raise error()5152 assert super_len(BoomFile()) == 0Added tests module.Dmitry Dygalobefore adoption18b26d2
line 53why, one step back53Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 54–55why, one step back54 def test_string(self):55 assert super_len('Test') == 4Added tests module.Dmitry Dygalobefore adoption18b26d2
line 56why, one step back56Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 57–68why, one step back57 @pytest.mark.parametrize(58 'mode, warnings_num', (59 ('r', 1),60 ('rb', 0),61 ))62 def test_file(self, tmpdir, mode, warnings_num, recwarn):63 file_obj = tmpdir.join('test.txt')64 file_obj.write('Test')65 with file_obj.open(mode) as fd:66 assert super_len(fd) == 467 assert len(recwarn) == warnings_num68Merge pull request #3535 from nateprewitt/3339_avoid_getvaluesCory Benfieldbefore adoption5524472
lines 69–96why, one step back69 def test_super_len_with__len__(self):70 foo = [1,2,3,4]71 len_foo = super_len(foo)72 assert len_foo == 47374 def test_super_len_with_no__len__(self):75 class LenFile(object):76 def __init__(self):77 self.len = 57879 assert super_len(LenFile()) == 58081 def test_super_len_with_tell(self):82 foo = StringIO.StringIO('12345')83 assert super_len(foo) == 584 foo.read(2)85 assert super_len(foo) == 38687 def test_super_len_with_fileno(self):88 with open(__file__, 'rb') as f:89 length = super_len(f)90 file_data = f.read()91 assert length == len(file_data)9293 def test_super_len_with_no_matches(self):94 """Ensure that objects without any length methods default to 0"""95 assert super_len(object()) == 096Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 97–131why, one step back9798class TestToKeyValList:99100 @pytest.mark.parametrize(101 'value, expected', (102 ([('key', 'val')], [('key', 'val')]),103 ((('key', 'val'), ), [('key', 'val')]),104 ({'key': 'val'}, [('key', 'val')]),105 (None, None)106 ))107 def test_valid(self, value, expected):108 assert to_key_val_list(value) == expected109110 def test_invalid(self):111 with pytest.raises(ValueError):112 to_key_val_list('string')113114115class TestUnquoteHeaderValue:116117 @pytest.mark.parametrize(118 'value, expected', (119 (None, None),120 ('Test', 'Test'),121 ('"Test"', 'Test'),122 ('"Test\\\\"', 'Test\\'),123 ('"\\\\Comp\\Res"', '\\Comp\\Res'),124 ))125 def test_valid(self, value, expected):126 assert unquote_header_value(value) == expected127128 def test_is_filename(self):129 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'130131Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 132–133why, one step back132class TestGetEnvironProxies:133 """Ensures that IP addresses are correctly matches with rangesMerge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
lines 134–135why, one step back134 in no_proxy variable.135 """Added tests module.Dmitry Dygalobefore adoption18b26d2
line 136why, one step back136Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 137–139why, one step back137 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])138 def no_proxy(self, request, monkeypatch):139 monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 140–147why, one step back140141 @pytest.mark.parametrize(142 'url', (143 'http://192.168.0.1:5000/',144 'http://192.168.0.1/',145 'http://172.16.1.1/',146 'http://172.16.1.1:5000/',147 'http://localhost.localdomain:5000/v1.0/',syntax changesKenneth Reitzbefore adoptionbbadf47
line 148why, one step back148 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 149–156why, one step back149 def test_bypass(self, url):150 assert get_environ_proxies(url) == {}151152 @pytest.mark.parametrize(153 'url', (154 'http://192.168.1.1:5000/',155 'http://192.168.1.1/',156 'http://www.requests.com/',syntax changesKenneth Reitzbefore adoptionbbadf47
line 157why, one step back157 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 158–183why, one step back158 def test_not_bypass(self, url):159 assert get_environ_proxies(url) != {}160161162class TestIsIPv4Address:163164 def test_valid(self):165 assert is_ipv4_address('8.8.8.8')166167 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))168 def test_invalid(self, value):169 assert not is_ipv4_address(value)170171172class TestIsValidCIDR:173174 def test_valid(self):175 assert is_valid_cidr('192.168.1.0/24')176177 @pytest.mark.parametrize(178 'value', (179 '8.8.8.8',180 '192.168.1.0/a',181 '192.168.1.0/128',182 '192.168.1.0/-1',183 '192.168.1.999/24',syntax changesKenneth Reitzbefore adoptionbbadf47
line 184why, one step back184 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 185–209why, one step back185 def test_invalid(self, value):186 assert not is_valid_cidr(value)187188189class TestAddressInNetwork:190191 def test_valid(self):192 assert address_in_network('192.168.1.1', '192.168.1.0/24')193194 def test_invalid(self):195 assert not address_in_network('172.16.0.1', '192.168.1.0/24')196197198class TestGuessFilename:199200 @pytest.mark.parametrize(201 'value', (1, type('Fake', (object,), {'name': 1})()),202 )203 def test_guess_filename_invalid(self, value):204 assert guess_filename(value) is None205206 @pytest.mark.parametrize(207 'value, expected_type', (208 (b'value', compat.bytes),209 (b'value'.decode('utf-8'), compat.str)syntax changesKenneth Reitzbefore adoptionbbadf47
line 210why, one step back210 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 211–233why, one step back211 def test_guess_filename_valid(self, value, expected_type):212 obj = type('Fake', (object,), {'name': value})()213 result = guess_filename(obj)214 assert result == value215 assert isinstance(result, expected_type)216217218class TestContentEncodingDetection:219220 def test_none(self):221 encodings = get_encodings_from_content('')222 assert not len(encodings)223224 @pytest.mark.parametrize(225 'content', (226 # HTML5 meta charset attribute227 '<meta charset="UTF-8">',228 # HTML4 pragma directive229 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',230 # XHTML 1.x served with text/html MIME type231 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',232 # XHTML 1.x served as XML233 '<?xml version="1.0" encoding="UTF-8"?>',syntax changesKenneth Reitzbefore adoptionbbadf47
line 234why, one step back234 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 235–248why, one step back235 def test_pragmas(self, content):236 encodings = get_encodings_from_content(content)237 assert len(encodings) == 1238 assert encodings[0] == 'UTF-8'239240 def test_precedence(self):241 content = '''242 <?xml version="1.0" encoding="XML"?>243 <meta charset="HTML5">244 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />245 '''.strip()246 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']247248Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 249–263why, one step back249class TestGuessJSONUTF:250251 @pytest.mark.parametrize(252 'encoding', (253 'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',254 'utf-32-be', 'utf-32-le'255 ))256 def test_encoded(self, encoding):257 data = '{}'.encode(encoding)258 assert guess_json_utf(data) == encoding259260 def test_bad_utf_like_encoding(self):261 assert guess_json_utf(b'\x00\x00\x00\x00') is None262263Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 264–295why, one step back264USER = PASSWORD = "%!*'();:@&=+$,/?#[] "265ENCODED_USER = compat.quote(USER, '')266ENCODED_PASSWORD = compat.quote(PASSWORD, '')267268269@pytest.mark.parametrize(270 'url, auth', (271 (272 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +273 'request.com/url.html#test',274 (USER, PASSWORD)275 ),276 (277 'http://user:pass@complex.url.com/path?query=yes',278 ('user', 'pass')279 ),280 (281 'http://user:pass%20pass@complex.url.com/path?query=yes',282 ('user', 'pass pass')283 ),284 (285 'http://user:pass pass@complex.url.com/path?query=yes',286 ('user', 'pass pass')287 ),288 (289 'http://user%25user:pass@complex.url.com/path?query=yes',290 ('user%user', 'pass')291 ),292 (293 'http://user:pass%23pass@complex.url.com/path?query=yes',294 ('user', 'pass#pass')295 ),Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 296–299why, one step back296 (297 'http://complex.url.com/path?query=yes',298 ('', '')299 ),syntax changesKenneth Reitzbefore adoptionbbadf47
line 300why, one step back300 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 301–316why, one step back301def test_get_auth_from_url(url, auth):302 assert get_auth_from_url(url) == auth303304305@pytest.mark.parametrize(306 'uri, expected', (307 (308 # Ensure requoting doesn't break expectations309 'http://example.com/fiz?buz=%25ppicture',310 'http://example.com/fiz?buz=%25ppicture',311 ),312 (313 # Ensure we handle unquoted percent signs in redirects314 'http://example.com/fiz?buz=%ppicture',315 'http://example.com/fiz?buz=%25ppicture',316 ),syntax changesKenneth Reitzbefore adoptionbbadf47
line 317why, one step back317 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
line 318why, one step back318def test_requote_uri_with_unquoted_percents(uri, expected):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
line 319why, one step back319 """See: https://github.com/kennethreitz/requests/issues/2356"""Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 320–323why, one step back320 assert requote_uri(uri) == expected321322323@pytest.mark.parametrize(Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 324–340why, one step back324 'uri, expected', (325 (326 # Illegal bytes327 'http://example.com/?a=%--',328 'http://example.com/?a=%--',329 ),330 (331 # Reserved characters332 'http://example.com/?a=%300',333 'http://example.com/?a=00',334 )335 ))336def test_unquote_unreserved(uri, expected):337 assert unquote_unreserved(uri) == expected338339340@pytest.mark.parametrize(Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 341–344why, one step back341 'mask, expected', (342 (8, '255.0.0.0'),343 (24, '255.255.255.0'),344 (25, '255.255.255.128'),syntax changesKenneth Reitzbefore adoptionbbadf47
line 345why, one step back345 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 346–349why, one step back346def test_dotted_netmask(mask, expected):347 assert dotted_netmask(mask) == expected348349Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9
lines 350–353why, one step back350http_proxies = {'http': 'http://http.proxy',351 'http://some.host': 'http://some.host.proxy'}352all_proxies = {'all': 'socks5://http.proxy',353 'all://some.host': 'socks5://some.host.proxy'}Merge pull request #3526 from shellhead/mixed-proxy-bugCory Benfieldbefore adoption3314259
lines 354–356why, one step back354mixed_proxies = {'http': 'http://http.proxy',355 'http://some.host': 'http://some.host.proxy',356 'all': 'socks5://http.proxy'}Added tests module.Dmitry Dygalobefore adoption18b26d2
line 357why, one step back357@pytest.mark.parametrize(Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9
lines 358–369why, one step back358 'url, expected, proxies', (359 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),360 ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),361 ('hTTp:///path', 'http://http.proxy', http_proxies),362 ('hTTps://Other.Host', None, http_proxies),363 ('file:///etc/motd', None, http_proxies),364365 ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),366 ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),367 ('hTTp:///path', 'socks5://http.proxy', all_proxies),368 ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),369Merge pull request #3526 from shellhead/mixed-proxy-bugCory Benfieldbefore adoption3314259
lines 370–373why, one step back370 ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),371 ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),372 ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),373 ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),Merge pull request #3530 from shellhead/mixed-proxy-bugCory Benfieldbefore adoption52b15f8
line 374why, one step back374 ('https://', 'socks5://http.proxy', mixed_proxies),Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9
lines 375–376why, one step back375 # XXX: unsure whether this is reasonable behavior376 ('file:///etc/motd', 'socks5://http.proxy', all_proxies),syntax changesKenneth Reitzbefore adoptionbbadf47
line 377why, one step back377 ))Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9
line 378why, one step back378def test_select_proxies(url, expected, proxies):Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 379–380why, one step back379 """Make sure we can select per-host proxies correctly."""380 assert select_proxy(url, proxies) == expectedMerge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 381–415why, one step back381382383@pytest.mark.parametrize(384 'value, expected', (385 ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),386 ('key_without_value', {'key_without_value': None})387 ))388def test_parse_dict_header(value, expected):389 assert parse_dict_header(value) == expected390391392@pytest.mark.parametrize(393 'value, expected', (394 (395 CaseInsensitiveDict(),396 None397 ),398 (399 CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),400 'utf-8'401 ),402 (403 CaseInsensitiveDict({'content-type': 'text/plain'}),404 'ISO-8859-1'405 ),406 ))407def test_get_encoding_from_headers(value, expected):408 assert get_encoding_from_headers(value) == expected409410411@pytest.mark.parametrize(412 'value, length', (413 ('', 0),414 ('T', 1),415 ('Test', 4),adding in slice_length fix and test for chunk_size=None (#3370)Nate Prewittbefore adoption71050e9
lines 416–418why, one step back416 ('Cont', 0),417 ('Other', -5),418 ('Content', None),Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 419–420why, one step back419 ))420def test_iter_slices(value, length):adding in slice_length fix and test for chunk_size=None (#3370)Nate Prewittbefore adoption71050e9
lines 421–425why, one step back421 if length is None or (length <= 0 and len(value) > 0):422 # Reads all content at once423 assert len(list(iter_slices(value, length))) == 1424 else:425 assert len(list(iter_slices(value, 1))) == lengthMerge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
line 426why, one step back426Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac
line 427why, one step back427Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 428–483why, one step back428@pytest.mark.parametrize(429 'value, expected', (430 (431 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',432 [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]433 ),434 (435 '<http:/.../front.jpeg>',436 [{'url': 'http:/.../front.jpeg'}]437 ),438 (439 '<http:/.../front.jpeg>;',440 [{'url': 'http:/.../front.jpeg'}]441 ),442 (443 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',444 [445 {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},446 {'url': 'http://.../back.jpeg'}447 ]448 ),449 ))450def test_parse_header_links(value, expected):451 assert parse_header_links(value) == expected452453454@pytest.mark.parametrize(455 'value, expected', (456 ('example.com/path', 'http://example.com/path'),457 ('//example.com/path', 'http://example.com/path'),458 ))459def test_prepend_scheme_if_needed(value, expected):460 assert prepend_scheme_if_needed(value, 'http') == expected461462463@pytest.mark.parametrize(464 'value, expected', (465 ('T', 'T'),466 (b'T', 'T'),467 (u'T', 'T'),468 ))469def test_to_native_string(value, expected):470 assert to_native_string(value) == expected471472473@pytest.mark.parametrize(474 'url, expected', (475 ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),476 ('http://example.com/path', 'http://example.com/path'),477 ('//u:p@example.com/path', '//example.com/path'),478 ('//example.com/path', '//example.com/path'),479 ('example.com/path', '//example.com/path'),480 ('scheme:u:p@example.com/path', 'scheme://example.com/path'),481 ))482def test_urldefragauth(url, expected):483 assert urldefragauth(url) == expectedMerge pull request #3195 from kumarvaradarajulu/no_proxy_fixIan Cordascobefore adoption12e3631
lines 484–497why, one step back484485486@pytest.mark.parametrize(487 'url, expected', (488 ('http://192.168.0.1:5000/', True),489 ('http://192.168.0.1/', True),490 ('http://172.16.1.1/', True),491 ('http://172.16.1.1:5000/', True),492 ('http://localhost.localdomain:5000/v1.0/', True),493 ('http://172.16.1.12/', False),494 ('http://172.16.1.12:5000/', False),495 ('http://google.com:5000/v1.0/', False),496 ))497def test_should_bypass_proxies(url, expected, monkeypatch):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
lines 498–499why, one step back498 """Tests for function should_bypass_proxies to check if proxy499 can be bypassed or notMerge pull request #3195 from kumarvaradarajulu/no_proxy_fixIan Cordascobefore adoption12e3631
lines 500–503why, one step back500 """501 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')502 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')503 assert should_bypass_proxies(url) == expected