Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

544 lines · 16.8 KiB · Python

Last changed by

Merge pull request #3695 from nateprewitt/idna_bypassCory Benfieldbefore adoption5c45494

History of this file

Take it

1# -*- coding: utf-8 -*-23from io import BytesIO45import pytest6from requests import compat7from requests.cookies import RequestsCookieJar, cookiejar_from_dict8from requests.structures import CaseInsensitiveDict9from requests.utils import (10    address_in_network, dotted_netmask,11    get_auth_from_url, get_encoding_from_headers,12    get_encodings_from_content, get_environ_proxies,13    guess_filename, guess_json_utf, is_ipv4_address,14    is_valid_cidr, iter_slices, parse_dict_header,15    parse_header_links, prepend_scheme_if_needed,16    requote_uri, select_proxy, should_bypass_proxies, super_len,17    to_key_val_list, to_native_string,18    unquote_header_value, unquote_unreserved,19    urldefragauth, add_dict_to_cookiejar)20from requests._internal_utils import unicode_is_ascii2122from .compat import StringIO, cStringIO232425class TestSuperLen:2627    @pytest.mark.parametrize(28        'stream, value', (29            (StringIO.StringIO, 'Test'),30            (BytesIO, b'Test'),31            pytest.mark.skipif('cStringIO is None')((cStringIO, 'Test')),32        ))33    def test_io_streams(self, stream, value):34        """Ensures that we properly deal with different kinds of IO streams."""35        assert super_len(stream()) == 036        assert super_len(stream(value)) == 43738    def test_super_len_correctly_calculates_len_of_partially_read_file(self):39        """Ensure that we handle partially consumed file like objects."""40        s = StringIO.StringIO()41        s.write('foobarbogus')42        assert super_len(s) == 04344    @pytest.mark.parametrize('error', [IOError, OSError])45    def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):46        """If tell() raises errors, assume the cursor is at position zero."""47        class BoomFile(object):48            def __len__(self):49                return 55051            def tell(self):52                raise error()5354        assert super_len(BoomFile()) == 05556    @pytest.mark.parametrize('error', [IOError, OSError])57    def test_super_len_tell_ioerror(self, error):58        """Ensure that if tell gives an IOError super_len doesn't fail"""59        class NoLenBoomFile(object):60            def tell(self):61                raise error()6263            def seek(self, offset, whence):64                pass6566        assert super_len(NoLenBoomFile()) == 06768    def test_string(self):69        assert super_len('Test') == 47071    @pytest.mark.parametrize(72        'mode, warnings_num', (73            ('r', 1),74            ('rb', 0),75        ))76    def test_file(self, tmpdir, mode, warnings_num, recwarn):77        file_obj = tmpdir.join('test.txt')78        file_obj.write('Test')79        with file_obj.open(mode) as fd:80            assert super_len(fd) == 481        assert len(recwarn) == warnings_num8283    def test_super_len_with__len__(self):84        foo = [1,2,3,4]85        len_foo = super_len(foo)86        assert len_foo == 48788    def test_super_len_with_no__len__(self):89        class LenFile(object):90            def __init__(self):91                self.len = 59293        assert super_len(LenFile()) == 59495    def test_super_len_with_tell(self):96        foo = StringIO.StringIO('12345')97        assert super_len(foo) == 598        foo.read(2)99        assert super_len(foo) == 3100101    def test_super_len_with_fileno(self):102        with open(__file__, 'rb') as f:103            length = super_len(f)104            file_data = f.read()105        assert length == len(file_data)106107    def test_super_len_with_no_matches(self):108        """Ensure that objects without any length methods default to 0"""109        assert super_len(object()) == 0110111112class TestToKeyValList:113114    @pytest.mark.parametrize(115        'value, expected', (116            ([('key', 'val')], [('key', 'val')]),117            ((('key', 'val'), ), [('key', 'val')]),118            ({'key': 'val'}, [('key', 'val')]),119            (None, None)120        ))121    def test_valid(self, value, expected):122        assert to_key_val_list(value) == expected123124    def test_invalid(self):125        with pytest.raises(ValueError):126            to_key_val_list('string')127128129class TestUnquoteHeaderValue:130131    @pytest.mark.parametrize(132        'value, expected', (133            (None, None),134            ('Test', 'Test'),135            ('"Test"', 'Test'),136            ('"Test\\\\"', 'Test\\'),137            ('"\\\\Comp\\Res"', '\\Comp\\Res'),138        ))139    def test_valid(self, value, expected):140        assert unquote_header_value(value) == expected141142    def test_is_filename(self):143        assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'144145146class TestGetEnvironProxies:147    """Ensures that IP addresses are correctly matches with ranges148    in no_proxy variable.149    """150151    @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])152    def no_proxy(self, request, monkeypatch):153        monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')154155    @pytest.mark.parametrize(156        'url', (157            'http://192.168.0.1:5000/',158            'http://192.168.0.1/',159            'http://172.16.1.1/',160            'http://172.16.1.1:5000/',161            'http://localhost.localdomain:5000/v1.0/',162        ))163    def test_bypass(self, url):164        assert get_environ_proxies(url) == {}165166    @pytest.mark.parametrize(167        'url', (168            'http://192.168.1.1:5000/',169            'http://192.168.1.1/',170            'http://www.requests.com/',171        ))172    def test_not_bypass(self, url):173        assert get_environ_proxies(url) != {}174175176class TestIsIPv4Address:177178    def test_valid(self):179        assert is_ipv4_address('8.8.8.8')180181    @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))182    def test_invalid(self, value):183        assert not is_ipv4_address(value)184185186class TestIsValidCIDR:187188    def test_valid(self):189        assert is_valid_cidr('192.168.1.0/24')190191    @pytest.mark.parametrize(192        'value', (193            '8.8.8.8',194            '192.168.1.0/a',195            '192.168.1.0/128',196            '192.168.1.0/-1',197            '192.168.1.999/24',198        ))199    def test_invalid(self, value):200        assert not is_valid_cidr(value)201202203class TestAddressInNetwork:204205    def test_valid(self):206        assert address_in_network('192.168.1.1', '192.168.1.0/24')207208    def test_invalid(self):209        assert not address_in_network('172.16.0.1', '192.168.1.0/24')210211212class TestGuessFilename:213214    @pytest.mark.parametrize(215        'value', (1, type('Fake', (object,), {'name': 1})()),216    )217    def test_guess_filename_invalid(self, value):218        assert guess_filename(value) is None219220    @pytest.mark.parametrize(221        'value, expected_type', (222            (b'value', compat.bytes),223            (b'value'.decode('utf-8'), compat.str)224        ))225    def test_guess_filename_valid(self, value, expected_type):226        obj = type('Fake', (object,), {'name': value})()227        result = guess_filename(obj)228        assert result == value229        assert isinstance(result, expected_type)230231232class TestContentEncodingDetection:233234    def test_none(self):235        encodings = get_encodings_from_content('')236        assert not len(encodings)237238    @pytest.mark.parametrize(239        'content', (240            # HTML5 meta charset attribute241            '<meta charset="UTF-8">',242            # HTML4 pragma directive243            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',244            # XHTML 1.x served with text/html MIME type245            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',246            # XHTML 1.x served as XML247            '<?xml version="1.0" encoding="UTF-8"?>',248        ))249    def test_pragmas(self, content):250        encodings = get_encodings_from_content(content)251        assert len(encodings) == 1252        assert encodings[0] == 'UTF-8'253254    def test_precedence(self):255        content = '''256        <?xml version="1.0" encoding="XML"?>257        <meta charset="HTML5">258        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />259        '''.strip()260        assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']261262263class TestGuessJSONUTF:264265    @pytest.mark.parametrize(266        'encoding', (267            'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',268            'utf-32-be', 'utf-32-le'269        ))270    def test_encoded(self, encoding):271        data = '{}'.encode(encoding)272        assert guess_json_utf(data) == encoding273274    def test_bad_utf_like_encoding(self):275        assert guess_json_utf(b'\x00\x00\x00\x00') is None276277278USER = PASSWORD = "%!*'();:@&=+$,/?#[] "279ENCODED_USER = compat.quote(USER, '')280ENCODED_PASSWORD = compat.quote(PASSWORD, '')281282283@pytest.mark.parametrize(284    'url, auth', (285        (286            'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +287            'request.com/url.html#test',288            (USER, PASSWORD)289        ),290        (291            'http://user:pass@complex.url.com/path?query=yes',292            ('user', 'pass')293        ),294        (295            'http://user:pass%20pass@complex.url.com/path?query=yes',296            ('user', 'pass pass')297        ),298        (299            'http://user:pass pass@complex.url.com/path?query=yes',300            ('user', 'pass pass')301        ),302        (303            'http://user%25user:pass@complex.url.com/path?query=yes',304            ('user%user', 'pass')305        ),306        (307            'http://user:pass%23pass@complex.url.com/path?query=yes',308            ('user', 'pass#pass')309        ),310        (311            'http://complex.url.com/path?query=yes',312            ('', '')313        ),314    ))315def test_get_auth_from_url(url, auth):316    assert get_auth_from_url(url) == auth317318319@pytest.mark.parametrize(320    'uri, expected', (321        (322            # Ensure requoting doesn't break expectations323            'http://example.com/fiz?buz=%25ppicture',324            'http://example.com/fiz?buz=%25ppicture',325        ),326        (327            # Ensure we handle unquoted percent signs in redirects328            'http://example.com/fiz?buz=%ppicture',329            'http://example.com/fiz?buz=%25ppicture',330        ),331    ))332def test_requote_uri_with_unquoted_percents(uri, expected):333    """See: https://github.com/kennethreitz/requests/issues/2356"""334    assert requote_uri(uri) == expected335336337@pytest.mark.parametrize(338    'uri, expected', (339        (340            # Illegal bytes341            'http://example.com/?a=%--',342            'http://example.com/?a=%--',343        ),344        (345            # Reserved characters346            'http://example.com/?a=%300',347            'http://example.com/?a=00',348        )349    ))350def test_unquote_unreserved(uri, expected):351    assert unquote_unreserved(uri) == expected352353354@pytest.mark.parametrize(355    'mask, expected', (356        (8, '255.0.0.0'),357        (24, '255.255.255.0'),358        (25, '255.255.255.128'),359    ))360def test_dotted_netmask(mask, expected):361    assert dotted_netmask(mask) == expected362363364http_proxies = {'http': 'http://http.proxy',365                'http://some.host': 'http://some.host.proxy'}366all_proxies = {'all': 'socks5://http.proxy',367               'all://some.host': 'socks5://some.host.proxy'}368mixed_proxies = {'http': 'http://http.proxy',369                 'http://some.host': 'http://some.host.proxy',370                 'all': 'socks5://http.proxy'}371@pytest.mark.parametrize(372    'url, expected, proxies', (373        ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),374        ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),375        ('hTTp:///path', 'http://http.proxy', http_proxies),376        ('hTTps://Other.Host', None, http_proxies),377        ('file:///etc/motd', None, http_proxies),378379        ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),380        ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),381        ('hTTp:///path', 'socks5://http.proxy', all_proxies),382        ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),383384        ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),385        ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),386        ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),387        ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),388        ('https://', 'socks5://http.proxy', mixed_proxies),389        # XXX: unsure whether this is reasonable behavior390        ('file:///etc/motd', 'socks5://http.proxy', all_proxies),391    ))392def test_select_proxies(url, expected, proxies):393    """Make sure we can select per-host proxies correctly."""394    assert select_proxy(url, proxies) == expected395396397@pytest.mark.parametrize(398    'value, expected', (399        ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),400        ('key_without_value', {'key_without_value': None})401    ))402def test_parse_dict_header(value, expected):403    assert parse_dict_header(value) == expected404405406@pytest.mark.parametrize(407    'value, expected', (408        (409            CaseInsensitiveDict(),410            None411        ),412        (413            CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),414            'utf-8'415        ),416        (417            CaseInsensitiveDict({'content-type': 'text/plain'}),418            'ISO-8859-1'419        ),420    ))421def test_get_encoding_from_headers(value, expected):422    assert get_encoding_from_headers(value) == expected423424425@pytest.mark.parametrize(426    'value, length', (427        ('', 0),428        ('T', 1),429        ('Test', 4),430        ('Cont', 0),431        ('Other', -5),432        ('Content', None),433    ))434def test_iter_slices(value, length):435    if length is None or (length <= 0 and len(value) > 0):436        # Reads all content at once437        assert len(list(iter_slices(value, length))) == 1438    else:439        assert len(list(iter_slices(value, 1))) == length440441442@pytest.mark.parametrize(443    'value, expected', (444        (445            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',446            [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]447        ),448        (449            '<http:/.../front.jpeg>',450            [{'url': 'http:/.../front.jpeg'}]451        ),452        (453            '<http:/.../front.jpeg>;',454            [{'url': 'http:/.../front.jpeg'}]455        ),456        (457            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',458            [459                {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},460                {'url': 'http://.../back.jpeg'}461            ]462        ),463    ))464def test_parse_header_links(value, expected):465    assert parse_header_links(value) == expected466467468@pytest.mark.parametrize(469    'value, expected', (470        ('example.com/path', 'http://example.com/path'),471        ('//example.com/path', 'http://example.com/path'),472    ))473def test_prepend_scheme_if_needed(value, expected):474    assert prepend_scheme_if_needed(value, 'http') == expected475476477@pytest.mark.parametrize(478    'value, expected', (479        ('T', 'T'),480        (b'T', 'T'),481        (u'T', 'T'),482    ))483def test_to_native_string(value, expected):484    assert to_native_string(value) == expected485486487@pytest.mark.parametrize(488    'url, expected', (489        ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),490        ('http://example.com/path', 'http://example.com/path'),491        ('//u:p@example.com/path', '//example.com/path'),492        ('//example.com/path', '//example.com/path'),493        ('example.com/path', '//example.com/path'),494        ('scheme:u:p@example.com/path', 'scheme://example.com/path'),495    ))496def test_urldefragauth(url, expected):497    assert urldefragauth(url) == expected498499500@pytest.mark.parametrize(501    'url, expected', (502            ('http://192.168.0.1:5000/', True),503            ('http://192.168.0.1/', True),504            ('http://172.16.1.1/', True),505            ('http://172.16.1.1:5000/', True),506            ('http://localhost.localdomain:5000/v1.0/', True),507            ('http://172.16.1.12/', False),508            ('http://172.16.1.12:5000/', False),509            ('http://google.com:5000/v1.0/', False),510    ))511def test_should_bypass_proxies(url, expected, monkeypatch):512    """Tests for function should_bypass_proxies to check if proxy513    can be bypassed or not514    """515    monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')516    monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')517    assert should_bypass_proxies(url) == expected518519520@pytest.mark.parametrize(521    'cookiejar', (522        compat.cookielib.CookieJar(),523        RequestsCookieJar()524    ))525def test_add_dict_to_cookiejar(cookiejar):526    """Ensure add_dict_to_cookiejar works for527    non-RequestsCookieJar CookieJars528    """529    cookiedict = {'test': 'cookies',530                  'good': 'cookies'}531    cj = add_dict_to_cookiejar(cookiejar, cookiedict)532    cookies = dict((cookie.name, cookie.value) for cookie in cj)533    assert cookiedict == cookies534535536@pytest.mark.parametrize(537    'value, expected', (538                (u'test', True),539                (u'æíöû', False),540                (u'ジェーピーニック', False),541    )542)543def test_unicode_is_ascii(value, expected):544    assert unicode_is_ascii(value) is expected