Merge remote-tracking branch 'origin/master'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 21010ee, 07ee20d · Browse files · 14 files·+339 added−94 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+339 added−94 removed
- other:+339 added−94 removed
Provenance
- Commit
b2c801f- Tree
b6cc3da- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
21010ee- Parent 2
07ee20d
14 files changed+339 added−94 removed
modified:docs/user/install.rst+2 added-12 removed
8 unmodified lines9 10 Distribute & Pip11 ----------------12 13-Installing Requests is simple with `pip <http://www.pip-installer.org/>`_::13+Installing Requests is simple with `pip <http://www.pip-installer.org/>`_, just run this in your terminal::14 15 $ pip install requests16 17 or, with `easy_install <http://pypi.python.org/pypi/setuptools>`_::2 unmodified lines20 21 But, you really `shouldn't do that <http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install>`_.22 23 24-25-Cheeseshop (PyPI) Mirror26-------------------------27-28-If the Cheeseshop (a.k.a. PyPI) is down, you can also install Requests from one29-of the mirrors. `Crate.io <http://crate.io>`_ is one of them::30-31- $ pip install -i http://simple.crate.io/ requests32-33-24 Get the Code25 ------------26 27 Requests is actively developed on GitHub, where the code is28 `always available <https://github.com/kennethreitz/requests>`_.29 30 You can either clone the public repository::31 42- git clone git://github.com/kennethreitz/requests.git32+ $ git clone git://github.com/kennethreitz/requests.git33 34 Download the `tarball <https://github.com/kennethreitz/requests/tarball/master>`_::35 36 $ curl -OL https://github.com/kennethreitz/requests/tarball/master10 unmodified linesmodified:requests/packages/urllib3/contrib/pyopenssl.py+34 added-11 removed
27 unmodified lines28 Module Variables29 ----------------30 31 :var DEFAULT_SSL_CIPHER_LIST: The list of supported SSL/TLS cipher suites.32- Default: ``EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA25633- EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EDH+aRSA EECDH RC4 !aNULL !eNULL !LOW !3DES34- !MD5 !EXP !PSK !SRP !DSS'``32+ Default: ``ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:33+ ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS``34 35 .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication36 .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)37 3 unmodified lines41 from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName42 import OpenSSL.SSL43 from pyasn1.codec.der import decoder as der_decoder44 from pyasn1.type import univ, constraint46-from socket import _fileobject45+from socket import _fileobject, timeout46 import ssl47 import select48 from cStringIO import StringIO49 17 unmodified lines67 ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER68 + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,69 }70 72-# Default SSL/TLS cipher list.73-# Recommendation by https://community.qualys.com/blogs/securitylabs/2013/08/05/74-# configuring-apache-nginx-and-openssl-for-forward-secrecy75-DEFAULT_SSL_CIPHER_LIST = 'EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM ' + \76- 'EECDH+ECDSA+SHA256 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EDH+aRSA ' + \77- 'EECDH RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS'71+# A secure default.72+# Sources for more information on TLS ciphers:73+#74+# - https://wiki.mozilla.org/Security/Server_Side_TLS75+# - https://www.ssllabs.com/projects/best-practices/index.html76+# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/77+#78+# The general intent is:79+# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),80+# - prefer ECDHE over DHE for better performance,81+# - prefer any AES-GCM over any AES-CBC for better performance and security,82+# - use 3DES as fallback which is secure but slow,83+# - disable NULL authentication, MD5 MACs and DSS for security reasons.84+DEFAULT_SSL_CIPHER_LIST = "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:" + \85+ "ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:" + \86+ "!aNULL:!MD5:!DSS"87 88 89 orig_util_HAS_SNI = util.HAS_SNI90 orig_connection_ssl_wrap_socket = connection.ssl_wrap_socket56 unmodified lines147 148 149 class fileobject(_fileobject):150 151+ def _wait_for_sock(self):152+ rd, wd, ed = select.select([self._sock], [], [],153+ self._sock.gettimeout())154+ if not rd:155+ raise timeout()156+157+158 def read(self, size=-1):159 # Use max, disallow tiny reads in a loop as they are very inefficient.160 # We never leave read() with any leftover data from a new recv() call161 # in our internal buffer.9 unmodified lines171 while True:172 try:173 data = self._sock.recv(rbufsize)174 except OpenSSL.SSL.WantReadError:175+ self._wait_for_sock()176 continue177 if not data:178 break179 buf.write(data)19 unmodified lines199 # fragmentation issues on many platforms.200 try:201 data = self._sock.recv(left)202 except OpenSSL.SSL.WantReadError:203+ self._wait_for_sock()204 continue205 if not data:206 break207 n = len(data)43 unmodified lines251 if not data:252 break253 buffers.append(data)254 except OpenSSL.SSL.WantReadError:255+ self._wait_for_sock()256 continue257 break258 return "".join(buffers)259 2 unmodified lines262 while True:263 try:264 data = self._sock.recv(self._rbufsize)265 except OpenSSL.SSL.WantReadError:266+ self._wait_for_sock()267 continue268 if not data:269 break270 nl = data.find('\n')19 unmodified lines290 while True:291 try:292 data = self._sock.recv(self._rbufsize)293 except OpenSSL.SSL.WantReadError:294+ self._wait_for_sock()274- continue295+ continue296 if not data:297 break298 left = size - buf_len299 # did we just receive a newline?86 unmodified lines386 try:387 ctx.load_verify_locations(ca_certs, None)388 except OpenSSL.SSL.Error as e:389 raise ssl.SSLError('bad ca_certs: %r' % ca_certs, e)390+ else:391+ ctx.set_default_verify_paths()392 393 # Disable TLS compression to migitate CRIME attack (issue #309)394 OP_NO_COMPRESSION = 0x20000395 ctx.set_options(OP_NO_COMPRESSION)18 unmodified linesmodified:requests/packages/urllib3/packages/ssl_match_hostname/__init__.py+1 added-1 removed
5 unmodified lines6 # Backport of the function from a pypi module7 from backports.ssl_match_hostname import CertificateError, match_hostname8 except ImportError:9 # Our vendored copy10- from _implementation import CertificateError, match_hostname10+ from ._implementation import CertificateError, match_hostname11 12 # Not needed, but documenting what we provide.13 __all__ = ('CertificateError', 'match_hostname')modified:requests/packages/urllib3/__init__.py+1 added-1 removed
8 unmodified lines9 """10 11 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12 __license__ = 'MIT'13-__version__ = 'dev'13+__version__ = '1.8'14 15 16 from .connectionpool import (17 HTTPConnectionPool,41 unmodified linesmodified:requests/packages/urllib3/_collections.py+104 added-2 removed
2 unmodified lines3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7-from collections import MutableMapping7+from collections import Mapping, MutableMapping8 try:9 from threading import RLock10 except ImportError: # Platform-specific: No threads available11 class RLock:7 unmodified lines19 try: # Python 2.7+20 from collections import OrderedDict21 except ImportError:22 from .packages.ordered_dict import OrderedDict23+from .packages.six import itervalues24 25 25-__all__ = ['RecentlyUsedContainer']26+__all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict']27 28 29 _Null = object()30 70 unmodified lines101 102 def keys(self):103 with self.lock:104 return self._container.keys()105+106+107+class HTTPHeaderDict(MutableMapping):108+ """109+ :param headers:110+ An iterable of field-value pairs. Must not contain multiple field names111+ when compared case-insensitively.112+113+ :param kwargs:114+ Additional field-value pairs to pass in to ``dict.update``.115+116+ A ``dict`` like container for storing HTTP Headers.117+118+ Field names are stored and compared case-insensitively in compliance with119+ RFC 2616. Iteration provides the first case-sensitive key seen for each120+ case-insensitive pair.121+122+ Using ``__setitem__`` syntax overwrites fields that compare equal123+ case-insensitively in order to maintain ``dict``'s api. For fields that124+ compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``125+ in a loop.126+127+ If multiple fields that are equal case-insensitively are passed to the128+ constructor or ``.update``, the behavior is undefined and some will be129+ lost.130+131+ >>> headers = HTTPHeaderDict()132+ >>> headers.add('Set-Cookie', 'foo=bar')133+ >>> headers.add('set-cookie', 'baz=quxx')134+ >>> headers['content-length'] = '7'135+ >>> headers['SET-cookie']136+ 'foo=bar, baz=quxx'137+ >>> headers['Content-Length']138+ '7'139+140+ If you want to access the raw headers with their original casing141+ for debugging purposes you can access the private ``._data`` attribute142+ which is a normal python ``dict`` that maps the case-insensitive key to a143+ list of tuples stored as (case-sensitive-original-name, value). Using the144+ structure from above as our example:145+146+ >>> headers._data147+ {'set-cookie': [('Set-Cookie', 'foo=bar'), ('set-cookie', 'baz=quxx')],148+ 'content-length': [('content-length', '7')]}149+ """150+151+ def __init__(self, headers=None, **kwargs):152+ self._data = {}153+ if headers is None:154+ headers = {}155+ self.update(headers, **kwargs)156+157+ def add(self, key, value):158+ """Adds a (name, value) pair, doesn't overwrite the value if it already159+ exists.160+161+ >>> headers = HTTPHeaderDict(foo='bar')162+ >>> headers.add('Foo', 'baz')163+ >>> headers['foo']164+ 'bar, baz'165+ """166+ self._data.setdefault(key.lower(), []).append((key, value))167+168+ def getlist(self, key):169+ """Returns a list of all the values for the named field. Returns an170+ empty list if the key doesn't exist."""171+ return self[key].split(', ') if key in self else []172+173+ def copy(self):174+ h = HTTPHeaderDict()175+ for key in self._data:176+ for rawkey, value in self._data[key]:177+ h.add(rawkey, value)178+ return h179+180+ def __eq__(self, other):181+ if not isinstance(other, Mapping):182+ return False183+ other = HTTPHeaderDict(other)184+ return dict((k1, self[k1]) for k1 in self._data) == \185+ dict((k2, other[k2]) for k2 in other._data)186+187+ def __getitem__(self, key):188+ values = self._data[key.lower()]189+ return ', '.join(value[1] for value in values)190+191+ def __setitem__(self, key, value):192+ self._data[key.lower()] = [(key, value)]193+194+ def __delitem__(self, key):195+ del self._data[key.lower()]196+197+ def __len__(self):198+ return len(self._data)199+200+ def __iter__(self):201+ for headers in itervalues(self._data):202+ yield headers[0][0]203+204+ def __repr__(self):205+ return '%s(%r)' % (self.__class__.__name__, dict(self.items()))modified:requests/packages/urllib3/connection.py+32 added-15 removed
2 unmodified lines3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7+import sys8 import socket9 from socket import timeout as SocketTimeout10 11 try: # Python 326 unmodified lines38 from .exceptions import (39 ConnectTimeoutError,40 )41 from .packages.ssl_match_hostname import match_hostname42+from .packages import six43 from .util import (44 assert_fingerprint,45 resolve_cert_reqs,46 resolve_ssl_version,7 unmodified lines54 }55 56 57 class HTTPConnection(_HTTPConnection, object):58+ """59+ Based on httplib.HTTPConnection but provides an extra constructor60+ backwards-compatibility layer between older and newer Pythons.61+ """62+63 default_port = port_by_scheme['http']64 65 # By default, disable Nagle's Algorithm.66 tcp_nodelay = 167 68+ def __init__(self, *args, **kw):69+ if six.PY3: # Python 370+ kw.pop('strict', None)71+72+ if sys.version_info < (2, 7): # Python 2.6 and earlier73+ kw.pop('source_address', None)74+ self.source_address = None75+76+ _HTTPConnection.__init__(self, *args, **kw)77+78 def _new_conn(self):79 """ Establish a socket connection and set nodelay settings on it80 81 :return: a new socket connection82 """66- try:67- conn = socket.create_connection(68- (self.host, self.port),69- self.timeout,70- self.source_address,71- )72- except AttributeError: # Python 2.673- conn = socket.create_connection(74- (self.host, self.port),75- self.timeout,76- )83+ extra_args = []84+ if self.source_address: # Python 2.7+85+ extra_args.append(self.source_address)86+87+ conn = socket.create_connection(88+ (self.host, self.port),89+ self.timeout,90+ *extra_args91+ )92 conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,93 self.tcp_nodelay)94 return conn95 13 unmodified lines109 110 def __init__(self, host, port=None, key_file=None, cert_file=None,111 strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,112 source_address=None):98- try:99- HTTPConnection.__init__(self, host, port, strict, timeout, source_address)100- except TypeError: # Python 2.6101- HTTPConnection.__init__(self, host, port, strict, timeout)113+114+ HTTPConnection.__init__(self, host, port,115+ strict=strict,116+ timeout=timeout,117+ source_address=source_address)118+119 self.key_file = key_file120 self.cert_file = cert_file121 122 def connect(self):73 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+43 added-35 removed
17 unmodified lines18 19 20 from .exceptions import (21 ClosedPoolError,22+ ConnectionError,23 ConnectTimeoutError,24 EmptyPoolError,25 HostChangedError,26 MaxRetryError,143 unmodified lines170 self.num_connections += 1171 log.info("Starting new HTTP connection (%d): %s" %172 (self.num_connections, self.host))173 173- extra_params = {}174- if not six.PY3: # Python 2175- extra_params['strict'] = self.strict176-174 conn = self.ConnectionCls(host=self.host, port=self.port,175 timeout=self.timeout.connect_timeout,179- **extra_params)176+ strict=self.strict)177 if self.proxy is not None:178 # Enable Nagle's algorithm for proxies, to avoid packet179 # fragmentation.180 conn.tcp_nodelay = 053 unmodified lines234 # self.pool is None.235 pass236 except Full:237 # This should never happen if self.block == True241- log.warning("HttpConnectionPool is full, discarding connection: %s"242- % self.host)238+ log.warning(239+ "Connection pool is full, discarding connection: %s" %240+ self.host)241 242 # Connection never got put back into the pool, close it.243 if conn:244 conn.close()166 unmodified lines411 these headers completely replace any pool-specific headers.412 413 :param retries:414 Number of retries to allow before raising a MaxRetryError exception.415+ If `False`, then retries are disabled and any exception is raised416+ immediately.417 418 :param redirect:419 If True, automatically handle redirects (status codes 301, 302,420- 303, 307, 308). Each redirect counts as a retry.420+ 303, 307, 308). Each redirect counts as a retry. Disabling retries421+ will disable redirect, too.422 423 :param assert_same_host:424 If ``True``, will make sure that the host of the pool requests is425 consistent else will raise HostChangedError. When False, you can25 unmodified lines451 """452 if headers is None:453 headers = self.headers454 454- if retries < 0:455+ if retries < 0 and retries is not False:456 raise MaxRetryError(self, url)457 458 if release_conn is None:459 release_conn = response_kw.get('preload_content', True)10 unmodified lines470 if self.scheme == 'http':471 headers = headers.copy()472 headers.update(self.proxy_headers)473 474+ # Must keep the exception bound to a separate variable or else Python 3475+ # complains about UnboundLocalError.476+ err = None477+478 try:479 # Request a connection from the queue480 conn = self._get_conn(timeout=pool_timeout)481 19 unmodified lines501 # ``response.release_conn()`` is called (implicitly by502 # ``response.read()``)503 504 except Empty:500- # Timed out by queue505+ # Timed out by queue.506 raise EmptyPoolError(self, "No pool connections are available.")507 503- except BaseSSLError as e:508+ except (BaseSSLError, CertificateError) as e:509+ # Release connection unconditionally because there is no way to510+ # close it externally in case of exception.511+ release_conn = True512 raise SSLError(e)513 506- except CertificateError as e:507- # Name mismatch508- raise SSLError(e)514+ except (TimeoutError, HTTPException, SocketError) as e:515+ if conn:516+ # Discard the connection for these exceptions. It will be517+ # be replaced during the next _get_conn() call.518+ conn.close()519+ conn = None520 510- except TimeoutError as e:511- # Connection broken, discard.512- conn = None513- # Save the error off for retry logic.514- err = e521+ if not retries:522+ if isinstance(e, TimeoutError):523+ # TimeoutError is exempt from MaxRetryError-wrapping.524+ # FIXME: ... Not sure why. Add a reason here.525+ raise526 516- if retries == 0:517- raise527+ # Wrap unexpected exceptions with the most appropriate528+ # module-level exception and re-raise.529+ if isinstance(e, SocketError) and self.proxy:530+ raise ProxyError('Cannot connect to proxy.', e)531 519- except (HTTPException, SocketError) as e:520- # Connection broken, discard. It will be replaced next _get_conn().521- conn = None522- # This is necessary so we can access e below523- err = e532+ if retries is False:533+ raise ConnectionError('Connection failed.', e)534 525- if retries == 0:526- if isinstance(e, SocketError) and self.proxy is not None:527- raise ProxyError('Cannot connect to proxy. '528- 'Socket error: %s.' % e)529- else:530- raise MaxRetryError(self, url, e)535+ raise MaxRetryError(self, url, e)536 537+ # Keep track of the error for the retry warning.538+ err = e539+540 finally:541 if release_conn:542 # Put the connection back to be reused. If the connection is543 # expired then it will be None, which will get replaced with a1 unmodified line545 self._put_conn(conn)546 547 if not conn:548 # Try again541- log.warn("Retrying (%d attempts remain) after connection "542- "broken by '%r': %s" % (retries, err, url))549+ log.warning("Retrying (%d attempts remain) after connection "550+ "broken by '%r': %s" % (retries, err, url))551 return self.urlopen(method, url, body, headers, retries - 1,552 redirect, assert_same_host,553 timeout=timeout, pool_timeout=pool_timeout,554 release_conn=release_conn, **response_kw)555 556 # Handle redirect?557 redirect_location = redirect and response.get_redirect_location()550- if redirect_location:558+ if redirect_location and retries is not False:559 if response.status == 303:560 method = 'GET'561 log.info("Redirecting %s -> %s" % (url, redirect_location))562 return self.urlopen(method, redirect_location, body, headers,133 unmodified linesmodified:requests/packages/urllib3/exceptions.py+5 added
42 unmodified lines43 "Raised when the connection to a proxy fails."44 pass45 46 47+class ConnectionError(HTTPError):48+ "Raised when a normal connection fails."49+ pass50+51+52 class DecodeError(HTTPError):53 "Raised when automatic decoding based on Content-Type fails."54 pass55 71 unmodified linesmodified:requests/packages/urllib3/response.py+7 added-11 removed
7 unmodified lines8 import logging9 import zlib10 import io11 12+from ._collections import HTTPHeaderDict13 from .exceptions import DecodeError14 from .packages.six import string_types as basestring, binary_type15 from .util import is_fp_closed16 62 unmodified lines79 80 def __init__(self, body='', headers=None, status=0, version=0, reason=None,81 strict=0, preload_content=True, decode_content=True,82 original_response=None, pool=None, connection=None):82- self.headers = headers or {}83+84+ self.headers = HTTPHeaderDict()85+ if headers:86+ self.headers.update(headers)87 self.status = status88 self.version = version89 self.reason = reason90 self.strict = strict161 unmodified lines252 Remaining parameters are passed to the HTTPResponse constructor, along253 with ``original_response=r``.254 """255 252- # Normalize headers between different versions of Python253- headers = {}256+ headers = HTTPHeaderDict()257 for k, v in r.getheaders():255- # Python 3: Header keys are returned capitalised256- k = k.lower()258+ headers.add(k, v)259 258- has_value = headers.get(k)259- if has_value: # Python 3: Repeating header keys are unmerged.260- v = ', '.join([has_value, v])261-262- headers[k] = v263-260 # HTTPResponse objects in Python 3 don't have a .strict attribute261 strict = getattr(r, 'strict', 0)262 return ResponseCls(body=r,263 headers=headers,45 unmodified linesmodified:requests/models.py+1 added-3 removed
406 unmodified lines407 length = None408 409 is_stream = all([410 hasattr(data, '__iter__'),411- not isinstance(data, basestring),412- not isinstance(data, list),413- not isinstance(data, dict)411+ not isinstance(data, (basestring, list, tuple, dict))412 ])413 414 try:415 length = super_len(data)384 unmodified linesmodified:requests/sessions.py+5 added-2 removed
160 unmodified lines161 # Rebuild auth and proxy information.162 proxies = self.rebuild_proxies(prepared_request, proxies)163 self.rebuild_auth(prepared_request, resp)164 165+ # Override the original request.166+ req = prepared_request167+168 resp = self.send(166- prepared_request,169+ req,170 stream=stream,171 timeout=timeout,172 verify=verify,173 cert=cert,411 unmodified lines585 # Insert the first (original) request at the start586 history.insert(0, r)587 # Get the last request made588 r = history.pop()586- r.history = tuple(history)589+ r.history = history590 591 return r592 593 def get_adapter(self, url):37 unmodified linesmodified:requests/utils.py+1 added-1 removed
59 unmodified lines60 else:61 return os.fstat(fileno).st_size62 63 if hasattr(o, 'getvalue'):64- # e.g. BytesIO, cStringIO.StringI64+ # e.g. BytesIO, cStringIO.StringIO65 return len(o.getvalue())66 67 68 def get_netrc_auth(url):600 unmodified linesmodified:HISTORY.rst+5 added
12 unmodified lines13 or not it actually did).14 - The ``timeout`` parameter now affects requests with both ``stream=True`` and15 ``stream=False`` equally.16 17+**Bugfixes**18+19+- No longer expose Authorization or Proxy-Authorization headers on redirect.20+ Fix CVE-2014-1829 and CVE-2014-1830 respectively.21+22 2.2.1 (2014-01-23)23 ++++++++++++++++++24 25 **Bugfixes**762 unmodified linesmodified:test_requests.py+98 added
6 unmodified lines7 import json8 import os9 import pickle10 import unittest11+import collections12 13 import requests14 import pytest15 from requests.adapters import HTTPAdapter3 unmodified lines19 from requests.cookies import cookiejar_from_dict, morsel_to_cookie20 from requests.exceptions import InvalidURL, MissingSchema21 from requests.models import PreparedRequest, Response22 from requests.structures import CaseInsensitiveDict23+from requests.sessions import SessionRedirectMixin24+from requests.models import PreparedRequest, urlencode25+from requests.hooks import default_hooks26 27 try:28 import StringIO29 except ImportError:185 unmodified lines215 urls = [r.url for r in resp.history]216 req_urls = [r.request.url for r in resp.history]217 assert urls == req_urls218 219+ def test_history_is_always_a_list(self):220+ """221+ Show that even with redirects, Response.history is always a list.222+ """223+ resp = requests.get(httpbin('get'))224+ assert isinstance(resp.history, list)225+ resp = requests.get(httpbin('redirect/1'))226+ assert isinstance(resp.history, list)227+ assert not isinstance(resp.history, tuple)228+229 def test_headers_on_session_with_None_are_not_sent(self):230 """Do not send headers in Session.headers with None values."""231 ses = requests.Session()232 ses.headers['Accept-Encoding'] = None984 unmodified lines1217 except requests.exceptions.Timeout as e:1218 assert 'Read timed out' in e.args[0].args[0]1219 1220 1221+SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))1222+1223+1224+class RedirectSession(SessionRedirectMixin):1225+ def __init__(self, order_of_redirects):1226+ self.redirects = order_of_redirects1227+ self.calls = []1228+ self.max_redirects = 301229+ self.cookies = {}1230+ self.trust_env = False1231+1232+ def send(self, *args, **kwargs):1233+ self.calls.append(SendCall(args, kwargs))1234+ return self.build_response()1235+1236+ def build_response(self):1237+ request = self.calls[-1].args[0]1238+ r = requests.Response()1239+1240+ try:1241+ r.status_code = int(self.redirects.pop(0))1242+ except IndexError:1243+ r.status_code = 2001244+1245+ r.headers = CaseInsensitiveDict({'Location': '/'})1246+ r.raw = self._build_raw()1247+ r.request = request1248+ return r1249+1250+ def _build_raw(self):1251+ string = StringIO.StringIO('')1252+ setattr(string, 'release_conn', lambda *args: args)1253+ return string1254+1255+1256+class TestRedirects:1257+ default_keyword_args = {1258+ 'stream': False,1259+ 'verify': True,1260+ 'cert': None,1261+ 'timeout': None,1262+ 'allow_redirects': False,1263+ 'proxies': {},1264+ }1265+1266+ def test_requests_are_updated_each_time(self):1267+ session = RedirectSession([303, 307])1268+ prep = requests.Request('POST', 'http://httpbin.org/post').prepare()1269+ r0 = session.send(prep)1270+ assert r0.request.method == 'POST'1271+ assert session.calls[-1] == SendCall((r0.request,), {})1272+ redirect_generator = session.resolve_redirects(r0, prep)1273+ for response in redirect_generator:1274+ assert response.request.method == 'GET'1275+ send_call = SendCall((response.request,),1276+ TestRedirects.default_keyword_args)1277+ assert session.calls[-1] == send_call1278+1279+1280+@pytest.fixture1281+def list_of_tuples():1282+ return [1283+ (('a', 'b'), ('c', 'd')),1284+ (('c', 'd'), ('a', 'b')),1285+ (('a', 'b'), ('c', 'd'), ('e', 'f')),1286+ ]1287+1288+1289+def test_data_argument_accepts_tuples(list_of_tuples):1290+ """1291+ Ensure that the data argument will accept tuples of strings1292+ and properly encode them.1293+ """1294+ for data in list_of_tuples:1295+ p = PreparedRequest()1296+ p.prepare(1297+ method='GET',1298+ url='http://www.example.com',1299+ data=data,1300+ hooks=default_hooks()1301+ )1302+ assert p.body == urlencode(data)1303+ 1304+1305 if __name__ == '__main__':1306 unittest.main()