Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

809 lines · 26.3 KiB · Python

Last changed by

Merge pull request #6028 from nateprewitt/prox_auth_fixIan Stapleton Cordascobefore adoption8fa9724

History of this file

Take it

1# -*- coding: utf-8 -*-23import os4import copy5import filecmp6from io import BytesIO7import tarfile8import zipfile9from collections import deque1011import pytest12from requests import compat13from requests.cookies import RequestsCookieJar14from requests.structures import CaseInsensitiveDict15from requests.utils import (16    address_in_network, dotted_netmask, extract_zipped_paths,17    get_auth_from_url, _parse_content_type_header, get_encoding_from_headers,18    get_encodings_from_content, get_environ_proxies,19    guess_filename, guess_json_utf, is_ipv4_address,20    is_valid_cidr, iter_slices, parse_dict_header,21    parse_header_links, prepend_scheme_if_needed,22    requote_uri, select_proxy, should_bypass_proxies, super_len,23    to_key_val_list, to_native_string,24    unquote_header_value, unquote_unreserved,25    urldefragauth, add_dict_to_cookiejar, set_environ)26from requests._internal_utils import unicode_is_ascii2728from .compat import StringIO, cStringIO293031class TestSuperLen:3233    @pytest.mark.parametrize(34        'stream, value', (35            (StringIO.StringIO, 'Test'),36            (BytesIO, b'Test'),37            pytest.param(cStringIO, 'Test',38                         marks=pytest.mark.skipif('cStringIO is None')),39        ))40    def test_io_streams(self, stream, value):41        """Ensures that we properly deal with different kinds of IO streams."""42        assert super_len(stream()) == 043        assert super_len(stream(value)) == 44445    def test_super_len_correctly_calculates_len_of_partially_read_file(self):46        """Ensure that we handle partially consumed file like objects."""47        s = StringIO.StringIO()48        s.write('foobarbogus')49        assert super_len(s) == 05051    @pytest.mark.parametrize('error', [IOError, OSError])52    def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):53        """If tell() raises errors, assume the cursor is at position zero."""54        class BoomFile(object):55            def __len__(self):56                return 55758            def tell(self):59                raise error()6061        assert super_len(BoomFile()) == 06263    @pytest.mark.parametrize('error', [IOError, OSError])64    def test_super_len_tell_ioerror(self, error):65        """Ensure that if tell gives an IOError super_len doesn't fail"""66        class NoLenBoomFile(object):67            def tell(self):68                raise error()6970            def seek(self, offset, whence):71                pass7273        assert super_len(NoLenBoomFile()) == 07475    def test_string(self):76        assert super_len('Test') == 47778    @pytest.mark.parametrize(79        'mode, warnings_num', (80            ('r', 1),81            ('rb', 0),82        ))83    def test_file(self, tmpdir, mode, warnings_num, recwarn):84        file_obj = tmpdir.join('test.txt')85        file_obj.write('Test')86        with file_obj.open(mode) as fd:87            assert super_len(fd) == 488        assert len(recwarn) == warnings_num8990    def test_tarfile_member(self, tmpdir):91        file_obj = tmpdir.join('test.txt')92        file_obj.write('Test')9394        tar_obj = str(tmpdir.join('test.tar'))95        with tarfile.open(tar_obj, 'w') as tar:96            tar.add(str(file_obj), arcname='test.txt')9798        with tarfile.open(tar_obj) as tar:99            member = tar.extractfile('test.txt')100            assert super_len(member) == 4101102    def test_super_len_with__len__(self):103        foo = [1,2,3,4]104        len_foo = super_len(foo)105        assert len_foo == 4106107    def test_super_len_with_no__len__(self):108        class LenFile(object):109            def __init__(self):110                self.len = 5111112        assert super_len(LenFile()) == 5113114    def test_super_len_with_tell(self):115        foo = StringIO.StringIO('12345')116        assert super_len(foo) == 5117        foo.read(2)118        assert super_len(foo) == 3119120    def test_super_len_with_fileno(self):121        with open(__file__, 'rb') as f:122            length = super_len(f)123            file_data = f.read()124        assert length == len(file_data)125126    def test_super_len_with_no_matches(self):127        """Ensure that objects without any length methods default to 0"""128        assert super_len(object()) == 0129130131class TestToKeyValList:132133    @pytest.mark.parametrize(134        'value, expected', (135            ([('key', 'val')], [('key', 'val')]),136            ((('key', 'val'), ), [('key', 'val')]),137            ({'key': 'val'}, [('key', 'val')]),138            (None, None)139        ))140    def test_valid(self, value, expected):141        assert to_key_val_list(value) == expected142143    def test_invalid(self):144        with pytest.raises(ValueError):145            to_key_val_list('string')146147148class TestUnquoteHeaderValue:149150    @pytest.mark.parametrize(151        'value, expected', (152            (None, None),153            ('Test', 'Test'),154            ('"Test"', 'Test'),155            ('"Test\\\\"', 'Test\\'),156            ('"\\\\Comp\\Res"', '\\Comp\\Res'),157        ))158    def test_valid(self, value, expected):159        assert unquote_header_value(value) == expected160161    def test_is_filename(self):162        assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'163164165class TestGetEnvironProxies:166    """Ensures that IP addresses are correctly matches with ranges167    in no_proxy variable.168    """169170    @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])171    def no_proxy(self, request, monkeypatch):172        monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')173174    @pytest.mark.parametrize(175        'url', (176            'http://192.168.0.1:5000/',177            'http://192.168.0.1/',178            'http://172.16.1.1/',179            'http://172.16.1.1:5000/',180            'http://localhost.localdomain:5000/v1.0/',181        ))182    def test_bypass(self, url):183        assert get_environ_proxies(url, no_proxy=None) == {}184185    @pytest.mark.parametrize(186        'url', (187            'http://192.168.1.1:5000/',188            'http://192.168.1.1/',189            'http://www.requests.com/',190        ))191    def test_not_bypass(self, url):192        assert get_environ_proxies(url, no_proxy=None) != {}193194    @pytest.mark.parametrize(195        'url', (196            'http://192.168.1.1:5000/',197            'http://192.168.1.1/',198            'http://www.requests.com/',199        ))200    def test_bypass_no_proxy_keyword(self, url):201        no_proxy = '192.168.1.1,requests.com'202        assert get_environ_proxies(url, no_proxy=no_proxy) == {}203204    @pytest.mark.parametrize(205        'url', (206            'http://192.168.0.1:5000/',207            'http://192.168.0.1/',208            'http://172.16.1.1/',209            'http://172.16.1.1:5000/',210            'http://localhost.localdomain:5000/v1.0/',211        ))212    def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):213        # This is testing that the 'no_proxy' argument overrides the214        # environment variable 'no_proxy'215        monkeypatch.setenv('http_proxy', 'http://proxy.example.com:3128/')216        no_proxy = '192.168.1.1,requests.com'217        assert get_environ_proxies(url, no_proxy=no_proxy) != {}218219220class TestIsIPv4Address:221222    def test_valid(self):223        assert is_ipv4_address('8.8.8.8')224225    @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))226    def test_invalid(self, value):227        assert not is_ipv4_address(value)228229230class TestIsValidCIDR:231232    def test_valid(self):233        assert is_valid_cidr('192.168.1.0/24')234235    @pytest.mark.parametrize(236        'value', (237            '8.8.8.8',238            '192.168.1.0/a',239            '192.168.1.0/128',240            '192.168.1.0/-1',241            '192.168.1.999/24',242        ))243    def test_invalid(self, value):244        assert not is_valid_cidr(value)245246247class TestAddressInNetwork:248249    def test_valid(self):250        assert address_in_network('192.168.1.1', '192.168.1.0/24')251252    def test_invalid(self):253        assert not address_in_network('172.16.0.1', '192.168.1.0/24')254255256class TestGuessFilename:257258    @pytest.mark.parametrize(259        'value', (1, type('Fake', (object,), {'name': 1})()),260    )261    def test_guess_filename_invalid(self, value):262        assert guess_filename(value) is None263264    @pytest.mark.parametrize(265        'value, expected_type', (266            (b'value', compat.bytes),267            (b'value'.decode('utf-8'), compat.str)268        ))269    def test_guess_filename_valid(self, value, expected_type):270        obj = type('Fake', (object,), {'name': value})()271        result = guess_filename(obj)272        assert result == value273        assert isinstance(result, expected_type)274275276class TestExtractZippedPaths:277278    @pytest.mark.parametrize(279        'path', (280            '/',281            __file__,282            pytest.__file__,283            '/etc/invalid/location',284        ))285    def test_unzipped_paths_unchanged(self, path):286        assert path == extract_zipped_paths(path)287288    def test_zipped_paths_extracted(self, tmpdir):289        zipped_py = tmpdir.join('test.zip')290        with zipfile.ZipFile(zipped_py.strpath, 'w') as f:291            f.write(__file__)292293        _, name = os.path.splitdrive(__file__)294        zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r'\/'))295        extracted_path = extract_zipped_paths(zipped_path)296297        assert extracted_path != zipped_path298        assert os.path.exists(extracted_path)299        assert filecmp.cmp(extracted_path, __file__)300301    def test_invalid_unc_path(self):302        path = r"\\localhost\invalid\location"303        assert extract_zipped_paths(path) == path304305306class TestContentEncodingDetection:307308    def test_none(self):309        encodings = get_encodings_from_content('')310        assert not len(encodings)311312    @pytest.mark.parametrize(313        'content', (314            # HTML5 meta charset attribute315            '<meta charset="UTF-8">',316            # HTML4 pragma directive317            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',318            # XHTML 1.x served with text/html MIME type319            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',320            # XHTML 1.x served as XML321            '<?xml version="1.0" encoding="UTF-8"?>',322        ))323    def test_pragmas(self, content):324        encodings = get_encodings_from_content(content)325        assert len(encodings) == 1326        assert encodings[0] == 'UTF-8'327328    def test_precedence(self):329        content = '''330        <?xml version="1.0" encoding="XML"?>331        <meta charset="HTML5">332        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />333        '''.strip()334        assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']335336337class TestGuessJSONUTF:338339    @pytest.mark.parametrize(340        'encoding', (341            'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',342            'utf-32-be', 'utf-32-le'343        ))344    def test_encoded(self, encoding):345        data = '{}'.encode(encoding)346        assert guess_json_utf(data) == encoding347348    def test_bad_utf_like_encoding(self):349        assert guess_json_utf(b'\x00\x00\x00\x00') is None350351    @pytest.mark.parametrize(352        ('encoding', 'expected'), (353            ('utf-16-be', 'utf-16'),354            ('utf-16-le', 'utf-16'),355            ('utf-32-be', 'utf-32'),356            ('utf-32-le', 'utf-32')357        ))358    def test_guess_by_bom(self, encoding, expected):359        data = u'\ufeff{}'.encode(encoding)360        assert guess_json_utf(data) == expected361362363USER = PASSWORD = "%!*'();:@&=+$,/?#[] "364ENCODED_USER = compat.quote(USER, '')365ENCODED_PASSWORD = compat.quote(PASSWORD, '')366367368@pytest.mark.parametrize(369    'url, auth', (370        (371            'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +372            'request.com/url.html#test',373            (USER, PASSWORD)374        ),375        (376            'http://user:pass@complex.url.com/path?query=yes',377            ('user', 'pass')378        ),379        (380            'http://user:pass%20pass@complex.url.com/path?query=yes',381            ('user', 'pass pass')382        ),383        (384            'http://user:pass pass@complex.url.com/path?query=yes',385            ('user', 'pass pass')386        ),387        (388            'http://user%25user:pass@complex.url.com/path?query=yes',389            ('user%user', 'pass')390        ),391        (392            'http://user:pass%23pass@complex.url.com/path?query=yes',393            ('user', 'pass#pass')394        ),395        (396            'http://complex.url.com/path?query=yes',397            ('', '')398        ),399    ))400def test_get_auth_from_url(url, auth):401    assert get_auth_from_url(url) == auth402403404@pytest.mark.parametrize(405    'uri, expected', (406        (407            # Ensure requoting doesn't break expectations408            'http://example.com/fiz?buz=%25ppicture',409            'http://example.com/fiz?buz=%25ppicture',410        ),411        (412            # Ensure we handle unquoted percent signs in redirects413            'http://example.com/fiz?buz=%ppicture',414            'http://example.com/fiz?buz=%25ppicture',415        ),416    ))417def test_requote_uri_with_unquoted_percents(uri, expected):418    """See: https://github.com/psf/requests/issues/2356"""419    assert requote_uri(uri) == expected420421422@pytest.mark.parametrize(423    'uri, expected', (424        (425            # Illegal bytes426            'http://example.com/?a=%--',427            'http://example.com/?a=%--',428        ),429        (430            # Reserved characters431            'http://example.com/?a=%300',432            'http://example.com/?a=00',433        )434    ))435def test_unquote_unreserved(uri, expected):436    assert unquote_unreserved(uri) == expected437438439@pytest.mark.parametrize(440    'mask, expected', (441        (8, '255.0.0.0'),442        (24, '255.255.255.0'),443        (25, '255.255.255.128'),444    ))445def test_dotted_netmask(mask, expected):446    assert dotted_netmask(mask) == expected447448449http_proxies = {'http': 'http://http.proxy',450                'http://some.host': 'http://some.host.proxy'}451all_proxies = {'all': 'socks5://http.proxy',452               'all://some.host': 'socks5://some.host.proxy'}453mixed_proxies = {'http': 'http://http.proxy',454                 'http://some.host': 'http://some.host.proxy',455                 'all': 'socks5://http.proxy'}456@pytest.mark.parametrize(457    'url, expected, proxies', (458        ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),459        ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),460        ('hTTp:///path', 'http://http.proxy', http_proxies),461        ('hTTps://Other.Host', None, http_proxies),462        ('file:///etc/motd', None, http_proxies),463464        ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),465        ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),466        ('hTTp:///path', 'socks5://http.proxy', all_proxies),467        ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),468469        ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),470        ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),471        ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),472        ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),473        ('https://', 'socks5://http.proxy', mixed_proxies),474        # XXX: unsure whether this is reasonable behavior475        ('file:///etc/motd', 'socks5://http.proxy', all_proxies),476    ))477def test_select_proxies(url, expected, proxies):478    """Make sure we can select per-host proxies correctly."""479    assert select_proxy(url, proxies) == expected480481482@pytest.mark.parametrize(483    'value, expected', (484        ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),485        ('key_without_value', {'key_without_value': None})486    ))487def test_parse_dict_header(value, expected):488    assert parse_dict_header(value) == expected489490491@pytest.mark.parametrize(492    'value, expected', (493        (494            'application/xml',495            ('application/xml', {})496        ),497        (498            'application/json ; charset=utf-8',499            ('application/json', {'charset': 'utf-8'})500        ),501        (502            'application/json ; Charset=utf-8',503            ('application/json', {'charset': 'utf-8'})504        ),505        (506            'text/plain',507            ('text/plain', {})508        ),509        (510            'multipart/form-data; boundary = something ; boundary2=\'something_else\' ; no_equals ',511            ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})512        ),513        (514                'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',515                ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})516        ),517        (518            'multipart/form-data; boundary = something ; \'boundary2=something_else\' ; no_equals ',519            ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})520        ),521        (522            'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',523            ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})524        ),525        (526            'application/json ; ; ',527            ('application/json', {})528        )529    ))530def test__parse_content_type_header(value, expected):531    assert _parse_content_type_header(value) == expected532533534@pytest.mark.parametrize(535    'value, expected', (536        (537            CaseInsensitiveDict(),538            None539        ),540        (541            CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),542            'utf-8'543        ),544        (545            CaseInsensitiveDict({'content-type': 'text/plain'}),546            'ISO-8859-1'547        ),548    ))549def test_get_encoding_from_headers(value, expected):550    assert get_encoding_from_headers(value) == expected551552553@pytest.mark.parametrize(554    'value, length', (555        ('', 0),556        ('T', 1),557        ('Test', 4),558        ('Cont', 0),559        ('Other', -5),560        ('Content', None),561    ))562def test_iter_slices(value, length):563    if length is None or (length <= 0 and len(value) > 0):564        # Reads all content at once565        assert len(list(iter_slices(value, length))) == 1566    else:567        assert len(list(iter_slices(value, 1))) == length568569570@pytest.mark.parametrize(571    'value, expected', (572        (573            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',574            [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]575        ),576        (577            '<http:/.../front.jpeg>',578            [{'url': 'http:/.../front.jpeg'}]579        ),580        (581            '<http:/.../front.jpeg>;',582            [{'url': 'http:/.../front.jpeg'}]583        ),584        (585            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',586            [587                {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},588                {'url': 'http://.../back.jpeg'}589            ]590        ),591        (592            '',593            []594        ),595    ))596def test_parse_header_links(value, expected):597    assert parse_header_links(value) == expected598599600@pytest.mark.parametrize(601    'value, expected', (602        ('example.com/path', 'http://example.com/path'),603        ('//example.com/path', 'http://example.com/path'),604        ('example.com:80', 'http://example.com:80'),605        (606            'http://user:pass@example.com/path?query',607            'http://user:pass@example.com/path?query'608        ),609        (610            'http://user@example.com/path?query',611            'http://user@example.com/path?query'612        )613    ))614def test_prepend_scheme_if_needed(value, expected):615    assert prepend_scheme_if_needed(value, 'http') == expected616617618@pytest.mark.parametrize(619    'value, expected', (620        ('T', 'T'),621        (b'T', 'T'),622        (u'T', 'T'),623    ))624def test_to_native_string(value, expected):625    assert to_native_string(value) == expected626627628@pytest.mark.parametrize(629    'url, expected', (630        ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),631        ('http://example.com/path', 'http://example.com/path'),632        ('//u:p@example.com/path', '//example.com/path'),633        ('//example.com/path', '//example.com/path'),634        ('example.com/path', '//example.com/path'),635        ('scheme:u:p@example.com/path', 'scheme://example.com/path'),636    ))637def test_urldefragauth(url, expected):638    assert urldefragauth(url) == expected639640641@pytest.mark.parametrize(642    'url, expected', (643            ('http://192.168.0.1:5000/', True),644            ('http://192.168.0.1/', True),645            ('http://172.16.1.1/', True),646            ('http://172.16.1.1:5000/', True),647            ('http://localhost.localdomain:5000/v1.0/', True),648            ('http://google.com:6000/', True),649            ('http://172.16.1.12/', False),650            ('http://172.16.1.12:5000/', False),651            ('http://google.com:5000/v1.0/', False),652            ('file:///some/path/on/disk', True),653    ))654def test_should_bypass_proxies(url, expected, monkeypatch):655    """Tests for function should_bypass_proxies to check if proxy656    can be bypassed or not657    """658    monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')659    monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')660    assert should_bypass_proxies(url, no_proxy=None) == expected661662663@pytest.mark.parametrize(664    'url, expected', (665            ('http://172.16.1.1/', '172.16.1.1'),666            ('http://172.16.1.1:5000/', '172.16.1.1'),667            ('http://user:pass@172.16.1.1', '172.16.1.1'),668            ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),669            ('http://hostname/', 'hostname'),670            ('http://hostname:5000/', 'hostname'),671            ('http://user:pass@hostname', 'hostname'),672            ('http://user:pass@hostname:5000', 'hostname'),673    ))674def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):675    """The proxy_bypass function should be called with a hostname or IP without676    a port number or auth credentials.677    """678    proxy_bypass = mocker.patch('requests.utils.proxy_bypass')679    should_bypass_proxies(url, no_proxy=None)680    proxy_bypass.assert_called_once_with(expected)681682683@pytest.mark.parametrize(684    'cookiejar', (685        compat.cookielib.CookieJar(),686        RequestsCookieJar()687    ))688def test_add_dict_to_cookiejar(cookiejar):689    """Ensure add_dict_to_cookiejar works for690    non-RequestsCookieJar CookieJars691    """692    cookiedict = {'test': 'cookies',693                  'good': 'cookies'}694    cj = add_dict_to_cookiejar(cookiejar, cookiedict)695    cookies = {cookie.name: cookie.value for cookie in cj}696    assert cookiedict == cookies697698699@pytest.mark.parametrize(700    'value, expected', (701                (u'test', True),702                (u'æíöû', False),703                (u'ジェーピーニック', False),704    )705)706def test_unicode_is_ascii(value, expected):707    assert unicode_is_ascii(value) is expected708709710@pytest.mark.parametrize(711    'url, expected', (712            ('http://192.168.0.1:5000/', True),713            ('http://192.168.0.1/', True),714            ('http://172.16.1.1/', True),715            ('http://172.16.1.1:5000/', True),716            ('http://localhost.localdomain:5000/v1.0/', True),717            ('http://172.16.1.12/', False),718            ('http://172.16.1.12:5000/', False),719            ('http://google.com:5000/v1.0/', False),720    ))721def test_should_bypass_proxies_no_proxy(722        url, expected, monkeypatch):723    """Tests for function should_bypass_proxies to check if proxy724    can be bypassed or not using the 'no_proxy' argument725    """726    no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'727    # Test 'no_proxy' argument728    assert should_bypass_proxies(url, no_proxy=no_proxy) == expected729730731@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')732@pytest.mark.parametrize(733    'url, expected, override', (734            ('http://192.168.0.1:5000/', True, None),735            ('http://192.168.0.1/', True, None),736            ('http://172.16.1.1/', True, None),737            ('http://172.16.1.1:5000/', True, None),738            ('http://localhost.localdomain:5000/v1.0/', True, None),739            ('http://172.16.1.22/', False, None),740            ('http://172.16.1.22:5000/', False, None),741            ('http://google.com:5000/v1.0/', False, None),742            ('http://mylocalhostname:5000/v1.0/', True, '<local>'),743            ('http://192.168.0.1/', False, ''),744    ))745def test_should_bypass_proxies_win_registry(url, expected, override,746                                            monkeypatch):747    """Tests for function should_bypass_proxies to check if proxy748    can be bypassed or not with Windows registry settings749    """750    if override is None:751        override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'752    if compat.is_py3:753        import winreg754    else:755        import _winreg as winreg756757    class RegHandle:758        def Close(self):759            pass760761    ie_settings = RegHandle()762    proxyEnableValues = deque([1, "1"])763764    def OpenKey(key, subkey):765        return ie_settings766767    def QueryValueEx(key, value_name):768        if key is ie_settings:769            if value_name == 'ProxyEnable':770                # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)771                proxyEnableValues.rotate()772                return [proxyEnableValues[0]]773            elif value_name == 'ProxyOverride':774                return [override]775776    monkeypatch.setenv('http_proxy', '')777    monkeypatch.setenv('https_proxy', '')778    monkeypatch.setenv('ftp_proxy', '')779    monkeypatch.setenv('no_proxy', '')780    monkeypatch.setenv('NO_PROXY', '')781    monkeypatch.setattr(winreg, 'OpenKey', OpenKey)782    monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)783    assert should_bypass_proxies(url, None) == expected784785786@pytest.mark.parametrize(787    'env_name, value', (788            ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),789            ('no_proxy', None),790            ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),791            ('a_new_key', None),792    ))793def test_set_environ(env_name, value):794    """Tests set_environ will set environ values and will restore the environ."""795    environ_copy = copy.deepcopy(os.environ)796    with set_environ(env_name, value):797        assert os.environ.get(env_name) == value798799    assert os.environ == environ_copy800801802def test_set_environ_raises_exception():803    """Tests set_environ will raise exceptions in context when the804    value parameter is None."""805    with pytest.raises(Exception) as exception:806        with set_environ('test1', None):807            raise Exception('Expected exception')808809    assert 'Expected exception' in str(exception.value)