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 d7e8073, 65a0fd8 · Browse files · 22 files·+269 added−70 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
22 files+269 added−70 removed
- other:+269 added−70 removed
Provenance
- Commit
e0df216- Tree
89c6591- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
d7e8073- Parent 2
65a0fd8
22 files changed+269 added−70 removed
modified:docs/_templates/sidebarintro.html+1 added-2 removed
9 unmodified lines101112131415141516171837 unmodified lines9 unmodified lines</p>
<p> Requests is an elegant and simple HTTP library for Python, built for human beings. You are currently looking at the documentation of the development release. human beings.</p>
<h3>Donate</h3>37 unmodified linesmodified:docs/dev/todo.rst+5 added
51 unmodified lines52 Are you crazy?53 --------------54 55 - SPDY support would be awesome. No C extensions.56+57+Downstream Repackaging58+--------------------59+60+If you are repackaging Requests, please note that you must also redistribute the ``cacerts.pem`` file in order to get correct SSL functionality.modified:docs/user/advanced.rst+20 added-2 removed
47 unmodified lines48 Request and Response Objects49 ----------------------------50 51 Whenever a call is made to requests.*() you are doing two major things. First,52-you are constructing a ``Request`` object which will be sent of to a server52+you are constructing a ``Request`` object which will be sent off to a server53 to request or query some resource. Second, a ``Response`` object is generated54 once ``requests`` gets a response back from the server. The response object55 contains all of the information returned by the server and also contains the56 ``Request`` object you created originally. Here is a simple request to get some210 unmodified lines267 268 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))269 <Response [200]>270 271+.. _streaming-requests272+273 Streaming Requests274 ------------------275 276 With ``requests.Response.iter_lines()`` you can easily iterate over streaming3 unmodified lines280 281 import json282 import requests283 282- r = requests.post('http://httpbin.org/stream/20', stream=True)284+ r = requests.get('http://httpbin.org/stream/20', stream=True)285 286 for line in r.iter_lines():287 288 # filter out keep-alive new lines286 unmodified lines575 576 .. _`described here`: http://kennethreitz.org/exposures/the-future-of-python-http577 .. _`urllib3`: https://github.com/shazow/urllib3578 579+Blocking Or Non-Blocking?580+-------------------------581+582+With the default Transport Adapter in place, Requests does not provide any kind583+of non-blocking IO. The ``Response.content`` property will block until the584+entire response has been downloaded. If you require more granularity, the585+streaming features of the library (see :ref:`streaming-requests`) allow you to586+retrieve smaller quantities of the response at a time. However, these calls587+will still block.588+589+If you are concerned about the use of blocking IO, there are lots of projects590+out there that combine Requests with one of Python's asynchronicity frameworks.591+Two excellent examples are `grequests`_ and `requests-futures`_.592+593+.. _`grequests`: https://github.com/kennethreitz/grequests594+.. _`requests-futures`: https://github.com/ross/requests-futuresmodified:docs/user/quickstart.rst+7 added-6 removed
258 unmodified lines259 260 >>> r.status_code == requests.codes.ok261 True262 263-If we made a bad request (non-200 response), we can raise it with263+If we made a bad request (a 4XX client error or 5XX server error response), we can raise it with264 :class:`Response.raise_for_status()`::265 266 >>> bad_r = requests.get('http://httpbin.org/status/404')267 >>> bad_r.status_code130 unmodified lines398 Errors and Exceptions399 ---------------------400 401 In the event of a network problem (e.g. DNS failure, refused connection, etc),402-Requests will raise a :class:`ConnectionError` exception.402+Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.403 404-In the event of the rare invalid HTTP response, Requests will raise405-an :class:`HTTPError` exception.404+In the event of the rare invalid HTTP response, Requests will raise an405+:class:`~requests.exceptions.HTTPError` exception.406 407-If a request times out, a :class:`Timeout` exception is raised.407+If a request times out, a :class:`~requests.exceptions.Timeout` exception is408+raised.409 410 If a request exceeds the configured number of maximum redirections, a410-:class:`TooManyRedirects` exception is raised.411+:class:`~requests.exceptions.TooManyRedirects` exception is raised.412 413 All exceptions that Requests explicitly raises inherit from414 :class:`requests.exceptions.RequestException`.415 3 unmodified linesmodified:requests/packages/urllib3/contrib/ntlmpool.py+1 added-1 removed
31 unmodified lines32 33 def __init__(self, user, pw, authurl, *args, **kwargs):34 """35 authurl is a random URL on the server that is protected by NTLM.36- user is the Windows user, probably in the DOMAIN\username format.36+ user is the Windows user, probably in the DOMAIN\\username format.37 pw is the password for the user.38 """39 super(NTLMConnectionPool, self).__init__(*args, **kwargs)40 self.authurl = authurl80 unmodified linesmodified:requests/packages/urllib3/contrib/pyopenssl.py+3 added
113 unmodified lines114 115 def sendall(self, data):116 return self.connection.sendall(data)117 118+ def close(self):119+ return self.connection.shutdown()120+121 def getpeercert(self, binary_form=False):122 x509 = self.connection.get_peer_certificate()123 if not x509:124 raise ssl.SSLError('')46 unmodified linesmodified:requests/packages/urllib3/connectionpool.py+2 added-1 removed
108 unmodified lines109 if resolved_cert_reqs != ssl.CERT_NONE:110 if self.assert_fingerprint:111 assert_fingerprint(self.sock.getpeercert(binary_form=True),112 self.assert_fingerprint)113- else:113+ elif self.assert_hostname is not False:114 match_hostname(self.sock.getpeercert(),115 self.assert_hostname or self.host)116 117 ## Pool objects394 unmodified lines512 instead of :class:`httplib.HTTPSConnection`.513 514 :class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,515 ``assert_hostname`` and ``host`` in this order to verify connections.516+ If ``assert_hostname`` is False, no verification is done.517 518 The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs`` and519 ``ssl_version`` are only used if :mod:`ssl` is available and are fed into520 :meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket78 unmodified linesmodified:requests/packages/urllib3/filepost.py+1 added-1 removed
1 # urllib3/filepost.py2-# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 92 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+9 added
4 unmodified lines5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7 import logging8 9+try: # Python 310+ from urllib.parse import urljoin11+except ImportError:12+ from urlparse import urljoin13+14 from ._collections import RecentlyUsedContainer15 from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool16 from .connectionpool import connection_from_url, port_by_scheme17 from .request import RequestMethods131 unmodified lines149 redirect_location = redirect and response.get_redirect_location()150 if not redirect_location:151 return response152 153+ # Support relative URLs for redirecting.154+ redirect_location = urljoin(url, redirect_location)155+156+ # RFC 2616, Section 10.3.4157 if response.status == 303:158 method = 'GET'159 160 log.info("Redirecting %s -> %s" % (url, redirect_location))41 unmodified linesmodified:requests/packages/urllib3/request.py+1 added-1 removed
28 unmodified lines29 :meth:`.request_encode_url` is for sending requests whose fields are encoded30 in the URL (such as GET, HEAD, DELETE).31 32 :meth:`.request_encode_body` is for sending requests whose fields are33- encoded in the *body* of the request using multipart or www-orm-urlencoded33+ encoded in the *body* of the request using multipart or www-form-urlencoded34 (such as for POST, PUT, PATCH).35 36 :meth:`.request` is for making any kind of request, it will look up the37 appropriate encoding format and use one of the above two methods to make105 unmodified linesmodified:requests/packages/urllib3/response.py+59 added-2 removed
1 # urllib3/response.py2-# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2+# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7 8 import logging9 import zlib10+import io11 12 from .exceptions import DecodeError13 from .packages.six import string_types as basestring, binary_type14+from .util import is_fp_closed15 16 17 log = logging.getLogger(__name__)18 30 unmodified lines49 50 return DeflateDecoder()51 52 51-class HTTPResponse(object):53+class HTTPResponse(io.IOBase):54 """55 HTTP Response container.56 57 Backwards-compatible to httplib's HTTPResponse but the response ``body`` is143 unmodified lines201 finally:202 if self._original_response and self._original_response.isclosed():203 self.release_conn()204 205+ def stream(self, amt=2**16, decode_content=None):206+ """207+ A generator wrapper for the read() method. A call will block until208+ ``amt`` bytes have been read from the connection or until the209+ connection is closed.210+211+ :param amt:212+ How much of the content to read. The generator will return up to213+ much data per iteration, but may return less. This is particularly214+ likely when using compressed data. However, the empty string will215+ never be returned.216+217+ :param decode_content:218+ If True, will attempt to decode the body based on the219+ 'content-encoding' header.220+ """221+ while not is_fp_closed(self._fp):222+ data = self.read(amt=amt, decode_content=decode_content)223+224+ if data:225+ yield data226+227+228 @classmethod229 def from_httplib(ResponseCls, r, **response_kw):230 """231 Given an :class:`httplib.HTTPResponse` instance ``r``, return a31 unmodified lines263 return self.headers264 265 def getheader(self, name, default=None):266 return self.headers.get(name, default)267+268+ # Overrides from io.IOBase269+ def close(self):270+ if not self.closed:271+ self._fp.close()272+273+ @property274+ def closed(self):275+ if self._fp is None:276+ return True277+ elif hasattr(self._fp, 'closed'):278+ return self._fp.closed279+ elif hasattr(self._fp, 'isclosed'): # Python 2280+ return self._fp.isclosed()281+ else:282+ return True283+284+ def fileno(self):285+ if self._fp is None:286+ raise IOError("HTTPResponse has no file to get a fileno from")287+ elif hasattr(self._fp, "fileno"):288+ return self._fp.fileno()289+ else:290+ raise IOError("The file-like object this HTTPResponse is wrapped "291+ "around has no file descriptor")292+293+ def flush(self):294+ if self._fp is not None and hasattr(self._fp, 'flush'):295+ return self._fp.flush()296+297+ def readable(self):298+ return Truemodified:requests/packages/urllib3/util.py+14 added-1 removed
29 unmodified lines30 from ssl import HAS_SNI # Has SNI?31 except ImportError:32 pass33 34-34 from .packages import six35 from .exceptions import LocationParseError, SSLError36 37 301 unmodified lines339 raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'340 .format(hexlify(fingerprint_bytes),341 hexlify(cert_digest)))342 343+def is_fp_closed(obj):344+ """345+ Checks whether a given file-like object is closed.346 347+ :param obj:348+ The file-like object to check.349+ """350+ if hasattr(obj, 'fp'):351+ # Object is a container for another file-like object that gets released352+ # on exhaustion (e.g. HTTPResponse)353+ return obj.fp is None354+355+ return obj.closed356+357+358 if SSLContext is not None: # Python 3.2+359 def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,360 ca_certs=None, server_hostname=None,361 ssl_version=None):30 unmodified linesmodified:requests/adapters.py+4 added-4 removed
116 unmodified lines117 :param url: The requested URL.118 :param verify: Whether we should actually verify the certificate.119 :param cert: The SSL certificate to verify.120 """121- if url.startswith('https') and verify:121+ if url.lower().startswith('https') and verify:122 123 cert_loc = None124 125 # Allow self-specified cert location.63 unmodified lines189 :param url: The URL to connect to.190 :param proxies: (optional) A Requests-style dictionary of proxies used on this request.191 """192 proxies = proxies or {}193- proxy = proxies.get(urlparse(url).scheme)193+ proxy = proxies.get(urlparse(url.lower()).scheme)194 195 if proxy:196- proxy = prepend_scheme_if_needed(proxy, urlparse(url).scheme)196+ proxy = prepend_scheme_if_needed(proxy, urlparse(url.lower()).scheme)197 conn = ProxyManager(self.poolmanager.connection_from_url(proxy))198 else:199- conn = self.poolmanager.connection_from_url(url)199+ conn = self.poolmanager.connection_from_url(url.lower())200 201 return conn202 203 def close(self):139 unmodified linesmodified:requests/compat.py+2 added-2 removed
81 unmodified lines82 # Specifics83 # ---------84 85 if is_py2:86- from urllib import quote, unquote, quote_plus, unquote_plus, urlencode86+ from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass87 from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag88 from urllib2 import parse_http_list89 import cookielib90 from Cookie import Morsel8 unmodified lines99 100 101 elif is_py3:102 from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag103- from urllib.request import parse_http_list103+ from urllib.request import parse_http_list, getproxies, proxy_bypass104 from http import cookiejar as cookielib105 from http.cookies import Morsel106 from io import StringIO107 from collections import OrderedDict6 unmodified linesmodified:requests/cookies.py+15 added-5 removed
4 unmodified lines5 6 requests.utils imports from here, so be careful with imports.7 """8 9+import time10 import collections11 from .compat import cookielib, urlparse, Morsel12 13 try:244 unmodified lines258 def __delitem__(self, name):259 """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name()."""260 remove_cookie_by_name(self, name)261 262+ def set_cookie(self, cookie, *args, **kwargs):263+ if cookie.value.startswith('"') and cookie.value.endswith('"'):264+ cookie.value = cookie.value.replace('\\"', '')265+ return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)266+267 def update(self, other):268 """Updates this jar with cookies from another CookieJar or dict-like"""269 if isinstance(other, cookielib.CookieJar):270 for cookie in other:88 unmodified lines359 360 361 def morsel_to_cookie(morsel):362 """Convert a Morsel object into a Cookie containing the one k/v pair."""363+ expires = None364+ if morsel["max-age"]:365+ expires = time.time() + morsel["max-age"]366+ elif morsel['expires']:367+ expires = morsel['expires']368+ if type(expires) == type(""):369+ time_template = "%a, %d-%b-%Y %H:%M:%S GMT"370+ expires = time.mktime(time.strptime(expires, time_template))371 c = create_cookie(372 name=morsel.key,373 value=morsel.value,374 version=morsel['version'] or 0,375 port=None,362- port_specified=False,376 domain=morsel['domain'],364- domain_specified=bool(morsel['domain']),365- domain_initial_dot=morsel['domain'].startswith('.'),377 path=morsel['path'],367- path_specified=bool(morsel['path']),378 secure=bool(morsel['secure']),369- expires=morsel['max-age'] or morsel['expires'],379+ expires=expires,380 discard=False,381 comment=morsel['comment'],382 comment_url=bool(morsel['comment']),383 rest={'HttpOnly': morsel['httponly']},16 unmodified linesmodified:requests/models.py+14 added-7 removed
362 unmodified lines363 364 try:365 length = super_len(data)366 except (TypeError, AttributeError):367- length = False367+ length = None368 369 if is_stream:370 body = data371 372 if files:373 raise NotImplementedError('Streamed bodies and files are mutually exclusive.')374 375- if length:375+ if length is not None:376 self.headers['Content-Length'] = str(length)377 else:378 self.headers['Transfer-Encoding'] = 'chunked'379 # Check if file, fo, generator, iterator.156 unmodified lines536 # simulate reading small chunks of the content537 return iter_slices(self._content, chunk_size)538 539 def generate():540+ try:541+ # Special case for urllib3.542+ for chunk in self.raw.stream(chunk_size, decode_content=True):543+ yield chunk544+ except AttributeError:545+ # Standard file-like object.540- while 1:541- chunk = self.raw.read(chunk_size, decode_content=True)542- if not chunk:543- break544- yield chunk546+ while 1:547+ chunk = self.raw.read(chunk_size)548+ if not chunk:549+ break550+ yield chunk551+552 self._content_consumed = True553 554 gen = generate()555 138 unmodified linesmodified:requests/sessions.py+15 added-12 removed
69 unmodified lines70 verify=True, cert=None, proxies=None):71 """Receives a Response. Returns a generator of Responses."""72 73 i = 074- prepared_request = PreparedRequest()75- prepared_request.body = req.body76- prepared_request.headers = req.headers.copy()77- prepared_request.hooks = req.hooks78- prepared_request.method = req.method79- prepared_request.url = req.url74 75 # ((resp.status_code is codes.see_other))76 while (('location' in resp.headers and resp.status_code in REDIRECT_STATI)):77+ prepared_request = PreparedRequest()78+ prepared_request.body = req.body79+ prepared_request.headers = req.headers.copy()80+ prepared_request.hooks = req.hooks81 82 resp.content # Consume socket so it can be released83 84 if i >= self.max_redirects:2 unmodified lines87 # Release the connection back into the pool.88 resp.close()89 90 url = resp.headers['location']93- method = prepared_request.method91+ method = req.method92 93 # Handle redirection without scheme (see: RFC 1808 Section 4)94 if url.startswith('//'):95 parsed_rurl = urlparse(resp.url)96 url = '%s:%s' % (parsed_rurl.scheme, url)97 98+ # The scheme should be lower case...99+ if '://' in url:100+ scheme, uri = url.split('://', 1)101+ url = '%s://%s' % (scheme.lower(), uri)102+103 # Facilitate non-RFC2616-compliant 'location' headers104 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')105 # Compliant with RFC3986, we percent encode the url.106 if not urlparse(url).netloc:4 unmodified lines111 prepared_request.url = url112 113 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4114 if (resp.status_code == codes.see_other and112- prepared_request.method != 'HEAD'):115+ method != 'HEAD'):116 method = 'GET'117 118 # Do what the browsers do, despite standards...119 if (resp.status_code in (codes.moved, codes.found) and117- prepared_request.method not in ('GET', 'HEAD')):120+ method not in ('GET', 'HEAD')):121 method = 'GET'122 123 prepared_request.method = method124 163 unmodified lines288 env_proxies = get_environ_proxies(url) or {}289 for (k, v) in env_proxies.items():290 proxies.setdefault(k, v)291 289- # Set environment's basic authentication.290- if not auth:292+ # Set environment's basic authentication if not explicitly set.293+ if not auth and not self.auth:294 auth = get_netrc_auth(url)295 296 # Look for configuration.297 if not verify and verify is not False:171 unmodified lines469 def get_adapter(self, url):470 """Returns the appropriate connnection adapter for the given URL."""471 for (prefix, adapter) in self.adapters.items():472 470- if url.startswith(prefix):473+ if url.lower().startswith(prefix):474 return adapter475 476 # Nothing matches :-/477 raise InvalidSchema("No connection adapters were found for '%s'" % url)27 unmodified linesmodified:requests/status_codes.py+2 added-1 removed
16 unmodified lines17 204: ('no_content',),18 205: ('reset_content', 'reset'),19 206: ('partial_content', 'partial'),20 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),21- 208: ('im_used',),21+ 208: ('already_reported',),22+ 226: ('im_used',),23 24 # Redirection.25 300: ('multiple_choices',),26 301: ('moved_permanently', 'moved', '\\o-'),62 unmodified linesmodified:requests/utils.py+14 added-16 removed
20 unmodified lines21 from . import __version__22 from . import certs23 from .compat import parse_http_list as _parse_list_header24 from .compat import quote, urlparse, bytes, str, OrderedDict, urlunparse25+from .compat import getproxies, proxy_bypass26 from .cookies import RequestsCookieJar, cookiejar_from_dict27 from .structures import CaseInsensitiveDict28 29 _hush_pyflakes = (RequestsCookieJar,)271 unmodified lines301 for chunk in iterator:302 rv = decoder.decode(chunk)303 if rv:304 yield rv304- rv = decoder.decode('', final=True)305+ rv = decoder.decode(b'', final=True)306 if rv:307 yield rv308 309 76 unmodified lines386 387 def get_environ_proxies(url):388 """Return a dict of environment proxies."""389 389- proxy_keys = [390- 'all',391- 'http',392- 'https',393- 'ftp',394- 'socks'395- ]396-390 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())391 392 # First check whether no_proxy is defined. If it is, check that the URL393 # we're getting isn't in the no_proxy list.394 no_proxy = get_proxy('no_proxy')395+ netloc = urlparse(url).netloc402-396+ 397 if no_proxy:398 # We need to check whether we match here. We need to see if we match399 # the end of the netloc, both with and without the port.400 no_proxy = no_proxy.split(',')407- netloc = urlparse(url).netloc408-401+ 402 for host in no_proxy:403 if netloc.endswith(host) or netloc.split(':')[0].endswith(host):404 # The URL does match something in no_proxy, so we don't want405 # to apply the proxies on this URL.406 return {}407+ 408+ # If the system proxy settings indicate that this URL should be bypassed,409+ # don't proxy.410+ if proxy_bypass(netloc):411+ return {}412 413 # If we get here, we either didn't have no_proxy set or we're not going416- # anywhere that no_proxy applies to.417- proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys]418- return dict([(key, val) for (key, val) in proxies if val])414+ # anywhere that no_proxy applies to, and the system settings don't require415+ # bypassing the proxy for the current URL.416+ return getproxies()417+ 418 420-419 def default_user_agent():420 """Return a string representing the default user agent."""421 _implementation = platform.python_implementation()422 126 unmodified linesmodified:AUTHORS.rst+4 added
123 unmodified lines124 - Wilfred Hughes <me@wilfred.me.uk> @dontYetKnow125 - Dmitry Medvinsky <me@dmedvinsky.name>126 - Bryce Boe <bbzbryce@gmail.com> @bboe127 - Colin Dunklau <colin.dunklau@gmail.com> @cdunklau128+- Bob Carroll <bob.carroll@alum.rit.edu> @rcarz129 - Hugo Osvaldo Barrera <hugo@osvaldobarrera.com.ar> @hobarrera130 - Łukasz Langa <lukasz@langa.pl> @llanga131 - Dave Shawley <daveshawley@gmail.com>132+- James Clarke (jam)133+- Kevin Burke <kev@inburke.com>134+- Flavio Curelladeleted:invokefile.py-5 removed
1-from invoke import run, task2-3-@task4-def build():5- print("Building!")modified:test_requests.py+76 added-1 removed
85 unmodified lines86 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()87 self.assertEqual(request.url,88 "http://example.com/path?key=value&a=b#fragment")89 90+ def test_mixed_case_scheme_acceptable(self):91+ s = requests.Session()92+ r = requests.Request('GET', 'http://httpbin.org/get')93+ r = s.send(r.prepare())94+ self.assertEqual(r.status_code,200)95+ s = requests.Session()96+ r = requests.Request('GET', 'HTTP://httpbin.org/get')97+ r = s.send(r.prepare())98+ self.assertEqual(r.status_code,200)99+ r = requests.Request('GET', 'hTTp://httpbin.org/get')100+ r = s.send(r.prepare())101+ self.assertEqual(r.status_code,200)102+ r = requests.Request('GET', 'HttP://httpbin.org/get')103+ r = s.send(r.prepare())104+ self.assertEqual(r.status_code,200)105+ r = requests.Request('GET', 'https://httpbin.org/get')106+ r = s.send(r.prepare())107+ self.assertEqual(r.status_code,200)108+ r = requests.Request('GET', 'HTTPS://httpbin.org/get')109+ r = s.send(r.prepare())110+ self.assertEqual(r.status_code,200)111+ r = requests.Request('GET', 'hTTps://httpbin.org/get')112+ r = s.send(r.prepare())113+ self.assertEqual(r.status_code,200)114+ r = requests.Request('GET', 'HttPs://httpbin.org/get')115+ r = s.send(r.prepare())116+ self.assertEqual(r.status_code,200)117+118 def test_HTTP_200_OK_GET_ALTERNATIVE(self):119 r = requests.Request('GET', httpbin('get'))120 s = requests.Session()121 47 unmodified lines169 }170 )171 assert 'foo' not in s.cookies172 173+ def test_cookie_quote_wrapped(self):174+ s = requests.session()175+ s.get(httpbin('cookies/set?foo="bar:baz"'))176+ self.assertTrue(s.cookies['foo'] == '"bar:baz"')177+178 def test_request_cookie_overrides_session_cookie(self):179 s = requests.session()180 s.cookies['foo'] = 'bar'181 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})10 unmodified lines192 # Make sure the cookie was sent193 assert r.json()['cookies']['foo'] == 'bar'194 # Make sure the session cj is still the custom one195 assert s.cookies is cj163-196+ 197+ def test_requests_in_history_are_not_overridden(self):198+ resp = requests.get(httpbin('redirect/3'))199+ urls = [r.url for r in resp.history]200+ req_urls = [r.request.url for r in resp.history]201+ self.assertEquals(urls, req_urls)202+ 203 def test_user_agent_transfers(self):204 205 heads = {206 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'31 unmodified lines238 s.auth = auth239 r = s.get(url)240 self.assertEqual(r.status_code, 200)241 242+ def test_basicauth_with_netrc(self):243+ auth = ('user', 'pass')244+ wrong_auth = ('wronguser', 'wrongpass')245+ url = httpbin('basic-auth', 'user', 'pass')246+247+ def get_netrc_auth_mock(url):248+ return auth249+ requests.sessions.get_netrc_auth = get_netrc_auth_mock250+251+ # Should use netrc and work.252+ r = requests.get(url)253+ self.assertEqual(r.status_code, 200)254+255+ # Given auth should override and fail.256+ r = requests.get(url, auth=wrong_auth)257+ self.assertEqual(r.status_code, 401)258+259+ s = requests.session()260+ 261+ # Should use netrc and work.262+ r = s.get(url)263+ self.assertEqual(r.status_code, 200)264+265+ # Given auth should override and fail.266+ s.auth = wrong_auth267+ r = s.get(url)268+ self.assertEqual(r.status_code, 401)269+270 def test_DIGEST_HTTP_200_OK_GET(self):271 272 auth = HTTPDigestAuth('user', 'pass')273 url = httpbin('digest-auth', 'auth', 'user', 'pass')288 unmodified lines562 headers['ACCEPT'.encode('ascii')],563 'application/json'564 )565 566+ def test_uppercase_scheme(self):567+ r = requests.get('HTTP://example.com/')568+ self.assertEqual(r.status_code, 200)569+570+ def test_uppercase_scheme_redirect(self):571+ r = requests.get(httpbin('redirect-to'), params={'url': 'HTTP://example.com/'})572+ self.assertEqual(r.status_code, 200)573+574 def test_transport_adapter_ordering(self):575 s = requests.Session()576 order = ['https://', 'http://']577 self.assertEqual(order, list(s.adapters))204 unmodified lines