Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

555 lines · 17.2 KiB · Python

Last changed by

Merge pull request #3809 from JungWinter/masterCory Benfieldbefore adoptione2bd1f9

History of this file

Take it

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

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

lines 1–2why, one step back
1# -*- coding: utf-8 -*-
2

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 3–6why, one step back
3from io import BytesIO
45import pytest6from requests import compat

Merge pull request #3809 from JungWinter/masterCory Benfieldbefore adoptione2bd1f9

line 7why, one step back
7from requests.cookies import RequestsCookieJar

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 8–15why, one step back
8from requests.structures import CaseInsensitiveDict
9from 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,

Merge pull request #3195 from kumarvaradarajulu/no_proxy_fixIan Cordascobefore adoption12e3631

line 16why, one step back
16 requote_uri, select_proxy, should_bypass_proxies, super_len,

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 17–18why, one step back
17 to_key_val_list, to_native_string,
18 unquote_header_value, unquote_unreserved,

Merge pull request #3627 from nateprewitt/remove_update_callCory Benfieldbefore adoption595a409

line 19why, one step back
19 urldefragauth, add_dict_to_cookiejar)

Merge pull request #3695 from nateprewitt/idna_bypassCory Benfieldbefore adoption5c45494

line 20why, one step back
20from requests._internal_utils import unicode_is_ascii

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 21–45why, one step back
21
22from .compat import StringIO, cStringIO232425class TestSuperLen:2627 @pytest.mark.parametrize(28 'stream, value', (29 (StringIO.StringIO, 'Test'),30 (BytesIO, b'Test'),31 pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),32 ))33 def test_io_streams(self, stream, value):34 """Ensures that we properly deal with different kinds of IO streams."""35 assert super_len(stream()) == 036 assert super_len(stream(value)) == 43738 def test_super_len_correctly_calculates_len_of_partially_read_file(self):39 """Ensure that we handle partially consumed file like objects."""40 s = StringIO.StringIO()41 s.write('foobarbogus')42 assert super_len(s) == 04344 @pytest.mark.parametrize('error', [IOError, OSError])45 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

line 46why, one step back
46 """If tell() raises errors, assume the cursor is at position zero."""

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 47–55why, one step back
47 class BoomFile(object):
48 def __len__(self):49 return 55051 def tell(self):52 raise error()5354 assert super_len(BoomFile()) == 055

Merge pull request #3625 from mie00/tellioerrorCory Benfieldbefore adoption83fcabc

lines 56–67why, one step back
56 @pytest.mark.parametrize('error', [IOError, OSError])
57 def test_super_len_tell_ioerror(self, error):58 """Ensure that if tell gives an IOError super_len doesn't fail"""59 class NoLenBoomFile(object):60 def tell(self):61 raise error()6263 def seek(self, offset, whence):64 pass6566 assert super_len(NoLenBoomFile()) == 067

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 68–82why, one step back
68 def test_string(self):
69 assert super_len('Test') == 47071 @pytest.mark.parametrize(72 'mode, warnings_num', (73 ('r', 1),74 ('rb', 0),75 ))76 def test_file(self, tmpdir, mode, warnings_num, recwarn):77 file_obj = tmpdir.join('test.txt')78 file_obj.write('Test')79 with file_obj.open(mode) as fd:80 assert super_len(fd) == 481 assert len(recwarn) == warnings_num82

Merge pull request #3535 from nateprewitt/3339_avoid_getvaluesCory Benfieldbefore adoption5524472

lines 83–110why, one step back
83 def test_super_len_with__len__(self):
84 foo = [1,2,3,4]85 len_foo = super_len(foo)86 assert len_foo == 48788 def test_super_len_with_no__len__(self):89 class LenFile(object):90 def __init__(self):91 self.len = 59293 assert super_len(LenFile()) == 59495 def test_super_len_with_tell(self):96 foo = StringIO.StringIO('12345')97 assert super_len(foo) == 598 foo.read(2)99 assert super_len(foo) == 3100101 def test_super_len_with_fileno(self):102 with open(__file__, 'rb') as f:103 length = super_len(f)104 file_data = f.read()105 assert length == len(file_data)106107 def test_super_len_with_no_matches(self):108 """Ensure that objects without any length methods default to 0"""109 assert super_len(object()) == 0110

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 111–147why, one step back
111
112class TestToKeyValList:113114 @pytest.mark.parametrize(115 'value, expected', (116 ([('key', 'val')], [('key', 'val')]),117 ((('key', 'val'), ), [('key', 'val')]),118 ({'key': 'val'}, [('key', 'val')]),119 (None, None)120 ))121 def test_valid(self, value, expected):122 assert to_key_val_list(value) == expected123124 def test_invalid(self):125 with pytest.raises(ValueError):126 to_key_val_list('string')127128129class TestUnquoteHeaderValue:130131 @pytest.mark.parametrize(132 'value, expected', (133 (None, None),134 ('Test', 'Test'),135 ('"Test"', 'Test'),136 ('"Test\\\\"', 'Test\\'),137 ('"\\\\Comp\\Res"', '\\Comp\\Res'),138 ))139 def test_valid(self, value, expected):140 assert unquote_header_value(value) == expected141142 def test_is_filename(self):143 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'144145146class TestGetEnvironProxies:147 """Ensures that IP addresses are correctly matches with ranges

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

lines 148–149why, one step back
148 in no_proxy variable.
149 """

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 150–276why, one step back
150
151 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])152 def no_proxy(self, request, monkeypatch):153 monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')154155 @pytest.mark.parametrize(156 'url', (157 'http://192.168.0.1:5000/',158 'http://192.168.0.1/',159 'http://172.16.1.1/',160 'http://172.16.1.1:5000/',161 'http://localhost.localdomain:5000/v1.0/',162 ))163 def test_bypass(self, url):164 assert get_environ_proxies(url) == {}165166 @pytest.mark.parametrize(167 'url', (168 'http://192.168.1.1:5000/',169 'http://192.168.1.1/',170 'http://www.requests.com/',171 ))172 def test_not_bypass(self, url):173 assert get_environ_proxies(url) != {}174175176class TestIsIPv4Address:177178 def test_valid(self):179 assert is_ipv4_address('8.8.8.8')180181 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))182 def test_invalid(self, value):183 assert not is_ipv4_address(value)184185186class TestIsValidCIDR:187188 def test_valid(self):189 assert is_valid_cidr('192.168.1.0/24')190191 @pytest.mark.parametrize(192 'value', (193 '8.8.8.8',194 '192.168.1.0/a',195 '192.168.1.0/128',196 '192.168.1.0/-1',197 '192.168.1.999/24',198 ))199 def test_invalid(self, value):200 assert not is_valid_cidr(value)201202203class TestAddressInNetwork:204205 def test_valid(self):206 assert address_in_network('192.168.1.1', '192.168.1.0/24')207208 def test_invalid(self):209 assert not address_in_network('172.16.0.1', '192.168.1.0/24')210211212class TestGuessFilename:213214 @pytest.mark.parametrize(215 'value', (1, type('Fake', (object,), {'name': 1})()),216 )217 def test_guess_filename_invalid(self, value):218 assert guess_filename(value) is None219220 @pytest.mark.parametrize(221 'value, expected_type', (222 (b'value', compat.bytes),223 (b'value'.decode('utf-8'), compat.str)224 ))225 def test_guess_filename_valid(self, value, expected_type):226 obj = type('Fake', (object,), {'name': value})()227 result = guess_filename(obj)228 assert result == value229 assert isinstance(result, expected_type)230231232class TestContentEncodingDetection:233234 def test_none(self):235 encodings = get_encodings_from_content('')236 assert not len(encodings)237238 @pytest.mark.parametrize(239 'content', (240 # HTML5 meta charset attribute241 '<meta charset="UTF-8">',242 # HTML4 pragma directive243 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',244 # XHTML 1.x served with text/html MIME type245 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',246 # XHTML 1.x served as XML247 '<?xml version="1.0" encoding="UTF-8"?>',248 ))249 def test_pragmas(self, content):250 encodings = get_encodings_from_content(content)251 assert len(encodings) == 1252 assert encodings[0] == 'UTF-8'253254 def test_precedence(self):255 content = '''256 <?xml version="1.0" encoding="XML"?>257 <meta charset="HTML5">258 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />259 '''.strip()260 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']261262263class TestGuessJSONUTF:264265 @pytest.mark.parametrize(266 'encoding', (267 'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',268 'utf-32-be', 'utf-32-le'269 ))270 def test_encoded(self, encoding):271 data = '{}'.encode(encoding)272 assert guess_json_utf(data) == encoding273274 def test_bad_utf_like_encoding(self):275 assert guess_json_utf(b'\x00\x00\x00\x00') is None276

Merge pull request #3791 from evgen231/masterCory Benfieldbefore adoptionb9d282b

lines 277–287why, one step back
277 @pytest.mark.parametrize(
278 ('encoding', 'expected'), (279 ('utf-16-be', 'utf-16'),280 ('utf-16-le', 'utf-16'),281 ('utf-32-be', 'utf-32'),282 ('utf-32-le', 'utf-32')283 ))284 def test_guess_by_bom(self, encoding, expected):285 data = u'\ufeff{}'.encode(encoding)286 assert guess_json_utf(data) == expected287

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 288–343why, one step back
288
289USER = PASSWORD = "%!*'();:@&=+$,/?#[] "290ENCODED_USER = compat.quote(USER, '')291ENCODED_PASSWORD = compat.quote(PASSWORD, '')292293294@pytest.mark.parametrize(295 'url, auth', (296 (297 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +298 'request.com/url.html#test',299 (USER, PASSWORD)300 ),301 (302 'http://user:pass@complex.url.com/path?query=yes',303 ('user', 'pass')304 ),305 (306 'http://user:pass%20pass@complex.url.com/path?query=yes',307 ('user', 'pass pass')308 ),309 (310 'http://user:pass pass@complex.url.com/path?query=yes',311 ('user', 'pass pass')312 ),313 (314 'http://user%25user:pass@complex.url.com/path?query=yes',315 ('user%user', 'pass')316 ),317 (318 'http://user:pass%23pass@complex.url.com/path?query=yes',319 ('user', 'pass#pass')320 ),321 (322 'http://complex.url.com/path?query=yes',323 ('', '')324 ),325 ))326def test_get_auth_from_url(url, auth):327 assert get_auth_from_url(url) == auth328329330@pytest.mark.parametrize(331 'uri, expected', (332 (333 # Ensure requoting doesn't break expectations334 'http://example.com/fiz?buz=%25ppicture',335 'http://example.com/fiz?buz=%25ppicture',336 ),337 (338 # Ensure we handle unquoted percent signs in redirects339 'http://example.com/fiz?buz=%ppicture',340 'http://example.com/fiz?buz=%25ppicture',341 ),342 ))343def test_requote_uri_with_unquoted_percents(uri, expected):

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

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

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 345–374why, one step back
345 assert requote_uri(uri) == expected
346347348@pytest.mark.parametrize(349 'uri, expected', (350 (351 # Illegal bytes352 'http://example.com/?a=%--',353 'http://example.com/?a=%--',354 ),355 (356 # Reserved characters357 'http://example.com/?a=%300',358 'http://example.com/?a=00',359 )360 ))361def test_unquote_unreserved(uri, expected):362 assert unquote_unreserved(uri) == expected363364365@pytest.mark.parametrize(366 'mask, expected', (367 (8, '255.0.0.0'),368 (24, '255.255.255.0'),369 (25, '255.255.255.128'),370 ))371def test_dotted_netmask(mask, expected):372 assert dotted_netmask(mask) == expected373374

Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9

lines 375–378why, one step back
375http_proxies = {'http': 'http://http.proxy',
376 'http://some.host': 'http://some.host.proxy'}377all_proxies = {'all': 'socks5://http.proxy',378 'all://some.host': 'socks5://some.host.proxy'}

Merge pull request #3526 from shellhead/mixed-proxy-bugCory Benfieldbefore adoption3314259

lines 379–381why, one step back
379mixed_proxies = {'http': 'http://http.proxy',
380 'http://some.host': 'http://some.host.proxy',381 'all': 'socks5://http.proxy'}

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

line 382why, one step back
382@pytest.mark.parametrize(

Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9

lines 383–394why, one step back
383 'url, expected, proxies', (
384 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),385 ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),386 ('hTTp:///path', 'http://http.proxy', http_proxies),387 ('hTTps://Other.Host', None, http_proxies),388 ('file:///etc/motd', None, http_proxies),389390 ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),391 ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),392 ('hTTp:///path', 'socks5://http.proxy', all_proxies),393 ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),394

Merge pull request #3526 from shellhead/mixed-proxy-bugCory Benfieldbefore adoption3314259

lines 395–398why, one step back
395 ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),
396 ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),397 ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),398 ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),

Merge pull request #3530 from shellhead/mixed-proxy-bugCory Benfieldbefore adoption52b15f8

line 399why, one step back
399 ('https://', 'socks5://http.proxy', mixed_proxies),

Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9

lines 400–401why, one step back
400 # XXX: unsure whether this is reasonable behavior
401 ('file:///etc/motd', 'socks5://http.proxy', all_proxies),

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

line 402why, one step back
402 ))

Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9

line 403why, one step back
403def test_select_proxies(url, expected, proxies):

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 404–440why, one step back
404 """Make sure we can select per-host proxies correctly."""
405 assert select_proxy(url, proxies) == expected406407408@pytest.mark.parametrize(409 'value, expected', (410 ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),411 ('key_without_value', {'key_without_value': None})412 ))413def test_parse_dict_header(value, expected):414 assert parse_dict_header(value) == expected415416417@pytest.mark.parametrize(418 'value, expected', (419 (420 CaseInsensitiveDict(),421 None422 ),423 (424 CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),425 'utf-8'426 ),427 (428 CaseInsensitiveDict({'content-type': 'text/plain'}),429 'ISO-8859-1'430 ),431 ))432def test_get_encoding_from_headers(value, expected):433 assert get_encoding_from_headers(value) == expected434435436@pytest.mark.parametrize(437 'value, length', (438 ('', 0),439 ('T', 1),440 ('Test', 4),

adding in slice_length fix and test for chunk_size=None (#3370)Nate Prewittbefore adoption71050e9

lines 441–443why, one step back
441 ('Cont', 0),
442 ('Other', -5),443 ('Content', None),

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 444–445why, one step back
444 ))
445def test_iter_slices(value, length):

adding in slice_length fix and test for chunk_size=None (#3370)Nate Prewittbefore adoption71050e9

lines 446–450why, one step back
446 if length is None or (length <= 0 and len(value) > 0):
447 # Reads all content at once448 assert len(list(iter_slices(value, length))) == 1449 else:450 assert len(list(iter_slices(value, 1))) == length

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

line 451why, one step back
451

Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac

line 452why, one step back
452

updated urllib3 (v1.15.1)Kenneth Reitzbefore adoptionf69d8c1

lines 453–508why, one step back
453@pytest.mark.parametrize(
454 'value, expected', (455 (456 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',457 [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]458 ),459 (460 '<http:/.../front.jpeg>',461 [{'url': 'http:/.../front.jpeg'}]462 ),463 (464 '<http:/.../front.jpeg>;',465 [{'url': 'http:/.../front.jpeg'}]466 ),467 (468 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',469 [470 {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},471 {'url': 'http://.../back.jpeg'}472 ]473 ),474 ))475def test_parse_header_links(value, expected):476 assert parse_header_links(value) == expected477478479@pytest.mark.parametrize(480 'value, expected', (481 ('example.com/path', 'http://example.com/path'),482 ('//example.com/path', 'http://example.com/path'),483 ))484def test_prepend_scheme_if_needed(value, expected):485 assert prepend_scheme_if_needed(value, 'http') == expected486487488@pytest.mark.parametrize(489 'value, expected', (490 ('T', 'T'),491 (b'T', 'T'),492 (u'T', 'T'),493 ))494def test_to_native_string(value, expected):495 assert to_native_string(value) == expected496497498@pytest.mark.parametrize(499 'url, expected', (500 ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),501 ('http://example.com/path', 'http://example.com/path'),502 ('//u:p@example.com/path', '//example.com/path'),503 ('//example.com/path', '//example.com/path'),504 ('example.com/path', '//example.com/path'),505 ('scheme:u:p@example.com/path', 'scheme://example.com/path'),506 ))507def test_urldefragauth(url, expected):508 assert urldefragauth(url) == expected

Merge pull request #3195 from kumarvaradarajulu/no_proxy_fixIan Cordascobefore adoption12e3631

lines 509–522why, one step back
509
510511@pytest.mark.parametrize(512 'url, expected', (513 ('http://192.168.0.1:5000/', True),514 ('http://192.168.0.1/', True),515 ('http://172.16.1.1/', True),516 ('http://172.16.1.1:5000/', True),517 ('http://localhost.localdomain:5000/v1.0/', True),518 ('http://172.16.1.12/', False),519 ('http://172.16.1.12:5000/', False),520 ('http://google.com:5000/v1.0/', False),521 ))522def test_should_bypass_proxies(url, expected, monkeypatch):

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

lines 523–524why, one step back
523 """Tests for function should_bypass_proxies to check if proxy
524 can be bypassed or not

Merge pull request #3195 from kumarvaradarajulu/no_proxy_fixIan Cordascobefore adoption12e3631

lines 525–528why, one step back
525 """
526 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')527 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')528 assert should_bypass_proxies(url) == expected

Merge pull request #3627 from nateprewitt/remove_update_callCory Benfieldbefore adoption595a409

line 529why, one step back
529

Merge pull request #3695 from nateprewitt/idna_bypassCory Benfieldbefore adoption5c45494

line 530why, one step back
530

Merge pull request #3627 from nateprewitt/remove_update_callCory Benfieldbefore adoption595a409

lines 531–544why, one step back
531@pytest.mark.parametrize(
532 'cookiejar', (533 compat.cookielib.CookieJar(),534 RequestsCookieJar()535 ))536def test_add_dict_to_cookiejar(cookiejar):537 """Ensure add_dict_to_cookiejar works for538 non-RequestsCookieJar CookieJars539 """540 cookiedict = {'test': 'cookies',541 'good': 'cookies'}542 cj = add_dict_to_cookiejar(cookiejar, cookiedict)543 cookies = dict((cookie.name, cookie.value) for cookie in cj)544 assert cookiedict == cookies

Merge pull request #3695 from nateprewitt/idna_bypassCory Benfieldbefore adoption5c45494

lines 545–555why, one step back
545
546547@pytest.mark.parametrize(548 'value, expected', (549 (u'test', True),550 (u'æíöû', False),551 (u'ジェーピーニック', False),552 )553)554def test_unicode_is_ascii(value, expected):555 assert unicode_is_ascii(value) is expected