test_utils.py
This file
Path
tests/test_utils.py
475 lines · 14.8 KiB · Python
Last changed by
Merge pull request #3530 from shellhead/mixed-proxy-bugCory Benfieldbefore adoption52b15f8
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–103why, 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_num686970class TestToKeyValList:7172 @pytest.mark.parametrize(73 'value, expected', (74 ([('key', 'val')], [('key', 'val')]),75 ((('key', 'val'), ), [('key', 'val')]),76 ({'key': 'val'}, [('key', 'val')]),77 (None, None)78 ))79 def test_valid(self, value, expected):80 assert to_key_val_list(value) == expected8182 def test_invalid(self):83 with pytest.raises(ValueError):84 to_key_val_list('string')858687class TestUnquoteHeaderValue:8889 @pytest.mark.parametrize(90 'value, expected', (91 (None, None),92 ('Test', 'Test'),93 ('"Test"', 'Test'),94 ('"Test\\\\"', 'Test\\'),95 ('"\\\\Comp\\Res"', '\\Comp\\Res'),96 ))97 def test_valid(self, value, expected):98 assert unquote_header_value(value) == expected99100 def test_is_filename(self):101 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'102103Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 104–105why, one step back104class TestGetEnvironProxies:105 """Ensures that IP addresses are correctly matches with rangesMerge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
lines 106–107why, one step back106 in no_proxy variable.107 """Added tests module.Dmitry Dygalobefore adoption18b26d2
line 108why, one step back108Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 109–111why, one step back109 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])110 def no_proxy(self, request, monkeypatch):111 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 112–119why, one step back112113 @pytest.mark.parametrize(114 'url', (115 'http://192.168.0.1:5000/',116 'http://192.168.0.1/',117 'http://172.16.1.1/',118 'http://172.16.1.1:5000/',119 'http://localhost.localdomain:5000/v1.0/',syntax changesKenneth Reitzbefore adoptionbbadf47
line 120why, one step back120 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 121–128why, one step back121 def test_bypass(self, url):122 assert get_environ_proxies(url) == {}123124 @pytest.mark.parametrize(125 'url', (126 'http://192.168.1.1:5000/',127 'http://192.168.1.1/',128 'http://www.requests.com/',syntax changesKenneth Reitzbefore adoptionbbadf47
line 129why, one step back129 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 130–155why, one step back130 def test_not_bypass(self, url):131 assert get_environ_proxies(url) != {}132133134class TestIsIPv4Address:135136 def test_valid(self):137 assert is_ipv4_address('8.8.8.8')138139 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))140 def test_invalid(self, value):141 assert not is_ipv4_address(value)142143144class TestIsValidCIDR:145146 def test_valid(self):147 assert is_valid_cidr('192.168.1.0/24')148149 @pytest.mark.parametrize(150 'value', (151 '8.8.8.8',152 '192.168.1.0/a',153 '192.168.1.0/128',154 '192.168.1.0/-1',155 '192.168.1.999/24',syntax changesKenneth Reitzbefore adoptionbbadf47
line 156why, one step back156 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 157–181why, one step back157 def test_invalid(self, value):158 assert not is_valid_cidr(value)159160161class TestAddressInNetwork:162163 def test_valid(self):164 assert address_in_network('192.168.1.1', '192.168.1.0/24')165166 def test_invalid(self):167 assert not address_in_network('172.16.0.1', '192.168.1.0/24')168169170class TestGuessFilename:171172 @pytest.mark.parametrize(173 'value', (1, type('Fake', (object,), {'name': 1})()),174 )175 def test_guess_filename_invalid(self, value):176 assert guess_filename(value) is None177178 @pytest.mark.parametrize(179 'value, expected_type', (180 (b'value', compat.bytes),181 (b'value'.decode('utf-8'), compat.str)syntax changesKenneth Reitzbefore adoptionbbadf47
line 182why, one step back182 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 183–205why, one step back183 def test_guess_filename_valid(self, value, expected_type):184 obj = type('Fake', (object,), {'name': value})()185 result = guess_filename(obj)186 assert result == value187 assert isinstance(result, expected_type)188189190class TestContentEncodingDetection:191192 def test_none(self):193 encodings = get_encodings_from_content('')194 assert not len(encodings)195196 @pytest.mark.parametrize(197 'content', (198 # HTML5 meta charset attribute199 '<meta charset="UTF-8">',200 # HTML4 pragma directive201 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',202 # XHTML 1.x served with text/html MIME type203 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',204 # XHTML 1.x served as XML205 '<?xml version="1.0" encoding="UTF-8"?>',syntax changesKenneth Reitzbefore adoptionbbadf47
line 206why, one step back206 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 207–220why, one step back207 def test_pragmas(self, content):208 encodings = get_encodings_from_content(content)209 assert len(encodings) == 1210 assert encodings[0] == 'UTF-8'211212 def test_precedence(self):213 content = '''214 <?xml version="1.0" encoding="XML"?>215 <meta charset="HTML5">216 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />217 '''.strip()218 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']219220Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 221–235why, one step back221class TestGuessJSONUTF:222223 @pytest.mark.parametrize(224 'encoding', (225 'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',226 'utf-32-be', 'utf-32-le'227 ))228 def test_encoded(self, encoding):229 data = '{}'.encode(encoding)230 assert guess_json_utf(data) == encoding231232 def test_bad_utf_like_encoding(self):233 assert guess_json_utf(b'\x00\x00\x00\x00') is None234235Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 236–267why, one step back236USER = PASSWORD = "%!*'();:@&=+$,/?#[] "237ENCODED_USER = compat.quote(USER, '')238ENCODED_PASSWORD = compat.quote(PASSWORD, '')239240241@pytest.mark.parametrize(242 'url, auth', (243 (244 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +245 'request.com/url.html#test',246 (USER, PASSWORD)247 ),248 (249 'http://user:pass@complex.url.com/path?query=yes',250 ('user', 'pass')251 ),252 (253 'http://user:pass%20pass@complex.url.com/path?query=yes',254 ('user', 'pass pass')255 ),256 (257 'http://user:pass pass@complex.url.com/path?query=yes',258 ('user', 'pass pass')259 ),260 (261 'http://user%25user:pass@complex.url.com/path?query=yes',262 ('user%user', 'pass')263 ),264 (265 'http://user:pass%23pass@complex.url.com/path?query=yes',266 ('user', 'pass#pass')267 ),Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 268–271why, one step back268 (269 'http://complex.url.com/path?query=yes',270 ('', '')271 ),syntax changesKenneth Reitzbefore adoptionbbadf47
line 272why, one step back272 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 273–288why, one step back273def test_get_auth_from_url(url, auth):274 assert get_auth_from_url(url) == auth275276277@pytest.mark.parametrize(278 'uri, expected', (279 (280 # Ensure requoting doesn't break expectations281 'http://example.com/fiz?buz=%25ppicture',282 'http://example.com/fiz?buz=%25ppicture',283 ),284 (285 # Ensure we handle unquoted percent signs in redirects286 'http://example.com/fiz?buz=%ppicture',287 'http://example.com/fiz?buz=%25ppicture',288 ),syntax changesKenneth Reitzbefore adoptionbbadf47
line 289why, one step back289 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
line 290why, one step back290def test_requote_uri_with_unquoted_percents(uri, expected):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
line 291why, one step back291 """See: https://github.com/kennethreitz/requests/issues/2356"""Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 292–295why, one step back292 assert requote_uri(uri) == expected293294295@pytest.mark.parametrize(Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 296–312why, one step back296 'uri, expected', (297 (298 # Illegal bytes299 'http://example.com/?a=%--',300 'http://example.com/?a=%--',301 ),302 (303 # Reserved characters304 'http://example.com/?a=%300',305 'http://example.com/?a=00',306 )307 ))308def test_unquote_unreserved(uri, expected):309 assert unquote_unreserved(uri) == expected310311312@pytest.mark.parametrize(Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 313–316why, one step back313 'mask, expected', (314 (8, '255.0.0.0'),315 (24, '255.255.255.0'),316 (25, '255.255.255.128'),syntax changesKenneth Reitzbefore adoptionbbadf47
line 317why, one step back317 ))Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 318–321why, one step back318def test_dotted_netmask(mask, expected):319 assert dotted_netmask(mask) == expected320321Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9
lines 322–325why, one step back322http_proxies = {'http': 'http://http.proxy',323 'http://some.host': 'http://some.host.proxy'}324all_proxies = {'all': 'socks5://http.proxy',325 'all://some.host': 'socks5://some.host.proxy'}Merge pull request #3526 from shellhead/mixed-proxy-bugCory Benfieldbefore adoption3314259
lines 326–328why, one step back326mixed_proxies = {'http': 'http://http.proxy',327 'http://some.host': 'http://some.host.proxy',328 'all': 'socks5://http.proxy'}Added tests module.Dmitry Dygalobefore adoption18b26d2
line 329why, one step back329@pytest.mark.parametrize(Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9
lines 330–341why, one step back330 'url, expected, proxies', (331 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),332 ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),333 ('hTTp:///path', 'http://http.proxy', http_proxies),334 ('hTTps://Other.Host', None, http_proxies),335 ('file:///etc/motd', None, http_proxies),336337 ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),338 ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),339 ('hTTp:///path', 'socks5://http.proxy', all_proxies),340 ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),341Merge pull request #3526 from shellhead/mixed-proxy-bugCory Benfieldbefore adoption3314259
lines 342–345why, one step back342 ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),343 ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),344 ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),345 ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),Merge pull request #3530 from shellhead/mixed-proxy-bugCory Benfieldbefore adoption52b15f8
line 346why, one step back346 ('https://', 'socks5://http.proxy', mixed_proxies),Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9
lines 347–348why, one step back347 # XXX: unsure whether this is reasonable behavior348 ('file:///etc/motd', 'socks5://http.proxy', all_proxies),syntax changesKenneth Reitzbefore adoptionbbadf47
line 349why, one step back349 ))Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9
line 350why, one step back350def test_select_proxies(url, expected, proxies):Added tests module.Dmitry Dygalobefore adoption18b26d2
lines 351–352why, one step back351 """Make sure we can select per-host proxies correctly."""352 assert select_proxy(url, proxies) == expectedMerge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 353–387why, one step back353354355@pytest.mark.parametrize(356 'value, expected', (357 ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),358 ('key_without_value', {'key_without_value': None})359 ))360def test_parse_dict_header(value, expected):361 assert parse_dict_header(value) == expected362363364@pytest.mark.parametrize(365 'value, expected', (366 (367 CaseInsensitiveDict(),368 None369 ),370 (371 CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),372 'utf-8'373 ),374 (375 CaseInsensitiveDict({'content-type': 'text/plain'}),376 'ISO-8859-1'377 ),378 ))379def test_get_encoding_from_headers(value, expected):380 assert get_encoding_from_headers(value) == expected381382383@pytest.mark.parametrize(384 'value, length', (385 ('', 0),386 ('T', 1),387 ('Test', 4),adding in slice_length fix and test for chunk_size=None (#3370)Nate Prewittbefore adoption71050e9
lines 388–390why, one step back388 ('Cont', 0),389 ('Other', -5),390 ('Content', None),Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 391–392why, one step back391 ))392def test_iter_slices(value, length):adding in slice_length fix and test for chunk_size=None (#3370)Nate Prewittbefore adoption71050e9
lines 393–397why, one step back393 if length is None or (length <= 0 and len(value) > 0):394 # Reads all content at once395 assert len(list(iter_slices(value, length))) == 1396 else:397 assert len(list(iter_slices(value, 1))) == lengthMerge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
line 398why, one step back398Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac
line 399why, one step back399Merge pull request #3024 from Stranger6667/utils-unit-testsKenneth Reitzbefore adoption456be3c
lines 400–455why, one step back400@pytest.mark.parametrize(401 'value, expected', (402 (403 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',404 [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]405 ),406 (407 '<http:/.../front.jpeg>',408 [{'url': 'http:/.../front.jpeg'}]409 ),410 (411 '<http:/.../front.jpeg>;',412 [{'url': 'http:/.../front.jpeg'}]413 ),414 (415 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',416 [417 {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},418 {'url': 'http://.../back.jpeg'}419 ]420 ),421 ))422def test_parse_header_links(value, expected):423 assert parse_header_links(value) == expected424425426@pytest.mark.parametrize(427 'value, expected', (428 ('example.com/path', 'http://example.com/path'),429 ('//example.com/path', 'http://example.com/path'),430 ))431def test_prepend_scheme_if_needed(value, expected):432 assert prepend_scheme_if_needed(value, 'http') == expected433434435@pytest.mark.parametrize(436 'value, expected', (437 ('T', 'T'),438 (b'T', 'T'),439 (u'T', 'T'),440 ))441def test_to_native_string(value, expected):442 assert to_native_string(value) == expected443444445@pytest.mark.parametrize(446 'url, expected', (447 ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),448 ('http://example.com/path', 'http://example.com/path'),449 ('//u:p@example.com/path', '//example.com/path'),450 ('//example.com/path', '//example.com/path'),451 ('example.com/path', '//example.com/path'),452 ('scheme:u:p@example.com/path', 'scheme://example.com/path'),453 ))454def test_urldefragauth(url, expected):455 assert urldefragauth(url) == expectedMerge pull request #3195 from kumarvaradarajulu/no_proxy_fixIan Cordascobefore adoption12e3631
lines 456–469why, one step back456457458@pytest.mark.parametrize(459 'url, expected', (460 ('http://192.168.0.1:5000/', True),461 ('http://192.168.0.1/', True),462 ('http://172.16.1.1/', True),463 ('http://172.16.1.1:5000/', True),464 ('http://localhost.localdomain:5000/v1.0/', True),465 ('http://172.16.1.12/', False),466 ('http://172.16.1.12:5000/', False),467 ('http://google.com:5000/v1.0/', False),468 ))469def test_should_bypass_proxies(url, expected, monkeypatch):Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456
lines 470–471why, one step back470 """Tests for function should_bypass_proxies to check if proxy471 can be bypassed or notMerge pull request #3195 from kumarvaradarajulu/no_proxy_fixIan Cordascobefore adoption12e3631
lines 472–475why, one step back472 """473 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')474 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')475 assert should_bypass_proxies(url) == expected