Skip to content
Myr

Add automatic code formatting to Requests (#6095)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Nate Prewitt · committed by GitHub · parent 2d55176 · Browse files · 39 files+2828 added−2397 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

39 files+2828 added−2397 removed

  • tests:+1596 added−1437 removed
  • other:+1232 added−960 removed

39 files+2828 added−2397 removed

modified:.github/workflows/codeql-analysis.yml+1 added-1 removed
modified:.github/ISSUE_TEMPLATE.md+1 added-1 removed
modified:docs/dev/contributing.rst+15 added-56 removed
91 unmodified lines
92event that you object to the code review feedback, you should make your case93clearly and calmly. If, after doing so, the feedback is judged to still apply,94you must either apply the feedback or withdraw your contribution.9596Code Style97~~~~~~~~~~9899Requests uses a collection of tools to ensure the code base has a consistent100style as it grows. We have these orchestrated using a tool called101`pre-commit`_. This can be installed locally and run over your changes prior102to opening a PR, and will also be run as part of the CI approval process103before a change is merged.104105You can find the full list of formatting requirements specified in the106`.pre-commit-config.yaml`_ at the top level directory of Requests.107108.. _pre-commit: https://pre-commit.com/109.. _.pre-commit-config.yaml: https://github.com/psf/requests/blob/main/.pre-commit-config.yaml110111New Contributors112~~~~~~~~~~~~~~~~113114If you are new or relatively new to Open Source, welcome! Requests aims to
2 unmodified lines
117asking for help.118119Please also check the :ref:`early-feedback` section.120106Kenneth Reitz's Code Style™107~~~~~~~~~~~~~~~~~~~~~~~~~~~121109The Requests codebase uses the `PEP 8`_ code style.110111In addition to the standards outlined in PEP 8, we have a few guidelines:112113- Line-length can exceed 79 characters, to 100, when convenient.114- Line-length can exceed 100 characters, when doing otherwise would be *terribly* inconvenient.115- Always use single-quoted strings (e.g. ``'#flatearth'``), unless a single-quote occurs within the string.116117Additionally, one of the styles that PEP8 recommends for `line continuations`_118completely lacks all sense of taste, and is not to be permitted within119the Requests codebase::120121 # Aligned with opening delimiter.122 foo = long_function_name(var_one, var_two,123 var_three, var_four)124125No. Just don't. Please. This is much better::126127 foo = long_function_name(128 var_one,129 var_two,130 var_three,131 var_four,132 )133134Docstrings are to follow the following syntaxes::135136 def the_earth_is_flat():137 """NASA divided up the seas into thirty-three degrees."""138 pass139140::141142 def fibonacci_spiral_tool():143 """With my feet upon the ground I lose myself / between the sounds144 and open wide to suck it in. / I feel it move across my skin. / I'm145 reaching up and reaching out. / I'm reaching for the random or146 whatever will bewilder me. / Whatever will bewilder me. / And147 following our will and wind we may just go where no one's been. /148 We'll ride the spiral to the end and may just go where no one's149 been.150151 Spiral out. Keep going...152 """153 pass154155All functions, methods, and classes are to contain docstrings. Object data156model methods (e.g. ``__repr__``) are typically the exception to this rule.157158Thanks for helping to make the world a better place!159160.. _PEP 8: https://pep8.org/161.. _line continuations: https://www.python.org/dev/peps/pep-0008/#indentation162122Documentation Contributions123---------------------------124125Documentation improvements are always welcome! The documentation files live in
42 unmodified lines
modified:requests/__init__.py+59 added-31 removed
1# -*- coding: utf-8 -*-21# __2# /__) _ _ _ _ _/ _3# / ( (- (/ (/ (- _) / _)4# /
32 unmodified lines
37:copyright: (c) 2017 by Kenneth Reitz.38:license: Apache 2.0, see LICENSE for more details.39"""4043import urllib341import warnings4243import urllib34445from .exceptions import RequestsDependencyWarning4647try:48 from charset_normalizer import __version__ as charset_normalizer_version
4 unmodified lines
53 from chardet import __version__ as chardet_version54except ImportError:55 chardet_version = None565758def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):58 urllib3_version = urllib3_version.split('.')59 assert urllib3_version != ['dev'] # Verify urllib3 isn't installed from git.59 urllib3_version = urllib3_version.split(".")60 assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git.6162 # Sometimes, urllib3 only reports its version as 16.1.63 if len(urllib3_version) == 2:63 urllib3_version.append('0')64 urllib3_version.append("0")6566 # Check urllib3 for compatibility.67 major, minor, patch = urllib3_version # noqa: F81168 major, minor, patch = int(major), int(minor), int(patch)
3 unmodified lines
72 assert minor <= 267374 # Check charset_normalizer for compatibility.75 if chardet_version:75 major, minor, patch = chardet_version.split('.')[:3]76 major, minor, patch = chardet_version.split(".")[:3]77 major, minor, patch = int(major), int(minor), int(patch)78 # chardet_version >= 3.0.2, < 5.0.079 assert (3, 0, 2) <= (major, minor, patch) < (5, 0, 0)80 elif charset_normalizer_version:80 major, minor, patch = charset_normalizer_version.split('.')[:3]81 major, minor, patch = charset_normalizer_version.split(".")[:3]82 major, minor, patch = int(major), int(minor), int(patch)83 # charset_normalizer >= 2.0.0 < 3.0.084 assert (2, 0, 0) <= (major, minor, patch) < (3, 0, 0)85 else:86 raise Exception("You need either charset_normalizer or chardet installed")878889def _check_cryptography(cryptography_version):90 # cryptography < 1.3.491 try:90 cryptography_version = list(map(int, cryptography_version.split('.')))92 cryptography_version = list(map(int, cryptography_version.split(".")))93 except ValueError:94 return9596 if cryptography_version < [1, 3, 4]:95 warning = 'Old version of cryptography ({}) may cause slowdown.'.format(cryptography_version)97 warning = "Old version of cryptography ({}) may cause slowdown.".format(98 cryptography_version99 )100 warnings.warn(warning, RequestsDependencyWarning)101102103# Check imported dependencies for compatibility.104try:100 check_compatibility(urllib3.__version__, chardet_version, charset_normalizer_version)105 check_compatibility(106 urllib3.__version__, chardet_version, charset_normalizer_version107 )108except (AssertionError, ValueError):102 warnings.warn("urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "103 "version!".format(urllib3.__version__, chardet_version, charset_normalizer_version),104 RequestsDependencyWarning)109 warnings.warn(110 "urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "111 "version!".format(112 urllib3.__version__, chardet_version, charset_normalizer_version113 ),114 RequestsDependencyWarning,115 )116117# Attempt to enable urllib3's fallback for SNI support118# if the standard library doesn't support SNI or the119# 'ssl' library isn't available.
4 unmodified lines
124 ssl = None125126 if not getattr(ssl, "HAS_SNI", False):127 from urllib3.contrib import pyopenssl128129 pyopenssl.inject_into_urllib3()130131 # Check cryptography version132 from cryptography import __version__ as cryptography_version133134 _check_cryptography(cryptography_version)135except ImportError:136 pass137138# urllib3's DependencyWarnings should be silenced.139from urllib3.exceptions import DependencyWarning127warnings.simplefilter('ignore', DependencyWarning)140129from .__version__ import __title__, __description__, __url__, __version__130from .__version__ import __build__, __author__, __author_email__, __license__131from .__version__ import __copyright__, __cake__141warnings.simplefilter("ignore", DependencyWarning)142133from . import utils134from . import packages135from .models import Request, Response, PreparedRequest136from .api import request, get, head, post, patch, put, delete, options137from .sessions import session, Session138from .status_codes import codes139from .exceptions import (140 RequestException, Timeout, URLRequired,141 TooManyRedirects, HTTPError, ConnectionError,142 FileModeWarning, ConnectTimeout, ReadTimeout, JSONDecodeError143)144143# Set default logging handler to avoid "No handler found" warnings.144import logging145from logging import NullHandler146147from . import packages, utils148from .__version__ import (149 __author__,150 __author_email__,151 __build__,152 __cake__,153 __copyright__,154 __description__,155 __license__,156 __title__,157 __url__,158 __version__,159)160from .api import delete, get, head, options, patch, post, put, request161from .exceptions import (162 ConnectionError,163 ConnectTimeout,164 FileModeWarning,165 HTTPError,166 JSONDecodeError,167 ReadTimeout,168 RequestException,169 Timeout,170 TooManyRedirects,171 URLRequired,172)173from .models import PreparedRequest, Request, Response174from .sessions import Session, session175from .status_codes import codes176177logging.getLogger(__name__).addHandler(NullHandler())178179# FileModeWarnings go off per the default.152warnings.simplefilter('default', FileModeWarning, append=True)180warnings.simplefilter("default", FileModeWarning, append=True)
modified:requests/__version__.py+9 added-9 removed
1# .-. .-. .-. . . .-. .-. .-. .-.2# |( |- |.| | | |- `-. | `-.3# ' ' `-' `-`.`-' `-' `-' ' `-'45__title__ = 'requests'6__description__ = 'Python HTTP for Humans.'7__url__ = 'https://requests.readthedocs.io'8__version__ = '2.27.1'5__title__ = "requests"6__description__ = "Python HTTP for Humans."7__url__ = "https://requests.readthedocs.io"8__version__ = "2.27.1"9__build__ = 0x02270110__author__ = 'Kenneth Reitz'11__author_email__ = 'me@kennethreitz.org'12__license__ = 'Apache 2.0'13__copyright__ = 'Copyright 2022 Kenneth Reitz'14__cake__ = u'\u2728 \U0001f370 \u2728'10__author__ = "Kenneth Reitz"11__author_email__ = "me@kennethreitz.org"12__license__ = "Apache 2.0"13__copyright__ = "Copyright 2022 Kenneth Reitz"14__cake__ = "\u2728 \U0001f370 \u2728"
modified:requests/_internal_utils.py+2 added-4 removed
1# -*- coding: utf-8 -*-21"""2requests._internal_utils3~~~~~~~~~~~~~~4
3 unmodified lines
89from .compat import builtin_str101114def to_native_string(string, encoding='ascii'):12def to_native_string(string, encoding="ascii"):13 """Given a string object, regardless of type, returns a representation of14 that string in the native string type, encoding and decoding where15 necessary. This assumes ASCII unless told otherwise.16 """
13 unmodified lines
30 :rtype: bool31 """32 assert isinstance(u_string, str)33 try:36 u_string.encode('ascii')34 u_string.encode("ascii")35 return True36 except UnicodeEncodeError:37 return False
modified:requests/adapters.py+137 added-86 removed
1# -*- coding: utf-8 -*-21"""2requests.adapters3~~~~~~~~~~~~~~~~~4
1 unmodified line
6and maintain connections.7"""89import os.path12import socket10import socket # noqa: F4011114from urllib3.poolmanager import PoolManager, proxy_from_url15from urllib3.response import HTTPResponse16from urllib3.util import parse_url17from urllib3.util import Timeout as TimeoutSauce18from urllib3.util.retry import Retry19from urllib3.exceptions import ClosedPoolError20from urllib3.exceptions import ConnectTimeoutError12from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError13from urllib3.exceptions import HTTPError as _HTTPError14from urllib3.exceptions import InvalidHeader as _InvalidHeader23from urllib3.exceptions import MaxRetryError24from urllib3.exceptions import NewConnectionError15from urllib3.exceptions import (16 LocationValueError,17 MaxRetryError,18 NewConnectionError,19 ProtocolError,20)21from urllib3.exceptions import ProxyError as _ProxyError26from urllib3.exceptions import ProtocolError27from urllib3.exceptions import ReadTimeoutError22from urllib3.exceptions import ReadTimeoutError, ResponseError23from urllib3.exceptions import SSLError as _SSLError29from urllib3.exceptions import ResponseError30from urllib3.exceptions import LocationValueError24from urllib3.poolmanager import PoolManager, proxy_from_url25from urllib3.response import HTTPResponse26from urllib3.util import Timeout as TimeoutSauce27from urllib3.util import parse_url28from urllib3.util.retry import Retry2930from .auth import _basic_auth_str31from .compat import basestring, urlparse32from .cookies import extract_cookies_to_jar33from .exceptions import (34 ConnectionError,35 ConnectTimeout,36 InvalidHeader,37 InvalidProxyURL,38 InvalidSchema,39 InvalidURL,40 ProxyError,41 ReadTimeout,42 RetryError,43 SSLError,44)45from .models import Response33from .compat import urlparse, basestring34from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths,35 get_encoding_from_headers, prepend_scheme_if_needed,36 get_auth_from_url, urldefragauth, select_proxy)46from .structures import CaseInsensitiveDict38from .cookies import extract_cookies_to_jar39from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,40 ProxyError, RetryError, InvalidSchema, InvalidProxyURL,41 InvalidURL, InvalidHeader)42from .auth import _basic_auth_str47from .utils import (48 DEFAULT_CA_BUNDLE_PATH,49 extract_zipped_paths,50 get_auth_from_url,51 get_encoding_from_headers,52 prepend_scheme_if_needed,53 select_proxy,54 urldefragauth,55)5657try:58 from urllib3.contrib.socks import SOCKSProxyManager59except ImportError:6061 def SOCKSProxyManager(*args, **kwargs):62 raise InvalidSchema("Missing dependencies for SOCKS support.")636465DEFAULT_POOLBLOCK = False66DEFAULT_POOLSIZE = 1067DEFAULT_RETRIES = 068DEFAULT_POOL_TIMEOUT = None697056class BaseAdapter(object):71class BaseAdapter:72 """The Base Transport Adapter"""7374 def __init__(self):60 super(BaseAdapter, self).__init__()75 super().__init__()7662 def send(self, request, stream=False, timeout=None, verify=True,63 cert=None, proxies=None):77 def send(78 self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None79 ):80 """Sends PreparedRequest object. Returns Response object.8182 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.83 :param stream: (optional) Whether to stream the request content.
39 unmodified lines
123 >>> s = requests.Session()124 >>> a = requests.adapters.HTTPAdapter(max_retries=3)125 >>> s.mount('http://', a)126 """111 __attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize',112 '_pool_block']127128 __attrs__ = [129 "max_retries",130 "config",131 "_pool_connections",132 "_pool_maxsize",133 "_pool_block",134 ]135136 def __init__(137 self,138 pool_connections=DEFAULT_POOLSIZE,114 def __init__(self, pool_connections=DEFAULT_POOLSIZE,115 pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,116 pool_block=DEFAULT_POOLBLOCK):139 pool_maxsize=DEFAULT_POOLSIZE,140 max_retries=DEFAULT_RETRIES,141 pool_block=DEFAULT_POOLBLOCK,142 ):143 if max_retries == DEFAULT_RETRIES:144 self.max_retries = Retry(0, read=False)145 else:146 self.max_retries = Retry.from_int(max_retries)147 self.config = {}148 self.proxy_manager = {}149124 super(HTTPAdapter, self).__init__()150 super().__init__()151152 self._pool_connections = pool_connections153 self._pool_maxsize = pool_maxsize154 self._pool_block = pool_block
11 unmodified lines
166167 for attr, value in state.items():168 setattr(self, attr, value)169144 self.init_poolmanager(self._pool_connections, self._pool_maxsize,145 block=self._pool_block)170 self.init_poolmanager(171 self._pool_connections, self._pool_maxsize, block=self._pool_block172 )173147 def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):174 def init_poolmanager(175 self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs176 ):177 """Initializes a urllib3 PoolManager.178179 This method should not be called from user code, and is only180 exposed for use when subclassing the
8 unmodified lines
189 self._pool_connections = connections190 self._pool_maxsize = maxsize191 self._pool_block = block192164 self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,165 block=block, strict=True, **pool_kwargs)193 self.poolmanager = PoolManager(194 num_pools=connections,195 maxsize=maxsize,196 block=block,197 strict=True,198 **pool_kwargs,199 )200201 def proxy_manager_for(self, proxy, **proxy_kwargs):202 """Return urllib3 ProxyManager for the given proxy.203
7 unmodified lines
211 :rtype: urllib3.ProxyManager212 """213 if proxy in self.proxy_manager:214 manager = self.proxy_manager[proxy]181 elif proxy.lower().startswith('socks'):215 elif proxy.lower().startswith("socks"):216 username, password = get_auth_from_url(proxy)217 manager = self.proxy_manager[proxy] = SOCKSProxyManager(218 proxy,219 username=username,220 password=password,221 num_pools=self._pool_connections,222 maxsize=self._pool_maxsize,223 block=self._pool_block,190 **proxy_kwargs224 **proxy_kwargs,225 )226 else:227 proxy_headers = self.proxy_headers(proxy)228 manager = self.proxy_manager[proxy] = proxy_from_url(
1 unmodified line
230 proxy_headers=proxy_headers,231 num_pools=self._pool_connections,232 maxsize=self._pool_maxsize,233 block=self._pool_block,200 **proxy_kwargs)234 **proxy_kwargs,235 )236237 return manager238239 def cert_verify(self, conn, url, verify, cert):
7 unmodified lines
247 the server's TLS certificate, or a string, in which case it must be a path248 to a CA bundle to use249 :param cert: The SSL certificate to verify.250 """216 if url.lower().startswith('https') and verify:251 if url.lower().startswith("https") and verify:252253 cert_loc = None254255 # Allow self-specified cert location.
3 unmodified lines
259 if not cert_loc:260 cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)261262 if not cert_loc or not os.path.exists(cert_loc):228 raise IOError("Could not find a suitable TLS CA certificate bundle, "229 "invalid path: {}".format(cert_loc))263 raise OSError(264 f"Could not find a suitable TLS CA certificate bundle, "265 f"invalid path: {cert_loc}"266 )267231 conn.cert_reqs = 'CERT_REQUIRED'268 conn.cert_reqs = "CERT_REQUIRED"269270 if not os.path.isdir(cert_loc):271 conn.ca_certs = cert_loc272 else:273 conn.ca_cert_dir = cert_loc274 else:238 conn.cert_reqs = 'CERT_NONE'275 conn.cert_reqs = "CERT_NONE"276 conn.ca_certs = None277 conn.ca_cert_dir = None278279 if cert:
3 unmodified lines
283 else:284 conn.cert_file = cert285 conn.key_file = None286 if conn.cert_file and not os.path.exists(conn.cert_file):250 raise IOError("Could not find the TLS certificate file, "251 "invalid path: {}".format(conn.cert_file))287 raise OSError(288 f"Could not find the TLS certificate file, "289 f"invalid path: {conn.cert_file}"290 )291 if conn.key_file and not os.path.exists(conn.key_file):253 raise IOError("Could not find the TLS key file, "254 "invalid path: {}".format(conn.key_file))292 raise OSError(293 f"Could not find the TLS key file, invalid path: {conn.key_file}"294 )295296 def build_response(self, req, resp):297 """Builds a :class:`Response <requests.Response>` object from a urllib3298 response. This should not be called from user code, and is only exposed
6 unmodified lines
305 """306 response = Response()307308 # Fallback to None if there's no status_code, for whatever reason.269 response.status_code = getattr(resp, 'status', None)309 response.status_code = getattr(resp, "status", None)310311 # Make headers case-insensitive.272 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))312 response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))313314 # Set encoding.315 response.encoding = get_encoding_from_headers(response.headers)316 response.raw = resp317 response.reason = response.raw.reason318319 if isinstance(req.url, bytes):280 response.url = req.url.decode('utf-8')320 response.url = req.url.decode("utf-8")321 else:322 response.url = req.url323324 # Add new cookies from the server.
16 unmodified lines
341 """342 proxy = select_proxy(url, proxies)343344 if proxy:305 proxy = prepend_scheme_if_needed(proxy, 'http')345 proxy = prepend_scheme_if_needed(proxy, "http")346 proxy_url = parse_url(proxy)347 if not proxy_url.host:348 raise InvalidProxyURL(308 raise InvalidProxyURL("Please check proxy URL. It is malformed"309 " and could be missing the host.")349 "Please check proxy URL. It is malformed "350 "and could be missing the host."351 )352 proxy_manager = self.proxy_manager_for(proxy)353 conn = proxy_manager.connection_from_url(url)354 else:355 # Only scheme should be lower case
29 unmodified lines
385 """386 proxy = select_proxy(request.url, proxies)387 scheme = urlparse(request.url).scheme388347 is_proxied_http_request = (proxy and scheme != 'https')389 is_proxied_http_request = proxy and scheme != "https"390 using_socks_proxy = False391 if proxy:392 proxy_scheme = urlparse(proxy).scheme.lower()351 using_socks_proxy = proxy_scheme.startswith('socks')393 using_socks_proxy = proxy_scheme.startswith("socks")394395 url = request.path_url396 if is_proxied_http_request and not using_socks_proxy:397 url = urldefragauth(request.url)
30 unmodified lines
428 headers = {}429 username, password = get_auth_from_url(proxy)430431 if username:390 headers['Proxy-Authorization'] = _basic_auth_str(username,391 password)432 headers["Proxy-Authorization"] = _basic_auth_str(username, password)433434 return headers435395 def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):436 def send(437 self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None438 ):439 """Sends PreparedRequest object. Returns Response object.440441 :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.442 :param stream: (optional) Whether to stream the request content.
15 unmodified lines
458 raise InvalidURL(e, request=request)459460 self.cert_verify(conn, request.url, verify, cert)461 url = self.request_url(request, proxies)419 self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)462 self.add_headers(463 request,464 stream=stream,465 timeout=timeout,466 verify=verify,467 cert=cert,468 proxies=proxies,469 )470421 chunked = not (request.body is None or 'Content-Length' in request.headers)471 chunked = not (request.body is None or "Content-Length" in request.headers)472473 if isinstance(timeout, tuple):474 try:475 connect, read = timeout476 timeout = TimeoutSauce(connect=connect, read=read)427 except ValueError as e:428 # this may raise a string formatting error.429 err = ("Invalid timeout {}. Pass a (connect, read) "430 "timeout tuple, or a single float to set "431 "both timeouts to the same value".format(timeout))432 raise ValueError(err)477 except ValueError:478 raise ValueError(479 f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, "480 f"or a single float to set both timeouts to the same value."481 )482 elif isinstance(timeout, TimeoutSauce):483 pass484 else:485 timeout = TimeoutSauce(connect=timeout, read=timeout)
9 unmodified lines
495 assert_same_host=False,496 preload_content=False,497 decode_content=False,498 retries=self.max_retries,450 timeout=timeout499 timeout=timeout,500 )501502 # Send the request.503 else:455 if hasattr(conn, 'proxy_pool'):504 if hasattr(conn, "proxy_pool"):505 conn = conn.proxy_pool506507 low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)508509 try:461 skip_host = 'Host' in request.headers462 low_conn.putrequest(request.method,463 url,464 skip_accept_encoding=True,465 skip_host=skip_host)510 skip_host = "Host" in request.headers511 low_conn.putrequest(512 request.method,513 url,514 skip_accept_encoding=True,515 skip_host=skip_host,516 )517518 for header, value in request.headers.items():519 low_conn.putheader(header, value)520521 low_conn.endheaders()522523 for i in request.body:473 low_conn.send(hex(len(i))[2:].encode('utf-8'))474 low_conn.send(b'\r\n')524 low_conn.send(hex(len(i))[2:].encode("utf-8"))525 low_conn.send(b"\r\n")526 low_conn.send(i)476 low_conn.send(b'\r\n')477 low_conn.send(b'0\r\n\r\n')527 low_conn.send(b"\r\n")528 low_conn.send(b"0\r\n\r\n")529530 # Receive the response from the server531 r = low_conn.getresponse()532
1 unmodified line
534 r,535 pool=conn,536 connection=low_conn,537 preload_content=False,487 decode_content=False538 decode_content=False,539 )489 except:540 except Exception:541 # If we hit any problems here, clean up the connection.491 # Then, reraise so that we can handle the actual exception.542 # Then, raise so that we can handle the actual exception.543 low_conn.close()544 raise545495 except (ProtocolError, socket.error) as err:546 except (ProtocolError, OSError) as err:547 raise ConnectionError(err, request=request)548549 except MaxRetryError as e:550 if isinstance(e.reason, ConnectTimeoutError):
34 unmodified lines
modified:requests/api.py+8 added-10 removed
1# -*- coding: utf-8 -*-21"""2requests.api3~~~~~~~~~~~~4
64 unmodified lines
69 :return: :class:`Response <Response>` object70 :rtype: requests.Response71 """7275 return request('get', url, params=params, **kwargs)73 return request("get", url, params=params, **kwargs)747576def options(url, **kwargs):77 r"""Sends an OPTIONS request.
3 unmodified lines
81 :return: :class:`Response <Response>` object82 :rtype: requests.Response83 """8487 return request('options', url, **kwargs)85 return request("options", url, **kwargs)868788def head(url, **kwargs):89 r"""Sends a HEAD request.
5 unmodified lines
95 :return: :class:`Response <Response>` object96 :rtype: requests.Response97 """98101 kwargs.setdefault('allow_redirects', False)102 return request('head', url, **kwargs)99 kwargs.setdefault("allow_redirects", False)100 return request("head", url, **kwargs)101102103def post(url, data=None, json=None, **kwargs):104 r"""Sends a POST request.
6 unmodified lines
111 :return: :class:`Response <Response>` object112 :rtype: requests.Response113 """114117 return request('post', url, data=data, json=json, **kwargs)115 return request("post", url, data=data, json=json, **kwargs)116117118def put(url, data=None, **kwargs):119 r"""Sends a PUT request.
6 unmodified lines
126 :return: :class:`Response <Response>` object127 :rtype: requests.Response128 """129132 return request('put', url, data=data, **kwargs)130 return request("put", url, data=data, **kwargs)131132133def patch(url, data=None, **kwargs):134 r"""Sends a PATCH request.
6 unmodified lines
141 :return: :class:`Response <Response>` object142 :rtype: requests.Response143 """144147 return request('patch', url, data=data, **kwargs)145 return request("patch", url, data=data, **kwargs)146147148def delete(url, **kwargs):149 r"""Sends a DELETE request.
3 unmodified lines
153 :return: :class:`Response <Response>` object154 :rtype: requests.Response155 """156159 return request('delete', url, **kwargs)157 return request("delete", url, **kwargs)
modified:requests/auth.py+83 added-73 removed
1# -*- coding: utf-8 -*-21"""2requests.auth3~~~~~~~~~~~~~45This module contains the authentication handlers for Requests.6"""78import hashlib9import os10import re12import time13import hashlib11import threading12import time13import warnings1614from base64 import b64encode1519from .compat import urlparse, str, basestring20from .cookies import extract_cookies_to_jar16from ._internal_utils import to_native_string17from .compat import basestring, str, urlparse18from .cookies import extract_cookies_to_jar19from .utils import parse_dict_header2024CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'25CONTENT_TYPE_MULTI_PART = 'multipart/form-data'21CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"22CONTENT_TYPE_MULTI_PART = "multipart/form-data"232425def _basic_auth_str(username, password):26 """Returns a Basic Auth string."""
26 unmodified lines
53 password = str(password)54 # -- End Removal --5556 if isinstance(username, str):60 username = username.encode('latin1')57 username = username.encode("latin1")5859 if isinstance(password, str):63 password = password.encode('latin1')60 password = password.encode("latin1")6165 authstr = 'Basic ' + to_native_string(66 b64encode(b':'.join((username, password))).strip()62 authstr = "Basic " + to_native_string(63 b64encode(b":".join((username, password))).strip()64 )6566 return authstr676872class AuthBase(object):69class AuthBase:70 """Base class that all auth implementations derive from"""7172 def __call__(self, r):76 raise NotImplementedError('Auth hooks must be callable.')73 raise NotImplementedError("Auth hooks must be callable.")747576class HTTPBasicAuth(AuthBase):77 """Attaches HTTP Basic Authentication to the given Request object."""
2 unmodified lines
80 self.username = username81 self.password = password8283 def __eq__(self, other):87 return all([88 self.username == getattr(other, 'username', None),89 self.password == getattr(other, 'password', None)90 ])84 return all(85 [86 self.username == getattr(other, "username", None),87 self.password == getattr(other, "password", None),88 ]89 )9091 def __ne__(self, other):92 return not self == other9394 def __call__(self, r):96 r.headers['Authorization'] = _basic_auth_str(self.username, self.password)95 r.headers["Authorization"] = _basic_auth_str(self.username, self.password)96 return r979899class HTTPProxyAuth(HTTPBasicAuth):100 """Attaches HTTP Proxy Authentication to a given Request object."""101102 def __call__(self, r):104 r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)103 r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password)104 return r105106107class HTTPDigestAuth(AuthBase):
6 unmodified lines
114 self._thread_local = threading.local()115116 def init_per_thread_state(self):117 # Ensure state is initialized just once per-thread119 if not hasattr(self._thread_local, 'init'):118 if not hasattr(self._thread_local, "init"):119 self._thread_local.init = True121 self._thread_local.last_nonce = ''120 self._thread_local.last_nonce = ""121 self._thread_local.nonce_count = 0122 self._thread_local.chal = {}123 self._thread_local.pos = None124 self._thread_local.num_401_calls = None
2 unmodified lines
127 """128 :rtype: str129 """130132 realm = self._thread_local.chal['realm']133 nonce = self._thread_local.chal['nonce']134 qop = self._thread_local.chal.get('qop')135 algorithm = self._thread_local.chal.get('algorithm')136 opaque = self._thread_local.chal.get('opaque')131 realm = self._thread_local.chal["realm"]132 nonce = self._thread_local.chal["nonce"]133 qop = self._thread_local.chal.get("qop")134 algorithm = self._thread_local.chal.get("algorithm")135 opaque = self._thread_local.chal.get("opaque")136 hash_utf8 = None137138 if algorithm is None:140 _algorithm = 'MD5'139 _algorithm = "MD5"140 else:141 _algorithm = algorithm.upper()142 # lambdas assume digest modules are imported at the top level144 if _algorithm == 'MD5' or _algorithm == 'MD5-SESS':143 if _algorithm == "MD5" or _algorithm == "MD5-SESS":144145 def md5_utf8(x):146 if isinstance(x, str):147 x = x.encode('utf-8')147 x = x.encode("utf-8")148 return hashlib.md5(x).hexdigest()149150 hash_utf8 = md5_utf8150 elif _algorithm == 'SHA':151 elif _algorithm == "SHA":152153 def sha_utf8(x):154 if isinstance(x, str):153 x = x.encode('utf-8')155 x = x.encode("utf-8")156 return hashlib.sha1(x).hexdigest()157158 hash_utf8 = sha_utf8156 elif _algorithm == 'SHA-256':159 elif _algorithm == "SHA-256":160161 def sha256_utf8(x):162 if isinstance(x, str):159 x = x.encode('utf-8')163 x = x.encode("utf-8")164 return hashlib.sha256(x).hexdigest()165166 hash_utf8 = sha256_utf8162 elif _algorithm == 'SHA-512':167 elif _algorithm == "SHA-512":168169 def sha512_utf8(x):170 if isinstance(x, str):165 x = x.encode('utf-8')171 x = x.encode("utf-8")172 return hashlib.sha512(x).hexdigest()173174 hash_utf8 = sha512_utf8175169 KD = lambda s, d: hash_utf8("%s:%s" % (s, d))176 KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731177178 if hash_utf8 is None:179 return None180
2 unmodified lines
183 p_parsed = urlparse(url)184 #: path is request-uri defined in RFC 2616 which should not be empty185 path = p_parsed.path or "/"186 if p_parsed.query:180 path += '?' + p_parsed.query187 path += f"?{p_parsed.query}"188182 A1 = '%s:%s:%s' % (self.username, realm, self.password)183 A2 = '%s:%s' % (method, path)189 A1 = f"{self.username}:{realm}:{self.password}"190 A2 = f"{method}:{path}"191192 HA1 = hash_utf8(A1)193 HA2 = hash_utf8(A2)194195 if nonce == self._thread_local.last_nonce:196 self._thread_local.nonce_count += 1197 else:198 self._thread_local.nonce_count = 1192 ncvalue = '%08x' % self._thread_local.nonce_count193 s = str(self._thread_local.nonce_count).encode('utf-8')194 s += nonce.encode('utf-8')195 s += time.ctime().encode('utf-8')199 ncvalue = f"{self._thread_local.nonce_count:08x}"200 s = str(self._thread_local.nonce_count).encode("utf-8")201 s += nonce.encode("utf-8")202 s += time.ctime().encode("utf-8")203 s += os.urandom(8)204198 cnonce = (hashlib.sha1(s).hexdigest()[:16])199 if _algorithm == 'MD5-SESS':200 HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))205 cnonce = hashlib.sha1(s).hexdigest()[:16]206 if _algorithm == "MD5-SESS":207 HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}")208209 if not qop:203 respdig = KD(HA1, "%s:%s" % (nonce, HA2))204 elif qop == 'auth' or 'auth' in qop.split(','):205 noncebit = "%s:%s:%s:%s:%s" % (206 nonce, ncvalue, cnonce, 'auth', HA2207 )210 respdig = KD(HA1, f"{nonce}:{HA2}")211 elif qop == "auth" or "auth" in qop.split(","):212 noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}"213 respdig = KD(HA1, noncebit)214 else:215 # XXX handle auth-int.216 return None217218 self._thread_local.last_nonce = nonce219220 # XXX should the partial digests be encoded too?216 base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \217 'response="%s"' % (self.username, realm, nonce, path, respdig)221 base = (222 f'username="{self.username}", realm="{realm}", nonce="{nonce}", '223 f'uri="{path}", response="{respdig}"'224 )225 if opaque:219 base += ', opaque="%s"' % opaque226 base += f', opaque="{opaque}"'227 if algorithm:221 base += ', algorithm="%s"' % algorithm228 base += f', algorithm="{algorithm}"'229 if entdig:223 base += ', digest="%s"' % entdig230 base += f', digest="{entdig}"'231 if qop:225 base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)232 base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"'233227 return 'Digest %s' % (base)234 return f"Digest {base}"235236 def handle_redirect(self, r, **kwargs):237 """Reset num_401_calls counter on redirects."""238 if r.is_redirect:
15 unmodified lines
254 if self._thread_local.pos is not None:255 # Rewind the file position indicator of the body to where256 # it was to resend the request.257 r.request.body.seek(self._thread_local.pos)251 s_auth = r.headers.get('www-authenticate', '')258 s_auth = r.headers.get("www-authenticate", "")259253 if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:260 if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2:261262 self._thread_local.num_401_calls += 1256 pat = re.compile(r'digest ', flags=re.IGNORECASE)257 self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))263 pat = re.compile(r"digest ", flags=re.IGNORECASE)264 self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1))265266 # Consume content and release the original connection267 # to allow our new request to reuse the same one.268 r.content
1 unmodified line
270 prep = r.request.copy()271 extract_cookies_to_jar(prep._cookies, r.request, r.raw)272 prep.prepare_cookies(prep._cookies)273267 prep.headers['Authorization'] = self.build_digest_header(268 prep.method, prep.url)274 prep.headers["Authorization"] = self.build_digest_header(275 prep.method, prep.url276 )277 _r = r.connection.send(prep, **kwargs)278 _r.history.append(r)279 _r.request = prep280
6 unmodified lines
287 # Initialize per-thread state, if needed288 self.init_per_thread_state()289 # If we have a saved nonce, skip the 401290 if self._thread_local.last_nonce:283 r.headers['Authorization'] = self.build_digest_header(r.method, r.url)291 r.headers["Authorization"] = self.build_digest_header(r.method, r.url)292 try:293 self._thread_local.pos = r.body.tell()294 except AttributeError:295 # In the case of HTTPDigestAuth being reused and the body of296 # the previous request was a file-like object, pos has the297 # file position of the previous body. Ensure it's set to298 # None.299 self._thread_local.pos = None292 r.register_hook('response', self.handle_401)293 r.register_hook('response', self.handle_redirect)300 r.register_hook("response", self.handle_401)301 r.register_hook("response", self.handle_redirect)302 self._thread_local.num_401_calls = 1303304 return r305306 def __eq__(self, other):299 return all([300 self.username == getattr(other, 'username', None),301 self.password == getattr(other, 'password', None)302 ])307 return all(308 [309 self.username == getattr(other, "username", None),310 self.password == getattr(other, "password", None),311 ]312 )313314 def __ne__(self, other):315 return not self == other
modified:requests/certs.py+1 added-2 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-23"""4requests.certs5~~~~~~~~~~~~~~
6 unmodified lines
12packaged CA bundle.13"""14from certifi import where1517if __name__ == '__main__':16if __name__ == "__main__":17 print(where())
modified:requests/compat.py+28 added-12 removed
1# -*- coding: utf-8 -*-21"""2requests.compat3~~~~~~~~~~~~~~~4
16 unmodified lines
21# Syntax sugar.22_ver = sys.version_info2324#: Python 2.x?27is_py2 = (_ver[0] == 2)25is_py2 = _ver[0] == 22627#: Python 3.x?30is_py3 = (_ver[0] == 3)28is_py3 = _ver[0] == 32930# json/simplejson module import resolution31has_simplejson = False32try:33 import simplejson as json3435 has_simplejson = True36except ImportError:37 import json38
1 unmodified line
40 from simplejson import JSONDecodeError41else:42 from json import JSONDecodeError4345# ---------46# Legacy Imports47# ---------48from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag49from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment44# Keep OrderedDict for backwards compatibility.45from collections import OrderedDict46from collections.abc import Callable, Mapping, MutableMapping47from http import cookiejar as cookielib48from http.cookies import Morsel49from io import StringIO5054# Keep OrderedDict for backwards compatibility.55from collections import OrderedDict56from collections.abc import Callable, Mapping, MutableMapping51# --------------52# Legacy Imports53# --------------54from urllib.parse import (55 quote,56 quote_plus,57 unquote,58 unquote_plus,59 urldefrag,60 urlencode,61 urljoin,62 urlparse,63 urlsplit,64 urlunparse,65)66from urllib.request import (67 getproxies,68 getproxies_environment,69 parse_http_list,70 proxy_bypass,71 proxy_bypass_environment,72)7374builtin_str = str75str = str76bytes = bytes
3 unmodified lines
modified:requests/cookies.py+82 added-70 removed
1# -*- coding: utf-8 -*-21"""2requests.cookies3~~~~~~~~~~~~~~~~4
1 unmodified line
67requests.utils imports from here, so be careful with imports.8"""910import calendar11import copy12import time14import calendar1314from ._internal_utils import to_native_string17from .compat import cookielib, urlparse, urlunparse, Morsel, MutableMapping15from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse1617try:18 import threading19except ImportError:20 import dummy_threading as threading212225class MockRequest(object):23class MockRequest:24 """Wraps a `requests.Request` to mimic a `urllib2.Request`.2526 The code in `cookielib.CookieJar` expects this interface in order to correctly27 manage cookie policies, i.e., determine whether a cookie can be set, given the
20 unmodified lines
4849 def get_full_url(self):50 # Only return the response's URL if the user hadn't set the Host51 # header54 if not self._r.headers.get('Host'):52 if not self._r.headers.get("Host"):53 return self._r.url54 # If they did set it, retrieve it and reconstruct the expected domain57 host = to_native_string(self._r.headers['Host'], encoding='utf-8')55 host = to_native_string(self._r.headers["Host"], encoding="utf-8")56 parsed = urlparse(self._r.url)57 # Reconstruct the URL as we expect it60 return urlunparse([61 parsed.scheme, host, parsed.path, parsed.params, parsed.query,62 parsed.fragment63 ])58 return urlunparse(59 [60 parsed.scheme,61 host,62 parsed.path,63 parsed.params,64 parsed.query,65 parsed.fragment,66 ]67 )6869 def is_unverifiable(self):70 return True71
4 unmodified lines
76 return self._r.headers.get(name, self._new_headers.get(name, default))7778 def add_header(self, key, val):79 """cookielib has no legitimate use for this method; add it back if you find one."""76 raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")80 raise NotImplementedError(81 "Cookie headers should be added with add_unredirected_header()"82 )8384 def add_unredirected_header(self, name, value):85 self._new_headers[name] = value86
12 unmodified lines
99 def host(self):100 return self.get_host()10110297class MockResponse(object):103class MockResponse:104 """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.105106 ...what? Basically, expose the parsed HTTP headers from the server response107 the way `cookielib` expects to see them.
19 unmodified lines
127 :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)128 :param request: our own requests.Request object129 :param response: urllib3.HTTPResponse object130 """125 if not (hasattr(response, '_original_response') and126 response._original_response):131 if not (hasattr(response, "_original_response") and response._original_response):132 return133 # the _original_response field is the wrapped httplib.HTTPResponse object,134 req = MockRequest(request)135 # pull out the HTTPMessage with the headers and put it in the mock:
8 unmodified lines
144 :rtype: str145 """146 r = MockRequest(request)147 jar.add_cookie_header(r)143 return r.get_new_headers().get('Cookie')148 return r.get_new_headers().get("Cookie")149150151def remove_cookie_by_name(cookiejar, name, domain=None, path=None):152 """Unsets a cookie by name, by default over all domains and paths.
56 unmodified lines
209 multiple domains.210 """211 # support client code that unsets cookies by assignment of a None value:212 if value is None:208 remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))213 remove_cookie_by_name(214 self, name, domain=kwargs.get("domain"), path=kwargs.get("path")215 )216 return217218 if isinstance(value, Morsel):219 c = morsel_to_cookie(value)
91 unmodified lines
311 :rtype: dict312 """313 dictionary = {}314 for cookie in iter(self):308 if (309 (domain is None or cookie.domain == domain) and310 (path is None or cookie.path == path)315 if (domain is None or cookie.domain == domain) and (316 path is None or cookie.path == path317 ):318 dictionary[cookie.name] = cookie.value319 return dictionary320321 def __contains__(self, name):322 try:317 return super(RequestsCookieJar, self).__contains__(name)323 return super().__contains__(name)324 except CookieConflictError:325 return True326327 def __getitem__(self, name):
18 unmodified lines
346 """347 remove_cookie_by_name(self, name)348349 def set_cookie(self, cookie, *args, **kwargs):350 if (351 hasattr(cookie.value, "startswith")352 and cookie.value.startswith('"')353 and cookie.value.endswith('"')344 if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):345 cookie.value = cookie.value.replace('\\"', '')346 return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)354 ):355 cookie.value = cookie.value.replace('\\"', "")356 return super().set_cookie(cookie, *args, **kwargs)357358 def update(self, other):359 """Updates this jar with cookies from another CookieJar or dict-like"""360 if isinstance(other, cookielib.CookieJar):361 for cookie in other:362 self.set_cookie(copy.copy(cookie))363 else:354 super(RequestsCookieJar, self).update(other)364 super().update(other)365366 def _find(self, name, domain=None, path=None):367 """Requests uses this method internally to get cookie values.368
11 unmodified lines
380 if domain is None or cookie.domain == domain:381 if path is None or cookie.path == path:382 return cookie.value383374 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))384 raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")385386 def _find_no_duplicates(self, name, domain=None, path=None):387 """Both ``__get_item__`` and ``get`` call this function: it's never388 used elsewhere in Requests.
10 unmodified lines
399 for cookie in iter(self):400 if cookie.name == name:401 if domain is None or cookie.domain == domain:402 if path is None or cookie.path == path:393 if toReturn is not None: # if there are multiple cookies that meet passed in criteria394 raise CookieConflictError('There are multiple cookies with name, %r' % (name))395 toReturn = cookie.value # we will eventually return this as long as no cookie conflict403 if toReturn is not None:404 # if there are multiple cookies that meet passed in criteria405 raise CookieConflictError(406 f"There are multiple cookies with name, {name!r}"407 )408 # we will eventually return this as long as no cookie conflict409 toReturn = cookie.value410411 if toReturn:412 return toReturn399 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))413 raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")414415 def __getstate__(self):416 """Unlike a normal CookieJar, this class is pickleable."""417 state = self.__dict__.copy()418 # remove the unpickleable RLock object405 state.pop('_cookies_lock')419 state.pop("_cookies_lock")420 return state421422 def __setstate__(self, state):423 """Unlike a normal CookieJar, this class is pickleable."""424 self.__dict__.update(state)411 if '_cookies_lock' not in self.__dict__:425 if "_cookies_lock" not in self.__dict__:426 self._cookies_lock = threading.RLock()427428 def copy(self):429 """Return a copy of this RequestsCookieJar."""
10 unmodified lines
440def _copy_cookie_jar(jar):441 if jar is None:442 return None443430 if hasattr(jar, 'copy'):444 if hasattr(jar, "copy"):445 # We're dealing with an instance of RequestsCookieJar446 return jar.copy()447 # We're dealing with a generic CookieJar instance448 new_jar = copy.copy(jar)
9 unmodified lines
458 By default, the pair of `name` and `value` will be set for the domain ''459 and sent on every request (this is sometimes called a "supercookie").460 """461 result = {448 'version': 0,449 'name': name,450 'value': value,451 'port': None,452 'domain': '',453 'path': '/',454 'secure': False,455 'expires': None,456 'discard': True,457 'comment': None,458 'comment_url': None,459 'rest': {'HttpOnly': None},460 'rfc2109': False,462 "version": 0,463 "name": name,464 "value": value,465 "port": None,466 "domain": "",467 "path": "/",468 "secure": False,469 "expires": None,470 "discard": True,471 "comment": None,472 "comment_url": None,473 "rest": {"HttpOnly": None},474 "rfc2109": False,475 }476477 badargs = set(kwargs) - set(result)478 if badargs:465 err = 'create_cookie() got unexpected keyword arguments: %s'466 raise TypeError(err % list(badargs))479 raise TypeError(480 f"create_cookie() got unexpected keyword arguments: {list(badargs)}"481 )482483 result.update(kwargs)469 result['port_specified'] = bool(result['port'])470 result['domain_specified'] = bool(result['domain'])471 result['domain_initial_dot'] = result['domain'].startswith('.')472 result['path_specified'] = bool(result['path'])484 result["port_specified"] = bool(result["port"])485 result["domain_specified"] = bool(result["domain"])486 result["domain_initial_dot"] = result["domain"].startswith(".")487 result["path_specified"] = bool(result["path"])488489 return cookielib.Cookie(**result)490491492def morsel_to_cookie(morsel):493 """Convert a Morsel object into a Cookie containing the one k/v pair."""494495 expires = None481 if morsel['max-age']:496 if morsel["max-age"]:497 try:483 expires = int(time.time() + int(morsel['max-age']))498 expires = int(time.time() + int(morsel["max-age"]))499 except ValueError:485 raise TypeError('max-age: %s must be integer' % morsel['max-age'])486 elif morsel['expires']:487 time_template = '%a, %d-%b-%Y %H:%M:%S GMT'488 expires = calendar.timegm(489 time.strptime(morsel['expires'], time_template)490 )500 raise TypeError(f"max-age: {morsel['max-age']} must be integer")501 elif morsel["expires"]:502 time_template = "%a, %d-%b-%Y %H:%M:%S GMT"503 expires = calendar.timegm(time.strptime(morsel["expires"], time_template))504 return create_cookie(492 comment=morsel['comment'],493 comment_url=bool(morsel['comment']),505 comment=morsel["comment"],506 comment_url=bool(morsel["comment"]),507 discard=False,495 domain=morsel['domain'],508 domain=morsel["domain"],509 expires=expires,510 name=morsel.key,498 path=morsel['path'],511 path=morsel["path"],512 port=None,500 rest={'HttpOnly': morsel['httponly']},513 rest={"HttpOnly": morsel["httponly"]},514 rfc2109=False,502 secure=bool(morsel['secure']),515 secure=bool(morsel["secure"]),516 value=morsel.value,504 version=morsel['version'] or 0,517 version=morsel["version"] or 0,518 )519520521def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
24 unmodified lines
546 :param cookies: Dictionary or CookieJar object to be added.547 :rtype: CookieJar548 """549 if not isinstance(cookiejar, cookielib.CookieJar):537 raise ValueError('You can only merge into CookieJar')550 raise ValueError("You can only merge into CookieJar")551552 if isinstance(cookies, dict):540 cookiejar = cookiejar_from_dict(541 cookies, cookiejar=cookiejar, overwrite=False)553 cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)554 elif isinstance(cookies, cookielib.CookieJar):555 try:556 cookiejar.update(cookies)557 except AttributeError:
4 unmodified lines
modified:requests/exceptions.py+5 added-7 removed
1# -*- coding: utf-8 -*-21"""2requests.exceptions3~~~~~~~~~~~~~~~~~~~4
10 unmodified lines
15 """1617 def __init__(self, *args, **kwargs):18 """Initialize RequestException with `request` and `response` objects."""21 response = kwargs.pop('response', None)19 response = kwargs.pop("response", None)20 self.response = response23 self.request = kwargs.pop('request', None)24 if (response is not None and not self.request and25 hasattr(response, 'request')):21 self.request = kwargs.pop("request", None)22 if response is not None and not self.request and hasattr(response, "request"):23 self.request = self.response.request27 super(RequestException, self).__init__(*args, **kwargs)24 super().__init__(*args, **kwargs)252627class InvalidJSONError(RequestException):28 """A JSON error occurred."""
95 unmodified lines
124125class UnrewindableBodyError(RequestException):126 """Requests encountered an error when trying to rewind a body."""127128129# Warnings130131132class RequestsWarning(Warning):
9 unmodified lines
modified:requests/help.py+48 added-49 removed
1"""Module containing bug report helper(s)."""2from __future__ import print_function23import json4import platform6import sys5import ssl6import sys78import idna9import urllib310
15 unmodified lines
26 pyopenssl = None27 OpenSSL = None28 cryptography = None29else:31 import OpenSSL30 import cryptography31 import OpenSSL323334def _implementation():35 """Return a dict with the Python implementation and version.
7 unmodified lines
43 to work out the correct shape of the code for those platforms.44 """45 implementation = platform.python_implementation()4648 if implementation == 'CPython':47 if implementation == "CPython":48 implementation_version = platform.python_version()50 elif implementation == 'PyPy':51 implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,52 sys.pypy_version_info.minor,53 sys.pypy_version_info.micro)54 if sys.pypy_version_info.releaselevel != 'final':55 implementation_version = ''.join([56 implementation_version, sys.pypy_version_info.releaselevel57 ])58 elif implementation == 'Jython':49 elif implementation == "PyPy":50 implementation_version = "{}.{}.{}".format(51 sys.pypy_version_info.major,52 sys.pypy_version_info.minor,53 sys.pypy_version_info.micro,54 )55 if sys.pypy_version_info.releaselevel != "final":56 implementation_version = "".join(57 [implementation_version, sys.pypy_version_info.releaselevel]58 )59 elif implementation == "Jython":60 implementation_version = platform.python_version() # Complete Guess60 elif implementation == 'IronPython':61 elif implementation == "IronPython":62 implementation_version = platform.python_version() # Complete Guess63 else:63 implementation_version = 'Unknown'64 implementation_version = "Unknown"6565 return {'name': implementation, 'version': implementation_version}66 return {"name": implementation, "version": implementation_version}676869def info():70 """Generate information for a bug report."""71 try:72 platform_info = {72 'system': platform.system(),73 'release': platform.release(),73 "system": platform.system(),74 "release": platform.release(),75 }75 except IOError:76 except OSError:77 platform_info = {77 'system': 'Unknown',78 'release': 'Unknown',78 "system": "Unknown",79 "release": "Unknown",80 }8182 implementation_info = _implementation()82 urllib3_info = {'version': urllib3.__version__}83 charset_normalizer_info = {'version': None}84 chardet_info = {'version': None}83 urllib3_info = {"version": urllib3.__version__}84 charset_normalizer_info = {"version": None}85 chardet_info = {"version": None}86 if charset_normalizer:86 charset_normalizer_info = {'version': charset_normalizer.__version__}87 charset_normalizer_info = {"version": charset_normalizer.__version__}88 if chardet:88 chardet_info = {'version': chardet.__version__}89 chardet_info = {"version": chardet.__version__}9091 pyopenssl_info = {91 'version': None,92 'openssl_version': '',92 "version": None,93 "openssl_version": "",94 }95 if OpenSSL:96 pyopenssl_info = {96 'version': OpenSSL.__version__,97 'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER,97 "version": OpenSSL.__version__,98 "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}",99 }100 cryptography_info = {100 'version': getattr(cryptography, '__version__', ''),101 "version": getattr(cryptography, "__version__", ""),102 }103 idna_info = {103 'version': getattr(idna, '__version__', ''),104 "version": getattr(idna, "__version__", ""),105 }106107 system_ssl = ssl.OPENSSL_VERSION_NUMBER107 system_ssl_info = {108 'version': '%x' % system_ssl if system_ssl is not None else ''109 }108 system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""}109110 return {112 'platform': platform_info,113 'implementation': implementation_info,114 'system_ssl': system_ssl_info,115 'using_pyopenssl': pyopenssl is not None,116 'using_charset_normalizer': chardet is None,117 'pyOpenSSL': pyopenssl_info,118 'urllib3': urllib3_info,119 'chardet': chardet_info,120 'charset_normalizer': charset_normalizer_info,121 'cryptography': cryptography_info,122 'idna': idna_info,123 'requests': {124 'version': requests_version,111 "platform": platform_info,112 "implementation": implementation_info,113 "system_ssl": system_ssl_info,114 "using_pyopenssl": pyopenssl is not None,115 "using_charset_normalizer": chardet is None,116 "pyOpenSSL": pyopenssl_info,117 "urllib3": urllib3_info,118 "chardet": chardet_info,119 "charset_normalizer": charset_normalizer_info,120 "cryptography": cryptography_info,121 "idna": idna_info,122 "requests": {123 "version": requests_version,124 },125 }126127
1 unmodified line
129 """Pretty-print the bug information as JSON."""130 print(json.dumps(info(), sort_keys=True, indent=2))131132134if __name__ == '__main__':133if __name__ == "__main__":134 main()
modified:requests/hooks.py+3 added-4 removed
1# -*- coding: utf-8 -*-21"""2requests.hooks3~~~~~~~~~~~~~~4
3 unmodified lines
89``response``:10 The response generated from a Request.11"""14HOOKS = ['response']12HOOKS = ["response"]131415def default_hooks():16 return {event: [] for event in HOOKS}171819# TODO: response is the only one202122def dispatch_hook(key, hooks, hook_data, **kwargs):23 """Dispatches a hook dictionary on a given piece of data."""24 hooks = hooks or {}25 hooks = hooks.get(key)26 if hooks:28 if hasattr(hooks, '__call__'):27 if hasattr(hooks, "__call__"):28 hooks = [hooks]29 for hook in hooks:30 _hook_data = hook(hook_data, **kwargs)31 if _hook_data is not None:
2 unmodified lines
modified:requests/models.py+192 added-124 removed
1# -*- coding: utf-8 -*-21"""2requests.models3~~~~~~~~~~~~~~~4
4 unmodified lines
910# Import encoding now, to avoid implicit import later.11# Implicit import within threads may cause LookupError when standard library is in a ZIP,12# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.15import encodings.idna13import encodings.idna # noqa: F40114from io import UnsupportedOperation1517from urllib3.fields import RequestField18from urllib3.filepost import encode_multipart_formdata19from urllib3.util import parse_url16from urllib3.exceptions import (17 DecodeError,18 LocationParseError,19 ProtocolError,20 ReadTimeoutError,21 SSLError,22)23from urllib3.fields import RequestField24from urllib3.filepost import encode_multipart_formdata25from urllib3.util import parse_url2628from io import UnsupportedOperation29from .hooks import default_hooks30from .structures import CaseInsensitiveDict3127from ._internal_utils import to_native_string, unicode_is_ascii28from .auth import HTTPBasicAuth33from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar29from .compat import (30 Callable,31 JSONDecodeError,32 Mapping,33 basestring,34 builtin_str,35 chardet,36 cookielib,37)38from .compat import json as complexjson39from .compat import urlencode, urlsplit, urlunparse40from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header41from .exceptions import (35 HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,36 ContentDecodingError, ConnectionError, StreamConsumedError,37 InvalidJSONError)42 ChunkedEncodingError,43 ConnectionError,44 ContentDecodingError,45 HTTPError,46 InvalidJSONError,47 InvalidURL,48)49from .exceptions import JSONDecodeError as RequestsJSONDecodeError50from .exceptions import MissingSchema51from .exceptions import SSLError as RequestsSSLError40from ._internal_utils import to_native_string, unicode_is_ascii41from .utils import (42 guess_filename, get_auth_from_url, requote_uri,43 stream_decode_response_unicode, to_key_val_list, parse_header_links,44 iter_slices, guess_json_utf, super_len, check_header_validity)45from .compat import (46 Callable, Mapping,47 cookielib, urlunparse, urlsplit, urlencode,48 chardet, builtin_str, basestring, JSONDecodeError)49from .compat import json as complexjson52from .exceptions import StreamConsumedError53from .hooks import default_hooks54from .status_codes import codes55from .structures import CaseInsensitiveDict56from .utils import (57 check_header_validity,58 get_auth_from_url,59 guess_filename,60 guess_json_utf,61 iter_slices,62 parse_header_links,63 requote_uri,64 stream_decode_response_unicode,65 super_len,66 to_key_val_list,67)6869#: The set of HTTP status codes that indicate an automatically70#: processable redirect.71REDIRECT_STATI = (55 codes.moved, # 30156 codes.found, # 30257 codes.other, # 30372 codes.moved, # 30173 codes.found, # 30274 codes.other, # 30375 codes.temporary_redirect, # 30776 codes.permanent_redirect, # 30877)78
1 unmodified line
80CONTENT_CHUNK_SIZE = 10 * 102481ITER_CHUNK_SIZE = 512828367class RequestEncodingMixin(object):84class RequestEncodingMixin:85 @property86 def path_url(self):87 """Build the path URL to use."""88
2 unmodified lines
91 p = urlsplit(self.url)9293 path = p.path94 if not path:78 path = '/'95 path = "/"9697 url.append(path)9899 query = p.query100 if query:84 url.append('?')101 url.append("?")102 url.append(query)10387 return ''.join(url)104 return "".join(url)105106 @staticmethod107 def _encode_params(data):108 """Encode parameters in a piece of data.
4 unmodified lines
113 """114115 if isinstance(data, (str, bytes)):116 return data100 elif hasattr(data, 'read'):117 elif hasattr(data, "read"):118 return data102 elif hasattr(data, '__iter__'):119 elif hasattr(data, "__iter__"):120 result = []121 for k, vs in to_key_val_list(data):105 if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):122 if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):123 vs = [vs]124 for v in vs:125 if v is not None:126 result.append(110 (k.encode('utf-8') if isinstance(k, str) else k,111 v.encode('utf-8') if isinstance(v, str) else v))127 (128 k.encode("utf-8") if isinstance(k, str) else k,129 v.encode("utf-8") if isinstance(v, str) else v,130 )131 )132 return urlencode(result, doseq=True)133 else:134 return data135
6 unmodified lines
142 if parameters are supplied as a dict.143 The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)144 or 4-tuples (filename, fileobj, contentype, custom_headers).145 """126 if (not files):146 if not files:147 raise ValueError("Files must be provided.")148 elif isinstance(data, basestring):149 raise ValueError("Data must not be a string.")150
1 unmodified line
152 fields = to_key_val_list(data or {})153 files = to_key_val_list(files or {})154155 for field, val in fields:136 if isinstance(val, basestring) or not hasattr(val, '__iter__'):156 if isinstance(val, basestring) or not hasattr(val, "__iter__"):157 val = [val]158 for v in val:159 if v is not None:160 # Don't call str() on bytestrings: in Py3 it all goes wrong.161 if not isinstance(v, bytes):162 v = str(v)163164 new_fields.append(145 (field.decode('utf-8') if isinstance(field, bytes) else field,146 v.encode('utf-8') if isinstance(v, str) else v))165 (166 field.decode("utf-8")167 if isinstance(field, bytes)168 else field,169 v.encode("utf-8") if isinstance(v, str) else v,170 )171 )172173 for (k, v) in files:174 # support for explicit filename175 ft = None
10 unmodified lines
186 fp = v187188 if isinstance(fp, (str, bytes, bytearray)):189 fdata = fp165 elif hasattr(fp, 'read'):190 elif hasattr(fp, "read"):191 fdata = fp.read()192 elif fp is None:193 continue194 else:
7 unmodified lines
202203 return body, content_type204205181class RequestHooksMixin(object):206class RequestHooksMixin:207 def register_hook(self, event, hook):208 """Properly register a hook."""209210 if event not in self.hooks:186 raise ValueError('Unsupported event specified, with event name "%s"' % (event))211 raise ValueError(f'Unsupported event specified, with event name "{event}"')212213 if isinstance(hook, Callable):214 self.hooks[event].append(hook)190 elif hasattr(hook, '__iter__'):215 elif hasattr(hook, "__iter__"):216 self.hooks[event].extend(h for h in hook if isinstance(h, Callable))217218 def deregister_hook(self, event, hook):219 """Deregister a previously registered hook.
34 unmodified lines
254 >>> req.prepare()255 <PreparedRequest [GET]>256 """257233 def __init__(self,234 method=None, url=None, headers=None, files=None, data=None,235 params=None, auth=None, cookies=None, hooks=None, json=None):258 def __init__(259 self,260 method=None,261 url=None,262 headers=None,263 files=None,264 data=None,265 params=None,266 auth=None,267 cookies=None,268 hooks=None,269 json=None,270 ):271272 # Default empty dicts for dict params.273 data = [] if data is None else data274 files = [] if files is None else files
15 unmodified lines
290 self.auth = auth291 self.cookies = cookies292293 def __repr__(self):259 return '<Request [%s]>' % (self.method)294 return f"<Request [{self.method}]>"295296 def prepare(self):297 """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""298 p = PreparedRequest()
49 unmodified lines
348 self.hooks = default_hooks()349 #: integer denoting starting position of a readable file-like body.350 self._body_position = None351317 def prepare(self,318 method=None, url=None, headers=None, files=None, data=None,319 params=None, auth=None, cookies=None, hooks=None, json=None):352 def prepare(353 self,354 method=None,355 url=None,356 headers=None,357 files=None,358 data=None,359 params=None,360 auth=None,361 cookies=None,362 hooks=None,363 json=None,364 ):365 """Prepares the entire request with the given parameters."""366367 self.prepare_method(method)368 self.prepare_url(url, params)
8 unmodified lines
377 # This MUST go after prepare_auth. Authenticators could add a hook378 self.prepare_hooks(hooks)379380 def __repr__(self):336 return '<PreparedRequest [%s]>' % (self.method)381 return f"<PreparedRequest [{self.method}]>"382383 def copy(self):384 p = PreparedRequest()385 p.method = self.method
15 unmodified lines
401 def _get_idna_encoded_host(host):402 import idna403404 try:360 host = idna.encode(host, uts46=True).decode('utf-8')405 host = idna.encode(host, uts46=True).decode("utf-8")406 except idna.IDNAError:407 raise UnicodeError408 return host409
4 unmodified lines
414 #: as this will include the bytestring indicator (b'')415 #: on python 3.x.416 #: https://github.com/psf/requests/pull/2238417 if isinstance(url, bytes):373 url = url.decode('utf8')418 url = url.decode("utf8")419 else:420 url = str(url)421422 # Remove leading whitespaces from url
1 unmodified line
424425 # Don't do any URL preparation for non-HTTP schemes like `mailto`,426 # `data` etc to work around exceptions from `url_parse`, which427 # handles RFC 3986 only.383 if ':' in url and not url.lower().startswith('http'):428 if ":" in url and not url.lower().startswith("http"):429 self.url = url430 return431432 # Support for unicode domain names and paths.
2 unmodified lines
435 except LocationParseError as e:436 raise InvalidURL(*e.args)437438 if not scheme:394 error = ("Invalid URL {0!r}: No scheme supplied. Perhaps you meant http://{0}?")395 error = error.format(to_native_string(url, 'utf8'))439 raise MissingSchema(440 f"Invalid URL {url!r}: No scheme supplied. "441 f"Perhaps you meant http://{url}?"442 )443397 raise MissingSchema(error)398444 if not host:400 raise InvalidURL("Invalid URL %r: No host supplied" % url)445 raise InvalidURL(f"Invalid URL {url!r}: No host supplied")446447 # In general, we want to try IDNA encoding the hostname if the string contains448 # non-ASCII characters. This allows users to automatically get the correct IDNA449 # behaviour. For strings containing only ASCII characters, we need to also verify
1 unmodified line
451 if not unicode_is_ascii(host):452 try:453 host = self._get_idna_encoded_host(host)454 except UnicodeError:410 raise InvalidURL('URL has an invalid label.')411 elif host.startswith((u'*', u'.')):412 raise InvalidURL('URL has an invalid label.')455 raise InvalidURL("URL has an invalid label.")456 elif host.startswith(("*", ".")):457 raise InvalidURL("URL has an invalid label.")458459 # Carefully reconstruct the network location415 netloc = auth or ''460 netloc = auth or ""461 if netloc:417 netloc += '@'462 netloc += "@"463 netloc += host464 if port:420 netloc += ':' + str(port)465 netloc += f":{port}"466467 # Bare domains aren't valid URLs.468 if not path:424 path = '/'469 path = "/"470471 if isinstance(params, (str, bytes)):472 params = to_native_string(params)473474 enc_params = self._encode_params(params)475 if enc_params:476 if query:432 query = '%s&%s' % (query, enc_params)477 query = f"{query}&{enc_params}"478 else:479 query = enc_params480481 url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
22 unmodified lines
504505 if not data and json is not None:506 # urllib3 requires a bytes-like body. Python 2's json.dumps507 # provides this natively, but Python 3 gives a Unicode string.463 content_type = 'application/json'508 content_type = "application/json"509510 try:511 body = complexjson.dumps(json, allow_nan=False)512 except ValueError as ve:513 raise InvalidJSONError(ve, request=self)514515 if not isinstance(body, bytes):471 body = body.encode('utf-8')516 body = body.encode("utf-8")517473 is_stream = all([474 hasattr(data, '__iter__'),475 not isinstance(data, (basestring, list, tuple, Mapping))476 ])518 is_stream = all(519 [520 hasattr(data, "__iter__"),521 not isinstance(data, (basestring, list, tuple, Mapping)),522 ]523 )524525 if is_stream:526 try:527 length = super_len(data)
1 unmodified line
529 length = None530531 body = data532486 if getattr(body, 'tell', None) is not None:533 if getattr(body, "tell", None) is not None:534 # Record the current file position before reading.535 # This will allow us to rewind a file in the event536 # of a redirect.537 try:538 self._body_position = body.tell()492 except (IOError, OSError):539 except OSError:540 # This differentiates from None, allowing us to catch541 # a failed `tell()` later when trying to rewind the body542 self._body_position = object()543544 if files:498 raise NotImplementedError('Streamed bodies and files are mutually exclusive.')545 raise NotImplementedError(546 "Streamed bodies and files are mutually exclusive."547 )548549 if length:501 self.headers['Content-Length'] = builtin_str(length)550 self.headers["Content-Length"] = builtin_str(length)551 else:503 self.headers['Transfer-Encoding'] = 'chunked'552 self.headers["Transfer-Encoding"] = "chunked"553 else:554 # Multi-part file uploads.555 if files:556 (body, content_type) = self._encode_files(files, data)557 else:558 if data:559 body = self._encode_params(data)511 if isinstance(data, basestring) or hasattr(data, 'read'):560 if isinstance(data, basestring) or hasattr(data, "read"):561 content_type = None562 else:514 content_type = 'application/x-www-form-urlencoded'563 content_type = "application/x-www-form-urlencoded"564565 self.prepare_content_length(body)566567 # Add content-type if it wasn't explicitly provided.519 if content_type and ('content-type' not in self.headers):520 self.headers['Content-Type'] = content_type568 if content_type and ("content-type" not in self.headers):569 self.headers["Content-Type"] = content_type570571 self.body = body572573 def prepare_content_length(self, body):
2 unmodified lines
576 length = super_len(body)577 if length:578 # If length exists, set it. Otherwise, we fallback579 # to Transfer-Encoding: chunked.531 self.headers['Content-Length'] = builtin_str(length)532 elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:580 self.headers["Content-Length"] = builtin_str(length)581 elif (582 self.method not in ("GET", "HEAD")583 and self.headers.get("Content-Length") is None584 ):585 # Set Content-Length to 0 for methods that can have a body586 # but don't provide one. (i.e. not GET or HEAD)535 self.headers['Content-Length'] = '0'587 self.headers["Content-Length"] = "0"588537 def prepare_auth(self, auth, url=''):589 def prepare_auth(self, auth, url=""):590 """Prepares the given HTTP auth data."""591592 # If no Auth is explicitly provided, extract it from the URL first.593 if auth is None:
31 unmodified lines
625 self._cookies = cookiejar_from_dict(cookies)626627 cookie_header = get_cookie_header(self._cookies, self)628 if cookie_header is not None:577 self.headers['Cookie'] = cookie_header629 self.headers["Cookie"] = cookie_header630631 def prepare_hooks(self, hooks):632 """Prepares the given hooks."""633 # hooks can be passed as None to the prepare method and to this
3 unmodified lines
637 for event in hooks:638 self.register_hook(event, hooks[event])639640589class Response(object):641class Response:642 """The :class:`Response <Response>` object, which contains a643 server's response to an HTTP request.644 """645646 __attrs__ = [595 '_content', 'status_code', 'headers', 'url', 'history',596 'encoding', 'reason', 'cookies', 'elapsed', 'request'647 "_content",648 "status_code",649 "headers",650 "url",651 "history",652 "encoding",653 "reason",654 "cookies",655 "elapsed",656 "request",657 ]658659 def __init__(self):660 self._content = False
60 unmodified lines
721 for name, value in state.items():722 setattr(self, name, value)723724 # pickled objects do not have .raw665 setattr(self, '_content_consumed', True)666 setattr(self, 'raw', None)725 setattr(self, "_content_consumed", True)726 setattr(self, "raw", None)727728 def __repr__(self):669 return '<Response [%s]>' % (self.status_code)729 return f"<Response [{self.status_code}]>"730731 def __bool__(self):732 """Returns True if :attr:`status_code` is less than 400.733
37 unmodified lines
771 def is_redirect(self):772 """True if this Response is a well-formed HTTP redirect that could have773 been processed automatically (by :meth:`Session.resolve_redirects`).774 """715 return ('location' in self.headers and self.status_code in REDIRECT_STATI)775 return "location" in self.headers and self.status_code in REDIRECT_STATI776777 @property778 def is_permanent_redirect(self):779 """True if this Response one of the permanent versions of redirect."""720 return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))780 return "location" in self.headers and self.status_code in (781 codes.moved_permanently,782 codes.permanent_redirect,783 )784785 @property786 def next(self):787 """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
1 unmodified line
789790 @property791 def apparent_encoding(self):792 """The apparent encoding, provided by the charset_normalizer or chardet libraries."""730 return chardet.detect(self.content)['encoding']793 return chardet.detect(self.content)["encoding"]794795 def iter_content(self, chunk_size=1, decode_unicode=False):796 """Iterates over the response data. When stream=True is set on the797 request, this avoids reading the content at once into memory for
12 unmodified lines
810 """811812 def generate():813 # Special case for urllib3.751 if hasattr(self.raw, 'stream'):814 if hasattr(self.raw, "stream"):815 try:816 for chunk in self.raw.stream(chunk_size, decode_content=True):817 yield chunk818 except ProtocolError as e:
16 unmodified lines
835836 if self._content_consumed and isinstance(self._content, bool):837 raise StreamConsumedError()838 elif chunk_size is not None and not isinstance(chunk_size, int):776 raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size))839 raise TypeError(840 f"chunk_size must be an int, it is instead a {type(chunk_size)}."841 )842 # simulate reading small chunks of the content843 reused_chunks = iter_slices(self._content, chunk_size)844845 stream_chunks = generate()
4 unmodified lines
850 chunks = stream_decode_response_unicode(chunks, self)851852 return chunks853789 def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None):854 def iter_lines(855 self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None856 ):857 """Iterates over the response data, one line at a time. When858 stream=True is set on the request, this avoids reading the859 content at once into memory for large responses.860
1 unmodified line
862 """863864 pending = None865799 for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):866 for chunk in self.iter_content(867 chunk_size=chunk_size, decode_unicode=decode_unicode868 ):869870 if pending is not None:871 chunk = pending + chunk872
6 unmodified lines
879 pending = lines.pop()880 else:881 pending = None882814 for line in lines:815 yield line883 yield from lines884885 if pending is not None:886 yield pending887
3 unmodified lines
891892 if self._content is False:893 # Read the contents.894 if self._content_consumed:827 raise RuntimeError(828 'The content for this response was already consumed')895 raise RuntimeError("The content for this response was already consumed")896897 if self.status_code == 0 or self.raw is None:898 self._content = None899 else:833 self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''900 self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""901902 self._content_consumed = True903 # don't need to release the connection; that's been handled by urllib3904 # since we exhausted the data.
16 unmodified lines
921 content = None922 encoding = self.encoding923924 if not self.content:858 return str('')925 return ""926927 # Fallback to auto-detected encoding.928 if self.encoding is None:929 encoding = self.apparent_encoding930931 # Decode unicode from given encoding.932 try:866 content = str(self.content, encoding, errors='replace')933 content = str(self.content, encoding, errors="replace")934 except (LookupError, TypeError):935 # A LookupError is raised if the encoding was not found which could936 # indicate a misspelling or similar mistake.937 #938 # A TypeError can be raised if encoding is None939 #940 # So we try blindly encoding.874 content = str(self.content, errors='replace')941 content = str(self.content, errors="replace")942943 return content944945 def json(self, **kwargs):
11 unmodified lines
957 # a best guess).958 encoding = guess_json_utf(self.content)959 if encoding is not None:960 try:894 return complexjson.loads(895 self.content.decode(encoding), **kwargs896 )961 return complexjson.loads(self.content.decode(encoding), **kwargs)962 except UnicodeDecodeError:963 # Wrong UTF codec detected; usually because it's not UTF-8964 # but some other 8-bit codec. This is an RFC violation,965 # and the server didn't bother to tell us what codec *was*
12 unmodified lines
978 @property979 def links(self):980 """Returns the parsed header links of the response, if any."""981917 header = self.headers.get('link')982 header = self.headers.get("link")983919 # l = MultiDict()920 l = {}984 resolved_links = {}985986 if header:987 links = parse_header_links(header)988989 for link in links:926 key = link.get('rel') or link.get('url')927 l[key] = link990 key = link.get("rel") or link.get("url")991 resolved_links[key] = link992929 return l993 return resolved_links994995 def raise_for_status(self):996 """Raises :class:`HTTPError`, if one occurred."""997934 http_error_msg = ''998 http_error_msg = ""999 if isinstance(self.reason, bytes):1000 # We attempt to decode utf-8 first because some servers1001 # choose to localize their reason strings. If the string1002 # isn't utf-8, we fall back to iso-8859-1 for all other1003 # encodings. (See PR #3538)1004 try:941 reason = self.reason.decode('utf-8')1005 reason = self.reason.decode("utf-8")1006 except UnicodeDecodeError:943 reason = self.reason.decode('iso-8859-1')1007 reason = self.reason.decode("iso-8859-1")1008 else:1009 reason = self.reason10101011 if 400 <= self.status_code < 500:948 http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)1012 http_error_msg = (1013 f"{self.status_code} Client Error: {reason} for url: {self.url}"1014 )10151016 elif 500 <= self.status_code < 600:951 http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)1017 http_error_msg = (1018 f"{self.status_code} Server Error: {reason} for url: {self.url}"1019 )10201021 if http_error_msg:1022 raise HTTPError(http_error_msg, response=self)1023
5 unmodified lines
1029 """1030 if not self._content_consumed:1031 self.raw.close()1032965 release_conn = getattr(self.raw, 'release_conn', None)1033 release_conn = getattr(self.raw, "release_conn", None)1034 if release_conn is not None:1035 release_conn()
modified:requests/packages.py+9 added-7 removed
1 unmodified line
23try:4 import chardet5except ImportError:6 import charset_normalizer as chardet6 import warnings79 warnings.filterwarnings('ignore', 'Trying to detect', module='charset_normalizer')8 import charset_normalizer as chardet910 warnings.filterwarnings("ignore", "Trying to detect", module="charset_normalizer")1112# This code exists for backwards compatibility reasons.13# I don't like it either. Just look the other way. :)1414for package in ('urllib3', 'idna'):15for package in ("urllib3", "idna"):16 locals()[package] = __import__(package)17 # This traversal is apparently necessary such that the identities are18 # preserved (requests.packages.urllib3.* is urllib3.*)19 for mod in list(sys.modules):19 if mod == package or mod.startswith(package + '.'):20 sys.modules['requests.packages.' + mod] = sys.modules[mod]20 if mod == package or mod.startswith(f"{package}."):21 sys.modules[f"requests.packages.{mod}"] = sys.modules[mod]2223target = chardet.__name__24for mod in list(sys.modules):24 if mod == target or mod.startswith(target + '.'):25 sys.modules['requests.packages.' + target.replace(target, 'chardet')] = sys.modules[mod]25 if mod == target or mod.startswith(f"{target}."):26 target = target.replace(target, "chardet")27 sys.modules[f"requests.packages.{target}"] = sys.modules[mod]28# Kinda cool, though, right?
modified:requests/sessions.py+161 added-104 removed
1# -*- coding: utf-8 -*-21"""2requests.sessions3~~~~~~~~~~~~~~~~~4
2 unmodified lines
7"""8import os9import sys10import time13from datetime import timedelta11from collections import OrderedDict12from datetime import timedelta1314from ._internal_utils import to_native_string15from .adapters import HTTPAdapter16from .auth import _basic_auth_str17from .compat import cookielib, urljoin, urlparse, Mapping17from .compat import Mapping, cookielib, urljoin, urlparse18from .cookies import (19 cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)20from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT21from .hooks import default_hooks, dispatch_hook22from ._internal_utils import to_native_string23from .utils import to_key_val_list, default_headers, DEFAULT_PORTS19 RequestsCookieJar,20 cookiejar_from_dict,21 extract_cookies_to_jar,22 merge_cookies,23)24from .exceptions import (25 TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError)25 ChunkedEncodingError,26 ContentDecodingError,27 InvalidSchema,28 TooManyRedirects,29)30from .hooks import default_hooks, dispatch_hook3132# formerly defined here, reexposed here for backward compatibility33from .models import ( # noqa: F40134 DEFAULT_REDIRECT_LIMIT,35 REDIRECT_STATI,36 PreparedRequest,37 Request,38)39from .status_codes import codes40from .structures import CaseInsensitiveDict28from .adapters import HTTPAdapter2930from .utils import (31 requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,32 get_auth_from_url, rewind_body, resolve_proxies41from .utils import ( # noqa: F40142 DEFAULT_PORTS,43 default_headers,44 get_auth_from_url,45 get_environ_proxies,46 get_netrc_auth,47 requote_uri,48 resolve_proxies,49 rewind_body,50 should_bypass_proxies,51 to_key_val_list,52)5335from .status_codes import codes3637# formerly defined here, reexposed here for backward compatibility38from .models import REDIRECT_STATI3954# Preferred clock, based on which one is more accurate on a given system.41if sys.platform == 'win32':55if sys.platform == "win32":56 preferred_clock = time.perf_counter57else:58 preferred_clock = time.time59
11 unmodified lines
71 return session_setting7273 # Bypass if not a dictionary (e.g. verify)74 if not (61 isinstance(session_setting, Mapping) and62 isinstance(request_setting, Mapping)75 isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)76 ):77 return request_setting7879 merged_setting = dict_class(to_key_val_list(session_setting))
13 unmodified lines
9394 This is necessary because when request_hooks == {'response': []}, the95 merge breaks Session hooks entirely.96 """84 if session_hooks is None or session_hooks.get('response') == []:97 if session_hooks is None or session_hooks.get("response") == []:98 return request_hooks9987 if request_hooks is None or request_hooks.get('response') == []:100 if request_hooks is None or request_hooks.get("response") == []:101 return session_hooks102103 return merge_setting(request_hooks, session_hooks, dict_class)10410593class SessionRedirectMixin(object):94106class SessionRedirectMixin:107 def get_redirect_target(self, resp):108 """Receives a Response. Returns a redirect URI or ``None``"""109 # Due to the nature of how requests processes redirects this method will110 # be called at least once upon the original response and at least twice
1 unmodified line
112 # If a custom mixin is used to handle this logic, it may be advantageous113 # to cache the redirect location onto the response object as a private114 # attribute.115 if resp.is_redirect:104 location = resp.headers['location']116 location = resp.headers["location"]117 # Currently the underlying http module on py3 decode headers118 # in latin1, but empirical evidence suggests that latin1 is very119 # rarely used with non-ASCII characters in HTTP headers.120 # It is more likely to get UTF8 header rather than latin1.121 # This causes incorrect handling of UTF8 encoded location headers.122 # To solve this, we re-encode the location in latin1.111 location = location.encode('latin1')112 return to_native_string(location, 'utf8')123 location = location.encode("latin1")124 return to_native_string(location, "utf8")125 return None126127 def should_strip_auth(self, old_url, new_url):128 """Decide whether Authorization header should be removed when redirecting"""
4 unmodified lines
133 # Special case: allow http -> https redirect when using the standard134 # ports. This isn't specified by RFC 7235, but is kept to avoid135 # breaking backwards compatibility with older versions of requests136 # that allowed any redirects on the same host.125 if (old_parsed.scheme == 'http' and old_parsed.port in (80, None)126 and new_parsed.scheme == 'https' and new_parsed.port in (443, None)):137 if (138 old_parsed.scheme == "http"139 and old_parsed.port in (80, None)140 and new_parsed.scheme == "https"141 and new_parsed.port in (443, None)142 ):143 return False144145 # Handle default port usage corresponding to scheme.146 changed_port = old_parsed.port != new_parsed.port147 changed_scheme = old_parsed.scheme != new_parsed.scheme148 default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)149 if (150 not changed_scheme133 if (not changed_scheme and old_parsed.port in default_port134 and new_parsed.port in default_port):151 and old_parsed.port in default_port152 and new_parsed.port in default_port153 ):154 return False155156 # Standard case: root URI must match157 return changed_port or changed_scheme158140 def resolve_redirects(self, resp, req, stream=False, timeout=None,141 verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):159 def resolve_redirects(160 self,161 resp,162 req,163 stream=False,164 timeout=None,165 verify=True,166 cert=None,167 proxies=None,168 yield_requests=False,169 **adapter_kwargs,170 ):171 """Receives a Response. Returns a generator of Responses or Requests."""172173 hist = [] # keep track of history174
12 unmodified lines
187 except (ChunkedEncodingError, ContentDecodingError, RuntimeError):188 resp.raw.read(decode_content=False)189190 if len(resp.history) >= self.max_redirects:162 raise TooManyRedirects('Exceeded {} redirects.'.format(self.max_redirects), response=resp)191 raise TooManyRedirects(192 f"Exceeded {self.max_redirects} redirects.", response=resp193 )194195 # Release the connection back into the pool.196 resp.close()197198 # Handle redirection without scheme (see: RFC 1808 Section 4)168 if url.startswith('//'):199 if url.startswith("//"):200 parsed_rurl = urlparse(resp.url)170 url = ':'.join([to_native_string(parsed_rurl.scheme), url])201 url = ":".join([to_native_string(parsed_rurl.scheme), url])202203 # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)204 parsed = urlparse(url)174 if parsed.fragment == '' and previous_fragment:205 if parsed.fragment == "" and previous_fragment:206 parsed = parsed._replace(fragment=previous_fragment)207 elif parsed.fragment:208 previous_fragment = parsed.fragment209 url = parsed.geturl()
10 unmodified lines
220221 self.rebuild_method(prepared_request, resp)222223 # https://github.com/psf/requests/issues/1084193 if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):224 if resp.status_code not in (225 codes.temporary_redirect,226 codes.permanent_redirect,227 ):228 # https://github.com/psf/requests/issues/3490195 purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding')229 purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding")230 for header in purged_headers:231 prepared_request.headers.pop(header, None)232 prepared_request.body = None233234 headers = prepared_request.headers201 headers.pop('Cookie', None)235 headers.pop("Cookie", None)236237 # Extract any cookies sent on the response to the cookiejar238 # in the new request. Because we've mutated our copied prepared239 # request, use the old one that we haven't yet touched.
7 unmodified lines
247248 # A failed tell() sets `_body_position` to `object()`. This non-None249 # value ensures `rewindable` will be True, allowing us to raise an250 # UnrewindableBodyError, instead of hanging the connection.217 rewindable = (218 prepared_request._body_position is not None and219 ('Content-Length' in headers or 'Transfer-Encoding' in headers)251 rewindable = prepared_request._body_position is not None and (252 "Content-Length" in headers or "Transfer-Encoding" in headers253 )254255 # Attempt to rewind consumed file-like object.256 if rewindable:
13 unmodified lines
270 verify=verify,271 cert=cert,272 proxies=proxies,273 allow_redirects=False,241 **adapter_kwargs274 **adapter_kwargs,275 )276277 extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)278
8 unmodified lines
287 """288 headers = prepared_request.headers289 url = prepared_request.url290258 if 'Authorization' in headers and self.should_strip_auth(response.request.url, url):291 if "Authorization" in headers and self.should_strip_auth(292 response.request.url, url293 ):294 # If we get redirected to a new host, we should strip out any295 # authentication headers.261 del headers['Authorization']296 del headers["Authorization"]297298 # .netrc might have more auth for us on our new host.299 new_auth = get_netrc_auth(url) if self.trust_env else None300 if new_auth is not None:
14 unmodified lines
315 headers = prepared_request.headers316 scheme = urlparse(prepared_request.url).scheme317 new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)318284 if 'Proxy-Authorization' in headers:285 del headers['Proxy-Authorization']319 if "Proxy-Authorization" in headers:320 del headers["Proxy-Authorization"]321322 try:323 username, password = get_auth_from_url(new_proxies[scheme])324 except KeyError:325 username, password = None, None326327 if username and password:293 headers['Proxy-Authorization'] = _basic_auth_str(username, password)328 headers["Proxy-Authorization"] = _basic_auth_str(username, password)329330 return new_proxies331332 def rebuild_method(self, prepared_request, response):
2 unmodified lines
335 """336 method = prepared_request.method337338 # https://tools.ietf.org/html/rfc7231#section-6.4.4304 if response.status_code == codes.see_other and method != 'HEAD':305 method = 'GET'339 if response.status_code == codes.see_other and method != "HEAD":340 method = "GET"341342 # Do what the browsers do, despite standards...343 # First, turn 302s into GETs.309 if response.status_code == codes.found and method != 'HEAD':310 method = 'GET'344 if response.status_code == codes.found and method != "HEAD":345 method = "GET"346347 # Second, if a POST is responded to with a 301, turn it into a GET.348 # This bizarre behaviour is explained in Issue 1704.314 if response.status_code == codes.moved and method == 'POST':315 method = 'GET'349 if response.status_code == codes.moved and method == "POST":350 method = "GET"351352 prepared_request.method = method353354
16 unmodified lines
371 <Response [200]>372 """373374 __attrs__ = [340 'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify',341 'cert', 'adapters', 'stream', 'trust_env',342 'max_redirects',375 "headers",376 "cookies",377 "auth",378 "proxies",379 "hooks",380 "params",381 "verify",382 "cert",383 "adapters",384 "stream",385 "trust_env",386 "max_redirects",387 ]388389 def __init__(self):390
53 unmodified lines
444 self.cookies = cookiejar_from_dict({})445446 # Default connection adapters.447 self.adapters = OrderedDict()404 self.mount('https://', HTTPAdapter())405 self.mount('http://', HTTPAdapter())448 self.mount("https://", HTTPAdapter())449 self.mount("http://", HTTPAdapter())450451 def __enter__(self):452 return self453
17 unmodified lines
471 cookies = cookiejar_from_dict(cookies)472473 # Merge with session cookies474 merged_cookies = merge_cookies(431 merge_cookies(RequestsCookieJar(), self.cookies), cookies)475 merge_cookies(RequestsCookieJar(), self.cookies), cookies476 )477478 # Set environment's basic authentication if not explicitly set.479 auth = request.auth480 if self.trust_env and not auth and not self.auth:
5 unmodified lines
486 url=request.url,487 files=request.files,488 data=request.data,489 json=request.json,445 headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),490 headers=merge_setting(491 request.headers, self.headers, dict_class=CaseInsensitiveDict492 ),493 params=merge_setting(request.params, self.params),494 auth=merge_setting(auth, self.auth),495 cookies=merged_cookies,496 hooks=merge_hooks(request.hooks, self.hooks),497 )498 return p499453 def request(self, method, url,454 params=None, data=None, headers=None, cookies=None, files=None,455 auth=None, timeout=None, allow_redirects=True, proxies=None,456 hooks=None, stream=None, verify=None, cert=None, json=None):500 def request(501 self,502 method,503 url,504 params=None,505 data=None,506 headers=None,507 cookies=None,508 files=None,509 auth=None,510 timeout=None,511 allow_redirects=True,512 proxies=None,513 hooks=None,514 stream=None,515 verify=None,516 cert=None,517 json=None,518 ):519 """Constructs a :class:`Request <Request>`, prepares it and sends it.520 Returns :class:`Response <Response>` object.521522 :param method: method for the new :class:`Request` object.
27 unmodified lines
550 to a CA bundle to use. Defaults to ``True``. When set to551 ``False``, requests will accept any TLS certificate presented by552 the server, and will ignore hostname mismatches and/or expired553 certificates, which will make your application vulnerable to492 man-in-the-middle (MitM) attacks. Setting verify to ``False`` 554 man-in-the-middle (MitM) attacks. Setting verify to ``False``555 may be useful during local development or testing.556 :param cert: (optional) if String, path to ssl client cert file (.pem).557 If Tuple, ('cert', 'key') pair.558 :rtype: requests.Response
20 unmodified lines
579 )580581 # Send the request.582 send_kwargs = {521 'timeout': timeout,522 'allow_redirects': allow_redirects,583 "timeout": timeout,584 "allow_redirects": allow_redirects,585 }586 send_kwargs.update(settings)587 resp = self.send(prep, **send_kwargs)588
6 unmodified lines
595 :param \*\*kwargs: Optional arguments that ``request`` takes.596 :rtype: requests.Response597 """598537 kwargs.setdefault('allow_redirects', True)538 return self.request('GET', url, **kwargs)599 kwargs.setdefault("allow_redirects", True)600 return self.request("GET", url, **kwargs)601602 def options(self, url, **kwargs):603 r"""Sends a OPTIONS request. Returns :class:`Response` object.604
1 unmodified line
606 :param \*\*kwargs: Optional arguments that ``request`` takes.607 :rtype: requests.Response608 """609548 kwargs.setdefault('allow_redirects', True)549 return self.request('OPTIONS', url, **kwargs)610 kwargs.setdefault("allow_redirects", True)611 return self.request("OPTIONS", url, **kwargs)612613 def head(self, url, **kwargs):614 r"""Sends a HEAD request. Returns :class:`Response` object.615
1 unmodified line
617 :param \*\*kwargs: Optional arguments that ``request`` takes.618 :rtype: requests.Response619 """620559 kwargs.setdefault('allow_redirects', False)560 return self.request('HEAD', url, **kwargs)621 kwargs.setdefault("allow_redirects", False)622 return self.request("HEAD", url, **kwargs)623624 def post(self, url, data=None, json=None, **kwargs):625 r"""Sends a POST request. Returns :class:`Response` object.626
4 unmodified lines
631 :param \*\*kwargs: Optional arguments that ``request`` takes.632 :rtype: requests.Response633 """634573 return self.request('POST', url, data=data, json=json, **kwargs)635 return self.request("POST", url, data=data, json=json, **kwargs)636637 def put(self, url, data=None, **kwargs):638 r"""Sends a PUT request. Returns :class:`Response` object.639
3 unmodified lines
643 :param \*\*kwargs: Optional arguments that ``request`` takes.644 :rtype: requests.Response645 """646585 return self.request('PUT', url, data=data, **kwargs)647 return self.request("PUT", url, data=data, **kwargs)648649 def patch(self, url, data=None, **kwargs):650 r"""Sends a PATCH request. Returns :class:`Response` object.651
3 unmodified lines
655 :param \*\*kwargs: Optional arguments that ``request`` takes.656 :rtype: requests.Response657 """658597 return self.request('PATCH', url, data=data, **kwargs)659 return self.request("PATCH", url, data=data, **kwargs)660661 def delete(self, url, **kwargs):662 r"""Sends a DELETE request. Returns :class:`Response` object.663
1 unmodified line
665 :param \*\*kwargs: Optional arguments that ``request`` takes.666 :rtype: requests.Response667 """668607 return self.request('DELETE', url, **kwargs)669 return self.request("DELETE", url, **kwargs)670671 def send(self, request, **kwargs):672 """Send a given PreparedRequest.673674 :rtype: requests.Response675 """676 # Set defaults that the hooks can utilize to ensure they always have677 # the correct parameters to reproduce the previous request.616 kwargs.setdefault('stream', self.stream)617 kwargs.setdefault('verify', self.verify)618 kwargs.setdefault('cert', self.cert)619 if 'proxies' not in kwargs:620 kwargs['proxies'] = resolve_proxies(621 request, self.proxies, self.trust_env622 )678 kwargs.setdefault("stream", self.stream)679 kwargs.setdefault("verify", self.verify)680 kwargs.setdefault("cert", self.cert)681 if "proxies" not in kwargs:682 kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)683684 # It's possible that users might accidentally send a Request object.685 # Guard against that specific failure case.686 if isinstance(request, Request):627 raise ValueError('You can only send PreparedRequests.')687 raise ValueError("You can only send PreparedRequests.")688689 # Set up variables needed for resolve_redirects and dispatching of hooks630 allow_redirects = kwargs.pop('allow_redirects', True)631 stream = kwargs.get('stream')690 allow_redirects = kwargs.pop("allow_redirects", True)691 stream = kwargs.get("stream")692 hooks = request.hooks693694 # Get the appropriate adapter to use695 adapter = self.get_adapter(url=request.url)
8 unmodified lines
704 elapsed = preferred_clock() - start705 r.elapsed = timedelta(seconds=elapsed)706707 # Response manipulation hooks648 r = dispatch_hook('response', hooks, r, **kwargs)708 r = dispatch_hook("response", hooks, r, **kwargs)709710 # Persist cookies711 if r.history:712
21 unmodified lines
734735 # If redirects aren't being followed, store the response on the Request for Response.next().736 if not allow_redirects:737 try:678 r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs))738 r._next = next(739 self.resolve_redirects(r, request, yield_requests=True, **kwargs)740 )741 except StopIteration:742 pass743744 if not stream:
9 unmodified lines
754 """755 # Gather clues from the surrounding environment.756 if self.trust_env:757 # Set environment's proxies.696 no_proxy = proxies.get('no_proxy') if proxies is not None else None758 no_proxy = proxies.get("no_proxy") if proxies is not None else None759 env_proxies = get_environ_proxies(url, no_proxy=no_proxy)760 for (k, v) in env_proxies.items():761 proxies.setdefault(k, v)762763 # Look for requests environment configuration764 # and be compatible with cURL.765 if verify is True or verify is None:766 verify = (705 os.environ.get('REQUESTS_CA_BUNDLE')706 or os.environ.get('CURL_CA_BUNDLE')767 os.environ.get("REQUESTS_CA_BUNDLE")768 or os.environ.get("CURL_CA_BUNDLE")769 or verify770 )771772 # Merge all the kwargs.
1 unmodified line
774 stream = merge_setting(stream, self.stream)775 verify = merge_setting(verify, self.verify)776 cert = merge_setting(cert, self.cert)777716 return {717 'proxies': proxies,718 'stream': stream,719 'verify': verify,720 'cert': cert721 }778 return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}779780 def get_adapter(self, url):781 """782 Returns the appropriate connection adapter for the given URL.
5 unmodified lines
788 if url.lower().startswith(prefix.lower()):789 return adapter790791 # Nothing matches :-/735 raise InvalidSchema("No connection adapters were found for {!r}".format(url))792 raise InvalidSchema(f"No connection adapters were found for {url!r}")793794 def close(self):795 """Closes all adapters and as such the session"""796 for v in self.adapters.values():
35 unmodified lines
modified:requests/status_codes.py+87 added-82 removed
1# -*- coding: utf-8 -*-21r"""2The ``codes`` object defines a mapping from common names for HTTP statuses3to their numerical codes, accessible either as attributes or as dictionary4items.
15 unmodified lines
2021from .structures import LookupDict2223_codes = {2624 # Informational.28 100: ('continue',),29 101: ('switching_protocols',),30 102: ('processing',),31 103: ('checkpoint',),32 122: ('uri_too_long', 'request_uri_too_long'),33 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),34 201: ('created',),35 202: ('accepted',),36 203: ('non_authoritative_info', 'non_authoritative_information'),37 204: ('no_content',),38 205: ('reset_content', 'reset'),39 206: ('partial_content', 'partial'),40 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),41 208: ('already_reported',),42 226: ('im_used',),4325 100: ("continue",),26 101: ("switching_protocols",),27 102: ("processing",),28 103: ("checkpoint",),29 122: ("uri_too_long", "request_uri_too_long"),30 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"),31 201: ("created",),32 202: ("accepted",),33 203: ("non_authoritative_info", "non_authoritative_information"),34 204: ("no_content",),35 205: ("reset_content", "reset"),36 206: ("partial_content", "partial"),37 207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"),38 208: ("already_reported",),39 226: ("im_used",),40 # Redirection.45 300: ('multiple_choices',),46 301: ('moved_permanently', 'moved', '\\o-'),47 302: ('found',),48 303: ('see_other', 'other'),49 304: ('not_modified',),50 305: ('use_proxy',),51 306: ('switch_proxy',),52 307: ('temporary_redirect', 'temporary_moved', 'temporary'),53 308: ('permanent_redirect',54 'resume_incomplete', 'resume',), # These 2 to be removed in 3.05541 300: ("multiple_choices",),42 301: ("moved_permanently", "moved", "\\o-"),43 302: ("found",),44 303: ("see_other", "other"),45 304: ("not_modified",),46 305: ("use_proxy",),47 306: ("switch_proxy",),48 307: ("temporary_redirect", "temporary_moved", "temporary"),49 308: (50 "permanent_redirect",51 "resume_incomplete",52 "resume",53 ), # "resume" and "resume_incomplete" to be removed in 3.054 # Client Error.57 400: ('bad_request', 'bad'),58 401: ('unauthorized',),59 402: ('payment_required', 'payment'),60 403: ('forbidden',),61 404: ('not_found', '-o-'),62 405: ('method_not_allowed', 'not_allowed'),63 406: ('not_acceptable',),64 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),65 408: ('request_timeout', 'timeout'),66 409: ('conflict',),67 410: ('gone',),68 411: ('length_required',),69 412: ('precondition_failed', 'precondition'),70 413: ('request_entity_too_large',),71 414: ('request_uri_too_large',),72 415: ('unsupported_media_type', 'unsupported_media', 'media_type'),73 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),74 417: ('expectation_failed',),75 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),76 421: ('misdirected_request',),77 422: ('unprocessable_entity', 'unprocessable'),78 423: ('locked',),79 424: ('failed_dependency', 'dependency'),80 425: ('unordered_collection', 'unordered'),81 426: ('upgrade_required', 'upgrade'),82 428: ('precondition_required', 'precondition'),83 429: ('too_many_requests', 'too_many'),84 431: ('header_fields_too_large', 'fields_too_large'),85 444: ('no_response', 'none'),86 449: ('retry_with', 'retry'),87 450: ('blocked_by_windows_parental_controls', 'parental_controls'),88 451: ('unavailable_for_legal_reasons', 'legal_reasons'),89 499: ('client_closed_request',),9055 400: ("bad_request", "bad"),56 401: ("unauthorized",),57 402: ("payment_required", "payment"),58 403: ("forbidden",),59 404: ("not_found", "-o-"),60 405: ("method_not_allowed", "not_allowed"),61 406: ("not_acceptable",),62 407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"),63 408: ("request_timeout", "timeout"),64 409: ("conflict",),65 410: ("gone",),66 411: ("length_required",),67 412: ("precondition_failed", "precondition"),68 413: ("request_entity_too_large",),69 414: ("request_uri_too_large",),70 415: ("unsupported_media_type", "unsupported_media", "media_type"),71 416: (72 "requested_range_not_satisfiable",73 "requested_range",74 "range_not_satisfiable",75 ),76 417: ("expectation_failed",),77 418: ("im_a_teapot", "teapot", "i_am_a_teapot"),78 421: ("misdirected_request",),79 422: ("unprocessable_entity", "unprocessable"),80 423: ("locked",),81 424: ("failed_dependency", "dependency"),82 425: ("unordered_collection", "unordered"),83 426: ("upgrade_required", "upgrade"),84 428: ("precondition_required", "precondition"),85 429: ("too_many_requests", "too_many"),86 431: ("header_fields_too_large", "fields_too_large"),87 444: ("no_response", "none"),88 449: ("retry_with", "retry"),89 450: ("blocked_by_windows_parental_controls", "parental_controls"),90 451: ("unavailable_for_legal_reasons", "legal_reasons"),91 499: ("client_closed_request",),92 # Server Error.92 500: ('internal_server_error', 'server_error', '/o\\', '✗'),93 501: ('not_implemented',),94 502: ('bad_gateway',),95 503: ('service_unavailable', 'unavailable'),96 504: ('gateway_timeout',),97 505: ('http_version_not_supported', 'http_version'),98 506: ('variant_also_negotiates',),99 507: ('insufficient_storage',),100 509: ('bandwidth_limit_exceeded', 'bandwidth'),101 510: ('not_extended',),102 511: ('network_authentication_required', 'network_auth', 'network_authentication'),93 500: ("internal_server_error", "server_error", "/o\\", "✗"),94 501: ("not_implemented",),95 502: ("bad_gateway",),96 503: ("service_unavailable", "unavailable"),97 504: ("gateway_timeout",),98 505: ("http_version_not_supported", "http_version"),99 506: ("variant_also_negotiates",),100 507: ("insufficient_storage",),101 509: ("bandwidth_limit_exceeded", "bandwidth"),102 510: ("not_extended",),103 511: ("network_authentication_required", "network_auth", "network_authentication"),104}105105codes = LookupDict(name='status_codes')106codes = LookupDict(name="status_codes")107108109def _init():110 for code, titles in _codes.items():111 for title in titles:112 setattr(codes, title, code)111 if not title.startswith(('\\', '/')):113 if not title.startswith(("\\", "/")):114 setattr(codes, title.upper(), code)115116 def doc(code):115 names = ', '.join('``%s``' % n for n in _codes[code])116 return '* %d: %s' % (code, names)117 names = ", ".join(f"``{n}``" for n in _codes[code])118 return "* %d: %s" % (code, names)119120 global __doc__119 __doc__ = (__doc__ + '\n' +120 '\n'.join(doc(code) for code in sorted(_codes))121 if __doc__ is not None else None)121 __doc__ = (122 __doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes))123 if __doc__ is not None124 else None125 )126127128_init()
modified:requests/structures.py+3 added-9 removed
1# -*- coding: utf-8 -*-21"""2requests.structures3~~~~~~~~~~~~~~~~~~~4
56 unmodified lines
61 return len(self._store)6263 def lower_items(self):64 """Like iteritems(), but with all lowercase keys."""67 return (68 (lowerkey, keyval[1])69 for (lowerkey, keyval)70 in self._store.items()71 )65 return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())6667 def __eq__(self, other):68 if isinstance(other, Mapping):69 other = CaseInsensitiveDict(other)
14 unmodified lines
84 """Dictionary lookup object."""8586 def __init__(self, name=None):87 self.name = name94 super(LookupDict, self).__init__()88 super().__init__()8990 def __repr__(self):97 return '<lookup \'%s\'>' % (self.name)91 return f"<lookup '{self.name}'>"9293 def __getitem__(self, key):94 # We allow fall-through here, so values default to None95
4 unmodified lines
modified:requests/utils.py+193 added-160 removed
1# -*- coding: utf-8 -*-21"""2requests.utils3~~~~~~~~~~~~~~4
12 unmodified lines
17import tempfile18import warnings19import zipfile20from collections import OrderedDict23from urllib3.util import make_headers24from urllib3.util import parse_url2126from .__version__ import __version__22from urllib3.util import make_headers, parse_url2324from . import certs25from .__version__ import __version__2627# to_native_string is unused here, but imported here for backwards compatibility29from ._internal_utils import to_native_string28from ._internal_utils import to_native_string # noqa: F40129from .compat import (30 Mapping,31 basestring,32 bytes,33 getproxies,34 getproxies_environment,35 integer_types,36)37from .compat import parse_http_list as _parse_list_header38from .compat import (32 quote, urlparse, bytes, str, unquote, getproxies,33 proxy_bypass, urlunparse, basestring, integer_types,34 proxy_bypass_environment, getproxies_environment, Mapping)39 proxy_bypass,40 proxy_bypass_environment,41 quote,42 str,43 unquote,44 urlparse,45 urlunparse,46)47from .cookies import cookiejar_from_dict36from .structures import CaseInsensitiveDict48from .exceptions import (38 InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)49 FileModeWarning,50 InvalidHeader,51 InvalidURL,52 UnrewindableBodyError,53)54from .structures import CaseInsensitiveDict5540NETRC_FILES = ('.netrc', '_netrc')56NETRC_FILES = (".netrc", "_netrc")5758DEFAULT_CA_BUNDLE_PATH = certs.where()5944DEFAULT_PORTS = {'http': 80, 'https': 443}60DEFAULT_PORTS = {"http": 80, "https": 443}6162# Ensure that ', ' is used to preserve previous delimiter behavior.63DEFAULT_ACCEPT_ENCODING = ", ".join(64 re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])65)666752if sys.platform == 'win32':68if sys.platform == "win32":69 # provide a proxy_bypass version on Windows without DNS lookups7071 def proxy_bypass_registry(host):72 try:
1 unmodified line
74 except ImportError:75 return False7677 try:62 internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,63 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')78 internetSettings = winreg.OpenKey(79 winreg.HKEY_CURRENT_USER,80 r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",81 )82 # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it65 proxyEnable = int(winreg.QueryValueEx(internetSettings,66 'ProxyEnable')[0])83 proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0])84 # ProxyOverride is almost always a string68 proxyOverride = winreg.QueryValueEx(internetSettings,69 'ProxyOverride')[0]85 proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0]86 except OSError:87 return False88 if not proxyEnable or not proxyOverride:89 return False9091 # make a check value list from the registry entry: replace the92 # '<local>' string by the localhost entry and the corresponding93 # canonical entry.78 proxyOverride = proxyOverride.split(';')94 proxyOverride = proxyOverride.split(";")95 # now check if we match one of the registry values.96 for test in proxyOverride:81 if test == '<local>':82 if '.' not in host:97 if test == "<local>":98 if "." not in host:99 return True84 test = test.replace(".", r"\.") # mask dots85 test = test.replace("*", r".*") # change glob sequence86 test = test.replace("?", r".") # change glob char100 test = test.replace(".", r"\.") # mask dots101 test = test.replace("*", r".*") # change glob sequence102 test = test.replace("?", r".") # change glob char103 if re.match(test, host, re.I):104 return True105 return False106
11 unmodified lines
118119def dict_to_sequence(d):120 """Returns an internal sequence dictionary update."""121106 if hasattr(d, 'items'):122 if hasattr(d, "items"):123 d = d.items()124125 return d126
1 unmodified line
128def super_len(o):129 total_length = None130 current_position = 0131116 if hasattr(o, '__len__'):132 if hasattr(o, "__len__"):133 total_length = len(o)134119 elif hasattr(o, 'len'):135 elif hasattr(o, "len"):136 total_length = o.len137122 elif hasattr(o, 'fileno'):138 elif hasattr(o, "fileno"):139 try:140 fileno = o.fileno()141 except (io.UnsupportedOperation, AttributeError):142 # AttributeError is a surprising exception, seeing as how we've just checked
4 unmodified lines
147 total_length = os.fstat(fileno).st_size148149 # Having used fstat to determine the file length, we need to150 # confirm that this file was opened up in binary mode.135 if 'b' not in o.mode:136 warnings.warn((137 "Requests has determined the content-length for this "138 "request using the binary size of the file: however, the "139 "file has been opened in text mode (i.e. without the 'b' "140 "flag in the mode). This may lead to an incorrect "141 "content-length. In Requests 3.0, support will be removed "142 "for files in text mode."),143 FileModeWarning151 if "b" not in o.mode:152 warnings.warn(153 (154 "Requests has determined the content-length for this "155 "request using the binary size of the file: however, the "156 "file has been opened in text mode (i.e. without the 'b' "157 "flag in the mode). This may lead to an incorrect "158 "content-length. In Requests 3.0, support will be removed "159 "for files in text mode."160 ),161 FileModeWarning,162 )163146 if hasattr(o, 'tell'):164 if hasattr(o, "tell"):165 try:166 current_position = o.tell()149 except (OSError, IOError):167 except OSError:168 # This can happen in some weird situations, such as when the file169 # is actually a special file descriptor like stdin. In this170 # instance, we don't know what the length is, so set it to zero and171 # let requests chunk it instead.172 if total_length is not None:173 current_position = total_length174 else:157 if hasattr(o, 'seek') and total_length is None:175 if hasattr(o, "seek") and total_length is None:176 # StringIO and BytesIO have seek but no usable fileno177 try:178 # seek to end of file179 o.seek(0, 2)
1 unmodified line
181182 # seek back to current position to support183 # partially read file-like objects184 o.seek(current_position or 0)167 except (OSError, IOError):185 except OSError:186 total_length = 0187188 if total_length is None:189 total_length = 0
3 unmodified lines
193194def get_netrc_auth(url, raise_errors=False):195 """Returns the Requests tuple auth for a given url from netrc."""196179 netrc_file = os.environ.get('NETRC')197 netrc_file = os.environ.get("NETRC")198 if netrc_file is not None:199 netrc_locations = (netrc_file,)200 else:183 netrc_locations = ('~/{}'.format(f) for f in NETRC_FILES)201 netrc_locations = (f"~/{f}" for f in NETRC_FILES)202203 try:186 from netrc import netrc, NetrcParseError204 from netrc import NetrcParseError, netrc205206 netrc_path = None207208 for f in netrc_locations:
16 unmodified lines
225 ri = urlparse(url)226227 # Strip port numbers from netloc. This weird `if...encode`` dance is228 # used for Python 3.2, which doesn't support unicode literals.211 splitstr = b':'229 splitstr = b":"230 if isinstance(url, str):213 splitstr = splitstr.decode('ascii')231 splitstr = splitstr.decode("ascii")232 host = ri.netloc.split(splitstr)[0]233234 try:235 _netrc = netrc(netrc_path).authenticators(host)236 if _netrc:237 # Return with login / password220 login_i = (0 if _netrc[0] else 1)238 login_i = 0 if _netrc[0] else 1239 return (_netrc[login_i], _netrc[2])222 except (NetrcParseError, IOError):240 except (NetrcParseError, OSError):241 # If there was a parsing error or a permissions issue reading the file,242 # we'll just skip netrc auth unless explicitly asked to raise errors.243 if raise_errors:244 raise
4 unmodified lines
249250251def guess_filename(obj):252 """Tries to guess the filename of the given object."""235 name = getattr(obj, 'name', None)236 if (name and isinstance(name, basestring) and name[0] != '<' and237 name[-1] != '>'):253 name = getattr(obj, "name", None)254 if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">":255 return os.path.basename(name)256257258def extract_zipped_paths(path):
13 unmodified lines
272 if not prefix:273 # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),274 # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users275 break259 member = '/'.join([prefix, member])276 member = "/".join([prefix, member])277278 if not zipfile.is_zipfile(archive):279 return path280
2 unmodified lines
283 return path284285 # we have a valid zip archive and a valid member of that archive286 tmp = tempfile.gettempdir()270 extracted_path = os.path.join(tmp, member.split('/')[-1])287 extracted_path = os.path.join(tmp, member.split("/")[-1])288 if not os.path.exists(extracted_path):289 # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition290 with atomic_open(extracted_path) as file_handler:291 file_handler.write(zip_file.read(member))
4 unmodified lines
296def atomic_open(filename):297 """Write a file to the disk in an atomic fashion"""298 tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))299 try:283 with os.fdopen(tmp_descriptor, 'wb') as tmp_handler:300 with os.fdopen(tmp_descriptor, "wb") as tmp_handler:301 yield tmp_handler302 os.replace(tmp_name, filename)303 except BaseException:304 os.remove(tmp_name)
21 unmodified lines
326 if value is None:327 return None328329 if isinstance(value, (str, bytes, bool, int)):313 raise ValueError('cannot encode objects that are not 2-tuples')330 raise ValueError("cannot encode objects that are not 2-tuples")331332 return OrderedDict(value)333334
17 unmodified lines
352 if value is None:353 return None354355 if isinstance(value, (str, bytes, bool, int)):339 raise ValueError('cannot encode objects that are not 2-tuples')356 raise ValueError("cannot encode objects that are not 2-tuples")357358 if isinstance(value, Mapping):359 value = value.items()360
56 unmodified lines
417 :rtype: dict418 """419 result = {}420 for item in _parse_list_header(value):404 if '=' not in item:421 if "=" not in item:422 result[item] = None423 continue407 name, value = item.split('=', 1)424 name, value = item.split("=", 1)425 if value[:1] == value[-1:] == '"':426 value = unquote_header_value(value[1:-1])427 result[name] = value428 return result
19 unmodified lines
448 # a UNC path, then just return the value without quotes. Using the449 # replace sequence below on a UNC path has the effect of turning450 # the leading double slash into a single slash and then451 # _fix_ie_filename() doesn't work correctly. See #458.435 if not is_filename or value[:2] != '\\\\':436 return value.replace('\\\\', '\\').replace('\\"', '"')452 if not is_filename or value[:2] != "\\\\":453 return value.replace("\\\\", "\\").replace('\\"', '"')454 return value455456457def dict_from_cookiejar(cj):
26 unmodified lines
484 """Returns encodings from given content string.485486 :param content: bytestring to extract encodings from.487 """471 warnings.warn((472 'In requests 3.0, get_encodings_from_content will be removed. For '473 'more information, please see the discussion on issue #2266. (This'474 ' warning should only appear once.)'),475 DeprecationWarning)488 warnings.warn(489 (490 "In requests 3.0, get_encodings_from_content will be removed. For "491 "more information, please see the discussion on issue #2266. (This"492 " warning should only appear once.)"493 ),494 DeprecationWarning,495 )496497 charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)498 pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)499 xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')500481 return (charset_re.findall(content) +482 pragma_re.findall(content) +483 xml_re.findall(content))501 return (502 charset_re.findall(content)503 + pragma_re.findall(content)504 + xml_re.findall(content)505 )506507508def _parse_content_type_header(header):509 """Returns content type and parameters from given header
2 unmodified lines
512 :return: tuple containing content type and dictionary of513 parameters514 """515494 tokens = header.split(';')516 tokens = header.split(";")517 content_type, params = tokens[0].strip(), tokens[1:]518 params_dict = {}519 items_to_strip = "\"' "520
3 unmodified lines
524 key, value = param, True525 index_of_equals = param.find("=")526 if index_of_equals != -1:527 key = param[:index_of_equals].strip(items_to_strip)506 value = param[index_of_equals + 1:].strip(items_to_strip)528 value = param[index_of_equals + 1 :].strip(items_to_strip)529 params_dict[key.lower()] = value530 return content_type, params_dict531532
3 unmodified lines
536 :param headers: dictionary to extract encoding from.537 :rtype: str538 """539518 content_type = headers.get('content-type')540 content_type = headers.get("content-type")541542 if not content_type:543 return None544545 content_type, params = _parse_content_type_header(content_type)546525 if 'charset' in params:526 return params['charset'].strip("'\"")547 if "charset" in params:548 return params["charset"].strip("'\"")549528 if 'text' in content_type:529 return 'ISO-8859-1'550 if "text" in content_type:551 return "ISO-8859-1"552531 if 'application/json' in content_type:553 if "application/json" in content_type:554 # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset533 return 'utf-8'555 return "utf-8"556557558def stream_decode_response_unicode(iterator, r):559 """Stream decodes a iterator."""560561 if r.encoding is None:540 for item in iterator:541 yield item562 yield from iterator563 return564544 decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')565 decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace")566 for chunk in iterator:567 rv = decoder.decode(chunk)568 if rv:569 yield rv549 rv = decoder.decode(b'', final=True)570 rv = decoder.decode(b"", final=True)571 if rv:572 yield rv573574
2 unmodified lines
577 pos = 0578 if slice_length is None or slice_length <= 0:579 slice_length = len(string)580 while pos < len(string):560 yield string[pos:pos + slice_length]581 yield string[pos : pos + slice_length]582 pos += slice_length583584585def get_unicode_from_response(r):
7 unmodified lines
593 2. fall back and replace all unicode characters594595 :rtype: str596 """576 warnings.warn((577 'In requests 3.0, get_unicode_from_response will be removed. For '578 'more information, please see the discussion on issue #2266. (This'579 ' warning should only appear once.)'),580 DeprecationWarning)597 warnings.warn(598 (599 "In requests 3.0, get_unicode_from_response will be removed. For "600 "more information, please see the discussion on issue #2266. (This"601 " warning should only appear once.)"602 ),603 DeprecationWarning,604 )605606 tried_encodings = []607608 # Try charset from content-type
6 unmodified lines
615 tried_encodings.append(encoding)616617 # Fall back:618 try:595 return str(r.content, encoding, errors='replace')619 return str(r.content, encoding, errors="replace")620 except TypeError:621 return r.content622623624# The unreserved URI characters (RFC 3986)625UNRESERVED_SET = frozenset(602 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~")626 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"627)628629630def unquote_unreserved(uri):631 """Un-escape any percent-escape sequences in a URI that are unreserved632 characters. This leaves all reserved, illegal and non-ASCII bytes encoded.633634 :rtype: str635 """611 parts = uri.split('%')636 parts = uri.split("%")637 for i in range(1, len(parts)):638 h = parts[i][0:2]639 if len(h) == 2 and h.isalnum():640 try:641 c = chr(int(h, 16))642 except ValueError:618 raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)643 raise InvalidURL(f"Invalid percent-escape sequence: '{h}'")644645 if c in UNRESERVED_SET:646 parts[i] = c + parts[i][2:]647 else:623 parts[i] = '%' + parts[i]648 parts[i] = f"%{parts[i]}"649 else:625 parts[i] = '%' + parts[i]626 return ''.join(parts)650 parts[i] = f"%{parts[i]}"651 return "".join(parts)652653654def requote_uri(uri):655 """Re-quote the given URI.
24 unmodified lines
680 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24681682 :rtype: bool683 """659 ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]660 netaddr, bits = net.split('/')661 netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]662 network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask684 ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]685 netaddr, bits = net.split("/")686 netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]687 network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask688 return (ipaddr & netmask) == (network & netmask)689690691def dotted_netmask(mask):
2 unmodified lines
694 Example: if mask is 24 function returns 255.255.255.0695696 :rtype: str697 """673 bits = 0xffffffff ^ (1 << 32 - mask) - 1674 return socket.inet_ntoa(struct.pack('>I', bits))698 bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1699 return socket.inet_ntoa(struct.pack(">I", bits))700701702def is_ipv4_address(string_ip):703 """704 :rtype: bool705 """706 try:707 socket.inet_aton(string_ip)683 except socket.error:708 except OSError:709 return False710 return True711712
2 unmodified lines
715 Very simple check of the cidr format in no_proxy variable.716717 :rtype: bool718 """694 if string_network.count('/') == 1:719 if string_network.count("/") == 1:720 try:696 mask = int(string_network.split('/')[1])721 mask = int(string_network.split("/")[1])722 except ValueError:723 return False724725 if mask < 1 or mask > 32:726 return False727728 try:704 socket.inet_aton(string_network.split('/')[0])705 except socket.error:729 socket.inet_aton(string_network.split("/")[0])730 except OSError:731 return False732 else:733 return False734 return True
28 unmodified lines
763 :rtype: bool764 """765 # Prioritize lowercase environment variables over uppercase766 # to keep a consistent behaviour with other http projects (curl, wget).742 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())767 def get_proxy(key):768 return os.environ.get(key) or os.environ.get(key.upper())769770 # First check whether no_proxy is defined. If it is, check that the URL771 # we're getting isn't in the no_proxy list.772 no_proxy_arg = no_proxy773 if no_proxy is None:748 no_proxy = get_proxy('no_proxy')774 no_proxy = get_proxy("no_proxy")775 parsed = urlparse(url)776777 if parsed.hostname is None:778 # URLs don't always have hostnames, e.g. file:/// urls.
1 unmodified line
780781 if no_proxy:782 # We need to check whether we match here. We need to see if we match783 # the end of the hostname, both with and without the port.758 no_proxy = (759 host for host in no_proxy.replace(' ', '').split(',') if host760 )784 no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host)785786 if is_ipv4_address(parsed.hostname):787 for proxy_ip in no_proxy:788 if is_valid_cidr(proxy_ip):
5 unmodified lines
794 return True795 else:796 host_with_port = parsed.hostname797 if parsed.port:774 host_with_port += ':{}'.format(parsed.port)798 host_with_port += f":{parsed.port}"799800 for host in no_proxy:801 if parsed.hostname.endswith(host) or host_with_port.endswith(host):802 # The URL does match something in no_proxy, so we don't want803 # to apply the proxies on this URL.804 return True805782 with set_environ('no_proxy', no_proxy_arg):806 with set_environ("no_proxy", no_proxy_arg):807 # parsed.hostname can be `None` in cases such as a file URI.808 try:809 bypass = proxy_bypass(parsed.hostname)810 except (TypeError, socket.gaierror):
25 unmodified lines
836 """837 proxies = proxies or {}838 urlparts = urlparse(url)839 if urlparts.hostname is None:816 return proxies.get(urlparts.scheme, proxies.get('all'))840 return proxies.get(urlparts.scheme, proxies.get("all"))841842 proxy_keys = [819 urlparts.scheme + '://' + urlparts.hostname,843 urlparts.scheme + "://" + urlparts.hostname,844 urlparts.scheme,821 'all://' + urlparts.hostname,822 'all',845 "all://" + urlparts.hostname,846 "all",847 ]848 proxy = None849 for proxy_key in proxy_keys:850 if proxy_key in proxies:
16 unmodified lines
867 """868 proxies = proxies if proxies is not None else {}869 url = request.url870 scheme = urlparse(url).scheme847 no_proxy = proxies.get('no_proxy')871 no_proxy = proxies.get("no_proxy")872 new_proxies = proxies.copy()873874 if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):875 environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)876853 proxy = environ_proxies.get(scheme, environ_proxies.get('all'))877 proxy = environ_proxies.get(scheme, environ_proxies.get("all"))878879 if proxy:880 new_proxies.setdefault(scheme, proxy)881 return new_proxies
4 unmodified lines
886 Return a string representing the default user agent.887888 :rtype: str889 """866 return '%s/%s' % (name, __version__)890 return f"{name}/{__version__}"891892893def default_headers():894 """895 :rtype: requests.structures.CaseInsensitiveDict896 """873 return CaseInsensitiveDict({874 'User-Agent': default_user_agent(),875 'Accept-Encoding': DEFAULT_ACCEPT_ENCODING,876 'Accept': '*/*',877 'Connection': 'keep-alive',878 })897 return CaseInsensitiveDict(898 {899 "User-Agent": default_user_agent(),900 "Accept-Encoding": DEFAULT_ACCEPT_ENCODING,901 "Accept": "*/*",902 "Connection": "keep-alive",903 }904 )905906907def parse_header_links(value):908 """Return a list of parsed link headers proxies.
4 unmodified lines
913 """914915 links = []916891 replace_chars = ' \'"'917 replace_chars = " '\""918919 value = value.strip(replace_chars)920 if not value:921 return links922897 for val in re.split(', *<', value):923 for val in re.split(", *<", value):924 try:899 url, params = val.split(';', 1)925 url, params = val.split(";", 1)926 except ValueError:901 url, params = val, ''927 url, params = val, ""928903 link = {'url': url.strip('<> \'"')}929 link = {"url": url.strip("<> '\"")}930905 for param in params.split(';'):931 for param in params.split(";"):932 try:907 key, value = param.split('=')933 key, value = param.split("=")934 except ValueError:935 break936937 link[key.strip(replace_chars)] = value.strip(replace_chars)
3 unmodified lines
941 return links942943944# Null bytes; no need to recreate these on each call to guess_json_utf919_null = '\x00'.encode('ascii') # encoding to ASCII for Python 3945_null = "\x00".encode("ascii") # encoding to ASCII for Python 3946_null2 = _null * 2947_null3 = _null * 3948949
5 unmodified lines
955 # easy as counting the nulls and from their location and count956 # determine the encoding. Also detect a BOM, if present.957 sample = data[:4]958 if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):933 return 'utf-32' # BOM included959 return "utf-32" # BOM included960 if sample[:3] == codecs.BOM_UTF8:935 return 'utf-8-sig' # BOM included, MS style (discouraged)961 return "utf-8-sig" # BOM included, MS style (discouraged)962 if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):937 return 'utf-16' # BOM included963 return "utf-16" # BOM included964 nullcount = sample.count(_null)965 if nullcount == 0:940 return 'utf-8'966 return "utf-8"967 if nullcount == 2:942 if sample[::2] == _null2: # 1st and 3rd are null943 return 'utf-16-be'968 if sample[::2] == _null2: # 1st and 3rd are null969 return "utf-16-be"970 if sample[1::2] == _null2: # 2nd and 4th are null945 return 'utf-16-le'971 return "utf-16-le"972 # Did not detect 2 valid UTF-16 ascii-range characters973 if nullcount == 3:974 if sample[:3] == _null3:949 return 'utf-32-be'975 return "utf-32-be"976 if sample[1:] == _null3:951 return 'utf-32-le'977 return "utf-32-le"978 # Did not detect a valid UTF-32 ascii-range character979 return None980981
16 unmodified lines
998999 if auth:1000 # parse_url doesn't provide the netloc with auth1001 # so we'll add it ourselves.976 netloc = '@'.join([auth, netloc])1002 netloc = "@".join([auth, netloc])1003 if scheme is None:1004 scheme = new_scheme1005 if path is None:980 path = ''1006 path = ""1007982 return urlunparse((scheme, netloc, path, '', query, fragment))1008 return urlunparse((scheme, netloc, path, "", query, fragment))100910101011def get_auth_from_url(url):1012 """Given a url with authentication components, extract them into a tuple of
5 unmodified lines
10181019 try:1020 auth = (unquote(parsed.username), unquote(parsed.password))1021 except (AttributeError, TypeError):996 auth = ('', '')1022 auth = ("", "")10231024 return auth102510261027# Moved outside of function to avoid recompile every call1002_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')1003_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')1028_CLEAN_HEADER_REGEX_BYTE = re.compile(b"^\\S[^\\r\\n]*$|^$")1029_CLEAN_HEADER_REGEX_STR = re.compile(r"^\S[^\r\n]*$|^$")103010311032def check_header_validity(header):1033 """Verifies that header value is a string which doesn't contain
9 unmodified lines
1043 else:1044 pat = _CLEAN_HEADER_REGEX_STR1045 try:1046 if not pat.match(value):1021 raise InvalidHeader("Invalid return character or leading space in header: %s" % name)1047 raise InvalidHeader(1048 f"Invalid return character or leading space in header: {name}"1049 )1050 except TypeError:1023 raise InvalidHeader("Value for header {%s: %s} must be of type str or "1024 "bytes, not %s" % (name, value, type(value)))1051 raise InvalidHeader(1052 f"Value for header {{{name}: {value}}} must be of type "1053 f"str or bytes, not {type(value)}"1054 )105510561057def urldefragauth(url):1058 """
6 unmodified lines
1065 # see func:`prepend_scheme_if_needed`1066 if not netloc:1067 netloc, path = path, netloc10681039 netloc = netloc.rsplit('@', 1)[-1]1069 netloc = netloc.rsplit("@", 1)[-1]10701041 return urlunparse((scheme, netloc, path, params, query, ''))1071 return urlunparse((scheme, netloc, path, params, query, ""))107210731074def rewind_body(prepared_request):1075 """Move file pointer back to its recorded starting position1076 so it can be read again on redirect.1077 """1048 body_seek = getattr(prepared_request.body, 'seek', None)1049 if body_seek is not None and isinstance(prepared_request._body_position, integer_types):1078 body_seek = getattr(prepared_request.body, "seek", None)1079 if body_seek is not None and isinstance(1080 prepared_request._body_position, integer_types1081 ):1082 try:1083 body_seek(prepared_request._body_position)1052 except (IOError, OSError):1053 raise UnrewindableBodyError("An error occurred when rewinding request "1054 "body for redirect.")1084 except OSError:1085 raise UnrewindableBodyError(1086 "An error occurred when rewinding request body for redirect."1087 )1088 else:1089 raise UnrewindableBodyError("Unable to rewind request body for redirect.")
modified:tests/testserver/server.py+22 added-17 removed
1# -*- coding: utf-8 -*-23import threading4import socket1import select2import socket3import threading456def consume_socket_content(sock, timeout=0.5):7 chunks = 6553610 content = b''8 content = b""910 while True:11 more_to_read = select.select([sock], [], [], timeout)[0]12 if not more_to_read:
9 unmodified lines
222324class Server(threading.Thread):25 """Dummy server using for unit testing"""2627 WAIT_EVENT_TIMEOUT = 52830 def __init__(self, handler=None, host='localhost', port=0, requests_to_handle=1, wait_to_close_event=None):31 super(Server, self).__init__()29 def __init__(30 self,31 handler=None,32 host="localhost",33 port=0,34 requests_to_handle=1,35 wait_to_close_event=None,36 ):37 super().__init__()3839 self.handler = handler or consume_socket_content40 self.handler_results = []41
8 unmodified lines
50 @classmethod51 def text_response_server(cls, text, request_timeout=0.5, **kwargs):52 def text_response_handler(sock):53 request_content = consume_socket_content(sock, timeout=request_timeout)48 sock.send(text.encode('utf-8'))54 sock.send(text.encode("utf-8"))5556 return request_content575258 return Server(text_response_handler, **kwargs)5960 @classmethod61 def basic_response_server(cls, **kwargs):62 return cls.text_response_server(58 "HTTP/1.1 200 OK\r\n" +59 "Content-Length: 0\r\n\r\n",60 **kwargs63 "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n\r\n", **kwargs64 )6566 def run(self):67 try:
5 unmodified lines
7374 if self.wait_to_close_event:75 self.wait_to_close_event.wait(self.WAIT_EVENT_TIMEOUT)76 finally:74 self.ready_event.set() # just in case of exception77 self.ready_event.set() # just in case of exception78 self._close_server_sock_ignore_errors()79 self.stop_event.set()8081 def _create_socket_and_bind(self):
4 unmodified lines
8687 def _close_server_sock_ignore_errors(self):88 try:89 self.server_sock.close()87 except IOError:90 except OSError:91 pass9293 def _handle_requests(self):94 for _ in range(self.requests_to_handle):
7 unmodified lines
102 sock.close()103104 def _accept_connection(self):105 try:103 ready, _, _ = select.select([self.server_sock], [], [], self.WAIT_EVENT_TIMEOUT)106 ready, _, _ = select.select(107 [self.server_sock], [], [], self.WAIT_EVENT_TIMEOUT108 )109 if not ready:110 return None111112 return self.server_sock.accept()[0]108 except (select.error, socket.error):113 except OSError:114 return None115116 def __enter__(self):117 self.start()
11 unmodified lines
129130 # ensure server thread doesn't get stuck waiting for connections131 self._close_server_sock_ignore_errors()132 self.join()128 return False # allow exceptions to propagate133 return False # allow exceptions to propagate
modified:tests/__init__.py+1 added-4 removed
1# -*- coding: utf-8 -*-21"""Requests test package initialisation."""23import warnings47import urllib35from urllib3.exceptions import SNIMissingWarning67# urllib3 sets SNIMissingWarning to only go off once,8# while this test suite requires it to always fire9# so that it occurs during test_requests.test_https_warnings13warnings.simplefilter('always', SNIMissingWarning)10warnings.simplefilter("always", SNIMissingWarning)
modified:tests/compat.py-1 removed
1# -*- coding: utf-8 -*-1import warnings23try:4 import StringIO
19 unmodified lines
modified:tests/conftest.py+6 added-9 removed
1# -*- coding: utf-8 -*-21try:4 from http.server import HTTPServer5 from http.server import SimpleHTTPRequestHandler2 from http.server import HTTPServer, SimpleHTTPRequestHandler3except ImportError:4 from BaseHTTPServer import HTTPServer8 from SimpleHTTPServer import SimpleHTTPRequestHandler 5 from SimpleHTTPServer import SimpleHTTPRequestHandler67import ssl11import tempfile8import threading910import pytest1112from requests.compat import urljoin131415def prepare_url(value):16 # Issue #1483: Make sure the URL always has a trailing slash20 httpbin_url = value.url.rstrip('/') + '/'17 httpbin_url = value.url.rstrip("/") + "/"1819 def inner(*suffix):23 return urljoin(httpbin_url, '/'.join(suffix))20 return urljoin(httpbin_url, "/".join(suffix))2122 return inner2324
15 unmodified lines
4041 tmpdir = tmp_path_factory.mktemp("certs")42 ca = trustme.CA()43 # only commonName, no subjectAltName47 server_cert = ca.issue_cert(common_name=u"localhost")44 server_cert = ca.issue_cert(common_name="localhost")45 ca_bundle = str(tmpdir / "ca.pem")46 ca.cert_pem.write_to_path(ca_bundle)4748 context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
10 unmodified lines
modified:tests/test_help.py+6 added-12 removed
1# -*- encoding: utf-823import sys45import pytest61from requests.help import info234def test_system_ssl():5 """Verify we're actually setting system_ssl when it should be available."""12 assert info()['system_ssl']['version'] != ''6 assert info()["system_ssl"]["version"] != ""7815class VersionedPackage(object):9class VersionedPackage:10 def __init__(self, version):11 self.__version__ = version121314def test_idna_without_version_attribute(mocker):15 """Older versions of IDNA don't provide a __version__ attribute, verify16 that if we have such a package, we don't blow up.17 """24 mocker.patch('requests.help.idna', new=None)25 assert info()['idna'] == {'version': ''}18 mocker.patch("requests.help.idna", new=None)19 assert info()["idna"] == {"version": ""}202122def test_idna_with_version_attribute(mocker):23 """Verify we're actually setting idna version when it should be available."""30 mocker.patch('requests.help.idna', new=VersionedPackage('2.6'))31 assert info()['idna'] == {'version': '2.6'}24 mocker.patch("requests.help.idna", new=VersionedPackage("2.6"))25 assert info()["idna"] == {"version": "2.6"}
modified:tests/test_hooks.py+7 added-8 removed
1# -*- coding: utf-8 -*-21import pytest23from requests import hooks4
2 unmodified lines
7 return value[1:]8910@pytest.mark.parametrize(13 'hooks_list, result', (14 (hook, 'ata'),15 ([hook, lambda x: None, hook], 'ta'),16 )11 "hooks_list, result",12 (13 (hook, "ata"),14 ([hook, lambda x: None, hook], "ta"),15 ),16)17def test_hooks(hooks_list, result):19 assert hooks.dispatch_hook('response', {'response': hooks_list}, 'Data') == result18 assert hooks.dispatch_hook("response", {"response": hooks_list}, "Data") == result192021def test_default_hooks():23 assert hooks.default_hooks() == {'response': []}22 assert hooks.default_hooks() == {"response": []}
modified:tests/test_lowlevel.py+61 added-62 removed
1# -*- coding: utf-8 -*-23import pytest1import threading5import requests23import pytest4from tests.testserver.server import Server, consume_socket_content56import requests7from requests.compat import JSONDecodeError89from .utils import override_environ101112def echo_response_handler(sock):13 """Simple handler that will take request and echo it back to requester."""14 request_content = consume_socket_content(sock, timeout=0.5)1516 text_200 = (18 b'HTTP/1.1 200 OK\r\n'19 b'Content-Length: %d\r\n\r\n'20 b'%s'17 b"HTTP/1.1 200 OK\r\n"18 b"Content-Length: %d\r\n\r\n"19 b"%s"20 ) % (len(request_content), request_content)21 sock.send(text_200)222324def test_chunked_upload():25 """can safely send generators"""26 close_server = threading.Event()27 server = Server.basic_response_server(wait_to_close_event=close_server)29 data = iter([b'a', b'b', b'c'])28 data = iter([b"a", b"b", b"c"])2930 with server as (host, port):32 url = 'http://{}:{}/'.format(host, port)31 url = f"http://{host}:{port}/"32 r = requests.post(url, data=data, stream=True)33 close_server.set() # release server block3435 assert r.status_code == 20037 assert r.request.headers['Transfer-Encoding'] == 'chunked'36 assert r.request.headers["Transfer-Encoding"] == "chunked"373839def test_chunked_encoding_error():40 """get a ChunkedEncodingError if the server returns a bad response"""
1 unmodified line
42 def incomplete_chunked_response_handler(sock):43 request_content = consume_socket_content(sock, timeout=0.5)4445 # The server never ends the request and doesn't provide any valid chunks47 sock.send(b"HTTP/1.1 200 OK\r\n" +48 b"Transfer-Encoding: chunked\r\n")46 sock.send(47 b"HTTP/1.1 200 OK\r\n"48 b"Transfer-Encoding: chunked\r\n"49 )5051 return request_content5253 close_server = threading.Event()54 server = Server(incomplete_chunked_response_handler)5556 with server as (host, port):56 url = 'http://{}:{}/'.format(host, port)57 url = f"http://{host}:{port}/"58 with pytest.raises(requests.exceptions.ChunkedEncodingError):58 r = requests.get(url)59 requests.get(url)60 close_server.set() # release server block616263def test_chunked_upload_uses_only_specified_host_header():64 """Ensure we use only the specified Host header for chunked requests."""65 close_server = threading.Event()66 server = Server(echo_response_handler, wait_to_close_event=close_server)6767 data = iter([b'a', b'b', b'c'])68 custom_host = 'sample-host'68 data = iter([b"a", b"b", b"c"])69 custom_host = "sample-host"7071 with server as (host, port):71 url = 'http://{}:{}/'.format(host, port)72 r = requests.post(url, data=data, headers={'Host': custom_host}, stream=True)72 url = f"http://{host}:{port}/"73 r = requests.post(url, data=data, headers={"Host": custom_host}, stream=True)74 close_server.set() # release server block7575 expected_header = b'Host: %s\r\n' % custom_host.encode('utf-8')76 expected_header = b"Host: %s\r\n" % custom_host.encode("utf-8")77 assert expected_header in r.content77 assert r.content.count(b'Host: ') == 178 assert r.content.count(b"Host: ") == 1798081def test_chunked_upload_doesnt_skip_host_header():82 """Ensure we don't omit all Host headers with chunked requests."""83 close_server = threading.Event()84 server = Server(echo_response_handler, wait_to_close_event=close_server)8585 data = iter([b'a', b'b', b'c'])86 data = iter([b"a", b"b", b"c"])8788 with server as (host, port):88 expected_host = '{}:{}'.format(host, port)89 url = 'http://{}:{}/'.format(host, port)89 expected_host = f"{host}:{port}"90 url = f"http://{host}:{port}/"91 r = requests.post(url, data=data, stream=True)92 close_server.set() # release server block9393 expected_header = b'Host: %s\r\n' % expected_host.encode('utf-8')94 expected_header = b"Host: %s\r\n" % expected_host.encode("utf-8")95 assert expected_header in r.content95 assert r.content.count(b'Host: ') == 196 assert r.content.count(b"Host: ") == 1979899def test_conflicting_content_lengths():100 """Ensure we correctly throw an InvalidHeader error if multiple
1 unmodified line
102 """103104 def multiple_content_length_response_handler(sock):105 request_content = consume_socket_content(sock, timeout=0.5)106 response = (107 b"HTTP/1.1 200 OK\r\n"108 b"Content-Type: text/plain\r\n"109 b"Content-Length: 16\r\n"110 b"Content-Length: 32\r\n\r\n"111 b"-- Bad Actor -- Original Content\r\n"112 )113 sock.send(response)114106 sock.send(b"HTTP/1.1 200 OK\r\n" +107 b"Content-Type: text/plain\r\n" +108 b"Content-Length: 16\r\n" +109 b"Content-Length: 32\r\n\r\n" +110 b"-- Bad Actor -- Original Content\r\n")111115 return request_content116117 close_server = threading.Event()118 server = Server(multiple_content_length_response_handler)119120 with server as (host, port):118 url = 'http://{}:{}/'.format(host, port)121 url = f"http://{host}:{port}/"122 with pytest.raises(requests.exceptions.InvalidHeader):120 r = requests.get(url)123 requests.get(url)124 close_server.set()125126127def test_digestauth_401_count_reset_on_redirect():
48 unmodified lines
176 close_server = threading.Event()177 server = Server(digest_response_handler, wait_to_close_event=close_server)178179 with server as (host, port):177 url = 'http://{}:{}/'.format(host, port)180 url = f'http://{host}:{port}/'181 r = requests.get(url, auth=auth)182 # Verify server succeeded in authenticating.183 assert r.status_code == 200184 # Verify Authorization was sent in final request.
41 unmodified lines
226 close_server = threading.Event()227 server = Server(digest_failed_response_handler, wait_to_close_event=close_server)228229 with server as (host, port):227 url = 'http://{}:{}/'.format(host, port)230 url = f'http://{host}:{port}/'231 r = requests.get(url, auth=auth)232 # Verify server didn't authenticate us.233 assert r.status_code == 401234 assert r.history[0].status_code == 401
28 unmodified lines
263 close_server = threading.Event()264 server = Server(digest_response_handler, wait_to_close_event=close_server)265266 with server as (host, port):264 url = 'http://{}:{}/'.format(host, port)267 url = f'http://{host}:{port}/'268 r = requests.get(url, auth=auth)269 # Verify server didn't receive auth from us.270 assert r.status_code == 200271 assert len(r.history) == 0
8 unmodified lines
280281_proxy_combos = []282for prefix, schemes in _schemes_by_var_prefix:283 for scheme in schemes:281 _proxy_combos.append(("{}_proxy".format(prefix), scheme))284 _proxy_combos.append((f"{prefix}_proxy", scheme))285286_proxy_combos += [(var.upper(), scheme) for var, scheme in _proxy_combos]287288289@pytest.mark.parametrize("var,scheme", _proxy_combos)290def test_use_proxy_from_environment(httpbin, var, scheme):288 url = "{}://httpbin.org".format(scheme)291 url = f"{scheme}://httpbin.org"292 fake_proxy = Server() # do nothing with the requests; just close the socket293 with fake_proxy as (host, port):291 proxy_url = "socks5://{}:{}".format(host, port)294 proxy_url = f"socks5://{host}:{port}"295 kwargs = {var: proxy_url}296 with override_environ(**kwargs):297 # fake proxy's lack of response will cause a ConnectionError298 with pytest.raises(requests.exceptions.ConnectionError):
6 unmodified lines
305 assert len(fake_proxy.handler_results[0]) > 0306307308def test_redirect_rfc1808_to_non_ascii_location():306 path = u'š'309 path = 'š'310 expected_path = b'%C5%A1'311 redirect_request = [] # stores the second request to the server312313 def redirect_resp_handler(sock):314 consume_socket_content(sock, timeout=0.5)312 location = u'//{}:{}/{}'.format(host, port, path)315 location = f'//{host}:{port}/{path}'316 sock.send(317 (314 b'HTTP/1.1 301 Moved Permanently\r\n'315 b'Content-Length: 0\r\n'316 b'Location: ' + location.encode('utf8') + b'\r\n'317 b'\r\n'318 b'HTTP/1.1 301 Moved Permanently\r\n'319 b'Content-Length: 0\r\n'320 b'Location: %s\r\n'321 b'\r\n'322 ) % location.encode('utf8')323 )324 redirect_request.append(consume_socket_content(sock, timeout=0.5))325 sock.send(b'HTTP/1.1 200 OK\r\n\r\n')326327 close_server = threading.Event()328 server = Server(redirect_resp_handler, wait_to_close_event=close_server)329330 with server as (host, port):326 url = u'http://{}:{}'.format(host, port)331 url = f'http://{host}:{port}'332 r = requests.get(url=url, allow_redirects=True)333 assert r.status_code == 200334 assert len(r.history) == 1335 assert r.history[0].status_code == 301336 assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')332 assert r.url == u'{}/{}'.format(url, expected_path.decode('ascii'))337 assert r.url == '{}/{}'.format(url, expected_path.decode('ascii'))338339 close_server.set()340341342def test_fragment_not_sent_with_request():343 """Verify that the fragment portion of a URI isn't sent to the server."""338 def response_handler(sock):339 req = consume_socket_content(sock, timeout=0.5)340 sock.send(341 b'HTTP/1.1 200 OK\r\n'342 b'Content-Length: '+bytes(len(req))+b'\r\n'343 b'\r\n'+req344 )345344 close_server = threading.Event()347 server = Server(response_handler, wait_to_close_event=close_server)345 server = Server(echo_response_handler, wait_to_close_event=close_server)346347 with server as (host, port):350 url = 'http://{}:{}/path/to/thing/#view=edit&token=hunter2'.format(host, port)348 url = f'http://{host}:{port}/path/to/thing/#view=edit&token=hunter2'349 r = requests.get(url)350 raw_request = r.content351352 assert r.status_code == 200
6 unmodified lines
359 assert frag not in body360361 close_server.set()362363364def test_fragment_update_on_redirect():365 """Verify we only append previous fragment if one doesn't exist on new366 location. If a new fragment is encountered in a Location header, it should367 be added to all subsequent requests.
20 unmodified lines
388 close_server = threading.Event()389 server = Server(response_handler, wait_to_close_event=close_server)390391 with server as (host, port):393 url = 'http://{}:{}/path/to/thing/#view=edit&token=hunter2'.format(host, port)392 url = f'http://{host}:{port}/path/to/thing/#view=edit&token=hunter2'393 r = requests.get(url)395 raw_request = r.content394395 assert r.status_code == 200396 assert len(r.history) == 2397 assert r.history[0].request.url == url398399 # Verify we haven't overwritten the location with our previous fragment.402 assert r.history[1].request.url == 'http://{}:{}/get#relevant-section'.format(host, port)400 assert r.history[1].request.url == f'http://{host}:{port}/get#relevant-section'401 # Verify previous fragment is used and not the original.404 assert r.url == 'http://{}:{}/final-url/#relevant-section'.format(host, port)402 assert r.url == f'http://{host}:{port}/final-url/#relevant-section'403404 close_server.set()405406407def test_json_decode_compatibility_for_alt_utf_encodings():408409 def response_handler(sock):410 consume_socket_content(sock, timeout=0.5)
6 unmodified lines
417 close_server = threading.Event()418 server = Server(response_handler, wait_to_close_event=close_server)419420 with server as (host, port):422 url = 'http://{}:{}/'.format(host, port)421 url = f'http://{host}:{port}/'422 r = requests.get(url)423 r.encoding = None424 with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:425 r.json()
3 unmodified lines
modified:tests/test_requests.py+982 added-898 removed
1# -*- coding: utf-8 -*-21"""Tests for Requests."""23import collections4import contextlib5import io6import json7import os8import pickle8import collections9import contextlib10import warnings9import re10import warnings1113import io14import requests12import pytest13import urllib314from urllib3.util import Timeout as Urllib3Timeout1516import requests17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (20 Morsel, cookielib, getproxies, urlparse,21 builtin_str)22from requests.cookies import (23 cookiejar_from_dict, morsel_to_cookie)20 JSONDecodeError,21 Morsel,22 MutableMapping,23 builtin_str,24 cookielib,25 getproxies,26 urlparse,27)28from requests.cookies import cookiejar_from_dict, morsel_to_cookie29from requests.exceptions import (30 ChunkedEncodingError,31 ConnectionError,32 ConnectTimeout,33 ContentDecodingError,34 InvalidHeader,30 InvalidJSONError,35 InvalidProxyURL,36 InvalidSchema,37 InvalidURL,38 MissingSchema,39 ProxyError,40 ReadTimeout,41 RequestException,42 RetryError,39 Timeout,40 TooManyRedirects,41 UnrewindableBodyError,43)44from requests.exceptions import SSLError as RequestsSSLError44from requests.models import PreparedRequest45from requests.structures import CaseInsensitiveDict46from requests.sessions import SessionRedirectMixin47from requests.models import urlencode45from requests.exceptions import Timeout, TooManyRedirects, UnrewindableBodyError46from requests.hooks import default_hooks49from requests.compat import JSONDecodeError, MutableMapping47from requests.models import PreparedRequest, urlencode48from requests.sessions import SessionRedirectMixin49from requests.structures import CaseInsensitiveDict5051from .compat import StringIO52from .utils import override_environ53from urllib3.util import Timeout as Urllib3Timeout5354# Requests to this URL should always fail with a connection timeout (nothing55# listening on that port)57TARPIT = 'http://10.255.255.1'56TARPIT = "http://10.255.255.1"5758# This is to avoid waiting the timeout of using TARPIT60INVALID_PROXY='http://localhost:1'59INVALID_PROXY = "http://localhost:1"6061try:62 from ssl import SSLContext6364 del SSLContext65 HAS_MODERN_SSL = True66except ImportError:67 HAS_MODERN_SSL = False
6 unmodified lines
747576class TestRequests:7778 digest_auth_algo = ('MD5', 'SHA-256', 'SHA-512')78 digest_auth_algo = ("MD5", "SHA-256", "SHA-512")7980 def test_entry_points(self):8182 requests.session
4 unmodified lines
87 requests.put88 requests.patch89 requests.post90 # Not really an entry point, but people rely on it.91 from requests.packages.urllib3.poolmanager import PoolManager91 from requests.packages.urllib3.poolmanager import PoolManager # noqa:F4019293 @pytest.mark.parametrize(94 'exception, url', (95 (MissingSchema, 'hiwpefhipowhefopw'),96 (InvalidSchema, 'localhost:3128'),97 (InvalidSchema, 'localhost.localdomain:3128/'),98 (InvalidSchema, '10.122.1.1:3128/'),99 (InvalidURL, 'http://'),100 (InvalidURL, 'http://*example.com'),101 (InvalidURL, 'http://.example.com'),102 ))94 "exception, url",95 (96 (MissingSchema, "hiwpefhipowhefopw"),97 (InvalidSchema, "localhost:3128"),98 (InvalidSchema, "localhost.localdomain:3128/"),99 (InvalidSchema, "10.122.1.1:3128/"),100 (InvalidURL, "http://"),101 (InvalidURL, "http://*example.com"),102 (InvalidURL, "http://.example.com"),103 ),104 )105 def test_invalid_url(self, exception, url):106 with pytest.raises(exception):107 requests.get(url)108109 def test_basic_building(self):110 req = requests.Request()109 req.url = 'http://kennethreitz.org/'110 req.data = {'life': '42'}111 req.url = "http://kennethreitz.org/"112 req.data = {"life": "42"}113114 pr = req.prepare()115 assert pr.url == req.url114 assert pr.body == 'life=42'116 assert pr.body == "life=42"117116 @pytest.mark.parametrize('method', ('GET', 'HEAD'))118 @pytest.mark.parametrize("method", ("GET", "HEAD"))119 def test_no_content_length(self, httpbin, method):120 req = requests.Request(method, httpbin(method.lower())).prepare()119 assert 'Content-Length' not in req.headers121 assert "Content-Length" not in req.headers122121 @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))123 @pytest.mark.parametrize("method", ("POST", "PUT", "PATCH", "OPTIONS"))124 def test_no_body_content_length(self, httpbin, method):125 req = requests.Request(method, httpbin(method.lower())).prepare()124 assert req.headers['Content-Length'] == '0'126 assert req.headers["Content-Length"] == "0"127126 @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))128 @pytest.mark.parametrize("method", ("POST", "PUT", "PATCH", "OPTIONS"))129 def test_empty_content_length(self, httpbin, method):128 req = requests.Request(method, httpbin(method.lower()), data='').prepare()129 assert req.headers['Content-Length'] == '0'130 req = requests.Request(method, httpbin(method.lower()), data="").prepare()131 assert req.headers["Content-Length"] == "0"132133 def test_override_content_length(self, httpbin):132 headers = {133 'Content-Length': 'not zero'134 }135 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()136 assert 'Content-Length' in r.headers137 assert r.headers['Content-Length'] == 'not zero'134 headers = {"Content-Length": "not zero"}135 r = requests.Request("POST", httpbin("post"), headers=headers).prepare()136 assert "Content-Length" in r.headers137 assert r.headers["Content-Length"] == "not zero"138139 def test_path_is_not_double_encoded(self):140 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()140 request = requests.Request("GET", "http://0.0.0.0/get/test case").prepare()141142 assert request.path_url == '/get/test%20case'142 assert request.path_url == "/get/test%20case"143144 @pytest.mark.parametrize(145 'url, expected', (146 ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),147 ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')148 ))145 "url, expected",146 (147 (148 "http://example.com/path#fragment",149 "http://example.com/path?a=b#fragment",150 ),151 (152 "http://example.com/path?key=value#fragment",153 "http://example.com/path?key=value&a=b#fragment",154 ),155 ),156 )157 def test_params_are_added_before_fragment(self, url, expected):150 request = requests.Request('GET', url, params={"a": "b"}).prepare()158 request = requests.Request("GET", url, params={"a": "b"}).prepare()159 assert request.url == expected160161 def test_params_original_order_is_preserved_by_default(self):154 param_ordered_dict = collections.OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))162 param_ordered_dict = collections.OrderedDict(163 (("z", 1), ("a", 1), ("k", 1), ("d", 1))164 )165 session = requests.Session()156 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)166 request = requests.Request(167 "GET", "http://example.com/", params=param_ordered_dict168 )169 prep = session.prepare_request(request)158 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'170 assert prep.url == "http://example.com/?z=1&a=1&k=1&d=1"171172 def test_params_bytes_are_encoded(self):161 request = requests.Request('GET', 'http://example.com',162 params=b'test=foo').prepare()163 assert request.url == 'http://example.com/?test=foo'173 request = requests.Request(174 "GET", "http://example.com", params=b"test=foo"175 ).prepare()176 assert request.url == "http://example.com/?test=foo"177178 def test_binary_put(self):166 request = requests.Request('PUT', 'http://example.com',167 data=u"ööö".encode("utf-8")).prepare()179 request = requests.Request(180 "PUT", "http://example.com", data="ööö".encode()181 ).prepare()182 assert isinstance(request.body, bytes)183184 def test_whitespaces_are_removed_from_url(self):185 # Test for issue #3696172 request = requests.Request('GET', ' http://example.com').prepare()173 assert request.url == 'http://example.com/'186 request = requests.Request("GET", " http://example.com").prepare()187 assert request.url == "http://example.com/"188175 @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))189 @pytest.mark.parametrize("scheme", ("http://", "HTTP://", "hTTp://", "HttP://"))190 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):191 s = requests.Session()192 s.proxies = getproxies()179 parts = urlparse(httpbin('get'))193 parts = urlparse(httpbin("get"))194 url = scheme + parts.netloc + parts.path181 r = requests.Request('GET', url)195 r = requests.Request("GET", url)196 r = s.send(r.prepare())183 assert r.status_code == 200, 'failed for scheme {}'.format(scheme)197 assert r.status_code == 200, f"failed for scheme {scheme}"198199 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):186 r = requests.Request('GET', httpbin('get'))200 r = requests.Request("GET", httpbin("get"))201 s = requests.Session()202 s.proxies = getproxies()203204 r = s.send(r.prepare())205206 assert r.status_code == 200207208 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):195 r = requests.get(httpbin('redirect', '1'))209 r = requests.get(httpbin("redirect", "1"))210 assert r.status_code == 200211 assert r.history[0].status_code == 302212 assert r.history[0].is_redirect213214 def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):201 r = requests.post(httpbin('redirect-to'), data='test', params={'url': 'post', 'status_code': 307})215 r = requests.post(216 httpbin("redirect-to"),217 data="test",218 params={"url": "post", "status_code": 307},219 )220 assert r.status_code == 200221 assert r.history[0].status_code == 307222 assert r.history[0].is_redirect205 assert r.json()['data'] == 'test'223 assert r.json()["data"] == "test"224225 def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):208 byte_str = b'test'209 r = requests.post(httpbin('redirect-to'), data=io.BytesIO(byte_str), params={'url': 'post', 'status_code': 307})226 byte_str = b"test"227 r = requests.post(228 httpbin("redirect-to"),229 data=io.BytesIO(byte_str),230 params={"url": "post", "status_code": 307},231 )232 assert r.status_code == 200233 assert r.history[0].status_code == 307234 assert r.history[0].is_redirect213 assert r.json()['data'] == byte_str.decode('utf-8')235 assert r.json()["data"] == byte_str.decode("utf-8")236237 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):238 try:217 requests.get(httpbin('relative-redirect', '50'))239 requests.get(httpbin("relative-redirect", "50"))240 except TooManyRedirects as e:219 url = httpbin('relative-redirect', '20')241 url = httpbin("relative-redirect", "20")242 assert e.request.url == url243 assert e.response.url == url244 assert len(e.response.history) == 30245 else:224 pytest.fail('Expected redirect to raise TooManyRedirects but it did not')246 pytest.fail("Expected redirect to raise TooManyRedirects but it did not")247248 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):249 s = requests.session()250 s.max_redirects = 5251 try:230 s.get(httpbin('relative-redirect', '50'))252 s.get(httpbin("relative-redirect", "50"))253 except TooManyRedirects as e:232 url = httpbin('relative-redirect', '45')254 url = httpbin("relative-redirect", "45")255 assert e.request.url == url256 assert e.response.url == url257 assert len(e.response.history) == 5258 else:237 pytest.fail('Expected custom max number of redirects to be respected but was not')259 pytest.fail(260 "Expected custom max number of redirects to be respected but was not"261 )262263 def test_http_301_changes_post_to_get(self, httpbin):240 r = requests.post(httpbin('status', '301'))264 r = requests.post(httpbin("status", "301"))265 assert r.status_code == 200242 assert r.request.method == 'GET'266 assert r.request.method == "GET"267 assert r.history[0].status_code == 301268 assert r.history[0].is_redirect269270 def test_http_301_doesnt_change_head_to_get(self, httpbin):247 r = requests.head(httpbin('status', '301'), allow_redirects=True)271 r = requests.head(httpbin("status", "301"), allow_redirects=True)272 print(r.content)273 assert r.status_code == 200250 assert r.request.method == 'HEAD'274 assert r.request.method == "HEAD"275 assert r.history[0].status_code == 301276 assert r.history[0].is_redirect277278 def test_http_302_changes_post_to_get(self, httpbin):255 r = requests.post(httpbin('status', '302'))279 r = requests.post(httpbin("status", "302"))280 assert r.status_code == 200257 assert r.request.method == 'GET'281 assert r.request.method == "GET"282 assert r.history[0].status_code == 302283 assert r.history[0].is_redirect284285 def test_http_302_doesnt_change_head_to_get(self, httpbin):262 r = requests.head(httpbin('status', '302'), allow_redirects=True)286 r = requests.head(httpbin("status", "302"), allow_redirects=True)287 assert r.status_code == 200264 assert r.request.method == 'HEAD'288 assert r.request.method == "HEAD"289 assert r.history[0].status_code == 302290 assert r.history[0].is_redirect291292 def test_http_303_changes_post_to_get(self, httpbin):269 r = requests.post(httpbin('status', '303'))293 r = requests.post(httpbin("status", "303"))294 assert r.status_code == 200271 assert r.request.method == 'GET'295 assert r.request.method == "GET"296 assert r.history[0].status_code == 303297 assert r.history[0].is_redirect298299 def test_http_303_doesnt_change_head_to_get(self, httpbin):276 r = requests.head(httpbin('status', '303'), allow_redirects=True)300 r = requests.head(httpbin("status", "303"), allow_redirects=True)301 assert r.status_code == 200278 assert r.request.method == 'HEAD'302 assert r.request.method == "HEAD"303 assert r.history[0].status_code == 303304 assert r.history[0].is_redirect305306 def test_header_and_body_removal_on_redirect(self, httpbin):283 purged_headers = ('Content-Length', 'Content-Type')307 purged_headers = ("Content-Length", "Content-Type")308 ses = requests.Session()285 req = requests.Request('POST', httpbin('post'), data={'test': 'data'})309 req = requests.Request("POST", httpbin("post"), data={"test": "data"})310 prep = ses.prepare_request(req)311 resp = ses.send(prep)312313 # Mimic a redirect response314 resp.status_code = 302291 resp.headers['location'] = 'get'315 resp.headers["location"] = "get"316317 # Run request through resolve_redirects318 next_resp = next(ses.resolve_redirects(resp, prep))319 assert next_resp.request.body is None320 for header in purged_headers:321 assert header not in next_resp.request.headers322323 def test_transfer_enc_removal_on_redirect(self, httpbin):300 purged_headers = ('Transfer-Encoding', 'Content-Type')324 purged_headers = ("Transfer-Encoding", "Content-Type")325 ses = requests.Session()302 req = requests.Request('POST', httpbin('post'), data=(b'x' for x in range(1)))326 req = requests.Request("POST", httpbin("post"), data=(b"x" for x in range(1)))327 prep = ses.prepare_request(req)304 assert 'Transfer-Encoding' in prep.headers328 assert "Transfer-Encoding" in prep.headers329330 # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33331 resp = requests.Response()308 resp.raw = io.BytesIO(b'the content')332 resp.raw = io.BytesIO(b"the content")333 resp.request = prep310 setattr(resp.raw, 'release_conn', lambda *args: args)334 setattr(resp.raw, "release_conn", lambda *args: args)335336 # Mimic a redirect response337 resp.status_code = 302314 resp.headers['location'] = httpbin('get')338 resp.headers["location"] = httpbin("get")339340 # Run request through resolve_redirect341 next_resp = next(ses.resolve_redirects(resp, prep))342 assert next_resp.request.body is None
1 unmodified line
344 assert header not in next_resp.request.headers345346 def test_fragment_maintained_on_redirect(self, httpbin):347 fragment = "#view=edit&token=hunter2"324 r = requests.get(httpbin('redirect-to?url=get')+fragment)348 r = requests.get(httpbin("redirect-to?url=get") + fragment)349350 assert len(r.history) > 0327 assert r.history[0].request.url == httpbin('redirect-to?url=get')+fragment328 assert r.url == httpbin('get')+fragment351 assert r.history[0].request.url == httpbin("redirect-to?url=get") + fragment352 assert r.url == httpbin("get") + fragment353354 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):331 heads = {'User-agent': 'Mozilla/5.0'}355 heads = {"User-agent": "Mozilla/5.0"}356333 r = requests.get(httpbin('user-agent'), headers=heads)357 r = requests.get(httpbin("user-agent"), headers=heads)358335 assert heads['User-agent'] in r.text359 assert heads["User-agent"] in r.text360 assert r.status_code == 200361362 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):339 heads = {'User-agent': 'Mozilla/5.0'}363 heads = {"User-agent": "Mozilla/5.0"}364341 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)365 r = requests.get(366 httpbin("get") + "?test=true", params={"q": "test"}, headers=heads367 )368 assert r.status_code == 200369370 def test_set_cookie_on_301(self, httpbin):371 s = requests.session()346 url = httpbin('cookies/set?foo=bar')372 url = httpbin("cookies/set?foo=bar")373 s.get(url)348 assert s.cookies['foo'] == 'bar'374 assert s.cookies["foo"] == "bar"375376 def test_cookie_sent_on_redirect(self, httpbin):377 s = requests.session()352 s.get(httpbin('cookies/set?foo=bar'))353 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')354 assert 'Cookie' in r.json()['headers']378 s.get(httpbin("cookies/set?foo=bar"))379 r = s.get(httpbin("redirect/1")) # redirects to httpbin('get')380 assert "Cookie" in r.json()["headers"]381382 def test_cookie_removed_on_expire(self, httpbin):383 s = requests.session()358 s.get(httpbin('cookies/set?foo=bar'))359 assert s.cookies['foo'] == 'bar'384 s.get(httpbin("cookies/set?foo=bar"))385 assert s.cookies["foo"] == "bar"386 s.get(361 httpbin('response-headers'),362 params={363 'Set-Cookie':364 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'365 }387 httpbin("response-headers"),388 params={"Set-Cookie": "foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT"},389 )367 assert 'foo' not in s.cookies390 assert "foo" not in s.cookies391392 def test_cookie_quote_wrapped(self, httpbin):393 s = requests.session()394 s.get(httpbin('cookies/set?foo="bar:baz"'))372 assert s.cookies['foo'] == '"bar:baz"'395 assert s.cookies["foo"] == '"bar:baz"'396397 def test_cookie_persists_via_api(self, httpbin):398 s = requests.session()376 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})377 assert 'foo' in r.request.headers['Cookie']378 assert 'foo' in r.history[0].request.headers['Cookie']399 r = s.get(httpbin("redirect/1"), cookies={"foo": "bar"})400 assert "foo" in r.request.headers["Cookie"]401 assert "foo" in r.history[0].request.headers["Cookie"]402403 def test_request_cookie_overrides_session_cookie(self, httpbin):404 s = requests.session()382 s.cookies['foo'] = 'bar'383 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})384 assert r.json()['cookies']['foo'] == 'baz'405 s.cookies["foo"] = "bar"406 r = s.get(httpbin("cookies"), cookies={"foo": "baz"})407 assert r.json()["cookies"]["foo"] == "baz"408 # Session cookie should not be modified386 assert s.cookies['foo'] == 'bar'409 assert s.cookies["foo"] == "bar"410411 def test_request_cookies_not_persisted(self, httpbin):412 s = requests.session()390 s.get(httpbin('cookies'), cookies={'foo': 'baz'})413 s.get(httpbin("cookies"), cookies={"foo": "baz"})414 # Sending a request with cookies should not add cookies to the session415 assert not s.cookies416417 def test_generic_cookiejar_works(self, httpbin):418 cj = cookielib.CookieJar()396 cookiejar_from_dict({'foo': 'bar'}, cj)419 cookiejar_from_dict({"foo": "bar"}, cj)420 s = requests.session()421 s.cookies = cj399 r = s.get(httpbin('cookies'))422 r = s.get(httpbin("cookies"))423 # Make sure the cookie was sent401 assert r.json()['cookies']['foo'] == 'bar'424 assert r.json()["cookies"]["foo"] == "bar"425 # Make sure the session cj is still the custom one426 assert s.cookies is cj427428 def test_param_cookiejar_works(self, httpbin):429 cj = cookielib.CookieJar()407 cookiejar_from_dict({'foo': 'bar'}, cj)430 cookiejar_from_dict({"foo": "bar"}, cj)431 s = requests.session()409 r = s.get(httpbin('cookies'), cookies=cj)432 r = s.get(httpbin("cookies"), cookies=cj)433 # Make sure the cookie was sent411 assert r.json()['cookies']['foo'] == 'bar'434 assert r.json()["cookies"]["foo"] == "bar"435436 def test_cookielib_cookiejar_on_redirect(self, httpbin):437 """Tests resolve_redirect doesn't fail when merging cookies438 with non-RequestsCookieJar cookiejar.439440 See GH #3579441 """419 cj = cookiejar_from_dict({'foo': 'bar'}, cookielib.CookieJar())442 cj = cookiejar_from_dict({"foo": "bar"}, cookielib.CookieJar())443 s = requests.Session()421 s.cookies = cookiejar_from_dict({'cookie': 'tasty'})444 s.cookies = cookiejar_from_dict({"cookie": "tasty"})445446 # Prepare request without using Session424 req = requests.Request('GET', httpbin('headers'), cookies=cj)447 req = requests.Request("GET", httpbin("headers"), cookies=cj)448 prep_req = req.prepare()449450 # Send request and simulate redirect451 resp = s.send(prep_req)452 resp.status_code = 302430 resp.headers['location'] = httpbin('get')453 resp.headers["location"] = httpbin("get")454 redirects = s.resolve_redirects(resp, prep_req)455 resp = next(redirects)456457 # Verify CookieJar isn't being converted to RequestsCookieJar
3 unmodified lines
461462 cookies = {}463 for c in resp.request._cookies:464 cookies[c.name] = c.value442 assert cookies['foo'] == 'bar'443 assert cookies['cookie'] == 'tasty'465 assert cookies["foo"] == "bar"466 assert cookies["cookie"] == "tasty"467468 def test_requests_in_history_are_not_overridden(self, httpbin):446 resp = requests.get(httpbin('redirect/3'))469 resp = requests.get(httpbin("redirect/3"))470 urls = [r.url for r in resp.history]471 req_urls = [r.request.url for r in resp.history]472 assert urls == req_urls473474 def test_history_is_always_a_list(self, httpbin):475 """Show that even with redirects, Response.history is always a list."""453 resp = requests.get(httpbin('get'))476 resp = requests.get(httpbin("get"))477 assert isinstance(resp.history, list)455 resp = requests.get(httpbin('redirect/1'))478 resp = requests.get(httpbin("redirect/1"))479 assert isinstance(resp.history, list)480 assert not isinstance(resp.history, tuple)481482 def test_headers_on_session_with_None_are_not_sent(self, httpbin):483 """Do not send headers in Session.headers with None values."""484 ses = requests.Session()462 ses.headers['Accept-Encoding'] = None463 req = requests.Request('GET', httpbin('get'))485 ses.headers["Accept-Encoding"] = None486 req = requests.Request("GET", httpbin("get"))487 prep = ses.prepare_request(req)465 assert 'Accept-Encoding' not in prep.headers488 assert "Accept-Encoding" not in prep.headers489490 def test_headers_preserve_order(self, httpbin):491 """Preserve order when headers provided as OrderedDict."""492 ses = requests.Session()493 ses.headers = collections.OrderedDict()471 ses.headers['Accept-Encoding'] = 'identity'472 ses.headers['First'] = '1'473 ses.headers['Second'] = '2'474 headers = collections.OrderedDict([('Third', '3'), ('Fourth', '4')])475 headers['Fifth'] = '5'476 headers['Second'] = '222'477 req = requests.Request('GET', httpbin('get'), headers=headers)494 ses.headers["Accept-Encoding"] = "identity"495 ses.headers["First"] = "1"496 ses.headers["Second"] = "2"497 headers = collections.OrderedDict([("Third", "3"), ("Fourth", "4")])498 headers["Fifth"] = "5"499 headers["Second"] = "222"500 req = requests.Request("GET", httpbin("get"), headers=headers)501 prep = ses.prepare_request(req)502 items = list(prep.headers.items())480 assert items[0] == ('Accept-Encoding', 'identity')481 assert items[1] == ('First', '1')482 assert items[2] == ('Second', '222')483 assert items[3] == ('Third', '3')484 assert items[4] == ('Fourth', '4')485 assert items[5] == ('Fifth', '5')503 assert items[0] == ("Accept-Encoding", "identity")504 assert items[1] == ("First", "1")505 assert items[2] == ("Second", "222")506 assert items[3] == ("Third", "3")507 assert items[4] == ("Fourth", "4")508 assert items[5] == ("Fifth", "5")509487 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))510 @pytest.mark.parametrize("key", ("User-agent", "user-agent"))511 def test_user_agent_transfers(self, httpbin, key):512490 heads = {key: 'Mozilla/5.0 (github.com/psf/requests)'}513 heads = {key: "Mozilla/5.0 (github.com/psf/requests)"}514492 r = requests.get(httpbin('user-agent'), headers=heads)515 r = requests.get(httpbin("user-agent"), headers=heads)516 assert heads[key] in r.text517518 def test_HTTP_200_OK_HEAD(self, httpbin):496 r = requests.head(httpbin('get'))519 r = requests.head(httpbin("get"))520 assert r.status_code == 200521522 def test_HTTP_200_OK_PUT(self, httpbin):500 r = requests.put(httpbin('put'))523 r = requests.put(httpbin("put"))524 assert r.status_code == 200525526 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):504 auth = ('user', 'pass')505 url = httpbin('basic-auth', 'user', 'pass')527 auth = ("user", "pass")528 url = httpbin("basic-auth", "user", "pass")529530 r = requests.get(url, auth=auth)531 assert r.status_code == 200532
5 unmodified lines
538 r = s.get(url)539 assert r.status_code == 200540541 @pytest.mark.parametrize(519 'username, password', (520 ('user', 'pass'),521 ('имя'.encode('utf-8'), 'пароль'.encode('utf-8')),542 "username, password",543 (544 ("user", "pass"),545 ("имя".encode(), "пароль".encode()),546 (42, 42),547 (None, None),524 ))548 ),549 )550 def test_set_basicauth(self, httpbin, username, password):551 auth = (username, password)527 url = httpbin('get')552 url = httpbin("get")553529 r = requests.Request('GET', url, auth=auth)554 r = requests.Request("GET", url, auth=auth)555 p = r.prepare()556532 assert p.headers['Authorization'] == _basic_auth_str(username, password)557 assert p.headers["Authorization"] == _basic_auth_str(username, password)558559 def test_basicauth_encodes_byte_strings(self):560 """Ensure b'test' formats as the byte string "test" rather561 than the unicode string "b'test'" in Python 3.562 """538 auth = (b'\xc5\xafsername', b'test\xc6\xb6')539 r = requests.Request('GET', 'http://localhost', auth=auth)563 auth = (b"\xc5\xafsername", b"test\xc6\xb6")564 r = requests.Request("GET", "http://localhost", auth=auth)565 p = r.prepare()566542 assert p.headers['Authorization'] == 'Basic xa9zZXJuYW1lOnRlc3TGtg=='567 assert p.headers["Authorization"] == "Basic xa9zZXJuYW1lOnRlc3TGtg=="568569 @pytest.mark.parametrize(545 'url, exception', (570 "url, exception",571 (572 # Connecting to an unknown domain should raise a ConnectionError547 ('http://doesnotexist.google.com', ConnectionError),573 ("http://doesnotexist.google.com", ConnectionError),574 # Connecting to an invalid port should raise a ConnectionError549 ('http://localhost:1', ConnectionError),575 ("http://localhost:1", ConnectionError),576 # Inputing a URL that cannot be parsed should raise an InvalidURL error551 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)552 ))577 ("http://fe80::5054:ff:fe5a:fc0", InvalidURL),578 ),579 )580 def test_errors(self, url, exception):581 with pytest.raises(exception):582 requests.get(url, timeout=1)583584 def test_proxy_error(self):585 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError586 with pytest.raises(ProxyError):560 requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})587 requests.get(588 "http://localhost:1", proxies={"http": "non-resolvable-address"}589 )590591 def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):592 with pytest.raises(InvalidProxyURL):564 requests.get(httpbin_secure(), proxies={'https': 'http:/badproxyurl:3128'})593 requests.get(httpbin_secure(), proxies={"https": "http:/badproxyurl:3128"})594595 with pytest.raises(InvalidProxyURL):567 requests.get(httpbin(), proxies={'http': 'http://:8080'})596 requests.get(httpbin(), proxies={"http": "http://:8080"})597598 with pytest.raises(InvalidProxyURL):570 requests.get(httpbin_secure(), proxies={'https': 'https://'})599 requests.get(httpbin_secure(), proxies={"https": "https://"})600601 with pytest.raises(InvalidProxyURL):573 requests.get(httpbin(), proxies={'http': 'http:///example.com:8080'})602 requests.get(httpbin(), proxies={"http": "http:///example.com:8080"})603604 def test_respect_proxy_env_on_send_self_prepared_request(self, httpbin):605 with override_environ(http_proxy=INVALID_PROXY):606 with pytest.raises(ProxyError):607 session = requests.Session()579 request = requests.Request('GET', httpbin())608 request = requests.Request("GET", httpbin())609 session.send(request.prepare())610611 def test_respect_proxy_env_on_send_session_prepared_request(self, httpbin):612 with override_environ(http_proxy=INVALID_PROXY):613 with pytest.raises(ProxyError):614 session = requests.Session()586 request = requests.Request('GET', httpbin())615 request = requests.Request("GET", httpbin())616 prepared = session.prepare_request(request)617 session.send(prepared)618619 def test_respect_proxy_env_on_send_with_redirects(self, httpbin):620 with override_environ(http_proxy=INVALID_PROXY):621 with pytest.raises(ProxyError):622 session = requests.Session()594 url = httpbin('redirect/1')623 url = httpbin("redirect/1")624 print(url)596 request = requests.Request('GET', url)625 request = requests.Request("GET", url)626 session.send(request.prepare())627628 def test_respect_proxy_env_on_get(self, httpbin):629 with override_environ(http_proxy=INVALID_PROXY):
4 unmodified lines
634 def test_respect_proxy_env_on_request(self, httpbin):635 with override_environ(http_proxy=INVALID_PROXY):636 with pytest.raises(ProxyError):637 session = requests.Session()609 session.request(method='GET', url=httpbin())638 session.request(method="GET", url=httpbin())639640 def test_proxy_authorization_preserved_on_request(self, httpbin):641 proxy_auth_value = "Bearer XXX"642 session = requests.Session()643 session.headers.update({"Proxy-Authorization": proxy_auth_value})615 resp = session.request(method='GET', url=httpbin('get'))616 sent_headers = resp.json().get('headers', {})644 resp = session.request(method="GET", url=httpbin("get"))645 sent_headers = resp.json().get("headers", {})646647 assert sent_headers.get("Proxy-Authorization") == proxy_auth_value648649 def test_basicauth_with_netrc(self, httpbin):621 auth = ('user', 'pass')622 wrong_auth = ('wronguser', 'wrongpass')623 url = httpbin('basic-auth', 'user', 'pass')650 auth = ("user", "pass")651 wrong_auth = ("wronguser", "wrongpass")652 url = httpbin("basic-auth", "user", "pass")653654 old_auth = requests.sessions.get_netrc_auth655656 try:657658 def get_netrc_auth_mock(url):659 return auth660661 requests.sessions.get_netrc_auth = get_netrc_auth_mock662663 # Should use netrc and work.664 r = requests.get(url)
18 unmodified lines
683684 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):685686 for authtype in self.digest_auth_algo:656 auth = HTTPDigestAuth('user', 'pass')657 url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype, 'never')687 auth = HTTPDigestAuth("user", "pass")688 url = httpbin("digest-auth", "auth", "user", "pass", authtype, "never")689690 r = requests.get(url, auth=auth)691 assert r.status_code == 200692693 r = requests.get(url)694 assert r.status_code == 401664 print(r.headers['WWW-Authenticate'])695 print(r.headers["WWW-Authenticate"])696697 s = requests.session()667 s.auth = HTTPDigestAuth('user', 'pass')698 s.auth = HTTPDigestAuth("user", "pass")699 r = s.get(url)700 assert r.status_code == 200701702 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):703704 for authtype in self.digest_auth_algo:674 url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)675 auth = HTTPDigestAuth('user', 'pass')705 url = httpbin("digest-auth", "auth", "user", "pass", authtype)706 auth = HTTPDigestAuth("user", "pass")707 r = requests.get(url)677 assert r.cookies['fake'] == 'fake_value'708 assert r.cookies["fake"] == "fake_value"709710 r = requests.get(url, auth=auth)711 assert r.status_code == 200712713 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):714715 for authtype in self.digest_auth_algo:685 url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)686 auth = HTTPDigestAuth('user', 'pass')716 url = httpbin("digest-auth", "auth", "user", "pass", authtype)717 auth = HTTPDigestAuth("user", "pass")718 s = requests.Session()719 s.get(url, auth=auth)689 assert s.cookies['fake'] == 'fake_value'720 assert s.cookies["fake"] == "fake_value"721722 def test_DIGEST_STREAM(self, httpbin):723724 for authtype in self.digest_auth_algo:694 auth = HTTPDigestAuth('user', 'pass')695 url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)725 auth = HTTPDigestAuth("user", "pass")726 url = httpbin("digest-auth", "auth", "user", "pass", authtype)727728 r = requests.get(url, auth=auth, stream=True)698 assert r.raw.read() != b''729 assert r.raw.read() != b""730731 r = requests.get(url, auth=auth, stream=False)701 assert r.raw.read() == b''732 assert r.raw.read() == b""733734 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):735736 for authtype in self.digest_auth_algo:706 auth = HTTPDigestAuth('user', 'wrongpass')707 url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)737 auth = HTTPDigestAuth("user", "wrongpass")738 url = httpbin("digest-auth", "auth", "user", "pass", authtype)739740 r = requests.get(url, auth=auth)741 assert r.status_code == 401742
7 unmodified lines
750751 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):752753 for authtype in self.digest_auth_algo:723 auth = HTTPDigestAuth('user', 'pass')724 url = httpbin('digest-auth', 'auth', 'user', 'pass', authtype)754 auth = HTTPDigestAuth("user", "pass")755 url = httpbin("digest-auth", "auth", "user", "pass", authtype)756757 r = requests.get(url, auth=auth)727 assert '"auth"' in r.request.headers['Authorization']758 assert '"auth"' in r.request.headers["Authorization"]759760 def test_POSTBIN_GET_POST_FILES(self, httpbin):761731 url = httpbin('post')762 url = httpbin("post")763 requests.post(url).raise_for_status()764734 post1 = requests.post(url, data={'some': 'data'})765 post1 = requests.post(url, data={"some": "data"})766 assert post1.status_code == 200767737 with open('requirements-dev.txt') as f:738 post2 = requests.post(url, files={'some': f})768 with open("requirements-dev.txt") as f:769 post2 = requests.post(url, files={"some": f})770 assert post2.status_code == 200771772 post4 = requests.post(url, data='[{"some": "json"}]')773 assert post4.status_code == 200774775 with pytest.raises(ValueError):745 requests.post(url, files=['bad file data'])776 requests.post(url, files=["bad file data"])777778 def test_invalid_files_input(self, httpbin):779749 url = httpbin('post')750 post = requests.post(url,751 files={"random-file-1": None, "random-file-2": 1})780 url = httpbin("post")781 post = requests.post(url, files={"random-file-1": None, "random-file-2": 1})782 assert b'name="random-file-1"' not in post.request.body783 assert b'name="random-file-2"' in post.request.body784785 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):756757 class TestStream(object):786 class TestStream:787 def __init__(self, data):788 self.data = data.encode()789 self.length = len(self.data)790 self.index = 0
2 unmodified lines
793 return self.length794795 def read(self, size=None):796 if size:768 ret = self.data[self.index:self.index + size]797 ret = self.data[self.index : self.index + size]798 self.index += size799 else:771 ret = self.data[self.index:]800 ret = self.data[self.index :]801 self.index = self.length802 return ret803804 def tell(self):
6 unmodified lines
811 self.index += offset812 elif where == 2:813 self.index = self.length + offset814786 test = TestStream('test')787 post1 = requests.post(httpbin('post'), data=test)815 test = TestStream("test")816 post1 = requests.post(httpbin("post"), data=test)817 assert post1.status_code == 200789 assert post1.json()['data'] == 'test'818 assert post1.json()["data"] == "test"819791 test = TestStream('test')820 test = TestStream("test")821 test.seek(2)793 post2 = requests.post(httpbin('post'), data=test)822 post2 = requests.post(httpbin("post"), data=test)823 assert post2.status_code == 200795 assert post2.json()['data'] == 'st'824 assert post2.json()["data"] == "st"825826 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):827799 url = httpbin('post')828 url = httpbin("post")829 requests.post(url).raise_for_status()830802 post1 = requests.post(url, data={'some': 'data'})831 post1 = requests.post(url, data={"some": "data"})832 assert post1.status_code == 200833805 with open('requirements-dev.txt') as f:806 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})834 with open("requirements-dev.txt") as f:835 post2 = requests.post(url, data={"some": "data"}, files={"some": f})836 assert post2.status_code == 200837838 post4 = requests.post(url, data='[{"some": "json"}]')839 assert post4.status_code == 200840841 with pytest.raises(ValueError):813 requests.post(url, files=['bad file data'])842 requests.post(url, files=["bad file data"])843844 def test_post_with_custom_mapping(self, httpbin):845 class CustomMapping(MutableMapping):846 def __init__(self, *args, **kwargs):
13 unmodified lines
860861 def __len__(self):862 return len(self.data)863835 data = CustomMapping({'some': 'data'})836 url = httpbin('post')837 found_json = requests.post(url, data=data).json().get('form')838 assert found_json == {'some': 'data'}864 data = CustomMapping({"some": "data"})865 url = httpbin("post")866 found_json = requests.post(url, data=data).json().get("form")867 assert found_json == {"some": "data"}868869 def test_conflicting_post_params(self, httpbin):841 url = httpbin('post')842 with open('requirements-dev.txt') as f:870 url = httpbin("post")871 with open("requirements-dev.txt") as f:872 with pytest.raises(ValueError):844 requests.post(url, data='[{"some": "data"}]', files={'some': f})873 requests.post(url, data='[{"some": "data"}]', files={"some": f})874875 def test_request_ok_set(self, httpbin):847 r = requests.get(httpbin('status', '404'))876 r = requests.get(httpbin("status", "404"))877 assert not r.ok878879 def test_status_raising(self, httpbin):851 r = requests.get(httpbin('status', '404'))880 r = requests.get(httpbin("status", "404"))881 with pytest.raises(requests.exceptions.HTTPError):882 r.raise_for_status()883855 r = requests.get(httpbin('status', '500'))884 r = requests.get(httpbin("status", "500"))885 assert not r.ok886887 def test_decompress_gzip(self, httpbin):859 r = requests.get(httpbin('gzip'))860 r.content.decode('ascii')888 r = requests.get(httpbin("gzip"))889 r.content.decode("ascii")890891 @pytest.mark.parametrize(863 'url, params', (864 ('/get', {'foo': 'føø'}),865 ('/get', {'føø': 'føø'}),866 ('/get', {'føø': 'føø'}),867 ('/get', {'foo': 'foo'}),868 ('ø', {'foo': 'foo'}),869 ))892 "url, params",893 (894 ("/get", {"foo": "føø"}),895 ("/get", {"føø": "føø"}),896 ("/get", {"føø": "føø"}),897 ("/get", {"foo": "foo"}),898 ("ø", {"foo": "foo"}),899 ),900 )901 def test_unicode_get(self, httpbin, url, params):902 requests.get(httpbin(url), params=params)903904 def test_unicode_header_name(self, httpbin):905 requests.put(875 httpbin('put'),876 headers={str('Content-Type'): 'application/octet-stream'},877 data='\xff') # compat.str is unicode.906 httpbin("put"),907 headers={"Content-Type": "application/octet-stream"},908 data="\xff",909 ) # compat.str is unicode.910911 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):880 requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)912 requests.get(httpbin_secure("status", "301"), verify=httpbin_ca_bundle)913914 def test_invalid_ca_certificate_path(self, httpbin_secure):883 INVALID_PATH = '/garbage'915 INVALID_PATH = "/garbage"916 with pytest.raises(IOError) as e:917 requests.get(httpbin_secure(), verify=INVALID_PATH)886 assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {}'.format(INVALID_PATH)918 assert str(919 e.value920 ) == "Could not find a suitable TLS CA certificate bundle, invalid path: {}".format(921 INVALID_PATH922 )923924 def test_invalid_ssl_certificate_files(self, httpbin_secure):889 INVALID_PATH = '/garbage'925 INVALID_PATH = "/garbage"926 with pytest.raises(IOError) as e:927 requests.get(httpbin_secure(), cert=INVALID_PATH)892 assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {}'.format(INVALID_PATH)928 assert str(929 e.value930 ) == "Could not find the TLS certificate file, invalid path: {}".format(931 INVALID_PATH932 )933934 with pytest.raises(IOError) as e:895 requests.get(httpbin_secure(), cert=('.', INVALID_PATH))896 assert str(e.value) == 'Could not find the TLS key file, invalid path: {}'.format(INVALID_PATH)935 requests.get(httpbin_secure(), cert=(".", INVALID_PATH))936 assert str(e.value) == (937 f"Could not find the TLS key file, invalid path: {INVALID_PATH}"938 )939940 @pytest.mark.parametrize(899 'env, expected', (941 "env, expected",942 (943 ({}, True),901 ({'REQUESTS_CA_BUNDLE': '/some/path'}, '/some/path'),902 ({'REQUESTS_CA_BUNDLE': ''}, True),903 ({'CURL_CA_BUNDLE': '/some/path'}, '/some/path'),904 ({'CURL_CA_BUNDLE': ''}, True),905 ({'REQUESTS_CA_BUNDLE': '', 'CURL_CA_BUNDLE': ''}, True),944 ({"REQUESTS_CA_BUNDLE": "/some/path"}, "/some/path"),945 ({"REQUESTS_CA_BUNDLE": ""}, True),946 ({"CURL_CA_BUNDLE": "/some/path"}, "/some/path"),947 ({"CURL_CA_BUNDLE": ""}, True),948 ({"REQUESTS_CA_BUNDLE": "", "CURL_CA_BUNDLE": ""}, True),949 (950 {908 'REQUESTS_CA_BUNDLE': '/some/path',909 'CURL_CA_BUNDLE': '/curl/path',951 "REQUESTS_CA_BUNDLE": "/some/path",952 "CURL_CA_BUNDLE": "/curl/path",953 },911 '/some/path',954 "/some/path",955 ),956 (957 {915 'REQUESTS_CA_BUNDLE': '',916 'CURL_CA_BUNDLE': '/curl/path',958 "REQUESTS_CA_BUNDLE": "",959 "CURL_CA_BUNDLE": "/curl/path",960 },918 '/curl/path',961 "/curl/path",962 ),920 )963 ),964 )965 def test_env_cert_bundles(self, httpbin, mocker, env, expected):966 s = requests.Session()924 mocker.patch('os.environ', env)967 mocker.patch("os.environ", env)968 settings = s.merge_environment_settings(926 url=httpbin('get'),927 proxies={},928 stream=False,929 verify=True,930 cert=None969 url=httpbin("get"), proxies={}, stream=False, verify=True, cert=None970 )932 assert settings['verify'] == expected971 assert settings["verify"] == expected972973 def test_http_with_certificate(self, httpbin):935 r = requests.get(httpbin(), cert='.')974 r = requests.get(httpbin(), cert=".")975 assert r.status_code == 200976977 def test_https_warnings(self, nosan_server):978 """warnings are emitted with requests.get"""979 host, port, ca_bundle = nosan_server980 if HAS_MODERN_SSL or HAS_PYOPENSSL:942 warnings_expected = ('SubjectAltNameWarning', )981 warnings_expected = ("SubjectAltNameWarning",)982 else:944 warnings_expected = ('SNIMissingWarning',945 'InsecurePlatformWarning',946 'SubjectAltNameWarning', )983 warnings_expected = (984 "SNIMissingWarning",985 "InsecurePlatformWarning",986 "SubjectAltNameWarning",987 )988989 with pytest.warns(None) as warning_records:949 warnings.simplefilter('always')950 requests.get("https://localhost:{}/".format(port), verify=ca_bundle)990 warnings.simplefilter("always")991 requests.get(f"https://localhost:{port}/", verify=ca_bundle)992952 warning_records = [item for item in warning_records953 if item.category.__name__ != 'ResourceWarning']993 warning_records = [994 item995 for item in warning_records996 if item.category.__name__ != "ResourceWarning"997 ]998955 warnings_category = tuple(956 item.category.__name__ for item in warning_records)999 warnings_category = tuple(item.category.__name__ for item in warning_records)1000 assert warnings_category == warnings_expected10011002 def test_certificate_failure(self, httpbin_secure):1003 """
1 unmodified line
1005 """1006 with pytest.raises(RequestsSSLError):1007 # Our local httpbin does not have a trusted CA, so this call will1008 # fail if we use our default trust bundle.966 requests.get(httpbin_secure('status', '200'))1009 requests.get(httpbin_secure("status", "200"))10101011 def test_urlencoded_get_query_multivalued_param(self, httpbin):1012970 r = requests.get(httpbin('get'), params={'test': ['foo', 'baz']})1013 r = requests.get(httpbin("get"), params={"test": ["foo", "baz"]})1014 assert r.status_code == 200972 assert r.url == httpbin('get?test=foo&test=baz')1015 assert r.url == httpbin("get?test=foo&test=baz")10161017 def test_form_encoded_post_query_multivalued_element(self, httpbin):975 r = requests.Request(method='POST', url=httpbin('post'),976 data=dict(test=['foo', 'baz']))1018 r = requests.Request(1019 method="POST", url=httpbin("post"), data=dict(test=["foo", "baz"])1020 )1021 prep = r.prepare()978 assert prep.body == 'test=foo&test=baz'1022 assert prep.body == "test=foo&test=baz"10231024 def test_different_encodings_dont_break_post(self, httpbin):981 r = requests.post(httpbin('post'),982 data={'stuff': json.dumps({'a': 123})},983 params={'blah': 'asdf1234'},984 files={'file': ('test_requests.py', open(__file__, 'rb'))})1025 r = requests.post(1026 httpbin("post"),1027 data={"stuff": json.dumps({"a": 123})},1028 params={"blah": "asdf1234"},1029 files={"file": ("test_requests.py", open(__file__, "rb"))},1030 )1031 assert r.status_code == 20010321033 @pytest.mark.parametrize(988 'data', (989 {'stuff': 'ëlïxr'},990 {'stuff': 'ëlïxr'.encode('utf-8')},991 {'stuff': 'elixr'},992 {'stuff': 'elixr'.encode('utf-8')},993 ))1034 "data",1035 (1036 {"stuff": "ëlïxr"},1037 {"stuff": "ëlïxr".encode()},1038 {"stuff": "elixr"},1039 {"stuff": b"elixr"},1040 ),1041 )1042 def test_unicode_multipart_post(self, httpbin, data):995 r = requests.post(httpbin('post'),1043 r = requests.post(1044 httpbin("post"),1045 data=data,997 files={'file': ('test_requests.py', open(__file__, 'rb'))})1046 files={"file": ("test_requests.py", open(__file__, "rb"))},1047 )1048 assert r.status_code == 20010491050 def test_unicode_multipart_post_fieldnames(self, httpbin):1001 filename = os.path.splitext(__file__)[0] + '.py'1051 filename = os.path.splitext(__file__)[0] + ".py"1052 r = requests.Request(1003 method='POST', url=httpbin('post'),1004 data={'stuff'.encode('utf-8'): 'elixr'},1005 files={'file': ('test_requests.py', open(filename, 'rb'))})1053 method="POST",1054 url=httpbin("post"),1055 data={b"stuff": "elixr"},1056 files={"file": ("test_requests.py", open(filename, "rb"))},1057 )1058 prep = r.prepare()1059 assert b'name="stuff"' in prep.body1008 assert b'name="b\'stuff\'"' not in prep.body1060 assert b"name=\"b'stuff'\"" not in prep.body10611062 def test_unicode_method_name(self, httpbin):1011 files = {'file': open(__file__, 'rb')}1012 r = requests.request(1013 method='POST', url=httpbin('post'), files=files)1063 files = {"file": open(__file__, "rb")}1064 r = requests.request(method="POST", url=httpbin("post"), files=files)1065 assert r.status_code == 20010661067 def test_unicode_method_name_with_request_object(self, httpbin):1017 files = {'file': open(__file__, 'rb')}1068 files = {"file": open(__file__, "rb")}1069 s = requests.Session()1019 req = requests.Request('POST', httpbin('post'), files=files)1070 req = requests.Request("POST", httpbin("post"), files=files)1071 prep = s.prepare_request(req)1072 assert isinstance(prep.method, builtin_str)1022 assert prep.method == 'POST'1073 assert prep.method == "POST"10741075 resp = s.send(prep)1076 assert resp.status_code == 20010771078 def test_non_prepared_request_error(self):1079 s = requests.Session()1029 req = requests.Request('POST', '/')1080 req = requests.Request("POST", "/")10811082 with pytest.raises(ValueError) as e:1083 s.send(req)1033 assert str(e.value) == 'You can only send PreparedRequests.'1084 assert str(e.value) == "You can only send PreparedRequests."10851086 def test_custom_content_type(self, httpbin):1087 r = requests.post(1037 httpbin('post'),1038 data={'stuff': json.dumps({'a': 123})},1088 httpbin("post"),1089 data={"stuff": json.dumps({"a": 123})},1090 files={1040 'file1': ('test_requests.py', open(__file__, 'rb')),1041 'file2': ('test_requests', open(__file__, 'rb'),1042 'text/py-content-type')})1091 "file1": ("test_requests.py", open(__file__, "rb")),1092 "file2": (1093 "test_requests",1094 open(__file__, "rb"),1095 "text/py-content-type",1096 ),1097 },1098 )1099 assert r.status_code == 2001100 assert b"text/py-content-type" in r.request.body11011102 def test_hook_receives_request_arguments(self, httpbin):
1 unmodified line
1104 assert resp is not None1105 assert kwargs != {}11061107 s = requests.Session()1052 r = requests.Request('GET', httpbin(), hooks={'response': hook})1108 r = requests.Request("GET", httpbin(), hooks={"response": hook})1109 prep = s.prepare_request(r)1110 s.send(prep)11111112 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):1057 hook = lambda x, *args, **kwargs: x1113 def hook(*args, **kwargs):1114 pass11151116 s = requests.Session()1059 s.hooks['response'].append(hook)1060 r = requests.Request('GET', httpbin())1117 s.hooks["response"].append(hook)1118 r = requests.Request("GET", httpbin())1119 prep = s.prepare_request(r)1062 assert prep.hooks['response'] != []1063 assert prep.hooks['response'] == [hook]1120 assert prep.hooks["response"] != []1121 assert prep.hooks["response"] == [hook]11221123 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):1066 hook1 = lambda x, *args, **kwargs: x1067 hook2 = lambda x, *args, **kwargs: x1124 def hook1(*args, **kwargs):1125 pass11261127 def hook2(*args, **kwargs):1128 pass11291130 assert hook1 is not hook21131 s = requests.Session()1070 s.hooks['response'].append(hook2)1071 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})1132 s.hooks["response"].append(hook2)1133 r = requests.Request("GET", httpbin(), hooks={"response": [hook1]})1134 prep = s.prepare_request(r)1073 assert prep.hooks['response'] == [hook1]1135 assert prep.hooks["response"] == [hook1]11361137 def test_prepared_request_hook(self, httpbin):1138 def hook(resp, **kwargs):1139 resp.hook_working = True1140 return resp11411080 req = requests.Request('GET', httpbin(), hooks={'response': hook})1142 req = requests.Request("GET", httpbin(), hooks={"response": hook})1143 prep = req.prepare()11441145 s = requests.Session()1146 s.proxies = getproxies()1147 resp = s.send(prep)11481087 assert hasattr(resp, 'hook_working')1149 assert hasattr(resp, "hook_working")11501151 def test_prepared_from_session(self, httpbin):1152 class DummyAuth(requests.auth.AuthBase):1153 def __call__(self, r):1092 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'1154 r.headers["Dummy-Auth-Test"] = "dummy-auth-test-ok"1155 return r11561095 req = requests.Request('GET', httpbin('headers'))1157 req = requests.Request("GET", httpbin("headers"))1158 assert not req.auth11591160 s = requests.Session()1161 s.auth = DummyAuth()11621163 prep = s.prepare_request(req)1164 resp = s.send(prep)11651104 assert resp.json()['headers'][1105 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'1166 assert resp.json()["headers"]["Dummy-Auth-Test"] == "dummy-auth-test-ok"11671168 def test_prepare_request_with_bytestring_url(self):1108 req = requests.Request('GET', b'https://httpbin.org/')1169 req = requests.Request("GET", b"https://httpbin.org/")1170 s = requests.Session()1171 prep = s.prepare_request(req)1172 assert prep.url == "https://httpbin.org/"11731174 def test_request_with_bytestring_host(self, httpbin):1175 s = requests.Session()1176 resp = s.request(1116 'GET',1117 httpbin('cookies/set?cookie=value'),1177 "GET",1178 httpbin("cookies/set?cookie=value"),1179 allow_redirects=False,1119 headers={'Host': b'httpbin.org'}1180 headers={"Host": b"httpbin.org"},1181 )1121 assert resp.cookies.get('cookie') == 'value'1182 assert resp.cookies.get("cookie") == "value"11831184 def test_links(self):1185 r = requests.Response()1186 r.headers = {1126 'cache-control': 'public, max-age=60, s-maxage=60',1127 'connection': 'keep-alive',1128 'content-encoding': 'gzip',1129 'content-type': 'application/json; charset=utf-8',1130 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',1131 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',1132 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',1133 'link': ('<https://api.github.com/users/kennethreitz/repos?'1134 'page=2&per_page=10>; rel="next", <https://api.github.'1135 'com/users/kennethreitz/repos?page=7&per_page=10>; '1136 ' rel="last"'),1137 'server': 'GitHub.com',1138 'status': '200 OK',1139 'vary': 'Accept',1140 'x-content-type-options': 'nosniff',1141 'x-github-media-type': 'github.beta',1142 'x-ratelimit-limit': '60',1143 'x-ratelimit-remaining': '57'1187 "cache-control": "public, max-age=60, s-maxage=60",1188 "connection": "keep-alive",1189 "content-encoding": "gzip",1190 "content-type": "application/json; charset=utf-8",1191 "date": "Sat, 26 Jan 2013 16:47:56 GMT",1192 "etag": '"6ff6a73c0e446c1f61614769e3ceb778"',1193 "last-modified": "Sat, 26 Jan 2013 16:22:39 GMT",1194 "link": (1195 "<https://api.github.com/users/kennethreitz/repos?"1196 'page=2&per_page=10>; rel="next", <https://api.github.'1197 "com/users/kennethreitz/repos?page=7&per_page=10>; "1198 ' rel="last"'1199 ),1200 "server": "GitHub.com",1201 "status": "200 OK",1202 "vary": "Accept",1203 "x-content-type-options": "nosniff",1204 "x-github-media-type": "github.beta",1205 "x-ratelimit-limit": "60",1206 "x-ratelimit-remaining": "57",1207 }1145 assert r.links['next']['rel'] == 'next'1208 assert r.links["next"]["rel"] == "next"12091210 def test_cookie_parameters(self):1148 key = 'some_cookie'1149 value = 'some_value'1211 key = "some_cookie"1212 value = "some_value"1213 secure = True1151 domain = 'test.com'1152 rest = {'HttpOnly': True}1214 domain = "test.com"1215 rest = {"HttpOnly": True}12161217 jar = requests.cookies.RequestsCookieJar()1218 jar.set(key, value, secure=secure, domain=domain, rest=rest)12191220 assert len(jar) == 11158 assert 'some_cookie' in jar1221 assert "some_cookie" in jar12221223 cookie = list(jar)[0]1224 assert cookie.secure == secure1225 assert cookie.domain == domain1163 assert cookie._rest['HttpOnly'] == rest['HttpOnly']1226 assert cookie._rest["HttpOnly"] == rest["HttpOnly"]12271228 def test_cookie_as_dict_keeps_len(self):1166 key = 'some_cookie'1167 value = 'some_value'1229 key = "some_cookie"1230 value = "some_value"12311169 key1 = 'some_cookie1'1170 value1 = 'some_value1'1232 key1 = "some_cookie1"1233 value1 = "some_value1"12341235 jar = requests.cookies.RequestsCookieJar()1236 jar.set(key, value)1237 jar.set(key1, value1)
7 unmodified lines
1245 assert len(d2) == 21246 assert len(d3) == 212471248 def test_cookie_as_dict_keeps_items(self):1186 key = 'some_cookie'1187 value = 'some_value'1249 key = "some_cookie"1250 value = "some_value"12511189 key1 = 'some_cookie1'1190 value1 = 'some_value1'1252 key1 = "some_cookie1"1253 value1 = "some_value1"12541255 jar = requests.cookies.RequestsCookieJar()1256 jar.set(key, value)1257 jar.set(key1, value1)
1 unmodified line
1259 d1 = dict(jar)1260 d2 = dict(jar.iteritems())1261 d3 = dict(jar.items())12621200 assert d1['some_cookie'] == 'some_value'1201 assert d2['some_cookie'] == 'some_value'1202 assert d3['some_cookie1'] == 'some_value1'1263 assert d1["some_cookie"] == "some_value"1264 assert d2["some_cookie"] == "some_value"1265 assert d3["some_cookie1"] == "some_value1"12661267 def test_cookie_as_dict_keys(self):1205 key = 'some_cookie'1206 value = 'some_value'1268 key = "some_cookie"1269 value = "some_value"12701208 key1 = 'some_cookie1'1209 value1 = 'some_value1'1271 key1 = "some_cookie1"1272 value1 = "some_value1"12731274 jar = requests.cookies.RequestsCookieJar()1275 jar.set(key, value)1276 jar.set(key1, value1)
3 unmodified lines
1280 # make sure one can use keys multiple times1281 assert list(keys) == list(keys)12821283 def test_cookie_as_dict_values(self):1221 key = 'some_cookie'1222 value = 'some_value'1284 key = "some_cookie"1285 value = "some_value"12861224 key1 = 'some_cookie1'1225 value1 = 'some_value1'1287 key1 = "some_cookie1"1288 value1 = "some_value1"12891290 jar = requests.cookies.RequestsCookieJar()1291 jar.set(key, value)1292 jar.set(key1, value1)
3 unmodified lines
1296 # make sure one can use values multiple times1297 assert list(values) == list(values)12981299 def test_cookie_as_dict_items(self):1237 key = 'some_cookie'1238 value = 'some_value'1300 key = "some_cookie"1301 value = "some_value"13021240 key1 = 'some_cookie1'1241 value1 = 'some_value1'1303 key1 = "some_cookie1"1304 value1 = "some_value1"13051306 jar = requests.cookies.RequestsCookieJar()1307 jar.set(key, value)1308 jar.set(key1, value1)
3 unmodified lines
1312 # make sure one can use items multiple times1313 assert list(items) == list(items)13141315 def test_cookie_duplicate_names_different_domains(self):1253 key = 'some_cookie'1254 value = 'some_value'1255 domain1 = 'test1.com'1256 domain2 = 'test2.com'1316 key = "some_cookie"1317 value = "some_value"1318 domain1 = "test1.com"1319 domain2 = "test2.com"13201321 jar = requests.cookies.RequestsCookieJar()1322 jar.set(key, value, domain=domain1)1323 jar.set(key, value, domain=domain2)
9 unmodified lines
1333 cookie = jar.get(key, domain=domain1)1334 assert cookie == value13351336 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1274 key = 'some_cookie'1275 value = 'some_value'1276 path = 'some_path'1337 key = "some_cookie"1338 value = "some_value"1339 path = "some_path"13401341 jar = requests.cookies.RequestsCookieJar()1342 jar.set(key, value, path=path)1343 jar.set(key, value)
8 unmodified lines
1352 jar.set_policy(MyCookiePolicy())1353 assert isinstance(jar.copy().get_policy(), MyCookiePolicy)13541355 def test_time_elapsed_blank(self, httpbin):1293 r = requests.get(httpbin('get'))1356 r = requests.get(httpbin("get"))1357 td = r.elapsed1295 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)1358 total_seconds = (1359 td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**61360 ) / 10**61361 assert total_seconds > 0.013621363 def test_empty_response_has_content_none(self):1364 r = requests.Response()1365 assert r.content is None13661367 def test_response_is_iterable(self):1368 r = requests.Response()1304 io = StringIO.StringIO('abc')1369 io = StringIO.StringIO("abc")1370 read_ = io.read13711372 def read_mock(amt, decode_content=None):1373 return read_(amt)13741309 setattr(io, 'read', read_mock)1375 setattr(io, "read", read_mock)1376 r.raw = io1377 assert next(iter(r))1378 io.close()1379
2 unmodified lines
1382 return unicode.1383 """1384 r = requests.Response()1385 r._content_consumed = True1320 r._content = b'the content'1321 r.encoding = 'ascii'1386 r._content = b"the content"1387 r.encoding = "ascii"13881389 chunks = r.iter_content(decode_unicode=True)1390 assert all(isinstance(chunk, str) for chunk in chunks)13911392 # also for streaming1393 r = requests.Response()1328 r.raw = io.BytesIO(b'the content')1329 r.encoding = 'ascii'1394 r.raw = io.BytesIO(b"the content")1395 r.encoding = "ascii"1396 chunks = r.iter_content(decode_unicode=True)1397 assert all(isinstance(chunk, str) for chunk in chunks)13981399 def test_response_reason_unicode(self):1400 # check for unicode HTTP status1401 r = requests.Response()1336 r.url = 'unicode URL'1337 r.reason = 'Komponenttia ei löydy'.encode('utf-8')1402 r.url = "unicode URL"1403 r.reason = "Komponenttia ei löydy".encode()1404 r.status_code = 4041405 r.encoding = None1406 assert not r.ok # old behaviour - crashes here14071408 def test_response_reason_unicode_fallback(self):1409 # check raise_status falls back to ISO-8859-11410 r = requests.Response()1345 r.url = 'some url'1346 reason = 'Komponenttia ei löydy'1347 r.reason = reason.encode('latin-1')1411 r.url = "some url"1412 reason = "Komponenttia ei löydy"1413 r.reason = reason.encode("latin-1")1414 r.status_code = 5001415 r.encoding = None1416 with pytest.raises(requests.exceptions.HTTPError) as e:1417 r.raise_for_status()
3 unmodified lines
1421 """Ensure that chunk_size is passed as None or an integer, otherwise1422 raise a TypeError.1423 """1424 r = requests.Response()1359 r.raw = io.BytesIO(b'the content')1425 r.raw = io.BytesIO(b"the content")1426 chunks = r.iter_content(1)1427 assert all(len(chunk) == 1 for chunk in chunks)14281429 r = requests.Response()1364 r.raw = io.BytesIO(b'the content')1430 r.raw = io.BytesIO(b"the content")1431 chunks = r.iter_content(None)1366 assert list(chunks) == [b'the content']1432 assert list(chunks) == [b"the content"]14331434 r = requests.Response()1369 r.raw = io.BytesIO(b'the content')1435 r.raw = io.BytesIO(b"the content")1436 with pytest.raises(TypeError):1437 chunks = r.iter_content("1024")14381439 @pytest.mark.parametrize(1374 'exception, args, expected', (1440 "exception, args, expected",1441 (1442 (urllib3.exceptions.ProtocolError, tuple(), ChunkedEncodingError),1443 (urllib3.exceptions.DecodeError, tuple(), ContentDecodingError),1377 (urllib3.exceptions.ReadTimeoutError, (None, '', ''), ConnectionError),1444 (urllib3.exceptions.ReadTimeoutError, (None, "", ""), ConnectionError),1445 (urllib3.exceptions.SSLError, tuple(), RequestsSSLError),1379 )1446 ),1447 )1448 def test_iter_content_wraps_exceptions(1449 self, httpbin, mocker, exception, args, expected1450 ):
6 unmodified lines
1457 with pytest.raises(expected):1458 next(r.iter_content(1024))14591460 def test_request_and_response_are_pickleable(self, httpbin):1394 r = requests.get(httpbin('get'))1461 r = requests.get(httpbin("get"))14621463 # verify we can pickle the original request1464 assert pickle.loads(pickle.dumps(r.request))1465
3 unmodified lines
1469 assert r.request.url == pr.request.url1470 assert r.request.headers == pr.request.headers14711472 def test_prepared_request_is_pickleable(self, httpbin):1406 p = requests.Request('GET', httpbin('get')).prepare()1473 p = requests.Request("GET", httpbin("get")).prepare()14741475 # Verify PreparedRequest can be pickled and unpickled1476 r = pickle.loads(pickle.dumps(p))1477 assert r.url == p.url
5 unmodified lines
1483 resp = s.send(r)1484 assert resp.status_code == 20014851486 def test_prepared_request_with_file_is_pickleable(self, httpbin):1420 files = {'file': open(__file__, 'rb')}1421 r = requests.Request('POST', httpbin('post'), files=files)1487 files = {"file": open(__file__, "rb")}1488 r = requests.Request("POST", httpbin("post"), files=files)1489 p = r.prepare()14901491 # Verify PreparedRequest can be pickled and unpickled1492 r = pickle.loads(pickle.dumps(p))
6 unmodified lines
1499 resp = s.send(r)1500 assert resp.status_code == 20015011502 def test_prepared_request_with_hook_is_pickleable(self, httpbin):1436 r = requests.Request('GET', httpbin('get'), hooks=default_hooks())1503 r = requests.Request("GET", httpbin("get"), hooks=default_hooks())1504 p = r.prepare()15051506 # Verify PreparedRequest can be pickled1507 r = pickle.loads(pickle.dumps(p))
17 unmodified lines
1525 assert not error.response1526 response = requests.Response()1527 error = requests.exceptions.HTTPError(response=response)1528 assert error.response == response1462 error = requests.exceptions.HTTPError('message', response=response)1463 assert str(error) == 'message'1529 error = requests.exceptions.HTTPError("message", response=response)1530 assert str(error) == "message"1531 assert error.response == response15321533 def test_session_pickling(self, httpbin):1467 r = requests.Request('GET', httpbin('get'))1534 r = requests.Request("GET", httpbin("get"))1535 s = requests.Session()15361537 s = pickle.loads(pickle.dumps(s))1538 s.proxies = getproxies()
3 unmodified lines
15421543 def test_fixes_1329(self, httpbin):1544 """Ensure that header updates are done case-insensitively."""1545 s = requests.Session()1479 s.headers.update({'ACCEPT': 'BOGUS'})1480 s.headers.update({'accept': 'application/json'})1481 r = s.get(httpbin('get'))1546 s.headers.update({"ACCEPT": "BOGUS"})1547 s.headers.update({"accept": "application/json"})1548 r = s.get(httpbin("get"))1549 headers = r.request.headers1483 assert headers['accept'] == 'application/json'1484 assert headers['Accept'] == 'application/json'1485 assert headers['ACCEPT'] == 'application/json'1550 assert headers["accept"] == "application/json"1551 assert headers["Accept"] == "application/json"1552 assert headers["ACCEPT"] == "application/json"15531554 def test_uppercase_scheme_redirect(self, httpbin):1488 parts = urlparse(httpbin('html'))1555 parts = urlparse(httpbin("html"))1556 url = "HTTP://" + parts.netloc + parts.path1490 r = requests.get(httpbin('redirect-to'), params={'url': url})1557 r = requests.get(httpbin("redirect-to"), params={"url": url})1558 assert r.status_code == 2001559 assert r.url.lower() == url.lower()15601561 def test_transport_adapter_ordering(self):1562 s = requests.Session()1496 order = ['https://', 'http://']1563 order = ["https://", "http://"]1564 assert order == list(s.adapters)1498 s.mount('http://git', HTTPAdapter())1499 s.mount('http://github', HTTPAdapter())1500 s.mount('http://github.com', HTTPAdapter())1501 s.mount('http://github.com/about/', HTTPAdapter())1565 s.mount("http://git", HTTPAdapter())1566 s.mount("http://github", HTTPAdapter())1567 s.mount("http://github.com", HTTPAdapter())1568 s.mount("http://github.com/about/", HTTPAdapter())1569 order = [1503 'http://github.com/about/',1504 'http://github.com',1505 'http://github',1506 'http://git',1507 'https://',1508 'http://',1570 "http://github.com/about/",1571 "http://github.com",1572 "http://github",1573 "http://git",1574 "https://",1575 "http://",1576 ]1577 assert order == list(s.adapters)1511 s.mount('http://gittip', HTTPAdapter())1512 s.mount('http://gittip.com', HTTPAdapter())1513 s.mount('http://gittip.com/about/', HTTPAdapter())1578 s.mount("http://gittip", HTTPAdapter())1579 s.mount("http://gittip.com", HTTPAdapter())1580 s.mount("http://gittip.com/about/", HTTPAdapter())1581 order = [1515 'http://github.com/about/',1516 'http://gittip.com/about/',1517 'http://github.com',1518 'http://gittip.com',1519 'http://github',1520 'http://gittip',1521 'http://git',1522 'https://',1523 'http://',1582 "http://github.com/about/",1583 "http://gittip.com/about/",1584 "http://github.com",1585 "http://gittip.com",1586 "http://github",1587 "http://gittip",1588 "http://git",1589 "https://",1590 "http://",1591 ]1592 assert order == list(s.adapters)1593 s2 = requests.Session()1527 s2.adapters = {'http://': HTTPAdapter()}1528 s2.mount('https://', HTTPAdapter())1529 assert 'http://' in s2.adapters1530 assert 'https://' in s2.adapters1594 s2.adapters = {"http://": HTTPAdapter()}1595 s2.mount("https://", HTTPAdapter())1596 assert "http://" in s2.adapters1597 assert "https://" in s2.adapters15981599 def test_session_get_adapter_prefix_matching(self):1533 prefix = 'https://example.com'1534 more_specific_prefix = prefix + '/some/path'1600 prefix = "https://example.com"1601 more_specific_prefix = prefix + "/some/path"16021536 url_matching_only_prefix = prefix + '/another/path'1537 url_matching_more_specific_prefix = more_specific_prefix + '/longer/path'1538 url_not_matching_prefix = 'https://another.example.com/'1603 url_matching_only_prefix = prefix + "/another/path"1604 url_matching_more_specific_prefix = more_specific_prefix + "/longer/path"1605 url_not_matching_prefix = "https://another.example.com/"16061607 s = requests.Session()1608 prefix_adapter = HTTPAdapter()1609 more_specific_prefix_adapter = HTTPAdapter()1610 s.mount(prefix, prefix_adapter)1611 s.mount(more_specific_prefix, more_specific_prefix_adapter)16121613 assert s.get_adapter(url_matching_only_prefix) is prefix_adapter1547 assert s.get_adapter(url_matching_more_specific_prefix) is more_specific_prefix_adapter1548 assert s.get_adapter(url_not_matching_prefix) not in (prefix_adapter, more_specific_prefix_adapter)1614 assert (1615 s.get_adapter(url_matching_more_specific_prefix)1616 is more_specific_prefix_adapter1617 )1618 assert s.get_adapter(url_not_matching_prefix) not in (1619 prefix_adapter,1620 more_specific_prefix_adapter,1621 )16221623 def test_session_get_adapter_prefix_matching_mixed_case(self):1551 mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1552 url_matching_prefix = mixed_case_prefix + '/full_url'1624 mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"1625 url_matching_prefix = mixed_case_prefix + "/full_url"16261627 s = requests.Session()1628 my_adapter = HTTPAdapter()1629 s.mount(mixed_case_prefix, my_adapter)16301631 assert s.get_adapter(url_matching_prefix) is my_adapter16321633 def test_session_get_adapter_prefix_matching_is_case_insensitive(self):1561 mixed_case_prefix = 'hTtPs://eXamPle.CoM/MixEd_CAse_PREfix'1562 url_matching_prefix_with_different_case = 'HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url'1634 mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"1635 url_matching_prefix_with_different_case = (1636 "HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url"1637 )16381639 s = requests.Session()1640 my_adapter = HTTPAdapter()1641 s.mount(mixed_case_prefix, my_adapter)
2 unmodified lines
16441645 def test_header_remove_is_case_insensitive(self, httpbin):1646 # From issue #13211647 s = requests.Session()1573 s.headers['foo'] = 'bar'1574 r = s.get(httpbin('get'), headers={'FOO': None})1575 assert 'foo' not in r.request.headers1648 s.headers["foo"] = "bar"1649 r = s.get(httpbin("get"), headers={"FOO": None})1650 assert "foo" not in r.request.headers16511652 def test_params_are_merged_case_sensitive(self, httpbin):1653 s = requests.Session()1579 s.params['foo'] = 'bar'1580 r = s.get(httpbin('get'), params={'FOO': 'bar'})1581 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}1654 s.params["foo"] = "bar"1655 r = s.get(httpbin("get"), params={"FOO": "bar"})1656 assert r.json()["args"] == {"foo": "bar", "FOO": "bar"}16571658 def test_long_authinfo_in_url(self):1584 url = 'http://{}:{}@{}:9000/path?query#frag'.format(1585 'E8A3BE87-9E3F-4620-8858-95478E385B5B',1586 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1587 'exactly-------------sixty-----------three------------characters',1659 url = "http://{}:{}@{}:9000/path?query#frag".format(1660 "E8A3BE87-9E3F-4620-8858-95478E385B5B",1661 "EA770032-DA4D-4D84-8CE9-29C6D910BF1E",1662 "exactly-------------sixty-----------three------------characters",1663 )1589 r = requests.Request('GET', url).prepare()1664 r = requests.Request("GET", url).prepare()1665 assert r.url == url16661667 def test_header_keys_are_native(self, httpbin):1593 headers = {'unicode': 'blah', 'byte'.encode('ascii'): 'blah'}1594 r = requests.Request('GET', httpbin('get'), headers=headers)1668 headers = {"unicode": "blah", b"byte": "blah"}1669 r = requests.Request("GET", httpbin("get"), headers=headers)1670 p = r.prepare()16711672 # This is testing that they are builtin strings. A bit weird, but there1673 # we go.1599 assert 'unicode' in p.headers.keys()1600 assert 'byte' in p.headers.keys()1674 assert "unicode" in p.headers.keys()1675 assert "byte" in p.headers.keys()16761677 def test_header_validation(self, httpbin):1678 """Ensure prepare_headers regex isn't flagging valid header contents."""1604 headers_ok = {'foo': 'bar baz qux',1605 'bar': 'fbbq'.encode('utf8'),1606 'baz': '',1607 'qux': '1'}1608 r = requests.get(httpbin('get'), headers=headers_ok)1609 assert r.request.headers['foo'] == headers_ok['foo']1679 headers_ok = {1680 "foo": "bar baz qux",1681 "bar": b"fbbq",1682 "baz": "",1683 "qux": "1",1684 }1685 r = requests.get(httpbin("get"), headers=headers_ok)1686 assert r.request.headers["foo"] == headers_ok["foo"]16871688 def test_header_value_not_str(self, httpbin):1689 """Ensure the header value is of type string or bytes as1690 per discussion in GH issue #33861691 """1615 headers_int = {'foo': 3}1616 headers_dict = {'bar': {'foo': 'bar'}}1617 headers_list = {'baz': ['foo', 'bar']}1692 headers_int = {"foo": 3}1693 headers_dict = {"bar": {"foo": "bar"}}1694 headers_list = {"baz": ["foo", "bar"]}16951696 # Test for int1697 with pytest.raises(InvalidHeader) as excinfo:1621 r = requests.get(httpbin('get'), headers=headers_int)1622 assert 'foo' in str(excinfo.value)1698 requests.get(httpbin("get"), headers=headers_int)1699 assert "foo" in str(excinfo.value)1700 # Test for dict1701 with pytest.raises(InvalidHeader) as excinfo:1625 r = requests.get(httpbin('get'), headers=headers_dict)1626 assert 'bar' in str(excinfo.value)1702 requests.get(httpbin("get"), headers=headers_dict)1703 assert "bar" in str(excinfo.value)1704 # Test for list1705 with pytest.raises(InvalidHeader) as excinfo:1629 r = requests.get(httpbin('get'), headers=headers_list)1630 assert 'baz' in str(excinfo.value)1706 requests.get(httpbin("get"), headers=headers_list)1707 assert "baz" in str(excinfo.value)17081709 def test_header_no_return_chars(self, httpbin):1710 """Ensure that a header containing return character sequences raise an1711 exception. Otherwise, multiple headers are created from single string.1712 """1636 headers_ret = {'foo': 'bar\r\nbaz: qux'}1637 headers_lf = {'foo': 'bar\nbaz: qux'}1638 headers_cr = {'foo': 'bar\rbaz: qux'}1713 headers_ret = {"foo": "bar\r\nbaz: qux"}1714 headers_lf = {"foo": "bar\nbaz: qux"}1715 headers_cr = {"foo": "bar\rbaz: qux"}17161717 # Test for newline1718 with pytest.raises(InvalidHeader):1642 r = requests.get(httpbin('get'), headers=headers_ret)1719 requests.get(httpbin("get"), headers=headers_ret)1720 # Test for line feed1721 with pytest.raises(InvalidHeader):1645 r = requests.get(httpbin('get'), headers=headers_lf)1722 requests.get(httpbin("get"), headers=headers_lf)1723 # Test for carriage return1724 with pytest.raises(InvalidHeader):1648 r = requests.get(httpbin('get'), headers=headers_cr)1725 requests.get(httpbin("get"), headers=headers_cr)17261727 def test_header_no_leading_space(self, httpbin):1728 """Ensure headers containing leading whitespace raise1729 InvalidHeader Error before sending.1730 """1654 headers_space = {'foo': ' bar'}1655 headers_tab = {'foo': ' bar'}1731 headers_space = {"foo": " bar"}1732 headers_tab = {"foo": " bar"}17331734 # Test for whitespace1735 with pytest.raises(InvalidHeader):1659 r = requests.get(httpbin('get'), headers=headers_space)1736 requests.get(httpbin("get"), headers=headers_space)17371738 # Test for tab1739 with pytest.raises(InvalidHeader):1662 r = requests.get(httpbin('get'), headers=headers_tab)1740 requests.get(httpbin("get"), headers=headers_tab)17411664 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1742 @pytest.mark.parametrize("files", ("foo", b"foo", bytearray(b"foo")))1743 def test_can_send_objects_with_files(self, httpbin, files):1666 data = {'a': 'this is a string'}1667 files = {'b': files}1668 r = requests.Request('POST', httpbin('post'), data=data, files=files)1744 data = {"a": "this is a string"}1745 files = {"b": files}1746 r = requests.Request("POST", httpbin("post"), data=data, files=files)1747 p = r.prepare()1670 assert 'multipart/form-data' in p.headers['Content-Type']1748 assert "multipart/form-data" in p.headers["Content-Type"]17491750 def test_can_send_file_object_with_non_string_filename(self, httpbin):1751 f = io.BytesIO()1752 f.name = 21675 r = requests.Request('POST', httpbin('post'), files={'f': f})1753 r = requests.Request("POST", httpbin("post"), files={"f": f})1754 p = r.prepare()17551678 assert 'multipart/form-data' in p.headers['Content-Type']1756 assert "multipart/form-data" in p.headers["Content-Type"]17571758 def test_autoset_header_values_are_native(self, httpbin):1681 data = 'this is a string'1682 length = '16'1683 req = requests.Request('POST', httpbin('post'), data=data)1759 data = "this is a string"1760 length = "16"1761 req = requests.Request("POST", httpbin("post"), data=data)1762 p = req.prepare()17631686 assert p.headers['Content-Length'] == length1764 assert p.headers["Content-Length"] == length17651766 def test_nonhttp_schemes_dont_check_URLs(self):1767 test_urls = (1690 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1691 'file:///etc/passwd',1692 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1768 "data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",1769 "file:///etc/passwd",1770 "magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431",1771 )1772 for test_url in test_urls:1695 req = requests.Request('GET', test_url)1773 req = requests.Request("GET", test_url)1774 preq = req.prepare()1775 assert test_url == preq.url17761699 def test_auth_is_stripped_on_http_downgrade(self, httpbin, httpbin_secure, httpbin_ca_bundle):1777 def test_auth_is_stripped_on_http_downgrade(1778 self, httpbin, httpbin_secure, httpbin_ca_bundle1779 ):1780 r = requests.get(1701 httpbin_secure('redirect-to'),1702 params={'url': httpbin('get')},1703 auth=('user', 'pass'),1704 verify=httpbin_ca_bundle1781 httpbin_secure("redirect-to"),1782 params={"url": httpbin("get")},1783 auth=("user", "pass"),1784 verify=httpbin_ca_bundle,1785 )1706 assert r.history[0].request.headers['Authorization']1707 assert 'Authorization' not in r.request.headers1786 assert r.history[0].request.headers["Authorization"]1787 assert "Authorization" not in r.request.headers17881789 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1710 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1711 h1 = r.history[0].request.headers['Authorization']1712 h2 = r.request.headers['Authorization']1790 r = requests.get(httpbin("redirect/1"), auth=("user", "pass"))1791 h1 = r.history[0].request.headers["Authorization"]1792 h2 = r.request.headers["Authorization"]17931794 assert h1 == h217951796 def test_should_strip_auth_host_change(self):1797 s = requests.Session()1718 assert s.should_strip_auth('http://example.com/foo', 'http://another.example.com/')1798 assert s.should_strip_auth(1799 "http://example.com/foo", "http://another.example.com/"1800 )18011802 def test_should_strip_auth_http_downgrade(self):1803 s = requests.Session()1722 assert s.should_strip_auth('https://example.com/foo', 'http://example.com/bar')1804 assert s.should_strip_auth("https://example.com/foo", "http://example.com/bar")18051806 def test_should_strip_auth_https_upgrade(self):1807 s = requests.Session()1726 assert not s.should_strip_auth('http://example.com/foo', 'https://example.com/bar')1727 assert not s.should_strip_auth('http://example.com:80/foo', 'https://example.com/bar')1728 assert not s.should_strip_auth('http://example.com/foo', 'https://example.com:443/bar')1808 assert not s.should_strip_auth(1809 "http://example.com/foo", "https://example.com/bar"1810 )1811 assert not s.should_strip_auth(1812 "http://example.com:80/foo", "https://example.com/bar"1813 )1814 assert not s.should_strip_auth(1815 "http://example.com/foo", "https://example.com:443/bar"1816 )1817 # Non-standard ports should trigger stripping1730 assert s.should_strip_auth('http://example.com:8080/foo', 'https://example.com/bar')1731 assert s.should_strip_auth('http://example.com/foo', 'https://example.com:8443/bar')1818 assert s.should_strip_auth(1819 "http://example.com:8080/foo", "https://example.com/bar"1820 )1821 assert s.should_strip_auth(1822 "http://example.com/foo", "https://example.com:8443/bar"1823 )18241825 def test_should_strip_auth_port_change(self):1826 s = requests.Session()1735 assert s.should_strip_auth('http://example.com:1234/foo', 'https://example.com:4321/bar')1827 assert s.should_strip_auth(1828 "http://example.com:1234/foo", "https://example.com:4321/bar"1829 )18301831 @pytest.mark.parametrize(1738 'old_uri, new_uri', (1739 ('https://example.com:443/foo', 'https://example.com/bar'),1740 ('http://example.com:80/foo', 'http://example.com/bar'),1741 ('https://example.com/foo', 'https://example.com:443/bar'),1742 ('http://example.com/foo', 'http://example.com:80/bar')1743 ))1832 "old_uri, new_uri",1833 (1834 ("https://example.com:443/foo", "https://example.com/bar"),1835 ("http://example.com:80/foo", "http://example.com/bar"),1836 ("https://example.com/foo", "https://example.com:443/bar"),1837 ("http://example.com/foo", "http://example.com:80/bar"),1838 ),1839 )1840 def test_should_strip_auth_default_port(self, old_uri, new_uri):1841 s = requests.Session()1842 assert not s.should_strip_auth(old_uri, new_uri)18431844 def test_manual_redirect_with_partial_body_read(self, httpbin):1845 s = requests.Session()1750 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1846 r1 = s.get(httpbin("redirect/2"), allow_redirects=False, stream=True)1847 assert r1.is_redirect1848 rg = s.resolve_redirects(r1, r1.request, stream=True)18491850 # read only the first eight bytes of the response body,
9 unmodified lines
1860 r3 = next(rg)1861 assert not r3.is_redirect18621863 def test_prepare_body_position_non_stream(self):1768 data = b'the data'1769 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1864 data = b"the data"1865 prep = requests.Request("GET", "http://example.com", data=data).prepare()1866 assert prep._body_position is None18671868 def test_rewind_body(self):1773 data = io.BytesIO(b'the data')1774 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1869 data = io.BytesIO(b"the data")1870 prep = requests.Request("GET", "http://example.com", data=data).prepare()1871 assert prep._body_position == 01776 assert prep.body.read() == b'the data'1872 assert prep.body.read() == b"the data"18731874 # the data has all been read1779 assert prep.body.read() == b''1875 assert prep.body.read() == b""18761877 # rewind it back1878 requests.utils.rewind_body(prep)1783 assert prep.body.read() == b'the data'1879 assert prep.body.read() == b"the data"18801881 def test_rewind_partially_read_body(self):1786 data = io.BytesIO(b'the data')1882 data = io.BytesIO(b"the data")1883 data.read(4) # read some data1788 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1884 prep = requests.Request("GET", "http://example.com", data=data).prepare()1885 assert prep._body_position == 41790 assert prep.body.read() == b'data'1886 assert prep.body.read() == b"data"18871888 # the data has all been read1793 assert prep.body.read() == b''1889 assert prep.body.read() == b""18901891 # rewind it back1892 requests.utils.rewind_body(prep)1797 assert prep.body.read() == b'data'1893 assert prep.body.read() == b"data"18941895 def test_rewind_body_no_seek(self):1896 class BadFileObj:1897 def __init__(self, data):
4 unmodified lines
19021903 def __iter__(self):1904 return19051810 data = BadFileObj('the data')1811 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1906 data = BadFileObj("the data")1907 prep = requests.Request("GET", "http://example.com", data=data).prepare()1908 assert prep._body_position == 019091910 with pytest.raises(UnrewindableBodyError) as e:1911 requests.utils.rewind_body(prep)19121817 assert 'Unable to rewind request body' in str(e)1913 assert "Unable to rewind request body" in str(e)19141915 def test_rewind_body_failed_seek(self):1916 class BadFileObj:1917 def __init__(self, data):
7 unmodified lines
19251926 def __iter__(self):1927 return19281833 data = BadFileObj('the data')1834 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1929 data = BadFileObj("the data")1930 prep = requests.Request("GET", "http://example.com", data=data).prepare()1931 assert prep._body_position == 019321933 with pytest.raises(UnrewindableBodyError) as e:1934 requests.utils.rewind_body(prep)19351840 assert 'error occurred when rewinding request body' in str(e)1936 assert "error occurred when rewinding request body" in str(e)19371938 def test_rewind_body_failed_tell(self):1939 class BadFileObj:1940 def __init__(self, data):
4 unmodified lines
19451946 def __iter__(self):1947 return19481853 data = BadFileObj('the data')1854 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1949 data = BadFileObj("the data")1950 prep = requests.Request("GET", "http://example.com", data=data).prepare()1951 assert prep._body_position is not None19521953 with pytest.raises(UnrewindableBodyError) as e:1954 requests.utils.rewind_body(prep)19551860 assert 'Unable to rewind request body' in str(e)1956 assert "Unable to rewind request body" in str(e)19571958 def _patch_adapter_gzipped_redirect(self, session, url):1959 adapter = session.get_adapter(url=url)1960 org_build_response = adapter.build_response
1 unmodified line
19621963 def build_response(*args, **kwargs):1964 resp = org_build_response(*args, **kwargs)1965 if not self._patched_response:1870 resp.raw.headers['content-encoding'] = 'gzip'1966 resp.raw.headers["content-encoding"] = "gzip"1967 self._patched_response = True1968 return resp19691970 adapter.build_response = build_response19711972 def test_redirect_with_wrong_gzipped_header(self, httpbin):1973 s = requests.Session()1878 url = httpbin('redirect/1')1974 url = httpbin("redirect/1")1975 self._patch_adapter_gzipped_redirect(s, url)1976 s.get(url)19771978 @pytest.mark.parametrize(1883 'username, password, auth_str', (1884 ('test', 'test', 'Basic dGVzdDp0ZXN0'),1885 ('имя'.encode('utf-8'), 'пароль'.encode('utf-8'), 'Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA=='),1886 ))1979 "username, password, auth_str",1980 (1981 ("test", "test", "Basic dGVzdDp0ZXN0"),1982 (1983 "имя".encode(),1984 "пароль".encode(),1985 "Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA==",1986 ),1987 ),1988 )1989 def test_basic_auth_str_is_always_native(self, username, password, auth_str):1990 s = _basic_auth_str(username, password)1991 assert isinstance(s, builtin_str)1992 assert s == auth_str19931994 def test_requests_history_is_saved(self, httpbin):1893 r = requests.get(httpbin('redirect/5'))1995 r = requests.get(httpbin("redirect/5"))1996 total = r.history[-1].history1997 i = 01998 for item in r.history:1999 assert item.history == total[0:i]2000 i += 120012002 def test_json_param_post_content_type_works(self, httpbin):1901 r = requests.post(1902 httpbin('post'),1903 json={'life': 42}1904 )2003 r = requests.post(httpbin("post"), json={"life": 42})2004 assert r.status_code == 2001906 assert 'application/json' in r.request.headers['Content-Type']1907 assert {'life': 42} == r.json()['json']2005 assert "application/json" in r.request.headers["Content-Type"]2006 assert {"life": 42} == r.json()["json"]20072008 def test_json_param_post_should_not_override_data_param(self, httpbin):1910 r = requests.Request(method='POST', url=httpbin('post'),1911 data={'stuff': 'elixr'},1912 json={'music': 'flute'})2009 r = requests.Request(2010 method="POST",2011 url=httpbin("post"),2012 data={"stuff": "elixr"},2013 json={"music": "flute"},2014 )2015 prep = r.prepare()1914 assert 'stuff=elixr' == prep.body2016 assert "stuff=elixr" == prep.body20172018 def test_response_iter_lines(self, httpbin):1917 r = requests.get(httpbin('stream/4'), stream=True)2019 r = requests.get(httpbin("stream/4"), stream=True)2020 assert r.status_code == 20020212022 it = r.iter_lines()2023 next(it)2024 assert len(list(it)) == 320252026 def test_response_context_manager(self, httpbin):1925 with requests.get(httpbin('stream/4'), stream=True) as response:2027 with requests.get(httpbin("stream/4"), stream=True) as response:2028 assert isinstance(response, requests.Response)20292030 assert response.raw.closed20312032 def test_unconsumed_session_response_closes_connection(self, httpbin):2033 s = requests.session()20341933 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:2035 with contextlib.closing(s.get(httpbin("stream/4"), stream=True)) as response:2036 pass20372038 assert response._content_consumed is False2039 assert response.raw.closed20402041 @pytest.mark.xfail2042 def test_response_iter_lines_reentrant(self, httpbin):2043 """Response.iter_lines() is not reentrant safe"""1942 r = requests.get(httpbin('stream/4'), stream=True)2044 r = requests.get(httpbin("stream/4"), stream=True)2045 assert r.status_code == 20020462047 next(r.iter_lines())2048 assert len(list(r.iter_lines())) == 320492050 def test_session_close_proxy_clear(self, mocker):2051 proxies = {1950 'one': mocker.Mock(),1951 'two': mocker.Mock(),2052 "one": mocker.Mock(),2053 "two": mocker.Mock(),2054 }2055 session = requests.Session()1954 mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)2056 mocker.patch.dict(session.adapters["http://"].proxy_manager, proxies)2057 session.close()1956 proxies['one'].clear.assert_called_once_with()1957 proxies['two'].clear.assert_called_once_with()2058 proxies["one"].clear.assert_called_once_with()2059 proxies["two"].clear.assert_called_once_with()20602061 def test_proxy_auth(self):2062 adapter = HTTPAdapter()2063 headers = adapter.proxy_headers("http://user:pass@httpbin.org")1962 assert headers == {'Proxy-Authorization': 'Basic dXNlcjpwYXNz'}2064 assert headers == {"Proxy-Authorization": "Basic dXNlcjpwYXNz"}20652066 def test_proxy_auth_empty_pass(self):2067 adapter = HTTPAdapter()2068 headers = adapter.proxy_headers("http://user:@httpbin.org")1967 assert headers == {'Proxy-Authorization': 'Basic dXNlcjo='}2069 assert headers == {"Proxy-Authorization": "Basic dXNlcjo="}20702071 def test_response_json_when_content_is_None(self, httpbin):1970 r = requests.get(httpbin('/status/204'))2072 r = requests.get(httpbin("/status/204"))2073 # Make sure r.content is None2074 r.status_code = 02075 r._content = False2076 r._content_consumed = False
6 unmodified lines
2083 """Test `close` call for non-urllib3-like raw objects.2084 Should work when `release_conn` attr doesn't exist on `response.raw`.2085 """2086 resp = requests.Response()1985 resp.raw = StringIO.StringIO('test')2087 resp.raw = StringIO.StringIO("test")2088 assert not resp.raw.closed2089 resp.close()2090 assert resp.raw.closed20912092 def test_empty_stream_with_auth_does_not_set_content_length_header(self, httpbin):2093 """Ensure that a byte stream with size 0 will not set both a Content-Length2094 and Transfer-Encoding header.2095 """1994 auth = ('user', 'pass')1995 url = httpbin('post')1996 file_obj = io.BytesIO(b'')1997 r = requests.Request('POST', url, auth=auth, data=file_obj)2096 auth = ("user", "pass")2097 url = httpbin("post")2098 file_obj = io.BytesIO(b"")2099 r = requests.Request("POST", url, auth=auth, data=file_obj)2100 prepared_request = r.prepare()1999 assert 'Transfer-Encoding' in prepared_request.headers2000 assert 'Content-Length' not in prepared_request.headers2101 assert "Transfer-Encoding" in prepared_request.headers2102 assert "Content-Length" not in prepared_request.headers21032104 def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):2105 """Ensure that a byte stream with size > 0 will not set both a Content-Length2106 and Transfer-Encoding header.2107 """2006 auth = ('user', 'pass')2007 url = httpbin('post')2008 file_obj = io.BytesIO(b'test data')2009 r = requests.Request('POST', url, auth=auth, data=file_obj)2108 auth = ("user", "pass")2109 url = httpbin("post")2110 file_obj = io.BytesIO(b"test data")2111 r = requests.Request("POST", url, auth=auth, data=file_obj)2112 prepared_request = r.prepare()2011 assert 'Transfer-Encoding' not in prepared_request.headers2012 assert 'Content-Length' in prepared_request.headers2113 assert "Transfer-Encoding" not in prepared_request.headers2114 assert "Content-Length" in prepared_request.headers21152116 def test_chunked_upload_does_not_set_content_length_header(self, httpbin):2117 """Ensure that requests with a generator body stream using2118 Transfer-Encoding: chunked, not a Content-Length header.2119 """2018 data = (i for i in [b'a', b'b', b'c'])2019 url = httpbin('post')2020 r = requests.Request('POST', url, data=data)2120 data = (i for i in [b"a", b"b", b"c"])2121 url = httpbin("post")2122 r = requests.Request("POST", url, data=data)2123 prepared_request = r.prepare()2022 assert 'Transfer-Encoding' in prepared_request.headers2023 assert 'Content-Length' not in prepared_request.headers2124 assert "Transfer-Encoding" in prepared_request.headers2125 assert "Content-Length" not in prepared_request.headers21262127 def test_custom_redirect_mixin(self, httpbin):2128 """Tests a custom mixin to overwrite ``get_redirect_target``.2129
5 unmodified lines
2135 status code = HTTP 2002136 location = alternate url2137 3. the custom session catches the edge case and follows the redirect2138 """2037 url_final = httpbin('html')2038 querystring_malformed = urlencode({'location': url_final})2039 url_redirect_malformed = httpbin('response-headers?%s' % querystring_malformed)2040 querystring_redirect = urlencode({'url': url_redirect_malformed})2041 url_redirect = httpbin('redirect-to?%s' % querystring_redirect)2042 urls_test = [url_redirect,2043 url_redirect_malformed,2044 url_final,2045 ]2139 url_final = httpbin("html")2140 querystring_malformed = urlencode({"location": url_final})2141 url_redirect_malformed = httpbin("response-headers?%s" % querystring_malformed)2142 querystring_redirect = urlencode({"url": url_redirect_malformed})2143 url_redirect = httpbin("redirect-to?%s" % querystring_redirect)2144 urls_test = [2145 url_redirect,2146 url_redirect_malformed,2147 url_final,2148 ]21492150 class CustomRedirectSession(requests.Session):2151 def get_redirect_target(self, resp):2152 # default behavior2153 if resp.is_redirect:2051 return resp.headers['location']2154 return resp.headers["location"]2155 # edge case - check to see if 'location' is in headers anyways2053 location = resp.headers.get('location')2156 location = resp.headers.get("location")2157 if location and (location != resp.url):2158 return location2159 return None2160
8 unmodified lines
2169 assert r.url == urls_test[2]217021712172class TestCaseInsensitiveDict:20702173 @pytest.mark.parametrize(2072 'cid', (2073 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),2074 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),2075 CaseInsensitiveDict(FOO='foo', BAr='bar'),2076 ))2174 "cid",2175 (2176 CaseInsensitiveDict({"Foo": "foo", "BAr": "bar"}),2177 CaseInsensitiveDict([("Foo", "foo"), ("BAr", "bar")]),2178 CaseInsensitiveDict(FOO="foo", BAr="bar"),2179 ),2180 )2181 def test_init(self, cid):2182 assert len(cid) == 22079 assert 'foo' in cid2080 assert 'bar' in cid2183 assert "foo" in cid2184 assert "bar" in cid21852186 def test_docstring_example(self):2187 cid = CaseInsensitiveDict()2084 cid['Accept'] = 'application/json'2085 assert cid['aCCEPT'] == 'application/json'2086 assert list(cid) == ['Accept']2188 cid["Accept"] = "application/json"2189 assert cid["aCCEPT"] == "application/json"2190 assert list(cid) == ["Accept"]21912192 def test_len(self):2089 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})2090 cid['A'] = 'a'2193 cid = CaseInsensitiveDict({"a": "a", "b": "b"})2194 cid["A"] = "a"2195 assert len(cid) == 221962197 def test_getitem(self):2094 cid = CaseInsensitiveDict({'Spam': 'blueval'})2095 assert cid['spam'] == 'blueval'2096 assert cid['SPAM'] == 'blueval'2198 cid = CaseInsensitiveDict({"Spam": "blueval"})2199 assert cid["spam"] == "blueval"2200 assert cid["SPAM"] == "blueval"22012202 def test_fixes_649(self):2203 """__setitem__ should behave case-insensitively."""2204 cid = CaseInsensitiveDict()2101 cid['spam'] = 'oneval'2102 cid['Spam'] = 'twoval'2103 cid['sPAM'] = 'redval'2104 cid['SPAM'] = 'blueval'2105 assert cid['spam'] == 'blueval'2106 assert cid['SPAM'] == 'blueval'2107 assert list(cid.keys()) == ['SPAM']2205 cid["spam"] = "oneval"2206 cid["Spam"] = "twoval"2207 cid["sPAM"] = "redval"2208 cid["SPAM"] = "blueval"2209 assert cid["spam"] == "blueval"2210 assert cid["SPAM"] == "blueval"2211 assert list(cid.keys()) == ["SPAM"]22122213 def test_delitem(self):2214 cid = CaseInsensitiveDict()2111 cid['Spam'] = 'someval'2112 del cid['sPam']2113 assert 'spam' not in cid2215 cid["Spam"] = "someval"2216 del cid["sPam"]2217 assert "spam" not in cid2218 assert len(cid) == 022192220 def test_contains(self):2221 cid = CaseInsensitiveDict()2118 cid['Spam'] = 'someval'2119 assert 'Spam' in cid2120 assert 'spam' in cid2121 assert 'SPAM' in cid2122 assert 'sPam' in cid2123 assert 'notspam' not in cid2222 cid["Spam"] = "someval"2223 assert "Spam" in cid2224 assert "spam" in cid2225 assert "SPAM" in cid2226 assert "sPam" in cid2227 assert "notspam" not in cid22282229 def test_get(self):2230 cid = CaseInsensitiveDict()2127 cid['spam'] = 'oneval'2128 cid['SPAM'] = 'blueval'2129 assert cid.get('spam') == 'blueval'2130 assert cid.get('SPAM') == 'blueval'2131 assert cid.get('sPam') == 'blueval'2132 assert cid.get('notspam', 'default') == 'default'2231 cid["spam"] = "oneval"2232 cid["SPAM"] = "blueval"2233 assert cid.get("spam") == "blueval"2234 assert cid.get("SPAM") == "blueval"2235 assert cid.get("sPam") == "blueval"2236 assert cid.get("notspam", "default") == "default"22372238 def test_update(self):2239 cid = CaseInsensitiveDict()2136 cid['spam'] = 'blueval'2137 cid.update({'sPam': 'notblueval'})2138 assert cid['spam'] == 'notblueval'2139 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})2140 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})2240 cid["spam"] = "blueval"2241 cid.update({"sPam": "notblueval"})2242 assert cid["spam"] == "notblueval"2243 cid = CaseInsensitiveDict({"Foo": "foo", "BAr": "bar"})2244 cid.update({"fOO": "anotherfoo", "bAR": "anotherbar"})2245 assert len(cid) == 22142 assert cid['foo'] == 'anotherfoo'2143 assert cid['bar'] == 'anotherbar'2246 assert cid["foo"] == "anotherfoo"2247 assert cid["bar"] == "anotherbar"22482249 def test_update_retains_unchanged(self):2146 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})2147 cid.update({'foo': 'newfoo'})2148 assert cid['bar'] == 'bar'2250 cid = CaseInsensitiveDict({"foo": "foo", "bar": "bar"})2251 cid.update({"foo": "newfoo"})2252 assert cid["bar"] == "bar"22532254 def test_iter(self):2151 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})2152 keys = frozenset(['Spam', 'Eggs'])2255 cid = CaseInsensitiveDict({"Spam": "spam", "Eggs": "eggs"})2256 keys = frozenset(["Spam", "Eggs"])2257 assert frozenset(iter(cid)) == keys22582259 def test_equality(self):2156 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})2157 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})2260 cid = CaseInsensitiveDict({"SPAM": "blueval", "Eggs": "redval"})2261 othercid = CaseInsensitiveDict({"spam": "blueval", "eggs": "redval"})2262 assert cid == othercid2159 del othercid['spam']2263 del othercid["spam"]2264 assert cid != othercid2161 assert cid == {'spam': 'blueval', 'eggs': 'redval'}2265 assert cid == {"spam": "blueval", "eggs": "redval"}2266 assert cid != object()22672268 def test_setdefault(self):2165 cid = CaseInsensitiveDict({'Spam': 'blueval'})2166 assert cid.setdefault('spam', 'notblueval') == 'blueval'2167 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'2269 cid = CaseInsensitiveDict({"Spam": "blueval"})2270 assert cid.setdefault("spam", "notblueval") == "blueval"2271 assert cid.setdefault("notspam", "notblueval") == "notblueval"22722273 def test_lower_items(self):2170 cid = CaseInsensitiveDict({2171 'Accept': 'application/json',2172 'user-Agent': 'requests',2173 })2274 cid = CaseInsensitiveDict(2275 {2276 "Accept": "application/json",2277 "user-Agent": "requests",2278 }2279 )2280 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())2175 lowerkeyset = frozenset(['accept', 'user-agent'])2281 lowerkeyset = frozenset(["accept", "user-agent"])2282 assert keyset == lowerkeyset22832284 def test_preserve_key_case(self):2179 cid = CaseInsensitiveDict({2180 'Accept': 'application/json',2181 'user-Agent': 'requests',2182 })2183 keyset = frozenset(['Accept', 'user-Agent'])2285 cid = CaseInsensitiveDict(2286 {2287 "Accept": "application/json",2288 "user-Agent": "requests",2289 }2290 )2291 keyset = frozenset(["Accept", "user-Agent"])2292 assert frozenset(i[0] for i in cid.items()) == keyset2293 assert frozenset(cid.keys()) == keyset2294 assert frozenset(cid) == keyset22952296 def test_preserve_last_key_case(self):2189 cid = CaseInsensitiveDict({2190 'Accept': 'application/json',2191 'user-Agent': 'requests',2192 })2193 cid.update({'ACCEPT': 'application/json'})2194 cid['USER-AGENT'] = 'requests'2195 keyset = frozenset(['ACCEPT', 'USER-AGENT'])2297 cid = CaseInsensitiveDict(2298 {2299 "Accept": "application/json",2300 "user-Agent": "requests",2301 }2302 )2303 cid.update({"ACCEPT": "application/json"})2304 cid["USER-AGENT"] = "requests"2305 keyset = frozenset(["ACCEPT", "USER-AGENT"])2306 assert frozenset(i[0] for i in cid.items()) == keyset2307 assert frozenset(cid.keys()) == keyset2308 assert frozenset(cid) == keyset23092310 def test_copy(self):2201 cid = CaseInsensitiveDict({2202 'Accept': 'application/json',2203 'user-Agent': 'requests',2204 })2311 cid = CaseInsensitiveDict(2312 {2313 "Accept": "application/json",2314 "user-Agent": "requests",2315 }2316 )2317 cid_copy = cid.copy()2318 assert cid == cid_copy2207 cid['changed'] = True2319 cid["changed"] = True2320 assert cid != cid_copy232123222323class TestMorselToCookieExpires:
2 unmodified lines
2326 def test_expires_valid_str(self):2327 """Test case where we convert expires from string time."""23282329 morsel = Morsel()2218 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'2330 morsel["expires"] = "Thu, 01-Jan-1970 00:00:01 GMT"2331 cookie = morsel_to_cookie(morsel)2332 assert cookie.expires == 123332334 @pytest.mark.parametrize(2223 'value, exception', (2335 "value, exception",2336 (2337 (100, TypeError),2225 ('woops', ValueError),2226 ))2338 ("woops", ValueError),2339 ),2340 )2341 def test_expires_invalid_int(self, value, exception):2342 """Test case where an invalid type is passed for expires."""2343 morsel = Morsel()2230 morsel['expires'] = value2344 morsel["expires"] = value2345 with pytest.raises(exception):2346 morsel_to_cookie(morsel)23472348 def test_expires_none(self):2349 """Test case where expires is None."""23502351 morsel = Morsel()2238 morsel['expires'] = None2352 morsel["expires"] = None2353 cookie = morsel_to_cookie(morsel)2354 assert cookie.expires is None23552356
4 unmodified lines
2361 def test_max_age_valid_int(self):2362 """Test case where a valid max age in seconds is passed."""23632364 morsel = Morsel()2251 morsel['max-age'] = 602365 morsel["max-age"] = 602366 cookie = morsel_to_cookie(morsel)2367 assert isinstance(cookie.expires, int)23682369 def test_max_age_invalid_str(self):2370 """Test case where a invalid max age is passed."""23712372 morsel = Morsel()2259 morsel['max-age'] = 'woops'2373 morsel["max-age"] = "woops"2374 with pytest.raises(TypeError):2375 morsel_to_cookie(morsel)237623772378class TestTimeout:22652379 def test_stream_timeout(self, httpbin):2380 try:2268 requests.get(httpbin('delay/10'), timeout=2.0)2381 requests.get(httpbin("delay/10"), timeout=2.0)2382 except requests.exceptions.Timeout as e:2270 assert 'Read timed out' in e.args[0].args[0]2383 assert "Read timed out" in e.args[0].args[0]23842385 @pytest.mark.parametrize(2273 'timeout, error_text', (2274 ((3, 4, 5), '(connect, read)'),2275 ('foo', 'must be an int, float or None'),2276 ))2386 "timeout, error_text",2387 (2388 ((3, 4, 5), "(connect, read)"),2389 ("foo", "must be an int, float or None"),2390 ),2391 )2392 def test_invalid_timeout(self, httpbin, timeout, error_text):2393 with pytest.raises(ValueError) as e:2279 requests.get(httpbin('get'), timeout=timeout)2394 requests.get(httpbin("get"), timeout=timeout)2395 assert error_text in str(e)23962282 @pytest.mark.parametrize(2283 'timeout', (2284 None,2285 Urllib3Timeout(connect=None, read=None)2286 ))2397 @pytest.mark.parametrize("timeout", (None, Urllib3Timeout(connect=None, read=None)))2398 def test_none_timeout(self, httpbin, timeout):2399 """Check that you can set None as a valid timeout value.24002401 To actually test this behavior, we'd want to check that setting the
1 unmodified line
2403 timeout. However, this would make the test suite unbearably slow.2404 Instead we verify that setting the timeout to None does not prevent the2405 request from succeeding.2406 """2296 r = requests.get(httpbin('get'), timeout=timeout)2407 r = requests.get(httpbin("get"), timeout=timeout)2408 assert r.status_code == 20024092410 @pytest.mark.parametrize(2300 'timeout', (2301 (None, 0.1),2302 Urllib3Timeout(connect=None, read=0.1)2303 ))2411 "timeout", ((None, 0.1), Urllib3Timeout(connect=None, read=0.1))2412 )2413 def test_read_timeout(self, httpbin, timeout):2414 try:2306 requests.get(httpbin('delay/10'), timeout=timeout)2307 pytest.fail('The recv() request should time out.')2415 requests.get(httpbin("delay/10"), timeout=timeout)2416 pytest.fail("The recv() request should time out.")2417 except ReadTimeout:2418 pass24192420 @pytest.mark.parametrize(2312 'timeout', (2313 (0.1, None),2314 Urllib3Timeout(connect=0.1, read=None)2315 ))2421 "timeout", ((0.1, None), Urllib3Timeout(connect=0.1, read=None))2422 )2423 def test_connect_timeout(self, timeout):2424 try:2425 requests.get(TARPIT, timeout=timeout)2319 pytest.fail('The connect() request should time out.')2426 pytest.fail("The connect() request should time out.")2427 except ConnectTimeout as e:2428 assert isinstance(e, ConnectionError)2429 assert isinstance(e, Timeout)24302431 @pytest.mark.parametrize(2325 'timeout', (2326 (0.1, 0.1),2327 Urllib3Timeout(connect=0.1, read=0.1)2328 ))2432 "timeout", ((0.1, 0.1), Urllib3Timeout(connect=0.1, read=0.1))2433 )2434 def test_total_timeout_connect(self, timeout):2435 try:2436 requests.get(TARPIT, timeout=timeout)2332 pytest.fail('The connect() request should time out.')2437 pytest.fail("The connect() request should time out.")2438 except ConnectTimeout:2439 pass24402441 def test_encoded_methods(self, httpbin):2442 """See: https://github.com/psf/requests/issues/2316"""2338 r = requests.request(b'GET', httpbin('get'))2443 r = requests.request(b"GET", httpbin("get"))2444 assert r.ok244524462342SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))2447SendCall = collections.namedtuple("SendCall", ("args", "kwargs"))244824492450class RedirectSession(SessionRedirectMixin):2451 def __init__(self, order_of_redirects):
15 unmodified lines
2467 r.status_code = int(self.redirects.pop(0))2468 except IndexError:2469 r.status_code = 20024702366 r.headers = CaseInsensitiveDict({'Location': '/'})2471 r.headers = CaseInsensitiveDict({"Location": "/"})2472 r.raw = self._build_raw()2473 r.request = request2474 return r24752476 def _build_raw(self):2372 string = StringIO.StringIO('')2373 setattr(string, 'release_conn', lambda *args: args)2477 string = StringIO.StringIO("")2478 setattr(string, "release_conn", lambda *args: args)2479 return string248024812482def test_json_encodes_as_bytes():2483 # urllib3 expects bodies as bytes-like objects2484 body = {"key": "value"}2485 p = PreparedRequest()2381 p.prepare(2382 method='GET',2383 url='https://www.example.com/',2384 json=body2385 )2486 p.prepare(method="GET", url="https://www.example.com/", json=body)2487 assert isinstance(p.body, bytes)248824892490def test_requests_are_updated_each_time(httpbin):2491 session = RedirectSession([303, 307])2391 prep = requests.Request('POST', httpbin('post')).prepare()2492 prep = requests.Request("POST", httpbin("post")).prepare()2493 r0 = session.send(prep)2393 assert r0.request.method == 'POST'2494 assert r0.request.method == "POST"2495 assert session.calls[-1] == SendCall((r0.request,), {})2496 redirect_generator = session.resolve_redirects(r0, prep)2497 default_keyword_args = {2397 'stream': False,2398 'verify': True,2399 'cert': None,2400 'timeout': None,2401 'allow_redirects': False,2402 'proxies': {},2498 "stream": False,2499 "verify": True,2500 "cert": None,2501 "timeout": None,2502 "allow_redirects": False,2503 "proxies": {},2504 }2505 for response in redirect_generator:2405 assert response.request.method == 'GET'2506 assert response.request.method == "GET"2507 send_call = SendCall((response.request,), default_keyword_args)2508 assert session.calls[-1] == send_call250925102410@pytest.mark.parametrize("var,url,proxy", [2411 ('http_proxy', 'http://example.com', 'socks5://proxy.com:9876'),2412 ('https_proxy', 'https://example.com', 'socks5://proxy.com:9876'),2413 ('all_proxy', 'http://example.com', 'socks5://proxy.com:9876'),2414 ('all_proxy', 'https://example.com', 'socks5://proxy.com:9876'),2415])2511@pytest.mark.parametrize(2512 "var,url,proxy",2513 [2514 ("http_proxy", "http://example.com", "socks5://proxy.com:9876"),2515 ("https_proxy", "https://example.com", "socks5://proxy.com:9876"),2516 ("all_proxy", "http://example.com", "socks5://proxy.com:9876"),2517 ("all_proxy", "https://example.com", "socks5://proxy.com:9876"),2518 ],2519)2520def test_proxy_env_vars_override_default(var, url, proxy):2521 session = requests.Session()2522 prep = PreparedRequest()2419 prep.prepare(method='GET', url=url)2523 prep.prepare(method="GET", url=url)25242421 kwargs = {2422 var: proxy2423 }2525 kwargs = {var: proxy}2526 scheme = urlparse(url).scheme2527 with override_environ(**kwargs):2528 proxies = session.rebuild_proxies(prep, {})2529 assert scheme in proxies2530 assert proxies[scheme] == proxy253125322533@pytest.mark.parametrize(2432 'data', (2433 (('a', 'b'), ('c', 'd')),2434 (('c', 'd'), ('a', 'b')),2435 (('a', 'b'), ('c', 'd'), ('e', 'f')),2436 ))2534 "data",2535 (2536 (("a", "b"), ("c", "d")),2537 (("c", "d"), ("a", "b")),2538 (("a", "b"), ("c", "d"), ("e", "f")),2539 ),2540)2541def test_data_argument_accepts_tuples(data):2542 """Ensure that the data argument will accept tuples of strings2543 and properly encode them.2544 """2545 p = PreparedRequest()2546 p.prepare(2443 method='GET',2444 url='http://www.example.com',2445 data=data,2446 hooks=default_hooks()2547 method="GET", url="http://www.example.com", data=data, hooks=default_hooks()2548 )2549 assert p.body == urlencode(data)255025512552@pytest.mark.parametrize(2452 'kwargs', (2553 "kwargs",2554 (2555 None,2556 {2455 'method': 'GET',2456 'url': 'http://www.example.com',2457 'data': 'foo=bar',2458 'hooks': default_hooks()2557 "method": "GET",2558 "url": "http://www.example.com",2559 "data": "foo=bar",2560 "hooks": default_hooks(),2561 },2562 {2461 'method': 'GET',2462 'url': 'http://www.example.com',2463 'data': 'foo=bar',2464 'hooks': default_hooks(),2465 'cookies': {'foo': 'bar'}2563 "method": "GET",2564 "url": "http://www.example.com",2565 "data": "foo=bar",2566 "hooks": default_hooks(),2567 "cookies": {"foo": "bar"},2568 },2467 {2468 'method': 'GET',2469 'url': 'http://www.example.com/üniçø∂é'2470 },2471 ))2569 {"method": "GET", "url": "http://www.example.com/üniçø∂é"},2570 ),2571)2572def test_prepared_copy(kwargs):2573 p = PreparedRequest()2574 if kwargs:2575 p.prepare(**kwargs)2576 copy = p.copy()2477 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):2577 for attr in ("method", "url", "headers", "_cookies", "body", "hooks"):2578 assert getattr(p, attr) == getattr(copy, attr)257925802581def test_urllib3_retries(httpbin):2582 from urllib3.util import Retry25832584 s = requests.Session()2484 s.mount('http://', HTTPAdapter(max_retries=Retry(2485 total=2, status_forcelist=[500]2486 )))2585 s.mount("http://", HTTPAdapter(max_retries=Retry(total=2, status_forcelist=[500])))25862587 with pytest.raises(RetryError):2489 s.get(httpbin('status/500'))2588 s.get(httpbin("status/500"))258925902591def test_urllib3_pool_connection_closed(httpbin):2592 s = requests.Session()2494 s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))2593 s.mount("http://", HTTPAdapter(pool_connections=0, pool_maxsize=0))25942595 try:2497 s.get(httpbin('status/200'))2596 s.get(httpbin("status/200"))2597 except ConnectionError as e:2499 assert u"Pool is closed." in str(e)2598 assert "Pool is closed." in str(e)259926002502class TestPreparingURLs(object):2601class TestPreparingURLs:2602 @pytest.mark.parametrize(2504 'url,expected',2603 "url,expected",2604 (2506 ('http://google.com', 'http://google.com/'),2507 ('http://ジェーピーニック.jp', 'http://xn--hckqz9bzb1cyrb.jp/'),2508 ('http://xn--n3h.net/', 'http://xn--n3h.net/'),2605 ("http://google.com", "http://google.com/"),2606 ("http://ジェーピーニック.jp", "http://xn--hckqz9bzb1cyrb.jp/"),2607 ("http://xn--n3h.net/", "http://xn--n3h.net/"),2608 ("http://ジェーピーニック.jp".encode(), "http://xn--hckqz9bzb1cyrb.jp/"),2609 ("http://straße.de/straße", "http://xn--strae-oqa.de/stra%C3%9Fe"),2610 (2510 'http://ジェーピーニック.jp'.encode('utf-8'),2511 'http://xn--hckqz9bzb1cyrb.jp/'2611 "http://straße.de/straße".encode(),2612 "http://xn--strae-oqa.de/stra%C3%9Fe",2613 ),2614 (2514 'http://straße.de/straße',2515 'http://xn--strae-oqa.de/stra%C3%9Fe'2615 "http://Königsgäßchen.de/straße",2616 "http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe",2617 ),2618 (2518 'http://straße.de/straße'.encode('utf-8'),2519 'http://xn--strae-oqa.de/stra%C3%9Fe'2619 "http://Königsgäßchen.de/straße".encode(),2620 "http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe",2621 ),2622 (b"http://xn--n3h.net/", "http://xn--n3h.net/"),2623 (2522 'http://Königsgäßchen.de/straße',2523 'http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe'2624 b"http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/",2625 "http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/",2626 ),2627 (2526 'http://Königsgäßchen.de/straße'.encode('utf-8'),2527 'http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe'2628 "http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/",2629 "http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/",2630 ),2529 (2530 b'http://xn--n3h.net/',2531 'http://xn--n3h.net/'2532 ),2631 ),2533 (2534 b'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/',2535 'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/'2536 ),2537 (2538 'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/',2539 'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/'2540 )2541 )2632 )2633 def test_preparing_url(self, url, expected):25442634 def normalize_percent_encode(x):2546 # Helper function that normalizes equivalent 2635 # Helper function that normalizes equivalent2636 # percent-encoded bytes before comparisons2548 for c in re.findall(r'%[a-fA-F0-9]{2}', x):2637 for c in re.findall(r"%[a-fA-F0-9]{2}", x):2638 x = x.replace(c, c.upper())2639 return x2551 2552 r = requests.Request('GET', url=url)26402641 r = requests.Request("GET", url=url)2642 p = r.prepare()2643 assert normalize_percent_encode(p.url) == expected26442645 @pytest.mark.parametrize(2557 'url',2646 "url",2647 (2648 b"http://*.google.com",2649 b"http://*",2561 u"http://*.google.com",2562 u"http://*",2563 u"http://☃.net/"2564 )2650 "http://*.google.com",2651 "http://*",2652 "http://☃.net/",2653 ),2654 )2655 def test_preparing_bad_url(self, url):2567 r = requests.Request('GET', url=url)2656 r = requests.Request("GET", url=url)2657 with pytest.raises(requests.exceptions.InvalidURL):2658 r.prepare()26592571 @pytest.mark.parametrize(2572 'url, exception',2573 (2574 ('http://localhost:-1', InvalidURL),2575 )2576 )2660 @pytest.mark.parametrize("url, exception", (("http://localhost:-1", InvalidURL),))2661 def test_redirecting_to_bad_url(self, httpbin, url, exception):2662 with pytest.raises(exception):2579 r = requests.get(httpbin('redirect-to'), params={'url': url})2663 requests.get(httpbin("redirect-to"), params={"url": url})26642665 @pytest.mark.parametrize(2582 'input, expected',2666 "input, expected",2667 (2668 (2669 b"http+unix://%2Fvar%2Frun%2Fsocket/path%7E",2586 u"http+unix://%2Fvar%2Frun%2Fsocket/path~",2670 "http+unix://%2Fvar%2Frun%2Fsocket/path~",2671 ),2672 (2589 u"http+unix://%2Fvar%2Frun%2Fsocket/path%7E",2590 u"http+unix://%2Fvar%2Frun%2Fsocket/path~",2673 "http+unix://%2Fvar%2Frun%2Fsocket/path%7E",2674 "http+unix://%2Fvar%2Frun%2Fsocket/path~",2675 ),2676 (2677 b"mailto:user@example.org",2594 u"mailto:user@example.org",2678 "mailto:user@example.org",2679 ),2680 (2597 u"mailto:user@example.org",2598 u"mailto:user@example.org",2681 "mailto:user@example.org",2682 "mailto:user@example.org",2683 ),2684 (2685 b"data:SSDimaUgUHl0aG9uIQ==",2602 u"data:SSDimaUgUHl0aG9uIQ==",2603 )2604 )2686 "data:SSDimaUgUHl0aG9uIQ==",2687 ),2688 ),2689 )2690 def test_url_mutation(self, input, expected):2691 """2692 This test validates that we correctly exclude some URLs from2693 preparation, and that we handle others. Specifically, it tests that2694 any URL whose scheme doesn't begin with "http" is left alone, and2695 those whose scheme *does* begin with "http" are mutated.2696 """2613 r = requests.Request('GET', url=input)2697 r = requests.Request("GET", url=input)2698 p = r.prepare()2699 assert p.url == expected27002701 @pytest.mark.parametrize(2618 'input, params, expected',2702 "input, params, expected",2703 (2704 (2705 b"http+unix://%2Fvar%2Frun%2Fsocket/path",2706 {"key": "value"},2623 u"http+unix://%2Fvar%2Frun%2Fsocket/path?key=value",2707 "http+unix://%2Fvar%2Frun%2Fsocket/path?key=value",2708 ),2709 (2626 u"http+unix://%2Fvar%2Frun%2Fsocket/path",2710 "http+unix://%2Fvar%2Frun%2Fsocket/path",2711 {"key": "value"},2628 u"http+unix://%2Fvar%2Frun%2Fsocket/path?key=value",2712 "http+unix://%2Fvar%2Frun%2Fsocket/path?key=value",2713 ),2714 (2715 b"mailto:user@example.org",2716 {"key": "value"},2633 u"mailto:user@example.org",2717 "mailto:user@example.org",2718 ),2719 (2636 u"mailto:user@example.org",2720 "mailto:user@example.org",2721 {"key": "value"},2638 u"mailto:user@example.org",2722 "mailto:user@example.org",2723 ),2640 )2724 ),2725 )2726 def test_parameters_for_nonstandard_schemes(self, input, params, expected):2727 """2728 Setting parameters for nonstandard schemes is allowed if those schemes2729 begin with "http", and is forbidden otherwise.2730 """2647 r = requests.Request('GET', url=input, params=params)2731 r = requests.Request("GET", url=input, params=params)2732 p = r.prepare()2733 assert p.url == expected27342735 def test_post_json_nan(self, httpbin):2736 data = {"foo": float("nan")}2737 with pytest.raises(requests.exceptions.InvalidJSONError):2654 r = requests.post(httpbin('post'), json=data)2738 requests.post(httpbin("post"), json=data)27392740 def test_json_decode_compatibility(self, httpbin):2657 r = requests.get(httpbin('bytes/20'))2741 r = requests.get(httpbin("bytes/20"))2742 with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:2743 r.json()2744 assert isinstance(excinfo.value, RequestException)2745 assert isinstance(excinfo.value, JSONDecodeError)2746 assert r.text not in str(excinfo.value)27472748 def test_json_decode_persists_doc_attr(self, httpbin):2665 r = requests.get(httpbin('bytes/20'))2749 r = requests.get(httpbin("bytes/20"))2750 with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:2751 r.json()2752 assert excinfo.value.doc == r.text
modified:tests/test_structures.py+20 added-18 removed
1# -*- coding: utf-8 -*-21import pytest23from requests.structures import CaseInsensitiveDict, LookupDict456class TestCaseInsensitiveDict:97 @pytest.fixture(autouse=True)8 def setup(self):9 """CaseInsensitiveDict instance with "Accept" header."""10 self.case_insensitive_dict = CaseInsensitiveDict()14 self.case_insensitive_dict['Accept'] = 'application/json'11 self.case_insensitive_dict["Accept"] = "application/json"1213 def test_list(self):17 assert list(self.case_insensitive_dict) == ['Accept']14 assert list(self.case_insensitive_dict) == ["Accept"]1519 possible_keys = pytest.mark.parametrize('key', ('accept', 'ACCEPT', 'aCcEpT', 'Accept'))16 possible_keys = pytest.mark.parametrize(17 "key", ("accept", "ACCEPT", "aCcEpT", "Accept")18 )1920 @possible_keys21 def test_getitem(self, key):23 assert self.case_insensitive_dict[key] == 'application/json'22 assert self.case_insensitive_dict[key] == "application/json"2324 @possible_keys25 def test_delitem(self, key):26 del self.case_insensitive_dict[key]27 assert key not in self.case_insensitive_dict2829 def test_lower_items(self):31 assert list(self.case_insensitive_dict.lower_items()) == [('accept', 'application/json')]30 assert list(self.case_insensitive_dict.lower_items()) == [31 ("accept", "application/json")32 ]3334 def test_repr(self):35 assert repr(self.case_insensitive_dict) == "{'Accept': 'application/json'}"36
2 unmodified lines
39 assert copy is not self.case_insensitive_dict40 assert copy == self.case_insensitive_dict4142 @pytest.mark.parametrize(42 'other, result', (43 ({'AccePT': 'application/json'}, True),43 "other, result",44 (45 ({"AccePT": "application/json"}, True),46 ({}, False),45 (None, False)46 )47 (None, False),48 ),49 )50 def test_instance_equality(self, other, result):51 assert (self.case_insensitive_dict == other) is result525354class TestLookupDict:5355 @pytest.fixture(autouse=True)56 def setup(self):57 """LookupDict instance with "bad_gateway" attribute."""57 self.lookup_dict = LookupDict('test')58 self.lookup_dict = LookupDict("test")59 self.lookup_dict.bad_gateway = 5026061 def test_repr(self):62 assert repr(self.lookup_dict) == "<lookup 'test'>"6364 get_item_parameters = pytest.mark.parametrize(64 'key, value', (65 ('bad_gateway', 502),66 ('not_a_key', None)67 )65 "key, value",66 (67 ("bad_gateway", 502),68 ("not_a_key", None),69 ),70 )7172 @get_item_parameters73 def test_getitem(self, key, value):
5 unmodified lines
modified:tests/test_testserver.py+22 added-23 removed
1# -*- coding: utf-8 -*-23import threading1import socket2import threading3import time45import pytest8import requests6from tests.testserver.server import Server78import requests912class TestTestServer:1011class TestTestServer:12 def test_basic(self):13 """messages are sent and received properly"""14 question = b"success?"15 answer = b"yeah, success"
25 unmodified lines
4142 def test_text_response(self):43 """the text_response_server sends the given text"""44 server = Server.text_response_server(47 "HTTP/1.1 200 OK\r\n" +48 "Content-Length: 6\r\n" +49 "\r\nroflol"45 "HTTP/1.1 200 OK\r\n" "Content-Length: 6\r\n" "\r\nroflol"46 )4748 with server as (host, port):53 r = requests.get('http://{}:{}'.format(host, port))49 r = requests.get(f"http://{host}:{port}")5051 assert r.status_code == 20056 assert r.text == u'roflol'57 assert r.headers['Content-Length'] == '6'52 assert r.text == "roflol"53 assert r.headers["Content-Length"] == "6"5455 def test_basic_response(self):56 """the basic response server returns an empty http response"""57 with Server.basic_response_server() as (host, port):62 r = requests.get('http://{}:{}'.format(host, port))58 r = requests.get(f"http://{host}:{port}")59 assert r.status_code == 20064 assert r.text == u''65 assert r.headers['Content-Length'] == '0'60 assert r.text == ""61 assert r.headers["Content-Length"] == "0"6263 def test_basic_waiting_server(self):64 """the server waits for the block_server event to be set before closing"""65 block_server = threading.Event()6671 with Server.basic_response_server(wait_to_close_event=block_server) as (host, port):67 with Server.basic_response_server(wait_to_close_event=block_server) as (68 host,69 port,70 ):71 sock = socket.socket()72 sock.connect((host, port))74 sock.sendall(b'send something')73 sock.sendall(b"send something")74 time.sleep(2.5)76 sock.sendall(b'still alive')75 sock.sendall(b"still alive")76 block_server.set() # release server block7778 def test_multiple_requests(self):79 """multiple requests can be served"""
1 unmodified line
8182 server = Server.basic_response_server(requests_to_handle=requests_to_handle)8384 with server as (host, port):86 server_url = 'http://{}:{}'.format(host, port)85 server_url = f"http://{host}:{port}"86 for _ in range(requests_to_handle):87 r = requests.get(server_url)88 assert r.status_code == 20089
5 unmodified lines
95 def test_request_recovery(self):96 """can check the requests content"""97 # TODO: figure out why this sometimes fails when using pytest-xdist.98 server = Server.basic_response_server(requests_to_handle=2)100 first_request = b'put your hands up in the air'101 second_request = b'put your hand down in the floor'99 first_request = b"put your hands up in the air"100 second_request = b"put your hand down in the floor"101102 with server as address:103 sock1 = socket.socket()104 sock2 = socket.socket()
16 unmodified lines
121 with server as address:122 sock = socket.socket()123 sock.connect(address)124 time.sleep(1.5)126 sock.sendall(b'hehehe, not received')125 sock.sendall(b"hehehe, not received")126 sock.close()127129 assert server.handler_results[0] == b''128 assert server.handler_results[0] == b""129130 def test_request_recovery_with_bigger_timeout(self):131 """a biggest timeout can be specified"""132 server = Server.basic_response_server(request_timeout=3)134 data = b'bananadine'133 data = b"bananadine"134135 with server as address:136 sock = socket.socket()137 sock.connect(address)
28 unmodified lines
modified:tests/test_utils.py+469 added-383 removed
1# -*- coding: utf-8 -*-23import os1import copy2import filecmp6from io import BytesIO3import os4import tarfile5import zipfile6from collections import deque7from io import BytesIO89import pytest1011from requests import compat12from requests._internal_utils import unicode_is_ascii13from requests.cookies import RequestsCookieJar14from requests.structures import CaseInsensitiveDict15from requests.utils import (16 address_in_network, dotted_netmask, extract_zipped_paths,17 get_auth_from_url, _parse_content_type_header, get_encoding_from_headers,18 get_encodings_from_content, get_environ_proxies,19 guess_filename, guess_json_utf, is_ipv4_address,20 is_valid_cidr, iter_slices, parse_dict_header,21 parse_header_links, prepend_scheme_if_needed,22 requote_uri, select_proxy, should_bypass_proxies, super_len,23 to_key_val_list, to_native_string,24 unquote_header_value, unquote_unreserved,25 urldefragauth, add_dict_to_cookiejar, set_environ)26from requests._internal_utils import unicode_is_ascii16 _parse_content_type_header,17 add_dict_to_cookiejar,18 address_in_network,19 dotted_netmask,20 extract_zipped_paths,21 get_auth_from_url,22 get_encoding_from_headers,23 get_encodings_from_content,24 get_environ_proxies,25 guess_filename,26 guess_json_utf,27 is_ipv4_address,28 is_valid_cidr,29 iter_slices,30 parse_dict_header,31 parse_header_links,32 prepend_scheme_if_needed,33 requote_uri,34 select_proxy,35 set_environ,36 should_bypass_proxies,37 super_len,38 to_key_val_list,39 to_native_string,40 unquote_header_value,41 unquote_unreserved,42 urldefragauth,43)4445from .compat import StringIO, cStringIO464748class TestSuperLen:3249 @pytest.mark.parametrize(34 'stream, value', (35 (StringIO.StringIO, 'Test'),36 (BytesIO, b'Test'),37 pytest.param(cStringIO, 'Test',38 marks=pytest.mark.skipif('cStringIO is None')),39 ))50 "stream, value",51 (52 (StringIO.StringIO, "Test"),53 (BytesIO, b"Test"),54 pytest.param(55 cStringIO, "Test", marks=pytest.mark.skipif("cStringIO is None")56 ),57 ),58 )59 def test_io_streams(self, stream, value):60 """Ensures that we properly deal with different kinds of IO streams."""61 assert super_len(stream()) == 062 assert super_len(stream(value)) == 46364 def test_super_len_correctly_calculates_len_of_partially_read_file(self):65 """Ensure that we handle partially consumed file like objects."""66 s = StringIO.StringIO()48 s.write('foobarbogus')67 s.write("foobarbogus")68 assert super_len(s) == 06951 @pytest.mark.parametrize('error', [IOError, OSError])70 @pytest.mark.parametrize("error", [IOError, OSError])71 def test_super_len_handles_files_raising_weird_errors_in_tell(self, error):72 """If tell() raises errors, assume the cursor is at position zero."""7354 class BoomFile(object):74 class BoomFile:75 def __len__(self):76 return 57778 def tell(self):79 raise error()8081 assert super_len(BoomFile()) == 08263 @pytest.mark.parametrize('error', [IOError, OSError])83 @pytest.mark.parametrize("error", [IOError, OSError])84 def test_super_len_tell_ioerror(self, error):85 """Ensure that if tell gives an IOError super_len doesn't fail"""8666 class NoLenBoomFile(object):87 class NoLenBoomFile:88 def tell(self):89 raise error()9091 def seek(self, offset, whence):
1 unmodified line
9394 assert super_len(NoLenBoomFile()) == 09596 def test_string(self):76 assert super_len('Test') == 497 assert super_len("Test") == 49899 @pytest.mark.parametrize(79 'mode, warnings_num', (80 ('r', 1),81 ('rb', 0),82 ))100 "mode, warnings_num",101 (102 ("r", 1),103 ("rb", 0),104 ),105 )106 def test_file(self, tmpdir, mode, warnings_num, recwarn):84 file_obj = tmpdir.join('test.txt')85 file_obj.write('Test')107 file_obj = tmpdir.join("test.txt")108 file_obj.write("Test")109 with file_obj.open(mode) as fd:110 assert super_len(fd) == 4111 assert len(recwarn) == warnings_num112113 def test_tarfile_member(self, tmpdir):91 file_obj = tmpdir.join('test.txt')92 file_obj.write('Test')114 file_obj = tmpdir.join("test.txt")115 file_obj.write("Test")11694 tar_obj = str(tmpdir.join('test.tar'))95 with tarfile.open(tar_obj, 'w') as tar:96 tar.add(str(file_obj), arcname='test.txt')117 tar_obj = str(tmpdir.join("test.tar"))118 with tarfile.open(tar_obj, "w") as tar:119 tar.add(str(file_obj), arcname="test.txt")120121 with tarfile.open(tar_obj) as tar:99 member = tar.extractfile('test.txt')122 member = tar.extractfile("test.txt")123 assert super_len(member) == 4124125 def test_super_len_with__len__(self):103 foo = [1,2,3,4]126 foo = [1, 2, 3, 4]127 len_foo = super_len(foo)128 assert len_foo == 4129130 def test_super_len_with_no__len__(self):108 class LenFile(object):131 class LenFile:132 def __init__(self):133 self.len = 5134135 assert super_len(LenFile()) == 5136137 def test_super_len_with_tell(self):115 foo = StringIO.StringIO('12345')138 foo = StringIO.StringIO("12345")139 assert super_len(foo) == 5140 foo.read(2)141 assert super_len(foo) == 3142143 def test_super_len_with_fileno(self):121 with open(__file__, 'rb') as f:144 with open(__file__, "rb") as f:145 length = super_len(f)146 file_data = f.read()147 assert length == len(file_data)148
2 unmodified lines
151 assert super_len(object()) == 0152153154class TestToKeyValList:132155 @pytest.mark.parametrize(134 'value, expected', (135 ([('key', 'val')], [('key', 'val')]),136 ((('key', 'val'), ), [('key', 'val')]),137 ({'key': 'val'}, [('key', 'val')]),138 (None, None)139 ))156 "value, expected",157 (158 ([("key", "val")], [("key", "val")]),159 ((("key", "val"),), [("key", "val")]),160 ({"key": "val"}, [("key", "val")]),161 (None, None),162 ),163 )164 def test_valid(self, value, expected):165 assert to_key_val_list(value) == expected166167 def test_invalid(self):168 with pytest.raises(ValueError):145 to_key_val_list('string')169 to_key_val_list("string")170171172class TestUnquoteHeaderValue:149173 @pytest.mark.parametrize(151 'value, expected', (174 "value, expected",175 (176 (None, None),153 ('Test', 'Test'),154 ('"Test"', 'Test'),155 ('"Test\\\\"', 'Test\\'),156 ('"\\\\Comp\\Res"', '\\Comp\\Res'),157 ))177 ("Test", "Test"),178 ('"Test"', "Test"),179 ('"Test\\\\"', "Test\\"),180 ('"\\\\Comp\\Res"', "\\Comp\\Res"),181 ),182 )183 def test_valid(self, value, expected):184 assert unquote_header_value(value) == expected185186 def test_is_filename(self):162 assert unquote_header_value('"\\\\Comp\\Res"', True) == '\\\\Comp\\Res'187 assert unquote_header_value('"\\\\Comp\\Res"', True) == "\\\\Comp\\Res"188189190class TestGetEnvironProxies:191 """Ensures that IP addresses are correctly matches with ranges192 in no_proxy variable.193 """194170 @pytest.fixture(autouse=True, params=['no_proxy', 'NO_PROXY'])195 @pytest.fixture(autouse=True, params=["no_proxy", "NO_PROXY"])196 def no_proxy(self, request, monkeypatch):172 monkeypatch.setenv(request.param, '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')197 monkeypatch.setenv(198 request.param, "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"199 )200201 @pytest.mark.parametrize(175 'url', (176 'http://192.168.0.1:5000/',177 'http://192.168.0.1/',178 'http://172.16.1.1/',179 'http://172.16.1.1:5000/',180 'http://localhost.localdomain:5000/v1.0/',181 ))202 "url",203 (204 "http://192.168.0.1:5000/",205 "http://192.168.0.1/",206 "http://172.16.1.1/",207 "http://172.16.1.1:5000/",208 "http://localhost.localdomain:5000/v1.0/",209 ),210 )211 def test_bypass(self, url):212 assert get_environ_proxies(url, no_proxy=None) == {}213214 @pytest.mark.parametrize(186 'url', (187 'http://192.168.1.1:5000/',188 'http://192.168.1.1/',189 'http://www.requests.com/',190 ))215 "url",216 (217 "http://192.168.1.1:5000/",218 "http://192.168.1.1/",219 "http://www.requests.com/",220 ),221 )222 def test_not_bypass(self, url):223 assert get_environ_proxies(url, no_proxy=None) != {}224225 @pytest.mark.parametrize(195 'url', (196 'http://192.168.1.1:5000/',197 'http://192.168.1.1/',198 'http://www.requests.com/',199 ))226 "url",227 (228 "http://192.168.1.1:5000/",229 "http://192.168.1.1/",230 "http://www.requests.com/",231 ),232 )233 def test_bypass_no_proxy_keyword(self, url):201 no_proxy = '192.168.1.1,requests.com'234 no_proxy = "192.168.1.1,requests.com"235 assert get_environ_proxies(url, no_proxy=no_proxy) == {}236237 @pytest.mark.parametrize(205 'url', (206 'http://192.168.0.1:5000/',207 'http://192.168.0.1/',208 'http://172.16.1.1/',209 'http://172.16.1.1:5000/',210 'http://localhost.localdomain:5000/v1.0/',211 ))238 "url",239 (240 "http://192.168.0.1:5000/",241 "http://192.168.0.1/",242 "http://172.16.1.1/",243 "http://172.16.1.1:5000/",244 "http://localhost.localdomain:5000/v1.0/",245 ),246 )247 def test_not_bypass_no_proxy_keyword(self, url, monkeypatch):248 # This is testing that the 'no_proxy' argument overrides the249 # environment variable 'no_proxy'215 monkeypatch.setenv('http_proxy', 'http://proxy.example.com:3128/')216 no_proxy = '192.168.1.1,requests.com'250 monkeypatch.setenv("http_proxy", "http://proxy.example.com:3128/")251 no_proxy = "192.168.1.1,requests.com"252 assert get_environ_proxies(url, no_proxy=no_proxy) != {}253254255class TestIsIPv4Address:221256 def test_valid(self):223 assert is_ipv4_address('8.8.8.8')257 assert is_ipv4_address("8.8.8.8")258225 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))259 @pytest.mark.parametrize("value", ("8.8.8.8.8", "localhost.localdomain"))260 def test_invalid(self, value):261 assert not is_ipv4_address(value)262263264class TestIsValidCIDR:231265 def test_valid(self):233 assert is_valid_cidr('192.168.1.0/24')266 assert is_valid_cidr("192.168.1.0/24")267268 @pytest.mark.parametrize(236 'value', (237 '8.8.8.8',238 '192.168.1.0/a',239 '192.168.1.0/128',240 '192.168.1.0/-1',241 '192.168.1.999/24',242 ))269 "value",270 (271 "8.8.8.8",272 "192.168.1.0/a",273 "192.168.1.0/128",274 "192.168.1.0/-1",275 "192.168.1.999/24",276 ),277 )278 def test_invalid(self, value):279 assert not is_valid_cidr(value)280281282class TestAddressInNetwork:248283 def test_valid(self):250 assert address_in_network('192.168.1.1', '192.168.1.0/24')284 assert address_in_network("192.168.1.1", "192.168.1.0/24")285286 def test_invalid(self):253 assert not address_in_network('172.16.0.1', '192.168.1.0/24')287 assert not address_in_network("172.16.0.1", "192.168.1.0/24")288289290class TestGuessFilename:257291 @pytest.mark.parametrize(259 'value', (1, type('Fake', (object,), {'name': 1})()),292 "value",293 (1, type("Fake", (object,), {"name": 1})()),294 )295 def test_guess_filename_invalid(self, value):296 assert guess_filename(value) is None297298 @pytest.mark.parametrize(265 'value, expected_type', (266 (b'value', compat.bytes),267 (b'value'.decode('utf-8'), compat.str)268 ))299 "value, expected_type",300 (301 (b"value", compat.bytes),302 (b"value".decode("utf-8"), compat.str),303 ),304 )305 def test_guess_filename_valid(self, value, expected_type):270 obj = type('Fake', (object,), {'name': value})()306 obj = type("Fake", (object,), {"name": value})()307 result = guess_filename(obj)308 assert result == value309 assert isinstance(result, expected_type)310311312class TestExtractZippedPaths:277313 @pytest.mark.parametrize(279 'path', (280 '/',314 "path",315 (316 "/",317 __file__,318 pytest.__file__,283 '/etc/invalid/location',284 ))319 "/etc/invalid/location",320 ),321 )322 def test_unzipped_paths_unchanged(self, path):323 assert path == extract_zipped_paths(path)324325 def test_zipped_paths_extracted(self, tmpdir):289 zipped_py = tmpdir.join('test.zip')290 with zipfile.ZipFile(zipped_py.strpath, 'w') as f:326 zipped_py = tmpdir.join("test.zip")327 with zipfile.ZipFile(zipped_py.strpath, "w") as f:328 f.write(__file__)329330 _, name = os.path.splitdrive(__file__)294 zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r'\/'))331 zipped_path = os.path.join(zipped_py.strpath, name.lstrip(r"\/"))332 extracted_path = extract_zipped_paths(zipped_path)333334 assert extracted_path != zipped_path335 assert os.path.exists(extracted_path)
4 unmodified lines
340 assert extract_zipped_paths(path) == path341342343class TestContentEncodingDetection:307344 def test_none(self):309 encodings = get_encodings_from_content('')345 encodings = get_encodings_from_content("")346 assert not len(encodings)347348 @pytest.mark.parametrize(313 'content', (349 "content",350 (351 # HTML5 meta charset attribute352 '<meta charset="UTF-8">',353 # HTML4 pragma directive354 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',355 # XHTML 1.x served with text/html MIME type356 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',357 # XHTML 1.x served as XML358 '<?xml version="1.0" encoding="UTF-8"?>',322 ))359 ),360 )361 def test_pragmas(self, content):362 encodings = get_encodings_from_content(content)363 assert len(encodings) == 1326 assert encodings[0] == 'UTF-8'364 assert encodings[0] == "UTF-8"365366 def test_precedence(self):329 content = '''367 content = """368 <?xml version="1.0" encoding="XML"?>369 <meta charset="HTML5">370 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />333 '''.strip()334 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']371 """.strip()372 assert get_encodings_from_content(content) == ["HTML5", "HTML4", "XML"]373374375class TestGuessJSONUTF:338376 @pytest.mark.parametrize(340 'encoding', (341 'utf-32', 'utf-8-sig', 'utf-16', 'utf-8', 'utf-16-be', 'utf-16-le',342 'utf-32-be', 'utf-32-le'343 ))377 "encoding",378 (379 "utf-32",380 "utf-8-sig",381 "utf-16",382 "utf-8",383 "utf-16-be",384 "utf-16-le",385 "utf-32-be",386 "utf-32-le",387 ),388 )389 def test_encoded(self, encoding):345 data = '{}'.encode(encoding)390 data = "{}".encode(encoding)391 assert guess_json_utf(data) == encoding392393 def test_bad_utf_like_encoding(self):349 assert guess_json_utf(b'\x00\x00\x00\x00') is None394 assert guess_json_utf(b"\x00\x00\x00\x00") is None395396 @pytest.mark.parametrize(352 ('encoding', 'expected'), (353 ('utf-16-be', 'utf-16'),354 ('utf-16-le', 'utf-16'),355 ('utf-32-be', 'utf-32'),356 ('utf-32-le', 'utf-32')357 ))397 ("encoding", "expected"),398 (399 ("utf-16-be", "utf-16"),400 ("utf-16-le", "utf-16"),401 ("utf-32-be", "utf-32"),402 ("utf-32-le", "utf-32"),403 ),404 )405 def test_guess_by_bom(self, encoding, expected):359 data = u'\ufeff{}'.encode(encoding)406 data = "\ufeff{}".encode(encoding)407 assert guess_json_utf(data) == expected408409410USER = PASSWORD = "%!*'();:@&=+$,/?#[] "364ENCODED_USER = compat.quote(USER, '')365ENCODED_PASSWORD = compat.quote(PASSWORD, '')411ENCODED_USER = compat.quote(USER, "")412ENCODED_PASSWORD = compat.quote(PASSWORD, "")413414415@pytest.mark.parametrize(369 'url, auth', (416 "url, auth",417 (418 (371 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +372 'request.com/url.html#test',373 (USER, PASSWORD)419 f"http://{ENCODED_USER}:{ENCODED_PASSWORD}@request.com/url.html#test",420 (USER, PASSWORD),421 ),422 ("http://user:pass@complex.url.com/path?query=yes", ("user", "pass")),423 (376 'http://user:pass@complex.url.com/path?query=yes',377 ('user', 'pass')424 "http://user:pass%20pass@complex.url.com/path?query=yes",425 ("user", "pass pass"),426 ),427 ("http://user:pass pass@complex.url.com/path?query=yes", ("user", "pass pass")),428 (380 'http://user:pass%20pass@complex.url.com/path?query=yes',381 ('user', 'pass pass')429 "http://user%25user:pass@complex.url.com/path?query=yes",430 ("user%user", "pass"),431 ),432 (384 'http://user:pass pass@complex.url.com/path?query=yes',385 ('user', 'pass pass')433 "http://user:pass%23pass@complex.url.com/path?query=yes",434 ("user", "pass#pass"),435 ),387 (388 'http://user%25user:pass@complex.url.com/path?query=yes',389 ('user%user', 'pass')390 ),391 (392 'http://user:pass%23pass@complex.url.com/path?query=yes',393 ('user', 'pass#pass')394 ),395 (396 'http://complex.url.com/path?query=yes',397 ('', '')398 ),399 ))436 ("http://complex.url.com/path?query=yes", ("", "")),437 ),438)439def test_get_auth_from_url(url, auth):440 assert get_auth_from_url(url) == auth441442443@pytest.mark.parametrize(405 'uri, expected', (444 "uri, expected",445 (446 (447 # Ensure requoting doesn't break expectations408 'http://example.com/fiz?buz=%25ppicture',409 'http://example.com/fiz?buz=%25ppicture',448 "http://example.com/fiz?buz=%25ppicture",449 "http://example.com/fiz?buz=%25ppicture",450 ),451 (452 # Ensure we handle unquoted percent signs in redirects413 'http://example.com/fiz?buz=%ppicture',414 'http://example.com/fiz?buz=%25ppicture',453 "http://example.com/fiz?buz=%ppicture",454 "http://example.com/fiz?buz=%25ppicture",455 ),416 ))456 ),457)458def test_requote_uri_with_unquoted_percents(uri, expected):459 """See: https://github.com/psf/requests/issues/2356"""460 assert requote_uri(uri) == expected461462463@pytest.mark.parametrize(423 'uri, expected', (464 "uri, expected",465 (466 (467 # Illegal bytes426 'http://example.com/?a=%--',427 'http://example.com/?a=%--',468 "http://example.com/?a=%--",469 "http://example.com/?a=%--",470 ),471 (472 # Reserved characters431 'http://example.com/?a=%300',432 'http://example.com/?a=00',433 )434 ))473 "http://example.com/?a=%300",474 "http://example.com/?a=00",475 ),476 ),477)478def test_unquote_unreserved(uri, expected):479 assert unquote_unreserved(uri) == expected480481482@pytest.mark.parametrize(440 'mask, expected', (441 (8, '255.0.0.0'),442 (24, '255.255.255.0'),443 (25, '255.255.255.128'),444 ))483 "mask, expected",484 (485 (8, "255.0.0.0"),486 (24, "255.255.255.0"),487 (25, "255.255.255.128"),488 ),489)490def test_dotted_netmask(mask, expected):491 assert dotted_netmask(mask) == expected492493449http_proxies = {'http': 'http://http.proxy',450 'http://some.host': 'http://some.host.proxy'}451all_proxies = {'all': 'socks5://http.proxy',452 'all://some.host': 'socks5://some.host.proxy'}453mixed_proxies = {'http': 'http://http.proxy',454 'http://some.host': 'http://some.host.proxy',455 'all': 'socks5://http.proxy'}456@pytest.mark.parametrize(457 'url, expected, proxies', (458 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy', http_proxies),459 ('hTTp://u:p@Other.Host/path', 'http://http.proxy', http_proxies),460 ('hTTp:///path', 'http://http.proxy', http_proxies),461 ('hTTps://Other.Host', None, http_proxies),462 ('file:///etc/motd', None, http_proxies),494http_proxies = {495 "http": "http://http.proxy",496 "http://some.host": "http://some.host.proxy",497}498all_proxies = {499 "all": "socks5://http.proxy",500 "all://some.host": "socks5://some.host.proxy",501}502mixed_proxies = {503 "http": "http://http.proxy",504 "http://some.host": "http://some.host.proxy",505 "all": "socks5://http.proxy",506}507464 ('hTTp://u:p@Some.Host/path', 'socks5://some.host.proxy', all_proxies),465 ('hTTp://u:p@Other.Host/path', 'socks5://http.proxy', all_proxies),466 ('hTTp:///path', 'socks5://http.proxy', all_proxies),467 ('hTTps://Other.Host', 'socks5://http.proxy', all_proxies),508469 ('http://u:p@other.host/path', 'http://http.proxy', mixed_proxies),470 ('http://u:p@some.host/path', 'http://some.host.proxy', mixed_proxies),471 ('https://u:p@other.host/path', 'socks5://http.proxy', mixed_proxies),472 ('https://u:p@some.host/path', 'socks5://http.proxy', mixed_proxies),473 ('https://', 'socks5://http.proxy', mixed_proxies),509@pytest.mark.parametrize(510 "url, expected, proxies",511 (512 ("hTTp://u:p@Some.Host/path", "http://some.host.proxy", http_proxies),513 ("hTTp://u:p@Other.Host/path", "http://http.proxy", http_proxies),514 ("hTTp:///path", "http://http.proxy", http_proxies),515 ("hTTps://Other.Host", None, http_proxies),516 ("file:///etc/motd", None, http_proxies),517 ("hTTp://u:p@Some.Host/path", "socks5://some.host.proxy", all_proxies),518 ("hTTp://u:p@Other.Host/path", "socks5://http.proxy", all_proxies),519 ("hTTp:///path", "socks5://http.proxy", all_proxies),520 ("hTTps://Other.Host", "socks5://http.proxy", all_proxies),521 ("http://u:p@other.host/path", "http://http.proxy", mixed_proxies),522 ("http://u:p@some.host/path", "http://some.host.proxy", mixed_proxies),523 ("https://u:p@other.host/path", "socks5://http.proxy", mixed_proxies),524 ("https://u:p@some.host/path", "socks5://http.proxy", mixed_proxies),525 ("https://", "socks5://http.proxy", mixed_proxies),526 # XXX: unsure whether this is reasonable behavior475 ('file:///etc/motd', 'socks5://http.proxy', all_proxies),476 ))527 ("file:///etc/motd", "socks5://http.proxy", all_proxies),528 ),529)530def test_select_proxies(url, expected, proxies):531 """Make sure we can select per-host proxies correctly."""532 assert select_proxy(url, proxies) == expected533534535@pytest.mark.parametrize(483 'value, expected', (484 ('foo="is a fish", bar="as well"', {'foo': 'is a fish', 'bar': 'as well'}),485 ('key_without_value', {'key_without_value': None})486 ))536 "value, expected",537 (538 ('foo="is a fish", bar="as well"', {"foo": "is a fish", "bar": "as well"}),539 ("key_without_value", {"key_without_value": None}),540 ),541)542def test_parse_dict_header(value, expected):543 assert parse_dict_header(value) == expected544545546@pytest.mark.parametrize(492 'value, expected', (547 "value, expected",548 (549 ("application/xml", ("application/xml", {})),550 (494 'application/xml',495 ('application/xml', {})551 "application/json ; charset=utf-8",552 ("application/json", {"charset": "utf-8"}),553 ),554 (498 'application/json ; charset=utf-8',499 ('application/json', {'charset': 'utf-8'})555 "application/json ; Charset=utf-8",556 ("application/json", {"charset": "utf-8"}),557 ),558 ("text/plain", ("text/plain", {})),559 (502 'application/json ; Charset=utf-8',503 ('application/json', {'charset': 'utf-8'})560 "multipart/form-data; boundary = something ; boundary2='something_else' ; no_equals ",561 (562 "multipart/form-data",563 {564 "boundary": "something",565 "boundary2": "something_else",566 "no_equals": True,567 },568 ),569 ),570 (506 'text/plain',507 ('text/plain', {})571 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',572 (573 "multipart/form-data",574 {575 "boundary": "something",576 "boundary2": "something_else",577 "no_equals": True,578 },579 ),580 ),581 (510 'multipart/form-data; boundary = something ; boundary2=\'something_else\' ; no_equals ',511 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})582 "multipart/form-data; boundary = something ; 'boundary2=something_else' ; no_equals ",583 (584 "multipart/form-data",585 {586 "boundary": "something",587 "boundary2": "something_else",588 "no_equals": True,589 },590 ),591 ),592 (514 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ',515 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})516 ),517 (518 'multipart/form-data; boundary = something ; \'boundary2=something_else\' ; no_equals ',519 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})520 ),521 (593 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ',523 ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})594 (595 "multipart/form-data",596 {597 "boundary": "something",598 "boundary2": "something_else",599 "no_equals": True,600 },601 ),602 ),525 (526 'application/json ; ; ',527 ('application/json', {})528 )529 ))603 ("application/json ; ; ", ("application/json", {})),604 ),605)606def test__parse_content_type_header(value, expected):607 assert _parse_content_type_header(value) == expected608609610@pytest.mark.parametrize(535 'value, expected', (611 "value, expected",612 (613 (CaseInsensitiveDict(), None),614 (537 CaseInsensitiveDict(),538 None615 CaseInsensitiveDict({"content-type": "application/json; charset=utf-8"}),616 "utf-8",617 ),540 (541 CaseInsensitiveDict({'content-type': 'application/json; charset=utf-8'}),542 'utf-8'543 ),544 (545 CaseInsensitiveDict({'content-type': 'text/plain'}),546 'ISO-8859-1'547 ),548 ))618 (CaseInsensitiveDict({"content-type": "text/plain"}), "ISO-8859-1"),619 ),620)621def test_get_encoding_from_headers(value, expected):622 assert get_encoding_from_headers(value) == expected623624625@pytest.mark.parametrize(554 'value, length', (555 ('', 0),556 ('T', 1),557 ('Test', 4),558 ('Cont', 0),559 ('Other', -5),560 ('Content', None),561 ))626 "value, length",627 (628 ("", 0),629 ("T", 1),630 ("Test", 4),631 ("Cont", 0),632 ("Other", -5),633 ("Content", None),634 ),635)636def test_iter_slices(value, length):637 if length is None or (length <= 0 and len(value) > 0):638 # Reads all content at once639 assert len(list(iter_slices(value, length))) == 1
1 unmodified line
641 assert len(list(iter_slices(value, 1))) == length642643644@pytest.mark.parametrize(571 'value, expected', (645 "value, expected",646 (647 (648 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',574 [{'url': 'http:/.../front.jpeg', 'rel': 'front', 'type': 'image/jpeg'}]649 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],650 ),651 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),652 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),653 (577 '<http:/.../front.jpeg>',578 [{'url': 'http:/.../front.jpeg'}]579 ),580 (581 '<http:/.../front.jpeg>;',582 [{'url': 'http:/.../front.jpeg'}]583 ),584 (654 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',655 [587 {'url': 'http:/.../front.jpeg', 'type': 'image/jpeg'},588 {'url': 'http://.../back.jpeg'}589 ]656 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},657 {"url": "http://.../back.jpeg"},658 ],659 ),591 (592 '',593 []594 ),595 ))660 ("", []),661 ),662)663def test_parse_header_links(value, expected):664 assert parse_header_links(value) == expected665666667@pytest.mark.parametrize(601 'value, expected', (602 ('example.com/path', 'http://example.com/path'),603 ('//example.com/path', 'http://example.com/path'),604 ('example.com:80', 'http://example.com:80'),668 "value, expected",669 (670 ("example.com/path", "http://example.com/path"),671 ("//example.com/path", "http://example.com/path"),672 ("example.com:80", "http://example.com:80"),673 (606 'http://user:pass@example.com/path?query',607 'http://user:pass@example.com/path?query'674 "http://user:pass@example.com/path?query",675 "http://user:pass@example.com/path?query",676 ),609 (610 'http://user@example.com/path?query',611 'http://user@example.com/path?query'612 )613 ))677 ("http://user@example.com/path?query", "http://user@example.com/path?query"),678 ),679)680def test_prepend_scheme_if_needed(value, expected):615 assert prepend_scheme_if_needed(value, 'http') == expected681 assert prepend_scheme_if_needed(value, "http") == expected682683684@pytest.mark.parametrize(619 'value, expected', (620 ('T', 'T'),621 (b'T', 'T'),622 (u'T', 'T'),623 ))685 "value, expected",686 (687 ("T", "T"),688 (b"T", "T"),689 ("T", "T"),690 ),691)692def test_to_native_string(value, expected):693 assert to_native_string(value) == expected694695696@pytest.mark.parametrize(629 'url, expected', (630 ('http://u:p@example.com/path?a=1#test', 'http://example.com/path?a=1'),631 ('http://example.com/path', 'http://example.com/path'),632 ('//u:p@example.com/path', '//example.com/path'),633 ('//example.com/path', '//example.com/path'),634 ('example.com/path', '//example.com/path'),635 ('scheme:u:p@example.com/path', 'scheme://example.com/path'),636 ))697 "url, expected",698 (699 ("http://u:p@example.com/path?a=1#test", "http://example.com/path?a=1"),700 ("http://example.com/path", "http://example.com/path"),701 ("//u:p@example.com/path", "//example.com/path"),702 ("//example.com/path", "//example.com/path"),703 ("example.com/path", "//example.com/path"),704 ("scheme:u:p@example.com/path", "scheme://example.com/path"),705 ),706)707def test_urldefragauth(url, expected):708 assert urldefragauth(url) == expected709710711@pytest.mark.parametrize(642 'url, expected', (643 ('http://192.168.0.1:5000/', True),644 ('http://192.168.0.1/', True),645 ('http://172.16.1.1/', True),646 ('http://172.16.1.1:5000/', True),647 ('http://localhost.localdomain:5000/v1.0/', True),648 ('http://google.com:6000/', True),649 ('http://172.16.1.12/', False),650 ('http://172.16.1.12:5000/', False),651 ('http://google.com:5000/v1.0/', False),652 ('file:///some/path/on/disk', True),653 ))712 "url, expected",713 (714 ("http://192.168.0.1:5000/", True),715 ("http://192.168.0.1/", True),716 ("http://172.16.1.1/", True),717 ("http://172.16.1.1:5000/", True),718 ("http://localhost.localdomain:5000/v1.0/", True),719 ("http://google.com:6000/", True),720 ("http://172.16.1.12/", False),721 ("http://172.16.1.12:5000/", False),722 ("http://google.com:5000/v1.0/", False),723 ("file:///some/path/on/disk", True),724 ),725)726def test_should_bypass_proxies(url, expected, monkeypatch):727 """Tests for function should_bypass_proxies to check if proxy728 can be bypassed or not729 """658 monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')659 monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')730 monkeypatch.setenv(731 "no_proxy",732 "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000",733 )734 monkeypatch.setenv(735 "NO_PROXY",736 "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000",737 )738 assert should_bypass_proxies(url, no_proxy=None) == expected739740741@pytest.mark.parametrize(664 'url, expected', (665 ('http://172.16.1.1/', '172.16.1.1'),666 ('http://172.16.1.1:5000/', '172.16.1.1'),667 ('http://user:pass@172.16.1.1', '172.16.1.1'),668 ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),669 ('http://hostname/', 'hostname'),670 ('http://hostname:5000/', 'hostname'),671 ('http://user:pass@hostname', 'hostname'),672 ('http://user:pass@hostname:5000', 'hostname'),673 ))742 "url, expected",743 (744 ("http://172.16.1.1/", "172.16.1.1"),745 ("http://172.16.1.1:5000/", "172.16.1.1"),746 ("http://user:pass@172.16.1.1", "172.16.1.1"),747 ("http://user:pass@172.16.1.1:5000", "172.16.1.1"),748 ("http://hostname/", "hostname"),749 ("http://hostname:5000/", "hostname"),750 ("http://user:pass@hostname", "hostname"),751 ("http://user:pass@hostname:5000", "hostname"),752 ),753)754def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):755 """The proxy_bypass function should be called with a hostname or IP without756 a port number or auth credentials.757 """678 proxy_bypass = mocker.patch('requests.utils.proxy_bypass')758 proxy_bypass = mocker.patch("requests.utils.proxy_bypass")759 should_bypass_proxies(url, no_proxy=None)760 proxy_bypass.assert_called_once_with(expected)761762763@pytest.mark.parametrize(684 'cookiejar', (764 "cookiejar",765 (766 compat.cookielib.CookieJar(),686 RequestsCookieJar()687 ))767 RequestsCookieJar(),768 ),769)770def test_add_dict_to_cookiejar(cookiejar):771 """Ensure add_dict_to_cookiejar works for772 non-RequestsCookieJar CookieJars773 """692 cookiedict = {'test': 'cookies',693 'good': 'cookies'}774 cookiedict = {"test": "cookies", "good": "cookies"}775 cj = add_dict_to_cookiejar(cookiejar, cookiedict)776 cookies = {cookie.name: cookie.value for cookie in cj}777 assert cookiedict == cookies778779780@pytest.mark.parametrize(700 'value, expected', (701 (u'test', True),702 (u'æíöû', False),703 (u'ジェーピーニック', False),704 )781 "value, expected",782 (783 ("test", True),784 ("æíöû", False),785 ("ジェーピーニック", False),786 ),787)788def test_unicode_is_ascii(value, expected):789 assert unicode_is_ascii(value) is expected790791792@pytest.mark.parametrize(711 'url, expected', (712 ('http://192.168.0.1:5000/', True),713 ('http://192.168.0.1/', True),714 ('http://172.16.1.1/', True),715 ('http://172.16.1.1:5000/', True),716 ('http://localhost.localdomain:5000/v1.0/', True),717 ('http://172.16.1.12/', False),718 ('http://172.16.1.12:5000/', False),719 ('http://google.com:5000/v1.0/', False),720 ))721def test_should_bypass_proxies_no_proxy(722 url, expected, monkeypatch):793 "url, expected",794 (795 ("http://192.168.0.1:5000/", True),796 ("http://192.168.0.1/", True),797 ("http://172.16.1.1/", True),798 ("http://172.16.1.1:5000/", True),799 ("http://localhost.localdomain:5000/v1.0/", True),800 ("http://172.16.1.12/", False),801 ("http://172.16.1.12:5000/", False),802 ("http://google.com:5000/v1.0/", False),803 ),804)805def test_should_bypass_proxies_no_proxy(url, expected, monkeypatch):806 """Tests for function should_bypass_proxies to check if proxy807 can be bypassed or not using the 'no_proxy' argument808 """726 no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'809 no_proxy = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"810 # Test 'no_proxy' argument811 assert should_bypass_proxies(url, no_proxy=no_proxy) == expected812813731@pytest.mark.skipif(os.name != 'nt', reason='Test only on Windows')814@pytest.mark.skipif(os.name != "nt", reason="Test only on Windows")815@pytest.mark.parametrize(733 'url, expected, override', (734 ('http://192.168.0.1:5000/', True, None),735 ('http://192.168.0.1/', True, None),736 ('http://172.16.1.1/', True, None),737 ('http://172.16.1.1:5000/', True, None),738 ('http://localhost.localdomain:5000/v1.0/', True, None),739 ('http://172.16.1.22/', False, None),740 ('http://172.16.1.22:5000/', False, None),741 ('http://google.com:5000/v1.0/', False, None),742 ('http://mylocalhostname:5000/v1.0/', True, '<local>'),743 ('http://192.168.0.1/', False, ''),744 ))745def test_should_bypass_proxies_win_registry(url, expected, override,746 monkeypatch):816 "url, expected, override",817 (818 ("http://192.168.0.1:5000/", True, None),819 ("http://192.168.0.1/", True, None),820 ("http://172.16.1.1/", True, None),821 ("http://172.16.1.1:5000/", True, None),822 ("http://localhost.localdomain:5000/v1.0/", True, None),823 ("http://172.16.1.22/", False, None),824 ("http://172.16.1.22:5000/", False, None),825 ("http://google.com:5000/v1.0/", False, None),826 ("http://mylocalhostname:5000/v1.0/", True, "<local>"),827 ("http://192.168.0.1/", False, ""),828 ),829)830def test_should_bypass_proxies_win_registry(url, expected, override, monkeypatch):831 """Tests for function should_bypass_proxies to check if proxy832 can be bypassed or not with Windows registry settings833 """834 if override is None:751 override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'835 override = "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"836 import winreg837838 class RegHandle:839 def Close(self):
6 unmodified lines
846 return ie_settings847848 def QueryValueEx(key, value_name):849 if key is ie_settings:766 if value_name == 'ProxyEnable':850 if value_name == "ProxyEnable":851 # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)852 proxyEnableValues.rotate()853 return [proxyEnableValues[0]]770 elif value_name == 'ProxyOverride':854 elif value_name == "ProxyOverride":855 return [override]856773 monkeypatch.setenv('http_proxy', '')774 monkeypatch.setenv('https_proxy', '')775 monkeypatch.setenv('ftp_proxy', '')776 monkeypatch.setenv('no_proxy', '')777 monkeypatch.setenv('NO_PROXY', '')778 monkeypatch.setattr(winreg, 'OpenKey', OpenKey)779 monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)857 monkeypatch.setenv("http_proxy", "")858 monkeypatch.setenv("https_proxy", "")859 monkeypatch.setenv("ftp_proxy", "")860 monkeypatch.setenv("no_proxy", "")861 monkeypatch.setenv("NO_PROXY", "")862 monkeypatch.setattr(winreg, "OpenKey", OpenKey)863 monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx)864 assert should_bypass_proxies(url, None) == expected865866867@pytest.mark.parametrize(784 'env_name, value', (785 ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),786 ('no_proxy', None),787 ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),788 ('a_new_key', None),789 ))868 "env_name, value",869 (870 ("no_proxy", "192.168.0.0/24,127.0.0.1,localhost.localdomain"),871 ("no_proxy", None),872 ("a_new_key", "192.168.0.0/24,127.0.0.1,localhost.localdomain"),873 ("a_new_key", None),874 ),875)876def test_set_environ(env_name, value):877 """Tests set_environ will set environ values and will restore the environ."""878 environ_copy = copy.deepcopy(os.environ)879 with set_environ(env_name, value):
5 unmodified lines
885def test_set_environ_raises_exception():886 """Tests set_environ will raise exceptions in context when the887 value parameter is None."""888 with pytest.raises(Exception) as exception:803 with set_environ('test1', None):804 raise Exception('Expected exception')889 with set_environ("test1", None):890 raise Exception("Expected exception")891806 assert 'Expected exception' in str(exception.value)892 assert "Expected exception" in str(exception.value)
modified:tests/utils.py-2 removed
1# -*- coding: utf-8 -*-21import contextlib2import os34
13 unmodified lines
modified:.coveragerc+1 added-1 removed
1[run]2omit = requests/packages/*2omit = requests/packages/*
added:.pre-commit-config.yaml+28 added
1exclude: 'docs/|ext/'23repos:4- repo: https://github.com/pre-commit/pre-commit-hooks5 rev: v4.0.16 hooks:7 - id: check-yaml8 - id: debug-statements9 - id: end-of-file-fixer10 - id: trailing-whitespace11- repo: https://github.com/PyCQA/isort12 rev: 5.10.113 hooks:14 - id: isort15- repo: https://github.com/psf/black16 rev: 22.3.017 hooks:18 - id: black19 exclude: tests/test_lowlevel.py20- repo: https://github.com/asottile/pyupgrade21 rev: v2.31.122 hooks:23 - id: pyupgrade24 args: [--py37-plus]25- repo: https://gitlab.com/pycqa/flake826 rev: 4.0.127 hooks:28 - id: flake8
added:pyproject.toml+13 added
1[tool.isort]2profile = "black"3src_paths = ["requests", "test"]4honor_noqa = true56[tool.pytest.ini_options]7addopts = "-p no:warnings --doctest-modules"8doctest_optionflags = "NORMALIZE_WHITESPACE ELLIPSIS"9minversion = "6.2"10testpaths = [11 "requests",12 "tests",13]
deleted:pytest.ini-3 removed
1[pytest]2addopts = -p no:warnings --doctest-modules3doctest_optionflags= NORMALIZE_WHITESPACE ELLIPSIS
modified:setup.cfg+7 added
6 unmodified lines
7 certifi>=2017.4.178 charset_normalizer~=2.0.09 idna>=2.5,<410 urllib3>=1.21.1,<1.271112[flake8]13ignore = E203, E501, W50314per-file-ignores =15 requests/__init__.py:E402, F40116 requests/compat.py:E402, F40117 tests/compat.py:F401
modified:setup.py+56 added-55 removed
1#!/usr/bin/env python2import os3import sys44from codecs import open56from setuptools import setup7from setuptools.command.test import test as TestCommand8109CURRENT_PYTHON = sys.version_info[:2]10REQUIRED_PYTHON = (3, 7)1112if CURRENT_PYTHON < REQUIRED_PYTHON:
13 unmodified lines
26 )27 )28 sys.exit(1)293031class PyTest(TestCommand):33 user_options = [('pytest-args=', 'a', "Arguments to pass into py.test")]32 user_options = [("pytest-args=", "a", "Arguments to pass into py.test")]3334 def initialize_options(self):35 TestCommand.initialize_options(self)36 try:37 from multiprocessing import cpu_count39 self.pytest_args = ['-n', str(cpu_count()), '--boxed']3839 self.pytest_args = ["-n", str(cpu_count()), "--boxed"]40 except (ImportError, NotImplementedError):41 self.pytest_args = ['-n', '1', '--boxed']41 self.pytest_args = ["-n", "1", "--boxed"]4243 def finalize_options(self):44 TestCommand.finalize_options(self)45 self.test_args = []
4 unmodified lines
5051 errno = pytest.main(self.pytest_args)52 sys.exit(errno)535455# 'setup.py publish' shortcut.55if sys.argv[-1] == 'publish':56 os.system('python setup.py sdist bdist_wheel')57 os.system('twine upload dist/*')56if sys.argv[-1] == "publish":57 os.system("python setup.py sdist bdist_wheel")58 os.system("twine upload dist/*")59 sys.exit()6061requires = [61 'charset_normalizer~=2.0.0',62 'idna>=2.5,<4',63 'urllib3>=1.21.1,<1.27',64 'certifi>=2017.4.17',62 "charset_normalizer~=2.0.0",63 "idna>=2.5,<4",64 "urllib3>=1.21.1,<1.27",65 "certifi>=2017.4.17",66]67test_requirements = [67 'pytest-httpbin==0.0.7',68 'pytest-cov',69 'pytest-mock',70 'pytest-xdist',71 'PySocks>=1.5.6, !=1.5.7',72 'pytest>=3',68 "pytest-httpbin==0.0.7",69 "pytest-cov",70 "pytest-mock",71 "pytest-xdist",72 "PySocks>=1.5.6, !=1.5.7",73 "pytest>=3",74]7576about = {}77here = os.path.abspath(os.path.dirname(__file__))77with open(os.path.join(here, 'requests', '__version__.py'), 'r', 'utf-8') as f:78with open(os.path.join(here, "requests", "__version__.py"), "r", "utf-8") as f:79 exec(f.read(), about)8080with open('README.md', 'r', 'utf-8') as f:81with open("README.md", "r", "utf-8") as f:82 readme = f.read()8384setup(84 name=about['__title__'],85 version=about['__version__'],86 description=about['__description__'],85 name=about["__title__"],86 version=about["__version__"],87 description=about["__description__"],88 long_description=readme,88 long_description_content_type='text/markdown',89 author=about['__author__'],90 author_email=about['__author_email__'],91 url=about['__url__'],92 packages=['requests'],93 package_data={'': ['LICENSE', 'NOTICE']},94 package_dir={'requests': 'requests'},89 long_description_content_type="text/markdown",90 author=about["__author__"],91 author_email=about["__author_email__"],92 url=about["__url__"],93 packages=["requests"],94 package_data={"": ["LICENSE", "NOTICE"]},95 package_dir={"requests": "requests"},96 include_package_data=True,97 python_requires=">=3.7, <4",98 install_requires=requires,98 license=about['__license__'],99 license=about["__license__"],100 zip_safe=False,101 classifiers=[101 'Development Status :: 5 - Production/Stable',102 'Environment :: Web Environment',103 'Intended Audience :: Developers',104 'License :: OSI Approved :: Apache Software License',105 'Natural Language :: English',106 'Operating System :: OS Independent',107 'Programming Language :: Python',108 'Programming Language :: Python :: 3',109 'Programming Language :: Python :: 3.7',110 'Programming Language :: Python :: 3.8',111 'Programming Language :: Python :: 3.9',112 'Programming Language :: Python :: 3.10',113 'Programming Language :: Python :: 3.11',114 'Programming Language :: Python :: 3 :: Only',115 'Programming Language :: Python :: Implementation :: CPython',116 'Programming Language :: Python :: Implementation :: PyPy',117 'Topic :: Internet :: WWW/HTTP',118 'Topic :: Software Development :: Libraries',102 "Development Status :: 5 - Production/Stable",103 "Environment :: Web Environment",104 "Intended Audience :: Developers",105 "License :: OSI Approved :: Apache Software License",106 "Natural Language :: English",107 "Operating System :: OS Independent",108 "Programming Language :: Python",109 "Programming Language :: Python :: 3",110 "Programming Language :: Python :: 3.7",111 "Programming Language :: Python :: 3.8",112 "Programming Language :: Python :: 3.9",113 "Programming Language :: Python :: 3.10",114 "Programming Language :: Python :: 3.11",115 "Programming Language :: Python :: 3 :: Only",116 "Programming Language :: Python :: Implementation :: CPython",117 "Programming Language :: Python :: Implementation :: PyPy",118 "Topic :: Internet :: WWW/HTTP",119 "Topic :: Software Development :: Libraries",120 ],120 cmdclass={'test': PyTest},121 cmdclass={"test": PyTest},122 tests_require=test_requirements,123 extras_require={123 'security': [],124 'socks': ['PySocks>=1.5.6, !=1.5.7'],125 'use_chardet_on_py3': ['chardet>=3.0.2,<5']124 "security": [],125 "socks": ["PySocks>=1.5.6, !=1.5.7"],126 "use_chardet_on_py3": ["chardet>=3.0.2,<5"],127 },128 project_urls={128 'Documentation': 'https://requests.readthedocs.io',129 'Source': 'https://github.com/psf/requests',129 "Documentation": "https://requests.readthedocs.io",130 "Source": "https://github.com/psf/requests",131 },132)