Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

503 lines · 15.6 KiB · Python

Last changed by

Merge pull request #3535 from nateprewitt/3339_avoid_getvaluesCory Benfieldbefore adoption5524472

History of this file

Take it

1# -*- coding: utf-8 -*-23from io import BytesIO45import pytest6from requests import compat7from requests.structures import CaseInsensitiveDict8from requests.utils import (9    address_in_network, dotted_netmask,10    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,15    requote_uri, select_proxy, should_bypass_proxies, super_len,16    to_key_val_list, to_native_string,17    unquote_header_value, unquote_unreserved,18    urldefragauth)1920from .compat import StringIO, cStringIO212223class TestSuperLen:2425    @pytest.mark.parametrize(26        'stream, value', (27            (StringIO.StringIO, 'Test'),28            (BytesIO, b'Test'),29            pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),30        ))31    def test_io_streams(self, stream, value):32        """Ensures that we properly deal with different kinds of IO streams."""33        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) == 04142    @pytest.mark.parametrize('error', [IOError, OSError])43    def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):44        """If tell() raises errors, assume the cursor is at position zero."""45        class BoomFile(object):46            def __len__(self):47                return 54849            def tell(self):50                raise error()5152        assert super_len(BoomFile()) == 05354    def test_string(self):55        assert super_len('Test') == 45657    @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_num6869    def test_super_len_with__len__(self):70        foo = [1,2,3,4]71        len_foo = super_len(foo)72        assert len_foo == 47374    def test_super_len_with_no__len__(self):75        class LenFile(object):76            def __init__(self):77                self.len = 57879        assert super_len(LenFile()) == 58081    def test_super_len_with_tell(self):82        foo = StringIO.StringIO('12345')83        assert super_len(foo) == 584        foo.read(2)85        assert super_len(foo) == 38687    def test_super_len_with_fileno(self):88        with open(__file__, 'rb') as f:89            length = super_len(f)90            file_data = f.read()91        assert length == len(file_data)9293    def test_super_len_with_no_matches(self):94        """Ensure that objects without any length methods default to 0"""95        assert super_len(object()) == 0969798class TestToKeyValList:99100    @pytest.mark.parametrize(101        'value, expected', (102            ([('key', 'val')], [('key', 'val')]),103            ((('key', 'val'), ), [('key', 'val')]),104            ({'key': 'val'}, [('key', 'val')]),105            (None, None)106        ))107    def test_valid(self, value, expected):108        assert to_key_val_list(value) == expected109110    def test_invalid(self):111        with pytest.raises(ValueError):112            to_key_val_list('string')113114115class TestUnquoteHeaderValue:116117    @pytest.mark.parametrize(118        'value, expected', (119            (None, None),120            ('Test', 'Test'),121            ('"Test"', 'Test'),122            ('"Test\\\\"', 'Test\\'),123            ('"\\\\Comp\\Res"', '\\Comp\\Res'),124        ))125    def test_valid(self, value, expected):126        assert unquote_header_value(value) == expected127128    def test_is_filename(self):129        assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'130131132class TestGetEnvironProxies:133    """Ensures that IP addresses are correctly matches with ranges134    in no_proxy variable.135    """136137    @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])138    def no_proxy(self, request, monkeypatch):139        monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')140141    @pytest.mark.parametrize(142        'url', (143            'http://192.168.0.1:5000/',144            'http://192.168.0.1/',145            'http://172.16.1.1/',146            'http://172.16.1.1:5000/',147            'http://localhost.localdomain:5000/v1.0/',148        ))149    def test_bypass(self, url):150        assert get_environ_proxies(url) == {}151152    @pytest.mark.parametrize(153        'url', (154            'http://192.168.1.1:5000/',155            'http://192.168.1.1/',156            'http://www.requests.com/',157        ))158    def test_not_bypass(self, url):159        assert get_environ_proxies(url) != {}160161162class TestIsIPv4Address:163164    def test_valid(self):165        assert is_ipv4_address('8.8.8.8')166167    @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))168    def test_invalid(self, value):169        assert not is_ipv4_address(value)170171172class TestIsValidCIDR:173174    def test_valid(self):175        assert is_valid_cidr('192.168.1.0/24')176177    @pytest.mark.parametrize(178        'value', (179            '8.8.8.8',180            '192.168.1.0/a',181            '192.168.1.0/128',182            '192.168.1.0/-1',183            '192.168.1.999/24',184        ))185    def test_invalid(self, value):186        assert not is_valid_cidr(value)187188189class TestAddressInNetwork:190191    def test_valid(self):192        assert address_in_network('192.168.1.1', '192.168.1.0/24')193194    def test_invalid(self):195        assert not address_in_network('172.16.0.1', '192.168.1.0/24')196197198class TestGuessFilename:199200    @pytest.mark.parametrize(201        'value', (1, type('Fake', (object,), {'name': 1})()),202    )203    def test_guess_filename_invalid(self, value):204        assert guess_filename(value) is None205206    @pytest.mark.parametrize(207        'value, expected_type', (208            (b'value', compat.bytes),209            (b'value'.decode('utf-8'), compat.str)210        ))211    def test_guess_filename_valid(self, value, expected_type):212        obj = type('Fake', (object,), {'name': value})()213        result = guess_filename(obj)214        assert result == value215        assert isinstance(result, expected_type)216217218class TestContentEncodingDetection:219220    def test_none(self):221        encodings = get_encodings_from_content('')222        assert not len(encodings)223224    @pytest.mark.parametrize(225        'content', (226            # HTML5 meta charset attribute227            '<meta charset="UTF-8">',228            # HTML4 pragma directive229            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',230            # XHTML 1.x served with text/html MIME type231            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',232            # XHTML 1.x served as XML233            '<?xml version="1.0" encoding="UTF-8"?>',234        ))235    def test_pragmas(self, content):236        encodings = get_encodings_from_content(content)237        assert len(encodings) == 1238        assert encodings[0] == 'UTF-8'239240    def test_precedence(self):241        content = '''242        <?xml version="1.0" encoding="XML"?>243        <meta charset="HTML5">244        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />245        '''.strip()246        assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']247248249class TestGuessJSONUTF:250251    @pytest.mark.parametrize(252        'encoding', (253            'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',254            'utf-32-be', 'utf-32-le'255        ))256    def test_encoded(self, encoding):257        data = '{}'.encode(encoding)258        assert guess_json_utf(data) == encoding259260    def test_bad_utf_like_encoding(self):261        assert guess_json_utf(b'\x00\x00\x00\x00') is None262263264USER = PASSWORD = "%!*'();:@&=+$,/?#[] "265ENCODED_USER = compat.quote(USER, '')266ENCODED_PASSWORD = compat.quote(PASSWORD, '')267268269@pytest.mark.parametrize(270    'url, auth', (271        (272            'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +273            'request.com/url.html#test',274            (USER, PASSWORD)275        ),276        (277            'http://user:pass@complex.url.com/path?query=yes',278            ('user', 'pass')279        ),280        (281            'http://user:pass%20pass@complex.url.com/path?query=yes',282            ('user', 'pass pass')283        ),284        (285            'http://user:pass pass@complex.url.com/path?query=yes',286            ('user', 'pass pass')287        ),288        (289            'http://user%25user:pass@complex.url.com/path?query=yes',290            ('user%user', 'pass')291        ),292        (293            'http://user:pass%23pass@complex.url.com/path?query=yes',294            ('user', 'pass#pass')295        ),296        (297            'http://complex.url.com/path?query=yes',298            ('', '')299        ),300    ))301def test_get_auth_from_url(url, auth):302    assert get_auth_from_url(url) == auth303304305@pytest.mark.parametrize(306    'uri, expected', (307        (308            # Ensure requoting doesn't break expectations309            'http://example.com/fiz?buz=%25ppicture',310            'http://example.com/fiz?buz=%25ppicture',311        ),312        (313            # Ensure we handle unquoted percent signs in redirects314            'http://example.com/fiz?buz=%ppicture',315            'http://example.com/fiz?buz=%25ppicture',316        ),317    ))318def test_requote_uri_with_unquoted_percents(uri, expected):319    """See: https://github.com/kennethreitz/requests/issues/2356"""320    assert requote_uri(uri) == expected321322323@pytest.mark.parametrize(324    'uri, expected', (325        (326            # Illegal bytes327            'http://example.com/?a=%--',328            'http://example.com/?a=%--',329        ),330        (331            # Reserved characters332            'http://example.com/?a=%300',333            'http://example.com/?a=00',334        )335    ))336def test_unquote_unreserved(uri, expected):337    assert unquote_unreserved(uri) == expected338339340@pytest.mark.parametrize(341    'mask, expected', (342        (8, '255.0.0.0'),343        (24, '255.255.255.0'),344        (25, '255.255.255.128'),345    ))346def test_dotted_netmask(mask, expected):347    assert dotted_netmask(mask) == expected348349350http_proxies = {'http': 'http://http.proxy',351                'http://some.host': 'http://some.host.proxy'}352all_proxies = {'all': 'socks5://http.proxy',353               'all://some.host': 'socks5://some.host.proxy'}354mixed_proxies = {'http': 'http://http.proxy',355                 'http://some.host': 'http://some.host.proxy',356                 'all': 'socks5://http.proxy'}357@pytest.mark.parametrize(358    'url, expected, proxies', (359        ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),360        ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),361        ('hTTp:///path', 'http://http.proxy', http_proxies),362        ('hTTps://Other.Host', None, http_proxies),363        ('file:///etc/motd', None, http_proxies),364365        ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),366        ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),367        ('hTTp:///path', 'socks5://http.proxy', all_proxies),368        ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),369370        ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),371        ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),372        ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),373        ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),374        ('https://', 'socks5://http.proxy', mixed_proxies),375        # XXX: unsure whether this is reasonable behavior376        ('file:///etc/motd', 'socks5://http.proxy', all_proxies),377    ))378def test_select_proxies(url, expected, proxies):379    """Make sure we can select per-host proxies correctly."""380    assert select_proxy(url, proxies) == expected381382383@pytest.mark.parametrize(384    'value, expected', (385        ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),386        ('key_without_value', {'key_without_value': None})387    ))388def test_parse_dict_header(value, expected):389    assert parse_dict_header(value) == expected390391392@pytest.mark.parametrize(393    'value, expected', (394        (395            CaseInsensitiveDict(),396            None397        ),398        (399            CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),400            'utf-8'401        ),402        (403            CaseInsensitiveDict({'content-type': 'text/plain'}),404            'ISO-8859-1'405        ),406    ))407def test_get_encoding_from_headers(value, expected):408    assert get_encoding_from_headers(value) == expected409410411@pytest.mark.parametrize(412    'value, length', (413        ('', 0),414        ('T', 1),415        ('Test', 4),416        ('Cont', 0),417        ('Other', -5),418        ('Content', None),419    ))420def test_iter_slices(value, length):421    if length is None or (length <= 0 and len(value) > 0):422        # Reads all content at once423        assert len(list(iter_slices(value, length))) == 1424    else:425        assert len(list(iter_slices(value, 1))) == length426427428@pytest.mark.parametrize(429    'value, expected', (430        (431            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',432            [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]433        ),434        (435            '<http:/.../front.jpeg>',436            [{'url': 'http:/.../front.jpeg'}]437        ),438        (439            '<http:/.../front.jpeg>;',440            [{'url': 'http:/.../front.jpeg'}]441        ),442        (443            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',444            [445                {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},446                {'url': 'http://.../back.jpeg'}447            ]448        ),449    ))450def test_parse_header_links(value, expected):451    assert parse_header_links(value) == expected452453454@pytest.mark.parametrize(455    'value, expected', (456        ('example.com/path', 'http://example.com/path'),457        ('//example.com/path', 'http://example.com/path'),458    ))459def test_prepend_scheme_if_needed(value, expected):460    assert prepend_scheme_if_needed(value, 'http') == expected461462463@pytest.mark.parametrize(464    'value, expected', (465        ('T', 'T'),466        (b'T', 'T'),467        (u'T', 'T'),468    ))469def test_to_native_string(value, expected):470    assert to_native_string(value) == expected471472473@pytest.mark.parametrize(474    'url, expected', (475        ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),476        ('http://example.com/path', 'http://example.com/path'),477        ('//u:p@example.com/path', '//example.com/path'),478        ('//example.com/path', '//example.com/path'),479        ('example.com/path', '//example.com/path'),480        ('scheme:u:p@example.com/path', 'scheme://example.com/path'),481    ))482def test_urldefragauth(url, expected):483    assert urldefragauth(url) == expected484485486@pytest.mark.parametrize(487    'url, expected', (488            ('http://192.168.0.1:5000/', True),489            ('http://192.168.0.1/', True),490            ('http://172.16.1.1/', True),491            ('http://172.16.1.1:5000/', True),492            ('http://localhost.localdomain:5000/v1.0/', True),493            ('http://172.16.1.12/', False),494            ('http://172.16.1.12:5000/', False),495            ('http://google.com:5000/v1.0/', False),496    ))497def test_should_bypass_proxies(url, expected, monkeypatch):498    """Tests for function should_bypass_proxies to check if proxy499    can be bypassed or not500    """501    monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')502    monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')503    assert should_bypass_proxies(url) == expected