Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

784 lines · 25.5 KiB · Python

Last changed by

Merge pull request #4976 from eduardomourar/feature/strip-utf8-bomKenneth Reitzbefore adoptiona71e224

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-8-sig', 'utf-8-sig'),337            ('utf-16-be', 'utf-16'),338            ('utf-16-le', 'utf-16'),339            ('utf-32-be', 'utf-32'),340            ('utf-32-le', 'utf-32')341        ))342    def test_guess_by_bom(self, encoding, expected):343        data = u'\ufeff{}'.encode(encoding)344        assert guess_json_utf(data) == expected345346347USER = PASSWORD = "%!*'();:@&=+$,/?#[] "348ENCODED_USER = compat.quote(USER, '')349ENCODED_PASSWORD = compat.quote(PASSWORD, '')350351352@pytest.mark.parametrize(353    'url, auth', (354        (355            'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +356            'request.com/url.html#test',357            (USER, PASSWORD)358        ),359        (360            'http://user:pass@complex.url.com/path?query=yes',361            ('user', 'pass')362        ),363        (364            'http://user:pass%20pass@complex.url.com/path?query=yes',365            ('user', 'pass pass')366        ),367        (368            'http://user:pass pass@complex.url.com/path?query=yes',369            ('user', 'pass pass')370        ),371        (372            'http://user%25user:pass@complex.url.com/path?query=yes',373            ('user%user', 'pass')374        ),375        (376            'http://user:pass%23pass@complex.url.com/path?query=yes',377            ('user', 'pass#pass')378        ),379        (380            'http://complex.url.com/path?query=yes',381            ('', '')382        ),383    ))384def test_get_auth_from_url(url, auth):385    assert get_auth_from_url(url) == auth386387388@pytest.mark.parametrize(389    'uri, expected', (390        (391            # Ensure requoting doesn't break expectations392            'http://example.com/fiz?buz=%25ppicture',393            'http://example.com/fiz?buz=%25ppicture',394        ),395        (396            # Ensure we handle unquoted percent signs in redirects397            'http://example.com/fiz?buz=%ppicture',398            'http://example.com/fiz?buz=%25ppicture',399        ),400    ))401def test_requote_uri_with_unquoted_percents(uri, expected):402    """See: https://github.com/psf/requests/issues/2356"""403    assert requote_uri(uri) == expected404405406@pytest.mark.parametrize(407    'uri, expected', (408        (409            # Illegal bytes410            'http://example.com/?a=%--',411            'http://example.com/?a=%--',412        ),413        (414            # Reserved characters415            'http://example.com/?a=%300',416            'http://example.com/?a=00',417        )418    ))419def test_unquote_unreserved(uri, expected):420    assert unquote_unreserved(uri) == expected421422423@pytest.mark.parametrize(424    'mask, expected', (425        (8, '255.0.0.0'),426        (24, '255.255.255.0'),427        (25, '255.255.255.128'),428    ))429def test_dotted_netmask(mask, expected):430    assert dotted_netmask(mask) == expected431432433http_proxies = {'http': 'http://http.proxy',434                'http://some.host': 'http://some.host.proxy'}435all_proxies = {'all': 'socks5://http.proxy',436               'all://some.host': 'socks5://some.host.proxy'}437mixed_proxies = {'http': 'http://http.proxy',438                 'http://some.host': 'http://some.host.proxy',439                 'all': 'socks5://http.proxy'}440@pytest.mark.parametrize(441    'url, expected, proxies', (442        ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),443        ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),444        ('hTTp:///path', 'http://http.proxy', http_proxies),445        ('hTTps://Other.Host', None, http_proxies),446        ('file:///etc/motd', None, http_proxies),447448        ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),449        ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),450        ('hTTp:///path', 'socks5://http.proxy', all_proxies),451        ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),452453        ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),454        ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),455        ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),456        ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),457        ('https://', 'socks5://http.proxy', mixed_proxies),458        # XXX: unsure whether this is reasonable behavior459        ('file:///etc/motd', 'socks5://http.proxy', all_proxies),460    ))461def test_select_proxies(url, expected, proxies):462    """Make sure we can select per-host proxies correctly."""463    assert select_proxy(url, proxies) == expected464465466@pytest.mark.parametrize(467    'value, expected', (468        ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),469        ('key_without_value', {'key_without_value': None})470    ))471def test_parse_dict_header(value, expected):472    assert parse_dict_header(value) == expected473474475@pytest.mark.parametrize(476    'value, expected', (477        (478            'application/xml',479            ('application/xml', {})480        ),481        (482            'application/json ; charset=utf-8',483            ('application/json', {'charset': 'utf-8'})484        ),485        (486            'application/json ; Charset=utf-8',487            ('application/json', {'charset': 'utf-8'})488        ),489        (490            'text/plain',491            ('text/plain', {})492        ),493        (494            'multipart/form-data; boundary = something ; boundary2=\'something_else\' ; no_equals ',495            ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})496        ),497        (498                'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',499                ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})500        ),501        (502            'multipart/form-data; boundary = something ; \'boundary2=something_else\' ; no_equals ',503            ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})504        ),505        (506            'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',507            ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})508        ),509        (510            'application/json ; ; ',511            ('application/json', {})512        )513    ))514def test__parse_content_type_header(value, expected):515    assert _parse_content_type_header(value) == expected516517518@pytest.mark.parametrize(519    'value, expected', (520        (521            CaseInsensitiveDict(),522            None523        ),524        (525            CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),526            'utf-8'527        ),528        (529            CaseInsensitiveDict({'content-type': 'text/plain'}),530            'ISO-8859-1'531        ),532    ))533def test_get_encoding_from_headers(value, expected):534    assert get_encoding_from_headers(value) == expected535536537@pytest.mark.parametrize(538    'value, length', (539        ('', 0),540        ('T', 1),541        ('Test', 4),542        ('Cont', 0),543        ('Other', -5),544        ('Content', None),545    ))546def test_iter_slices(value, length):547    if length is None or (length <= 0 and len(value) > 0):548        # Reads all content at once549        assert len(list(iter_slices(value, length))) == 1550    else:551        assert len(list(iter_slices(value, 1))) == length552553554@pytest.mark.parametrize(555    'value, expected', (556        (557            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',558            [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]559        ),560        (561            '<http:/.../front.jpeg>',562            [{'url': 'http:/.../front.jpeg'}]563        ),564        (565            '<http:/.../front.jpeg>;',566            [{'url': 'http:/.../front.jpeg'}]567        ),568        (569            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',570            [571                {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},572                {'url': 'http://.../back.jpeg'}573            ]574        ),575        (576            '',577            []578        ),579    ))580def test_parse_header_links(value, expected):581    assert parse_header_links(value) == expected582583584@pytest.mark.parametrize(585    'value, expected', (586        ('example.com/path', 'http://example.com/path'),587        ('//example.com/path', 'http://example.com/path'),588    ))589def test_prepend_scheme_if_needed(value, expected):590    assert prepend_scheme_if_needed(value, 'http') == expected591592593@pytest.mark.parametrize(594    'value, expected', (595        ('T', 'T'),596        (b'T', 'T'),597        (u'T', 'T'),598    ))599def test_to_native_string(value, expected):600    assert to_native_string(value) == expected601602603@pytest.mark.parametrize(604    'url, expected', (605        ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),606        ('http://example.com/path', 'http://example.com/path'),607        ('//u:p@example.com/path', '//example.com/path'),608        ('//example.com/path', '//example.com/path'),609        ('example.com/path', '//example.com/path'),610        ('scheme:u:p@example.com/path', 'scheme://example.com/path'),611    ))612def test_urldefragauth(url, expected):613    assert urldefragauth(url) == expected614615616@pytest.mark.parametrize(617    'url, expected', (618            ('http://192.168.0.1:5000/', True),619            ('http://192.168.0.1/', True),620            ('http://172.16.1.1/', True),621            ('http://172.16.1.1:5000/', True),622            ('http://localhost.localdomain:5000/v1.0/', True),623            ('http://google.com:6000/', True),624            ('http://172.16.1.12/', False),625            ('http://172.16.1.12:5000/', False),626            ('http://google.com:5000/v1.0/', False),627            ('file:///some/path/on/disk', True),628    ))629def test_should_bypass_proxies(url, expected, monkeypatch):630    """Tests for function should_bypass_proxies to check if proxy631    can be bypassed or not632    """633    monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')634    monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')635    assert should_bypass_proxies(url, no_proxy=None) == expected636637638@pytest.mark.parametrize(639    'url, expected', (640            ('http://172.16.1.1/', '172.16.1.1'),641            ('http://172.16.1.1:5000/', '172.16.1.1'),642            ('http://user:pass@172.16.1.1', '172.16.1.1'),643            ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),644            ('http://hostname/', 'hostname'),645            ('http://hostname:5000/', 'hostname'),646            ('http://user:pass@hostname', 'hostname'),647            ('http://user:pass@hostname:5000', 'hostname'),648    ))649def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):650    """The proxy_bypass function should be called with a hostname or IP without651    a port number or auth credentials.652    """653    proxy_bypass = mocker.patch('requests.utils.proxy_bypass')654    should_bypass_proxies(url, no_proxy=None)655    proxy_bypass.assert_called_once_with(expected)656657658@pytest.mark.parametrize(659    'cookiejar', (660        compat.cookielib.CookieJar(),661        RequestsCookieJar()662    ))663def test_add_dict_to_cookiejar(cookiejar):664    """Ensure add_dict_to_cookiejar works for665    non-RequestsCookieJar CookieJars666    """667    cookiedict = {'test': 'cookies',668                  'good': 'cookies'}669    cj = add_dict_to_cookiejar(cookiejar, cookiedict)670    cookies = {cookie.name: cookie.value for cookie in cj}671    assert cookiedict == cookies672673674@pytest.mark.parametrize(675    'value, expected', (676                (u'test', True),677                (u'æíöû', False),678                (u'ジェーピーニック', False),679    )680)681def test_unicode_is_ascii(value, expected):682    assert unicode_is_ascii(value) is expected683684685@pytest.mark.parametrize(686    'url, expected', (687            ('http://192.168.0.1:5000/', True),688            ('http://192.168.0.1/', True),689            ('http://172.16.1.1/', True),690            ('http://172.16.1.1:5000/', True),691            ('http://localhost.localdomain:5000/v1.0/', True),692            ('http://172.16.1.12/', False),693            ('http://172.16.1.12:5000/', False),694            ('http://google.com:5000/v1.0/', False),695    ))696def test_should_bypass_proxies_no_proxy(697        url, expected, monkeypatch):698    """Tests for function should_bypass_proxies to check if proxy699    can be bypassed or not using the 'no_proxy' argument700    """701    no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'702    # Test 'no_proxy' argument703    assert should_bypass_proxies(url, no_proxy=no_proxy) == expected704705706@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')707@pytest.mark.parametrize(708    'url, expected, override', (709            ('http://192.168.0.1:5000/', True, None),710            ('http://192.168.0.1/', True, None),711            ('http://172.16.1.1/', True, None),712            ('http://172.16.1.1:5000/', True, None),713            ('http://localhost.localdomain:5000/v1.0/', True, None),714            ('http://172.16.1.22/', False, None),715            ('http://172.16.1.22:5000/', False, None),716            ('http://google.com:5000/v1.0/', False, None),717            ('http://mylocalhostname:5000/v1.0/', True, '<local>'),718            ('http://192.168.0.1/', False, ''),719    ))720def test_should_bypass_proxies_win_registry(url, expected, override,721                                            monkeypatch):722    """Tests for function should_bypass_proxies to check if proxy723    can be bypassed or not with Windows registry settings724    """725    if override is None:726        override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'727    if compat.is_py3:728        import winreg729    else:730        import _winreg as winreg731732    class RegHandle:733        def Close(self):734            pass735736    ie_settings = RegHandle()737    proxyEnableValues = deque([1, "1"])738739    def OpenKey(key, subkey):740        return ie_settings741742    def QueryValueEx(key, value_name):743        if key is ie_settings:744            if value_name == 'ProxyEnable':745                # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)746                proxyEnableValues.rotate()747                return [proxyEnableValues[0]]748            elif value_name == 'ProxyOverride':749                return [override]750751    monkeypatch.setenv('http_proxy', '')752    monkeypatch.setenv('https_proxy', '')753    monkeypatch.setenv('ftp_proxy', '')754    monkeypatch.setenv('no_proxy', '')755    monkeypatch.setenv('NO_PROXY', '')756    monkeypatch.setattr(winreg, 'OpenKey', OpenKey)757    monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)758    assert should_bypass_proxies(url, None) == expected759760761@pytest.mark.parametrize(762    'env_name, value', (763            ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),764            ('no_proxy', None),765            ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),766            ('a_new_key', None),767    ))768def test_set_environ(env_name, value):769    """Tests set_environ will set environ values and will restore the environ."""770    environ_copy = copy.deepcopy(os.environ)771    with set_environ(env_name, value):772        assert os.environ.get(env_name) == value773774    assert os.environ == environ_copy775776777def test_set_environ_raises_exception():778    """Tests set_environ will raise exceptions in context when the779    value parameter is None."""780    with pytest.raises(Exception) as exception:781        with set_environ('test1', None):782            raise Exception('Expected exception')783784    assert 'Expected exception' in str(exception.value)