test_requests.py
This file
Path
tests/test_requests.py
3,039 lines · 104.1 KiB · Python
Last changed by
Fix CI and build failures (#7190)Nate Prewittbefore adoptionf8bec2f
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_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):221 r = requests.post(222 httpbin("redirect-to"),223 data="test",224 params={"url": "post", "status_code": 307},225 )226 assert r.status_code == 200227 assert r.history[0].status_code == 307228 assert r.history[0].is_redirect229 assert r.json()["data"] == "test"230231 def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):232 byte_str = b"test"233 r = requests.post(234 httpbin("redirect-to"),235 data=io.BytesIO(byte_str),236 params={"url": "post", "status_code": 307},237 )238 assert r.status_code == 200239 assert r.history[0].status_code == 307240 assert r.history[0].is_redirect241 assert r.json()["data"] == byte_str.decode("utf-8")242243 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):244 try:245 requests.get(httpbin("relative-redirect", "50"))246 except TooManyRedirects as e:247 url = httpbin("relative-redirect", "20")248 assert e.request.url == url249 assert e.response.url == url250 assert len(e.response.history) == 30251 else:252 pytest.fail("Expected redirect to raise TooManyRedirects but it did not")253254 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):255 s = requests.session()256 s.max_redirects = 5257 try:258 s.get(httpbin("relative-redirect", "50"))259 except TooManyRedirects as e:260 url = httpbin("relative-redirect", "45")261 assert e.request.url == url262 assert e.response.url == url263 assert len(e.response.history) == 5264 else:265 pytest.fail(266 "Expected custom max number of redirects to be respected but was not"267 )268269 def test_http_301_changes_post_to_get(self, httpbin):270 r = requests.post(httpbin("status", "301"))271 assert r.status_code == 200272 assert r.request.method == "GET"273 assert r.history[0].status_code == 301274 assert r.history[0].is_redirect275276 def test_http_301_doesnt_change_head_to_get(self, httpbin):277 r = requests.head(httpbin("status", "301"), allow_redirects=True)278 print(r.content)279 assert r.status_code == 200280 assert r.request.method == "HEAD"281 assert r.history[0].status_code == 301282 assert r.history[0].is_redirect283284 def test_http_302_changes_post_to_get(self, httpbin):285 r = requests.post(httpbin("status", "302"))286 assert r.status_code == 200287 assert r.request.method == "GET"288 assert r.history[0].status_code == 302289 assert r.history[0].is_redirect290291 def test_http_302_doesnt_change_head_to_get(self, httpbin):292 r = requests.head(httpbin("status", "302"), allow_redirects=True)293 assert r.status_code == 200294 assert r.request.method == "HEAD"295 assert r.history[0].status_code == 302296 assert r.history[0].is_redirect297298 def test_http_303_changes_post_to_get(self, httpbin):299 r = requests.post(httpbin("status", "303"))300 assert r.status_code == 200301 assert r.request.method == "GET"302 assert r.history[0].status_code == 303303 assert r.history[0].is_redirect304305 def test_http_303_doesnt_change_head_to_get(self, httpbin):306 r = requests.head(httpbin("status", "303"), allow_redirects=True)307 assert r.status_code == 200308 assert r.request.method == "HEAD"309 assert r.history[0].status_code == 303310 assert r.history[0].is_redirect311312 def test_header_and_body_removal_on_redirect(self, httpbin):313 purged_headers = ("Content-Length", "Content-Type")314 ses = requests.Session()315 req = requests.Request("POST", httpbin("post"), data={"test": "data"})316 prep = ses.prepare_request(req)317 resp = ses.send(prep)318319 # Mimic a redirect response320 resp.status_code = 302321 resp.headers["location"] = "get"322323 # Run request through resolve_redirects324 next_resp = next(ses.resolve_redirects(resp, prep))325 assert next_resp.request.body is None326 for header in purged_headers:327 assert header not in next_resp.request.headers328329 def test_transfer_enc_removal_on_redirect(self, httpbin):330 purged_headers = ("Transfer-Encoding", "Content-Type")331 ses = requests.Session()332 req = requests.Request("POST", httpbin("post"), data=(b"x" for x in range(1)))333 prep = ses.prepare_request(req)334 assert "Transfer-Encoding" in prep.headers335336 # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33337 resp = requests.Response()338 resp.raw = io.BytesIO(b"the content")339 resp.request = prep340 setattr(resp.raw, "release_conn", lambda *args: args)341342 # Mimic a redirect response343 resp.status_code = 302344 resp.headers["location"] = httpbin("get")345346 # Run request through resolve_redirect347 next_resp = next(ses.resolve_redirects(resp, prep))348 assert next_resp.request.body is None349 for header in purged_headers:350 assert header not in next_resp.request.headers351352 def test_fragment_maintained_on_redirect(self, httpbin):353 fragment = "#view=edit&token=hunter2"354 r = requests.get(httpbin("redirect-to?url=get") + fragment)355356 assert len(r.history) > 0357 assert r.history[0].request.url == httpbin("redirect-to?url=get") + fragment358 assert r.url == httpbin("get") + fragment359360 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):361 heads = {"User-agent": "Mozilla/5.0"}362363 r = requests.get(httpbin("user-agent"), headers=heads)364365 assert heads["User-agent"] in r.text366 assert r.status_code == 200367368 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):369 heads = {"User-agent": "Mozilla/5.0"}370371 r = requests.get(372 httpbin("get") + "?test=true", params={"q": "test"}, headers=heads373 )374 assert r.status_code == 200375376 def test_set_cookie_on_301(self, httpbin):377 s = requests.session()378 url = httpbin("cookies/set?foo=bar")379 s.get(url)380 assert s.cookies["foo"] == "bar"381382 def test_cookie_sent_on_redirect(self, httpbin):383 s = requests.session()384 s.get(httpbin("cookies/set?foo=bar"))385 r = s.get(httpbin("redirect/1")) # redirects to httpbin('get')386 assert "Cookie" in r.json()["headers"]387388 def test_cookie_removed_on_expire(self, httpbin):389 s = requests.session()390 s.get(httpbin("cookies/set?foo=bar"))391 assert s.cookies["foo"] == "bar"392 s.get(393 httpbin("response-headers"),394 params={"Set-Cookie": "foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT"},395 )396 assert "foo" not in s.cookies397398 def test_cookie_quote_wrapped(self, httpbin):399 s = requests.session()400 s.get(httpbin('cookies/set?foo="bar:baz"'))401 assert s.cookies["foo"] == '"bar:baz"'402403 def test_cookie_persists_via_api(self, httpbin):404 s = requests.session()405 r = s.get(httpbin("redirect/1"), cookies={"foo": "bar"})406 assert "foo" in r.request.headers["Cookie"]407 assert "foo" in r.history[0].request.headers["Cookie"]408409 def test_request_cookie_overrides_session_cookie(self, httpbin):410 s = requests.session()411 s.cookies["foo"] = "bar"412 r = s.get(httpbin("cookies"), cookies={"foo": "baz"})413 assert r.json()["cookies"]["foo"] == "baz"414 # Session cookie should not be modified415 assert s.cookies["foo"] == "bar"416417 def test_request_cookies_not_persisted(self, httpbin):418 s = requests.session()419 s.get(httpbin("cookies"), cookies={"foo": "baz"})420 # Sending a request with cookies should not add cookies to the session421 assert not s.cookies422423 def test_generic_cookiejar_works(self, httpbin):424 cj = cookielib.CookieJar()425 cookiejar_from_dict({"foo": "bar"}, cj)426 s = requests.session()427 s.cookies = cj428 r = s.get(httpbin("cookies"))429 # Make sure the cookie was sent430 assert r.json()["cookies"]["foo"] == "bar"431 # Make sure the session cj is still the custom one432 assert s.cookies is cj433434 def test_param_cookiejar_works(self, httpbin):435 cj = cookielib.CookieJar()436 cookiejar_from_dict({"foo": "bar"}, cj)437 s = requests.session()438 r = s.get(httpbin("cookies"), cookies=cj)439 # Make sure the cookie was sent440 assert r.json()["cookies"]["foo"] == "bar"441442 def test_cookielib_cookiejar_on_redirect(self, httpbin):443 """Tests resolve_redirect doesn't fail when merging cookies444 with non-RequestsCookieJar cookiejar.445446 See GH #3579447 """448 cj = cookiejar_from_dict({"foo": "bar"}, cookielib.CookieJar())449 s = requests.Session()450 s.cookies = cookiejar_from_dict({"cookie": "tasty"})451452 # Prepare request without using Session453 req = requests.Request("GET", httpbin("headers"), cookies=cj)454 prep_req = req.prepare()455456 # Send request and simulate redirect457 resp = s.send(prep_req)458 resp.status_code = 302459 resp.headers["location"] = httpbin("get")460 redirects = s.resolve_redirects(resp, prep_req)461 resp = next(redirects)462463 # Verify CookieJar isn't being converted to RequestsCookieJar464 assert isinstance(prep_req._cookies, cookielib.CookieJar)465 assert isinstance(resp.request._cookies, cookielib.CookieJar)466 assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)467468 cookies = {}469 for c in resp.request._cookies:470 cookies[c.name] = c.value471 assert cookies["foo"] == "bar"472 assert cookies["cookie"] == "tasty"473474 def test_requests_in_history_are_not_overridden(self, httpbin):475 resp = requests.get(httpbin("redirect/3"))476 urls = [r.url for r in resp.history]477 req_urls = [r.request.url for r in resp.history]478 assert urls == req_urls479480 def test_history_is_always_a_list(self, httpbin):481 """Show that even with redirects, Response.history is always a list."""482 resp = requests.get(httpbin("get"))483 assert isinstance(resp.history, list)484 resp = requests.get(httpbin("redirect/1"))485 assert isinstance(resp.history, list)486 assert not isinstance(resp.history, tuple)487488 def test_headers_on_session_with_None_are_not_sent(self, httpbin):489 """Do not send headers in Session.headers with None values."""490 ses = requests.Session()491 ses.headers["Accept-Encoding"] = None492 req = requests.Request("GET", httpbin("get"))493 prep = ses.prepare_request(req)494 assert "Accept-Encoding" not in prep.headers495496 def test_headers_preserve_order(self, httpbin):497 """Preserve order when headers provided as OrderedDict."""498 ses = requests.Session()499 ses.headers = collections.OrderedDict()500 ses.headers["Accept-Encoding"] = "identity"501 ses.headers["First"] = "1"502 ses.headers["Second"] = "2"503 headers = collections.OrderedDict([("Third", "3"), ("Fourth", "4")])504 headers["Fifth"] = "5"505 headers["Second"] = "222"506 req = requests.Request("GET", httpbin("get"), headers=headers)507 prep = ses.prepare_request(req)508 items = list(prep.headers.items())509 assert items[0] == ("Accept-Encoding", "identity")510 assert items[1] == ("First", "1")511 assert items[2] == ("Second", "222")512 assert items[3] == ("Third", "3")513 assert items[4] == ("Fourth", "4")514 assert items[5] == ("Fifth", "5")515516 @pytest.mark.parametrize("key", ("User-agent", "user-agent"))517 def test_user_agent_transfers(self, httpbin, key):518 heads = {key: "Mozilla/5.0 (github.com/psf/requests)"}519520 r = requests.get(httpbin("user-agent"), headers=heads)521 assert heads[key] in r.text522523 def test_HTTP_200_OK_HEAD(self, httpbin):524 r = requests.head(httpbin("get"))525 assert r.status_code == 200526527 def test_HTTP_200_OK_PUT(self, httpbin):528 r = requests.put(httpbin("put"))529 assert r.status_code == 200530531 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):532 auth = ("user", "pass")533 url = httpbin("basic-auth", "user", "pass")534535 r = requests.get(url, auth=auth)536 assert r.status_code == 200537538 r = requests.get(url)539 assert r.status_code == 401540541 s = requests.session()542 s.auth = auth543 r = s.get(url)544 assert r.status_code == 200545546 @pytest.mark.parametrize(547 "username, password",548 (549 ("user", "pass"),550 ("имя".encode(), "пароль".encode()),551 (42, 42),552 (None, None),553 ),554 )555 def test_set_basicauth(self, httpbin, username, password):556 auth = (username, password)557 url = httpbin("get")558559 r = requests.Request("GET", url, auth=auth)560 p = r.prepare()561562 assert p.headers["Authorization"] == _basic_auth_str(username, password)563564 def test_basicauth_encodes_byte_strings(self):565 """Ensure b'test' formats as the byte string "test" rather566 than the unicode string "b'test'" in Python 3.567 """568 auth = (b"\xc5\xafsername", b"test\xc6\xb6")569 r = requests.Request("GET", "http://localhost", auth=auth)570 p = r.prepare()571572 assert p.headers["Authorization"] == "Basic xa9zZXJuYW1lOnRlc3TGtg=="573574 @pytest.mark.parametrize(575 "url, exception",576 (577 # Connecting to an unknown domain should raise a ConnectionError578 ("http://doesnotexist.google.com", ConnectionError),579 # Connecting to an invalid port should raise a ConnectionError580 ("http://localhost:1", ConnectionError),581 # Inputing a URL that cannot be parsed should raise an InvalidURL error582 ("http://fe80::5054:ff:fe5a:fc0", InvalidURL),583 ),584 )585 def test_errors(self, url, exception):586 with pytest.raises(exception):587 requests.get(url, timeout=1)588589 def test_proxy_error(self):590 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError591 with pytest.raises(ProxyError):592 requests.get(593 "http://localhost:1", proxies={"http": "non-resolvable-address"}594 )595596 def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):597 with pytest.raises(InvalidProxyURL):598 requests.get(httpbin_secure(), proxies={"https": "http:/badproxyurl:3128"})599600 with pytest.raises(InvalidProxyURL):601 requests.get(httpbin(), proxies={"http": "http://:8080"})602603 with pytest.raises(InvalidProxyURL):604 requests.get(httpbin_secure(), proxies={"https": "https://"})605606 with pytest.raises(InvalidProxyURL):607 requests.get(httpbin(), proxies={"http": "http:///example.com:8080"})608609 def test_respect_proxy_env_on_send_self_prepared_request(self, httpbin):610 with override_environ(http_proxy=INVALID_PROXY):611 with pytest.raises(ProxyError):612 session = requests.Session()613 request = requests.Request("GET", httpbin())614 session.send(request.prepare())615616 def test_respect_proxy_env_on_send_session_prepared_request(self, httpbin):617 with override_environ(http_proxy=INVALID_PROXY):618 with pytest.raises(ProxyError):619 session = requests.Session()620 request = requests.Request("GET", httpbin())621 prepared = session.prepare_request(request)622 session.send(prepared)623624 def test_respect_proxy_env_on_send_with_redirects(self, httpbin):625 with override_environ(http_proxy=INVALID_PROXY):626 with pytest.raises(ProxyError):627 session = requests.Session()628 url = httpbin("redirect/1")629 print(url)630 request = requests.Request("GET", url)631 session.send(request.prepare())632633 def test_respect_proxy_env_on_get(self, httpbin):634 with override_environ(http_proxy=INVALID_PROXY):635 with pytest.raises(ProxyError):636 session = requests.Session()637 session.get(httpbin())638639 def test_respect_proxy_env_on_request(self, httpbin):640 with override_environ(http_proxy=INVALID_PROXY):641 with pytest.raises(ProxyError):642 session = requests.Session()643 session.request(method="GET", url=httpbin())644645 def test_proxy_authorization_preserved_on_request(self, httpbin):646 proxy_auth_value = "Bearer XXX"647 session = requests.Session()648 session.headers.update({"Proxy-Authorization": proxy_auth_value})649 resp = session.request(method="GET", url=httpbin("get"))650 sent_headers = resp.json().get("headers", {})651652 assert sent_headers.get("Proxy-Authorization") == proxy_auth_value653654 @pytest.mark.parametrize(655 "url,has_proxy_auth",656 (657 ("http://example.com", True),658 ("https://example.com", False),659 ),660 )661 def test_proxy_authorization_not_appended_to_https_request(662 self, url, has_proxy_auth663 ):664 session = requests.Session()665 proxies = {666 "http": "http://test:pass@localhost:8080",667 "https": "http://test:pass@localhost:8090",668 }669 req = requests.Request("GET", url)670 prep = req.prepare()671 session.rebuild_proxies(prep, proxies)672673 assert ("Proxy-Authorization" in prep.headers) is has_proxy_auth674675 def test_basicauth_with_netrc(self, httpbin):676 auth = ("user", "pass")677 wrong_auth = ("wronguser", "wrongpass")678 url = httpbin("basic-auth", "user", "pass")679680 old_auth = requests.sessions.get_netrc_auth681682 try:683684 def get_netrc_auth_mock(url):685 return auth686687 requests.sessions.get_netrc_auth = get_netrc_auth_mock688689 # Should use netrc and work.690 r = requests.get(url)691 assert r.status_code == 200692693 # Given auth should override and fail.694 r = requests.get(url, auth=wrong_auth)695 assert r.status_code == 401696697 s = requests.session()698699 # Should use netrc and work.700 r = s.get(url)701 assert r.status_code == 200702703 # Given auth should override and fail.704 s.auth = wrong_auth705 r = s.get(url)706 assert r.status_code == 401707 finally:708 requests.sessions.get_netrc_auth = old_auth709710 def test_basicauth_with_netrc_leak(self, httpbin):711 url1 = httpbin("basic-auth", "user", "pass")712 url = url1[len("http://") :]713 domain = url.split(":")[0]714 url = f"http://example.com:@{url}"715716 netrc_file = ""717 with tempfile.NamedTemporaryFile(mode="w", delete=False) as fp:718 fp.write("machine example.com\n")719 fp.write("login wronguser\n")720 fp.write("password wrongpass\n")721 fp.write(f"machine {domain}\n")722 fp.write("login user\n")723 fp.write("password pass\n")724 fp.close()725 netrc_file = fp.name726727 old_netrc = os.environ.get("NETRC", "")728 os.environ["NETRC"] = netrc_file729730 try:731 # Should use netrc732 # Make sure that we don't use the example.com credentails733 # for the request734 r = requests.get(url)735 assert r.status_code == 200736 finally:737 os.environ["NETRC"] = old_netrc738 os.unlink(netrc_file)739740 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):741 for authtype in self.digest_auth_algo:742 auth = HTTPDigestAuth("user", "pass")743 url = httpbin("digest-auth", "auth", "user", "pass", authtype, "never")744745 r = requests.get(url, auth=auth)746 assert r.status_code == 200747748 r = requests.get(url)749 assert r.status_code == 401750 print(r.headers["WWW-Authenticate"])751752 s = requests.session()753 s.auth = HTTPDigestAuth("user", "pass")754 r = s.get(url)755 assert r.status_code == 200756757 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):758 for authtype in self.digest_auth_algo:759 url = httpbin("digest-auth", "auth", "user", "pass", authtype)760 auth = HTTPDigestAuth("user", "pass")761 r = requests.get(url)762 assert r.cookies["fake"] == "fake_value"763764 r = requests.get(url, auth=auth)765 assert r.status_code == 200766767 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):768 for authtype in self.digest_auth_algo:769 url = httpbin("digest-auth", "auth", "user", "pass", authtype)770 auth = HTTPDigestAuth("user", "pass")771 s = requests.Session()772 s.get(url, auth=auth)773 assert s.cookies["fake"] == "fake_value"774775 def test_DIGEST_STREAM(self, httpbin):776 for authtype in self.digest_auth_algo:777 auth = HTTPDigestAuth("user", "pass")778 url = httpbin("digest-auth", "auth", "user", "pass", authtype)779780 r = requests.get(url, auth=auth, stream=True)781 assert r.raw.read() != b""782783 r = requests.get(url, auth=auth, stream=False)784 assert r.raw.read() == b""785786 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):787 for authtype in self.digest_auth_algo:788 auth = HTTPDigestAuth("user", "wrongpass")789 url = httpbin("digest-auth", "auth", "user", "pass", authtype)790791 r = requests.get(url, auth=auth)792 assert r.status_code == 401793794 r = requests.get(url)795 assert r.status_code == 401796797 s = requests.session()798 s.auth = auth799 r = s.get(url)800 assert r.status_code == 401801802 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):803 for authtype in self.digest_auth_algo:804 auth = HTTPDigestAuth("user", "pass")805 url = httpbin("digest-auth", "auth", "user", "pass", authtype)806807 r = requests.get(url, auth=auth)808 assert '"auth"' in r.request.headers["Authorization"]809810 def test_POSTBIN_GET_POST_FILES(self, httpbin):811 url = httpbin("post")812 requests.post(url).raise_for_status()813814 post1 = requests.post(url, data={"some": "data"})815 assert post1.status_code == 200816817 with open("requirements-dev.txt") as f:818 post2 = requests.post(url, files={"some": f})819 assert post2.status_code == 200820821 post4 = requests.post(url, data='[{"some": "json"}]')822 assert post4.status_code == 200823824 with pytest.raises(ValueError):825 requests.post(url, files=["bad file data"])826827 def test_invalid_files_input(self, httpbin):828 url = httpbin("post")829 post = requests.post(url, files={"random-file-1": None, "random-file-2": 1})830 assert b'name="random-file-1"' not in post.request.body831 assert b'name="random-file-2"' in post.request.body832833 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):834 class TestStream:835 def __init__(self, data):836 self.data = data.encode()837 self.length = len(self.data)838 self.index = 0839840 def __len__(self):841 return self.length842843 def read(self, size=None):844 if size:845 ret = self.data[self.index : self.index + size]846 self.index += size847 else:848 ret = self.data[self.index :]849 self.index = self.length850 return ret851852 def tell(self):853 return self.index854855 def seek(self, offset, where=0):856 if where == 0:857 self.index = offset858 elif where == 1:859 self.index += offset860 elif where == 2:861 self.index = self.length + offset862863 test = TestStream("test")864 post1 = requests.post(httpbin("post"), data=test)865 assert post1.status_code == 200866 assert post1.json()["data"] == "test"867868 test = TestStream("test")869 test.seek(2)870 post2 = requests.post(httpbin("post"), data=test)871 assert post2.status_code == 200872 assert post2.json()["data"] == "st"873874 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):875 url = httpbin("post")876 requests.post(url).raise_for_status()877878 post1 = requests.post(url, data={"some": "data"})879 assert post1.status_code == 200880881 with open("requirements-dev.txt") as f:882 post2 = requests.post(url, data={"some": "data"}, files={"some": f})883 assert post2.status_code == 200884885 post4 = requests.post(url, data='[{"some": "json"}]')886 assert post4.status_code == 200887888 with pytest.raises(ValueError):889 requests.post(url, files=["bad file data"])890891 def test_post_with_custom_mapping(self, httpbin):892 class CustomMapping(MutableMapping):893 def __init__(self, *args, **kwargs):894 self.data = dict(*args, **kwargs)895896 def __delitem__(self, key):897 del self.data[key]898899 def __getitem__(self, key):900 return self.data[key]901902 def __setitem__(self, key, value):903 self.data[key] = value904905 def __iter__(self):906 return iter(self.data)907908 def __len__(self):909 return len(self.data)910911 data = CustomMapping({"some": "data"})912 url = httpbin("post")913 found_json = requests.post(url, data=data).json().get("form")914 assert found_json == {"some": "data"}915916 def test_conflicting_post_params(self, httpbin):917 url = httpbin("post")918 with open("requirements-dev.txt") as f:919 with pytest.raises(ValueError):920 requests.post(url, data='[{"some": "data"}]', files={"some": f})921922 def test_request_ok_set(self, httpbin):923 r = requests.get(httpbin("status", "404"))924 assert not r.ok925926 def test_status_raising(self, httpbin):927 r = requests.get(httpbin("status", "404"))928 with pytest.raises(requests.exceptions.HTTPError):929 r.raise_for_status()930931 r = requests.get(httpbin("status", "500"))932 assert not r.ok933934 def test_decompress_gzip(self, httpbin):935 r = requests.get(httpbin("gzip"))936 r.content.decode("ascii")937938 @pytest.mark.parametrize(939 "url, params",940 (941 ("/get", {"foo": "føø"}),942 ("/get", {"føø": "føø"}),943 ("/get", {"føø": "føø"}),944 ("/get", {"foo": "foo"}),945 ("ø", {"foo": "foo"}),946 ),947 )948 def test_unicode_get(self, httpbin, url, params):949 requests.get(httpbin(url), params=params)950951 def test_unicode_header_name(self, httpbin):952 requests.put(953 httpbin("put"),954 headers={"Content-Type": "application/octet-stream"},955 data="\xff",956 ) # compat.str is unicode.957958 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):959 requests.get(httpbin_secure("status", "301"), verify=httpbin_ca_bundle)960961 def test_invalid_ca_certificate_path(self, httpbin_secure):962 INVALID_PATH = "/garbage"963 with pytest.raises(IOError) as e:964 requests.get(httpbin_secure(), verify=INVALID_PATH)965 assert (966 str(e.value)967 == f"Could not find a suitable TLS CA certificate bundle, invalid path: {INVALID_PATH}"968 )969970 def test_invalid_ssl_certificate_files(self, httpbin_secure):971 INVALID_PATH = "/garbage"972 with pytest.raises(IOError) as e:973 requests.get(httpbin_secure(), cert=INVALID_PATH)974 assert (975 str(e.value)976 == f"Could not find the TLS certificate file, invalid path: {INVALID_PATH}"977 )978979 with pytest.raises(IOError) as e:980 requests.get(httpbin_secure(), cert=(".", INVALID_PATH))981 assert str(e.value) == (982 f"Could not find the TLS key file, invalid path: {INVALID_PATH}"983 )984985 @pytest.mark.parametrize(986 "env, expected",987 (988 ({}, True),989 ({"REQUESTS_CA_BUNDLE": "/some/path"}, "/some/path"),990 ({"REQUESTS_CA_BUNDLE": ""}, True),991 ({"CURL_CA_BUNDLE": "/some/path"}, "/some/path"),992 ({"CURL_CA_BUNDLE": ""}, True),993 ({"REQUESTS_CA_BUNDLE": "", "CURL_CA_BUNDLE": ""}, True),994 (995 {996 "REQUESTS_CA_BUNDLE": "/some/path",997 "CURL_CA_BUNDLE": "/curl/path",998 },999 "/some/path",1000 ),1001 (1002 {1003 "REQUESTS_CA_BUNDLE": "",1004 "CURL_CA_BUNDLE": "/curl/path",1005 },1006 "/curl/path",1007 ),1008 ),1009 )1010 def test_env_cert_bundles(self, httpbin, env, expected):1011 s = requests.Session()1012 with mock.patch("os.environ", env):1013 settings = s.merge_environment_settings(1014 url=httpbin("get"), proxies={}, stream=False, verify=True, cert=None1015 )1016 assert settings["verify"] == expected10171018 def test_http_with_certificate(self, httpbin):1019 r = requests.get(httpbin(), cert=".")1020 assert r.status_code == 20010211022 @pytest.mark.skipif(1023 SNIMissingWarning is None,1024 reason="urllib3 2.0 removed that warning and errors out instead",1025 )1026 def test_https_warnings(self, nosan_server):1027 """warnings are emitted with requests.get"""1028 host, port, ca_bundle = nosan_server1029 if HAS_MODERN_SSL or HAS_PYOPENSSL:1030 warnings_expected = ("SubjectAltNameWarning",)1031 else:1032 warnings_expected = (1033 "SNIMissingWarning",1034 "InsecurePlatformWarning",1035 "SubjectAltNameWarning",1036 )10371038 with pytest.warns() as warning_records:1039 warnings.simplefilter("always")1040 requests.get(f"https://localhost:{port}/", verify=ca_bundle)10411042 warning_records = [1043 item1044 for item in warning_records1045 if item.category.__name__ != "ResourceWarning"1046 ]10471048 warnings_category = tuple(item.category.__name__ for item in warning_records)1049 assert warnings_category == warnings_expected10501051 def test_certificate_failure(self, httpbin_secure):1052 """1053 When underlying SSL problems occur, an SSLError is raised.1054 """1055 with pytest.raises(RequestsSSLError):1056 # Our local httpbin does not have a trusted CA, so this call will1057 # fail if we use our default trust bundle.1058 requests.get(httpbin_secure("status", "200"))10591060 def test_urlencoded_get_query_multivalued_param(self, httpbin):1061 r = requests.get(httpbin("get"), params={"test": ["foo", "baz"]})1062 assert r.status_code == 2001063 assert r.url == httpbin("get?test=foo&test=baz")10641065 def test_form_encoded_post_query_multivalued_element(self, httpbin):1066 r = requests.Request(1067 method="POST", url=httpbin("post"), data=dict(test=["foo", "baz"])1068 )1069 prep = r.prepare()1070 assert prep.body == "test=foo&test=baz"10711072 def test_different_encodings_dont_break_post(self, httpbin):1073 with open(__file__, "rb") as f:1074 r = requests.post(1075 httpbin("post"),1076 data={"stuff": json.dumps({"a": 123})},1077 params={"blah": "asdf1234"},1078 files={"file": ("test_requests.py", f)},1079 )1080 assert r.status_code == 20010811082 @pytest.mark.parametrize(1083 "data",1084 (1085 {"stuff": "ëlïxr"},1086 {"stuff": "ëlïxr".encode()},1087 {"stuff": "elixr"},1088 {"stuff": b"elixr"},1089 ),1090 )1091 def test_unicode_multipart_post(self, httpbin, data):1092 with open(__file__, "rb") as f:1093 r = requests.post(1094 httpbin("post"),1095 data=data,1096 files={"file": ("test_requests.py", f)},1097 )1098 assert r.status_code == 20010991100 def test_unicode_multipart_post_fieldnames(self, httpbin):1101 filename = os.path.splitext(__file__)[0] + ".py"1102 with open(filename, "rb") as f:1103 r = requests.Request(1104 method="POST",1105 url=httpbin("post"),1106 data={b"stuff": "elixr"},1107 files={"file": ("test_requests.py", f)},1108 )1109 prep = r.prepare()11101111 assert b'name="stuff"' in prep.body1112 assert b"name=\"b'stuff'\"" not in prep.body11131114 def test_unicode_method_name(self, httpbin):1115 with open(__file__, "rb") as f:1116 files = {"file": f}1117 r = requests.request(1118 method="POST",1119 url=httpbin("post"),1120 files=files,1121 )1122 assert r.status_code == 20011231124 def test_unicode_method_name_with_request_object(self, httpbin):1125 s = requests.Session()1126 with open(__file__, "rb") as f:1127 files = {"file": f}1128 req = requests.Request("POST", httpbin("post"), files=files)1129 prep = s.prepare_request(req)1130 assert isinstance(prep.method, builtin_str)1131 assert prep.method == "POST"11321133 resp = s.send(prep)1134 assert resp.status_code == 20011351136 def test_non_prepared_request_error(self):1137 s = requests.Session()1138 req = requests.Request("POST", "/")11391140 with pytest.raises(ValueError) as e:1141 s.send(req)1142 assert str(e.value) == "You can only send PreparedRequests."11431144 def test_custom_content_type(self, httpbin):1145 with open(__file__, "rb") as f1:1146 with open(__file__, "rb") as f2:1147 data = {"stuff": json.dumps({"a": 123})}1148 files = {1149 "file1": ("test_requests.py", f1),1150 "file2": ("test_requests", f2, "text/py-content-type"),1151 }1152 r = requests.post(httpbin("post"), data=data, files=files)1153 assert r.status_code == 2001154 assert b"text/py-content-type" in r.request.body11551156 def test_hook_receives_request_arguments(self, httpbin):1157 def hook(resp, **kwargs):1158 assert resp is not None1159 assert kwargs != {}11601161 s = requests.Session()1162 r = requests.Request("GET", httpbin(), hooks={"response": hook})1163 prep = s.prepare_request(r)1164 s.send(prep)11651166 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):1167 def hook(*args, **kwargs):1168 pass11691170 s = requests.Session()1171 s.hooks["response"].append(hook)1172 r = requests.Request("GET", httpbin())1173 prep = s.prepare_request(r)1174 assert prep.hooks["response"] != []1175 assert prep.hooks["response"] == [hook]11761177 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):1178 def hook1(*args, **kwargs):1179 pass11801181 def hook2(*args, **kwargs):1182 pass11831184 assert hook1 is not hook21185 s = requests.Session()1186 s.hooks["response"].append(hook2)1187 r = requests.Request("GET", httpbin(), hooks={"response": [hook1]})1188 prep = s.prepare_request(r)1189 assert prep.hooks["response"] == [hook1]11901191 def test_prepared_request_hook(self, httpbin):1192 def hook(resp, **kwargs):1193 resp.hook_working = True1194 return resp11951196 req = requests.Request("GET", httpbin(), hooks={"response": hook})1197 prep = req.prepare()11981199 s = requests.Session()1200 s.proxies = getproxies()1201 resp = s.send(prep)12021203 assert hasattr(resp, "hook_working")12041205 def test_prepared_from_session(self, httpbin):1206 class DummyAuth(requests.auth.AuthBase):1207 def __call__(self, r):1208 r.headers["Dummy-Auth-Test"] = "dummy-auth-test-ok"1209 return r12101211 req = requests.Request("GET", httpbin("headers"))1212 assert not req.auth12131214 s = requests.Session()1215 s.auth = DummyAuth()12161217 prep = s.prepare_request(req)1218 resp = s.send(prep)12191220 assert resp.json()["headers"]["Dummy-Auth-Test"] == "dummy-auth-test-ok"12211222 def test_prepare_request_with_bytestring_url(self):1223 req = requests.Request("GET", b"https://httpbin.org/")1224 s = requests.Session()1225 prep = s.prepare_request(req)1226 assert prep.url == "https://httpbin.org/"12271228 def test_request_with_bytestring_host(self, httpbin):1229 s = requests.Session()1230 resp = s.request(1231 "GET",1232 httpbin("cookies/set?cookie=value"),1233 allow_redirects=False,1234 headers={"Host": b"httpbin.org"},1235 )1236 assert resp.cookies.get("cookie") == "value"12371238 def test_links(self):1239 r = requests.Response()1240 r.headers = {1241 "cache-control": "public, max-age=60, s-maxage=60",1242 "connection": "keep-alive",1243 "content-encoding": "gzip",1244 "content-type": "application/json; charset=utf-8",1245 "date": "Sat, 26 Jan 2013 16:47:56 GMT",1246 "etag": '"6ff6a73c0e446c1f61614769e3ceb778"',1247 "last-modified": "Sat, 26 Jan 2013 16:22:39 GMT",1248 "link": (1249 "<https://api.github.com/users/kennethreitz/repos?"1250 'page=2&per_page=10>; rel="next", <https://api.github.'1251 "com/users/kennethreitz/repos?page=7&per_page=10>; "1252 ' rel="last"'1253 ),1254 "server": "GitHub.com",1255 "status": "200 OK",1256 "vary": "Accept",1257 "x-content-type-options": "nosniff",1258 "x-github-media-type": "github.beta",1259 "x-ratelimit-limit": "60",1260 "x-ratelimit-remaining": "57",1261 }1262 assert r.links["next"]["rel"] == "next"12631264 def test_cookie_parameters(self):1265 key = "some_cookie"1266 value = "some_value"1267 secure = True1268 domain = "test.com"1269 rest = {"HttpOnly": True}12701271 jar = requests.cookies.RequestsCookieJar()1272 jar.set(key, value, secure=secure, domain=domain, rest=rest)12731274 assert len(jar) == 11275 assert "some_cookie" in jar12761277 cookie = list(jar)[0]1278 assert cookie.secure == secure1279 assert cookie.domain == domain1280 assert cookie._rest["HttpOnly"] == rest["HttpOnly"]12811282 def test_cookie_as_dict_keeps_len(self):1283 key = "some_cookie"1284 value = "some_value"12851286 key1 = "some_cookie1"1287 value1 = "some_value1"12881289 jar = requests.cookies.RequestsCookieJar()1290 jar.set(key, value)1291 jar.set(key1, value1)12921293 d1 = dict(jar)1294 d2 = dict(jar.iteritems())1295 d3 = dict(jar.items())12961297 assert len(jar) == 21298 assert len(d1) == 21299 assert len(d2) == 21300 assert len(d3) == 213011302 def test_cookie_as_dict_keeps_items(self):1303 key = "some_cookie"1304 value = "some_value"13051306 key1 = "some_cookie1"1307 value1 = "some_value1"13081309 jar = requests.cookies.RequestsCookieJar()1310 jar.set(key, value)1311 jar.set(key1, value1)13121313 d1 = dict(jar)1314 d2 = dict(jar.iteritems())1315 d3 = dict(jar.items())13161317 assert d1["some_cookie"] == "some_value"1318 assert d2["some_cookie"] == "some_value"1319 assert d3["some_cookie1"] == "some_value1"13201321 def test_cookie_as_dict_keys(self):1322 key = "some_cookie"1323 value = "some_value"13241325 key1 = "some_cookie1"1326 value1 = "some_value1"13271328 jar = requests.cookies.RequestsCookieJar()1329 jar.set(key, value)1330 jar.set(key1, value1)13311332 keys = jar.keys()1333 assert keys == list(keys)1334 # make sure one can use keys multiple times1335 assert list(keys) == list(keys)13361337 def test_cookie_as_dict_values(self):1338 key = "some_cookie"1339 value = "some_value"13401341 key1 = "some_cookie1"1342 value1 = "some_value1"13431344 jar = requests.cookies.RequestsCookieJar()1345 jar.set(key, value)1346 jar.set(key1, value1)13471348 values = jar.values()1349 assert values == list(values)1350 # make sure one can use values multiple times1351 assert list(values) == list(values)13521353 def test_cookie_as_dict_items(self):1354 key = "some_cookie"1355 value = "some_value"13561357 key1 = "some_cookie1"1358 value1 = "some_value1"13591360 jar = requests.cookies.RequestsCookieJar()1361 jar.set(key, value)1362 jar.set(key1, value1)13631364 items = jar.items()1365 assert items == list(items)1366 # make sure one can use items multiple times1367 assert list(items) == list(items)13681369 def test_cookie_duplicate_names_different_domains(self):1370 key = "some_cookie"1371 value = "some_value"1372 domain1 = "test1.com"1373 domain2 = "test2.com"13741375 jar = requests.cookies.RequestsCookieJar()1376 jar.set(key, value, domain=domain1)1377 jar.set(key, value, domain=domain2)1378 assert key in jar1379 items = jar.items()1380 assert len(items) == 213811382 # Verify that CookieConflictError is raised if domain is not specified1383 with pytest.raises(requests.cookies.CookieConflictError):1384 jar.get(key)13851386 # Verify that CookieConflictError is not raised if domain is specified1387 cookie = jar.get(key, domain=domain1)1388 assert cookie == value13891390 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1391 key = "some_cookie"1392 value = "some_value"1393 path = "some_path"13941395 jar = requests.cookies.RequestsCookieJar()1396 jar.set(key, value, path=path)1397 jar.set(key, value)1398 with pytest.raises(requests.cookies.CookieConflictError):1399 jar.get(key)14001401 def test_cookie_policy_copy(self):1402 class MyCookiePolicy(cookielib.DefaultCookiePolicy):1403 pass14041405 jar = requests.cookies.RequestsCookieJar()1406 jar.set_policy(MyCookiePolicy())1407 assert isinstance(jar.copy().get_policy(), MyCookiePolicy)14081409 def test_time_elapsed_blank(self, httpbin):1410 r = requests.get(httpbin("get"))1411 td = r.elapsed1412 total_seconds = (1413 td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**61414 ) / 10**61415 assert total_seconds > 0.014161417 def test_empty_response_has_content_none(self):1418 r = requests.Response()1419 assert r.content is None14201421 def test_response_is_iterable(self):1422 r = requests.Response()1423 io = StringIO.StringIO("abc")1424 read_ = io.read14251426 def read_mock(amt, decode_content=None):1427 return read_(amt)14281429 setattr(io, "read", read_mock)1430 r.raw = io1431 assert next(iter(r))1432 io.close()14331434 def test_response_decode_unicode(self):1435 """When called with decode_unicode, Response.iter_content should always1436 return unicode.1437 """1438 r = requests.Response()1439 r._content_consumed = True1440 r._content = b"the content"1441 r.encoding = "ascii"14421443 chunks = r.iter_content(decode_unicode=True)1444 assert all(isinstance(chunk, str) for chunk in chunks)14451446 # also for streaming1447 r = requests.Response()1448 r.raw = io.BytesIO(b"the content")1449 r.encoding = "ascii"1450 chunks = r.iter_content(decode_unicode=True)1451 assert all(isinstance(chunk, str) for chunk in chunks)14521453 def test_response_reason_unicode(self):1454 # check for unicode HTTP status1455 r = requests.Response()1456 r.url = "unicode URL"1457 r.reason = "Komponenttia ei löydy".encode()1458 r.status_code = 4041459 r.encoding = None1460 assert not r.ok # old behaviour - crashes here14611462 def test_response_reason_unicode_fallback(self):1463 # check raise_status falls back to ISO-8859-11464 r = requests.Response()1465 r.url = "some url"1466 reason = "Komponenttia ei löydy"1467 r.reason = reason.encode("latin-1")1468 r.status_code = 5001469 r.encoding = None1470 with pytest.raises(requests.exceptions.HTTPError) as e:1471 r.raise_for_status()1472 assert reason in e.value.args[0]14731474 def test_response_chunk_size_type(self):1475 """Ensure that chunk_size is passed as None or an integer, otherwise1476 raise a TypeError.1477 """1478 r = requests.Response()1479 r.raw = io.BytesIO(b"the content")1480 chunks = r.iter_content(1)1481 assert all(len(chunk) == 1 for chunk in chunks)14821483 r = requests.Response()1484 r.raw = io.BytesIO(b"the content")1485 chunks = r.iter_content(None)1486 assert list(chunks) == [b"the content"]14871488 r = requests.Response()1489 r.raw = io.BytesIO(b"the content")1490 with pytest.raises(TypeError):1491 chunks = r.iter_content("1024")14921493 @pytest.mark.parametrize(1494 "exception, args, expected",1495 (1496 (urllib3.exceptions.ProtocolError, tuple(), ChunkedEncodingError),1497 (urllib3.exceptions.DecodeError, tuple(), ContentDecodingError),1498 (urllib3.exceptions.ReadTimeoutError, (None, "", ""), ConnectionError),1499 (urllib3.exceptions.SSLError, tuple(), RequestsSSLError),1500 ),1501 )1502 def test_iter_content_wraps_exceptions(self, httpbin, exception, args, expected):1503 r = requests.Response()1504 r.raw = mock.Mock()1505 # ReadTimeoutError can't be initialized by mock1506 # so we'll manually create the instance with args1507 r.raw.stream.side_effect = exception(*args)15081509 with pytest.raises(expected):1510 next(r.iter_content(1024))15111512 def test_request_and_response_are_pickleable(self, httpbin):1513 r = requests.get(httpbin("get"))15141515 # verify we can pickle the original request1516 assert pickle.loads(pickle.dumps(r.request))15171518 # verify we can pickle the response and that we have access to1519 # the original request.1520 pr = pickle.loads(pickle.dumps(r))1521 assert r.request.url == pr.request.url1522 assert r.request.headers == pr.request.headers15231524 def test_prepared_request_is_pickleable(self, httpbin):1525 p = requests.Request("GET", httpbin("get")).prepare()15261527 # Verify PreparedRequest can be pickled and unpickled1528 r = pickle.loads(pickle.dumps(p))1529 assert r.url == p.url1530 assert r.headers == p.headers1531 assert r.body == p.body15321533 # Verify unpickled PreparedRequest sends properly1534 s = requests.Session()1535 resp = s.send(r)1536 assert resp.status_code == 20015371538 def test_prepared_request_with_file_is_pickleable(self, httpbin):1539 with open(__file__, "rb") as f:1540 r = requests.Request("POST", httpbin("post"), files={"file": f})1541 p = r.prepare()15421543 # Verify PreparedRequest can be pickled and unpickled1544 r = pickle.loads(pickle.dumps(p))1545 assert r.url == p.url1546 assert r.headers == p.headers1547 assert r.body == p.body15481549 # Verify unpickled PreparedRequest sends properly1550 s = requests.Session()1551 resp = s.send(r)1552 assert resp.status_code == 20015531554 def test_prepared_request_with_hook_is_pickleable(self, httpbin):1555 r = requests.Request("GET", httpbin("get"), hooks=default_hooks())1556 p = r.prepare()15571558 # Verify PreparedRequest can be pickled1559 r = pickle.loads(pickle.dumps(p))1560 assert r.url == p.url1561 assert r.headers == p.headers1562 assert r.body == p.body1563 assert r.hooks == p.hooks15641565 # Verify unpickled PreparedRequest sends properly1566 s = requests.Session()1567 resp = s.send(r)1568 assert resp.status_code == 20015691570 def test_cannot_send_unprepared_requests(self, httpbin):1571 r = requests.Request(url=httpbin())1572 with pytest.raises(ValueError):1573 requests.Session().send(r)15741575 def test_http_error(self):1576 error = requests.exceptions.HTTPError()1577 assert not error.response1578 response = requests.Response()1579 error = requests.exceptions.HTTPError(response=response)1580 assert error.response == response1581 error = requests.exceptions.HTTPError("message", response=response)1582 assert str(error) == "message"1583 assert error.response == response15841585 def test_session_pickling(self, httpbin):1586 r = requests.Request("GET", httpbin("get"))1587 s = requests.Session()15881589 s = pickle.loads(pickle.dumps(s))1590 s.proxies = getproxies()15911592 r = s.send(r.prepare())1593 assert r.status_code == 20015941595 def test_fixes_1329(self, httpbin):1596 """Ensure that header updates are done case-insensitively."""1597 s = requests.Session()1598 s.headers.update({"ACCEPT": "BOGUS"})1599 s.headers.update({"accept": "application/json"})1600 r = s.get(httpbin("get"))1601 headers = r.request.headers1602 assert headers["accept"] == "application/json"1603 assert headers["Accept"] == "application/json"1604 assert headers["ACCEPT"] == "application/json"16051606 def test_uppercase_scheme_redirect(self, httpbin):1607 parts = urlparse(httpbin("html"))1608 url = "HTTP://" + parts.netloc + parts.path1609 r = requests.get(httpbin("redirect-to"), params={"url": url})1610 assert r.status_code == 2001611 assert r.url.lower() == url.lower()16121613 def test_transport_adapter_ordering(self):1614 s = requests.Session()1615 order = ["https://", "http://"]1616 assert order == list(s.adapters)1617 s.mount("http://git", HTTPAdapter())1618 s.mount("http://github", HTTPAdapter())1619 s.mount("http://github.com", HTTPAdapter())1620 s.mount("http://github.com/about/", HTTPAdapter())1621 order = [1622 "http://github.com/about/",1623 "http://github.com",1624 "http://github",1625 "http://git",1626 "https://",1627 "http://",1628 ]1629 assert order == list(s.adapters)1630 s.mount("http://gittip", HTTPAdapter())1631 s.mount("http://gittip.com", HTTPAdapter())1632 s.mount("http://gittip.com/about/", HTTPAdapter())1633 order = [1634 "http://github.com/about/",1635 "http://gittip.com/about/",1636 "http://github.com",1637 "http://gittip.com",1638 "http://github",1639 "http://gittip",1640 "http://git",1641 "https://",1642 "http://",1643 ]1644 assert order == list(s.adapters)1645 s2 = requests.Session()1646 s2.adapters = {"http://": HTTPAdapter()}1647 s2.mount("https://", HTTPAdapter())1648 assert "http://" in s2.adapters1649 assert "https://" in s2.adapters16501651 def test_session_get_adapter_prefix_matching(self):1652 prefix = "https://example.com"1653 more_specific_prefix = prefix + "/some/path"16541655 url_matching_only_prefix = prefix + "/another/path"1656 url_matching_more_specific_prefix = more_specific_prefix + "/longer/path"1657 url_not_matching_prefix = "https://another.example.com/"16581659 s = requests.Session()1660 prefix_adapter = HTTPAdapter()1661 more_specific_prefix_adapter = HTTPAdapter()1662 s.mount(prefix, prefix_adapter)1663 s.mount(more_specific_prefix, more_specific_prefix_adapter)16641665 assert s.get_adapter(url_matching_only_prefix) is prefix_adapter1666 assert (1667 s.get_adapter(url_matching_more_specific_prefix)1668 is more_specific_prefix_adapter1669 )1670 assert s.get_adapter(url_not_matching_prefix) not in (1671 prefix_adapter,1672 more_specific_prefix_adapter,1673 )16741675 def test_session_get_adapter_prefix_matching_mixed_case(self):1676 mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"1677 url_matching_prefix = mixed_case_prefix + "/full_url"16781679 s = requests.Session()1680 my_adapter = HTTPAdapter()1681 s.mount(mixed_case_prefix, my_adapter)16821683 assert s.get_adapter(url_matching_prefix) is my_adapter16841685 def test_session_get_adapter_prefix_matching_is_case_insensitive(self):1686 mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"1687 url_matching_prefix_with_different_case = (1688 "HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url"1689 )16901691 s = requests.Session()1692 my_adapter = HTTPAdapter()1693 s.mount(mixed_case_prefix, my_adapter)16941695 assert s.get_adapter(url_matching_prefix_with_different_case) is my_adapter16961697 def test_session_get_adapter_prefix_with_trailing_slash(self):1698 # from issue #69351699 prefix = "https://example.com/" # trailing slash1700 url_matching_prefix = "https://example.com/some/path"1701 url_not_matching_prefix = "https://example.com.other.com/some/path"17021703 s = requests.Session()1704 adapter = HTTPAdapter()1705 s.mount(prefix, adapter)17061707 assert s.get_adapter(url_matching_prefix) is adapter1708 assert s.get_adapter(url_not_matching_prefix) is not adapter17091710 def test_session_get_adapter_prefix_without_trailing_slash(self):1711 # from issue #69351712 prefix = "https://example.com" # no trailing slash1713 url_matching_prefix = "https://example.com/some/path"1714 url_extended_hostname = "https://example.com.other.com/some/path"17151716 s = requests.Session()1717 adapter = HTTPAdapter()1718 s.mount(prefix, adapter)17191720 assert s.get_adapter(url_matching_prefix) is adapter1721 assert s.get_adapter(url_extended_hostname) is adapter17221723 def test_header_remove_is_case_insensitive(self, httpbin):1724 # From issue #13211725 s = requests.Session()1726 s.headers["foo"] = "bar"1727 r = s.get(httpbin("get"), headers={"FOO": None})1728 assert "foo" not in r.request.headers17291730 def test_params_are_merged_case_sensitive(self, httpbin):1731 s = requests.Session()1732 s.params["foo"] = "bar"1733 r = s.get(httpbin("get"), params={"FOO": "bar"})1734 assert r.json()["args"] == {"foo": "bar", "FOO": "bar"}17351736 def test_long_authinfo_in_url(self):1737 url = "http://{}:{}@{}:9000/path?query#frag".format(1738 "E8A3BE87-9E3F-4620-8858-95478E385B5B",1739 "EA770032-DA4D-4D84-8CE9-29C6D910BF1E",1740 "exactly-------------sixty-----------three------------characters",1741 )1742 r = requests.Request("GET", url).prepare()1743 assert r.url == url17441745 def test_header_keys_are_native(self, httpbin):1746 headers = {"unicode": "blah", b"byte": "blah"}1747 r = requests.Request("GET", httpbin("get"), headers=headers)1748 p = r.prepare()17491750 # This is testing that they are builtin strings. A bit weird, but there1751 # we go.1752 assert "unicode" in p.headers.keys()1753 assert "byte" in p.headers.keys()17541755 def test_header_validation(self, httpbin):1756 """Ensure prepare_headers regex isn't flagging valid header contents."""1757 valid_headers = {1758 "foo": "bar baz qux",1759 "bar": b"fbbq",1760 "baz": "",1761 "qux": "1",1762 }1763 r = requests.get(httpbin("get"), headers=valid_headers)1764 for key in valid_headers.keys():1765 assert valid_headers[key] == r.request.headers[key]17661767 @pytest.mark.parametrize(1768 "invalid_header, key",1769 (1770 ({"foo": 3}, "foo"),1771 ({"bar": {"foo": "bar"}}, "bar"),1772 ({"baz": ["foo", "bar"]}, "baz"),1773 ),1774 )1775 def test_header_value_not_str(self, httpbin, invalid_header, key):1776 """Ensure the header value is of type string or bytes as1777 per discussion in GH issue #33861778 """1779 with pytest.raises(InvalidHeader) as excinfo:1780 requests.get(httpbin("get"), headers=invalid_header)1781 assert key in str(excinfo.value)17821783 @pytest.mark.parametrize(1784 "invalid_header",1785 (1786 {"foo": "bar\r\nbaz: qux"},1787 {"foo": "bar\n\rbaz: qux"},1788 {"foo": "bar\nbaz: qux"},1789 {"foo": "bar\rbaz: qux"},1790 {"fo\ro": "bar"},1791 {"fo\r\no": "bar"},1792 {"fo\n\ro": "bar"},1793 {"fo\no": "bar"},1794 ),1795 )1796 def test_header_no_return_chars(self, httpbin, invalid_header):1797 """Ensure that a header containing return character sequences raise an1798 exception. Otherwise, multiple headers are created from single string.1799 """1800 with pytest.raises(InvalidHeader):1801 requests.get(httpbin("get"), headers=invalid_header)18021803 @pytest.mark.parametrize(1804 "invalid_header",1805 (1806 {" foo": "bar"},1807 {"\tfoo": "bar"},1808 {" foo": "bar"},1809 {"foo": " bar"},1810 {"foo": " bar"},1811 {"foo": "\tbar"},1812 {" ": "bar"},1813 ),1814 )1815 def test_header_no_leading_space(self, httpbin, invalid_header):1816 """Ensure headers containing leading whitespace raise1817 InvalidHeader Error before sending.1818 """1819 with pytest.raises(InvalidHeader):1820 requests.get(httpbin("get"), headers=invalid_header)18211822 def test_header_with_subclass_types(self, httpbin):1823 """If the subclasses does not behave *exactly* like1824 the base bytes/str classes, this is not supported.1825 This test is for backwards compatibility.1826 """18271828 class MyString(str):1829 pass18301831 class MyBytes(bytes):1832 pass18331834 r_str = requests.get(httpbin("get"), headers={MyString("x-custom"): "myheader"})1835 assert r_str.request.headers["x-custom"] == "myheader"18361837 r_bytes = requests.get(1838 httpbin("get"), headers={MyBytes(b"x-custom"): b"myheader"}1839 )1840 assert r_bytes.request.headers["x-custom"] == b"myheader"18411842 r_mixed = requests.get(1843 httpbin("get"), headers={MyString("x-custom"): MyBytes(b"myheader")}1844 )1845 assert r_mixed.request.headers["x-custom"] == b"myheader"18461847 @pytest.mark.parametrize("files", ("foo", b"foo", bytearray(b"foo")))1848 def test_can_send_objects_with_files(self, httpbin, files):1849 data = {"a": "this is a string"}1850 files = {"b": files}1851 r = requests.Request("POST", httpbin("post"), data=data, files=files)1852 p = r.prepare()1853 assert "multipart/form-data" in p.headers["Content-Type"]18541855 def test_can_send_file_object_with_non_string_filename(self, httpbin):1856 f = io.BytesIO()1857 f.name = 21858 r = requests.Request("POST", httpbin("post"), files={"f": f})1859 p = r.prepare()18601861 assert "multipart/form-data" in p.headers["Content-Type"]18621863 def test_autoset_header_values_are_native(self, httpbin):1864 data = "this is a string"1865 length = "16"1866 req = requests.Request("POST", httpbin("post"), data=data)1867 p = req.prepare()18681869 assert p.headers["Content-Length"] == length18701871 def test_nonhttp_schemes_dont_check_URLs(self):1872 test_urls = (1873 "data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",1874 "file:///etc/passwd",1875 "magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431",1876 )1877 for test_url in test_urls:1878 req = requests.Request("GET", test_url)1879 preq = req.prepare()1880 assert test_url == preq.url18811882 def test_auth_is_stripped_on_http_downgrade(1883 self, httpbin, httpbin_secure, httpbin_ca_bundle1884 ):1885 r = requests.get(1886 httpbin_secure("redirect-to"),1887 params={"url": httpbin("get")},1888 auth=("user", "pass"),1889 verify=httpbin_ca_bundle,1890 )1891 assert r.history[0].request.headers["Authorization"]1892 assert "Authorization" not in r.request.headers18931894 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1895 r = requests.get(httpbin("redirect/1"), auth=("user", "pass"))1896 h1 = r.history[0].request.headers["Authorization"]1897 h2 = r.request.headers["Authorization"]18981899 assert h1 == h219001901 def test_should_strip_auth_host_change(self):1902 s = requests.Session()1903 assert s.should_strip_auth(1904 "http://example.com/foo", "http://another.example.com/"1905 )19061907 def test_should_strip_auth_http_downgrade(self):1908 s = requests.Session()1909 assert s.should_strip_auth("https://example.com/foo", "http://example.com/bar")19101911 def test_should_strip_auth_https_upgrade(self):1912 s = requests.Session()1913 assert not s.should_strip_auth(1914 "http://example.com/foo", "https://example.com/bar"1915 )1916 assert not s.should_strip_auth(1917 "http://example.com:80/foo", "https://example.com/bar"1918 )1919 assert not s.should_strip_auth(1920 "http://example.com/foo", "https://example.com:443/bar"1921 )1922 # Non-standard ports should trigger stripping1923 assert s.should_strip_auth(1924 "http://example.com:8080/foo", "https://example.com/bar"1925 )1926 assert s.should_strip_auth(1927 "http://example.com/foo", "https://example.com:8443/bar"1928 )19291930 def test_should_strip_auth_port_change(self):1931 s = requests.Session()1932 assert s.should_strip_auth(1933 "http://example.com:1234/foo", "https://example.com:4321/bar"1934 )19351936 @pytest.mark.parametrize(1937 "old_uri, new_uri",1938 (1939 ("https://example.com:443/foo", "https://example.com/bar"),1940 ("http://example.com:80/foo", "http://example.com/bar"),1941 ("https://example.com/foo", "https://example.com:443/bar"),1942 ("http://example.com/foo", "http://example.com:80/bar"),1943 ),1944 )1945 def test_should_strip_auth_default_port(self, old_uri, new_uri):1946 s = requests.Session()1947 assert not s.should_strip_auth(old_uri, new_uri)19481949 def test_manual_redirect_with_partial_body_read(self, httpbin):1950 s = requests.Session()1951 r1 = s.get(httpbin("redirect/2"), allow_redirects=False, stream=True)1952 assert r1.is_redirect1953 rg = s.resolve_redirects(r1, r1.request, stream=True)19541955 # read only the first eight bytes of the response body,1956 # then follow the redirect1957 r1.iter_content(8)1958 r2 = next(rg)1959 assert r2.is_redirect19601961 # read all of the response via iter_content,1962 # then follow the redirect1963 for _ in r2.iter_content():1964 pass1965 r3 = next(rg)1966 assert not r3.is_redirect19671968 def test_prepare_body_position_non_stream(self):1969 data = b"the data"1970 prep = requests.Request("GET", "http://example.com", data=data).prepare()1971 assert prep._body_position is None19721973 def test_rewind_body(self):1974 data = io.BytesIO(b"the data")1975 prep = requests.Request("GET", "http://example.com", data=data).prepare()1976 assert prep._body_position == 01977 assert prep.body.read() == b"the data"19781979 # the data has all been read1980 assert prep.body.read() == b""19811982 # rewind it back1983 requests.utils.rewind_body(prep)1984 assert prep.body.read() == b"the data"19851986 def test_rewind_partially_read_body(self):1987 data = io.BytesIO(b"the data")1988 data.read(4) # read some data1989 prep = requests.Request("GET", "http://example.com", data=data).prepare()1990 assert prep._body_position == 41991 assert prep.body.read() == b"data"19921993 # the data has all been read1994 assert prep.body.read() == b""19951996 # rewind it back1997 requests.utils.rewind_body(prep)1998 assert prep.body.read() == b"data"19992000 def test_rewind_body_no_seek(self):The first 2,000 of 3,039 lines.