Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

684 lines · 21.7 KiB · Python

Last changed by

Merge branch 'master' of https://github.com/requests/requestsKenneth Reitzbefore adoption88dc335

History of this file

Take it

1# -*- coding: utf-8 -*-23import os4import copy5from io import BytesIO67import pytest8from requests import compat9from requests.cookies import RequestsCookieJar10from requests.structures import CaseInsensitiveDict11from requests.utils import (12    address_in_network, dotted_netmask,13    get_auth_from_url, get_encoding_from_headers,14    get_encodings_from_content, get_environ_proxies,15    guess_filename, guess_json_utf, is_ipv4_address,16    is_valid_cidr, iter_slices, parse_dict_header,17    parse_header_links, prepend_scheme_if_needed,18    requote_uri, select_proxy, should_bypass_proxies, super_len,19    to_key_val_list, to_native_string,20    unquote_header_value, unquote_unreserved,21    urldefragauth, add_dict_to_cookiejar, set_environ)22from requests._internal_utils import unicode_is_ascii2324from .compat import StringIO, cStringIO252627class TestSuperLen:2829    @pytest.mark.parametrize(30        'stream, value', (31            (StringIO.StringIO, 'Test'),32            (BytesIO, b'Test'),33            pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),34        ))35    def test_io_streams(self, stream, value):36        """Ensures that we properly deal with different kinds of IO streams."""37        assert super_len(stream()) == 038        assert super_len(stream(value)) == 43940    def test_super_len_correctly_calculates_len_of_partially_read_file(self):41        """Ensure that we handle partially consumed file like objects."""42        s = StringIO.StringIO()43        s.write('foobarbogus')44        assert super_len(s) == 04546    @pytest.mark.parametrize('error', [IOError, OSError])47    def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):48        """If tell() raises errors, assume the cursor is at position zero."""49        class BoomFile(object):50            def __len__(self):51                return 55253            def tell(self):54                raise error()5556        assert super_len(BoomFile()) == 05758    @pytest.mark.parametrize('error', [IOError, OSError])59    def test_super_len_tell_ioerror(self, error):60        """Ensure that if tell gives an IOError super_len doesn't fail"""61        class NoLenBoomFile(object):62            def tell(self):63                raise error()6465            def seek(self, offset, whence):66                pass6768        assert super_len(NoLenBoomFile()) == 06970    def test_string(self):71        assert super_len('Test') == 47273    @pytest.mark.parametrize(74        'mode, warnings_num', (75            ('r', 1),76            ('rb', 0),77        ))78    def test_file(self, tmpdir, mode, warnings_num, recwarn):79        file_obj = tmpdir.join('test.txt')80        file_obj.write('Test')81        with file_obj.open(mode) as fd:82            assert super_len(fd) == 483        assert len(recwarn) == warnings_num8485    def test_super_len_with__len__(self):86        foo = [1,2,3,4]87        len_foo = super_len(foo)88        assert len_foo == 48990    def test_super_len_with_no__len__(self):91        class LenFile(object):92            def __init__(self):93                self.len = 59495        assert super_len(LenFile()) == 59697    def test_super_len_with_tell(self):98        foo = StringIO.StringIO('12345')99        assert super_len(foo) == 5100        foo.read(2)101        assert super_len(foo) == 3102103    def test_super_len_with_fileno(self):104        with open(__file__, 'rb') as f:105            length = super_len(f)106            file_data = f.read()107        assert length == len(file_data)108109    def test_super_len_with_no_matches(self):110        """Ensure that objects without any length methods default to 0"""111        assert super_len(object()) == 0112113114class TestToKeyValList:115116    @pytest.mark.parametrize(117        'value, expected', (118            ([('key', 'val')], [('key', 'val')]),119            ((('key', 'val'), ), [('key', 'val')]),120            ({'key': 'val'}, [('key', 'val')]),121            (None, None)122        ))123    def test_valid(self, value, expected):124        assert to_key_val_list(value) == expected125126    def test_invalid(self):127        with pytest.raises(ValueError):128            to_key_val_list('string')129130131class TestUnquoteHeaderValue:132133    @pytest.mark.parametrize(134        'value, expected', (135            (None, None),136            ('Test', 'Test'),137            ('"Test"', 'Test'),138            ('"Test\\\\"', 'Test\\'),139            ('"\\\\Comp\\Res"', '\\Comp\\Res'),140        ))141    def test_valid(self, value, expected):142        assert unquote_header_value(value) == expected143144    def test_is_filename(self):145        assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'146147148class TestGetEnvironProxies:149    """Ensures that IP addresses are correctly matches with ranges150    in no_proxy variable.151    """152153    @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])154    def no_proxy(self, request, monkeypatch):155        monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')156157    @pytest.mark.parametrize(158        'url', (159            'http://192.168.0.1:5000/',160            'http://192.168.0.1/',161            'http://172.16.1.1/',162            'http://172.16.1.1:5000/',163            'http://localhost.localdomain:5000/v1.0/',164        ))165    def test_bypass(self, url):166        assert get_environ_proxies(url, no_proxy=None) == {}167168    @pytest.mark.parametrize(169        'url', (170            'http://192.168.1.1:5000/',171            'http://192.168.1.1/',172            'http://www.requests.com/',173        ))174    def test_not_bypass(self, url):175        assert get_environ_proxies(url, no_proxy=None) != {}176177    @pytest.mark.parametrize(178        'url', (179            'http://192.168.1.1:5000/',180            'http://192.168.1.1/',181            'http://www.requests.com/',182        ))183    def test_bypass_no_proxy_keyword(self, url):184        no_proxy = '192.168.1.1,requests.com'185        assert get_environ_proxies(url, no_proxy=no_proxy) == {}186187    @pytest.mark.parametrize(188        'url', (189            'http://192.168.0.1:5000/',190            'http://192.168.0.1/',191            'http://172.16.1.1/',192            'http://172.16.1.1:5000/',193            'http://localhost.localdomain:5000/v1.0/',194        ))195    def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):196        # This is testing that the 'no_proxy' argument overrides the197        # environment variable 'no_proxy'198        monkeypatch.setenv('http_proxy', 'http://proxy.example.com:3128/')199        no_proxy = '192.168.1.1,requests.com'200        assert get_environ_proxies(url, no_proxy=no_proxy) != {}201202203class TestIsIPv4Address:204205    def test_valid(self):206        assert is_ipv4_address('8.8.8.8')207208    @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))209    def test_invalid(self, value):210        assert not is_ipv4_address(value)211212213class TestIsValidCIDR:214215    def test_valid(self):216        assert is_valid_cidr('192.168.1.0/24')217218    @pytest.mark.parametrize(219        'value', (220            '8.8.8.8',221            '192.168.1.0/a',222            '192.168.1.0/128',223            '192.168.1.0/-1',224            '192.168.1.999/24',225        ))226    def test_invalid(self, value):227        assert not is_valid_cidr(value)228229230class TestAddressInNetwork:231232    def test_valid(self):233        assert address_in_network('192.168.1.1', '192.168.1.0/24')234235    def test_invalid(self):236        assert not address_in_network('172.16.0.1', '192.168.1.0/24')237238239class TestGuessFilename:240241    @pytest.mark.parametrize(242        'value', (1, type('Fake', (object,), {'name': 1})()),243    )244    def test_guess_filename_invalid(self, value):245        assert guess_filename(value) is None246247    @pytest.mark.parametrize(248        'value, expected_type', (249            (b'value', compat.bytes),250            (b'value'.decode('utf-8'), compat.str)251        ))252    def test_guess_filename_valid(self, value, expected_type):253        obj = type('Fake', (object,), {'name': value})()254        result = guess_filename(obj)255        assert result == value256        assert isinstance(result, expected_type)257258259class TestContentEncodingDetection:260261    def test_none(self):262        encodings = get_encodings_from_content('')263        assert not len(encodings)264265    @pytest.mark.parametrize(266        'content', (267            # HTML5 meta charset attribute268            '<meta charset="UTF-8">',269            # HTML4 pragma directive270            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',271            # XHTML 1.x served with text/html MIME type272            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',273            # XHTML 1.x served as XML274            '<?xml version="1.0" encoding="UTF-8"?>',275        ))276    def test_pragmas(self, content):277        encodings = get_encodings_from_content(content)278        assert len(encodings) == 1279        assert encodings[0] == 'UTF-8'280281    def test_precedence(self):282        content = '''283        <?xml version="1.0" encoding="XML"?>284        <meta charset="HTML5">285        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />286        '''.strip()287        assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']288289290class TestGuessJSONUTF:291292    @pytest.mark.parametrize(293        'encoding', (294            'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',295            'utf-32-be', 'utf-32-le'296        ))297    def test_encoded(self, encoding):298        data = '{}'.encode(encoding)299        assert guess_json_utf(data) == encoding300301    def test_bad_utf_like_encoding(self):302        assert guess_json_utf(b'\x00\x00\x00\x00') is None303304    @pytest.mark.parametrize(305        ('encoding', 'expected'), (306            ('utf-16-be', 'utf-16'),307            ('utf-16-le', 'utf-16'),308            ('utf-32-be', 'utf-32'),309            ('utf-32-le', 'utf-32')310        ))311    def test_guess_by_bom(self, encoding, expected):312        data = u'\ufeff{}'.encode(encoding)313        assert guess_json_utf(data) == expected314315316USER = PASSWORD = "%!*'();:@&=+$,/?#[] "317ENCODED_USER = compat.quote(USER, '')318ENCODED_PASSWORD = compat.quote(PASSWORD, '')319320321@pytest.mark.parametrize(322    'url, auth', (323        (324            'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +325            'request.com/url.html#test',326            (USER, PASSWORD)327        ),328        (329            'http://user:pass@complex.url.com/path?query=yes',330            ('user', 'pass')331        ),332        (333            'http://user:pass%20pass@complex.url.com/path?query=yes',334            ('user', 'pass pass')335        ),336        (337            'http://user:pass pass@complex.url.com/path?query=yes',338            ('user', 'pass pass')339        ),340        (341            'http://user%25user:pass@complex.url.com/path?query=yes',342            ('user%user', 'pass')343        ),344        (345            'http://user:pass%23pass@complex.url.com/path?query=yes',346            ('user', 'pass#pass')347        ),348        (349            'http://complex.url.com/path?query=yes',350            ('', '')351        ),352    ))353def test_get_auth_from_url(url, auth):354    assert get_auth_from_url(url) == auth355356357@pytest.mark.parametrize(358    'uri, expected', (359        (360            # Ensure requoting doesn't break expectations361            'http://example.com/fiz?buz=%25ppicture',362            'http://example.com/fiz?buz=%25ppicture',363        ),364        (365            # Ensure we handle unquoted percent signs in redirects366            'http://example.com/fiz?buz=%ppicture',367            'http://example.com/fiz?buz=%25ppicture',368        ),369    ))370def test_requote_uri_with_unquoted_percents(uri, expected):371    """See: https://github.com/requests/requests/issues/2356"""372    assert requote_uri(uri) == expected373374375@pytest.mark.parametrize(376    'uri, expected', (377        (378            # Illegal bytes379            'http://example.com/?a=%--',380            'http://example.com/?a=%--',381        ),382        (383            # Reserved characters384            'http://example.com/?a=%300',385            'http://example.com/?a=00',386        )387    ))388def test_unquote_unreserved(uri, expected):389    assert unquote_unreserved(uri) == expected390391392@pytest.mark.parametrize(393    'mask, expected', (394        (8, '255.0.0.0'),395        (24, '255.255.255.0'),396        (25, '255.255.255.128'),397    ))398def test_dotted_netmask(mask, expected):399    assert dotted_netmask(mask) == expected400401402http_proxies = {'http': 'http://http.proxy',403                'http://some.host': 'http://some.host.proxy'}404all_proxies = {'all': 'socks5://http.proxy',405               'all://some.host': 'socks5://some.host.proxy'}406mixed_proxies = {'http': 'http://http.proxy',407                 'http://some.host': 'http://some.host.proxy',408                 'all': 'socks5://http.proxy'}409@pytest.mark.parametrize(410    'url, expected, proxies', (411        ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),412        ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),413        ('hTTp:///path', 'http://http.proxy', http_proxies),414        ('hTTps://Other.Host', None, http_proxies),415        ('file:///etc/motd', None, http_proxies),416417        ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),418        ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),419        ('hTTp:///path', 'socks5://http.proxy', all_proxies),420        ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),421422        ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),423        ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),424        ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),425        ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),426        ('https://', 'socks5://http.proxy', mixed_proxies),427        # XXX: unsure whether this is reasonable behavior428        ('file:///etc/motd', 'socks5://http.proxy', all_proxies),429    ))430def test_select_proxies(url, expected, proxies):431    """Make sure we can select per-host proxies correctly."""432    assert select_proxy(url, proxies) == expected433434435@pytest.mark.parametrize(436    'value, expected', (437        ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),438        ('key_without_value', {'key_without_value': None})439    ))440def test_parse_dict_header(value, expected):441    assert parse_dict_header(value) == expected442443444@pytest.mark.parametrize(445    'value, expected', (446        (447            CaseInsensitiveDict(),448            None449        ),450        (451            CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),452            'utf-8'453        ),454        (455            CaseInsensitiveDict({'content-type': 'text/plain'}),456            'ISO-8859-1'457        ),458    ))459def test_get_encoding_from_headers(value, expected):460    assert get_encoding_from_headers(value) == expected461462463@pytest.mark.parametrize(464    'value, length', (465        ('', 0),466        ('T', 1),467        ('Test', 4),468        ('Cont', 0),469        ('Other', -5),470        ('Content', None),471    ))472def test_iter_slices(value, length):473    if length is None or (length <= 0 and len(value) > 0):474        # Reads all content at once475        assert len(list(iter_slices(value, length))) == 1476    else:477        assert len(list(iter_slices(value, 1))) == length478479480@pytest.mark.parametrize(481    'value, expected', (482        (483            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',484            [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]485        ),486        (487            '<http:/.../front.jpeg>',488            [{'url': 'http:/.../front.jpeg'}]489        ),490        (491            '<http:/.../front.jpeg>;',492            [{'url': 'http:/.../front.jpeg'}]493        ),494        (495            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',496            [497                {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},498                {'url': 'http://.../back.jpeg'}499            ]500        ),501        (502            '',503            []504        ),505    ))506def test_parse_header_links(value, expected):507    assert parse_header_links(value) == expected508509510@pytest.mark.parametrize(511    'value, expected', (512        ('example.com/path', 'http://example.com/path'),513        ('//example.com/path', 'http://example.com/path'),514    ))515def test_prepend_scheme_if_needed(value, expected):516    assert prepend_scheme_if_needed(value, 'http') == expected517518519@pytest.mark.parametrize(520    'value, expected', (521        ('T', 'T'),522        (b'T', 'T'),523        (u'T', 'T'),524    ))525def test_to_native_string(value, expected):526    assert to_native_string(value) == expected527528529@pytest.mark.parametrize(530    'url, expected', (531        ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),532        ('http://example.com/path', 'http://example.com/path'),533        ('//u:p@example.com/path', '//example.com/path'),534        ('//example.com/path', '//example.com/path'),535        ('example.com/path', '//example.com/path'),536        ('scheme:u:p@example.com/path', 'scheme://example.com/path'),537    ))538def test_urldefragauth(url, expected):539    assert urldefragauth(url) == expected540541542@pytest.mark.parametrize(543    'url, expected', (544            ('http://192.168.0.1:5000/', True),545            ('http://192.168.0.1/', True),546            ('http://172.16.1.1/', True),547            ('http://172.16.1.1:5000/', True),548            ('http://localhost.localdomain:5000/v1.0/', True),549            ('http://172.16.1.12/', False),550            ('http://172.16.1.12:5000/', False),551            ('http://google.com:5000/v1.0/', False),552    ))553def test_should_bypass_proxies(url, expected, monkeypatch):554    """Tests for function should_bypass_proxies to check if proxy555    can be bypassed or not556    """557    monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')558    monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')559    assert should_bypass_proxies(url, no_proxy=None) == expected560561562@pytest.mark.parametrize(563    'cookiejar', (564        compat.cookielib.CookieJar(),565        RequestsCookieJar()566    ))567def test_add_dict_to_cookiejar(cookiejar):568    """Ensure add_dict_to_cookiejar works for569    non-RequestsCookieJar CookieJars570    """571    cookiedict = {'test': 'cookies',572                  'good': 'cookies'}573    cj = add_dict_to_cookiejar(cookiejar, cookiedict)574    cookies = dict((cookie.name, cookie.value) for cookie in cj)575    assert cookiedict == cookies576577578@pytest.mark.parametrize(579    'value, expected', (580                (u'test', True),581                (u'æíöû', False),582                (u'ジェーピーニック', False),583    )584)585def test_unicode_is_ascii(value, expected):586    assert unicode_is_ascii(value) is expected587588589@pytest.mark.parametrize(590    'url, expected', (591            ('http://192.168.0.1:5000/', True),592            ('http://192.168.0.1/', True),593            ('http://172.16.1.1/', True),594            ('http://172.16.1.1:5000/', True),595            ('http://localhost.localdomain:5000/v1.0/', True),596            ('http://172.16.1.12/', False),597            ('http://172.16.1.12:5000/', False),598            ('http://google.com:5000/v1.0/', False),599    ))600def test_should_bypass_proxies_no_proxy(601        url, expected, monkeypatch):602    """Tests for function should_bypass_proxies to check if proxy603    can be bypassed or not using the 'no_proxy' argument604    """605    no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'606    # Test 'no_proxy' argument607    assert should_bypass_proxies(url, no_proxy=no_proxy) == expected608609610@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')611@pytest.mark.parametrize(612    'url, expected, override', (613            ('http://192.168.0.1:5000/', True, None),614            ('http://192.168.0.1/', True, None),615            ('http://172.16.1.1/', True, None),616            ('http://172.16.1.1:5000/', True, None),617            ('http://localhost.localdomain:5000/v1.0/', True, None),618            ('http://172.16.1.22/', False, None),619            ('http://172.16.1.22:5000/', False, None),620            ('http://google.com:5000/v1.0/', False, None),621            ('http://mylocalhostname:5000/v1.0/', True, '<local>'),622            ('http://192.168.0.1/', False, ''),623    ))624def test_should_bypass_proxies_win_registry(url, expected, override,625                                            monkeypatch):626    """Tests for function should_bypass_proxies to check if proxy627    can be bypassed or not with Windows registry settings628    """629    if override is None:630        override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'631    if compat.is_py3:632        import winreg633    else:634        import _winreg as winreg635636    class RegHandle:637        def Close(self):638            pass639640    ie_settings = RegHandle()641642    def OpenKey(key, subkey):643        return ie_settings644645    def QueryValueEx(key, value_name):646        if key is ie_settings:647            if value_name == 'ProxyEnable':648                return [1]649            elif value_name == 'ProxyOverride':650                return [override]651652    monkeypatch.setenv('http_proxy', '')653    monkeypatch.setenv('https_proxy', '')654    monkeypatch.setenv('ftp_proxy', '')655    monkeypatch.setenv('no_proxy', '')656    monkeypatch.setenv('NO_PROXY', '')657    monkeypatch.setattr(winreg, 'OpenKey', OpenKey)658    monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)659660661@pytest.mark.parametrize(662    'env_name, value', (663            ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),664            ('no_proxy', None),665            ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),666            ('a_new_key', None),667    ))668def test_set_environ(env_name, value):669    """Tests set_environ will set environ values and will restore the environ."""670    environ_copy = copy.deepcopy(os.environ)671    with set_environ(env_name, value):672        assert os.environ.get(env_name) == value673674    assert os.environ == environ_copy675676677def test_set_environ_raises_exception():678    """Tests set_environ will raise exceptions in context when the679    value parameter is None."""680    with pytest.raises(Exception) as exception:681        with set_environ('test1', None):682            raise Exception('Expected exception')683684    assert 'Expected exception' in str(exception.value)