Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

787 lines · 25.6 KiB · Python

Last changed by

Fix extract_zipped_paths infinite loop when provided invalid unc path (#5851)Thomas Lambefore adoptiond8829f9

History of this file

Take it

1# -*- coding: utf-8 -*-23import os4import copy5import filecmp6from io import BytesIO7import zipfile8from collections import deque910import pytest11from requests import compat12from requests.cookies import RequestsCookieJar13from requests.structures import CaseInsensitiveDict14from requests.utils import (15    address_in_network, dotted_netmask, extract_zipped_paths,16    get_auth_from_url, _parse_content_type_header, get_encoding_from_headers,17    get_encodings_from_content, get_environ_proxies,18    guess_filename, guess_json_utf, is_ipv4_address,19    is_valid_cidr, iter_slices, parse_dict_header,20    parse_header_links, prepend_scheme_if_needed,21    requote_uri, select_proxy, should_bypass_proxies, super_len,22    to_key_val_list, to_native_string,23    unquote_header_value, unquote_unreserved,24    urldefragauth, add_dict_to_cookiejar, set_environ)25from requests._internal_utils import unicode_is_ascii2627from .compat import StringIO, cStringIO282930class TestSuperLen:3132    @pytest.mark.parametrize(33        'stream, value', (34            (StringIO.StringIO, 'Test'),35            (BytesIO, b'Test'),36            pytest.param(cStringIO, 'Test',37                         marks=pytest.mark.skipif('cStringIO is None')),38        ))39    def test_io_streams(self, stream, value):40        """Ensures that we properly deal with different kinds of IO streams."""41        assert super_len(stream()) == 042        assert super_len(stream(value)) == 44344    def test_super_len_correctly_calculates_len_of_partially_read_file(self):45        """Ensure that we handle partially consumed file like objects."""46        s = StringIO.StringIO()47        s.write('foobarbogus')48        assert super_len(s) == 04950    @pytest.mark.parametrize('error', [IOError, OSError])51    def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):52        """If tell() raises errors, assume the cursor is at position zero."""53        class BoomFile(object):54            def __len__(self):55                return 55657            def tell(self):58                raise error()5960        assert super_len(BoomFile()) == 06162    @pytest.mark.parametrize('error', [IOError, OSError])63    def test_super_len_tell_ioerror(self, error):64        """Ensure that if tell gives an IOError super_len doesn't fail"""65        class NoLenBoomFile(object):66            def tell(self):67                raise error()6869            def seek(self, offset, whence):70                pass7172        assert super_len(NoLenBoomFile()) == 07374    def test_string(self):75        assert super_len('Test') == 47677    @pytest.mark.parametrize(78        'mode, warnings_num', (79            ('r', 1),80            ('rb', 0),81        ))82    def test_file(self, tmpdir, mode, warnings_num, recwarn):83        file_obj = tmpdir.join('test.txt')84        file_obj.write('Test')85        with file_obj.open(mode) as fd:86            assert super_len(fd) == 487        assert len(recwarn) == warnings_num8889    def test_super_len_with__len__(self):90        foo = [1,2,3,4]91        len_foo = super_len(foo)92        assert len_foo == 49394    def test_super_len_with_no__len__(self):95        class LenFile(object):96            def __init__(self):97                self.len = 59899        assert super_len(LenFile()) == 5100101    def test_super_len_with_tell(self):102        foo = StringIO.StringIO('12345')103        assert super_len(foo) == 5104        foo.read(2)105        assert super_len(foo) == 3106107    def test_super_len_with_fileno(self):108        with open(__file__, 'rb') as f:109            length = super_len(f)110            file_data = f.read()111        assert length == len(file_data)112113    def test_super_len_with_no_matches(self):114        """Ensure that objects without any length methods default to 0"""115        assert super_len(object()) == 0116117118class TestToKeyValList:119120    @pytest.mark.parametrize(121        'value, expected', (122            ([('key', 'val')], [('key', 'val')]),123            ((('key', 'val'), ), [('key', 'val')]),124            ({'key': 'val'}, [('key', 'val')]),125            (None, None)126        ))127    def test_valid(self, value, expected):128        assert to_key_val_list(value) == expected129130    def test_invalid(self):131        with pytest.raises(ValueError):132            to_key_val_list('string')133134135class TestUnquoteHeaderValue:136137    @pytest.mark.parametrize(138        'value, expected', (139            (None, None),140            ('Test', 'Test'),141            ('"Test"', 'Test'),142            ('"Test\\\\"', 'Test\\'),143            ('"\\\\Comp\\Res"', '\\Comp\\Res'),144        ))145    def test_valid(self, value, expected):146        assert unquote_header_value(value) == expected147148    def test_is_filename(self):149        assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'150151152class TestGetEnvironProxies:153    """Ensures that IP addresses are correctly matches with ranges154    in no_proxy variable.155    """156157    @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])158    def no_proxy(self, request, monkeypatch):159        monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')160161    @pytest.mark.parametrize(162        'url', (163            'http://192.168.0.1:5000/',164            'http://192.168.0.1/',165            'http://172.16.1.1/',166            'http://172.16.1.1:5000/',167            'http://localhost.localdomain:5000/v1.0/',168        ))169    def test_bypass(self, url):170        assert get_environ_proxies(url, no_proxy=None) == {}171172    @pytest.mark.parametrize(173        'url', (174            'http://192.168.1.1:5000/',175            'http://192.168.1.1/',176            'http://www.requests.com/',177        ))178    def test_not_bypass(self, url):179        assert get_environ_proxies(url, no_proxy=None) != {}180181    @pytest.mark.parametrize(182        'url', (183            'http://192.168.1.1:5000/',184            'http://192.168.1.1/',185            'http://www.requests.com/',186        ))187    def test_bypass_no_proxy_keyword(self, url):188        no_proxy = '192.168.1.1,requests.com'189        assert get_environ_proxies(url, no_proxy=no_proxy) == {}190191    @pytest.mark.parametrize(192        'url', (193            'http://192.168.0.1:5000/',194            'http://192.168.0.1/',195            'http://172.16.1.1/',196            'http://172.16.1.1:5000/',197            'http://localhost.localdomain:5000/v1.0/',198        ))199    def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):200        # This is testing that the 'no_proxy' argument overrides the201        # environment variable 'no_proxy'202        monkeypatch.setenv('http_proxy', 'http://proxy.example.com:3128/')203        no_proxy = '192.168.1.1,requests.com'204        assert get_environ_proxies(url, no_proxy=no_proxy) != {}205206207class TestIsIPv4Address:208209    def test_valid(self):210        assert is_ipv4_address('8.8.8.8')211212    @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))213    def test_invalid(self, value):214        assert not is_ipv4_address(value)215216217class TestIsValidCIDR:218219    def test_valid(self):220        assert is_valid_cidr('192.168.1.0/24')221222    @pytest.mark.parametrize(223        'value', (224            '8.8.8.8',225            '192.168.1.0/a',226            '192.168.1.0/128',227            '192.168.1.0/-1',228            '192.168.1.999/24',229        ))230    def test_invalid(self, value):231        assert not is_valid_cidr(value)232233234class TestAddressInNetwork:235236    def test_valid(self):237        assert address_in_network('192.168.1.1', '192.168.1.0/24')238239    def test_invalid(self):240        assert not address_in_network('172.16.0.1', '192.168.1.0/24')241242243class TestGuessFilename:244245    @pytest.mark.parametrize(246        'value', (1, type('Fake', (object,), {'name': 1})()),247    )248    def test_guess_filename_invalid(self, value):249        assert guess_filename(value) is None250251    @pytest.mark.parametrize(252        'value, expected_type', (253            (b'value', compat.bytes),254            (b'value'.decode('utf-8'), compat.str)255        ))256    def test_guess_filename_valid(self, value, expected_type):257        obj = type('Fake', (object,), {'name': value})()258        result = guess_filename(obj)259        assert result == value260        assert isinstance(result, expected_type)261262263class TestExtractZippedPaths:264265    @pytest.mark.parametrize(266        'path', (267            '/',268            __file__,269            pytest.__file__,270            '/etc/invalid/location',271        ))272    def test_unzipped_paths_unchanged(self, path):273        assert path == extract_zipped_paths(path)274275    def test_zipped_paths_extracted(self, tmpdir):276        zipped_py = tmpdir.join('test.zip')277        with zipfile.ZipFile(zipped_py.strpath, 'w') as f:278            f.write(__file__)279280        _, name = os.path.splitdrive(__file__)281        zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r'\/'))282        extracted_path = extract_zipped_paths(zipped_path)283284        assert extracted_path != zipped_path285        assert os.path.exists(extracted_path)286        assert filecmp.cmp(extracted_path, __file__)287288    def test_invalid_unc_path(self):289        path = r"\\localhost\invalid\location"290        assert extract_zipped_paths(path) == path291292293class TestContentEncodingDetection:294295    def test_none(self):296        encodings = get_encodings_from_content('')297        assert not len(encodings)298299    @pytest.mark.parametrize(300        'content', (301            # HTML5 meta charset attribute302            '<meta charset="UTF-8">',303            # HTML4 pragma directive304            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',305            # XHTML 1.x served with text/html MIME type306            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',307            # XHTML 1.x served as XML308            '<?xml version="1.0" encoding="UTF-8"?>',309        ))310    def test_pragmas(self, content):311        encodings = get_encodings_from_content(content)312        assert len(encodings) == 1313        assert encodings[0] == 'UTF-8'314315    def test_precedence(self):316        content = '''317        <?xml version="1.0" encoding="XML"?>318        <meta charset="HTML5">319        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />320        '''.strip()321        assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']322323324class TestGuessJSONUTF:325326    @pytest.mark.parametrize(327        'encoding', (328            'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',329            'utf-32-be', 'utf-32-le'330        ))331    def test_encoded(self, encoding):332        data = '{}'.encode(encoding)333        assert guess_json_utf(data) == encoding334335    def test_bad_utf_like_encoding(self):336        assert guess_json_utf(b'\x00\x00\x00\x00') is None337338    @pytest.mark.parametrize(339        ('encoding', 'expected'), (340            ('utf-16-be', 'utf-16'),341            ('utf-16-le', 'utf-16'),342            ('utf-32-be', 'utf-32'),343            ('utf-32-le', 'utf-32')344        ))345    def test_guess_by_bom(self, encoding, expected):346        data = u'\ufeff{}'.encode(encoding)347        assert guess_json_utf(data) == expected348349350USER = PASSWORD = "%!*'();:@&=+$,/?#[] "351ENCODED_USER = compat.quote(USER, '')352ENCODED_PASSWORD = compat.quote(PASSWORD, '')353354355@pytest.mark.parametrize(356    'url, auth', (357        (358            'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +359            'request.com/url.html#test',360            (USER, PASSWORD)361        ),362        (363            'http://user:pass@complex.url.com/path?query=yes',364            ('user', 'pass')365        ),366        (367            'http://user:pass%20pass@complex.url.com/path?query=yes',368            ('user', 'pass pass')369        ),370        (371            'http://user:pass pass@complex.url.com/path?query=yes',372            ('user', 'pass pass')373        ),374        (375            'http://user%25user:pass@complex.url.com/path?query=yes',376            ('user%user', 'pass')377        ),378        (379            'http://user:pass%23pass@complex.url.com/path?query=yes',380            ('user', 'pass#pass')381        ),382        (383            'http://complex.url.com/path?query=yes',384            ('', '')385        ),386    ))387def test_get_auth_from_url(url, auth):388    assert get_auth_from_url(url) == auth389390391@pytest.mark.parametrize(392    'uri, expected', (393        (394            # Ensure requoting doesn't break expectations395            'http://example.com/fiz?buz=%25ppicture',396            'http://example.com/fiz?buz=%25ppicture',397        ),398        (399            # Ensure we handle unquoted percent signs in redirects400            'http://example.com/fiz?buz=%ppicture',401            'http://example.com/fiz?buz=%25ppicture',402        ),403    ))404def test_requote_uri_with_unquoted_percents(uri, expected):405    """See: https://github.com/psf/requests/issues/2356"""406    assert requote_uri(uri) == expected407408409@pytest.mark.parametrize(410    'uri, expected', (411        (412            # Illegal bytes413            'http://example.com/?a=%--',414            'http://example.com/?a=%--',415        ),416        (417            # Reserved characters418            'http://example.com/?a=%300',419            'http://example.com/?a=00',420        )421    ))422def test_unquote_unreserved(uri, expected):423    assert unquote_unreserved(uri) == expected424425426@pytest.mark.parametrize(427    'mask, expected', (428        (8, '255.0.0.0'),429        (24, '255.255.255.0'),430        (25, '255.255.255.128'),431    ))432def test_dotted_netmask(mask, expected):433    assert dotted_netmask(mask) == expected434435436http_proxies = {'http': 'http://http.proxy',437                'http://some.host': 'http://some.host.proxy'}438all_proxies = {'all': 'socks5://http.proxy',439               'all://some.host': 'socks5://some.host.proxy'}440mixed_proxies = {'http': 'http://http.proxy',441                 'http://some.host': 'http://some.host.proxy',442                 'all': 'socks5://http.proxy'}443@pytest.mark.parametrize(444    'url, expected, proxies', (445        ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),446        ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),447        ('hTTp:///path', 'http://http.proxy', http_proxies),448        ('hTTps://Other.Host', None, http_proxies),449        ('file:///etc/motd', None, http_proxies),450451        ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),452        ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),453        ('hTTp:///path', 'socks5://http.proxy', all_proxies),454        ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),455456        ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),457        ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),458        ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),459        ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),460        ('https://', 'socks5://http.proxy', mixed_proxies),461        # XXX: unsure whether this is reasonable behavior462        ('file:///etc/motd', 'socks5://http.proxy', all_proxies),463    ))464def test_select_proxies(url, expected, proxies):465    """Make sure we can select per-host proxies correctly."""466    assert select_proxy(url, proxies) == expected467468469@pytest.mark.parametrize(470    'value, expected', (471        ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),472        ('key_without_value', {'key_without_value': None})473    ))474def test_parse_dict_header(value, expected):475    assert parse_dict_header(value) == expected476477478@pytest.mark.parametrize(479    'value, expected', (480        (481            'application/xml',482            ('application/xml', {})483        ),484        (485            'application/json ; charset=utf-8',486            ('application/json', {'charset': 'utf-8'})487        ),488        (489            'application/json ; Charset=utf-8',490            ('application/json', {'charset': 'utf-8'})491        ),492        (493            'text/plain',494            ('text/plain', {})495        ),496        (497            'multipart/form-data; boundary = something ; boundary2=\'something_else\' ; no_equals ',498            ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})499        ),500        (501                'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',502                ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})503        ),504        (505            'multipart/form-data; boundary = something ; \'boundary2=something_else\' ; no_equals ',506            ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})507        ),508        (509            'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',510            ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})511        ),512        (513            'application/json ; ; ',514            ('application/json', {})515        )516    ))517def test__parse_content_type_header(value, expected):518    assert _parse_content_type_header(value) == expected519520521@pytest.mark.parametrize(522    'value, expected', (523        (524            CaseInsensitiveDict(),525            None526        ),527        (528            CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),529            'utf-8'530        ),531        (532            CaseInsensitiveDict({'content-type': 'text/plain'}),533            'ISO-8859-1'534        ),535    ))536def test_get_encoding_from_headers(value, expected):537    assert get_encoding_from_headers(value) == expected538539540@pytest.mark.parametrize(541    'value, length', (542        ('', 0),543        ('T', 1),544        ('Test', 4),545        ('Cont', 0),546        ('Other', -5),547        ('Content', None),548    ))549def test_iter_slices(value, length):550    if length is None or (length <= 0 and len(value) > 0):551        # Reads all content at once552        assert len(list(iter_slices(value, length))) == 1553    else:554        assert len(list(iter_slices(value, 1))) == length555556557@pytest.mark.parametrize(558    'value, expected', (559        (560            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',561            [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]562        ),563        (564            '<http:/.../front.jpeg>',565            [{'url': 'http:/.../front.jpeg'}]566        ),567        (568            '<http:/.../front.jpeg>;',569            [{'url': 'http:/.../front.jpeg'}]570        ),571        (572            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',573            [574                {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},575                {'url': 'http://.../back.jpeg'}576            ]577        ),578        (579            '',580            []581        ),582    ))583def test_parse_header_links(value, expected):584    assert parse_header_links(value) == expected585586587@pytest.mark.parametrize(588    'value, expected', (589        ('example.com/path', 'http://example.com/path'),590        ('//example.com/path', 'http://example.com/path'),591    ))592def test_prepend_scheme_if_needed(value, expected):593    assert prepend_scheme_if_needed(value, 'http') == expected594595596@pytest.mark.parametrize(597    'value, expected', (598        ('T', 'T'),599        (b'T', 'T'),600        (u'T', 'T'),601    ))602def test_to_native_string(value, expected):603    assert to_native_string(value) == expected604605606@pytest.mark.parametrize(607    'url, expected', (608        ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),609        ('http://example.com/path', 'http://example.com/path'),610        ('//u:p@example.com/path', '//example.com/path'),611        ('//example.com/path', '//example.com/path'),612        ('example.com/path', '//example.com/path'),613        ('scheme:u:p@example.com/path', 'scheme://example.com/path'),614    ))615def test_urldefragauth(url, expected):616    assert urldefragauth(url) == expected617618619@pytest.mark.parametrize(620    'url, expected', (621            ('http://192.168.0.1:5000/', True),622            ('http://192.168.0.1/', True),623            ('http://172.16.1.1/', True),624            ('http://172.16.1.1:5000/', True),625            ('http://localhost.localdomain:5000/v1.0/', True),626            ('http://google.com:6000/', True),627            ('http://172.16.1.12/', False),628            ('http://172.16.1.12:5000/', False),629            ('http://google.com:5000/v1.0/', False),630            ('file:///some/path/on/disk', True),631    ))632def test_should_bypass_proxies(url, expected, monkeypatch):633    """Tests for function should_bypass_proxies to check if proxy634    can be bypassed or not635    """636    monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')637    monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')638    assert should_bypass_proxies(url, no_proxy=None) == expected639640641@pytest.mark.parametrize(642    'url, expected', (643            ('http://172.16.1.1/', '172.16.1.1'),644            ('http://172.16.1.1:5000/', '172.16.1.1'),645            ('http://user:pass@172.16.1.1', '172.16.1.1'),646            ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),647            ('http://hostname/', 'hostname'),648            ('http://hostname:5000/', 'hostname'),649            ('http://user:pass@hostname', 'hostname'),650            ('http://user:pass@hostname:5000', 'hostname'),651    ))652def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):653    """The proxy_bypass function should be called with a hostname or IP without654    a port number or auth credentials.655    """656    proxy_bypass = mocker.patch('requests.utils.proxy_bypass')657    should_bypass_proxies(url, no_proxy=None)658    proxy_bypass.assert_called_once_with(expected)659660661@pytest.mark.parametrize(662    'cookiejar', (663        compat.cookielib.CookieJar(),664        RequestsCookieJar()665    ))666def test_add_dict_to_cookiejar(cookiejar):667    """Ensure add_dict_to_cookiejar works for668    non-RequestsCookieJar CookieJars669    """670    cookiedict = {'test': 'cookies',671                  'good': 'cookies'}672    cj = add_dict_to_cookiejar(cookiejar, cookiedict)673    cookies = {cookie.name: cookie.value for cookie in cj}674    assert cookiedict == cookies675676677@pytest.mark.parametrize(678    'value, expected', (679                (u'test', True),680                (u'æíöû', False),681                (u'ジェーピーニック', False),682    )683)684def test_unicode_is_ascii(value, expected):685    assert unicode_is_ascii(value) is expected686687688@pytest.mark.parametrize(689    'url, expected', (690            ('http://192.168.0.1:5000/', True),691            ('http://192.168.0.1/', True),692            ('http://172.16.1.1/', True),693            ('http://172.16.1.1:5000/', True),694            ('http://localhost.localdomain:5000/v1.0/', True),695            ('http://172.16.1.12/', False),696            ('http://172.16.1.12:5000/', False),697            ('http://google.com:5000/v1.0/', False),698    ))699def test_should_bypass_proxies_no_proxy(700        url, expected, monkeypatch):701    """Tests for function should_bypass_proxies to check if proxy702    can be bypassed or not using the 'no_proxy' argument703    """704    no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'705    # Test 'no_proxy' argument706    assert should_bypass_proxies(url, no_proxy=no_proxy) == expected707708709@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')710@pytest.mark.parametrize(711    'url, expected, override', (712            ('http://192.168.0.1:5000/', True, None),713            ('http://192.168.0.1/', True, None),714            ('http://172.16.1.1/', True, None),715            ('http://172.16.1.1:5000/', True, None),716            ('http://localhost.localdomain:5000/v1.0/', True, None),717            ('http://172.16.1.22/', False, None),718            ('http://172.16.1.22:5000/', False, None),719            ('http://google.com:5000/v1.0/', False, None),720            ('http://mylocalhostname:5000/v1.0/', True, '<local>'),721            ('http://192.168.0.1/', False, ''),722    ))723def test_should_bypass_proxies_win_registry(url, expected, override,724                                            monkeypatch):725    """Tests for function should_bypass_proxies to check if proxy726    can be bypassed or not with Windows registry settings727    """728    if override is None:729        override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'730    if compat.is_py3:731        import winreg732    else:733        import _winreg as winreg734735    class RegHandle:736        def Close(self):737            pass738739    ie_settings = RegHandle()740    proxyEnableValues = deque([1, "1"])741742    def OpenKey(key, subkey):743        return ie_settings744745    def QueryValueEx(key, value_name):746        if key is ie_settings:747            if value_name == 'ProxyEnable':748                # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)749                proxyEnableValues.rotate()750                return [proxyEnableValues[0]]751            elif value_name == 'ProxyOverride':752                return [override]753754    monkeypatch.setenv('http_proxy', '')755    monkeypatch.setenv('https_proxy', '')756    monkeypatch.setenv('ftp_proxy', '')757    monkeypatch.setenv('no_proxy', '')758    monkeypatch.setenv('NO_PROXY', '')759    monkeypatch.setattr(winreg, 'OpenKey', OpenKey)760    monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)761    assert should_bypass_proxies(url, None) == expected762763764@pytest.mark.parametrize(765    'env_name, value', (766            ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),767            ('no_proxy', None),768            ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),769            ('a_new_key', None),770    ))771def test_set_environ(env_name, value):772    """Tests set_environ will set environ values and will restore the environ."""773    environ_copy = copy.deepcopy(os.environ)774    with set_environ(env_name, value):775        assert os.environ.get(env_name) == value776777    assert os.environ == environ_copy778779780def test_set_environ_raises_exception():781    """Tests set_environ will raise exceptions in context when the782    value parameter is None."""783    with pytest.raises(Exception) as exception:784        with set_environ('test1', None):785            raise Exception('Expected exception')786787    assert 'Expected exception' in str(exception.value)