Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

783 lines · 25.4 KiB · Python

Last changed by

Merge pull request #5049 from hroncok/pytest4Kenneth Reitzbefore adoption0fe6653

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__)287288289class TestContentEncodingDetection:290291    def test_none(self):292        encodings = get_encodings_from_content('')293        assert not len(encodings)294295    @pytest.mark.parametrize(296        'content', (297            # HTML5 meta charset attribute298            '<meta charset="UTF-8">',299            # HTML4 pragma directive300            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',301            # XHTML 1.x served with text/html MIME type302            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',303            # XHTML 1.x served as XML304            '<?xml version="1.0" encoding="UTF-8"?>',305        ))306    def test_pragmas(self, content):307        encodings = get_encodings_from_content(content)308        assert len(encodings) == 1309        assert encodings[0] == 'UTF-8'310311    def test_precedence(self):312        content = '''313        <?xml version="1.0" encoding="XML"?>314        <meta charset="HTML5">315        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />316        '''.strip()317        assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']318319320class TestGuessJSONUTF:321322    @pytest.mark.parametrize(323        'encoding', (324            'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',325            'utf-32-be', 'utf-32-le'326        ))327    def test_encoded(self, encoding):328        data = '{}'.encode(encoding)329        assert guess_json_utf(data) == encoding330331    def test_bad_utf_like_encoding(self):332        assert guess_json_utf(b'\x00\x00\x00\x00') is None333334    @pytest.mark.parametrize(335        ('encoding', 'expected'), (336            ('utf-16-be', 'utf-16'),337            ('utf-16-le', 'utf-16'),338            ('utf-32-be', 'utf-32'),339            ('utf-32-le', 'utf-32')340        ))341    def test_guess_by_bom(self, encoding, expected):342        data = u'\ufeff{}'.encode(encoding)343        assert guess_json_utf(data) == expected344345346USER = PASSWORD = "%!*'();:@&=+$,/?#[] "347ENCODED_USER = compat.quote(USER, '')348ENCODED_PASSWORD = compat.quote(PASSWORD, '')349350351@pytest.mark.parametrize(352    'url, auth', (353        (354            'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +355            'request.com/url.html#test',356            (USER, PASSWORD)357        ),358        (359            'http://user:pass@complex.url.com/path?query=yes',360            ('user', 'pass')361        ),362        (363            'http://user:pass%20pass@complex.url.com/path?query=yes',364            ('user', 'pass pass')365        ),366        (367            'http://user:pass pass@complex.url.com/path?query=yes',368            ('user', 'pass pass')369        ),370        (371            'http://user%25user:pass@complex.url.com/path?query=yes',372            ('user%user', 'pass')373        ),374        (375            'http://user:pass%23pass@complex.url.com/path?query=yes',376            ('user', 'pass#pass')377        ),378        (379            'http://complex.url.com/path?query=yes',380            ('', '')381        ),382    ))383def test_get_auth_from_url(url, auth):384    assert get_auth_from_url(url) == auth385386387@pytest.mark.parametrize(388    'uri, expected', (389        (390            # Ensure requoting doesn't break expectations391            'http://example.com/fiz?buz=%25ppicture',392            'http://example.com/fiz?buz=%25ppicture',393        ),394        (395            # Ensure we handle unquoted percent signs in redirects396            'http://example.com/fiz?buz=%ppicture',397            'http://example.com/fiz?buz=%25ppicture',398        ),399    ))400def test_requote_uri_with_unquoted_percents(uri, expected):401    """See: https://github.com/psf/requests/issues/2356"""402    assert requote_uri(uri) == expected403404405@pytest.mark.parametrize(406    'uri, expected', (407        (408            # Illegal bytes409            'http://example.com/?a=%--',410            'http://example.com/?a=%--',411        ),412        (413            # Reserved characters414            'http://example.com/?a=%300',415            'http://example.com/?a=00',416        )417    ))418def test_unquote_unreserved(uri, expected):419    assert unquote_unreserved(uri) == expected420421422@pytest.mark.parametrize(423    'mask, expected', (424        (8, '255.0.0.0'),425        (24, '255.255.255.0'),426        (25, '255.255.255.128'),427    ))428def test_dotted_netmask(mask, expected):429    assert dotted_netmask(mask) == expected430431432http_proxies = {'http': 'http://http.proxy',433                'http://some.host': 'http://some.host.proxy'}434all_proxies = {'all': 'socks5://http.proxy',435               'all://some.host': 'socks5://some.host.proxy'}436mixed_proxies = {'http': 'http://http.proxy',437                 'http://some.host': 'http://some.host.proxy',438                 'all': 'socks5://http.proxy'}439@pytest.mark.parametrize(440    'url, expected, proxies', (441        ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),442        ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),443        ('hTTp:///path', 'http://http.proxy', http_proxies),444        ('hTTps://Other.Host', None, http_proxies),445        ('file:///etc/motd', None, http_proxies),446447        ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),448        ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),449        ('hTTp:///path', 'socks5://http.proxy', all_proxies),450        ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),451452        ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),453        ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),454        ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),455        ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),456        ('https://', 'socks5://http.proxy', mixed_proxies),457        # XXX: unsure whether this is reasonable behavior458        ('file:///etc/motd', 'socks5://http.proxy', all_proxies),459    ))460def test_select_proxies(url, expected, proxies):461    """Make sure we can select per-host proxies correctly."""462    assert select_proxy(url, proxies) == expected463464465@pytest.mark.parametrize(466    'value, expected', (467        ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),468        ('key_without_value', {'key_without_value': None})469    ))470def test_parse_dict_header(value, expected):471    assert parse_dict_header(value) == expected472473474@pytest.mark.parametrize(475    'value, expected', (476        (477            'application/xml',478            ('application/xml', {})479        ),480        (481            'application/json ; charset=utf-8',482            ('application/json', {'charset': 'utf-8'})483        ),484        (485            'application/json ; Charset=utf-8',486            ('application/json', {'charset': 'utf-8'})487        ),488        (489            'text/plain',490            ('text/plain', {})491        ),492        (493            'multipart/form-data; boundary = something ; boundary2=\'something_else\' ; no_equals ',494            ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})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            'application/json ; ; ',510            ('application/json', {})511        )512    ))513def test__parse_content_type_header(value, expected):514    assert _parse_content_type_header(value) == expected515516517@pytest.mark.parametrize(518    'value, expected', (519        (520            CaseInsensitiveDict(),521            None522        ),523        (524            CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),525            'utf-8'526        ),527        (528            CaseInsensitiveDict({'content-type': 'text/plain'}),529            'ISO-8859-1'530        ),531    ))532def test_get_encoding_from_headers(value, expected):533    assert get_encoding_from_headers(value) == expected534535536@pytest.mark.parametrize(537    'value, length', (538        ('', 0),539        ('T', 1),540        ('Test', 4),541        ('Cont', 0),542        ('Other', -5),543        ('Content', None),544    ))545def test_iter_slices(value, length):546    if length is None or (length <= 0 and len(value) > 0):547        # Reads all content at once548        assert len(list(iter_slices(value, length))) == 1549    else:550        assert len(list(iter_slices(value, 1))) == length551552553@pytest.mark.parametrize(554    'value, expected', (555        (556            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',557            [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]558        ),559        (560            '<http:/.../front.jpeg>',561            [{'url': 'http:/.../front.jpeg'}]562        ),563        (564            '<http:/.../front.jpeg>;',565            [{'url': 'http:/.../front.jpeg'}]566        ),567        (568            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',569            [570                {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},571                {'url': 'http://.../back.jpeg'}572            ]573        ),574        (575            '',576            []577        ),578    ))579def test_parse_header_links(value, expected):580    assert parse_header_links(value) == expected581582583@pytest.mark.parametrize(584    'value, expected', (585        ('example.com/path', 'http://example.com/path'),586        ('//example.com/path', 'http://example.com/path'),587    ))588def test_prepend_scheme_if_needed(value, expected):589    assert prepend_scheme_if_needed(value, 'http') == expected590591592@pytest.mark.parametrize(593    'value, expected', (594        ('T', 'T'),595        (b'T', 'T'),596        (u'T', 'T'),597    ))598def test_to_native_string(value, expected):599    assert to_native_string(value) == expected600601602@pytest.mark.parametrize(603    'url, expected', (604        ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),605        ('http://example.com/path', 'http://example.com/path'),606        ('//u:p@example.com/path', '//example.com/path'),607        ('//example.com/path', '//example.com/path'),608        ('example.com/path', '//example.com/path'),609        ('scheme:u:p@example.com/path', 'scheme://example.com/path'),610    ))611def test_urldefragauth(url, expected):612    assert urldefragauth(url) == expected613614615@pytest.mark.parametrize(616    'url, expected', (617            ('http://192.168.0.1:5000/', True),618            ('http://192.168.0.1/', True),619            ('http://172.16.1.1/', True),620            ('http://172.16.1.1:5000/', True),621            ('http://localhost.localdomain:5000/v1.0/', True),622            ('http://google.com:6000/', True),623            ('http://172.16.1.12/', False),624            ('http://172.16.1.12:5000/', False),625            ('http://google.com:5000/v1.0/', False),626            ('file:///some/path/on/disk', True),627    ))628def test_should_bypass_proxies(url, expected, monkeypatch):629    """Tests for function should_bypass_proxies to check if proxy630    can be bypassed or not631    """632    monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')633    monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')634    assert should_bypass_proxies(url, no_proxy=None) == expected635636637@pytest.mark.parametrize(638    'url, expected', (639            ('http://172.16.1.1/', '172.16.1.1'),640            ('http://172.16.1.1:5000/', '172.16.1.1'),641            ('http://user:pass@172.16.1.1', '172.16.1.1'),642            ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),643            ('http://hostname/', 'hostname'),644            ('http://hostname:5000/', 'hostname'),645            ('http://user:pass@hostname', 'hostname'),646            ('http://user:pass@hostname:5000', 'hostname'),647    ))648def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):649    """The proxy_bypass function should be called with a hostname or IP without650    a port number or auth credentials.651    """652    proxy_bypass = mocker.patch('requests.utils.proxy_bypass')653    should_bypass_proxies(url, no_proxy=None)654    proxy_bypass.assert_called_once_with(expected)655656657@pytest.mark.parametrize(658    'cookiejar', (659        compat.cookielib.CookieJar(),660        RequestsCookieJar()661    ))662def test_add_dict_to_cookiejar(cookiejar):663    """Ensure add_dict_to_cookiejar works for664    non-RequestsCookieJar CookieJars665    """666    cookiedict = {'test': 'cookies',667                  'good': 'cookies'}668    cj = add_dict_to_cookiejar(cookiejar, cookiedict)669    cookies = {cookie.name: cookie.value for cookie in cj}670    assert cookiedict == cookies671672673@pytest.mark.parametrize(674    'value, expected', (675                (u'test', True),676                (u'æíöû', False),677                (u'ジェーピーニック', False),678    )679)680def test_unicode_is_ascii(value, expected):681    assert unicode_is_ascii(value) is expected682683684@pytest.mark.parametrize(685    'url, expected', (686            ('http://192.168.0.1:5000/', True),687            ('http://192.168.0.1/', True),688            ('http://172.16.1.1/', True),689            ('http://172.16.1.1:5000/', True),690            ('http://localhost.localdomain:5000/v1.0/', True),691            ('http://172.16.1.12/', False),692            ('http://172.16.1.12:5000/', False),693            ('http://google.com:5000/v1.0/', False),694    ))695def test_should_bypass_proxies_no_proxy(696        url, expected, monkeypatch):697    """Tests for function should_bypass_proxies to check if proxy698    can be bypassed or not using the 'no_proxy' argument699    """700    no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'701    # Test 'no_proxy' argument702    assert should_bypass_proxies(url, no_proxy=no_proxy) == expected703704705@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')706@pytest.mark.parametrize(707    'url, expected, override', (708            ('http://192.168.0.1:5000/', True, None),709            ('http://192.168.0.1/', True, None),710            ('http://172.16.1.1/', True, None),711            ('http://172.16.1.1:5000/', True, None),712            ('http://localhost.localdomain:5000/v1.0/', True, None),713            ('http://172.16.1.22/', False, None),714            ('http://172.16.1.22:5000/', False, None),715            ('http://google.com:5000/v1.0/', False, None),716            ('http://mylocalhostname:5000/v1.0/', True, '<local>'),717            ('http://192.168.0.1/', False, ''),718    ))719def test_should_bypass_proxies_win_registry(url, expected, override,720                                            monkeypatch):721    """Tests for function should_bypass_proxies to check if proxy722    can be bypassed or not with Windows registry settings723    """724    if override is None:725        override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'726    if compat.is_py3:727        import winreg728    else:729        import _winreg as winreg730731    class RegHandle:732        def Close(self):733            pass734735    ie_settings = RegHandle()736    proxyEnableValues = deque([1, "1"])737738    def OpenKey(key, subkey):739        return ie_settings740741    def QueryValueEx(key, value_name):742        if key is ie_settings:743            if value_name == 'ProxyEnable':744                # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)745                proxyEnableValues.rotate()746                return [proxyEnableValues[0]]747            elif value_name == 'ProxyOverride':748                return [override]749750    monkeypatch.setenv('http_proxy', '')751    monkeypatch.setenv('https_proxy', '')752    monkeypatch.setenv('ftp_proxy', '')753    monkeypatch.setenv('no_proxy', '')754    monkeypatch.setenv('NO_PROXY', '')755    monkeypatch.setattr(winreg, 'OpenKey', OpenKey)756    monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)757    assert should_bypass_proxies(url, None) == expected758759760@pytest.mark.parametrize(761    'env_name, value', (762            ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),763            ('no_proxy', None),764            ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),765            ('a_new_key', None),766    ))767def test_set_environ(env_name, value):768    """Tests set_environ will set environ values and will restore the environ."""769    environ_copy = copy.deepcopy(os.environ)770    with set_environ(env_name, value):771        assert os.environ.get(env_name) == value772773    assert os.environ == environ_copy774775776def test_set_environ_raises_exception():777    """Tests set_environ will raise exceptions in context when the778    value parameter is None."""779    with pytest.raises(Exception) as exception:780        with set_environ('test1', None):781            raise Exception('Expected exception')782783    assert 'Expected exception' in str(exception.value)