Skip to content
Myr

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

2 files+206 added−24 removed

modified:requests/utils.py+11 added-14 removed
12 unmodified lines
13import codecs14import collections15import io16import os17import platform17import re19import sys18import socket19import struct20import warnings21
539 unmodified lines
561 return True562563 return False564565566def get_environ_proxies(url):567 """Return a dict of environment proxies."""568 if should_bypass_proxies(url):569 return {}570 else:571 return getproxies()572573574def select_proxy(url, proxies):575 """Select a proxy for the url, if applicable.576577 :param url: The url being for the request
5 unmodified lines
583 if proxy is None:584 proxy = proxies.get(urlparts.scheme)585 return proxy586587588def default_user_agent(name="python-requests"):589 """Return a string representing the default user agent."""590 return '%s/%s' % (name, __version__)591
15 unmodified lines
607 """608609 links = []610610 replace_chars = " '\""611 replace_chars = ' \'"'612612 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, ''618618 link = {}619 link = {'url': url.strip('<> \'"')}620620 link["url"] = url.strip("<> '\"")621622 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 break626627 link[key.strip(replace_chars)] = value.strip(replace_chars)
38 unmodified lines
666 return None667668669def 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)673674 # urlparse is a finicky beast, and sometimes decides that there isn't a675 # netloc present. Assume that it's being over-cautious, and switch netloc
22 unmodified lines
698 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 = None704702 if isinstance(string, builtin_str):703 out = string704 else:705 if is_py2:
20 unmodified lines
modified:tests/test_utils.py+195 added-10 removed
1# coding: utf-82import os2from io import BytesIO34import pytest5from requests import compat6from requests.structures import CaseInsensitiveDict7from 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)1819from .compat import StringIO, cStringIO202122class TestSuperLen:2324 @pytest.mark.parametrize(25 'stream, value', (26 (StringIO.StringIO, 'Test'),27 (BytesIO, b'Test'),
23 unmodified lines
51 raise error()5253 assert super_len(BoomFile()) == 05455 def test_string(self):56 assert super_len('Test') == 45758 @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_num697071class TestToKeyValList:7273 @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) == expected8283 def test_invalid(self):84 with pytest.raises(ValueError):85 to_key_val_list('string')868788class TestUnquoteHeaderValue:8990 @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) == expected100101 def test_is_filename(self):102 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'103104105class TestGetEnvironProxies:106 """Ensures that IP addresses are correctly matches with ranges107 in no_proxy variable."""10854 @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')112113 @pytest.mark.parametrize(114 'url', (115 'http://192.168.0.1:5000/',
101 unmodified lines
217 '''.strip()218 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']219220221class 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 None234235236USER = PASSWORD = "%!*'();:@&=+$,/?#[] "237ENCODED_USER = compat.quote(USER, '')238ENCODED_PASSWORD = compat.quote(PASSWORD, '')239
24 unmodified lines
264 (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 ))273def test_get_auth_from_url(url, auth):274 assert get_auth_from_url(url) == auth275
17 unmodified lines
293 assert requote_uri(uri) == expected294295296@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 ))309def test_unquote_unreserved(uri, expected):310 assert unquote_unreserved(uri) == expected311312313@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 lines
330 """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) == expected334335336@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 ))341def test_parse_dict_header(value, expected):342 assert parse_dict_header(value) == expected343344345@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 ))360def test_get_encoding_from_headers(value, expected):361 assert get_encoding_from_headers(value) == expected362363364@pytest.mark.parametrize(365 'value, length', (366 ('', 0),367 ('T', 1),368 ('Test', 4),369 ))370def test_iter_slices(value, length):371 assert len(list(iter_slices(value, 1))) == length372373374@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 ))396def test_parse_header_links(value, expected):397 assert parse_header_links(value) == expected398399400@pytest.mark.parametrize(401 'value, expected', (402 ('example.com/path', 'http://example.com/path'),403 ('//example.com/path', 'http://example.com/path'),404 ))405def test_prepend_scheme_if_needed(value, expected):406 assert prepend_scheme_if_needed(value, 'http') == expected407408409@pytest.mark.parametrize(410 'value, expected', (411 ('T', 'T'),412 (b'T', 'T'),413 (u'T', 'T'),414 ))415def test_to_native_string(value, expected):416 assert to_native_string(value) == expected417418419@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 ))428def test_urldefragauth(url, expected):429 assert urldefragauth(url) == expected