test_requests.py
This file
Path
tests/test_requests.py
3,094 lines · 106.0 KiB · Python
Last changed by
Add hasattr checks for remaining protocol isinstance checks (#7505)Nate Prewittbefore adoption6f66281
History of this fileTake it
1"""Tests for Requests."""23import collections4import contextlib5import io6import json7import os8import pickle9import re10import tempfile11import threading12import warnings13from unittest import mock1415import pytest16import urllib317from urllib3.util import Timeout as Urllib3Timeout1819import requests20from requests.adapters import HTTPAdapter21from requests.auth import HTTPDigestAuth, _basic_auth_str22from requests.compat import (23 JSONDecodeError,24 Morsel,25 MutableMapping,26 builtin_str,27 cookielib,28 getproxies,29 is_urllib3_1,30 urlparse,31)32from requests.cookies import cookiejar_from_dict, morsel_to_cookie33from requests.exceptions import (34 ChunkedEncodingError,35 ConnectionError,36 ConnectTimeout,37 ContentDecodingError,38 InvalidHeader,39 InvalidProxyURL,40 InvalidSchema,41 InvalidURL,42 MissingSchema,43 ProxyError,44 ReadTimeout,45 RequestException,46 RetryError,47 Timeout,48 TooManyRedirects,49 UnrewindableBodyError,50)51from requests.exceptions import SSLError as RequestsSSLError52from requests.hooks import default_hooks53from requests.models import PreparedRequest, urlencode54from requests.sessions import SessionRedirectMixin55from requests.structures import CaseInsensitiveDict5657from . import SNIMissingWarning58from .compat import StringIO59from .testserver.server import TLSServer, consume_socket_content60from .utils import override_environ6162# Requests to this URL should always fail with a connection timeout (nothing63# listening on that port)64TARPIT = "http://10.255.255.1"6566# This is to avoid waiting the timeout of using TARPIT67INVALID_PROXY = "http://localhost:1"6869try:70 from ssl import SSLContext7172 del SSLContext73 HAS_MODERN_SSL = True74except ImportError:75 HAS_MODERN_SSL = False7677try:78 requests.pyopenssl79 HAS_PYOPENSSL = True80except AttributeError:81 HAS_PYOPENSSL = False828384class TestRequests:85 digest_auth_algo = ("MD5", "SHA-256", "SHA-512")8687 def test_entry_points(self):88 requests.session89 requests.session().get90 requests.session().head91 requests.get92 requests.head93 requests.put94 requests.patch95 requests.post96 # Not really an entry point, but people rely on it.97 from requests.packages.urllib3.poolmanager import PoolManager # noqa:F4019899 @pytest.mark.parametrize(100 "exception, url",101 (102 (MissingSchema, "hiwpefhipowhefopw"),103 (InvalidSchema, "localhost:3128"),104 (InvalidSchema, "localhost.localdomain:3128/"),105 (InvalidSchema, "10.122.1.1:3128/"),106 (InvalidURL, "http://"),107 (InvalidURL, "http://*example.com"),108 (InvalidURL, "http://.example.com"),109 ),110 )111 def test_invalid_url(self, exception, url):112 with pytest.raises(exception):113 requests.get(url)114115 def test_basic_building(self):116 req = requests.Request()117 req.url = "http://kennethreitz.org/"118 req.data = {"life": "42"}119120 pr = req.prepare()121 assert pr.url == req.url122 assert pr.body == "life=42"123124 @pytest.mark.parametrize("method", ("GET", "HEAD"))125 def test_no_content_length(self, httpbin, method):126 req = requests.Request(method, httpbin(method.lower())).prepare()127 assert "Content-Length" not in req.headers128129 @pytest.mark.parametrize("method", ("POST", "PUT", "PATCH", "OPTIONS"))130 def test_no_body_content_length(self, httpbin, method):131 req = requests.Request(method, httpbin(method.lower())).prepare()132 assert req.headers["Content-Length"] == "0"133134 @pytest.mark.parametrize("method", ("POST", "PUT", "PATCH", "OPTIONS"))135 def test_empty_content_length(self, httpbin, method):136 req = requests.Request(method, httpbin(method.lower()), data="").prepare()137 assert req.headers["Content-Length"] == "0"138139 def test_override_content_length(self, httpbin):140 headers = {"Content-Length": "not zero"}141 r = requests.Request("POST", httpbin("post"), headers=headers).prepare()142 assert "Content-Length" in r.headers143 assert r.headers["Content-Length"] == "not zero"144145 def test_path_is_not_double_encoded(self):146 request = requests.Request("GET", "http://0.0.0.0/get/test case").prepare()147148 assert request.path_url == "/get/test%20case"149150 @pytest.mark.parametrize(151 "url, expected",152 (153 (154 "http://example.com/path#fragment",155 "http://example.com/path?a=b#fragment",156 ),157 (158 "http://example.com/path?key=value#fragment",159 "http://example.com/path?key=value&a=b#fragment",160 ),161 ),162 )163 def test_params_are_added_before_fragment(self, url, expected):164 request = requests.Request("GET", url, params={"a": "b"}).prepare()165 assert request.url == expected166167 def test_params_original_order_is_preserved_by_default(self):168 param_ordered_dict = collections.OrderedDict(169 (("z", 1), ("a", 1), ("k", 1), ("d", 1))170 )171 session = requests.Session()172 request = requests.Request(173 "GET", "http://example.com/", params=param_ordered_dict174 )175 prep = session.prepare_request(request)176 assert prep.url == "http://example.com/?z=1&a=1&k=1&d=1"177178 def test_params_bytes_are_encoded(self):179 request = requests.Request(180 "GET", "http://example.com", params=b"test=foo"181 ).prepare()182 assert request.url == "http://example.com/?test=foo"183184 def test_binary_put(self):185 request = requests.Request(186 "PUT", "http://example.com", data="ööö".encode()187 ).prepare()188 assert isinstance(request.body, bytes)189190 def test_whitespaces_are_removed_from_url(self):191 # Test for issue #3696192 request = requests.Request("GET", " http://example.com").prepare()193 assert request.url == "http://example.com/"194195 @pytest.mark.parametrize("scheme", ("http://", "HTTP://", "hTTp://", "HttP://"))196 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):197 s = requests.Session()198 s.proxies = getproxies()199 parts = urlparse(httpbin("get"))200 url = scheme + parts.netloc + parts.path201 r = requests.Request("GET", url)202 r = s.send(r.prepare())203 assert r.status_code == 200, f"failed for scheme {scheme}"204205 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):206 r = requests.Request("GET", httpbin("get"))207 s = requests.Session()208 s.proxies = getproxies()209210 r = s.send(r.prepare())211212 assert r.status_code == 200213214 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):215 r = requests.get(httpbin("redirect", "1"))216 assert r.status_code == 200217 assert r.history[0].status_code == 302218 assert r.history[0].is_redirect219220 def test_redirect_history_no_self_reference(self, httpbin):221 r = requests.get(httpbin("redirect", "3"))222 assert r.status_code == 200223 assert len(r.history) == 3224 for i, resp in enumerate(r.history):225 assert resp not in resp.history226 assert resp.history == r.history[:i]227228 def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):229 r = requests.post(230 httpbin("redirect-to"),231 data="test",232 params={"url": "post", "status_code": 307},233 )234 assert r.status_code == 200235 assert r.history[0].status_code == 307236 assert r.history[0].is_redirect237 assert r.json()["data"] == "test"238239 def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):240 byte_str = b"test"241 r = requests.post(242 httpbin("redirect-to"),243 data=io.BytesIO(byte_str),244 params={"url": "post", "status_code": 307},245 )246 assert r.status_code == 200247 assert r.history[0].status_code == 307248 assert r.history[0].is_redirect249 assert r.json()["data"] == byte_str.decode("utf-8")250251 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):252 try:253 requests.get(httpbin("relative-redirect", "50"))254 except TooManyRedirects as e:255 url = httpbin("relative-redirect", "20")256 assert e.request.url == url257 assert e.response.url == url258 assert len(e.response.history) == 30259 else:260 pytest.fail("Expected redirect to raise TooManyRedirects but it did not")261262 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):263 s = requests.session()264 s.max_redirects = 5265 try:266 s.get(httpbin("relative-redirect", "50"))267 except TooManyRedirects as e:268 url = httpbin("relative-redirect", "45")269 assert e.request.url == url270 assert e.response.url == url271 assert len(e.response.history) == 5272 else:273 pytest.fail(274 "Expected custom max number of redirects to be respected but was not"275 )276277 def test_http_301_changes_post_to_get(self, httpbin):278 r = requests.post(httpbin("status", "301"))279 assert r.status_code == 200280 assert r.request.method == "GET"281 assert r.history[0].status_code == 301282 assert r.history[0].is_redirect283284 def test_http_301_doesnt_change_head_to_get(self, httpbin):285 r = requests.head(httpbin("status", "301"), allow_redirects=True)286 print(r.content)287 assert r.status_code == 200288 assert r.request.method == "HEAD"289 assert r.history[0].status_code == 301290 assert r.history[0].is_redirect291292 def test_http_302_changes_post_to_get(self, httpbin):293 r = requests.post(httpbin("status", "302"))294 assert r.status_code == 200295 assert r.request.method == "GET"296 assert r.history[0].status_code == 302297 assert r.history[0].is_redirect298299 def test_http_302_doesnt_change_head_to_get(self, httpbin):300 r = requests.head(httpbin("status", "302"), allow_redirects=True)301 assert r.status_code == 200302 assert r.request.method == "HEAD"303 assert r.history[0].status_code == 302304 assert r.history[0].is_redirect305306 def test_http_303_changes_post_to_get(self, httpbin):307 r = requests.post(httpbin("status", "303"))308 assert r.status_code == 200309 assert r.request.method == "GET"310 assert r.history[0].status_code == 303311 assert r.history[0].is_redirect312313 def test_http_303_doesnt_change_head_to_get(self, httpbin):314 r = requests.head(httpbin("status", "303"), allow_redirects=True)315 assert r.status_code == 200316 assert r.request.method == "HEAD"317 assert r.history[0].status_code == 303318 assert r.history[0].is_redirect319320 def test_header_and_body_removal_on_redirect(self, httpbin):321 purged_headers = ("Content-Length", "Content-Type")322 ses = requests.Session()323 req = requests.Request("POST", httpbin("post"), data={"test": "data"})324 prep = ses.prepare_request(req)325 resp = ses.send(prep)326327 # Mimic a redirect response328 resp.status_code = 302329 resp.headers["location"] = "get"330331 # Run request through resolve_redirects332 next_resp = next(ses.resolve_redirects(resp, prep))333 assert next_resp.request.body is None334 for header in purged_headers:335 assert header not in next_resp.request.headers336337 def test_transfer_enc_removal_on_redirect(self, httpbin):338 purged_headers = ("Transfer-Encoding", "Content-Type")339 ses = requests.Session()340 req = requests.Request("POST", httpbin("post"), data=(b"x" for x in range(1)))341 prep = ses.prepare_request(req)342 assert "Transfer-Encoding" in prep.headers343344 # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33345 resp = requests.Response()346 resp.raw = io.BytesIO(b"the content")347 resp.request = prep348 setattr(resp.raw, "release_conn", lambda *args: args)349350 # Mimic a redirect response351 resp.status_code = 302352 resp.headers["location"] = httpbin("get")353354 # Run request through resolve_redirect355 next_resp = next(ses.resolve_redirects(resp, prep))356 assert next_resp.request.body is None357 for header in purged_headers:358 assert header not in next_resp.request.headers359360 def test_fragment_maintained_on_redirect(self, httpbin):361 fragment = "#view=edit&token=hunter2"362 r = requests.get(httpbin("redirect-to?url=get") + fragment)363364 assert len(r.history) > 0365 assert r.history[0].request.url == httpbin("redirect-to?url=get") + fragment366 assert r.url == httpbin("get") + fragment367368 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):369 heads = {"User-agent": "Mozilla/5.0"}370371 r = requests.get(httpbin("user-agent"), headers=heads)372373 assert heads["User-agent"] in r.text374 assert r.status_code == 200375376 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):377 heads = {"User-agent": "Mozilla/5.0"}378379 r = requests.get(380 httpbin("get") + "?test=true", params={"q": "test"}, headers=heads381 )382 assert r.status_code == 200383384 def test_set_cookie_on_301(self, httpbin):385 s = requests.session()386 url = httpbin("cookies/set?foo=bar")387 s.get(url)388 assert s.cookies["foo"] == "bar"389390 def test_cookie_sent_on_redirect(self, httpbin):391 s = requests.session()392 s.get(httpbin("cookies/set?foo=bar"))393 r = s.get(httpbin("redirect/1")) # redirects to httpbin('get')394 assert "Cookie" in r.json()["headers"]395396 def test_cookie_removed_on_expire(self, httpbin):397 s = requests.session()398 s.get(httpbin("cookies/set?foo=bar"))399 assert s.cookies["foo"] == "bar"400 s.get(401 httpbin("response-headers"),402 params={"Set-Cookie": "foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT"},403 )404 assert "foo" not in s.cookies405406 def test_cookie_quote_wrapped(self, httpbin):407 s = requests.session()408 s.get(httpbin('cookies/set?foo="bar:baz"'))409 assert s.cookies["foo"] == '"bar:baz"'410411 def test_cookie_persists_via_api(self, httpbin):412 s = requests.session()413 r = s.get(httpbin("redirect/1"), cookies={"foo": "bar"})414 assert "foo" in r.request.headers["Cookie"]415 assert "foo" in r.history[0].request.headers["Cookie"]416417 def test_request_cookie_overrides_session_cookie(self, httpbin):418 s = requests.session()419 s.cookies["foo"] = "bar"420 r = s.get(httpbin("cookies"), cookies={"foo": "baz"})421 assert r.json()["cookies"]["foo"] == "baz"422 # Session cookie should not be modified423 assert s.cookies["foo"] == "bar"424425 def test_request_cookies_not_persisted(self, httpbin):426 s = requests.session()427 s.get(httpbin("cookies"), cookies={"foo": "baz"})428 # Sending a request with cookies should not add cookies to the session429 assert not s.cookies430431 def test_generic_cookiejar_works(self, httpbin):432 cj = cookielib.CookieJar()433 cookiejar_from_dict({"foo": "bar"}, cj)434 s = requests.session()435 s.cookies = cj436 r = s.get(httpbin("cookies"))437 # Make sure the cookie was sent438 assert r.json()["cookies"]["foo"] == "bar"439 # Make sure the session cj is still the custom one440 assert s.cookies is cj441442 def test_param_cookiejar_works(self, httpbin):443 cj = cookielib.CookieJar()444 cookiejar_from_dict({"foo": "bar"}, cj)445 s = requests.session()446 r = s.get(httpbin("cookies"), cookies=cj)447 # Make sure the cookie was sent448 assert r.json()["cookies"]["foo"] == "bar"449450 def test_cookielib_cookiejar_on_redirect(self, httpbin):451 """Tests resolve_redirect doesn't fail when merging cookies452 with non-RequestsCookieJar cookiejar.453454 See GH #3579455 """456 cj = cookiejar_from_dict({"foo": "bar"}, cookielib.CookieJar())457 s = requests.Session()458 s.cookies = cookiejar_from_dict({"cookie": "tasty"})459460 # Prepare request without using Session461 req = requests.Request("GET", httpbin("headers"), cookies=cj)462 prep_req = req.prepare()463464 # Send request and simulate redirect465 resp = s.send(prep_req)466 resp.status_code = 302467 resp.headers["location"] = httpbin("get")468 redirects = s.resolve_redirects(resp, prep_req)469 resp = next(redirects)470471 # Verify CookieJar isn't being converted to RequestsCookieJar472 assert isinstance(prep_req._cookies, cookielib.CookieJar)473 assert isinstance(resp.request._cookies, cookielib.CookieJar)474 assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)475476 cookies = {}477 for c in resp.request._cookies:478 cookies[c.name] = c.value479 assert cookies["foo"] == "bar"480 assert cookies["cookie"] == "tasty"481482 def test_requests_in_history_are_not_overridden(self, httpbin):483 resp = requests.get(httpbin("redirect/3"))484 urls = [r.url for r in resp.history]485 req_urls = [r.request.url for r in resp.history]486 assert urls == req_urls487488 def test_history_is_always_a_list(self, httpbin):489 """Show that even with redirects, Response.history is always a list."""490 resp = requests.get(httpbin("get"))491 assert isinstance(resp.history, list)492 resp = requests.get(httpbin("redirect/1"))493 assert isinstance(resp.history, list)494 assert not isinstance(resp.history, tuple)495496 def test_headers_on_session_with_None_are_not_sent(self, httpbin):497 """Do not send headers in Session.headers with None values."""498 ses = requests.Session()499 ses.headers["Accept-Encoding"] = None500 req = requests.Request("GET", httpbin("get"))501 prep = ses.prepare_request(req)502 assert "Accept-Encoding" not in prep.headers503504 def test_headers_preserve_order(self, httpbin):505 """Preserve order when headers provided as OrderedDict."""506 ses = requests.Session()507 ses.headers = collections.OrderedDict()508 ses.headers["Accept-Encoding"] = "identity"509 ses.headers["First"] = "1"510 ses.headers["Second"] = "2"511 headers = collections.OrderedDict([("Third", "3"), ("Fourth", "4")])512 headers["Fifth"] = "5"513 headers["Second"] = "222"514 req = requests.Request("GET", httpbin("get"), headers=headers)515 prep = ses.prepare_request(req)516 items = list(prep.headers.items())517 assert items[0] == ("Accept-Encoding", "identity")518 assert items[1] == ("First", "1")519 assert items[2] == ("Second", "222")520 assert items[3] == ("Third", "3")521 assert items[4] == ("Fourth", "4")522 assert items[5] == ("Fifth", "5")523524 @pytest.mark.parametrize("key", ("User-agent", "user-agent"))525 def test_user_agent_transfers(self, httpbin, key):526 heads = {key: "Mozilla/5.0 (github.com/psf/requests)"}527528 r = requests.get(httpbin("user-agent"), headers=heads)529 assert heads[key] in r.text530531 def test_HTTP_200_OK_HEAD(self, httpbin):532 r = requests.head(httpbin("get"))533 assert r.status_code == 200534535 def test_HTTP_200_OK_PUT(self, httpbin):536 r = requests.put(httpbin("put"))537 assert r.status_code == 200538539 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):540 auth = ("user", "pass")541 url = httpbin("basic-auth", "user", "pass")542543 r = requests.get(url, auth=auth)544 assert r.status_code == 200545546 r = requests.get(url)547 assert r.status_code == 401548549 s = requests.session()550 s.auth = auth551 r = s.get(url)552 assert r.status_code == 200553554 @pytest.mark.parametrize(555 "username, password",556 (557 ("user", "pass"),558 ("имя".encode(), "пароль".encode()),559 (42, 42),560 (None, None),561 ),562 )563 def test_set_basicauth(self, httpbin, username, password):564 auth = (username, password)565 url = httpbin("get")566567 r = requests.Request("GET", url, auth=auth)568 p = r.prepare()569570 assert p.headers["Authorization"] == _basic_auth_str(username, password)571572 def test_basicauth_encodes_byte_strings(self):573 """Ensure b'test' formats as the byte string "test" rather574 than the unicode string "b'test'" in Python 3.575 """576 auth = (b"\xc5\xafsername", b"test\xc6\xb6")577 r = requests.Request("GET", "http://localhost", auth=auth)578 p = r.prepare()579580 assert p.headers["Authorization"] == "Basic xa9zZXJuYW1lOnRlc3TGtg=="581582 @pytest.mark.parametrize(583 "url, exception",584 (585 # Connecting to an unknown domain should raise a ConnectionError586 ("http://doesnotexist.google.com", ConnectionError),587 # Connecting to an invalid port should raise a ConnectionError588 ("http://localhost:1", ConnectionError),589 # Inputting a URL that cannot be parsed should raise an InvalidURL error590 ("http://fe80::5054:ff:fe5a:fc0", InvalidURL),591 ),592 )593 def test_errors(self, url, exception):594 with pytest.raises(exception):595 requests.get(url, timeout=1)596597 def test_proxy_error(self):598 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError599 with pytest.raises(ProxyError):600 requests.get(601 "http://localhost:1", proxies={"http": "non-resolvable-address"}602 )603604 def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):605 with pytest.raises(InvalidProxyURL):606 requests.get(httpbin_secure(), proxies={"https": "http:/badproxyurl:3128"})607608 with pytest.raises(InvalidProxyURL):609 requests.get(httpbin(), proxies={"http": "http://:8080"})610611 with pytest.raises(InvalidProxyURL):612 requests.get(httpbin_secure(), proxies={"https": "https://"})613614 with pytest.raises(InvalidProxyURL):615 requests.get(httpbin(), proxies={"http": "http:///example.com:8080"})616617 def test_respect_proxy_env_on_send_self_prepared_request(self, httpbin):618 with override_environ(http_proxy=INVALID_PROXY):619 with pytest.raises(ProxyError):620 session = requests.Session()621 request = requests.Request("GET", httpbin())622 session.send(request.prepare())623624 def test_respect_proxy_env_on_send_session_prepared_request(self, httpbin):625 with override_environ(http_proxy=INVALID_PROXY):626 with pytest.raises(ProxyError):627 session = requests.Session()628 request = requests.Request("GET", httpbin())629 prepared = session.prepare_request(request)630 session.send(prepared)631632 def test_respect_proxy_env_on_send_with_redirects(self, httpbin):633 with override_environ(http_proxy=INVALID_PROXY):634 with pytest.raises(ProxyError):635 session = requests.Session()636 url = httpbin("redirect/1")637 print(url)638 request = requests.Request("GET", url)639 session.send(request.prepare())640641 def test_respect_proxy_env_on_get(self, httpbin):642 with override_environ(http_proxy=INVALID_PROXY):643 with pytest.raises(ProxyError):644 session = requests.Session()645 session.get(httpbin())646647 def test_respect_proxy_env_on_request(self, httpbin):648 with override_environ(http_proxy=INVALID_PROXY):649 with pytest.raises(ProxyError):650 session = requests.Session()651 session.request(method="GET", url=httpbin())652653 def test_proxy_authorization_preserved_on_request(self, httpbin):654 proxy_auth_value = "Bearer XXX"655 session = requests.Session()656 session.headers.update({"Proxy-Authorization": proxy_auth_value})657 resp = session.request(method="GET", url=httpbin("get"))658 sent_headers = resp.json().get("headers", {})659660 assert sent_headers.get("Proxy-Authorization") == proxy_auth_value661662 @pytest.mark.parametrize(663 "url,has_proxy_auth",664 (665 ("http://example.com", True),666 ("https://example.com", False),667 ),668 )669 def test_proxy_authorization_not_appended_to_https_request(670 self, url, has_proxy_auth671 ):672 session = requests.Session()673 proxies = {674 "http": "http://test:pass@localhost:8080",675 "https": "http://test:pass@localhost:8090",676 }677 req = requests.Request("GET", url)678 prep = req.prepare()679 session.rebuild_proxies(prep, proxies)680681 assert ("Proxy-Authorization" in prep.headers) is has_proxy_auth682683 def test_basicauth_with_netrc(self, httpbin):684 auth = ("user", "pass")685 wrong_auth = ("wronguser", "wrongpass")686 url = httpbin("basic-auth", "user", "pass")687688 old_auth = requests.sessions.get_netrc_auth689690 try:691692 def get_netrc_auth_mock(url):693 return auth694695 requests.sessions.get_netrc_auth = get_netrc_auth_mock696697 # Should use netrc and work.698 r = requests.get(url)699 assert r.status_code == 200700701 # Given auth should override and fail.702 r = requests.get(url, auth=wrong_auth)703 assert r.status_code == 401704705 s = requests.session()706707 # Should use netrc and work.708 r = s.get(url)709 assert r.status_code == 200710711 # Given auth should override and fail.712 s.auth = wrong_auth713 r = s.get(url)714 assert r.status_code == 401715 finally:716 requests.sessions.get_netrc_auth = old_auth717718 def test_basicauth_with_netrc_leak(self, httpbin):719 url1 = httpbin("basic-auth", "user", "pass")720 url = url1[len("http://") :]721 domain = url.split(":")[0]722 url = f"http://example.com:@{url}"723724 netrc_file = ""725 with tempfile.NamedTemporaryFile(mode="w", delete=False) as fp:726 fp.write("machine example.com\n")727 fp.write("login wronguser\n")728 fp.write("password wrongpass\n")729 fp.write(f"machine {domain}\n")730 fp.write("login user\n")731 fp.write("password pass\n")732 fp.close()733 netrc_file = fp.name734735 old_netrc = os.environ.get("NETRC", "")736 os.environ["NETRC"] = netrc_file737738 try:739 # Should use netrc740 # Make sure that we don't use the example.com credentials741 # for the request742 r = requests.get(url)743 assert r.status_code == 200744 finally:745 os.environ["NETRC"] = old_netrc746 os.unlink(netrc_file)747748 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):749 for authtype in self.digest_auth_algo:750 auth = HTTPDigestAuth("user", "pass")751 url = httpbin("digest-auth", "auth", "user", "pass", authtype, "never")752753 r = requests.get(url, auth=auth)754 assert r.status_code == 200755756 r = requests.get(url)757 assert r.status_code == 401758 print(r.headers["WWW-Authenticate"])759760 s = requests.session()761 s.auth = HTTPDigestAuth("user", "pass")762 r = s.get(url)763 assert r.status_code == 200764765 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):766 for authtype in self.digest_auth_algo:767 url = httpbin("digest-auth", "auth", "user", "pass", authtype)768 auth = HTTPDigestAuth("user", "pass")769 r = requests.get(url)770 assert r.cookies["fake"] == "fake_value"771772 r = requests.get(url, auth=auth)773 assert r.status_code == 200774775 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):776 for authtype in self.digest_auth_algo:777 url = httpbin("digest-auth", "auth", "user", "pass", authtype)778 auth = HTTPDigestAuth("user", "pass")779 s = requests.Session()780 s.get(url, auth=auth)781 assert s.cookies["fake"] == "fake_value"782783 def test_DIGEST_STREAM(self, httpbin):784 for authtype in self.digest_auth_algo:785 auth = HTTPDigestAuth("user", "pass")786 url = httpbin("digest-auth", "auth", "user", "pass", authtype)787788 r = requests.get(url, auth=auth, stream=True)789 assert r.raw.read() != b""790791 r = requests.get(url, auth=auth, stream=False)792 assert r.raw.read() == b""793794 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):795 for authtype in self.digest_auth_algo:796 auth = HTTPDigestAuth("user", "wrongpass")797 url = httpbin("digest-auth", "auth", "user", "pass", authtype)798799 r = requests.get(url, auth=auth)800 assert r.status_code == 401801802 r = requests.get(url)803 assert r.status_code == 401804805 s = requests.session()806 s.auth = auth807 r = s.get(url)808 assert r.status_code == 401809810 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):811 for authtype in self.digest_auth_algo:812 auth = HTTPDigestAuth("user", "pass")813 url = httpbin("digest-auth", "auth", "user", "pass", authtype)814815 r = requests.get(url, auth=auth)816 assert '"auth"' in r.request.headers["Authorization"]817818 def test_POSTBIN_GET_POST_FILES(self, httpbin):819 url = httpbin("post")820 requests.post(url).raise_for_status()821822 post1 = requests.post(url, data={"some": "data"})823 assert post1.status_code == 200824825 with open("requirements-dev.txt") as f:826 post2 = requests.post(url, files={"some": f})827 assert post2.status_code == 200828829 post4 = requests.post(url, data='[{"some": "json"}]')830 assert post4.status_code == 200831832 with pytest.raises(ValueError):833 requests.post(url, files=["bad file data"])834835 def test_invalid_files_input(self, httpbin):836 url = httpbin("post")837 post = requests.post(url, files={"random-file-1": None, "random-file-2": 1})838 assert b'name="random-file-1"' not in post.request.body839 assert b'name="random-file-2"' in post.request.body840841 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):842 class TestStream:843 def __init__(self, data):844 self.data = data.encode()845 self.length = len(self.data)846 self.index = 0847848 def __len__(self):849 return self.length850851 def read(self, size=None):852 if size:853 ret = self.data[self.index : self.index + size]854 self.index += size855 else:856 ret = self.data[self.index :]857 self.index = self.length858 return ret859860 def tell(self):861 return self.index862863 def seek(self, offset, where=0):864 if where == 0:865 self.index = offset866 elif where == 1:867 self.index += offset868 elif where == 2:869 self.index = self.length + offset870871 test = TestStream("test")872 post1 = requests.post(httpbin("post"), data=test)873 assert post1.status_code == 200874 assert post1.json()["data"] == "test"875876 test = TestStream("test")877 test.seek(2)878 post2 = requests.post(httpbin("post"), data=test)879 assert post2.status_code == 200880 assert post2.json()["data"] == "st"881882 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):883 url = httpbin("post")884 requests.post(url).raise_for_status()885886 post1 = requests.post(url, data={"some": "data"})887 assert post1.status_code == 200888889 with open("requirements-dev.txt") as f:890 post2 = requests.post(url, data={"some": "data"}, files={"some": f})891 assert post2.status_code == 200892893 post4 = requests.post(url, data='[{"some": "json"}]')894 assert post4.status_code == 200895896 with pytest.raises(ValueError):897 requests.post(url, files=["bad file data"])898899 def test_post_with_custom_mapping(self, httpbin):900 class CustomMapping(MutableMapping):901 def __init__(self, *args, **kwargs):902 self.data = dict(*args, **kwargs)903904 def __delitem__(self, key):905 del self.data[key]906907 def __getitem__(self, key):908 return self.data[key]909910 def __setitem__(self, key, value):911 self.data[key] = value912913 def __iter__(self):914 return iter(self.data)915916 def __len__(self):917 return len(self.data)918919 data = CustomMapping({"some": "data"})920 url = httpbin("post")921 found_json = requests.post(url, data=data).json().get("form")922 assert found_json == {"some": "data"}923924 def test_conflicting_post_params(self, httpbin):925 url = httpbin("post")926 with open("requirements-dev.txt") as f:927 with pytest.raises(ValueError):928 requests.post(url, data='[{"some": "data"}]', files={"some": f})929930 def test_request_ok_set(self, httpbin):931 r = requests.get(httpbin("status", "404"))932 assert not r.ok933934 def test_status_raising(self, httpbin):935 r = requests.get(httpbin("status", "404"))936 with pytest.raises(requests.exceptions.HTTPError):937 r.raise_for_status()938939 r = requests.get(httpbin("status", "500"))940 assert not r.ok941942 def test_decompress_gzip(self, httpbin):943 r = requests.get(httpbin("gzip"))944 r.content.decode("ascii")945946 @pytest.mark.parametrize(947 "url, params",948 (949 ("/get", {"foo": "føø"}),950 ("/get", {"føø": "føø"}),951 ("/get", {"føø": "føø"}),952 ("/get", {"foo": "foo"}),953 ("ø", {"foo": "foo"}),954 ),955 )956 def test_unicode_get(self, httpbin, url, params):957 requests.get(httpbin(url), params=params)958959 def test_unicode_header_name(self, httpbin):960 requests.put(961 httpbin("put"),962 headers={"Content-Type": "application/octet-stream"},963 data="\xff",964 ) # compat.str is unicode.965966 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):967 requests.get(httpbin_secure("status", "301"), verify=httpbin_ca_bundle)968969 def test_invalid_ca_certificate_path(self, httpbin_secure):970 INVALID_PATH = "/garbage"971 with pytest.raises(IOError) as e:972 requests.get(httpbin_secure(), verify=INVALID_PATH)973 assert (974 str(e.value)975 == f"Could not find a suitable TLS CA certificate bundle, invalid path: {INVALID_PATH}"976 )977978 def test_invalid_ssl_certificate_files(self, httpbin_secure):979 INVALID_PATH = "/garbage"980 with pytest.raises(IOError) as e:981 requests.get(httpbin_secure(), cert=INVALID_PATH)982 assert (983 str(e.value)984 == f"Could not find the TLS certificate file, invalid path: {INVALID_PATH}"985 )986987 with pytest.raises(IOError) as e:988 requests.get(httpbin_secure(), cert=(".", INVALID_PATH))989 assert str(e.value) == (990 f"Could not find the TLS key file, invalid path: {INVALID_PATH}"991 )992993 @pytest.mark.parametrize(994 "env, expected",995 (996 ({}, True),997 ({"REQUESTS_CA_BUNDLE": "/some/path"}, "/some/path"),998 ({"REQUESTS_CA_BUNDLE": ""}, True),999 ({"CURL_CA_BUNDLE": "/some/path"}, "/some/path"),1000 ({"CURL_CA_BUNDLE": ""}, True),1001 ({"REQUESTS_CA_BUNDLE": "", "CURL_CA_BUNDLE": ""}, True),1002 (1003 {1004 "REQUESTS_CA_BUNDLE": "/some/path",1005 "CURL_CA_BUNDLE": "/curl/path",1006 },1007 "/some/path",1008 ),1009 (1010 {1011 "REQUESTS_CA_BUNDLE": "",1012 "CURL_CA_BUNDLE": "/curl/path",1013 },1014 "/curl/path",1015 ),1016 ),1017 )1018 def test_env_cert_bundles(self, httpbin, env, expected):1019 s = requests.Session()1020 with mock.patch("os.environ", env):1021 settings = s.merge_environment_settings(1022 url=httpbin("get"), proxies={}, stream=False, verify=True, cert=None1023 )1024 assert settings["verify"] == expected10251026 def test_http_with_certificate(self, httpbin):1027 r = requests.get(httpbin(), cert=".")1028 assert r.status_code == 20010291030 @pytest.mark.skipif(1031 SNIMissingWarning is None,1032 reason="urllib3 2.0 removed that warning and errors out instead",1033 )1034 def test_https_warnings(self, nosan_server):1035 """warnings are emitted with requests.get"""1036 host, port, ca_bundle = nosan_server1037 if HAS_MODERN_SSL or HAS_PYOPENSSL:1038 warnings_expected = ("SubjectAltNameWarning",)1039 else:1040 warnings_expected = (1041 "SNIMissingWarning",1042 "InsecurePlatformWarning",1043 "SubjectAltNameWarning",1044 )10451046 with pytest.warns() as warning_records:1047 warnings.simplefilter("always")1048 requests.get(f"https://localhost:{port}/", verify=ca_bundle)10491050 warning_records = [1051 item1052 for item in warning_records1053 if item.category.__name__ != "ResourceWarning"1054 ]10551056 warnings_category = tuple(item.category.__name__ for item in warning_records)1057 assert warnings_category == warnings_expected10581059 def test_certificate_failure(self, httpbin_secure):1060 """1061 When underlying SSL problems occur, an SSLError is raised.1062 """1063 with pytest.raises(RequestsSSLError):1064 # Our local httpbin does not have a trusted CA, so this call will1065 # fail if we use our default trust bundle.1066 requests.get(httpbin_secure("status", "200"))10671068 def test_urlencoded_get_query_multivalued_param(self, httpbin):1069 r = requests.get(httpbin("get"), params={"test": ["foo", "baz"]})1070 assert r.status_code == 2001071 assert r.url == httpbin("get?test=foo&test=baz")10721073 def test_form_encoded_post_query_multivalued_element(self, httpbin):1074 r = requests.Request(1075 method="POST", url=httpbin("post"), data=dict(test=["foo", "baz"])1076 )1077 prep = r.prepare()1078 assert prep.body == "test=foo&test=baz"10791080 def test_different_encodings_dont_break_post(self, httpbin):1081 with open(__file__, "rb") as f:1082 r = requests.post(1083 httpbin("post"),1084 data={"stuff": json.dumps({"a": 123})},1085 params={"blah": "asdf1234"},1086 files={"file": ("test_requests.py", f)},1087 )1088 assert r.status_code == 20010891090 def test_post_named_tempfile(self, httpbin):1091 with tempfile.NamedTemporaryFile(mode="w+") as f:1092 f.write("named temp file contents\n")1093 f.seek(0)1094 r = requests.post(1095 httpbin("post"),1096 files={"file": f},1097 )1098 assert r.status_code == 2001099 assert r.json()["files"]["file"] == "named temp file contents\n"11001101 def test_post_getattr_proxy_read_only(self, httpbin):11021103 class ReadProxy:1104 def __init__(self):1105 self._file = io.BytesIO(b"streamed body")11061107 def __getattr__(self, name):1108 if name == "__iter__":1109 raise AttributeError(name)1110 return getattr(self._file, name)11111112 r = requests.post(httpbin("post"), data=ReadProxy())1113 assert r.status_code == 2001114 assert r.json()["data"] == "streamed body"11151116 @pytest.mark.parametrize(1117 "data",1118 (1119 {"stuff": "ëlïxr"},1120 {"stuff": "ëlïxr".encode()},1121 {"stuff": "elixr"},1122 {"stuff": b"elixr"},1123 ),1124 )1125 def test_unicode_multipart_post(self, httpbin, data):1126 with open(__file__, "rb") as f:1127 r = requests.post(1128 httpbin("post"),1129 data=data,1130 files={"file": ("test_requests.py", f)},1131 )1132 assert r.status_code == 20011331134 def test_unicode_multipart_post_fieldnames(self, httpbin):1135 filename = os.path.splitext(__file__)[0] + ".py"1136 with open(filename, "rb") as f:1137 r = requests.Request(1138 method="POST",1139 url=httpbin("post"),1140 data={b"stuff": "elixr"},1141 files={"file": ("test_requests.py", f)},1142 )1143 prep = r.prepare()11441145 assert b'name="stuff"' in prep.body1146 assert b"name=\"b'stuff'\"" not in prep.body11471148 def test_unicode_method_name(self, httpbin):1149 with open(__file__, "rb") as f:1150 files = {"file": f}1151 r = requests.request(1152 method="POST",1153 url=httpbin("post"),1154 files=files,1155 )1156 assert r.status_code == 20011571158 def test_unicode_method_name_with_request_object(self, httpbin):1159 s = requests.Session()1160 with open(__file__, "rb") as f:1161 files = {"file": f}1162 req = requests.Request("POST", httpbin("post"), files=files)1163 prep = s.prepare_request(req)1164 assert isinstance(prep.method, builtin_str)1165 assert prep.method == "POST"11661167 resp = s.send(prep)1168 assert resp.status_code == 20011691170 def test_non_prepared_request_error(self):1171 s = requests.Session()1172 req = requests.Request("POST", "/")11731174 with pytest.raises(ValueError) as e:1175 s.send(req)1176 assert str(e.value) == "You can only send PreparedRequests."11771178 def test_custom_content_type(self, httpbin):1179 with open(__file__, "rb") as f1:1180 with open(__file__, "rb") as f2:1181 data = {"stuff": json.dumps({"a": 123})}1182 files = {1183 "file1": ("test_requests.py", f1),1184 "file2": ("test_requests", f2, "text/py-content-type"),1185 }1186 r = requests.post(httpbin("post"), data=data, files=files)1187 assert r.status_code == 2001188 assert b"text/py-content-type" in r.request.body11891190 def test_hook_receives_request_arguments(self, httpbin):1191 def hook(resp, **kwargs):1192 assert resp is not None1193 assert kwargs != {}11941195 s = requests.Session()1196 r = requests.Request("GET", httpbin(), hooks={"response": hook})1197 prep = s.prepare_request(r)1198 s.send(prep)11991200 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):1201 def hook(*args, **kwargs):1202 pass12031204 s = requests.Session()1205 s.hooks["response"].append(hook)1206 r = requests.Request("GET", httpbin())1207 prep = s.prepare_request(r)1208 assert prep.hooks["response"] != []1209 assert prep.hooks["response"] == [hook]12101211 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):1212 def hook1(*args, **kwargs):1213 pass12141215 def hook2(*args, **kwargs):1216 pass12171218 assert hook1 is not hook21219 s = requests.Session()1220 s.hooks["response"].append(hook2)1221 r = requests.Request("GET", httpbin(), hooks={"response": [hook1]})1222 prep = s.prepare_request(r)1223 assert prep.hooks["response"] == [hook1]12241225 def test_prepared_request_hook(self, httpbin):1226 def hook(resp, **kwargs):1227 resp.hook_working = True1228 return resp12291230 req = requests.Request("GET", httpbin(), hooks={"response": hook})1231 prep = req.prepare()12321233 s = requests.Session()1234 s.proxies = getproxies()1235 resp = s.send(prep)12361237 assert hasattr(resp, "hook_working")12381239 def test_prepared_from_session(self, httpbin):1240 class DummyAuth(requests.auth.AuthBase):1241 def __call__(self, r):1242 r.headers["Dummy-Auth-Test"] = "dummy-auth-test-ok"1243 return r12441245 req = requests.Request("GET", httpbin("headers"))1246 assert not req.auth12471248 s = requests.Session()1249 s.auth = DummyAuth()12501251 prep = s.prepare_request(req)1252 resp = s.send(prep)12531254 assert resp.json()["headers"]["Dummy-Auth-Test"] == "dummy-auth-test-ok"12551256 def test_prepare_request_with_bytestring_url(self):1257 req = requests.Request("GET", b"https://httpbin.org/")1258 s = requests.Session()1259 prep = s.prepare_request(req)1260 assert prep.url == "https://httpbin.org/"12611262 def test_request_with_bytestring_host(self, httpbin):1263 s = requests.Session()1264 resp = s.request(1265 "GET",1266 httpbin("cookies/set?cookie=value"),1267 allow_redirects=False,1268 headers={"Host": b"httpbin.org"},1269 )1270 assert resp.cookies.get("cookie") == "value"12711272 def test_links(self):1273 r = requests.Response()1274 r.headers = {1275 "cache-control": "public, max-age=60, s-maxage=60",1276 "connection": "keep-alive",1277 "content-encoding": "gzip",1278 "content-type": "application/json; charset=utf-8",1279 "date": "Sat, 26 Jan 2013 16:47:56 GMT",1280 "etag": '"6ff6a73c0e446c1f61614769e3ceb778"',1281 "last-modified": "Sat, 26 Jan 2013 16:22:39 GMT",1282 "link": (1283 "<https://api.github.com/users/kennethreitz/repos?"1284 'page=2&per_page=10>; rel="next", <https://api.github.'1285 "com/users/kennethreitz/repos?page=7&per_page=10>; "1286 ' rel="last"'1287 ),1288 "server": "GitHub.com",1289 "status": "200 OK",1290 "vary": "Accept",1291 "x-content-type-options": "nosniff",1292 "x-github-media-type": "github.beta",1293 "x-ratelimit-limit": "60",1294 "x-ratelimit-remaining": "57",1295 }1296 assert r.links["next"]["rel"] == "next"12971298 def test_cookie_parameters(self):1299 key = "some_cookie"1300 value = "some_value"1301 secure = True1302 domain = "test.com"1303 rest = {"HttpOnly": True}13041305 jar = requests.cookies.RequestsCookieJar()1306 jar.set(key, value, secure=secure, domain=domain, rest=rest)13071308 assert len(jar) == 11309 assert "some_cookie" in jar13101311 cookie = list(jar)[0]1312 assert cookie.secure == secure1313 assert cookie.domain == domain1314 assert cookie._rest["HttpOnly"] == rest["HttpOnly"]13151316 def test_cookie_as_dict_keeps_len(self):1317 key = "some_cookie"1318 value = "some_value"13191320 key1 = "some_cookie1"1321 value1 = "some_value1"13221323 jar = requests.cookies.RequestsCookieJar()1324 jar.set(key, value)1325 jar.set(key1, value1)13261327 d1 = dict(jar)1328 d2 = dict(jar.iteritems())1329 d3 = dict(jar.items())13301331 assert len(jar) == 21332 assert len(d1) == 21333 assert len(d2) == 21334 assert len(d3) == 213351336 def test_cookie_as_dict_keeps_items(self):1337 key = "some_cookie"1338 value = "some_value"13391340 key1 = "some_cookie1"1341 value1 = "some_value1"13421343 jar = requests.cookies.RequestsCookieJar()1344 jar.set(key, value)1345 jar.set(key1, value1)13461347 d1 = dict(jar)1348 d2 = dict(jar.iteritems())1349 d3 = dict(jar.items())13501351 assert d1["some_cookie"] == "some_value"1352 assert d2["some_cookie"] == "some_value"1353 assert d3["some_cookie1"] == "some_value1"13541355 def test_cookie_as_dict_keys(self):1356 key = "some_cookie"1357 value = "some_value"13581359 key1 = "some_cookie1"1360 value1 = "some_value1"13611362 jar = requests.cookies.RequestsCookieJar()1363 jar.set(key, value)1364 jar.set(key1, value1)13651366 keys = jar.keys()1367 assert keys == list(keys)1368 # make sure one can use keys multiple times1369 assert list(keys) == list(keys)13701371 def test_cookie_as_dict_values(self):1372 key = "some_cookie"1373 value = "some_value"13741375 key1 = "some_cookie1"1376 value1 = "some_value1"13771378 jar = requests.cookies.RequestsCookieJar()1379 jar.set(key, value)1380 jar.set(key1, value1)13811382 values = jar.values()1383 assert values == list(values)1384 # make sure one can use values multiple times1385 assert list(values) == list(values)13861387 def test_cookie_as_dict_items(self):1388 key = "some_cookie"1389 value = "some_value"13901391 key1 = "some_cookie1"1392 value1 = "some_value1"13931394 jar = requests.cookies.RequestsCookieJar()1395 jar.set(key, value)1396 jar.set(key1, value1)13971398 items = jar.items()1399 assert items == list(items)1400 # make sure one can use items multiple times1401 assert list(items) == list(items)14021403 def test_cookie_duplicate_names_different_domains(self):1404 key = "some_cookie"1405 value = "some_value"1406 domain1 = "test1.com"1407 domain2 = "test2.com"14081409 jar = requests.cookies.RequestsCookieJar()1410 jar.set(key, value, domain=domain1)1411 jar.set(key, value, domain=domain2)1412 assert key in jar1413 items = jar.items()1414 assert len(items) == 214151416 # Verify that CookieConflictError is raised if domain is not specified1417 with pytest.raises(requests.cookies.CookieConflictError):1418 jar.get(key)14191420 # Verify that CookieConflictError is not raised if domain is specified1421 cookie = jar.get(key, domain=domain1)1422 assert cookie == value14231424 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1425 key = "some_cookie"1426 value = "some_value"1427 path = "some_path"14281429 jar = requests.cookies.RequestsCookieJar()1430 jar.set(key, value, path=path)1431 jar.set(key, value)1432 with pytest.raises(requests.cookies.CookieConflictError):1433 jar.get(key)14341435 def test_cookie_policy_copy(self):1436 class MyCookiePolicy(cookielib.DefaultCookiePolicy):1437 pass14381439 jar = requests.cookies.RequestsCookieJar()1440 jar.set_policy(MyCookiePolicy())1441 assert isinstance(jar.copy().get_policy(), MyCookiePolicy)14421443 def test_time_elapsed_blank(self, httpbin):1444 r = requests.get(httpbin("get"))1445 td = r.elapsed1446 total_seconds = (1447 td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**61448 ) / 10**61449 assert total_seconds > 0.014501451 def test_empty_response_has_content_none(self):1452 r = requests.Response()1453 assert r.content is None14541455 def test_response_is_iterable(self):1456 r = requests.Response()1457 io = StringIO.StringIO("abc")1458 read_ = io.read14591460 def read_mock(amt, decode_content=None):1461 return read_(amt)14621463 setattr(io, "read", read_mock)1464 r.raw = io1465 assert next(iter(r))1466 io.close()14671468 def test_response_decode_unicode(self):1469 """When called with decode_unicode, Response.iter_content should always1470 return unicode.1471 """1472 r = requests.Response()1473 r._content_consumed = True1474 r._content = b"the content"1475 r.encoding = "ascii"14761477 chunks = r.iter_content(decode_unicode=True)1478 assert all(isinstance(chunk, str) for chunk in chunks)14791480 # also for streaming1481 r = requests.Response()1482 r.raw = io.BytesIO(b"the content")1483 r.encoding = "ascii"1484 chunks = r.iter_content(decode_unicode=True)1485 assert all(isinstance(chunk, str) for chunk in chunks)14861487 def test_response_reason_unicode(self):1488 # check for unicode HTTP status1489 r = requests.Response()1490 r.url = "unicode URL"1491 r.reason = "Komponenttia ei löydy".encode()1492 r.status_code = 4041493 r.encoding = None1494 assert not r.ok # old behaviour - crashes here14951496 def test_response_reason_unicode_fallback(self):1497 # check raise_status falls back to ISO-8859-11498 r = requests.Response()1499 r.url = "some url"1500 reason = "Komponenttia ei löydy"1501 r.reason = reason.encode("latin-1")1502 r.status_code = 5001503 r.encoding = None1504 with pytest.raises(requests.exceptions.HTTPError) as e:1505 r.raise_for_status()1506 assert reason in e.value.args[0]15071508 def test_response_chunk_size_type(self):1509 """Ensure that chunk_size is passed as None or an integer, otherwise1510 raise a TypeError.1511 """1512 r = requests.Response()1513 r.raw = io.BytesIO(b"the content")1514 chunks = r.iter_content(1)1515 assert all(len(chunk) == 1 for chunk in chunks)15161517 r = requests.Response()1518 r.raw = io.BytesIO(b"the content")1519 chunks = r.iter_content(None)1520 assert list(chunks) == [b"the content"]15211522 r = requests.Response()1523 r.raw = io.BytesIO(b"the content")1524 with pytest.raises(TypeError):1525 chunks = r.iter_content("1024")15261527 @pytest.mark.parametrize(1528 "exception, args, expected",1529 (1530 (urllib3.exceptions.ProtocolError, tuple(), ChunkedEncodingError),1531 (urllib3.exceptions.DecodeError, tuple(), ContentDecodingError),1532 (urllib3.exceptions.ReadTimeoutError, (None, "", ""), ConnectionError),1533 (urllib3.exceptions.SSLError, tuple(), RequestsSSLError),1534 ),1535 )1536 def test_iter_content_wraps_exceptions(self, httpbin, exception, args, expected):1537 r = requests.Response()1538 r.raw = mock.Mock()1539 # ReadTimeoutError can't be initialized by mock1540 # so we'll manually create the instance with args1541 r.raw.stream.side_effect = exception(*args)15421543 with pytest.raises(expected):1544 next(r.iter_content(1024))15451546 def test_request_and_response_are_pickleable(self, httpbin):1547 r = requests.get(httpbin("get"))15481549 # verify we can pickle the original request1550 assert pickle.loads(pickle.dumps(r.request))15511552 # verify we can pickle the response and that we have access to1553 # the original request.1554 pr = pickle.loads(pickle.dumps(r))1555 assert r.request.url == pr.request.url1556 assert r.request.headers == pr.request.headers15571558 def test_prepared_request_is_pickleable(self, httpbin):1559 p = requests.Request("GET", httpbin("get")).prepare()15601561 # Verify PreparedRequest can be pickled and unpickled1562 r = pickle.loads(pickle.dumps(p))1563 assert r.url == p.url1564 assert r.headers == p.headers1565 assert r.body == p.body15661567 # Verify unpickled PreparedRequest sends properly1568 s = requests.Session()1569 resp = s.send(r)1570 assert resp.status_code == 20015711572 def test_prepared_request_with_file_is_pickleable(self, httpbin):1573 with open(__file__, "rb") as f:1574 r = requests.Request("POST", httpbin("post"), files={"file": f})1575 p = r.prepare()15761577 # Verify PreparedRequest can be pickled and unpickled1578 r = pickle.loads(pickle.dumps(p))1579 assert r.url == p.url1580 assert r.headers == p.headers1581 assert r.body == p.body15821583 # Verify unpickled PreparedRequest sends properly1584 s = requests.Session()1585 resp = s.send(r)1586 assert resp.status_code == 20015871588 def test_prepared_request_with_hook_is_pickleable(self, httpbin):1589 r = requests.Request("GET", httpbin("get"), hooks=default_hooks())1590 p = r.prepare()15911592 # Verify PreparedRequest can be pickled1593 r = pickle.loads(pickle.dumps(p))1594 assert r.url == p.url1595 assert r.headers == p.headers1596 assert r.body == p.body1597 assert r.hooks == p.hooks15981599 # Verify unpickled PreparedRequest sends properly1600 s = requests.Session()1601 resp = s.send(r)1602 assert resp.status_code == 20016031604 def test_cannot_send_unprepared_requests(self, httpbin):1605 r = requests.Request(url=httpbin())1606 with pytest.raises(ValueError):1607 requests.Session().send(r)16081609 def test_http_error(self):1610 error = requests.exceptions.HTTPError()1611 assert not error.response1612 response = requests.Response()1613 error = requests.exceptions.HTTPError(response=response)1614 assert error.response == response1615 error = requests.exceptions.HTTPError("message", response=response)1616 assert str(error) == "message"1617 assert error.response == response16181619 def test_session_pickling(self, httpbin):1620 r = requests.Request("GET", httpbin("get"))1621 s = requests.Session()16221623 s = pickle.loads(pickle.dumps(s))1624 s.proxies = getproxies()16251626 r = s.send(r.prepare())1627 assert r.status_code == 20016281629 def test_fixes_1329(self, httpbin):1630 """Ensure that header updates are done case-insensitively."""1631 s = requests.Session()1632 s.headers.update({"ACCEPT": "BOGUS"})1633 s.headers.update({"accept": "application/json"})1634 r = s.get(httpbin("get"))1635 headers = r.request.headers1636 assert headers["accept"] == "application/json"1637 assert headers["Accept"] == "application/json"1638 assert headers["ACCEPT"] == "application/json"16391640 def test_uppercase_scheme_redirect(self, httpbin):1641 parts = urlparse(httpbin("html"))1642 url = "HTTP://" + parts.netloc + parts.path1643 r = requests.get(httpbin("redirect-to"), params={"url": url})1644 assert r.status_code == 2001645 assert r.url.lower() == url.lower()16461647 def test_transport_adapter_ordering(self):1648 s = requests.Session()1649 order = ["https://", "http://"]1650 assert order == list(s.adapters)1651 s.mount("http://git", HTTPAdapter())1652 s.mount("http://github", HTTPAdapter())1653 s.mount("http://github.com", HTTPAdapter())1654 s.mount("http://github.com/about/", HTTPAdapter())1655 order = [1656 "http://github.com/about/",1657 "http://github.com",1658 "http://github",1659 "http://git",1660 "https://",1661 "http://",1662 ]1663 assert order == list(s.adapters)1664 s.mount("http://gittip", HTTPAdapter())1665 s.mount("http://gittip.com", HTTPAdapter())1666 s.mount("http://gittip.com/about/", HTTPAdapter())1667 order = [1668 "http://github.com/about/",1669 "http://gittip.com/about/",1670 "http://github.com",1671 "http://gittip.com",1672 "http://github",1673 "http://gittip",1674 "http://git",1675 "https://",1676 "http://",1677 ]1678 assert order == list(s.adapters)1679 s2 = requests.Session()1680 s2.adapters = {"http://": HTTPAdapter()}1681 s2.mount("https://", HTTPAdapter())1682 assert "http://" in s2.adapters1683 assert "https://" in s2.adapters16841685 def test_session_get_adapter_prefix_matching(self):1686 prefix = "https://example.com"1687 more_specific_prefix = prefix + "/some/path"16881689 url_matching_only_prefix = prefix + "/another/path"1690 url_matching_more_specific_prefix = more_specific_prefix + "/longer/path"1691 url_not_matching_prefix = "https://another.example.com/"16921693 s = requests.Session()1694 prefix_adapter = HTTPAdapter()1695 more_specific_prefix_adapter = HTTPAdapter()1696 s.mount(prefix, prefix_adapter)1697 s.mount(more_specific_prefix, more_specific_prefix_adapter)16981699 assert s.get_adapter(url_matching_only_prefix) is prefix_adapter1700 assert (1701 s.get_adapter(url_matching_more_specific_prefix)1702 is more_specific_prefix_adapter1703 )1704 assert s.get_adapter(url_not_matching_prefix) not in (1705 prefix_adapter,1706 more_specific_prefix_adapter,1707 )17081709 def test_session_get_adapter_prefix_matching_mixed_case(self):1710 mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"1711 url_matching_prefix = mixed_case_prefix + "/full_url"17121713 s = requests.Session()1714 my_adapter = HTTPAdapter()1715 s.mount(mixed_case_prefix, my_adapter)17161717 assert s.get_adapter(url_matching_prefix) is my_adapter17181719 def test_session_get_adapter_prefix_matching_is_case_insensitive(self):1720 mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"1721 url_matching_prefix_with_different_case = (1722 "HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url"1723 )17241725 s = requests.Session()1726 my_adapter = HTTPAdapter()1727 s.mount(mixed_case_prefix, my_adapter)17281729 assert s.get_adapter(url_matching_prefix_with_different_case) is my_adapter17301731 def test_session_get_adapter_prefix_with_trailing_slash(self):1732 # from issue #69351733 prefix = "https://example.com/" # trailing slash1734 url_matching_prefix = "https://example.com/some/path"1735 url_not_matching_prefix = "https://example.com.other.com/some/path"17361737 s = requests.Session()1738 adapter = HTTPAdapter()1739 s.mount(prefix, adapter)17401741 assert s.get_adapter(url_matching_prefix) is adapter1742 assert s.get_adapter(url_not_matching_prefix) is not adapter17431744 def test_session_get_adapter_prefix_without_trailing_slash(self):1745 # from issue #69351746 prefix = "https://example.com" # no trailing slash1747 url_matching_prefix = "https://example.com/some/path"1748 url_extended_hostname = "https://example.com.other.com/some/path"17491750 s = requests.Session()1751 adapter = HTTPAdapter()1752 s.mount(prefix, adapter)17531754 assert s.get_adapter(url_matching_prefix) is adapter1755 assert s.get_adapter(url_extended_hostname) is adapter17561757 def test_header_remove_is_case_insensitive(self, httpbin):1758 # From issue #13211759 s = requests.Session()1760 s.headers["foo"] = "bar"1761 r = s.get(httpbin("get"), headers={"FOO": None})1762 assert "foo" not in r.request.headers17631764 def test_params_are_merged_case_sensitive(self, httpbin):1765 s = requests.Session()1766 s.params["foo"] = "bar"1767 r = s.get(httpbin("get"), params={"FOO": "bar"})1768 assert r.json()["args"] == {"foo": "bar", "FOO": "bar"}17691770 def test_long_authinfo_in_url(self):1771 url = "http://{}:{}@{}:9000/path?query#frag".format(1772 "E8A3BE87-9E3F-4620-8858-95478E385B5B",1773 "EA770032-DA4D-4D84-8CE9-29C6D910BF1E",1774 "exactly-------------sixty-----------three------------characters",1775 )1776 r = requests.Request("GET", url).prepare()1777 assert r.url == url17781779 def test_header_keys_are_native(self, httpbin):1780 headers = {"unicode": "blah", b"byte": "blah"}1781 r = requests.Request("GET", httpbin("get"), headers=headers)1782 p = r.prepare()17831784 # This is testing that they are builtin strings. A bit weird, but there1785 # we go.1786 assert "unicode" in p.headers.keys()1787 assert "byte" in p.headers.keys()17881789 def test_header_validation(self, httpbin):1790 """Ensure prepare_headers regex isn't flagging valid header contents."""1791 valid_headers = {1792 "foo": "bar baz qux",1793 "bar": b"fbbq",1794 "baz": "",1795 "qux": "1",1796 }1797 r = requests.get(httpbin("get"), headers=valid_headers)1798 for key in valid_headers.keys():1799 assert valid_headers[key] == r.request.headers[key]18001801 @pytest.mark.parametrize(1802 "invalid_header, key",1803 (1804 ({"foo": 3}, "foo"),1805 ({"bar": {"foo": "bar"}}, "bar"),1806 ({"baz": ["foo", "bar"]}, "baz"),1807 ),1808 )1809 def test_header_value_not_str(self, httpbin, invalid_header, key):1810 """Ensure the header value is of type string or bytes as1811 per discussion in GH issue #33861812 """1813 with pytest.raises(InvalidHeader) as excinfo:1814 requests.get(httpbin("get"), headers=invalid_header)1815 assert key in str(excinfo.value)18161817 @pytest.mark.parametrize(1818 "invalid_header",1819 (1820 {"foo": "bar\r\nbaz: qux"},1821 {"foo": "bar\n\rbaz: qux"},1822 {"foo": "bar\nbaz: qux"},1823 {"foo": "bar\rbaz: qux"},1824 {"fo\ro": "bar"},1825 {"fo\r\no": "bar"},1826 {"fo\n\ro": "bar"},1827 {"fo\no": "bar"},1828 {"foo": "bar\n"},1829 {"foo\n": "bar"},1830 {"foo": "bar\r\n"},1831 {"foo": "\n"},1832 {"foo": "\r\n"},1833 ),1834 )1835 def test_header_no_return_chars(self, httpbin, invalid_header):1836 """Ensure that a header containing return character sequences raise an1837 exception. Otherwise, multiple headers are created from single string.1838 """1839 with pytest.raises(InvalidHeader):1840 requests.get(httpbin("get"), headers=invalid_header)18411842 @pytest.mark.parametrize(1843 "invalid_header",1844 (1845 {" foo": "bar"},1846 {"\tfoo": "bar"},1847 {" foo": "bar"},1848 {"foo": " bar"},1849 {"foo": " bar"},1850 {"foo": "\tbar"},1851 {" ": "bar"},1852 ),1853 )1854 def test_header_no_leading_space(self, httpbin, invalid_header):1855 """Ensure headers containing leading whitespace raise1856 InvalidHeader Error before sending.1857 """1858 with pytest.raises(InvalidHeader):1859 requests.get(httpbin("get"), headers=invalid_header)18601861 def test_header_with_subclass_types(self, httpbin):1862 """If the subclasses does not behave *exactly* like1863 the base bytes/str classes, this is not supported.1864 This test is for backwards compatibility.1865 """18661867 class MyString(str):1868 pass18691870 class MyBytes(bytes):1871 pass18721873 r_str = requests.get(httpbin("get"), headers={MyString("x-custom"): "myheader"})1874 assert r_str.request.headers["x-custom"] == "myheader"18751876 r_bytes = requests.get(1877 httpbin("get"), headers={MyBytes(b"x-custom"): b"myheader"}1878 )1879 assert r_bytes.request.headers["x-custom"] == b"myheader"18801881 r_mixed = requests.get(1882 httpbin("get"), headers={MyString("x-custom"): MyBytes(b"myheader")}1883 )1884 assert r_mixed.request.headers["x-custom"] == b"myheader"18851886 @pytest.mark.parametrize("files", ("foo", b"foo", bytearray(b"foo")))1887 def test_can_send_objects_with_files(self, httpbin, files):1888 data = {"a": "this is a string"}1889 files = {"b": files}1890 r = requests.Request("POST", httpbin("post"), data=data, files=files)1891 p = r.prepare()1892 assert "multipart/form-data" in p.headers["Content-Type"]18931894 def test_can_send_file_object_with_non_string_filename(self, httpbin):1895 f = io.BytesIO()1896 f.name = 21897 r = requests.Request("POST", httpbin("post"), files={"f": f})1898 p = r.prepare()18991900 assert "multipart/form-data" in p.headers["Content-Type"]19011902 def test_autoset_header_values_are_native(self, httpbin):1903 data = "this is a string"1904 length = "16"1905 req = requests.Request("POST", httpbin("post"), data=data)1906 p = req.prepare()19071908 assert p.headers["Content-Length"] == length19091910 def test_nonhttp_schemes_dont_check_URLs(self):1911 test_urls = (1912 "data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",1913 "file:///etc/passwd",1914 "magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431",1915 )1916 for test_url in test_urls:1917 req = requests.Request("GET", test_url)1918 preq = req.prepare()1919 assert test_url == preq.url19201921 def test_auth_is_stripped_on_http_downgrade(1922 self, httpbin, httpbin_secure, httpbin_ca_bundle1923 ):1924 r = requests.get(1925 httpbin_secure("redirect-to"),1926 params={"url": httpbin("get")},1927 auth=("user", "pass"),1928 verify=httpbin_ca_bundle,1929 )1930 assert r.history[0].request.headers["Authorization"]1931 assert "Authorization" not in r.request.headers19321933 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1934 r = requests.get(httpbin("redirect/1"), auth=("user", "pass"))1935 h1 = r.history[0].request.headers["Authorization"]1936 h2 = r.request.headers["Authorization"]19371938 assert h1 == h219391940 def test_should_strip_auth_host_change(self):1941 s = requests.Session()1942 assert s.should_strip_auth(1943 "http://example.com/foo", "http://another.example.com/"1944 )19451946 def test_should_strip_auth_http_downgrade(self):1947 s = requests.Session()1948 assert s.should_strip_auth("https://example.com/foo", "http://example.com/bar")19491950 def test_should_strip_auth_https_upgrade(self):1951 s = requests.Session()1952 assert not s.should_strip_auth(1953 "http://example.com/foo", "https://example.com/bar"1954 )1955 assert not s.should_strip_auth(1956 "http://example.com:80/foo", "https://example.com/bar"1957 )1958 assert not s.should_strip_auth(1959 "http://example.com/foo", "https://example.com:443/bar"1960 )1961 # Non-standard ports should trigger stripping1962 assert s.should_strip_auth(1963 "http://example.com:8080/foo", "https://example.com/bar"1964 )1965 assert s.should_strip_auth(1966 "http://example.com/foo", "https://example.com:8443/bar"1967 )19681969 def test_should_strip_auth_port_change(self):1970 s = requests.Session()1971 assert s.should_strip_auth(1972 "http://example.com:1234/foo", "https://example.com:4321/bar"1973 )19741975 @pytest.mark.parametrize(1976 "old_uri, new_uri",1977 (1978 ("https://example.com:443/foo", "https://example.com/bar"),1979 ("http://example.com:80/foo", "http://example.com/bar"),1980 ("https://example.com/foo", "https://example.com:443/bar"),1981 ("http://example.com/foo", "http://example.com:80/bar"),1982 ),1983 )1984 def test_should_strip_auth_default_port(self, old_uri, new_uri):1985 s = requests.Session()1986 assert not s.should_strip_auth(old_uri, new_uri)19871988 def test_manual_redirect_with_partial_body_read(self, httpbin):1989 s = requests.Session()1990 r1 = s.get(httpbin("redirect/2"), allow_redirects=False, stream=True)1991 assert r1.is_redirect1992 rg = s.resolve_redirects(r1, r1.request, stream=True)19931994 # read only the first eight bytes of the response body,1995 # then follow the redirect1996 r1.iter_content(8)1997 r2 = next(rg)1998 assert r2.is_redirect19992000 # read all of the response via iter_content,The first 2,000 of 3,094 lines.