test_requests.py
This file
Path
tests/test_requests.py
2,983 lines · 102.1 KiB · Python
Last changed by
Add conditional string encoding based on urllib3 major versionNate Prewittbefore adoption4e38364
History of this fileTake it
1"""Tests for Requests."""23import collections4import contextlib5import io6import json7import os8import pickle9import re10import threading11import warnings12from unittest import mock1314import pytest15import urllib316from urllib3.util import Timeout as Urllib3Timeout1718import requests19from requests.adapters import HTTPAdapter20from requests.auth import HTTPDigestAuth, _basic_auth_str21from requests.compat import (22 JSONDecodeError,23 Morsel,24 MutableMapping,25 builtin_str,26 cookielib,27 getproxies,28 is_urllib3_2,29 urlparse,30)31from requests.cookies import cookiejar_from_dict, morsel_to_cookie32from requests.exceptions import (33 ChunkedEncodingError,34 ConnectionError,35 ConnectTimeout,36 ContentDecodingError,37 InvalidHeader,38 InvalidProxyURL,39 InvalidSchema,40 InvalidURL,41 MissingSchema,42 ProxyError,43 ReadTimeout,44 RequestException,45 RetryError,46)47from requests.exceptions import SSLError as RequestsSSLError48from requests.exceptions import Timeout, TooManyRedirects, UnrewindableBodyError49from requests.hooks import default_hooks50from requests.models import PreparedRequest, urlencode51from requests.sessions import SessionRedirectMixin52from requests.structures import CaseInsensitiveDict5354from . import SNIMissingWarning55from .compat import StringIO56from .testserver.server import TLSServer, consume_socket_content57from .utils import override_environ5859# Requests to this URL should always fail with a connection timeout (nothing60# listening on that port)61TARPIT = "http://10.255.255.1"6263# This is to avoid waiting the timeout of using TARPIT64INVALID_PROXY = "http://localhost:1"6566try:67 from ssl import SSLContext6869 del SSLContext70 HAS_MODERN_SSL = True71except ImportError:72 HAS_MODERN_SSL = False7374try:75 requests.pyopenssl76 HAS_PYOPENSSL = True77except AttributeError:78 HAS_PYOPENSSL = False798081class TestRequests:82 digest_auth_algo = ("MD5", "SHA-256", "SHA-512")8384 def test_entry_points(self):85 requests.session86 requests.session().get87 requests.session().head88 requests.get89 requests.head90 requests.put91 requests.patch92 requests.post93 # Not really an entry point, but people rely on it.94 from requests.packages.urllib3.poolmanager import PoolManager # noqa:F4019596 @pytest.mark.parametrize(97 "exception, url",98 (99 (MissingSchema, "hiwpefhipowhefopw"),100 (InvalidSchema, "localhost:3128"),101 (InvalidSchema, "localhost.localdomain:3128/"),102 (InvalidSchema, "10.122.1.1:3128/"),103 (InvalidURL, "http://"),104 (InvalidURL, "http://*example.com"),105 (InvalidURL, "http://.example.com"),106 ),107 )108 def test_invalid_url(self, exception, url):109 with pytest.raises(exception):110 requests.get(url)111112 def test_basic_building(self):113 req = requests.Request()114 req.url = "http://kennethreitz.org/"115 req.data = {"life": "42"}116117 pr = req.prepare()118 assert pr.url == req.url119 assert pr.body == "life=42"120121 @pytest.mark.parametrize("method", ("GET", "HEAD"))122 def test_no_content_length(self, httpbin, method):123 req = requests.Request(method, httpbin(method.lower())).prepare()124 assert "Content-Length" not in req.headers125126 @pytest.mark.parametrize("method", ("POST", "PUT", "PATCH", "OPTIONS"))127 def test_no_body_content_length(self, httpbin, method):128 req = requests.Request(method, httpbin(method.lower())).prepare()129 assert req.headers["Content-Length"] == "0"130131 @pytest.mark.parametrize("method", ("POST", "PUT", "PATCH", "OPTIONS"))132 def test_empty_content_length(self, httpbin, method):133 req = requests.Request(method, httpbin(method.lower()), data="").prepare()134 assert req.headers["Content-Length"] == "0"135136 def test_override_content_length(self, httpbin):137 headers = {"Content-Length": "not zero"}138 r = requests.Request("POST", httpbin("post"), headers=headers).prepare()139 assert "Content-Length" in r.headers140 assert r.headers["Content-Length"] == "not zero"141142 def test_path_is_not_double_encoded(self):143 request = requests.Request("GET", "http://0.0.0.0/get/test case").prepare()144145 assert request.path_url == "/get/test%20case"146147 @pytest.mark.parametrize(148 "url, expected",149 (150 (151 "http://example.com/path#fragment",152 "http://example.com/path?a=b#fragment",153 ),154 (155 "http://example.com/path?key=value#fragment",156 "http://example.com/path?key=value&a=b#fragment",157 ),158 ),159 )160 def test_params_are_added_before_fragment(self, url, expected):161 request = requests.Request("GET", url, params={"a": "b"}).prepare()162 assert request.url == expected163164 def test_params_original_order_is_preserved_by_default(self):165 param_ordered_dict = collections.OrderedDict(166 (("z", 1), ("a", 1), ("k", 1), ("d", 1))167 )168 session = requests.Session()169 request = requests.Request(170 "GET", "http://example.com/", params=param_ordered_dict171 )172 prep = session.prepare_request(request)173 assert prep.url == "http://example.com/?z=1&a=1&k=1&d=1"174175 def test_params_bytes_are_encoded(self):176 request = requests.Request(177 "GET", "http://example.com", params=b"test=foo"178 ).prepare()179 assert request.url == "http://example.com/?test=foo"180181 def test_binary_put(self):182 request = requests.Request(183 "PUT", "http://example.com", data="ööö".encode()184 ).prepare()185 assert isinstance(request.body, bytes)186187 def test_whitespaces_are_removed_from_url(self):188 # Test for issue #3696189 request = requests.Request("GET", " http://example.com").prepare()190 assert request.url == "http://example.com/"191192 @pytest.mark.parametrize("scheme", ("http://", "HTTP://", "hTTp://", "HttP://"))193 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):194 s = requests.Session()195 s.proxies = getproxies()196 parts = urlparse(httpbin("get"))197 url = scheme + parts.netloc + parts.path198 r = requests.Request("GET", url)199 r = s.send(r.prepare())200 assert r.status_code == 200, f"failed for scheme {scheme}"201202 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):203 r = requests.Request("GET", httpbin("get"))204 s = requests.Session()205 s.proxies = getproxies()206207 r = s.send(r.prepare())208209 assert r.status_code == 200210211 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):212 r = requests.get(httpbin("redirect", "1"))213 assert r.status_code == 200214 assert r.history[0].status_code == 302215 assert r.history[0].is_redirect216217 def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):218 r = requests.post(219 httpbin("redirect-to"),220 data="test",221 params={"url": "post", "status_code": 307},222 )223 assert r.status_code == 200224 assert r.history[0].status_code == 307225 assert r.history[0].is_redirect226 assert r.json()["data"] == "test"227228 def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):229 byte_str = b"test"230 r = requests.post(231 httpbin("redirect-to"),232 data=io.BytesIO(byte_str),233 params={"url": "post", "status_code": 307},234 )235 assert r.status_code == 200236 assert r.history[0].status_code == 307237 assert r.history[0].is_redirect238 assert r.json()["data"] == byte_str.decode("utf-8")239240 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):241 try:242 requests.get(httpbin("relative-redirect", "50"))243 except TooManyRedirects as e:244 url = httpbin("relative-redirect", "20")245 assert e.request.url == url246 assert e.response.url == url247 assert len(e.response.history) == 30248 else:249 pytest.fail("Expected redirect to raise TooManyRedirects but it did not")250251 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):252 s = requests.session()253 s.max_redirects = 5254 try:255 s.get(httpbin("relative-redirect", "50"))256 except TooManyRedirects as e:257 url = httpbin("relative-redirect", "45")258 assert e.request.url == url259 assert e.response.url == url260 assert len(e.response.history) == 5261 else:262 pytest.fail(263 "Expected custom max number of redirects to be respected but was not"264 )265266 def test_http_301_changes_post_to_get(self, httpbin):267 r = requests.post(httpbin("status", "301"))268 assert r.status_code == 200269 assert r.request.method == "GET"270 assert r.history[0].status_code == 301271 assert r.history[0].is_redirect272273 def test_http_301_doesnt_change_head_to_get(self, httpbin):274 r = requests.head(httpbin("status", "301"), allow_redirects=True)275 print(r.content)276 assert r.status_code == 200277 assert r.request.method == "HEAD"278 assert r.history[0].status_code == 301279 assert r.history[0].is_redirect280281 def test_http_302_changes_post_to_get(self, httpbin):282 r = requests.post(httpbin("status", "302"))283 assert r.status_code == 200284 assert r.request.method == "GET"285 assert r.history[0].status_code == 302286 assert r.history[0].is_redirect287288 def test_http_302_doesnt_change_head_to_get(self, httpbin):289 r = requests.head(httpbin("status", "302"), allow_redirects=True)290 assert r.status_code == 200291 assert r.request.method == "HEAD"292 assert r.history[0].status_code == 302293 assert r.history[0].is_redirect294295 def test_http_303_changes_post_to_get(self, httpbin):296 r = requests.post(httpbin("status", "303"))297 assert r.status_code == 200298 assert r.request.method == "GET"299 assert r.history[0].status_code == 303300 assert r.history[0].is_redirect301302 def test_http_303_doesnt_change_head_to_get(self, httpbin):303 r = requests.head(httpbin("status", "303"), allow_redirects=True)304 assert r.status_code == 200305 assert r.request.method == "HEAD"306 assert r.history[0].status_code == 303307 assert r.history[0].is_redirect308309 def test_header_and_body_removal_on_redirect(self, httpbin):310 purged_headers = ("Content-Length", "Content-Type")311 ses = requests.Session()312 req = requests.Request("POST", httpbin("post"), data={"test": "data"})313 prep = ses.prepare_request(req)314 resp = ses.send(prep)315316 # Mimic a redirect response317 resp.status_code = 302318 resp.headers["location"] = "get"319320 # Run request through resolve_redirects321 next_resp = next(ses.resolve_redirects(resp, prep))322 assert next_resp.request.body is None323 for header in purged_headers:324 assert header not in next_resp.request.headers325326 def test_transfer_enc_removal_on_redirect(self, httpbin):327 purged_headers = ("Transfer-Encoding", "Content-Type")328 ses = requests.Session()329 req = requests.Request("POST", httpbin("post"), data=(b"x" for x in range(1)))330 prep = ses.prepare_request(req)331 assert "Transfer-Encoding" in prep.headers332333 # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33334 resp = requests.Response()335 resp.raw = io.BytesIO(b"the content")336 resp.request = prep337 setattr(resp.raw, "release_conn", lambda *args: args)338339 # Mimic a redirect response340 resp.status_code = 302341 resp.headers["location"] = httpbin("get")342343 # Run request through resolve_redirect344 next_resp = next(ses.resolve_redirects(resp, prep))345 assert next_resp.request.body is None346 for header in purged_headers:347 assert header not in next_resp.request.headers348349 def test_fragment_maintained_on_redirect(self, httpbin):350 fragment = "#view=edit&token=hunter2"351 r = requests.get(httpbin("redirect-to?url=get") + fragment)352353 assert len(r.history) > 0354 assert r.history[0].request.url == httpbin("redirect-to?url=get") + fragment355 assert r.url == httpbin("get") + fragment356357 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):358 heads = {"User-agent": "Mozilla/5.0"}359360 r = requests.get(httpbin("user-agent"), headers=heads)361362 assert heads["User-agent"] in r.text363 assert r.status_code == 200364365 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):366 heads = {"User-agent": "Mozilla/5.0"}367368 r = requests.get(369 httpbin("get") + "?test=true", params={"q": "test"}, headers=heads370 )371 assert r.status_code == 200372373 def test_set_cookie_on_301(self, httpbin):374 s = requests.session()375 url = httpbin("cookies/set?foo=bar")376 s.get(url)377 assert s.cookies["foo"] == "bar"378379 def test_cookie_sent_on_redirect(self, httpbin):380 s = requests.session()381 s.get(httpbin("cookies/set?foo=bar"))382 r = s.get(httpbin("redirect/1")) # redirects to httpbin('get')383 assert "Cookie" in r.json()["headers"]384385 def test_cookie_removed_on_expire(self, httpbin):386 s = requests.session()387 s.get(httpbin("cookies/set?foo=bar"))388 assert s.cookies["foo"] == "bar"389 s.get(390 httpbin("response-headers"),391 params={"Set-Cookie": "foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT"},392 )393 assert "foo" not in s.cookies394395 def test_cookie_quote_wrapped(self, httpbin):396 s = requests.session()397 s.get(httpbin('cookies/set?foo="bar:baz"'))398 assert s.cookies["foo"] == '"bar:baz"'399400 def test_cookie_persists_via_api(self, httpbin):401 s = requests.session()402 r = s.get(httpbin("redirect/1"), cookies={"foo": "bar"})403 assert "foo" in r.request.headers["Cookie"]404 assert "foo" in r.history[0].request.headers["Cookie"]405406 def test_request_cookie_overrides_session_cookie(self, httpbin):407 s = requests.session()408 s.cookies["foo"] = "bar"409 r = s.get(httpbin("cookies"), cookies={"foo": "baz"})410 assert r.json()["cookies"]["foo"] == "baz"411 # Session cookie should not be modified412 assert s.cookies["foo"] == "bar"413414 def test_request_cookies_not_persisted(self, httpbin):415 s = requests.session()416 s.get(httpbin("cookies"), cookies={"foo": "baz"})417 # Sending a request with cookies should not add cookies to the session418 assert not s.cookies419420 def test_generic_cookiejar_works(self, httpbin):421 cj = cookielib.CookieJar()422 cookiejar_from_dict({"foo": "bar"}, cj)423 s = requests.session()424 s.cookies = cj425 r = s.get(httpbin("cookies"))426 # Make sure the cookie was sent427 assert r.json()["cookies"]["foo"] == "bar"428 # Make sure the session cj is still the custom one429 assert s.cookies is cj430431 def test_param_cookiejar_works(self, httpbin):432 cj = cookielib.CookieJar()433 cookiejar_from_dict({"foo": "bar"}, cj)434 s = requests.session()435 r = s.get(httpbin("cookies"), cookies=cj)436 # Make sure the cookie was sent437 assert r.json()["cookies"]["foo"] == "bar"438439 def test_cookielib_cookiejar_on_redirect(self, httpbin):440 """Tests resolve_redirect doesn't fail when merging cookies441 with non-RequestsCookieJar cookiejar.442443 See GH #3579444 """445 cj = cookiejar_from_dict({"foo": "bar"}, cookielib.CookieJar())446 s = requests.Session()447 s.cookies = cookiejar_from_dict({"cookie": "tasty"})448449 # Prepare request without using Session450 req = requests.Request("GET", httpbin("headers"), cookies=cj)451 prep_req = req.prepare()452453 # Send request and simulate redirect454 resp = s.send(prep_req)455 resp.status_code = 302456 resp.headers["location"] = httpbin("get")457 redirects = s.resolve_redirects(resp, prep_req)458 resp = next(redirects)459460 # Verify CookieJar isn't being converted to RequestsCookieJar461 assert isinstance(prep_req._cookies, cookielib.CookieJar)462 assert isinstance(resp.request._cookies, cookielib.CookieJar)463 assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)464465 cookies = {}466 for c in resp.request._cookies:467 cookies[c.name] = c.value468 assert cookies["foo"] == "bar"469 assert cookies["cookie"] == "tasty"470471 def test_requests_in_history_are_not_overridden(self, httpbin):472 resp = requests.get(httpbin("redirect/3"))473 urls = [r.url for r in resp.history]474 req_urls = [r.request.url for r in resp.history]475 assert urls == req_urls476477 def test_history_is_always_a_list(self, httpbin):478 """Show that even with redirects, Response.history is always a list."""479 resp = requests.get(httpbin("get"))480 assert isinstance(resp.history, list)481 resp = requests.get(httpbin("redirect/1"))482 assert isinstance(resp.history, list)483 assert not isinstance(resp.history, tuple)484485 def test_headers_on_session_with_None_are_not_sent(self, httpbin):486 """Do not send headers in Session.headers with None values."""487 ses = requests.Session()488 ses.headers["Accept-Encoding"] = None489 req = requests.Request("GET", httpbin("get"))490 prep = ses.prepare_request(req)491 assert "Accept-Encoding" not in prep.headers492493 def test_headers_preserve_order(self, httpbin):494 """Preserve order when headers provided as OrderedDict."""495 ses = requests.Session()496 ses.headers = collections.OrderedDict()497 ses.headers["Accept-Encoding"] = "identity"498 ses.headers["First"] = "1"499 ses.headers["Second"] = "2"500 headers = collections.OrderedDict([("Third", "3"), ("Fourth", "4")])501 headers["Fifth"] = "5"502 headers["Second"] = "222"503 req = requests.Request("GET", httpbin("get"), headers=headers)504 prep = ses.prepare_request(req)505 items = list(prep.headers.items())506 assert items[0] == ("Accept-Encoding", "identity")507 assert items[1] == ("First", "1")508 assert items[2] == ("Second", "222")509 assert items[3] == ("Third", "3")510 assert items[4] == ("Fourth", "4")511 assert items[5] == ("Fifth", "5")512513 @pytest.mark.parametrize("key", ("User-agent", "user-agent"))514 def test_user_agent_transfers(self, httpbin, key):515 heads = {key: "Mozilla/5.0 (github.com/psf/requests)"}516517 r = requests.get(httpbin("user-agent"), headers=heads)518 assert heads[key] in r.text519520 def test_HTTP_200_OK_HEAD(self, httpbin):521 r = requests.head(httpbin("get"))522 assert r.status_code == 200523524 def test_HTTP_200_OK_PUT(self, httpbin):525 r = requests.put(httpbin("put"))526 assert r.status_code == 200527528 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):529 auth = ("user", "pass")530 url = httpbin("basic-auth", "user", "pass")531532 r = requests.get(url, auth=auth)533 assert r.status_code == 200534535 r = requests.get(url)536 assert r.status_code == 401537538 s = requests.session()539 s.auth = auth540 r = s.get(url)541 assert r.status_code == 200542543 @pytest.mark.parametrize(544 "username, password",545 (546 ("user", "pass"),547 ("имя".encode(), "пароль".encode()),548 (42, 42),549 (None, None),550 ),551 )552 def test_set_basicauth(self, httpbin, username, password):553 auth = (username, password)554 url = httpbin("get")555556 r = requests.Request("GET", url, auth=auth)557 p = r.prepare()558559 assert p.headers["Authorization"] == _basic_auth_str(username, password)560561 def test_basicauth_encodes_byte_strings(self):562 """Ensure b'test' formats as the byte string "test" rather563 than the unicode string "b'test'" in Python 3.564 """565 auth = (b"\xc5\xafsername", b"test\xc6\xb6")566 r = requests.Request("GET", "http://localhost", auth=auth)567 p = r.prepare()568569 assert p.headers["Authorization"] == "Basic xa9zZXJuYW1lOnRlc3TGtg=="570571 @pytest.mark.parametrize(572 "url, exception",573 (574 # Connecting to an unknown domain should raise a ConnectionError575 ("http://doesnotexist.google.com", ConnectionError),576 # Connecting to an invalid port should raise a ConnectionError577 ("http://localhost:1", ConnectionError),578 # Inputing a URL that cannot be parsed should raise an InvalidURL error579 ("http://fe80::5054:ff:fe5a:fc0", InvalidURL),580 ),581 )582 def test_errors(self, url, exception):583 with pytest.raises(exception):584 requests.get(url, timeout=1)585586 def test_proxy_error(self):587 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError588 with pytest.raises(ProxyError):589 requests.get(590 "http://localhost:1", proxies={"http": "non-resolvable-address"}591 )592593 def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):594 with pytest.raises(InvalidProxyURL):595 requests.get(httpbin_secure(), proxies={"https": "http:/badproxyurl:3128"})596597 with pytest.raises(InvalidProxyURL):598 requests.get(httpbin(), proxies={"http": "http://:8080"})599600 with pytest.raises(InvalidProxyURL):601 requests.get(httpbin_secure(), proxies={"https": "https://"})602603 with pytest.raises(InvalidProxyURL):604 requests.get(httpbin(), proxies={"http": "http:///example.com:8080"})605606 def test_respect_proxy_env_on_send_self_prepared_request(self, httpbin):607 with override_environ(http_proxy=INVALID_PROXY):608 with pytest.raises(ProxyError):609 session = requests.Session()610 request = requests.Request("GET", httpbin())611 session.send(request.prepare())612613 def test_respect_proxy_env_on_send_session_prepared_request(self, httpbin):614 with override_environ(http_proxy=INVALID_PROXY):615 with pytest.raises(ProxyError):616 session = requests.Session()617 request = requests.Request("GET", httpbin())618 prepared = session.prepare_request(request)619 session.send(prepared)620621 def test_respect_proxy_env_on_send_with_redirects(self, httpbin):622 with override_environ(http_proxy=INVALID_PROXY):623 with pytest.raises(ProxyError):624 session = requests.Session()625 url = httpbin("redirect/1")626 print(url)627 request = requests.Request("GET", url)628 session.send(request.prepare())629630 def test_respect_proxy_env_on_get(self, httpbin):631 with override_environ(http_proxy=INVALID_PROXY):632 with pytest.raises(ProxyError):633 session = requests.Session()634 session.get(httpbin())635636 def test_respect_proxy_env_on_request(self, httpbin):637 with override_environ(http_proxy=INVALID_PROXY):638 with pytest.raises(ProxyError):639 session = requests.Session()640 session.request(method="GET", url=httpbin())641642 def test_proxy_authorization_preserved_on_request(self, httpbin):643 proxy_auth_value = "Bearer XXX"644 session = requests.Session()645 session.headers.update({"Proxy-Authorization": proxy_auth_value})646 resp = session.request(method="GET", url=httpbin("get"))647 sent_headers = resp.json().get("headers", {})648649 assert sent_headers.get("Proxy-Authorization") == proxy_auth_value650651 @pytest.mark.parametrize(652 "url,has_proxy_auth",653 (654 ("http://example.com", True),655 ("https://example.com", False),656 ),657 )658 def test_proxy_authorization_not_appended_to_https_request(659 self, url, has_proxy_auth660 ):661 session = requests.Session()662 proxies = {663 "http": "http://test:pass@localhost:8080",664 "https": "http://test:pass@localhost:8090",665 }666 req = requests.Request("GET", url)667 prep = req.prepare()668 session.rebuild_proxies(prep, proxies)669670 assert ("Proxy-Authorization" in prep.headers) is has_proxy_auth671672 def test_basicauth_with_netrc(self, httpbin):673 auth = ("user", "pass")674 wrong_auth = ("wronguser", "wrongpass")675 url = httpbin("basic-auth", "user", "pass")676677 old_auth = requests.sessions.get_netrc_auth678679 try:680681 def get_netrc_auth_mock(url):682 return auth683684 requests.sessions.get_netrc_auth = get_netrc_auth_mock685686 # Should use netrc and work.687 r = requests.get(url)688 assert r.status_code == 200689690 # Given auth should override and fail.691 r = requests.get(url, auth=wrong_auth)692 assert r.status_code == 401693694 s = requests.session()695696 # Should use netrc and work.697 r = s.get(url)698 assert r.status_code == 200699700 # Given auth should override and fail.701 s.auth = wrong_auth702 r = s.get(url)703 assert r.status_code == 401704 finally:705 requests.sessions.get_netrc_auth = old_auth706707 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):708 for authtype in self.digest_auth_algo:709 auth = HTTPDigestAuth("user", "pass")710 url = httpbin("digest-auth", "auth", "user", "pass", authtype, "never")711712 r = requests.get(url, auth=auth)713 assert r.status_code == 200714715 r = requests.get(url)716 assert r.status_code == 401717 print(r.headers["WWW-Authenticate"])718719 s = requests.session()720 s.auth = HTTPDigestAuth("user", "pass")721 r = s.get(url)722 assert r.status_code == 200723724 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):725 for authtype in self.digest_auth_algo:726 url = httpbin("digest-auth", "auth", "user", "pass", authtype)727 auth = HTTPDigestAuth("user", "pass")728 r = requests.get(url)729 assert r.cookies["fake"] == "fake_value"730731 r = requests.get(url, auth=auth)732 assert r.status_code == 200733734 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):735 for authtype in self.digest_auth_algo:736 url = httpbin("digest-auth", "auth", "user", "pass", authtype)737 auth = HTTPDigestAuth("user", "pass")738 s = requests.Session()739 s.get(url, auth=auth)740 assert s.cookies["fake"] == "fake_value"741742 def test_DIGEST_STREAM(self, httpbin):743 for authtype in self.digest_auth_algo:744 auth = HTTPDigestAuth("user", "pass")745 url = httpbin("digest-auth", "auth", "user", "pass", authtype)746747 r = requests.get(url, auth=auth, stream=True)748 assert r.raw.read() != b""749750 r = requests.get(url, auth=auth, stream=False)751 assert r.raw.read() == b""752753 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):754 for authtype in self.digest_auth_algo:755 auth = HTTPDigestAuth("user", "wrongpass")756 url = httpbin("digest-auth", "auth", "user", "pass", authtype)757758 r = requests.get(url, auth=auth)759 assert r.status_code == 401760761 r = requests.get(url)762 assert r.status_code == 401763764 s = requests.session()765 s.auth = auth766 r = s.get(url)767 assert r.status_code == 401768769 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):770 for authtype in self.digest_auth_algo:771 auth = HTTPDigestAuth("user", "pass")772 url = httpbin("digest-auth", "auth", "user", "pass", authtype)773774 r = requests.get(url, auth=auth)775 assert '"auth"' in r.request.headers["Authorization"]776777 def test_POSTBIN_GET_POST_FILES(self, httpbin):778 url = httpbin("post")779 requests.post(url).raise_for_status()780781 post1 = requests.post(url, data={"some": "data"})782 assert post1.status_code == 200783784 with open("requirements-dev.txt") as f:785 post2 = requests.post(url, files={"some": f})786 assert post2.status_code == 200787788 post4 = requests.post(url, data='[{"some": "json"}]')789 assert post4.status_code == 200790791 with pytest.raises(ValueError):792 requests.post(url, files=["bad file data"])793794 def test_invalid_files_input(self, httpbin):795 url = httpbin("post")796 post = requests.post(url, files={"random-file-1": None, "random-file-2": 1})797 assert b'name="random-file-1"' not in post.request.body798 assert b'name="random-file-2"' in post.request.body799800 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):801 class TestStream:802 def __init__(self, data):803 self.data = data.encode()804 self.length = len(self.data)805 self.index = 0806807 def __len__(self):808 return self.length809810 def read(self, size=None):811 if size:812 ret = self.data[self.index : self.index + size]813 self.index += size814 else:815 ret = self.data[self.index :]816 self.index = self.length817 return ret818819 def tell(self):820 return self.index821822 def seek(self, offset, where=0):823 if where == 0:824 self.index = offset825 elif where == 1:826 self.index += offset827 elif where == 2:828 self.index = self.length + offset829830 test = TestStream("test")831 post1 = requests.post(httpbin("post"), data=test)832 assert post1.status_code == 200833 assert post1.json()["data"] == "test"834835 test = TestStream("test")836 test.seek(2)837 post2 = requests.post(httpbin("post"), data=test)838 assert post2.status_code == 200839 assert post2.json()["data"] == "st"840841 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):842 url = httpbin("post")843 requests.post(url).raise_for_status()844845 post1 = requests.post(url, data={"some": "data"})846 assert post1.status_code == 200847848 with open("requirements-dev.txt") as f:849 post2 = requests.post(url, data={"some": "data"}, files={"some": f})850 assert post2.status_code == 200851852 post4 = requests.post(url, data='[{"some": "json"}]')853 assert post4.status_code == 200854855 with pytest.raises(ValueError):856 requests.post(url, files=["bad file data"])857858 def test_post_with_custom_mapping(self, httpbin):859 class CustomMapping(MutableMapping):860 def __init__(self, *args, **kwargs):861 self.data = dict(*args, **kwargs)862863 def __delitem__(self, key):864 del self.data[key]865866 def __getitem__(self, key):867 return self.data[key]868869 def __setitem__(self, key, value):870 self.data[key] = value871872 def __iter__(self):873 return iter(self.data)874875 def __len__(self):876 return len(self.data)877878 data = CustomMapping({"some": "data"})879 url = httpbin("post")880 found_json = requests.post(url, data=data).json().get("form")881 assert found_json == {"some": "data"}882883 def test_conflicting_post_params(self, httpbin):884 url = httpbin("post")885 with open("requirements-dev.txt") as f:886 with pytest.raises(ValueError):887 requests.post(url, data='[{"some": "data"}]', files={"some": f})888889 def test_request_ok_set(self, httpbin):890 r = requests.get(httpbin("status", "404"))891 assert not r.ok892893 def test_status_raising(self, httpbin):894 r = requests.get(httpbin("status", "404"))895 with pytest.raises(requests.exceptions.HTTPError):896 r.raise_for_status()897898 r = requests.get(httpbin("status", "500"))899 assert not r.ok900901 def test_decompress_gzip(self, httpbin):902 r = requests.get(httpbin("gzip"))903 r.content.decode("ascii")904905 @pytest.mark.parametrize(906 "url, params",907 (908 ("/get", {"foo": "føø"}),909 ("/get", {"føø": "føø"}),910 ("/get", {"føø": "føø"}),911 ("/get", {"foo": "foo"}),912 ("ø", {"foo": "foo"}),913 ),914 )915 def test_unicode_get(self, httpbin, url, params):916 requests.get(httpbin(url), params=params)917918 def test_unicode_header_name(self, httpbin):919 requests.put(920 httpbin("put"),921 headers={"Content-Type": "application/octet-stream"},922 data="\xff",923 ) # compat.str is unicode.924925 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):926 requests.get(httpbin_secure("status", "301"), verify=httpbin_ca_bundle)927928 def test_invalid_ca_certificate_path(self, httpbin_secure):929 INVALID_PATH = "/garbage"930 with pytest.raises(IOError) as e:931 requests.get(httpbin_secure(), verify=INVALID_PATH)932 assert str(933 e.value934 ) == "Could not find a suitable TLS CA certificate bundle, invalid path: {}".format(935 INVALID_PATH936 )937938 def test_invalid_ssl_certificate_files(self, httpbin_secure):939 INVALID_PATH = "/garbage"940 with pytest.raises(IOError) as e:941 requests.get(httpbin_secure(), cert=INVALID_PATH)942 assert str(943 e.value944 ) == "Could not find the TLS certificate file, invalid path: {}".format(945 INVALID_PATH946 )947948 with pytest.raises(IOError) as e:949 requests.get(httpbin_secure(), cert=(".", INVALID_PATH))950 assert str(e.value) == (951 f"Could not find the TLS key file, invalid path: {INVALID_PATH}"952 )953954 @pytest.mark.parametrize(955 "env, expected",956 (957 ({}, True),958 ({"REQUESTS_CA_BUNDLE": "/some/path"}, "/some/path"),959 ({"REQUESTS_CA_BUNDLE": ""}, True),960 ({"CURL_CA_BUNDLE": "/some/path"}, "/some/path"),961 ({"CURL_CA_BUNDLE": ""}, True),962 ({"REQUESTS_CA_BUNDLE": "", "CURL_CA_BUNDLE": ""}, True),963 (964 {965 "REQUESTS_CA_BUNDLE": "/some/path",966 "CURL_CA_BUNDLE": "/curl/path",967 },968 "/some/path",969 ),970 (971 {972 "REQUESTS_CA_BUNDLE": "",973 "CURL_CA_BUNDLE": "/curl/path",974 },975 "/curl/path",976 ),977 ),978 )979 def test_env_cert_bundles(self, httpbin, env, expected):980 s = requests.Session()981 with mock.patch("os.environ", env):982 settings = s.merge_environment_settings(983 url=httpbin("get"), proxies={}, stream=False, verify=True, cert=None984 )985 assert settings["verify"] == expected986987 def test_http_with_certificate(self, httpbin):988 r = requests.get(httpbin(), cert=".")989 assert r.status_code == 200990991 @pytest.mark.skipif(992 SNIMissingWarning is None,993 reason="urllib3 2.0 removed that warning and errors out instead",994 )995 def test_https_warnings(self, nosan_server):996 """warnings are emitted with requests.get"""997 host, port, ca_bundle = nosan_server998 if HAS_MODERN_SSL or HAS_PYOPENSSL:999 warnings_expected = ("SubjectAltNameWarning",)1000 else:1001 warnings_expected = (1002 "SNIMissingWarning",1003 "InsecurePlatformWarning",1004 "SubjectAltNameWarning",1005 )10061007 with pytest.warns() as warning_records:1008 warnings.simplefilter("always")1009 requests.get(f"https://localhost:{port}/", verify=ca_bundle)10101011 warning_records = [1012 item1013 for item in warning_records1014 if item.category.__name__ != "ResourceWarning"1015 ]10161017 warnings_category = tuple(item.category.__name__ for item in warning_records)1018 assert warnings_category == warnings_expected10191020 def test_certificate_failure(self, httpbin_secure):1021 """1022 When underlying SSL problems occur, an SSLError is raised.1023 """1024 with pytest.raises(RequestsSSLError):1025 # Our local httpbin does not have a trusted CA, so this call will1026 # fail if we use our default trust bundle.1027 requests.get(httpbin_secure("status", "200"))10281029 def test_urlencoded_get_query_multivalued_param(self, httpbin):1030 r = requests.get(httpbin("get"), params={"test": ["foo", "baz"]})1031 assert r.status_code == 2001032 assert r.url == httpbin("get?test=foo&test=baz")10331034 def test_form_encoded_post_query_multivalued_element(self, httpbin):1035 r = requests.Request(1036 method="POST", url=httpbin("post"), data=dict(test=["foo", "baz"])1037 )1038 prep = r.prepare()1039 assert prep.body == "test=foo&test=baz"10401041 def test_different_encodings_dont_break_post(self, httpbin):1042 with open(__file__, "rb") as f:1043 r = requests.post(1044 httpbin("post"),1045 data={"stuff": json.dumps({"a": 123})},1046 params={"blah": "asdf1234"},1047 files={"file": ("test_requests.py", f)},1048 )1049 assert r.status_code == 20010501051 @pytest.mark.parametrize(1052 "data",1053 (1054 {"stuff": "ëlïxr"},1055 {"stuff": "ëlïxr".encode()},1056 {"stuff": "elixr"},1057 {"stuff": b"elixr"},1058 ),1059 )1060 def test_unicode_multipart_post(self, httpbin, data):1061 with open(__file__, "rb") as f:1062 r = requests.post(1063 httpbin("post"),1064 data=data,1065 files={"file": ("test_requests.py", f)},1066 )1067 assert r.status_code == 20010681069 def test_unicode_multipart_post_fieldnames(self, httpbin):1070 filename = os.path.splitext(__file__)[0] + ".py"1071 with open(filename, "rb") as f:1072 r = requests.Request(1073 method="POST",1074 url=httpbin("post"),1075 data={b"stuff": "elixr"},1076 files={"file": ("test_requests.py", f)},1077 )1078 prep = r.prepare()10791080 assert b'name="stuff"' in prep.body1081 assert b"name=\"b'stuff'\"" not in prep.body10821083 def test_unicode_method_name(self, httpbin):1084 with open(__file__, "rb") as f:1085 files = {"file": f}1086 r = requests.request(1087 method="POST",1088 url=httpbin("post"),1089 files=files,1090 )1091 assert r.status_code == 20010921093 def test_unicode_method_name_with_request_object(self, httpbin):1094 s = requests.Session()1095 with open(__file__, "rb") as f:1096 files = {"file": f}1097 req = requests.Request("POST", httpbin("post"), files=files)1098 prep = s.prepare_request(req)1099 assert isinstance(prep.method, builtin_str)1100 assert prep.method == "POST"11011102 resp = s.send(prep)1103 assert resp.status_code == 20011041105 def test_non_prepared_request_error(self):1106 s = requests.Session()1107 req = requests.Request("POST", "/")11081109 with pytest.raises(ValueError) as e:1110 s.send(req)1111 assert str(e.value) == "You can only send PreparedRequests."11121113 def test_custom_content_type(self, httpbin):1114 with open(__file__, "rb") as f1:1115 with open(__file__, "rb") as f2:1116 data = {"stuff": json.dumps({"a": 123})}1117 files = {1118 "file1": ("test_requests.py", f1),1119 "file2": ("test_requests", f2, "text/py-content-type"),1120 }1121 r = requests.post(httpbin("post"), data=data, files=files)1122 assert r.status_code == 2001123 assert b"text/py-content-type" in r.request.body11241125 def test_hook_receives_request_arguments(self, httpbin):1126 def hook(resp, **kwargs):1127 assert resp is not None1128 assert kwargs != {}11291130 s = requests.Session()1131 r = requests.Request("GET", httpbin(), hooks={"response": hook})1132 prep = s.prepare_request(r)1133 s.send(prep)11341135 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):1136 def hook(*args, **kwargs):1137 pass11381139 s = requests.Session()1140 s.hooks["response"].append(hook)1141 r = requests.Request("GET", httpbin())1142 prep = s.prepare_request(r)1143 assert prep.hooks["response"] != []1144 assert prep.hooks["response"] == [hook]11451146 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):1147 def hook1(*args, **kwargs):1148 pass11491150 def hook2(*args, **kwargs):1151 pass11521153 assert hook1 is not hook21154 s = requests.Session()1155 s.hooks["response"].append(hook2)1156 r = requests.Request("GET", httpbin(), hooks={"response": [hook1]})1157 prep = s.prepare_request(r)1158 assert prep.hooks["response"] == [hook1]11591160 def test_prepared_request_hook(self, httpbin):1161 def hook(resp, **kwargs):1162 resp.hook_working = True1163 return resp11641165 req = requests.Request("GET", httpbin(), hooks={"response": hook})1166 prep = req.prepare()11671168 s = requests.Session()1169 s.proxies = getproxies()1170 resp = s.send(prep)11711172 assert hasattr(resp, "hook_working")11731174 def test_prepared_from_session(self, httpbin):1175 class DummyAuth(requests.auth.AuthBase):1176 def __call__(self, r):1177 r.headers["Dummy-Auth-Test"] = "dummy-auth-test-ok"1178 return r11791180 req = requests.Request("GET", httpbin("headers"))1181 assert not req.auth11821183 s = requests.Session()1184 s.auth = DummyAuth()11851186 prep = s.prepare_request(req)1187 resp = s.send(prep)11881189 assert resp.json()["headers"]["Dummy-Auth-Test"] == "dummy-auth-test-ok"11901191 def test_prepare_request_with_bytestring_url(self):1192 req = requests.Request("GET", b"https://httpbin.org/")1193 s = requests.Session()1194 prep = s.prepare_request(req)1195 assert prep.url == "https://httpbin.org/"11961197 def test_request_with_bytestring_host(self, httpbin):1198 s = requests.Session()1199 resp = s.request(1200 "GET",1201 httpbin("cookies/set?cookie=value"),1202 allow_redirects=False,1203 headers={"Host": b"httpbin.org"},1204 )1205 assert resp.cookies.get("cookie") == "value"12061207 def test_links(self):1208 r = requests.Response()1209 r.headers = {1210 "cache-control": "public, max-age=60, s-maxage=60",1211 "connection": "keep-alive",1212 "content-encoding": "gzip",1213 "content-type": "application/json; charset=utf-8",1214 "date": "Sat, 26 Jan 2013 16:47:56 GMT",1215 "etag": '"6ff6a73c0e446c1f61614769e3ceb778"',1216 "last-modified": "Sat, 26 Jan 2013 16:22:39 GMT",1217 "link": (1218 "<https://api.github.com/users/kennethreitz/repos?"1219 'page=2&per_page=10>; rel="next", <https://api.github.'1220 "com/users/kennethreitz/repos?page=7&per_page=10>; "1221 ' rel="last"'1222 ),1223 "server": "GitHub.com",1224 "status": "200 OK",1225 "vary": "Accept",1226 "x-content-type-options": "nosniff",1227 "x-github-media-type": "github.beta",1228 "x-ratelimit-limit": "60",1229 "x-ratelimit-remaining": "57",1230 }1231 assert r.links["next"]["rel"] == "next"12321233 def test_cookie_parameters(self):1234 key = "some_cookie"1235 value = "some_value"1236 secure = True1237 domain = "test.com"1238 rest = {"HttpOnly": True}12391240 jar = requests.cookies.RequestsCookieJar()1241 jar.set(key, value, secure=secure, domain=domain, rest=rest)12421243 assert len(jar) == 11244 assert "some_cookie" in jar12451246 cookie = list(jar)[0]1247 assert cookie.secure == secure1248 assert cookie.domain == domain1249 assert cookie._rest["HttpOnly"] == rest["HttpOnly"]12501251 def test_cookie_as_dict_keeps_len(self):1252 key = "some_cookie"1253 value = "some_value"12541255 key1 = "some_cookie1"1256 value1 = "some_value1"12571258 jar = requests.cookies.RequestsCookieJar()1259 jar.set(key, value)1260 jar.set(key1, value1)12611262 d1 = dict(jar)1263 d2 = dict(jar.iteritems())1264 d3 = dict(jar.items())12651266 assert len(jar) == 21267 assert len(d1) == 21268 assert len(d2) == 21269 assert len(d3) == 212701271 def test_cookie_as_dict_keeps_items(self):1272 key = "some_cookie"1273 value = "some_value"12741275 key1 = "some_cookie1"1276 value1 = "some_value1"12771278 jar = requests.cookies.RequestsCookieJar()1279 jar.set(key, value)1280 jar.set(key1, value1)12811282 d1 = dict(jar)1283 d2 = dict(jar.iteritems())1284 d3 = dict(jar.items())12851286 assert d1["some_cookie"] == "some_value"1287 assert d2["some_cookie"] == "some_value"1288 assert d3["some_cookie1"] == "some_value1"12891290 def test_cookie_as_dict_keys(self):1291 key = "some_cookie"1292 value = "some_value"12931294 key1 = "some_cookie1"1295 value1 = "some_value1"12961297 jar = requests.cookies.RequestsCookieJar()1298 jar.set(key, value)1299 jar.set(key1, value1)13001301 keys = jar.keys()1302 assert keys == list(keys)1303 # make sure one can use keys multiple times1304 assert list(keys) == list(keys)13051306 def test_cookie_as_dict_values(self):1307 key = "some_cookie"1308 value = "some_value"13091310 key1 = "some_cookie1"1311 value1 = "some_value1"13121313 jar = requests.cookies.RequestsCookieJar()1314 jar.set(key, value)1315 jar.set(key1, value1)13161317 values = jar.values()1318 assert values == list(values)1319 # make sure one can use values multiple times1320 assert list(values) == list(values)13211322 def test_cookie_as_dict_items(self):1323 key = "some_cookie"1324 value = "some_value"13251326 key1 = "some_cookie1"1327 value1 = "some_value1"13281329 jar = requests.cookies.RequestsCookieJar()1330 jar.set(key, value)1331 jar.set(key1, value1)13321333 items = jar.items()1334 assert items == list(items)1335 # make sure one can use items multiple times1336 assert list(items) == list(items)13371338 def test_cookie_duplicate_names_different_domains(self):1339 key = "some_cookie"1340 value = "some_value"1341 domain1 = "test1.com"1342 domain2 = "test2.com"13431344 jar = requests.cookies.RequestsCookieJar()1345 jar.set(key, value, domain=domain1)1346 jar.set(key, value, domain=domain2)1347 assert key in jar1348 items = jar.items()1349 assert len(items) == 213501351 # Verify that CookieConflictError is raised if domain is not specified1352 with pytest.raises(requests.cookies.CookieConflictError):1353 jar.get(key)13541355 # Verify that CookieConflictError is not raised if domain is specified1356 cookie = jar.get(key, domain=domain1)1357 assert cookie == value13581359 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1360 key = "some_cookie"1361 value = "some_value"1362 path = "some_path"13631364 jar = requests.cookies.RequestsCookieJar()1365 jar.set(key, value, path=path)1366 jar.set(key, value)1367 with pytest.raises(requests.cookies.CookieConflictError):1368 jar.get(key)13691370 def test_cookie_policy_copy(self):1371 class MyCookiePolicy(cookielib.DefaultCookiePolicy):1372 pass13731374 jar = requests.cookies.RequestsCookieJar()1375 jar.set_policy(MyCookiePolicy())1376 assert isinstance(jar.copy().get_policy(), MyCookiePolicy)13771378 def test_time_elapsed_blank(self, httpbin):1379 r = requests.get(httpbin("get"))1380 td = r.elapsed1381 total_seconds = (1382 td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**61383 ) / 10**61384 assert total_seconds > 0.013851386 def test_empty_response_has_content_none(self):1387 r = requests.Response()1388 assert r.content is None13891390 def test_response_is_iterable(self):1391 r = requests.Response()1392 io = StringIO.StringIO("abc")1393 read_ = io.read13941395 def read_mock(amt, decode_content=None):1396 return read_(amt)13971398 setattr(io, "read", read_mock)1399 r.raw = io1400 assert next(iter(r))1401 io.close()14021403 def test_response_decode_unicode(self):1404 """When called with decode_unicode, Response.iter_content should always1405 return unicode.1406 """1407 r = requests.Response()1408 r._content_consumed = True1409 r._content = b"the content"1410 r.encoding = "ascii"14111412 chunks = r.iter_content(decode_unicode=True)1413 assert all(isinstance(chunk, str) for chunk in chunks)14141415 # also for streaming1416 r = requests.Response()1417 r.raw = io.BytesIO(b"the content")1418 r.encoding = "ascii"1419 chunks = r.iter_content(decode_unicode=True)1420 assert all(isinstance(chunk, str) for chunk in chunks)14211422 def test_response_reason_unicode(self):1423 # check for unicode HTTP status1424 r = requests.Response()1425 r.url = "unicode URL"1426 r.reason = "Komponenttia ei löydy".encode()1427 r.status_code = 4041428 r.encoding = None1429 assert not r.ok # old behaviour - crashes here14301431 def test_response_reason_unicode_fallback(self):1432 # check raise_status falls back to ISO-8859-11433 r = requests.Response()1434 r.url = "some url"1435 reason = "Komponenttia ei löydy"1436 r.reason = reason.encode("latin-1")1437 r.status_code = 5001438 r.encoding = None1439 with pytest.raises(requests.exceptions.HTTPError) as e:1440 r.raise_for_status()1441 assert reason in e.value.args[0]14421443 def test_response_chunk_size_type(self):1444 """Ensure that chunk_size is passed as None or an integer, otherwise1445 raise a TypeError.1446 """1447 r = requests.Response()1448 r.raw = io.BytesIO(b"the content")1449 chunks = r.iter_content(1)1450 assert all(len(chunk) == 1 for chunk in chunks)14511452 r = requests.Response()1453 r.raw = io.BytesIO(b"the content")1454 chunks = r.iter_content(None)1455 assert list(chunks) == [b"the content"]14561457 r = requests.Response()1458 r.raw = io.BytesIO(b"the content")1459 with pytest.raises(TypeError):1460 chunks = r.iter_content("1024")14611462 @pytest.mark.parametrize(1463 "exception, args, expected",1464 (1465 (urllib3.exceptions.ProtocolError, tuple(), ChunkedEncodingError),1466 (urllib3.exceptions.DecodeError, tuple(), ContentDecodingError),1467 (urllib3.exceptions.ReadTimeoutError, (None, "", ""), ConnectionError),1468 (urllib3.exceptions.SSLError, tuple(), RequestsSSLError),1469 ),1470 )1471 def test_iter_content_wraps_exceptions(self, httpbin, exception, args, expected):1472 r = requests.Response()1473 r.raw = mock.Mock()1474 # ReadTimeoutError can't be initialized by mock1475 # so we'll manually create the instance with args1476 r.raw.stream.side_effect = exception(*args)14771478 with pytest.raises(expected):1479 next(r.iter_content(1024))14801481 def test_request_and_response_are_pickleable(self, httpbin):1482 r = requests.get(httpbin("get"))14831484 # verify we can pickle the original request1485 assert pickle.loads(pickle.dumps(r.request))14861487 # verify we can pickle the response and that we have access to1488 # the original request.1489 pr = pickle.loads(pickle.dumps(r))1490 assert r.request.url == pr.request.url1491 assert r.request.headers == pr.request.headers14921493 def test_prepared_request_is_pickleable(self, httpbin):1494 p = requests.Request("GET", httpbin("get")).prepare()14951496 # Verify PreparedRequest can be pickled and unpickled1497 r = pickle.loads(pickle.dumps(p))1498 assert r.url == p.url1499 assert r.headers == p.headers1500 assert r.body == p.body15011502 # Verify unpickled PreparedRequest sends properly1503 s = requests.Session()1504 resp = s.send(r)1505 assert resp.status_code == 20015061507 def test_prepared_request_with_file_is_pickleable(self, httpbin):1508 with open(__file__, "rb") as f:1509 r = requests.Request("POST", httpbin("post"), files={"file": f})1510 p = r.prepare()15111512 # Verify PreparedRequest can be pickled and unpickled1513 r = pickle.loads(pickle.dumps(p))1514 assert r.url == p.url1515 assert r.headers == p.headers1516 assert r.body == p.body15171518 # Verify unpickled PreparedRequest sends properly1519 s = requests.Session()1520 resp = s.send(r)1521 assert resp.status_code == 20015221523 def test_prepared_request_with_hook_is_pickleable(self, httpbin):1524 r = requests.Request("GET", httpbin("get"), hooks=default_hooks())1525 p = r.prepare()15261527 # Verify PreparedRequest can be pickled1528 r = pickle.loads(pickle.dumps(p))1529 assert r.url == p.url1530 assert r.headers == p.headers1531 assert r.body == p.body1532 assert r.hooks == p.hooks15331534 # Verify unpickled PreparedRequest sends properly1535 s = requests.Session()1536 resp = s.send(r)1537 assert resp.status_code == 20015381539 def test_cannot_send_unprepared_requests(self, httpbin):1540 r = requests.Request(url=httpbin())1541 with pytest.raises(ValueError):1542 requests.Session().send(r)15431544 def test_http_error(self):1545 error = requests.exceptions.HTTPError()1546 assert not error.response1547 response = requests.Response()1548 error = requests.exceptions.HTTPError(response=response)1549 assert error.response == response1550 error = requests.exceptions.HTTPError("message", response=response)1551 assert str(error) == "message"1552 assert error.response == response15531554 def test_session_pickling(self, httpbin):1555 r = requests.Request("GET", httpbin("get"))1556 s = requests.Session()15571558 s = pickle.loads(pickle.dumps(s))1559 s.proxies = getproxies()15601561 r = s.send(r.prepare())1562 assert r.status_code == 20015631564 def test_fixes_1329(self, httpbin):1565 """Ensure that header updates are done case-insensitively."""1566 s = requests.Session()1567 s.headers.update({"ACCEPT": "BOGUS"})1568 s.headers.update({"accept": "application/json"})1569 r = s.get(httpbin("get"))1570 headers = r.request.headers1571 assert headers["accept"] == "application/json"1572 assert headers["Accept"] == "application/json"1573 assert headers["ACCEPT"] == "application/json"15741575 def test_uppercase_scheme_redirect(self, httpbin):1576 parts = urlparse(httpbin("html"))1577 url = "HTTP://" + parts.netloc + parts.path1578 r = requests.get(httpbin("redirect-to"), params={"url": url})1579 assert r.status_code == 2001580 assert r.url.lower() == url.lower()15811582 def test_transport_adapter_ordering(self):1583 s = requests.Session()1584 order = ["https://", "http://"]1585 assert order == list(s.adapters)1586 s.mount("http://git", HTTPAdapter())1587 s.mount("http://github", HTTPAdapter())1588 s.mount("http://github.com", HTTPAdapter())1589 s.mount("http://github.com/about/", HTTPAdapter())1590 order = [1591 "http://github.com/about/",1592 "http://github.com",1593 "http://github",1594 "http://git",1595 "https://",1596 "http://",1597 ]1598 assert order == list(s.adapters)1599 s.mount("http://gittip", HTTPAdapter())1600 s.mount("http://gittip.com", HTTPAdapter())1601 s.mount("http://gittip.com/about/", HTTPAdapter())1602 order = [1603 "http://github.com/about/",1604 "http://gittip.com/about/",1605 "http://github.com",1606 "http://gittip.com",1607 "http://github",1608 "http://gittip",1609 "http://git",1610 "https://",1611 "http://",1612 ]1613 assert order == list(s.adapters)1614 s2 = requests.Session()1615 s2.adapters = {"http://": HTTPAdapter()}1616 s2.mount("https://", HTTPAdapter())1617 assert "http://" in s2.adapters1618 assert "https://" in s2.adapters16191620 def test_session_get_adapter_prefix_matching(self):1621 prefix = "https://example.com"1622 more_specific_prefix = prefix + "/some/path"16231624 url_matching_only_prefix = prefix + "/another/path"1625 url_matching_more_specific_prefix = more_specific_prefix + "/longer/path"1626 url_not_matching_prefix = "https://another.example.com/"16271628 s = requests.Session()1629 prefix_adapter = HTTPAdapter()1630 more_specific_prefix_adapter = HTTPAdapter()1631 s.mount(prefix, prefix_adapter)1632 s.mount(more_specific_prefix, more_specific_prefix_adapter)16331634 assert s.get_adapter(url_matching_only_prefix) is prefix_adapter1635 assert (1636 s.get_adapter(url_matching_more_specific_prefix)1637 is more_specific_prefix_adapter1638 )1639 assert s.get_adapter(url_not_matching_prefix) not in (1640 prefix_adapter,1641 more_specific_prefix_adapter,1642 )16431644 def test_session_get_adapter_prefix_matching_mixed_case(self):1645 mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"1646 url_matching_prefix = mixed_case_prefix + "/full_url"16471648 s = requests.Session()1649 my_adapter = HTTPAdapter()1650 s.mount(mixed_case_prefix, my_adapter)16511652 assert s.get_adapter(url_matching_prefix) is my_adapter16531654 def test_session_get_adapter_prefix_matching_is_case_insensitive(self):1655 mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"1656 url_matching_prefix_with_different_case = (1657 "HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url"1658 )16591660 s = requests.Session()1661 my_adapter = HTTPAdapter()1662 s.mount(mixed_case_prefix, my_adapter)16631664 assert s.get_adapter(url_matching_prefix_with_different_case) is my_adapter16651666 def test_header_remove_is_case_insensitive(self, httpbin):1667 # From issue #13211668 s = requests.Session()1669 s.headers["foo"] = "bar"1670 r = s.get(httpbin("get"), headers={"FOO": None})1671 assert "foo" not in r.request.headers16721673 def test_params_are_merged_case_sensitive(self, httpbin):1674 s = requests.Session()1675 s.params["foo"] = "bar"1676 r = s.get(httpbin("get"), params={"FOO": "bar"})1677 assert r.json()["args"] == {"foo": "bar", "FOO": "bar"}16781679 def test_long_authinfo_in_url(self):1680 url = "http://{}:{}@{}:9000/path?query#frag".format(1681 "E8A3BE87-9E3F-4620-8858-95478E385B5B",1682 "EA770032-DA4D-4D84-8CE9-29C6D910BF1E",1683 "exactly-------------sixty-----------three------------characters",1684 )1685 r = requests.Request("GET", url).prepare()1686 assert r.url == url16871688 def test_header_keys_are_native(self, httpbin):1689 headers = {"unicode": "blah", b"byte": "blah"}1690 r = requests.Request("GET", httpbin("get"), headers=headers)1691 p = r.prepare()16921693 # This is testing that they are builtin strings. A bit weird, but there1694 # we go.1695 assert "unicode" in p.headers.keys()1696 assert "byte" in p.headers.keys()16971698 def test_header_validation(self, httpbin):1699 """Ensure prepare_headers regex isn't flagging valid header contents."""1700 valid_headers = {1701 "foo": "bar baz qux",1702 "bar": b"fbbq",1703 "baz": "",1704 "qux": "1",1705 }1706 r = requests.get(httpbin("get"), headers=valid_headers)1707 for key in valid_headers.keys():1708 assert valid_headers[key] == r.request.headers[key]17091710 @pytest.mark.parametrize(1711 "invalid_header, key",1712 (1713 ({"foo": 3}, "foo"),1714 ({"bar": {"foo": "bar"}}, "bar"),1715 ({"baz": ["foo", "bar"]}, "baz"),1716 ),1717 )1718 def test_header_value_not_str(self, httpbin, invalid_header, key):1719 """Ensure the header value is of type string or bytes as1720 per discussion in GH issue #33861721 """1722 with pytest.raises(InvalidHeader) as excinfo:1723 requests.get(httpbin("get"), headers=invalid_header)1724 assert key in str(excinfo.value)17251726 @pytest.mark.parametrize(1727 "invalid_header",1728 (1729 {"foo": "bar\r\nbaz: qux"},1730 {"foo": "bar\n\rbaz: qux"},1731 {"foo": "bar\nbaz: qux"},1732 {"foo": "bar\rbaz: qux"},1733 {"fo\ro": "bar"},1734 {"fo\r\no": "bar"},1735 {"fo\n\ro": "bar"},1736 {"fo\no": "bar"},1737 ),1738 )1739 def test_header_no_return_chars(self, httpbin, invalid_header):1740 """Ensure that a header containing return character sequences raise an1741 exception. Otherwise, multiple headers are created from single string.1742 """1743 with pytest.raises(InvalidHeader):1744 requests.get(httpbin("get"), headers=invalid_header)17451746 @pytest.mark.parametrize(1747 "invalid_header",1748 (1749 {" foo": "bar"},1750 {"\tfoo": "bar"},1751 {" foo": "bar"},1752 {"foo": " bar"},1753 {"foo": " bar"},1754 {"foo": "\tbar"},1755 {" ": "bar"},1756 ),1757 )1758 def test_header_no_leading_space(self, httpbin, invalid_header):1759 """Ensure headers containing leading whitespace raise1760 InvalidHeader Error before sending.1761 """1762 with pytest.raises(InvalidHeader):1763 requests.get(httpbin("get"), headers=invalid_header)17641765 def test_header_with_subclass_types(self, httpbin):1766 """If the subclasses does not behave *exactly* like1767 the base bytes/str classes, this is not supported.1768 This test is for backwards compatibility.1769 """17701771 class MyString(str):1772 pass17731774 class MyBytes(bytes):1775 pass17761777 r_str = requests.get(httpbin("get"), headers={MyString("x-custom"): "myheader"})1778 assert r_str.request.headers["x-custom"] == "myheader"17791780 r_bytes = requests.get(1781 httpbin("get"), headers={MyBytes(b"x-custom"): b"myheader"}1782 )1783 assert r_bytes.request.headers["x-custom"] == b"myheader"17841785 r_mixed = requests.get(1786 httpbin("get"), headers={MyString("x-custom"): MyBytes(b"myheader")}1787 )1788 assert r_mixed.request.headers["x-custom"] == b"myheader"17891790 @pytest.mark.parametrize("files", ("foo", b"foo", bytearray(b"foo")))1791 def test_can_send_objects_with_files(self, httpbin, files):1792 data = {"a": "this is a string"}1793 files = {"b": files}1794 r = requests.Request("POST", httpbin("post"), data=data, files=files)1795 p = r.prepare()1796 assert "multipart/form-data" in p.headers["Content-Type"]17971798 def test_can_send_file_object_with_non_string_filename(self, httpbin):1799 f = io.BytesIO()1800 f.name = 21801 r = requests.Request("POST", httpbin("post"), files={"f": f})1802 p = r.prepare()18031804 assert "multipart/form-data" in p.headers["Content-Type"]18051806 def test_autoset_header_values_are_native(self, httpbin):1807 data = "this is a string"1808 length = "16"1809 req = requests.Request("POST", httpbin("post"), data=data)1810 p = req.prepare()18111812 assert p.headers["Content-Length"] == length18131814 def test_nonhttp_schemes_dont_check_URLs(self):1815 test_urls = (1816 "data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",1817 "file:///etc/passwd",1818 "magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431",1819 )1820 for test_url in test_urls:1821 req = requests.Request("GET", test_url)1822 preq = req.prepare()1823 assert test_url == preq.url18241825 def test_auth_is_stripped_on_http_downgrade(1826 self, httpbin, httpbin_secure, httpbin_ca_bundle1827 ):1828 r = requests.get(1829 httpbin_secure("redirect-to"),1830 params={"url": httpbin("get")},1831 auth=("user", "pass"),1832 verify=httpbin_ca_bundle,1833 )1834 assert r.history[0].request.headers["Authorization"]1835 assert "Authorization" not in r.request.headers18361837 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1838 r = requests.get(httpbin("redirect/1"), auth=("user", "pass"))1839 h1 = r.history[0].request.headers["Authorization"]1840 h2 = r.request.headers["Authorization"]18411842 assert h1 == h218431844 def test_should_strip_auth_host_change(self):1845 s = requests.Session()1846 assert s.should_strip_auth(1847 "http://example.com/foo", "http://another.example.com/"1848 )18491850 def test_should_strip_auth_http_downgrade(self):1851 s = requests.Session()1852 assert s.should_strip_auth("https://example.com/foo", "http://example.com/bar")18531854 def test_should_strip_auth_https_upgrade(self):1855 s = requests.Session()1856 assert not s.should_strip_auth(1857 "http://example.com/foo", "https://example.com/bar"1858 )1859 assert not s.should_strip_auth(1860 "http://example.com:80/foo", "https://example.com/bar"1861 )1862 assert not s.should_strip_auth(1863 "http://example.com/foo", "https://example.com:443/bar"1864 )1865 # Non-standard ports should trigger stripping1866 assert s.should_strip_auth(1867 "http://example.com:8080/foo", "https://example.com/bar"1868 )1869 assert s.should_strip_auth(1870 "http://example.com/foo", "https://example.com:8443/bar"1871 )18721873 def test_should_strip_auth_port_change(self):1874 s = requests.Session()1875 assert s.should_strip_auth(1876 "http://example.com:1234/foo", "https://example.com:4321/bar"1877 )18781879 @pytest.mark.parametrize(1880 "old_uri, new_uri",1881 (1882 ("https://example.com:443/foo", "https://example.com/bar"),1883 ("http://example.com:80/foo", "http://example.com/bar"),1884 ("https://example.com/foo", "https://example.com:443/bar"),1885 ("http://example.com/foo", "http://example.com:80/bar"),1886 ),1887 )1888 def test_should_strip_auth_default_port(self, old_uri, new_uri):1889 s = requests.Session()1890 assert not s.should_strip_auth(old_uri, new_uri)18911892 def test_manual_redirect_with_partial_body_read(self, httpbin):1893 s = requests.Session()1894 r1 = s.get(httpbin("redirect/2"), allow_redirects=False, stream=True)1895 assert r1.is_redirect1896 rg = s.resolve_redirects(r1, r1.request, stream=True)18971898 # read only the first eight bytes of the response body,1899 # then follow the redirect1900 r1.iter_content(8)1901 r2 = next(rg)1902 assert r2.is_redirect19031904 # read all of the response via iter_content,1905 # then follow the redirect1906 for _ in r2.iter_content():1907 pass1908 r3 = next(rg)1909 assert not r3.is_redirect19101911 def test_prepare_body_position_non_stream(self):1912 data = b"the data"1913 prep = requests.Request("GET", "http://example.com", data=data).prepare()1914 assert prep._body_position is None19151916 def test_rewind_body(self):1917 data = io.BytesIO(b"the data")1918 prep = requests.Request("GET", "http://example.com", data=data).prepare()1919 assert prep._body_position == 01920 assert prep.body.read() == b"the data"19211922 # the data has all been read1923 assert prep.body.read() == b""19241925 # rewind it back1926 requests.utils.rewind_body(prep)1927 assert prep.body.read() == b"the data"19281929 def test_rewind_partially_read_body(self):1930 data = io.BytesIO(b"the data")1931 data.read(4) # read some data1932 prep = requests.Request("GET", "http://example.com", data=data).prepare()1933 assert prep._body_position == 41934 assert prep.body.read() == b"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"data"19421943 def test_rewind_body_no_seek(self):1944 class BadFileObj:1945 def __init__(self, data):1946 self.data = data19471948 def tell(self):1949 return 019501951 def __iter__(self):1952 return19531954 data = BadFileObj("the data")1955 prep = requests.Request("GET", "http://example.com", data=data).prepare()1956 assert prep._body_position == 019571958 with pytest.raises(UnrewindableBodyError) as e:1959 requests.utils.rewind_body(prep)19601961 assert "Unable to rewind request body" in str(e)19621963 def test_rewind_body_failed_seek(self):1964 class BadFileObj:1965 def __init__(self, data):1966 self.data = data19671968 def tell(self):1969 return 019701971 def seek(self, pos, whence=0):1972 raise OSError()19731974 def __iter__(self):1975 return19761977 data = BadFileObj("the data")1978 prep = requests.Request("GET", "http://example.com", data=data).prepare()1979 assert prep._body_position == 019801981 with pytest.raises(UnrewindableBodyError) as e:1982 requests.utils.rewind_body(prep)19831984 assert "error occurred when rewinding request body" in str(e)19851986 def test_rewind_body_failed_tell(self):1987 class BadFileObj:1988 def __init__(self, data):1989 self.data = data19901991 def tell(self):1992 raise OSError()19931994 def __iter__(self):1995 return19961997 data = BadFileObj("the data")1998 prep = requests.Request("GET", "http://example.com", data=data).prepare()1999 assert prep._body_position is not None2000The first 2,000 of 2,983 lines.