Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

601 lines · 19.0 KiB · Python

Last changed by

Merge pull request #3865 from JohnVillalovos/masterKenneth Reitzbefore adoption6bd6249

History of this file

Take it

1# -*- coding: utf-8 -*-23from io import BytesIO45import pytest6from requests import compat7from requests.cookies import RequestsCookieJar8from 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, no_proxy=None) == {}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, no_proxy=None) != {}174175    @pytest.mark.parametrize(176        'url', (177            'http://192.168.1.1:5000/',178            'http://192.168.1.1/',179            'http://www.requests.com/',180        ))181    def test_bypass_no_proxy_keyword(self, url):182        no_proxy = '192.168.1.1,requests.com'183        assert get_environ_proxies(url, no_proxy=no_proxy) == {}184185    @pytest.mark.parametrize(186        'url', (187            'http://192.168.0.1:5000/',188            'http://192.168.0.1/',189            'http://172.16.1.1/',190            'http://172.16.1.1:5000/',191            'http://localhost.localdomain:5000/v1.0/',192        ))193    def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):194        # This is testing that the 'no_proxy' argument overrides the195        # environment variable 'no_proxy'196        monkeypatch.setenv('http_proxy', 'http://proxy.example.com:3128/')197        no_proxy = '192.168.1.1,requests.com'198        assert get_environ_proxies(url, no_proxy=no_proxy) != {}199200201class TestIsIPv4Address:202203    def test_valid(self):204        assert is_ipv4_address('8.8.8.8')205206    @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))207    def test_invalid(self, value):208        assert not is_ipv4_address(value)209210211class TestIsValidCIDR:212213    def test_valid(self):214        assert is_valid_cidr('192.168.1.0/24')215216    @pytest.mark.parametrize(217        'value', (218            '8.8.8.8',219            '192.168.1.0/a',220            '192.168.1.0/128',221            '192.168.1.0/-1',222            '192.168.1.999/24',223        ))224    def test_invalid(self, value):225        assert not is_valid_cidr(value)226227228class TestAddressInNetwork:229230    def test_valid(self):231        assert address_in_network('192.168.1.1', '192.168.1.0/24')232233    def test_invalid(self):234        assert not address_in_network('172.16.0.1', '192.168.1.0/24')235236237class TestGuessFilename:238239    @pytest.mark.parametrize(240        'value', (1, type('Fake', (object,), {'name': 1})()),241    )242    def test_guess_filename_invalid(self, value):243        assert guess_filename(value) is None244245    @pytest.mark.parametrize(246        'value, expected_type', (247            (b'value', compat.bytes),248            (b'value'.decode('utf-8'), compat.str)249        ))250    def test_guess_filename_valid(self, value, expected_type):251        obj = type('Fake', (object,), {'name': value})()252        result = guess_filename(obj)253        assert result == value254        assert isinstance(result, expected_type)255256257class TestContentEncodingDetection:258259    def test_none(self):260        encodings = get_encodings_from_content('')261        assert not len(encodings)262263    @pytest.mark.parametrize(264        'content', (265            # HTML5 meta charset attribute266            '<meta charset="UTF-8">',267            # HTML4 pragma directive268            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',269            # XHTML 1.x served with text/html MIME type270            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',271            # XHTML 1.x served as XML272            '<?xml version="1.0" encoding="UTF-8"?>',273        ))274    def test_pragmas(self, content):275        encodings = get_encodings_from_content(content)276        assert len(encodings) == 1277        assert encodings[0] == 'UTF-8'278279    def test_precedence(self):280        content = '''281        <?xml version="1.0" encoding="XML"?>282        <meta charset="HTML5">283        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />284        '''.strip()285        assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']286287288class TestGuessJSONUTF:289290    @pytest.mark.parametrize(291        'encoding', (292            'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',293            'utf-32-be', 'utf-32-le'294        ))295    def test_encoded(self, encoding):296        data = '{}'.encode(encoding)297        assert guess_json_utf(data) == encoding298299    def test_bad_utf_like_encoding(self):300        assert guess_json_utf(b'\x00\x00\x00\x00') is None301302    @pytest.mark.parametrize(303        ('encoding', 'expected'), (304            ('utf-16-be', 'utf-16'),305            ('utf-16-le', 'utf-16'),306            ('utf-32-be', 'utf-32'),307            ('utf-32-le', 'utf-32')308        ))309    def test_guess_by_bom(self, encoding, expected):310        data = u'\ufeff{}'.encode(encoding)311        assert guess_json_utf(data) == expected312313314USER = PASSWORD = "%!*'();:@&=+$,/?#[] "315ENCODED_USER = compat.quote(USER, '')316ENCODED_PASSWORD = compat.quote(PASSWORD, '')317318319@pytest.mark.parametrize(320    'url, auth', (321        (322            'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +323            'request.com/url.html#test',324            (USER, PASSWORD)325        ),326        (327            'http://user:pass@complex.url.com/path?query=yes',328            ('user', 'pass')329        ),330        (331            'http://user:pass%20pass@complex.url.com/path?query=yes',332            ('user', 'pass pass')333        ),334        (335            'http://user:pass pass@complex.url.com/path?query=yes',336            ('user', 'pass pass')337        ),338        (339            'http://user%25user:pass@complex.url.com/path?query=yes',340            ('user%user', 'pass')341        ),342        (343            'http://user:pass%23pass@complex.url.com/path?query=yes',344            ('user', 'pass#pass')345        ),346        (347            'http://complex.url.com/path?query=yes',348            ('', '')349        ),350    ))351def test_get_auth_from_url(url, auth):352    assert get_auth_from_url(url) == auth353354355@pytest.mark.parametrize(356    'uri, expected', (357        (358            # Ensure requoting doesn't break expectations359            'http://example.com/fiz?buz=%25ppicture',360            'http://example.com/fiz?buz=%25ppicture',361        ),362        (363            # Ensure we handle unquoted percent signs in redirects364            'http://example.com/fiz?buz=%ppicture',365            'http://example.com/fiz?buz=%25ppicture',366        ),367    ))368def test_requote_uri_with_unquoted_percents(uri, expected):369    """See: https://github.com/kennethreitz/requests/issues/2356"""370    assert requote_uri(uri) == expected371372373@pytest.mark.parametrize(374    'uri, expected', (375        (376            # Illegal bytes377            'http://example.com/?a=%--',378            'http://example.com/?a=%--',379        ),380        (381            # Reserved characters382            'http://example.com/?a=%300',383            'http://example.com/?a=00',384        )385    ))386def test_unquote_unreserved(uri, expected):387    assert unquote_unreserved(uri) == expected388389390@pytest.mark.parametrize(391    'mask, expected', (392        (8, '255.0.0.0'),393        (24, '255.255.255.0'),394        (25, '255.255.255.128'),395    ))396def test_dotted_netmask(mask, expected):397    assert dotted_netmask(mask) == expected398399400http_proxies = {'http': 'http://http.proxy',401                'http://some.host': 'http://some.host.proxy'}402all_proxies = {'all': 'socks5://http.proxy',403               'all://some.host': 'socks5://some.host.proxy'}404mixed_proxies = {'http': 'http://http.proxy',405                 'http://some.host': 'http://some.host.proxy',406                 'all': 'socks5://http.proxy'}407@pytest.mark.parametrize(408    'url, expected, proxies', (409        ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),410        ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),411        ('hTTp:///path', 'http://http.proxy', http_proxies),412        ('hTTps://Other.Host', None, http_proxies),413        ('file:///etc/motd', None, http_proxies),414415        ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),416        ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),417        ('hTTp:///path', 'socks5://http.proxy', all_proxies),418        ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),419420        ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),421        ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),422        ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),423        ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),424        ('https://', 'socks5://http.proxy', mixed_proxies),425        # XXX: unsure whether this is reasonable behavior426        ('file:///etc/motd', 'socks5://http.proxy', all_proxies),427    ))428def test_select_proxies(url, expected, proxies):429    """Make sure we can select per-host proxies correctly."""430    assert select_proxy(url, proxies) == expected431432433@pytest.mark.parametrize(434    'value, expected', (435        ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),436        ('key_without_value', {'key_without_value': None})437    ))438def test_parse_dict_header(value, expected):439    assert parse_dict_header(value) == expected440441442@pytest.mark.parametrize(443    'value, expected', (444        (445            CaseInsensitiveDict(),446            None447        ),448        (449            CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),450            'utf-8'451        ),452        (453            CaseInsensitiveDict({'content-type': 'text/plain'}),454            'ISO-8859-1'455        ),456    ))457def test_get_encoding_from_headers(value, expected):458    assert get_encoding_from_headers(value) == expected459460461@pytest.mark.parametrize(462    'value, length', (463        ('', 0),464        ('T', 1),465        ('Test', 4),466        ('Cont', 0),467        ('Other', -5),468        ('Content', None),469    ))470def test_iter_slices(value, length):471    if length is None or (length <= 0 and len(value) > 0):472        # Reads all content at once473        assert len(list(iter_slices(value, length))) == 1474    else:475        assert len(list(iter_slices(value, 1))) == length476477478@pytest.mark.parametrize(479    'value, expected', (480        (481            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',482            [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]483        ),484        (485            '<http:/.../front.jpeg>',486            [{'url': 'http:/.../front.jpeg'}]487        ),488        (489            '<http:/.../front.jpeg>;',490            [{'url': 'http:/.../front.jpeg'}]491        ),492        (493            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',494            [495                {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},496                {'url': 'http://.../back.jpeg'}497            ]498        ),499    ))500def test_parse_header_links(value, expected):501    assert parse_header_links(value) == expected502503504@pytest.mark.parametrize(505    'value, expected', (506        ('example.com/path', 'http://example.com/path'),507        ('//example.com/path', 'http://example.com/path'),508    ))509def test_prepend_scheme_if_needed(value, expected):510    assert prepend_scheme_if_needed(value, 'http') == expected511512513@pytest.mark.parametrize(514    'value, expected', (515        ('T', 'T'),516        (b'T', 'T'),517        (u'T', 'T'),518    ))519def test_to_native_string(value, expected):520    assert to_native_string(value) == expected521522523@pytest.mark.parametrize(524    'url, expected', (525        ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),526        ('http://example.com/path', 'http://example.com/path'),527        ('//u:p@example.com/path', '//example.com/path'),528        ('//example.com/path', '//example.com/path'),529        ('example.com/path', '//example.com/path'),530        ('scheme:u:p@example.com/path', 'scheme://example.com/path'),531    ))532def test_urldefragauth(url, expected):533    assert urldefragauth(url) == expected534535536@pytest.mark.parametrize(537    'url, expected', (538            ('http://192.168.0.1:5000/', True),539            ('http://192.168.0.1/', True),540            ('http://172.16.1.1/', True),541            ('http://172.16.1.1:5000/', True),542            ('http://localhost.localdomain:5000/v1.0/', True),543            ('http://172.16.1.12/', False),544            ('http://172.16.1.12:5000/', False),545            ('http://google.com:5000/v1.0/', False),546    ))547def test_should_bypass_proxies(url, expected, monkeypatch):548    """Tests for function should_bypass_proxies to check if proxy549    can be bypassed or not550    """551    monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')552    monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')553    assert should_bypass_proxies(url, no_proxy=None) == expected554555556@pytest.mark.parametrize(557    'cookiejar', (558        compat.cookielib.CookieJar(),559        RequestsCookieJar()560    ))561def test_add_dict_to_cookiejar(cookiejar):562    """Ensure add_dict_to_cookiejar works for563    non-RequestsCookieJar CookieJars564    """565    cookiedict = {'test': 'cookies',566                  'good': 'cookies'}567    cj = add_dict_to_cookiejar(cookiejar, cookiedict)568    cookies = dict((cookie.name, cookie.value) for cookie in cj)569    assert cookiedict == cookies570571572@pytest.mark.parametrize(573    'value, expected', (574                (u'test', True),575                (u'æíöû', False),576                (u'ジェーピーニック', False),577    )578)579def test_unicode_is_ascii(value, expected):580    assert unicode_is_ascii(value) is expected581582583@pytest.mark.parametrize(584    'url, expected', (585            ('http://192.168.0.1:5000/', True),586            ('http://192.168.0.1/', True),587            ('http://172.16.1.1/', True),588            ('http://172.16.1.1:5000/', True),589            ('http://localhost.localdomain:5000/v1.0/', True),590            ('http://172.16.1.12/', False),591            ('http://172.16.1.12:5000/', False),592            ('http://google.com:5000/v1.0/', False),593    ))594def test_should_bypass_proxies_no_proxy(595        url, expected, monkeypatch):596    """Tests for function should_bypass_proxies to check if proxy597    can be bypassed or not using the 'no_proxy' argument598    """599    no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'600    # Test 'no_proxy' argument601    assert should_bypass_proxies(url, no_proxy=no_proxy) == expected