Skip to content
Myr

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

2 files+205 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
532 unmodified lines
554 return True555556 return False557558559def get_environ_proxies(url):560 """Return a dict of environment proxies."""561 if should_bypass_proxies(url):562 return {}563 else:564 return getproxies()565566567def select_proxy(url, proxies):568 """Select a proxy for the url, if applicable.569570 :param url: The url being for the request
5 unmodified lines
576 if proxy is None:577 proxy = proxies.get(urlparts.scheme)578 return proxy579580581def default_user_agent(name="python-requests"):582 """Return a string representing the default user agent."""583 return '%s/%s' % (name, __version__)584
15 unmodified lines
600 """601602 links = []603603 replace_chars = " '\""604 replace_chars = ' \'"'605605 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, ''611611 link = {}612 link = {'url': url.strip('<> \'"')}613613 link["url"] = url.strip("<> '\"")614615 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 break619620 link[key.strip(replace_chars)] = value.strip(replace_chars)
38 unmodified lines
659 return None660661662def 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)666667 # urlparse is a finicky beast, and sometimes decides that there isn't a668 # netloc present. Assume that it's being over-cautious, and switch netloc
22 unmodified lines
691 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 = None697695 if isinstance(string, builtin_str):696 out = string697 else:698 if is_py2:
20 unmodified lines
modified:tests/test_utils.py+194 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, cStringIO2021
15 unmodified lines
37 s = StringIO.StringIO()38 s.write('foobarbogus')39 assert super_len(s) == 04041 def test_string(self):42 assert super_len('Test') == 44344 @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_num555657class TestToKeyValList:5859 @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) == expected6869 def test_invalid(self):70 with pytest.raises(ValueError):71 to_key_val_list('string')727374class TestUnquoteHeaderValue:7576 @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) == expected8687 def test_is_filename(self):88 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'899091class TestGetEnvironProxies:92 """Ensures that IP addresses are correctly matches with ranges93 in no_proxy variable."""9441 @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')9899 @pytest.mark.parametrize(100 'url', (101 'http://192.168.0.1:5000/',
101 unmodified lines
203 '''.strip()204 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']205206207class TestGuessJSONUTF:208209 @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) == encoding217218 def test_bad_utf_like_encoding(self):219 assert guess_json_utf(b'\x00\x00\x00\x00') is None220221222USER = PASSWORD = "%!*'();:@&=+$,/?#[] "223ENCODED_USER = compat.quote(USER, '')224ENCODED_PASSWORD = compat.quote(PASSWORD, '')225
24 unmodified lines
250 (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 ))259def test_get_auth_from_url(url, auth):260 assert get_auth_from_url(url) == auth261
17 unmodified lines
279 assert requote_uri(uri) == expected280281282@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 ))295def test_unquote_unreserved(uri, expected):296 assert unquote_unreserved(uri) == expected297298299@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 lines
316 """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) == expected320321322@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 ))327def test_parse_dict_header(value, expected):328 assert parse_dict_header(value) == expected329330331@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 ))346def test_get_encoding_from_headers(value, expected):347 assert get_encoding_from_headers(value) == expected348349350@pytest.mark.parametrize(351 'value, length', (352 ('', 0),353 ('T', 1),354 ('Test', 4),355 ))356def test_iter_slices(value, length):357 assert len(list(iter_slices(value, 1))) == length358359360@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 ))382def test_parse_header_links(value, expected):383 assert parse_header_links(value) == expected384385386@pytest.mark.parametrize(387 'value, expected', (388 ('example.com/path', 'http://example.com/path'),389 ('//example.com/path', 'http://example.com/path'),390 ))391def test_prepend_scheme_if_needed(value, expected):392 assert prepend_scheme_if_needed(value, 'http') == expected393394395@pytest.mark.parametrize(396 'value, expected', (397 ('T', 'T'),398 (b'T', 'T'),399 (u'T', 'T'),400 ))401def test_to_native_string(value, expected):402 assert to_native_string(value) == expected403404405@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 ))414def test_urldefragauth(url, expected):415 assert urldefragauth(url) == expected