Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

977 lines · 29.4 KiB · Python

Last changed by

Add more tests to prevent regression of CVE 2024 47081Arthur Woimbéebefore adoption5b4b64c

History of this file

Take it

1import copy2import filecmp3import os4import tarfile5import zipfile6from collections import deque7from io import BytesIO8from unittest import mock910import pytest1112from requests import compat13from requests._internal_utils import unicode_is_ascii14from requests.cookies import RequestsCookieJar15from requests.structures import CaseInsensitiveDict16from requests.utils import (17    _parse_content_type_header,18    add_dict_to_cookiejar,19    address_in_network,20    dotted_netmask,21    extract_zipped_paths,22    get_auth_from_url,23    get_encoding_from_headers,24    get_encodings_from_content,25    get_environ_proxies,26    get_netrc_auth,27    guess_filename,28    guess_json_utf,29    is_ipv4_address,30    is_valid_cidr,31    iter_slices,32    parse_dict_header,33    parse_header_links,34    prepend_scheme_if_needed,35    requote_uri,36    select_proxy,37    set_environ,38    should_bypass_proxies,39    super_len,40    to_key_val_list,41    to_native_string,42    unquote_header_value,43    unquote_unreserved,44    urldefragauth,45)4647from .compat import StringIO, cStringIO484950class TestSuperLen:51    @pytest.mark.parametrize(52        "stream, value",53        (54            (StringIO.StringIO, "Test"),55            (BytesIO, b"Test"),56            pytest.param(57                cStringIO, "Test", marks=pytest.mark.skipif("cStringIO is None")58            ),59        ),60    )61    def test_io_streams(self, stream, value):62        """Ensures that we properly deal with different kinds of IO streams."""63        assert super_len(stream()) == 064        assert super_len(stream(value)) == 46566    def test_super_len_correctly_calculates_len_of_partially_read_file(self):67        """Ensure that we handle partially consumed file like objects."""68        s = StringIO.StringIO()69        s.write("foobarbogus")70        assert super_len(s) == 07172    @pytest.mark.parametrize("error", [IOError, OSError])73    def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):74        """If tell() raises errors, assume the cursor is at position zero."""7576        class BoomFile:77            def __len__(self):78                return 57980            def tell(self):81                raise error()8283        assert super_len(BoomFile()) == 08485    @pytest.mark.parametrize("error", [IOError, OSError])86    def test_super_len_tell_ioerror(self, error):87        """Ensure that if tell gives an IOError super_len doesn't fail"""8889        class NoLenBoomFile:90            def tell(self):91                raise error()9293            def seek(self, offset, whence):94                pass9596        assert super_len(NoLenBoomFile()) == 09798    def test_string(self):99        assert super_len("Test") == 4100101    @pytest.mark.parametrize(102        "mode, warnings_num",103        (104            ("r", 1),105            ("rb", 0),106        ),107    )108    def test_file(self, tmpdir, mode, warnings_num, recwarn):109        file_obj = tmpdir.join("test.txt")110        file_obj.write("Test")111        with file_obj.open(mode) as fd:112            assert super_len(fd) == 4113        assert len(recwarn) == warnings_num114115    def test_tarfile_member(self, tmpdir):116        file_obj = tmpdir.join("test.txt")117        file_obj.write("Test")118119        tar_obj = str(tmpdir.join("test.tar"))120        with tarfile.open(tar_obj, "w") as tar:121            tar.add(str(file_obj), arcname="test.txt")122123        with tarfile.open(tar_obj) as tar:124            member = tar.extractfile("test.txt")125            assert super_len(member) == 4126127    def test_super_len_with__len__(self):128        foo = [1, 2, 3, 4]129        len_foo = super_len(foo)130        assert len_foo == 4131132    def test_super_len_with_no__len__(self):133        class LenFile:134            def __init__(self):135                self.len = 5136137        assert super_len(LenFile()) == 5138139    def test_super_len_with_tell(self):140        foo = StringIO.StringIO("12345")141        assert super_len(foo) == 5142        foo.read(2)143        assert super_len(foo) == 3144145    def test_super_len_with_fileno(self):146        with open(__file__, "rb") as f:147            length = super_len(f)148            file_data = f.read()149        assert length == len(file_data)150151    def test_super_len_with_no_matches(self):152        """Ensure that objects without any length methods default to 0"""153        assert super_len(object()) == 0154155156class TestGetNetrcAuth:157    def test_works(self, tmp_path, monkeypatch):158        netrc_path = tmp_path / ".netrc"159        monkeypatch.setenv("NETRC", str(netrc_path))160        with open(netrc_path, "w") as f:161            f.write("machine example.com login aaaa password bbbb\n")162        auth = get_netrc_auth("http://example.com/thing")163        assert auth == ("aaaa", "bbbb")164165    def test_not_vulnerable_to_bad_url_parsing(self, tmp_path, monkeypatch):166        netrc_path = tmp_path / ".netrc"167        monkeypatch.setenv("NETRC", str(netrc_path))168        with open(netrc_path, "w") as f:169            f.write("machine example.com login aaaa password bbbb\n")170        auth = get_netrc_auth("http://example.com:@evil.com/&apos;")171        assert auth is None172173174class TestToKeyValList:175    @pytest.mark.parametrize(176        "value, expected",177        (178            ([("key", "val")], [("key", "val")]),179            ((("key", "val"),), [("key", "val")]),180            ({"key": "val"}, [("key", "val")]),181            (None, None),182        ),183    )184    def test_valid(self, value, expected):185        assert to_key_val_list(value) == expected186187    def test_invalid(self):188        with pytest.raises(ValueError):189            to_key_val_list("string")190191192class TestUnquoteHeaderValue:193    @pytest.mark.parametrize(194        "value, expected",195        (196            (None, None),197            ("Test", "Test"),198            ('"Test"', "Test"),199            ('"Test\\\\"', "Test\\"),200            ('"\\\\Comp\\Res"', "\\Comp\\Res"),201        ),202    )203    def test_valid(self, value, expected):204        assert unquote_header_value(value) == expected205206    def test_is_filename(self):207        assert unquote_header_value('"\\\\Comp\\Res"', True) == "\\\\Comp\\Res"208209210class TestGetEnvironProxies:211    """Ensures that IP addresses are correctly matches with ranges212    in no_proxy variable.213    """214215    @pytest.fixture(autouse=True, params=["no_proxy", "NO_PROXY"])216    def no_proxy(self, request, monkeypatch):217        monkeypatch.setenv(218            request.param, "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"219        )220221    @pytest.mark.parametrize(222        "url",223        (224            "http://192.168.0.1:5000/",225            "http://192.168.0.1/",226            "http://172.16.1.1/",227            "http://172.16.1.1:5000/",228            "http://localhost.localdomain:5000/v1.0/",229        ),230    )231    def test_bypass(self, url):232        assert get_environ_proxies(url, no_proxy=None) == {}233234    @pytest.mark.parametrize(235        "url",236        (237            "http://192.168.1.1:5000/",238            "http://192.168.1.1/",239            "http://www.requests.com/",240        ),241    )242    def test_not_bypass(self, url):243        assert get_environ_proxies(url, no_proxy=None) != {}244245    @pytest.mark.parametrize(246        "url",247        (248            "http://192.168.1.1:5000/",249            "http://192.168.1.1/",250            "http://www.requests.com/",251        ),252    )253    def test_bypass_no_proxy_keyword(self, url):254        no_proxy = "192.168.1.1,requests.com"255        assert get_environ_proxies(url, no_proxy=no_proxy) == {}256257    @pytest.mark.parametrize(258        "url",259        (260            "http://192.168.0.1:5000/",261            "http://192.168.0.1/",262            "http://172.16.1.1/",263            "http://172.16.1.1:5000/",264            "http://localhost.localdomain:5000/v1.0/",265        ),266    )267    def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):268        # This is testing that the 'no_proxy' argument overrides the269        # environment variable 'no_proxy'270        monkeypatch.setenv("http_proxy", "http://proxy.example.com:3128/")271        no_proxy = "192.168.1.1,requests.com"272        assert get_environ_proxies(url, no_proxy=no_proxy) != {}273274275class TestIsIPv4Address:276    def test_valid(self):277        assert is_ipv4_address("8.8.8.8")278279    @pytest.mark.parametrize("value", ("8.8.8.8.8", "localhost.localdomain"))280    def test_invalid(self, value):281        assert not is_ipv4_address(value)282283284class TestIsValidCIDR:285    def test_valid(self):286        assert is_valid_cidr("192.168.1.0/24")287288    @pytest.mark.parametrize(289        "value",290        (291            "8.8.8.8",292            "192.168.1.0/a",293            "192.168.1.0/128",294            "192.168.1.0/-1",295            "192.168.1.999/24",296        ),297    )298    def test_invalid(self, value):299        assert not is_valid_cidr(value)300301302class TestAddressInNetwork:303    def test_valid(self):304        assert address_in_network("192.168.1.1", "192.168.1.0/24")305306    def test_invalid(self):307        assert not address_in_network("172.16.0.1", "192.168.1.0/24")308309310class TestGuessFilename:311    @pytest.mark.parametrize(312        "value",313        (1, type("Fake", (object,), {"name": 1})()),314    )315    def test_guess_filename_invalid(self, value):316        assert guess_filename(value) is None317318    @pytest.mark.parametrize(319        "value, expected_type",320        (321            (b"value", compat.bytes),322            (b"value".decode("utf-8"), compat.str),323        ),324    )325    def test_guess_filename_valid(self, value, expected_type):326        obj = type("Fake", (object,), {"name": value})()327        result = guess_filename(obj)328        assert result == value329        assert isinstance(result, expected_type)330331332class TestExtractZippedPaths:333    @pytest.mark.parametrize(334        "path",335        (336            "/",337            __file__,338            pytest.__file__,339            "/etc/invalid/location",340        ),341    )342    def test_unzipped_paths_unchanged(self, path):343        assert path == extract_zipped_paths(path)344345    def test_zipped_paths_extracted(self, tmpdir):346        zipped_py = tmpdir.join("test.zip")347        with zipfile.ZipFile(zipped_py.strpath, "w") as f:348            f.write(__file__)349350        _, name = os.path.splitdrive(__file__)351        zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r"\/"))352        extracted_path = extract_zipped_paths(zipped_path)353354        assert extracted_path != zipped_path355        assert os.path.exists(extracted_path)356        assert filecmp.cmp(extracted_path, __file__)357358    def test_invalid_unc_path(self):359        path = r"\\localhost\invalid\location"360        assert extract_zipped_paths(path) == path361362363class TestContentEncodingDetection:364    def test_none(self):365        encodings = get_encodings_from_content("")366        assert not len(encodings)367368    @pytest.mark.parametrize(369        "content",370        (371            # HTML5 meta charset attribute372            '<meta charset="UTF-8">',373            # HTML4 pragma directive374            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',375            # XHTML 1.x served with text/html MIME type376            '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',377            # XHTML 1.x served as XML378            '<?xml version="1.0" encoding="UTF-8"?>',379        ),380    )381    def test_pragmas(self, content):382        encodings = get_encodings_from_content(content)383        assert len(encodings) == 1384        assert encodings[0] == "UTF-8"385386    def test_precedence(self):387        content = """388        <?xml version="1.0" encoding="XML"?>389        <meta charset="HTML5">390        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />391        """.strip()392        assert get_encodings_from_content(content) == ["HTML5", "HTML4", "XML"]393394395class TestGuessJSONUTF:396    @pytest.mark.parametrize(397        "encoding",398        (399            "utf-32",400            "utf-8-sig",401            "utf-16",402            "utf-8",403            "utf-16-be",404            "utf-16-le",405            "utf-32-be",406            "utf-32-le",407        ),408    )409    def test_encoded(self, encoding):410        data = "{}".encode(encoding)411        assert guess_json_utf(data) == encoding412413    def test_bad_utf_like_encoding(self):414        assert guess_json_utf(b"\x00\x00\x00\x00") is None415416    @pytest.mark.parametrize(417        ("encoding", "expected"),418        (419            ("utf-16-be", "utf-16"),420            ("utf-16-le", "utf-16"),421            ("utf-32-be", "utf-32"),422            ("utf-32-le", "utf-32"),423        ),424    )425    def test_guess_by_bom(self, encoding, expected):426        data = "\ufeff{}".encode(encoding)427        assert guess_json_utf(data) == expected428429430USER = PASSWORD = "%!*'();:@&=+$,/?#[] "431ENCODED_USER = compat.quote(USER, "")432ENCODED_PASSWORD = compat.quote(PASSWORD, "")433434435@pytest.mark.parametrize(436    "url, auth",437    (438        (439            f"http://{ENCODED_USER}:{ENCODED_PASSWORD}@request.com/url.html#test",440            (USER, PASSWORD),441        ),442        ("http://user:pass@complex.url.com/path?query=yes", ("user", "pass")),443        (444            "http://user:pass%20pass@complex.url.com/path?query=yes",445            ("user", "pass pass"),446        ),447        ("http://user:pass pass@complex.url.com/path?query=yes", ("user", "pass pass")),448        (449            "http://user%25user:pass@complex.url.com/path?query=yes",450            ("user%user", "pass"),451        ),452        (453            "http://user:pass%23pass@complex.url.com/path?query=yes",454            ("user", "pass#pass"),455        ),456        ("http://complex.url.com/path?query=yes", ("", "")),457    ),458)459def test_get_auth_from_url(url, auth):460    assert get_auth_from_url(url) == auth461462463@pytest.mark.parametrize(464    "uri, expected",465    (466        (467            # Ensure requoting doesn't break expectations468            "http://example.com/fiz?buz=%25ppicture",469            "http://example.com/fiz?buz=%25ppicture",470        ),471        (472            # Ensure we handle unquoted percent signs in redirects473            "http://example.com/fiz?buz=%ppicture",474            "http://example.com/fiz?buz=%25ppicture",475        ),476    ),477)478def test_requote_uri_with_unquoted_percents(uri, expected):479    """See: https://github.com/psf/requests/issues/2356"""480    assert requote_uri(uri) == expected481482483@pytest.mark.parametrize(484    "uri, expected",485    (486        (487            # Illegal bytes488            "http://example.com/?a=%--",489            "http://example.com/?a=%--",490        ),491        (492            # Reserved characters493            "http://example.com/?a=%300",494            "http://example.com/?a=00",495        ),496    ),497)498def test_unquote_unreserved(uri, expected):499    assert unquote_unreserved(uri) == expected500501502@pytest.mark.parametrize(503    "mask, expected",504    (505        (8, "255.0.0.0"),506        (24, "255.255.255.0"),507        (25, "255.255.255.128"),508    ),509)510def test_dotted_netmask(mask, expected):511    assert dotted_netmask(mask) == expected512513514http_proxies = {515    "http": "http://http.proxy",516    "http://some.host": "http://some.host.proxy",517}518all_proxies = {519    "all": "socks5://http.proxy",520    "all://some.host": "socks5://some.host.proxy",521}522mixed_proxies = {523    "http": "http://http.proxy",524    "http://some.host": "http://some.host.proxy",525    "all": "socks5://http.proxy",526}527528529@pytest.mark.parametrize(530    "url, expected, proxies",531    (532        ("hTTp://u:p@Some.Host/path", "http://some.host.proxy", http_proxies),533        ("hTTp://u:p@Other.Host/path", "http://http.proxy", http_proxies),534        ("hTTp:///path", "http://http.proxy", http_proxies),535        ("hTTps://Other.Host", None, http_proxies),536        ("file:///etc/motd", None, http_proxies),537        ("hTTp://u:p@Some.Host/path", "socks5://some.host.proxy", all_proxies),538        ("hTTp://u:p@Other.Host/path", "socks5://http.proxy", all_proxies),539        ("hTTp:///path", "socks5://http.proxy", all_proxies),540        ("hTTps://Other.Host", "socks5://http.proxy", all_proxies),541        ("http://u:p@other.host/path", "http://http.proxy", mixed_proxies),542        ("http://u:p@some.host/path", "http://some.host.proxy", mixed_proxies),543        ("https://u:p@other.host/path", "socks5://http.proxy", mixed_proxies),544        ("https://u:p@some.host/path", "socks5://http.proxy", mixed_proxies),545        ("https://", "socks5://http.proxy", mixed_proxies),546        # XXX: unsure whether this is reasonable behavior547        ("file:///etc/motd", "socks5://http.proxy", all_proxies),548    ),549)550def test_select_proxies(url, expected, proxies):551    """Make sure we can select per-host proxies correctly."""552    assert select_proxy(url, proxies) == expected553554555@pytest.mark.parametrize(556    "value, expected",557    (558        ('foo="is a fish", bar="as well"', {"foo": "is a fish", "bar": "as well"}),559        ("key_without_value", {"key_without_value": None}),560    ),561)562def test_parse_dict_header(value, expected):563    assert parse_dict_header(value) == expected564565566@pytest.mark.parametrize(567    "value, expected",568    (569        ("application/xml", ("application/xml", {})),570        (571            "application/json ; charset=utf-8",572            ("application/json", {"charset": "utf-8"}),573        ),574        (575            "application/json ; Charset=utf-8",576            ("application/json", {"charset": "utf-8"}),577        ),578        ("text/plain", ("text/plain", {})),579        (580            "multipart/form-data; boundary = something ; boundary2='something_else' ; no_equals ",581            (582                "multipart/form-data",583                {584                    "boundary": "something",585                    "boundary2": "something_else",586                    "no_equals": True,587                },588            ),589        ),590        (591            'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',592            (593                "multipart/form-data",594                {595                    "boundary": "something",596                    "boundary2": "something_else",597                    "no_equals": True,598                },599            ),600        ),601        (602            "multipart/form-data; boundary = something ; 'boundary2=something_else' ; no_equals ",603            (604                "multipart/form-data",605                {606                    "boundary": "something",607                    "boundary2": "something_else",608                    "no_equals": True,609                },610            ),611        ),612        (613            'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',614            (615                "multipart/form-data",616                {617                    "boundary": "something",618                    "boundary2": "something_else",619                    "no_equals": True,620                },621            ),622        ),623        ("application/json ; ; ", ("application/json", {})),624    ),625)626def test__parse_content_type_header(value, expected):627    assert _parse_content_type_header(value) == expected628629630@pytest.mark.parametrize(631    "value, expected",632    (633        (CaseInsensitiveDict(), None),634        (635            CaseInsensitiveDict({"content-type": "application/json; charset=utf-8"}),636            "utf-8",637        ),638        (CaseInsensitiveDict({"content-type": "text/plain"}), "ISO-8859-1"),639    ),640)641def test_get_encoding_from_headers(value, expected):642    assert get_encoding_from_headers(value) == expected643644645@pytest.mark.parametrize(646    "value, length",647    (648        ("", 0),649        ("T", 1),650        ("Test", 4),651        ("Cont", 0),652        ("Other", -5),653        ("Content", None),654    ),655)656def test_iter_slices(value, length):657    if length is None or (length <= 0 and len(value) > 0):658        # Reads all content at once659        assert len(list(iter_slices(value, length))) == 1660    else:661        assert len(list(iter_slices(value, 1))) == length662663664@pytest.mark.parametrize(665    "value, expected",666    (667        (668            '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',669            [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],670        ),671        ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),672        ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),673        (674            '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',675            [676                {"url": "http:/.../front.jpeg", "type": "image/jpeg"},677                {"url": "http://.../back.jpeg"},678            ],679        ),680        ("", []),681    ),682)683def test_parse_header_links(value, expected):684    assert parse_header_links(value) == expected685686687@pytest.mark.parametrize(688    "value, expected",689    (690        ("example.com/path", "http://example.com/path"),691        ("//example.com/path", "http://example.com/path"),692        ("example.com:80", "http://example.com:80"),693        (694            "http://user:pass@example.com/path?query",695            "http://user:pass@example.com/path?query",696        ),697        ("http://user@example.com/path?query", "http://user@example.com/path?query"),698    ),699)700def test_prepend_scheme_if_needed(value, expected):701    assert prepend_scheme_if_needed(value, "http") == expected702703704@pytest.mark.parametrize(705    "value, expected",706    (707        ("T", "T"),708        (b"T", "T"),709        ("T", "T"),710    ),711)712def test_to_native_string(value, expected):713    assert to_native_string(value) == expected714715716@pytest.mark.parametrize(717    "url, expected",718    (719        ("http://u:p@example.com/path?a=1#test", "http://example.com/path?a=1"),720        ("http://example.com/path", "http://example.com/path"),721        ("//u:p@example.com/path", "//example.com/path"),722        ("//example.com/path", "//example.com/path"),723        ("example.com/path", "//example.com/path"),724        ("scheme:u:p@example.com/path", "scheme://example.com/path"),725    ),726)727def test_urldefragauth(url, expected):728    assert urldefragauth(url) == expected729730731@pytest.mark.parametrize(732    "url, expected",733    (734        ("http://192.168.0.1:5000/", True),735        ("http://192.168.0.1/", True),736        ("http://172.16.1.1/", True),737        ("http://172.16.1.1:5000/", True),738        ("http://localhost.localdomain:5000/v1.0/", True),739        ("http://google.com:6000/", True),740        ("http://172.16.1.12/", False),741        ("http://172.16.1.12:5000/", False),742        ("http://google.com:5000/v1.0/", False),743        ("file:///some/path/on/disk", True),744    ),745)746def test_should_bypass_proxies(url, expected, monkeypatch):747    """Tests for function should_bypass_proxies to check if proxy748    can be bypassed or not749    """750    monkeypatch.setenv(751        "no_proxy",752        "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000",753    )754    monkeypatch.setenv(755        "NO_PROXY",756        "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000",757    )758    assert should_bypass_proxies(url, no_proxy=None) == expected759760761@pytest.mark.parametrize(762    "url, expected",763    (764        ("http://172.16.1.1/", "172.16.1.1"),765        ("http://172.16.1.1:5000/", "172.16.1.1"),766        ("http://user:pass@172.16.1.1", "172.16.1.1"),767        ("http://user:pass@172.16.1.1:5000", "172.16.1.1"),768        ("http://hostname/", "hostname"),769        ("http://hostname:5000/", "hostname"),770        ("http://user:pass@hostname", "hostname"),771        ("http://user:pass@hostname:5000", "hostname"),772    ),773)774def test_should_bypass_proxies_pass_only_hostname(url, expected):775    """The proxy_bypass function should be called with a hostname or IP without776    a port number or auth credentials.777    """778    with mock.patch("requests.utils.proxy_bypass") as proxy_bypass:779        should_bypass_proxies(url, no_proxy=None)780        proxy_bypass.assert_called_once_with(expected)781782783@pytest.mark.parametrize(784    "cookiejar",785    (786        compat.cookielib.CookieJar(),787        RequestsCookieJar(),788    ),789)790def test_add_dict_to_cookiejar(cookiejar):791    """Ensure add_dict_to_cookiejar works for792    non-RequestsCookieJar CookieJars793    """794    cookiedict = {"test": "cookies", "good": "cookies"}795    cj = add_dict_to_cookiejar(cookiejar, cookiedict)796    cookies = {cookie.name: cookie.value for cookie in cj}797    assert cookiedict == cookies798799800@pytest.mark.parametrize(801    "value, expected",802    (803        ("test", True),804        ("æíöû", False),805        ("ジェーピーニック", False),806    ),807)808def test_unicode_is_ascii(value, expected):809    assert unicode_is_ascii(value) is expected810811812@pytest.mark.parametrize(813    "url, expected",814    (815        ("http://192.168.0.1:5000/", True),816        ("http://192.168.0.1/", True),817        ("http://172.16.1.1/", True),818        ("http://172.16.1.1:5000/", True),819        ("http://localhost.localdomain:5000/v1.0/", True),820        ("http://172.16.1.12/", False),821        ("http://172.16.1.12:5000/", False),822        ("http://google.com:5000/v1.0/", False),823    ),824)825def test_should_bypass_proxies_no_proxy(url, expected, monkeypatch):826    """Tests for function should_bypass_proxies to check if proxy827    can be bypassed or not using the 'no_proxy' argument828    """829    no_proxy = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"830    # Test 'no_proxy' argument831    assert should_bypass_proxies(url, no_proxy=no_proxy) == expected832833834@pytest.mark.skipif(os.name != "nt", reason="Test only on Windows")835@pytest.mark.parametrize(836    "url, expected, override",837    (838        ("http://192.168.0.1:5000/", True, None),839        ("http://192.168.0.1/", True, None),840        ("http://172.16.1.1/", True, None),841        ("http://172.16.1.1:5000/", True, None),842        ("http://localhost.localdomain:5000/v1.0/", True, None),843        ("http://172.16.1.22/", False, None),844        ("http://172.16.1.22:5000/", False, None),845        ("http://google.com:5000/v1.0/", False, None),846        ("http://mylocalhostname:5000/v1.0/", True, "<local>"),847        ("http://192.168.0.1/", False, ""),848    ),849)850def test_should_bypass_proxies_win_registry(url, expected, override, monkeypatch):851    """Tests for function should_bypass_proxies to check if proxy852    can be bypassed or not with Windows registry settings853    """854    if override is None:855        override = "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"856    import winreg857858    class RegHandle:859        def Close(self):860            pass861862    ie_settings = RegHandle()863    proxyEnableValues = deque([1, "1"])864865    def OpenKey(key, subkey):866        return ie_settings867868    def QueryValueEx(key, value_name):869        if key is ie_settings:870            if value_name == "ProxyEnable":871                # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)872                proxyEnableValues.rotate()873                return [proxyEnableValues[0]]874            elif value_name == "ProxyOverride":875                return [override]876877    monkeypatch.setenv("http_proxy", "")878    monkeypatch.setenv("https_proxy", "")879    monkeypatch.setenv("ftp_proxy", "")880    monkeypatch.setenv("no_proxy", "")881    monkeypatch.setenv("NO_PROXY", "")882    monkeypatch.setattr(winreg, "OpenKey", OpenKey)883    monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx)884    assert should_bypass_proxies(url, None) == expected885886887@pytest.mark.skipif(os.name != "nt", reason="Test only on Windows")888def test_should_bypass_proxies_win_registry_bad_values(monkeypatch):889    """Tests for function should_bypass_proxies to check if proxy890    can be bypassed or not with Windows invalid registry settings.891    """892    import winreg893894    class RegHandle:895        def Close(self):896            pass897898    ie_settings = RegHandle()899900    def OpenKey(key, subkey):901        return ie_settings902903    def QueryValueEx(key, value_name):904        if key is ie_settings:905            if value_name == "ProxyEnable":906                # Invalid response; Should be an int or int-y value907                return [""]908            elif value_name == "ProxyOverride":909                return ["192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"]910911    monkeypatch.setenv("http_proxy", "")912    monkeypatch.setenv("https_proxy", "")913    monkeypatch.setenv("no_proxy", "")914    monkeypatch.setenv("NO_PROXY", "")915    monkeypatch.setattr(winreg, "OpenKey", OpenKey)916    monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx)917    assert should_bypass_proxies("http://172.16.1.1/", None) is False918919920@pytest.mark.parametrize(921    "env_name, value",922    (923        ("no_proxy", "192.168.0.0/24,127.0.0.1,localhost.localdomain"),924        ("no_proxy", None),925        ("a_new_key", "192.168.0.0/24,127.0.0.1,localhost.localdomain"),926        ("a_new_key", None),927    ),928)929def test_set_environ(env_name, value):930    """Tests set_environ will set environ values and will restore the environ."""931    environ_copy = copy.deepcopy(os.environ)932    with set_environ(env_name, value):933        assert os.environ.get(env_name) == value934935    assert os.environ == environ_copy936937938def test_set_environ_raises_exception():939    """Tests set_environ will raise exceptions in context when the940    value parameter is None."""941    with pytest.raises(Exception) as exception:942        with set_environ("test1", None):943            raise Exception("Expected exception")944945    assert "Expected exception" in str(exception.value)946947948@pytest.mark.skipif(os.name != "nt", reason="Test only on Windows")949def test_should_bypass_proxies_win_registry_ProxyOverride_value(monkeypatch):950    """Tests for function should_bypass_proxies to check if proxy951    can be bypassed or not with Windows ProxyOverride registry value ending with a semicolon.952    """953    import winreg954955    class RegHandle:956        def Close(self):957            pass958959    ie_settings = RegHandle()960961    def OpenKey(key, subkey):962        return ie_settings963964    def QueryValueEx(key, value_name):965        if key is ie_settings:966            if value_name == "ProxyEnable":967                return [1]968            elif value_name == "ProxyOverride":969                return [970                    "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1;<-loopback>;"971                ]972973    monkeypatch.setenv("NO_PROXY", "")974    monkeypatch.setenv("no_proxy", "")975    monkeypatch.setattr(winreg, "OpenKey", OpenKey)976    monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx)977    assert should_bypass_proxies("http://example.com/", None) is False