Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

2,839 lines · 97.3 KiB · Python

Last changed by

Merge pull request #6589 from bruceadams/super_len_str_utf-8Ian Stapleton Cordascobefore adoptionb8be93a

History of this file

Take it

1"""Tests for Requests."""23import collections4import contextlib5import io6import json7import os8import pickle9import re10import warnings11from unittest import mock1213import pytest14import urllib315from urllib3.util import Timeout as Urllib3Timeout1617import requests18from requests.adapters import HTTPAdapter19from requests.auth import HTTPDigestAuth, _basic_auth_str20from requests.compat import (21    JSONDecodeError,22    Morsel,23    MutableMapping,24    builtin_str,25    cookielib,26    getproxies,27    urlparse,28)29from requests.cookies import cookiejar_from_dict, morsel_to_cookie30from requests.exceptions import (31    ChunkedEncodingError,32    ConnectionError,33    ConnectTimeout,34    ContentDecodingError,35    InvalidHeader,36    InvalidProxyURL,37    InvalidSchema,38    InvalidURL,39    MissingSchema,40    ProxyError,41    ReadTimeout,42    RequestException,43    RetryError,44)45from requests.exceptions import SSLError as RequestsSSLError46from requests.exceptions import Timeout, TooManyRedirects, UnrewindableBodyError47from requests.hooks import default_hooks48from requests.models import PreparedRequest, urlencode49from requests.sessions import SessionRedirectMixin50from requests.structures import CaseInsensitiveDict5152from . import SNIMissingWarning53from .compat import StringIO54from .utils import override_environ5556# Requests to this URL should always fail with a connection timeout (nothing57# listening on that port)58TARPIT = "http://10.255.255.1"5960# This is to avoid waiting the timeout of using TARPIT61INVALID_PROXY = "http://localhost:1"6263try:64    from ssl import SSLContext6566    del SSLContext67    HAS_MODERN_SSL = True68except ImportError:69    HAS_MODERN_SSL = False7071try:72    requests.pyopenssl73    HAS_PYOPENSSL = True74except AttributeError:75    HAS_PYOPENSSL = False767778class TestRequests:79    digest_auth_algo = ("MD5", "SHA-256", "SHA-512")8081    def test_entry_points(self):82        requests.session83        requests.session().get84        requests.session().head85        requests.get86        requests.head87        requests.put88        requests.patch89        requests.post90        # Not really an entry point, but people rely on it.91        from requests.packages.urllib3.poolmanager import PoolManager  # noqa:F4019293    @pytest.mark.parametrize(94        "exception, url",95        (96            (MissingSchema, "hiwpefhipowhefopw"),97            (InvalidSchema, "localhost:3128"),98            (InvalidSchema, "localhost.localdomain:3128/"),99            (InvalidSchema, "10.122.1.1:3128/"),100            (InvalidURL, "http://"),101            (InvalidURL, "http://*example.com"),102            (InvalidURL, "http://.example.com"),103        ),104    )105    def test_invalid_url(self, exception, url):106        with pytest.raises(exception):107            requests.get(url)108109    def test_basic_building(self):110        req = requests.Request()111        req.url = "http://kennethreitz.org/"112        req.data = {"life": "42"}113114        pr = req.prepare()115        assert pr.url == req.url116        assert pr.body == "life=42"117118    @pytest.mark.parametrize("method", ("GET", "HEAD"))119    def test_no_content_length(self, httpbin, method):120        req = requests.Request(method, httpbin(method.lower())).prepare()121        assert "Content-Length" not in req.headers122123    @pytest.mark.parametrize("method", ("POST", "PUT", "PATCH", "OPTIONS"))124    def test_no_body_content_length(self, httpbin, method):125        req = requests.Request(method, httpbin(method.lower())).prepare()126        assert req.headers["Content-Length"] == "0"127128    @pytest.mark.parametrize("method", ("POST", "PUT", "PATCH", "OPTIONS"))129    def test_empty_content_length(self, httpbin, method):130        req = requests.Request(method, httpbin(method.lower()), data="").prepare()131        assert req.headers["Content-Length"] == "0"132133    def test_override_content_length(self, httpbin):134        headers = {"Content-Length": "not zero"}135        r = requests.Request("POST", httpbin("post"), headers=headers).prepare()136        assert "Content-Length" in r.headers137        assert r.headers["Content-Length"] == "not zero"138139    def test_path_is_not_double_encoded(self):140        request = requests.Request("GET", "http://0.0.0.0/get/test case").prepare()141142        assert request.path_url == "/get/test%20case"143144    @pytest.mark.parametrize(145        "url, expected",146        (147            (148                "http://example.com/path#fragment",149                "http://example.com/path?a=b#fragment",150            ),151            (152                "http://example.com/path?key=value#fragment",153                "http://example.com/path?key=value&a=b#fragment",154            ),155        ),156    )157    def test_params_are_added_before_fragment(self, url, expected):158        request = requests.Request("GET", url, params={"a": "b"}).prepare()159        assert request.url == expected160161    def test_params_original_order_is_preserved_by_default(self):162        param_ordered_dict = collections.OrderedDict(163            (("z", 1), ("a", 1), ("k", 1), ("d", 1))164        )165        session = requests.Session()166        request = requests.Request(167            "GET", "http://example.com/", params=param_ordered_dict168        )169        prep = session.prepare_request(request)170        assert prep.url == "http://example.com/?z=1&a=1&k=1&d=1"171172    def test_params_bytes_are_encoded(self):173        request = requests.Request(174            "GET", "http://example.com", params=b"test=foo"175        ).prepare()176        assert request.url == "http://example.com/?test=foo"177178    def test_binary_put(self):179        request = requests.Request(180            "PUT", "http://example.com", data="ööö".encode()181        ).prepare()182        assert isinstance(request.body, bytes)183184    def test_whitespaces_are_removed_from_url(self):185        # Test for issue #3696186        request = requests.Request("GET", " http://example.com").prepare()187        assert request.url == "http://example.com/"188189    @pytest.mark.parametrize("scheme", ("http://", "HTTP://", "hTTp://", "HttP://"))190    def test_mixed_case_scheme_acceptable(self, httpbin, scheme):191        s = requests.Session()192        s.proxies = getproxies()193        parts = urlparse(httpbin("get"))194        url = scheme + parts.netloc + parts.path195        r = requests.Request("GET", url)196        r = s.send(r.prepare())197        assert r.status_code == 200, f"failed for scheme {scheme}"198199    def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):200        r = requests.Request("GET", httpbin("get"))201        s = requests.Session()202        s.proxies = getproxies()203204        r = s.send(r.prepare())205206        assert r.status_code == 200207208    def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):209        r = requests.get(httpbin("redirect", "1"))210        assert r.status_code == 200211        assert r.history[0].status_code == 302212        assert r.history[0].is_redirect213214    def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):215        r = requests.post(216            httpbin("redirect-to"),217            data="test",218            params={"url": "post", "status_code": 307},219        )220        assert r.status_code == 200221        assert r.history[0].status_code == 307222        assert r.history[0].is_redirect223        assert r.json()["data"] == "test"224225    def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):226        byte_str = b"test"227        r = requests.post(228            httpbin("redirect-to"),229            data=io.BytesIO(byte_str),230            params={"url": "post", "status_code": 307},231        )232        assert r.status_code == 200233        assert r.history[0].status_code == 307234        assert r.history[0].is_redirect235        assert r.json()["data"] == byte_str.decode("utf-8")236237    def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):238        try:239            requests.get(httpbin("relative-redirect", "50"))240        except TooManyRedirects as e:241            url = httpbin("relative-redirect", "20")242            assert e.request.url == url243            assert e.response.url == url244            assert len(e.response.history) == 30245        else:246            pytest.fail("Expected redirect to raise TooManyRedirects but it did not")247248    def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):249        s = requests.session()250        s.max_redirects = 5251        try:252            s.get(httpbin("relative-redirect", "50"))253        except TooManyRedirects as e:254            url = httpbin("relative-redirect", "45")255            assert e.request.url == url256            assert e.response.url == url257            assert len(e.response.history) == 5258        else:259            pytest.fail(260                "Expected custom max number of redirects to be respected but was not"261            )262263    def test_http_301_changes_post_to_get(self, httpbin):264        r = requests.post(httpbin("status", "301"))265        assert r.status_code == 200266        assert r.request.method == "GET"267        assert r.history[0].status_code == 301268        assert r.history[0].is_redirect269270    def test_http_301_doesnt_change_head_to_get(self, httpbin):271        r = requests.head(httpbin("status", "301"), allow_redirects=True)272        print(r.content)273        assert r.status_code == 200274        assert r.request.method == "HEAD"275        assert r.history[0].status_code == 301276        assert r.history[0].is_redirect277278    def test_http_302_changes_post_to_get(self, httpbin):279        r = requests.post(httpbin("status", "302"))280        assert r.status_code == 200281        assert r.request.method == "GET"282        assert r.history[0].status_code == 302283        assert r.history[0].is_redirect284285    def test_http_302_doesnt_change_head_to_get(self, httpbin):286        r = requests.head(httpbin("status", "302"), allow_redirects=True)287        assert r.status_code == 200288        assert r.request.method == "HEAD"289        assert r.history[0].status_code == 302290        assert r.history[0].is_redirect291292    def test_http_303_changes_post_to_get(self, httpbin):293        r = requests.post(httpbin("status", "303"))294        assert r.status_code == 200295        assert r.request.method == "GET"296        assert r.history[0].status_code == 303297        assert r.history[0].is_redirect298299    def test_http_303_doesnt_change_head_to_get(self, httpbin):300        r = requests.head(httpbin("status", "303"), allow_redirects=True)301        assert r.status_code == 200302        assert r.request.method == "HEAD"303        assert r.history[0].status_code == 303304        assert r.history[0].is_redirect305306    def test_header_and_body_removal_on_redirect(self, httpbin):307        purged_headers = ("Content-Length", "Content-Type")308        ses = requests.Session()309        req = requests.Request("POST", httpbin("post"), data={"test": "data"})310        prep = ses.prepare_request(req)311        resp = ses.send(prep)312313        # Mimic a redirect response314        resp.status_code = 302315        resp.headers["location"] = "get"316317        # Run request through resolve_redirects318        next_resp = next(ses.resolve_redirects(resp, prep))319        assert next_resp.request.body is None320        for header in purged_headers:321            assert header not in next_resp.request.headers322323    def test_transfer_enc_removal_on_redirect(self, httpbin):324        purged_headers = ("Transfer-Encoding", "Content-Type")325        ses = requests.Session()326        req = requests.Request("POST", httpbin("post"), data=(b"x" for x in range(1)))327        prep = ses.prepare_request(req)328        assert "Transfer-Encoding" in prep.headers329330        # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33331        resp = requests.Response()332        resp.raw = io.BytesIO(b"the content")333        resp.request = prep334        setattr(resp.raw, "release_conn", lambda *args: args)335336        # Mimic a redirect response337        resp.status_code = 302338        resp.headers["location"] = httpbin("get")339340        # Run request through resolve_redirect341        next_resp = next(ses.resolve_redirects(resp, prep))342        assert next_resp.request.body is None343        for header in purged_headers:344            assert header not in next_resp.request.headers345346    def test_fragment_maintained_on_redirect(self, httpbin):347        fragment = "#view=edit&token=hunter2"348        r = requests.get(httpbin("redirect-to?url=get") + fragment)349350        assert len(r.history) > 0351        assert r.history[0].request.url == httpbin("redirect-to?url=get") + fragment352        assert r.url == httpbin("get") + fragment353354    def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):355        heads = {"User-agent": "Mozilla/5.0"}356357        r = requests.get(httpbin("user-agent"), headers=heads)358359        assert heads["User-agent"] in r.text360        assert r.status_code == 200361362    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):363        heads = {"User-agent": "Mozilla/5.0"}364365        r = requests.get(366            httpbin("get") + "?test=true", params={"q": "test"}, headers=heads367        )368        assert r.status_code == 200369370    def test_set_cookie_on_301(self, httpbin):371        s = requests.session()372        url = httpbin("cookies/set?foo=bar")373        s.get(url)374        assert s.cookies["foo"] == "bar"375376    def test_cookie_sent_on_redirect(self, httpbin):377        s = requests.session()378        s.get(httpbin("cookies/set?foo=bar"))379        r = s.get(httpbin("redirect/1"))  # redirects to httpbin('get')380        assert "Cookie" in r.json()["headers"]381382    def test_cookie_removed_on_expire(self, httpbin):383        s = requests.session()384        s.get(httpbin("cookies/set?foo=bar"))385        assert s.cookies["foo"] == "bar"386        s.get(387            httpbin("response-headers"),388            params={"Set-Cookie": "foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT"},389        )390        assert "foo" not in s.cookies391392    def test_cookie_quote_wrapped(self, httpbin):393        s = requests.session()394        s.get(httpbin('cookies/set?foo="bar:baz"'))395        assert s.cookies["foo"] == '"bar:baz"'396397    def test_cookie_persists_via_api(self, httpbin):398        s = requests.session()399        r = s.get(httpbin("redirect/1"), cookies={"foo": "bar"})400        assert "foo" in r.request.headers["Cookie"]401        assert "foo" in r.history[0].request.headers["Cookie"]402403    def test_request_cookie_overrides_session_cookie(self, httpbin):404        s = requests.session()405        s.cookies["foo"] = "bar"406        r = s.get(httpbin("cookies"), cookies={"foo": "baz"})407        assert r.json()["cookies"]["foo"] == "baz"408        # Session cookie should not be modified409        assert s.cookies["foo"] == "bar"410411    def test_request_cookies_not_persisted(self, httpbin):412        s = requests.session()413        s.get(httpbin("cookies"), cookies={"foo": "baz"})414        # Sending a request with cookies should not add cookies to the session415        assert not s.cookies416417    def test_generic_cookiejar_works(self, httpbin):418        cj = cookielib.CookieJar()419        cookiejar_from_dict({"foo": "bar"}, cj)420        s = requests.session()421        s.cookies = cj422        r = s.get(httpbin("cookies"))423        # Make sure the cookie was sent424        assert r.json()["cookies"]["foo"] == "bar"425        # Make sure the session cj is still the custom one426        assert s.cookies is cj427428    def test_param_cookiejar_works(self, httpbin):429        cj = cookielib.CookieJar()430        cookiejar_from_dict({"foo": "bar"}, cj)431        s = requests.session()432        r = s.get(httpbin("cookies"), cookies=cj)433        # Make sure the cookie was sent434        assert r.json()["cookies"]["foo"] == "bar"435436    def test_cookielib_cookiejar_on_redirect(self, httpbin):437        """Tests resolve_redirect doesn't fail when merging cookies438        with non-RequestsCookieJar cookiejar.439440        See GH #3579441        """442        cj = cookiejar_from_dict({"foo": "bar"}, cookielib.CookieJar())443        s = requests.Session()444        s.cookies = cookiejar_from_dict({"cookie": "tasty"})445446        # Prepare request without using Session447        req = requests.Request("GET", httpbin("headers"), cookies=cj)448        prep_req = req.prepare()449450        # Send request and simulate redirect451        resp = s.send(prep_req)452        resp.status_code = 302453        resp.headers["location"] = httpbin("get")454        redirects = s.resolve_redirects(resp, prep_req)455        resp = next(redirects)456457        # Verify CookieJar isn't being converted to RequestsCookieJar458        assert isinstance(prep_req._cookies, cookielib.CookieJar)459        assert isinstance(resp.request._cookies, cookielib.CookieJar)460        assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)461462        cookies = {}463        for c in resp.request._cookies:464            cookies[c.name] = c.value465        assert cookies["foo"] == "bar"466        assert cookies["cookie"] == "tasty"467468    def test_requests_in_history_are_not_overridden(self, httpbin):469        resp = requests.get(httpbin("redirect/3"))470        urls = [r.url for r in resp.history]471        req_urls = [r.request.url for r in resp.history]472        assert urls == req_urls473474    def test_history_is_always_a_list(self, httpbin):475        """Show that even with redirects, Response.history is always a list."""476        resp = requests.get(httpbin("get"))477        assert isinstance(resp.history, list)478        resp = requests.get(httpbin("redirect/1"))479        assert isinstance(resp.history, list)480        assert not isinstance(resp.history, tuple)481482    def test_headers_on_session_with_None_are_not_sent(self, httpbin):483        """Do not send headers in Session.headers with None values."""484        ses = requests.Session()485        ses.headers["Accept-Encoding"] = None486        req = requests.Request("GET", httpbin("get"))487        prep = ses.prepare_request(req)488        assert "Accept-Encoding" not in prep.headers489490    def test_headers_preserve_order(self, httpbin):491        """Preserve order when headers provided as OrderedDict."""492        ses = requests.Session()493        ses.headers = collections.OrderedDict()494        ses.headers["Accept-Encoding"] = "identity"495        ses.headers["First"] = "1"496        ses.headers["Second"] = "2"497        headers = collections.OrderedDict([("Third", "3"), ("Fourth", "4")])498        headers["Fifth"] = "5"499        headers["Second"] = "222"500        req = requests.Request("GET", httpbin("get"), headers=headers)501        prep = ses.prepare_request(req)502        items = list(prep.headers.items())503        assert items[0] == ("Accept-Encoding", "identity")504        assert items[1] == ("First", "1")505        assert items[2] == ("Second", "222")506        assert items[3] == ("Third", "3")507        assert items[4] == ("Fourth", "4")508        assert items[5] == ("Fifth", "5")509510    @pytest.mark.parametrize("key", ("User-agent", "user-agent"))511    def test_user_agent_transfers(self, httpbin, key):512        heads = {key: "Mozilla/5.0 (github.com/psf/requests)"}513514        r = requests.get(httpbin("user-agent"), headers=heads)515        assert heads[key] in r.text516517    def test_HTTP_200_OK_HEAD(self, httpbin):518        r = requests.head(httpbin("get"))519        assert r.status_code == 200520521    def test_HTTP_200_OK_PUT(self, httpbin):522        r = requests.put(httpbin("put"))523        assert r.status_code == 200524525    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):526        auth = ("user", "pass")527        url = httpbin("basic-auth", "user", "pass")528529        r = requests.get(url, auth=auth)530        assert r.status_code == 200531532        r = requests.get(url)533        assert r.status_code == 401534535        s = requests.session()536        s.auth = auth537        r = s.get(url)538        assert r.status_code == 200539540    @pytest.mark.parametrize(541        "username, password",542        (543            ("user", "pass"),544            ("имя".encode(), "пароль".encode()),545            (42, 42),546            (None, None),547        ),548    )549    def test_set_basicauth(self, httpbin, username, password):550        auth = (username, password)551        url = httpbin("get")552553        r = requests.Request("GET", url, auth=auth)554        p = r.prepare()555556        assert p.headers["Authorization"] == _basic_auth_str(username, password)557558    def test_basicauth_encodes_byte_strings(self):559        """Ensure b'test' formats as the byte string "test" rather560        than the unicode string "b'test'" in Python 3.561        """562        auth = (b"\xc5\xafsername", b"test\xc6\xb6")563        r = requests.Request("GET", "http://localhost", auth=auth)564        p = r.prepare()565566        assert p.headers["Authorization"] == "Basic xa9zZXJuYW1lOnRlc3TGtg=="567568    @pytest.mark.parametrize(569        "url, exception",570        (571            # Connecting to an unknown domain should raise a ConnectionError572            ("http://doesnotexist.google.com", ConnectionError),573            # Connecting to an invalid port should raise a ConnectionError574            ("http://localhost:1", ConnectionError),575            # Inputing a URL that cannot be parsed should raise an InvalidURL error576            ("http://fe80::5054:ff:fe5a:fc0", InvalidURL),577        ),578    )579    def test_errors(self, url, exception):580        with pytest.raises(exception):581            requests.get(url, timeout=1)582583    def test_proxy_error(self):584        # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError585        with pytest.raises(ProxyError):586            requests.get(587                "http://localhost:1", proxies={"http": "non-resolvable-address"}588            )589590    def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):591        with pytest.raises(InvalidProxyURL):592            requests.get(httpbin_secure(), proxies={"https": "http:/badproxyurl:3128"})593594        with pytest.raises(InvalidProxyURL):595            requests.get(httpbin(), proxies={"http": "http://:8080"})596597        with pytest.raises(InvalidProxyURL):598            requests.get(httpbin_secure(), proxies={"https": "https://"})599600        with pytest.raises(InvalidProxyURL):601            requests.get(httpbin(), proxies={"http": "http:///example.com:8080"})602603    def test_respect_proxy_env_on_send_self_prepared_request(self, httpbin):604        with override_environ(http_proxy=INVALID_PROXY):605            with pytest.raises(ProxyError):606                session = requests.Session()607                request = requests.Request("GET", httpbin())608                session.send(request.prepare())609610    def test_respect_proxy_env_on_send_session_prepared_request(self, httpbin):611        with override_environ(http_proxy=INVALID_PROXY):612            with pytest.raises(ProxyError):613                session = requests.Session()614                request = requests.Request("GET", httpbin())615                prepared = session.prepare_request(request)616                session.send(prepared)617618    def test_respect_proxy_env_on_send_with_redirects(self, httpbin):619        with override_environ(http_proxy=INVALID_PROXY):620            with pytest.raises(ProxyError):621                session = requests.Session()622                url = httpbin("redirect/1")623                print(url)624                request = requests.Request("GET", url)625                session.send(request.prepare())626627    def test_respect_proxy_env_on_get(self, httpbin):628        with override_environ(http_proxy=INVALID_PROXY):629            with pytest.raises(ProxyError):630                session = requests.Session()631                session.get(httpbin())632633    def test_respect_proxy_env_on_request(self, httpbin):634        with override_environ(http_proxy=INVALID_PROXY):635            with pytest.raises(ProxyError):636                session = requests.Session()637                session.request(method="GET", url=httpbin())638639    def test_proxy_authorization_preserved_on_request(self, httpbin):640        proxy_auth_value = "Bearer XXX"641        session = requests.Session()642        session.headers.update({"Proxy-Authorization": proxy_auth_value})643        resp = session.request(method="GET", url=httpbin("get"))644        sent_headers = resp.json().get("headers", {})645646        assert sent_headers.get("Proxy-Authorization") == proxy_auth_value647648    @pytest.mark.parametrize(649        "url,has_proxy_auth",650        (651            ("http://example.com", True),652            ("https://example.com", False),653        ),654    )655    def test_proxy_authorization_not_appended_to_https_request(656        self, url, has_proxy_auth657    ):658        session = requests.Session()659        proxies = {660            "http": "http://test:pass@localhost:8080",661            "https": "http://test:pass@localhost:8090",662        }663        req = requests.Request("GET", url)664        prep = req.prepare()665        session.rebuild_proxies(prep, proxies)666667        assert ("Proxy-Authorization" in prep.headers) is has_proxy_auth668669    def test_basicauth_with_netrc(self, httpbin):670        auth = ("user", "pass")671        wrong_auth = ("wronguser", "wrongpass")672        url = httpbin("basic-auth", "user", "pass")673674        old_auth = requests.sessions.get_netrc_auth675676        try:677678            def get_netrc_auth_mock(url):679                return auth680681            requests.sessions.get_netrc_auth = get_netrc_auth_mock682683            # Should use netrc and work.684            r = requests.get(url)685            assert r.status_code == 200686687            # Given auth should override and fail.688            r = requests.get(url, auth=wrong_auth)689            assert r.status_code == 401690691            s = requests.session()692693            # Should use netrc and work.694            r = s.get(url)695            assert r.status_code == 200696697            # Given auth should override and fail.698            s.auth = wrong_auth699            r = s.get(url)700            assert r.status_code == 401701        finally:702            requests.sessions.get_netrc_auth = old_auth703704    def test_DIGEST_HTTP_200_OK_GET(self, httpbin):705        for authtype in self.digest_auth_algo:706            auth = HTTPDigestAuth("user", "pass")707            url = httpbin("digest-auth", "auth", "user", "pass", authtype, "never")708709            r = requests.get(url, auth=auth)710            assert r.status_code == 200711712            r = requests.get(url)713            assert r.status_code == 401714            print(r.headers["WWW-Authenticate"])715716            s = requests.session()717            s.auth = HTTPDigestAuth("user", "pass")718            r = s.get(url)719            assert r.status_code == 200720721    def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):722        for authtype in self.digest_auth_algo:723            url = httpbin("digest-auth", "auth", "user", "pass", authtype)724            auth = HTTPDigestAuth("user", "pass")725            r = requests.get(url)726            assert r.cookies["fake"] == "fake_value"727728            r = requests.get(url, auth=auth)729            assert r.status_code == 200730731    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):732        for authtype in self.digest_auth_algo:733            url = httpbin("digest-auth", "auth", "user", "pass", authtype)734            auth = HTTPDigestAuth("user", "pass")735            s = requests.Session()736            s.get(url, auth=auth)737            assert s.cookies["fake"] == "fake_value"738739    def test_DIGEST_STREAM(self, httpbin):740        for authtype in self.digest_auth_algo:741            auth = HTTPDigestAuth("user", "pass")742            url = httpbin("digest-auth", "auth", "user", "pass", authtype)743744            r = requests.get(url, auth=auth, stream=True)745            assert r.raw.read() != b""746747            r = requests.get(url, auth=auth, stream=False)748            assert r.raw.read() == b""749750    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):751        for authtype in self.digest_auth_algo:752            auth = HTTPDigestAuth("user", "wrongpass")753            url = httpbin("digest-auth", "auth", "user", "pass", authtype)754755            r = requests.get(url, auth=auth)756            assert r.status_code == 401757758            r = requests.get(url)759            assert r.status_code == 401760761            s = requests.session()762            s.auth = auth763            r = s.get(url)764            assert r.status_code == 401765766    def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):767        for authtype in self.digest_auth_algo:768            auth = HTTPDigestAuth("user", "pass")769            url = httpbin("digest-auth", "auth", "user", "pass", authtype)770771            r = requests.get(url, auth=auth)772            assert '"auth"' in r.request.headers["Authorization"]773774    def test_POSTBIN_GET_POST_FILES(self, httpbin):775        url = httpbin("post")776        requests.post(url).raise_for_status()777778        post1 = requests.post(url, data={"some": "data"})779        assert post1.status_code == 200780781        with open("requirements-dev.txt") as f:782            post2 = requests.post(url, files={"some": f})783        assert post2.status_code == 200784785        post4 = requests.post(url, data='[{"some": "json"}]')786        assert post4.status_code == 200787788        with pytest.raises(ValueError):789            requests.post(url, files=["bad file data"])790791    def test_invalid_files_input(self, httpbin):792        url = httpbin("post")793        post = requests.post(url, files={"random-file-1": None, "random-file-2": 1})794        assert b'name="random-file-1"' not in post.request.body795        assert b'name="random-file-2"' in post.request.body796797    def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):798        class TestStream:799            def __init__(self, data):800                self.data = data.encode()801                self.length = len(self.data)802                self.index = 0803804            def __len__(self):805                return self.length806807            def read(self, size=None):808                if size:809                    ret = self.data[self.index : self.index + size]810                    self.index += size811                else:812                    ret = self.data[self.index :]813                    self.index = self.length814                return ret815816            def tell(self):817                return self.index818819            def seek(self, offset, where=0):820                if where == 0:821                    self.index = offset822                elif where == 1:823                    self.index += offset824                elif where == 2:825                    self.index = self.length + offset826827        test = TestStream("test")828        post1 = requests.post(httpbin("post"), data=test)829        assert post1.status_code == 200830        assert post1.json()["data"] == "test"831832        test = TestStream("test")833        test.seek(2)834        post2 = requests.post(httpbin("post"), data=test)835        assert post2.status_code == 200836        assert post2.json()["data"] == "st"837838    def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):839        url = httpbin("post")840        requests.post(url).raise_for_status()841842        post1 = requests.post(url, data={"some": "data"})843        assert post1.status_code == 200844845        with open("requirements-dev.txt") as f:846            post2 = requests.post(url, data={"some": "data"}, files={"some": f})847        assert post2.status_code == 200848849        post4 = requests.post(url, data='[{"some": "json"}]')850        assert post4.status_code == 200851852        with pytest.raises(ValueError):853            requests.post(url, files=["bad file data"])854855    def test_post_with_custom_mapping(self, httpbin):856        class CustomMapping(MutableMapping):857            def __init__(self, *args, **kwargs):858                self.data = dict(*args, **kwargs)859860            def __delitem__(self, key):861                del self.data[key]862863            def __getitem__(self, key):864                return self.data[key]865866            def __setitem__(self, key, value):867                self.data[key] = value868869            def __iter__(self):870                return iter(self.data)871872            def __len__(self):873                return len(self.data)874875        data = CustomMapping({"some": "data"})876        url = httpbin("post")877        found_json = requests.post(url, data=data).json().get("form")878        assert found_json == {"some": "data"}879880    def test_conflicting_post_params(self, httpbin):881        url = httpbin("post")882        with open("requirements-dev.txt") as f:883            with pytest.raises(ValueError):884                requests.post(url, data='[{"some": "data"}]', files={"some": f})885886    def test_request_ok_set(self, httpbin):887        r = requests.get(httpbin("status", "404"))888        assert not r.ok889890    def test_status_raising(self, httpbin):891        r = requests.get(httpbin("status", "404"))892        with pytest.raises(requests.exceptions.HTTPError):893            r.raise_for_status()894895        r = requests.get(httpbin("status", "500"))896        assert not r.ok897898    def test_decompress_gzip(self, httpbin):899        r = requests.get(httpbin("gzip"))900        r.content.decode("ascii")901902    @pytest.mark.parametrize(903        "url, params",904        (905            ("/get", {"foo": "føø"}),906            ("/get", {"føø": "føø"}),907            ("/get", {"føø": "føø"}),908            ("/get", {"foo": "foo"}),909            ("ø", {"foo": "foo"}),910        ),911    )912    def test_unicode_get(self, httpbin, url, params):913        requests.get(httpbin(url), params=params)914915    def test_unicode_header_name(self, httpbin):916        requests.put(917            httpbin("put"),918            headers={"Content-Type": "application/octet-stream"},919            data="\xff",920        )  # compat.str is unicode.921922    def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):923        requests.get(httpbin_secure("status", "301"), verify=httpbin_ca_bundle)924925    def test_invalid_ca_certificate_path(self, httpbin_secure):926        INVALID_PATH = "/garbage"927        with pytest.raises(IOError) as e:928            requests.get(httpbin_secure(), verify=INVALID_PATH)929        assert str(930            e.value931        ) == "Could not find a suitable TLS CA certificate bundle, invalid path: {}".format(932            INVALID_PATH933        )934935    def test_invalid_ssl_certificate_files(self, httpbin_secure):936        INVALID_PATH = "/garbage"937        with pytest.raises(IOError) as e:938            requests.get(httpbin_secure(), cert=INVALID_PATH)939        assert str(940            e.value941        ) == "Could not find the TLS certificate file, invalid path: {}".format(942            INVALID_PATH943        )944945        with pytest.raises(IOError) as e:946            requests.get(httpbin_secure(), cert=(".", INVALID_PATH))947        assert str(e.value) == (948            f"Could not find the TLS key file, invalid path: {INVALID_PATH}"949        )950951    @pytest.mark.parametrize(952        "env, expected",953        (954            ({}, True),955            ({"REQUESTS_CA_BUNDLE": "/some/path"}, "/some/path"),956            ({"REQUESTS_CA_BUNDLE": ""}, True),957            ({"CURL_CA_BUNDLE": "/some/path"}, "/some/path"),958            ({"CURL_CA_BUNDLE": ""}, True),959            ({"REQUESTS_CA_BUNDLE": "", "CURL_CA_BUNDLE": ""}, True),960            (961                {962                    "REQUESTS_CA_BUNDLE": "/some/path",963                    "CURL_CA_BUNDLE": "/curl/path",964                },965                "/some/path",966            ),967            (968                {969                    "REQUESTS_CA_BUNDLE": "",970                    "CURL_CA_BUNDLE": "/curl/path",971                },972                "/curl/path",973            ),974        ),975    )976    def test_env_cert_bundles(self, httpbin, env, expected):977        s = requests.Session()978        with mock.patch("os.environ", env):979            settings = s.merge_environment_settings(980                url=httpbin("get"), proxies={}, stream=False, verify=True, cert=None981            )982        assert settings["verify"] == expected983984    def test_http_with_certificate(self, httpbin):985        r = requests.get(httpbin(), cert=".")986        assert r.status_code == 200987988    @pytest.mark.skipif(989        SNIMissingWarning is None,990        reason="urllib3 2.0 removed that warning and errors out instead",991    )992    def test_https_warnings(self, nosan_server):993        """warnings are emitted with requests.get"""994        host, port, ca_bundle = nosan_server995        if HAS_MODERN_SSL or HAS_PYOPENSSL:996            warnings_expected = ("SubjectAltNameWarning",)997        else:998            warnings_expected = (999                "SNIMissingWarning",1000                "InsecurePlatformWarning",1001                "SubjectAltNameWarning",1002            )10031004        with pytest.warns(None) as warning_records:1005            warnings.simplefilter("always")1006            requests.get(f"https://localhost:{port}/", verify=ca_bundle)10071008        warning_records = [1009            item1010            for item in warning_records1011            if item.category.__name__ != "ResourceWarning"1012        ]10131014        warnings_category = tuple(item.category.__name__ for item in warning_records)1015        assert warnings_category == warnings_expected10161017    def test_certificate_failure(self, httpbin_secure):1018        """1019        When underlying SSL problems occur, an SSLError is raised.1020        """1021        with pytest.raises(RequestsSSLError):1022            # Our local httpbin does not have a trusted CA, so this call will1023            # fail if we use our default trust bundle.1024            requests.get(httpbin_secure("status", "200"))10251026    def test_urlencoded_get_query_multivalued_param(self, httpbin):1027        r = requests.get(httpbin("get"), params={"test": ["foo", "baz"]})1028        assert r.status_code == 2001029        assert r.url == httpbin("get?test=foo&test=baz")10301031    def test_form_encoded_post_query_multivalued_element(self, httpbin):1032        r = requests.Request(1033            method="POST", url=httpbin("post"), data=dict(test=["foo", "baz"])1034        )1035        prep = r.prepare()1036        assert prep.body == "test=foo&test=baz"10371038    def test_different_encodings_dont_break_post(self, httpbin):1039        with open(__file__, "rb") as f:1040            r = requests.post(1041                httpbin("post"),1042                data={"stuff": json.dumps({"a": 123})},1043                params={"blah": "asdf1234"},1044                files={"file": ("test_requests.py", f)},1045            )1046        assert r.status_code == 20010471048    @pytest.mark.parametrize(1049        "data",1050        (1051            {"stuff": "ëlïxr"},1052            {"stuff": "ëlïxr".encode()},1053            {"stuff": "elixr"},1054            {"stuff": b"elixr"},1055        ),1056    )1057    def test_unicode_multipart_post(self, httpbin, data):1058        with open(__file__, "rb") as f:1059            r = requests.post(1060                httpbin("post"),1061                data=data,1062                files={"file": ("test_requests.py", f)},1063            )1064        assert r.status_code == 20010651066    def test_unicode_multipart_post_fieldnames(self, httpbin):1067        filename = os.path.splitext(__file__)[0] + ".py"1068        with open(filename, "rb") as f:1069            r = requests.Request(1070                method="POST",1071                url=httpbin("post"),1072                data={b"stuff": "elixr"},1073                files={"file": ("test_requests.py", f)},1074            )1075            prep = r.prepare()10761077        assert b'name="stuff"' in prep.body1078        assert b"name=\"b'stuff'\"" not in prep.body10791080    def test_unicode_method_name(self, httpbin):1081        with open(__file__, "rb") as f:1082            files = {"file": f}1083            r = requests.request(1084                method="POST",1085                url=httpbin("post"),1086                files=files,1087            )1088        assert r.status_code == 20010891090    def test_unicode_method_name_with_request_object(self, httpbin):1091        s = requests.Session()1092        with open(__file__, "rb") as f:1093            files = {"file": f}1094            req = requests.Request("POST", httpbin("post"), files=files)1095            prep = s.prepare_request(req)1096        assert isinstance(prep.method, builtin_str)1097        assert prep.method == "POST"10981099        resp = s.send(prep)1100        assert resp.status_code == 20011011102    def test_non_prepared_request_error(self):1103        s = requests.Session()1104        req = requests.Request("POST", "/")11051106        with pytest.raises(ValueError) as e:1107            s.send(req)1108        assert str(e.value) == "You can only send PreparedRequests."11091110    def test_custom_content_type(self, httpbin):1111        with open(__file__, "rb") as f1:1112            with open(__file__, "rb") as f2:1113                data = {"stuff": json.dumps({"a": 123})}1114                files = {1115                    "file1": ("test_requests.py", f1),1116                    "file2": ("test_requests", f2, "text/py-content-type"),1117                }1118                r = requests.post(httpbin("post"), data=data, files=files)1119        assert r.status_code == 2001120        assert b"text/py-content-type" in r.request.body11211122    def test_hook_receives_request_arguments(self, httpbin):1123        def hook(resp, **kwargs):1124            assert resp is not None1125            assert kwargs != {}11261127        s = requests.Session()1128        r = requests.Request("GET", httpbin(), hooks={"response": hook})1129        prep = s.prepare_request(r)1130        s.send(prep)11311132    def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):1133        def hook(*args, **kwargs):1134            pass11351136        s = requests.Session()1137        s.hooks["response"].append(hook)1138        r = requests.Request("GET", httpbin())1139        prep = s.prepare_request(r)1140        assert prep.hooks["response"] != []1141        assert prep.hooks["response"] == [hook]11421143    def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):1144        def hook1(*args, **kwargs):1145            pass11461147        def hook2(*args, **kwargs):1148            pass11491150        assert hook1 is not hook21151        s = requests.Session()1152        s.hooks["response"].append(hook2)1153        r = requests.Request("GET", httpbin(), hooks={"response": [hook1]})1154        prep = s.prepare_request(r)1155        assert prep.hooks["response"] == [hook1]11561157    def test_prepared_request_hook(self, httpbin):1158        def hook(resp, **kwargs):1159            resp.hook_working = True1160            return resp11611162        req = requests.Request("GET", httpbin(), hooks={"response": hook})1163        prep = req.prepare()11641165        s = requests.Session()1166        s.proxies = getproxies()1167        resp = s.send(prep)11681169        assert hasattr(resp, "hook_working")11701171    def test_prepared_from_session(self, httpbin):1172        class DummyAuth(requests.auth.AuthBase):1173            def __call__(self, r):1174                r.headers["Dummy-Auth-Test"] = "dummy-auth-test-ok"1175                return r11761177        req = requests.Request("GET", httpbin("headers"))1178        assert not req.auth11791180        s = requests.Session()1181        s.auth = DummyAuth()11821183        prep = s.prepare_request(req)1184        resp = s.send(prep)11851186        assert resp.json()["headers"]["Dummy-Auth-Test"] == "dummy-auth-test-ok"11871188    def test_prepare_request_with_bytestring_url(self):1189        req = requests.Request("GET", b"https://httpbin.org/")1190        s = requests.Session()1191        prep = s.prepare_request(req)1192        assert prep.url == "https://httpbin.org/"11931194    def test_request_with_bytestring_host(self, httpbin):1195        s = requests.Session()1196        resp = s.request(1197            "GET",1198            httpbin("cookies/set?cookie=value"),1199            allow_redirects=False,1200            headers={"Host": b"httpbin.org"},1201        )1202        assert resp.cookies.get("cookie") == "value"12031204    def test_links(self):1205        r = requests.Response()1206        r.headers = {1207            "cache-control": "public, max-age=60, s-maxage=60",1208            "connection": "keep-alive",1209            "content-encoding": "gzip",1210            "content-type": "application/json; charset=utf-8",1211            "date": "Sat, 26 Jan 2013 16:47:56 GMT",1212            "etag": '"6ff6a73c0e446c1f61614769e3ceb778"',1213            "last-modified": "Sat, 26 Jan 2013 16:22:39 GMT",1214            "link": (1215                "<https://api.github.com/users/kennethreitz/repos?"1216                'page=2&per_page=10>; rel="next", <https://api.github.'1217                "com/users/kennethreitz/repos?page=7&per_page=10>; "1218                ' rel="last"'1219            ),1220            "server": "GitHub.com",1221            "status": "200 OK",1222            "vary": "Accept",1223            "x-content-type-options": "nosniff",1224            "x-github-media-type": "github.beta",1225            "x-ratelimit-limit": "60",1226            "x-ratelimit-remaining": "57",1227        }1228        assert r.links["next"]["rel"] == "next"12291230    def test_cookie_parameters(self):1231        key = "some_cookie"1232        value = "some_value"1233        secure = True1234        domain = "test.com"1235        rest = {"HttpOnly": True}12361237        jar = requests.cookies.RequestsCookieJar()1238        jar.set(key, value, secure=secure, domain=domain, rest=rest)12391240        assert len(jar) == 11241        assert "some_cookie" in jar12421243        cookie = list(jar)[0]1244        assert cookie.secure == secure1245        assert cookie.domain == domain1246        assert cookie._rest["HttpOnly"] == rest["HttpOnly"]12471248    def test_cookie_as_dict_keeps_len(self):1249        key = "some_cookie"1250        value = "some_value"12511252        key1 = "some_cookie1"1253        value1 = "some_value1"12541255        jar = requests.cookies.RequestsCookieJar()1256        jar.set(key, value)1257        jar.set(key1, value1)12581259        d1 = dict(jar)1260        d2 = dict(jar.iteritems())1261        d3 = dict(jar.items())12621263        assert len(jar) == 21264        assert len(d1) == 21265        assert len(d2) == 21266        assert len(d3) == 212671268    def test_cookie_as_dict_keeps_items(self):1269        key = "some_cookie"1270        value = "some_value"12711272        key1 = "some_cookie1"1273        value1 = "some_value1"12741275        jar = requests.cookies.RequestsCookieJar()1276        jar.set(key, value)1277        jar.set(key1, value1)12781279        d1 = dict(jar)1280        d2 = dict(jar.iteritems())1281        d3 = dict(jar.items())12821283        assert d1["some_cookie"] == "some_value"1284        assert d2["some_cookie"] == "some_value"1285        assert d3["some_cookie1"] == "some_value1"12861287    def test_cookie_as_dict_keys(self):1288        key = "some_cookie"1289        value = "some_value"12901291        key1 = "some_cookie1"1292        value1 = "some_value1"12931294        jar = requests.cookies.RequestsCookieJar()1295        jar.set(key, value)1296        jar.set(key1, value1)12971298        keys = jar.keys()1299        assert keys == list(keys)1300        # make sure one can use keys multiple times1301        assert list(keys) == list(keys)13021303    def test_cookie_as_dict_values(self):1304        key = "some_cookie"1305        value = "some_value"13061307        key1 = "some_cookie1"1308        value1 = "some_value1"13091310        jar = requests.cookies.RequestsCookieJar()1311        jar.set(key, value)1312        jar.set(key1, value1)13131314        values = jar.values()1315        assert values == list(values)1316        # make sure one can use values multiple times1317        assert list(values) == list(values)13181319    def test_cookie_as_dict_items(self):1320        key = "some_cookie"1321        value = "some_value"13221323        key1 = "some_cookie1"1324        value1 = "some_value1"13251326        jar = requests.cookies.RequestsCookieJar()1327        jar.set(key, value)1328        jar.set(key1, value1)13291330        items = jar.items()1331        assert items == list(items)1332        # make sure one can use items multiple times1333        assert list(items) == list(items)13341335    def test_cookie_duplicate_names_different_domains(self):1336        key = "some_cookie"1337        value = "some_value"1338        domain1 = "test1.com"1339        domain2 = "test2.com"13401341        jar = requests.cookies.RequestsCookieJar()1342        jar.set(key, value, domain=domain1)1343        jar.set(key, value, domain=domain2)1344        assert key in jar1345        items = jar.items()1346        assert len(items) == 213471348        # Verify that CookieConflictError is raised if domain is not specified1349        with pytest.raises(requests.cookies.CookieConflictError):1350            jar.get(key)13511352        # Verify that CookieConflictError is not raised if domain is specified1353        cookie = jar.get(key, domain=domain1)1354        assert cookie == value13551356    def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1357        key = "some_cookie"1358        value = "some_value"1359        path = "some_path"13601361        jar = requests.cookies.RequestsCookieJar()1362        jar.set(key, value, path=path)1363        jar.set(key, value)1364        with pytest.raises(requests.cookies.CookieConflictError):1365            jar.get(key)13661367    def test_cookie_policy_copy(self):1368        class MyCookiePolicy(cookielib.DefaultCookiePolicy):1369            pass13701371        jar = requests.cookies.RequestsCookieJar()1372        jar.set_policy(MyCookiePolicy())1373        assert isinstance(jar.copy().get_policy(), MyCookiePolicy)13741375    def test_time_elapsed_blank(self, httpbin):1376        r = requests.get(httpbin("get"))1377        td = r.elapsed1378        total_seconds = (1379            td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**61380        ) / 10**61381        assert total_seconds > 0.013821383    def test_empty_response_has_content_none(self):1384        r = requests.Response()1385        assert r.content is None13861387    def test_response_is_iterable(self):1388        r = requests.Response()1389        io = StringIO.StringIO("abc")1390        read_ = io.read13911392        def read_mock(amt, decode_content=None):1393            return read_(amt)13941395        setattr(io, "read", read_mock)1396        r.raw = io1397        assert next(iter(r))1398        io.close()13991400    def test_response_decode_unicode(self):1401        """When called with decode_unicode, Response.iter_content should always1402        return unicode.1403        """1404        r = requests.Response()1405        r._content_consumed = True1406        r._content = b"the content"1407        r.encoding = "ascii"14081409        chunks = r.iter_content(decode_unicode=True)1410        assert all(isinstance(chunk, str) for chunk in chunks)14111412        # also for streaming1413        r = requests.Response()1414        r.raw = io.BytesIO(b"the content")1415        r.encoding = "ascii"1416        chunks = r.iter_content(decode_unicode=True)1417        assert all(isinstance(chunk, str) for chunk in chunks)14181419    def test_response_reason_unicode(self):1420        # check for unicode HTTP status1421        r = requests.Response()1422        r.url = "unicode URL"1423        r.reason = "Komponenttia ei löydy".encode()1424        r.status_code = 4041425        r.encoding = None1426        assert not r.ok  # old behaviour - crashes here14271428    def test_response_reason_unicode_fallback(self):1429        # check raise_status falls back to ISO-8859-11430        r = requests.Response()1431        r.url = "some url"1432        reason = "Komponenttia ei löydy"1433        r.reason = reason.encode("latin-1")1434        r.status_code = 5001435        r.encoding = None1436        with pytest.raises(requests.exceptions.HTTPError) as e:1437            r.raise_for_status()1438        assert reason in e.value.args[0]14391440    def test_response_chunk_size_type(self):1441        """Ensure that chunk_size is passed as None or an integer, otherwise1442        raise a TypeError.1443        """1444        r = requests.Response()1445        r.raw = io.BytesIO(b"the content")1446        chunks = r.iter_content(1)1447        assert all(len(chunk) == 1 for chunk in chunks)14481449        r = requests.Response()1450        r.raw = io.BytesIO(b"the content")1451        chunks = r.iter_content(None)1452        assert list(chunks) == [b"the content"]14531454        r = requests.Response()1455        r.raw = io.BytesIO(b"the content")1456        with pytest.raises(TypeError):1457            chunks = r.iter_content("1024")14581459    @pytest.mark.parametrize(1460        "exception, args, expected",1461        (1462            (urllib3.exceptions.ProtocolError, tuple(), ChunkedEncodingError),1463            (urllib3.exceptions.DecodeError, tuple(), ContentDecodingError),1464            (urllib3.exceptions.ReadTimeoutError, (None, "", ""), ConnectionError),1465            (urllib3.exceptions.SSLError, tuple(), RequestsSSLError),1466        ),1467    )1468    def test_iter_content_wraps_exceptions(self, httpbin, exception, args, expected):1469        r = requests.Response()1470        r.raw = mock.Mock()1471        # ReadTimeoutError can't be initialized by mock1472        # so we'll manually create the instance with args1473        r.raw.stream.side_effect = exception(*args)14741475        with pytest.raises(expected):1476            next(r.iter_content(1024))14771478    def test_request_and_response_are_pickleable(self, httpbin):1479        r = requests.get(httpbin("get"))14801481        # verify we can pickle the original request1482        assert pickle.loads(pickle.dumps(r.request))14831484        # verify we can pickle the response and that we have access to1485        # the original request.1486        pr = pickle.loads(pickle.dumps(r))1487        assert r.request.url == pr.request.url1488        assert r.request.headers == pr.request.headers14891490    def test_prepared_request_is_pickleable(self, httpbin):1491        p = requests.Request("GET", httpbin("get")).prepare()14921493        # Verify PreparedRequest can be pickled and unpickled1494        r = pickle.loads(pickle.dumps(p))1495        assert r.url == p.url1496        assert r.headers == p.headers1497        assert r.body == p.body14981499        # Verify unpickled PreparedRequest sends properly1500        s = requests.Session()1501        resp = s.send(r)1502        assert resp.status_code == 20015031504    def test_prepared_request_with_file_is_pickleable(self, httpbin):1505        with open(__file__, "rb") as f:1506            r = requests.Request("POST", httpbin("post"), files={"file": f})1507            p = r.prepare()15081509        # Verify PreparedRequest can be pickled and unpickled1510        r = pickle.loads(pickle.dumps(p))1511        assert r.url == p.url1512        assert r.headers == p.headers1513        assert r.body == p.body15141515        # Verify unpickled PreparedRequest sends properly1516        s = requests.Session()1517        resp = s.send(r)1518        assert resp.status_code == 20015191520    def test_prepared_request_with_hook_is_pickleable(self, httpbin):1521        r = requests.Request("GET", httpbin("get"), hooks=default_hooks())1522        p = r.prepare()15231524        # Verify PreparedRequest can be pickled1525        r = pickle.loads(pickle.dumps(p))1526        assert r.url == p.url1527        assert r.headers == p.headers1528        assert r.body == p.body1529        assert r.hooks == p.hooks15301531        # Verify unpickled PreparedRequest sends properly1532        s = requests.Session()1533        resp = s.send(r)1534        assert resp.status_code == 20015351536    def test_cannot_send_unprepared_requests(self, httpbin):1537        r = requests.Request(url=httpbin())1538        with pytest.raises(ValueError):1539            requests.Session().send(r)15401541    def test_http_error(self):1542        error = requests.exceptions.HTTPError()1543        assert not error.response1544        response = requests.Response()1545        error = requests.exceptions.HTTPError(response=response)1546        assert error.response == response1547        error = requests.exceptions.HTTPError("message", response=response)1548        assert str(error) == "message"1549        assert error.response == response15501551    def test_session_pickling(self, httpbin):1552        r = requests.Request("GET", httpbin("get"))1553        s = requests.Session()15541555        s = pickle.loads(pickle.dumps(s))1556        s.proxies = getproxies()15571558        r = s.send(r.prepare())1559        assert r.status_code == 20015601561    def test_fixes_1329(self, httpbin):1562        """Ensure that header updates are done case-insensitively."""1563        s = requests.Session()1564        s.headers.update({"ACCEPT": "BOGUS"})1565        s.headers.update({"accept": "application/json"})1566        r = s.get(httpbin("get"))1567        headers = r.request.headers1568        assert headers["accept"] == "application/json"1569        assert headers["Accept"] == "application/json"1570        assert headers["ACCEPT"] == "application/json"15711572    def test_uppercase_scheme_redirect(self, httpbin):1573        parts = urlparse(httpbin("html"))1574        url = "HTTP://" + parts.netloc + parts.path1575        r = requests.get(httpbin("redirect-to"), params={"url": url})1576        assert r.status_code == 2001577        assert r.url.lower() == url.lower()15781579    def test_transport_adapter_ordering(self):1580        s = requests.Session()1581        order = ["https://", "http://"]1582        assert order == list(s.adapters)1583        s.mount("http://git", HTTPAdapter())1584        s.mount("http://github", HTTPAdapter())1585        s.mount("http://github.com", HTTPAdapter())1586        s.mount("http://github.com/about/", HTTPAdapter())1587        order = [1588            "http://github.com/about/",1589            "http://github.com",1590            "http://github",1591            "http://git",1592            "https://",1593            "http://",1594        ]1595        assert order == list(s.adapters)1596        s.mount("http://gittip", HTTPAdapter())1597        s.mount("http://gittip.com", HTTPAdapter())1598        s.mount("http://gittip.com/about/", HTTPAdapter())1599        order = [1600            "http://github.com/about/",1601            "http://gittip.com/about/",1602            "http://github.com",1603            "http://gittip.com",1604            "http://github",1605            "http://gittip",1606            "http://git",1607            "https://",1608            "http://",1609        ]1610        assert order == list(s.adapters)1611        s2 = requests.Session()1612        s2.adapters = {"http://": HTTPAdapter()}1613        s2.mount("https://", HTTPAdapter())1614        assert "http://" in s2.adapters1615        assert "https://" in s2.adapters16161617    def test_session_get_adapter_prefix_matching(self):1618        prefix = "https://example.com"1619        more_specific_prefix = prefix + "/some/path"16201621        url_matching_only_prefix = prefix + "/another/path"1622        url_matching_more_specific_prefix = more_specific_prefix + "/longer/path"1623        url_not_matching_prefix = "https://another.example.com/"16241625        s = requests.Session()1626        prefix_adapter = HTTPAdapter()1627        more_specific_prefix_adapter = HTTPAdapter()1628        s.mount(prefix, prefix_adapter)1629        s.mount(more_specific_prefix, more_specific_prefix_adapter)16301631        assert s.get_adapter(url_matching_only_prefix) is prefix_adapter1632        assert (1633            s.get_adapter(url_matching_more_specific_prefix)1634            is more_specific_prefix_adapter1635        )1636        assert s.get_adapter(url_not_matching_prefix) not in (1637            prefix_adapter,1638            more_specific_prefix_adapter,1639        )16401641    def test_session_get_adapter_prefix_matching_mixed_case(self):1642        mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"1643        url_matching_prefix = mixed_case_prefix + "/full_url"16441645        s = requests.Session()1646        my_adapter = HTTPAdapter()1647        s.mount(mixed_case_prefix, my_adapter)16481649        assert s.get_adapter(url_matching_prefix) is my_adapter16501651    def test_session_get_adapter_prefix_matching_is_case_insensitive(self):1652        mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"1653        url_matching_prefix_with_different_case = (1654            "HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url"1655        )16561657        s = requests.Session()1658        my_adapter = HTTPAdapter()1659        s.mount(mixed_case_prefix, my_adapter)16601661        assert s.get_adapter(url_matching_prefix_with_different_case) is my_adapter16621663    def test_header_remove_is_case_insensitive(self, httpbin):1664        # From issue #13211665        s = requests.Session()1666        s.headers["foo"] = "bar"1667        r = s.get(httpbin("get"), headers={"FOO": None})1668        assert "foo" not in r.request.headers16691670    def test_params_are_merged_case_sensitive(self, httpbin):1671        s = requests.Session()1672        s.params["foo"] = "bar"1673        r = s.get(httpbin("get"), params={"FOO": "bar"})1674        assert r.json()["args"] == {"foo": "bar", "FOO": "bar"}16751676    def test_long_authinfo_in_url(self):1677        url = "http://{}:{}@{}:9000/path?query#frag".format(1678            "E8A3BE87-9E3F-4620-8858-95478E385B5B",1679            "EA770032-DA4D-4D84-8CE9-29C6D910BF1E",1680            "exactly-------------sixty-----------three------------characters",1681        )1682        r = requests.Request("GET", url).prepare()1683        assert r.url == url16841685    def test_header_keys_are_native(self, httpbin):1686        headers = {"unicode": "blah", b"byte": "blah"}1687        r = requests.Request("GET", httpbin("get"), headers=headers)1688        p = r.prepare()16891690        # This is testing that they are builtin strings. A bit weird, but there1691        # we go.1692        assert "unicode" in p.headers.keys()1693        assert "byte" in p.headers.keys()16941695    def test_header_validation(self, httpbin):1696        """Ensure prepare_headers regex isn't flagging valid header contents."""1697        valid_headers = {1698            "foo": "bar baz qux",1699            "bar": b"fbbq",1700            "baz": "",1701            "qux": "1",1702        }1703        r = requests.get(httpbin("get"), headers=valid_headers)1704        for key in valid_headers.keys():1705            assert valid_headers[key] == r.request.headers[key]17061707    @pytest.mark.parametrize(1708        "invalid_header, key",1709        (1710            ({"foo": 3}, "foo"),1711            ({"bar": {"foo": "bar"}}, "bar"),1712            ({"baz": ["foo", "bar"]}, "baz"),1713        ),1714    )1715    def test_header_value_not_str(self, httpbin, invalid_header, key):1716        """Ensure the header value is of type string or bytes as1717        per discussion in GH issue #33861718        """1719        with pytest.raises(InvalidHeader) as excinfo:1720            requests.get(httpbin("get"), headers=invalid_header)1721        assert key in str(excinfo.value)17221723    @pytest.mark.parametrize(1724        "invalid_header",1725        (1726            {"foo": "bar\r\nbaz: qux"},1727            {"foo": "bar\n\rbaz: qux"},1728            {"foo": "bar\nbaz: qux"},1729            {"foo": "bar\rbaz: qux"},1730            {"fo\ro": "bar"},1731            {"fo\r\no": "bar"},1732            {"fo\n\ro": "bar"},1733            {"fo\no": "bar"},1734        ),1735    )1736    def test_header_no_return_chars(self, httpbin, invalid_header):1737        """Ensure that a header containing return character sequences raise an1738        exception. Otherwise, multiple headers are created from single string.1739        """1740        with pytest.raises(InvalidHeader):1741            requests.get(httpbin("get"), headers=invalid_header)17421743    @pytest.mark.parametrize(1744        "invalid_header",1745        (1746            {" foo": "bar"},1747            {"\tfoo": "bar"},1748            {"    foo": "bar"},1749            {"foo": " bar"},1750            {"foo": "    bar"},1751            {"foo": "\tbar"},1752            {" ": "bar"},1753        ),1754    )1755    def test_header_no_leading_space(self, httpbin, invalid_header):1756        """Ensure headers containing leading whitespace raise1757        InvalidHeader Error before sending.1758        """1759        with pytest.raises(InvalidHeader):1760            requests.get(httpbin("get"), headers=invalid_header)17611762    def test_header_with_subclass_types(self, httpbin):1763        """If the subclasses does not behave *exactly* like1764        the base bytes/str classes, this is not supported.1765        This test is for backwards compatibility.1766        """17671768        class MyString(str):1769            pass17701771        class MyBytes(bytes):1772            pass17731774        r_str = requests.get(httpbin("get"), headers={MyString("x-custom"): "myheader"})1775        assert r_str.request.headers["x-custom"] == "myheader"17761777        r_bytes = requests.get(1778            httpbin("get"), headers={MyBytes(b"x-custom"): b"myheader"}1779        )1780        assert r_bytes.request.headers["x-custom"] == b"myheader"17811782        r_mixed = requests.get(1783            httpbin("get"), headers={MyString("x-custom"): MyBytes(b"myheader")}1784        )1785        assert r_mixed.request.headers["x-custom"] == b"myheader"17861787    @pytest.mark.parametrize("files", ("foo", b"foo", bytearray(b"foo")))1788    def test_can_send_objects_with_files(self, httpbin, files):1789        data = {"a": "this is a string"}1790        files = {"b": files}1791        r = requests.Request("POST", httpbin("post"), data=data, files=files)1792        p = r.prepare()1793        assert "multipart/form-data" in p.headers["Content-Type"]17941795    def test_can_send_file_object_with_non_string_filename(self, httpbin):1796        f = io.BytesIO()1797        f.name = 21798        r = requests.Request("POST", httpbin("post"), files={"f": f})1799        p = r.prepare()18001801        assert "multipart/form-data" in p.headers["Content-Type"]18021803    def test_autoset_header_values_are_native(self, httpbin):1804        data = "this is a string"1805        length = "16"1806        req = requests.Request("POST", httpbin("post"), data=data)1807        p = req.prepare()18081809        assert p.headers["Content-Length"] == length18101811    def test_content_length_for_bytes_data(self, httpbin):1812        data = "This is a string containing multi-byte UTF-8 ☃️"1813        encoded_data = data.encode("utf-8")1814        length = str(len(encoded_data))1815        req = requests.Request("POST", httpbin("post"), data=encoded_data)1816        p = req.prepare()18171818        assert p.headers["Content-Length"] == length18191820    def test_content_length_for_string_data_counts_bytes(self, httpbin):1821        data = "This is a string containing multi-byte UTF-8 ☃️"1822        length = str(len(data.encode("utf-8")))1823        req = requests.Request("POST", httpbin("post"), data=data)1824        p = req.prepare()18251826        assert p.headers["Content-Length"] == length18271828    def test_nonhttp_schemes_dont_check_URLs(self):1829        test_urls = (1830            "data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",1831            "file:///etc/passwd",1832            "magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431",1833        )1834        for test_url in test_urls:1835            req = requests.Request("GET", test_url)1836            preq = req.prepare()1837            assert test_url == preq.url18381839    def test_auth_is_stripped_on_http_downgrade(1840        self, httpbin, httpbin_secure, httpbin_ca_bundle1841    ):1842        r = requests.get(1843            httpbin_secure("redirect-to"),1844            params={"url": httpbin("get")},1845            auth=("user", "pass"),1846            verify=httpbin_ca_bundle,1847        )1848        assert r.history[0].request.headers["Authorization"]1849        assert "Authorization" not in r.request.headers18501851    def test_auth_is_retained_for_redirect_on_host(self, httpbin):1852        r = requests.get(httpbin("redirect/1"), auth=("user", "pass"))1853        h1 = r.history[0].request.headers["Authorization"]1854        h2 = r.request.headers["Authorization"]18551856        assert h1 == h218571858    def test_should_strip_auth_host_change(self):1859        s = requests.Session()1860        assert s.should_strip_auth(1861            "http://example.com/foo", "http://another.example.com/"1862        )18631864    def test_should_strip_auth_http_downgrade(self):1865        s = requests.Session()1866        assert s.should_strip_auth("https://example.com/foo", "http://example.com/bar")18671868    def test_should_strip_auth_https_upgrade(self):1869        s = requests.Session()1870        assert not s.should_strip_auth(1871            "http://example.com/foo", "https://example.com/bar"1872        )1873        assert not s.should_strip_auth(1874            "http://example.com:80/foo", "https://example.com/bar"1875        )1876        assert not s.should_strip_auth(1877            "http://example.com/foo", "https://example.com:443/bar"1878        )1879        # Non-standard ports should trigger stripping1880        assert s.should_strip_auth(1881            "http://example.com:8080/foo", "https://example.com/bar"1882        )1883        assert s.should_strip_auth(1884            "http://example.com/foo", "https://example.com:8443/bar"1885        )18861887    def test_should_strip_auth_port_change(self):1888        s = requests.Session()1889        assert s.should_strip_auth(1890            "http://example.com:1234/foo", "https://example.com:4321/bar"1891        )18921893    @pytest.mark.parametrize(1894        "old_uri, new_uri",1895        (1896            ("https://example.com:443/foo", "https://example.com/bar"),1897            ("http://example.com:80/foo", "http://example.com/bar"),1898            ("https://example.com/foo", "https://example.com:443/bar"),1899            ("http://example.com/foo", "http://example.com:80/bar"),1900        ),1901    )1902    def test_should_strip_auth_default_port(self, old_uri, new_uri):1903        s = requests.Session()1904        assert not s.should_strip_auth(old_uri, new_uri)19051906    def test_manual_redirect_with_partial_body_read(self, httpbin):1907        s = requests.Session()1908        r1 = s.get(httpbin("redirect/2"), allow_redirects=False, stream=True)1909        assert r1.is_redirect1910        rg = s.resolve_redirects(r1, r1.request, stream=True)19111912        # read only the first eight bytes of the response body,1913        # then follow the redirect1914        r1.iter_content(8)1915        r2 = next(rg)1916        assert r2.is_redirect19171918        # read all of the response via iter_content,1919        # then follow the redirect1920        for _ in r2.iter_content():1921            pass1922        r3 = next(rg)1923        assert not r3.is_redirect19241925    def test_prepare_body_position_non_stream(self):1926        data = b"the data"1927        prep = requests.Request("GET", "http://example.com", data=data).prepare()1928        assert prep._body_position is None19291930    def test_rewind_body(self):1931        data = io.BytesIO(b"the data")1932        prep = requests.Request("GET", "http://example.com", data=data).prepare()1933        assert prep._body_position == 01934        assert prep.body.read() == b"the data"19351936        # the data has all been read1937        assert prep.body.read() == b""19381939        # rewind it back1940        requests.utils.rewind_body(prep)1941        assert prep.body.read() == b"the data"19421943    def test_rewind_partially_read_body(self):1944        data = io.BytesIO(b"the data")1945        data.read(4)  # read some data1946        prep = requests.Request("GET", "http://example.com", data=data).prepare()1947        assert prep._body_position == 41948        assert prep.body.read() == b"data"19491950        # the data has all been read1951        assert prep.body.read() == b""19521953        # rewind it back1954        requests.utils.rewind_body(prep)1955        assert prep.body.read() == b"data"19561957    def test_rewind_body_no_seek(self):1958        class BadFileObj:1959            def __init__(self, data):1960                self.data = data19611962            def tell(self):1963                return 019641965            def __iter__(self):1966                return19671968        data = BadFileObj("the data")1969        prep = requests.Request("GET", "http://example.com", data=data).prepare()1970        assert prep._body_position == 019711972        with pytest.raises(UnrewindableBodyError) as e:1973            requests.utils.rewind_body(prep)19741975        assert "Unable to rewind request body" in str(e)19761977    def test_rewind_body_failed_seek(self):1978        class BadFileObj:1979            def __init__(self, data):1980                self.data = data19811982            def tell(self):1983                return 019841985            def seek(self, pos, whence=0):1986                raise OSError()19871988            def __iter__(self):1989                return19901991        data = BadFileObj("the data")1992        prep = requests.Request("GET", "http://example.com", data=data).prepare()1993        assert prep._body_position == 019941995        with pytest.raises(UnrewindableBodyError) as e:1996            requests.utils.rewind_body(prep)19971998        assert "error occurred when rewinding request body" in str(e)19992000    def test_rewind_body_failed_tell(self):

The first 2,000 of 2,839 lines.