Merge pull request #3024 from Stranger6667/utils-unit-tests
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Added unit tests for utils module
authored by Kenneth Reitz · committed by Kenneth Reitz · parents b6b1b3a, 1eb1535 · Browse files · 2 files·+206 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+206 added−24 removed
- tests:+195 added−10 removed
- other:+11 added−14 removed
Provenance
- Commit
456be3c- Tree
af32979- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
Kenneth Reitz <me@kennethreitz.org>- Parent 1
b6b1b3a- Parent 2
1eb1535
2 files changed+206 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 539 unmodified lines561 return True562 563 return False564 565+566 def get_environ_proxies(url):567 """Return a dict of environment proxies."""568 if should_bypass_proxies(url):569 return {}570 else:571 return getproxies()572 573+574 def select_proxy(url, proxies):575 """Select a proxy for the url, if applicable.576 577 :param url: The url being for the request5 unmodified lines583 if proxy is None:584 proxy = proxies.get(urlparts.scheme)585 return proxy586 587+588 def default_user_agent(name="python-requests"):589 """Return a string representing the default user agent."""590 return '%s/%s' % (name, __version__)591 15 unmodified lines607 """608 609 links = []610 610- replace_chars = " '\""611+ replace_chars = ' \'"'612 612- for val in re.split(", *<", value):613+ for val in re.split(', *<', value):614 try:614- url, params = val.split(";", 1)615+ url, params = val.split(';', 1)616 except ValueError:617 url, params = val, ''618 618- link = {}619+ link = {'url': url.strip('<> \'"')}620 620- link["url"] = url.strip("<> '\"")621-622- for param in params.split(";"):621+ for param in params.split(';'):622 try:624- key, value = param.split("=")623+ key, value = param.split('=')624 except ValueError:625 break626 627 link[key.strip(replace_chars)] = value.strip(replace_chars)38 unmodified lines666 return None667 668 669 def prepend_scheme_if_needed(url, new_scheme):671- '''Given a URL that may or may not have a scheme, prepend the given scheme.672- Does not replace a present scheme with the one provided as an argument.'''670+ """Given a URL that may or may not have a scheme, prepend the given scheme.671+ Does not replace a present scheme with the one provided as an argument."""672 scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)673 674 # urlparse is a finicky beast, and sometimes decides that there isn't a675 # netloc present. Assume that it's being over-cautious, and switch netloc22 unmodified lines698 Given a string object, regardless of type, returns a representation of that699 string in the native string type, encoding and decoding where necessary.700 This assumes ASCII unless told otherwise.701 """703- out = None704-702 if isinstance(string, builtin_str):703 out = string704 else:705 if is_py2:20 unmodified linesmodified:tests/test_utils.py+195 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 22 class TestSuperLen:23+24 @pytest.mark.parametrize(25 'stream, value', (26 (StringIO.StringIO, 'Test'),27 (BytesIO, b'Test'),23 unmodified lines51 raise error()52 53 assert super_len(BoomFile()) == 054 55+ def test_string(self):56+ assert super_len('Test') == 457 58+ @pytest.mark.parametrize(59+ 'mode, warnings_num', (60+ ('r', 1),61+ ('rb', 0),62+ ))63+ def test_file(self, tmpdir, mode, warnings_num, recwarn):64+ file_obj = tmpdir.join('test.txt')65+ file_obj.write('Test')66+ with file_obj.open(mode) as fd:67+ assert super_len(fd) == 468+ assert len(recwarn) == warnings_num69+70+71+class TestToKeyValList:72+73+ @pytest.mark.parametrize(74+ 'value, expected', (75+ ([('key', 'val')], [('key', 'val')]),76+ ((('key', 'val'), ), [('key', 'val')]),77+ ({'key': 'val'}, [('key', 'val')]),78+ (None, None)79+ ))80+ def test_valid(self, value, expected):81+ assert to_key_val_list(value) == expected82+83+ def test_invalid(self):84+ with pytest.raises(ValueError):85+ to_key_val_list('string')86+87+88+class TestUnquoteHeaderValue:89+90+ @pytest.mark.parametrize(91+ 'value, expected', (92+ (None, None),93+ ('Test', 'Test'),94+ ('"Test"', 'Test'),95+ ('"Test\\\\"', 'Test\\'),96+ ('"\\\\Comp\\Res"', '\\Comp\\Res'),97+ ))98+ def test_valid(self, value, expected):99+ assert unquote_header_value(value) == expected100+101+ def test_is_filename(self):102+ assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'103+104+105 class TestGetEnvironProxies:106 """Ensures that IP addresses are correctly matches with ranges107 in no_proxy variable."""108 54- @pytest.yield_fixture(scope='class', autouse=True, params=['no_proxy', 'NO_PROXY'])55- def no_proxy(self, request):56- os.environ[request.param] = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'57- yield58- del os.environ[request.param]109+ @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')112 113 @pytest.mark.parametrize(114 'url', (115 'http://192.168.0.1:5000/',101 unmodified lines217 '''.strip()218 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']219 220 221+class TestGuessJSONUTF:222+223+ @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) == encoding231+232+ def test_bad_utf_like_encoding(self):233+ assert guess_json_utf(b'\x00\x00\x00\x00') is None234+235+236 USER = PASSWORD = "%!*'();:@&=+$,/?#[] "237 ENCODED_USER = compat.quote(USER, '')238 ENCODED_PASSWORD = compat.quote(PASSWORD, '')239 24 unmodified lines264 (265 'http://user:pass%23pass@complex.url.com/path?query=yes',266 ('user', 'pass#pass')267 ),268+ (269+ 'http://complex.url.com/path?query=yes',270+ ('', '')271+ ),272 ))273 def test_get_auth_from_url(url, auth):274 assert get_auth_from_url(url) == auth275 17 unmodified lines293 assert requote_uri(uri) == expected294 295 296 @pytest.mark.parametrize(297+ 'uri, expected', (298+ (299+ # Illegal bytes300+ 'http://example.com/?a=%--',301+ 'http://example.com/?a=%--',302+ ),303+ (304+ # Reserved characters305+ 'http://example.com/?a=%300',306+ 'http://example.com/?a=00',307+ )308+ ))309+def test_unquote_unreserved(uri, expected):310+ assert unquote_unreserved(uri) == expected311+312+313+@pytest.mark.parametrize(314 'mask, expected', (315 (8, '255.0.0.0'),316 (24, '255.255.255.0'),317 (25, '255.255.255.128'),12 unmodified lines330 """Make sure we can select per-host proxies correctly."""331 proxies = {'http': 'http://http.proxy',332 'http://some.host': 'http://some.host.proxy'}333 assert select_proxy(url, proxies) == expected334+335+336+@pytest.mark.parametrize(337+ 'value, expected', (338+ ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),339+ ('key_without_value', {'key_without_value': None})340+ ))341+def test_parse_dict_header(value, expected):342+ assert parse_dict_header(value) == expected343+344+345+@pytest.mark.parametrize(346+ 'value, expected', (347+ (348+ CaseInsensitiveDict(),349+ None350+ ),351+ (352+ CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),353+ 'utf-8'354+ ),355+ (356+ CaseInsensitiveDict({'content-type': 'text/plain'}),357+ 'ISO-8859-1'358+ ),359+ ))360+def test_get_encoding_from_headers(value, expected):361+ assert get_encoding_from_headers(value) == expected362+363+364+@pytest.mark.parametrize(365+ 'value, length', (366+ ('', 0),367+ ('T', 1),368+ ('Test', 4),369+ ))370+def test_iter_slices(value, length):371+ assert len(list(iter_slices(value, 1))) == length372+373+374+@pytest.mark.parametrize(375+ 'value, expected', (376+ (377+ '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',378+ [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]379+ ),380+ (381+ '<http:/.../front.jpeg>',382+ [{'url': 'http:/.../front.jpeg'}]383+ ),384+ (385+ '<http:/.../front.jpeg>;',386+ [{'url': 'http:/.../front.jpeg'}]387+ ),388+ (389+ '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',390+ [391+ {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},392+ {'url': 'http://.../back.jpeg'}393+ ]394+ ),395+ ))396+def test_parse_header_links(value, expected):397+ assert parse_header_links(value) == expected398+399+400+@pytest.mark.parametrize(401+ 'value, expected', (402+ ('example.com/path', 'http://example.com/path'),403+ ('//example.com/path', 'http://example.com/path'),404+ ))405+def test_prepend_scheme_if_needed(value, expected):406+ assert prepend_scheme_if_needed(value, 'http') == expected407+408+409+@pytest.mark.parametrize(410+ 'value, expected', (411+ ('T', 'T'),412+ (b'T', 'T'),413+ (u'T', 'T'),414+ ))415+def test_to_native_string(value, expected):416+ assert to_native_string(value) == expected417+418+419+@pytest.mark.parametrize(420+ 'url, expected', (421+ ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),422+ ('http://example.com/path', 'http://example.com/path'),423+ ('//u:p@example.com/path', '//example.com/path'),424+ ('//example.com/path', '//example.com/path'),425+ ('example.com/path', '//example.com/path'),426+ ('scheme:u:p@example.com/path', 'scheme://example.com/path'),427+ ))428+def test_urldefragauth(url, expected):429+ assert urldefragauth(url) == expected