Added unit tests for utils module
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Dmitry Dygalo · committed by Dmitry Dygalo · parent 3a77b59 · Browse files · 2 files·+205 added−24 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+205 added−24 removed
- tests:+194 added−10 removed
- other:+11 added−14 removed
Provenance
- Commit
f123f89- Tree
15b0b17- Author
Dmitry Dygalo <dadygalo@gmail.com>- Committer
Dmitry Dygalo <dadygalo@gmail.com>- Parent
3a77b59
2 files changed+205 added−24 removed
modified:requests/utils.py+11 added-14 removed
12 unmodified lines13 import codecs14 import collections15 import io16 import os17-import platform17 import re19-import sys18 import socket19 import struct20 import warnings21 532 unmodified lines554 return True555 556 return False557 558+559 def get_environ_proxies(url):560 """Return a dict of environment proxies."""561 if should_bypass_proxies(url):562 return {}563 else:564 return getproxies()565 566+567 def select_proxy(url, proxies):568 """Select a proxy for the url, if applicable.569 570 :param url: The url being for the request5 unmodified lines576 if proxy is None:577 proxy = proxies.get(urlparts.scheme)578 return proxy579 580+581 def default_user_agent(name="python-requests"):582 """Return a string representing the default user agent."""583 return '%s/%s' % (name, __version__)584 15 unmodified lines600 """601 602 links = []603 603- replace_chars = " '\""604+ replace_chars = ' \'"'605 605- for val in re.split(", *<", value):606+ for val in re.split(', *<', value):607 try:607- url, params = val.split(";", 1)608+ url, params = val.split(';', 1)609 except ValueError:610 url, params = val, ''611 611- link = {}612+ link = {'url': url.strip('<> \'"')}613 613- link["url"] = url.strip("<> '\"")614-615- for param in params.split(";"):614+ for param in params.split(';'):615 try:617- key, value = param.split("=")616+ key, value = param.split('=')617 except ValueError:618 break619 620 link[key.strip(replace_chars)] = value.strip(replace_chars)38 unmodified lines659 return None660 661 662 def prepend_scheme_if_needed(url, new_scheme):664- '''Given a URL that may or may not have a scheme, prepend the given scheme.665- Does not replace a present scheme with the one provided as an argument.'''663+ """Given a URL that may or may not have a scheme, prepend the given scheme.664+ Does not replace a present scheme with the one provided as an argument."""665 scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)666 667 # urlparse is a finicky beast, and sometimes decides that there isn't a668 # netloc present. Assume that it's being over-cautious, and switch netloc22 unmodified lines691 Given a string object, regardless of type, returns a representation of that692 string in the native string type, encoding and decoding where necessary.693 This assumes ASCII unless told otherwise.694 """696- out = None697-695 if isinstance(string, builtin_str):696 out = string697 else:698 if is_py2:20 unmodified linesmodified:tests/test_utils.py+194 added-10 removed
1 # coding: utf-82-import os2 from io import BytesIO3 4 import pytest5 from requests import compat6+from requests.structures import CaseInsensitiveDict7 from requests.utils import (8 address_in_network, dotted_netmask,9- get_auth_from_url, get_encodings_from_content,10- get_environ_proxies, guess_filename,11- is_ipv4_address, is_valid_cidr, requote_uri,12- select_proxy, super_len)9+ get_auth_from_url, get_encoding_from_headers,10+ get_encodings_from_content, get_environ_proxies,11+ guess_filename, guess_json_utf, is_ipv4_address,12+ is_valid_cidr, iter_slices, parse_dict_header,13+ parse_header_links, prepend_scheme_if_needed,14+ requote_uri, select_proxy, super_len,15+ to_key_val_list, to_native_string,16+ unquote_header_value, unquote_unreserved,17+ urldefragauth)18 19 from .compat import StringIO, cStringIO20 21 15 unmodified lines37 s = StringIO.StringIO()38 s.write('foobarbogus')39 assert super_len(s) == 040 41+ def test_string(self):42+ assert super_len('Test') == 443 44+ @pytest.mark.parametrize(45+ 'mode, warnings_num', (46+ ('r', 1),47+ ('rb', 0),48+ ))49+ def test_file(self, tmpdir, mode, warnings_num, recwarn):50+ file_obj = tmpdir.join('test.txt')51+ file_obj.write('Test')52+ with file_obj.open(mode) as fd:53+ assert super_len(fd) == 454+ assert len(recwarn) == warnings_num55+56+57+class TestToKeyValList:58+59+ @pytest.mark.parametrize(60+ 'value, expected', (61+ ([('key', 'val')], [('key', 'val')]),62+ ((('key', 'val'), ), [('key', 'val')]),63+ ({'key': 'val'}, [('key', 'val')]),64+ (None, None)65+ ))66+ def test_valid(self, value, expected):67+ assert to_key_val_list(value) == expected68+69+ def test_invalid(self):70+ with pytest.raises(ValueError):71+ to_key_val_list('string')72+73+74+class TestUnquoteHeaderValue:75+76+ @pytest.mark.parametrize(77+ 'value, expected', (78+ (None, None),79+ ('Test', 'Test'),80+ ('"Test"', 'Test'),81+ ('"Test\\\\"', 'Test\\'),82+ ('"\\\\Comp\\Res"', '\\Comp\\Res'),83+ ))84+ def test_valid(self, value, expected):85+ assert unquote_header_value(value) == expected86+87+ def test_is_filename(self):88+ assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'89+90+91 class TestGetEnvironProxies:92 """Ensures that IP addresses are correctly matches with ranges93 in no_proxy variable."""94 41- @pytest.yield_fixture(scope='class', autouse=True, params=['no_proxy', 'NO_PROXY'])42- def no_proxy(self, request):43- os.environ[request.param] = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'44- yield45- del os.environ[request.param]95+ @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])96+ def no_proxy(self, request, monkeypatch):97+ monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')98 99 @pytest.mark.parametrize(100 'url', (101 'http://192.168.0.1:5000/',101 unmodified lines203 '''.strip()204 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']205 206 207+class TestGuessJSONUTF:208+209+ @pytest.mark.parametrize(210+ 'encoding', (211+ 'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',212+ 'utf-32-be', 'utf-32-le'213+ ))214+ def test_encoded(self, encoding):215+ data = '{}'.encode(encoding)216+ assert guess_json_utf(data) == encoding217+218+ def test_bad_utf_like_encoding(self):219+ assert guess_json_utf(b'\x00\x00\x00\x00') is None220+221+222 USER = PASSWORD = "%!*'();:@&=+$,/?#[] "223 ENCODED_USER = compat.quote(USER, '')224 ENCODED_PASSWORD = compat.quote(PASSWORD, '')225 24 unmodified lines250 (251 'http://user:pass%23pass@complex.url.com/path?query=yes',252 ('user', 'pass#pass')253 ),254+ (255+ 'http://complex.url.com/path?query=yes',256+ ('', '')257+ ),258 ))259 def test_get_auth_from_url(url, auth):260 assert get_auth_from_url(url) == auth261 17 unmodified lines279 assert requote_uri(uri) == expected280 281 282 @pytest.mark.parametrize(283+ 'uri, expected', (284+ (285+ # Illegal bytes286+ 'http://example.com/?a=%--',287+ 'http://example.com/?a=%--',288+ ),289+ (290+ # Reserved characters291+ 'http://example.com/?a=%300',292+ 'http://example.com/?a=00',293+ )294+ ))295+def test_unquote_unreserved(uri, expected):296+ assert unquote_unreserved(uri) == expected297+298+299+@pytest.mark.parametrize(300 'mask, expected', (301 (8, '255.0.0.0'),302 (24, '255.255.255.0'),303 (25, '255.255.255.128'),12 unmodified lines316 """Make sure we can select per-host proxies correctly."""317 proxies = {'http': 'http://http.proxy',318 'http://some.host': 'http://some.host.proxy'}319 assert select_proxy(url, proxies) == expected320+321+322+@pytest.mark.parametrize(323+ 'value, expected', (324+ ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),325+ ('key_without_value', {'key_without_value': None})326+ ))327+def test_parse_dict_header(value, expected):328+ assert parse_dict_header(value) == expected329+330+331+@pytest.mark.parametrize(332+ 'value, expected', (333+ (334+ CaseInsensitiveDict(),335+ None336+ ),337+ (338+ CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),339+ 'utf-8'340+ ),341+ (342+ CaseInsensitiveDict({'content-type': 'text/plain'}),343+ 'ISO-8859-1'344+ ),345+ ))346+def test_get_encoding_from_headers(value, expected):347+ assert get_encoding_from_headers(value) == expected348+349+350+@pytest.mark.parametrize(351+ 'value, length', (352+ ('', 0),353+ ('T', 1),354+ ('Test', 4),355+ ))356+def test_iter_slices(value, length):357+ assert len(list(iter_slices(value, 1))) == length358+359+360+@pytest.mark.parametrize(361+ 'value, expected', (362+ (363+ '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',364+ [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]365+ ),366+ (367+ '<http:/.../front.jpeg>',368+ [{'url': 'http:/.../front.jpeg'}]369+ ),370+ (371+ '<http:/.../front.jpeg>;',372+ [{'url': 'http:/.../front.jpeg'}]373+ ),374+ (375+ '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',376+ [377+ {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},378+ {'url': 'http://.../back.jpeg'}379+ ]380+ ),381+ ))382+def test_parse_header_links(value, expected):383+ assert parse_header_links(value) == expected384+385+386+@pytest.mark.parametrize(387+ 'value, expected', (388+ ('example.com/path', 'http://example.com/path'),389+ ('//example.com/path', 'http://example.com/path'),390+ ))391+def test_prepend_scheme_if_needed(value, expected):392+ assert prepend_scheme_if_needed(value, 'http') == expected393+394+395+@pytest.mark.parametrize(396+ 'value, expected', (397+ ('T', 'T'),398+ (b'T', 'T'),399+ (u'T', 'T'),400+ ))401+def test_to_native_string(value, expected):402+ assert to_native_string(value) == expected403+404+405+@pytest.mark.parametrize(406+ 'url, expected', (407+ ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),408+ ('http://example.com/path', 'http://example.com/path'),409+ ('//u:p@example.com/path', '//example.com/path'),410+ ('//example.com/path', '//example.com/path'),411+ ('example.com/path', '//example.com/path'),412+ ('scheme:u:p@example.com/path', 'scheme://example.com/path'),413+ ))414+def test_urldefragauth(url, expected):415+ assert urldefragauth(url) == expected