Merge remote-tracking branch 'upstream/develop' into develop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Idan Gazit · committed by Idan Gazit · parents 324336e, 53d60ca · Browse files · 13 files·+563 added−135 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+563 added−135 removed
- tests:+202 added−8 removed
- other:+361 added−127 removed
Provenance
- Commit
cf6b204- Tree
6dc0af2- Author
Idan Gazit <idan@gazit.me>- Committer
Idan Gazit <idan@gazit.me>- Parent 1
324336e- Parent 2
53d60ca
13 files changed+563 added−135 removed
modified:docs/user/quickstart.rst+2 added-2 removed
300 unmodified lines301 302 >>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'303 >>> r = requests.get(url)304 305- >>> print r.cookies306- {'requests-is': 'awesome'}305+ >>> r.cookies['requests-is']306+ 'awesome'307 308 To send your own cookies to the server, you can use the ``cookies``309 parameter::310 122 unmodified linesmodified:requests/compat.py+2 added-2 removed
81 unmodified lines82 from urllib import quote, unquote, urlencode83 from urlparse import urlparse, urlunparse, urljoin, urlsplit84 from urllib2 import parse_http_list85 import cookielib86- from .packages.oreos.monkeys import SimpleCookie86+ from Cookie import Morsel87 from StringIO import StringIO88 89 bytes = str90 str = unicode4 unmodified lines95 elif is_py3:96 from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote97 from urllib.request import parse_http_list98 from http import cookiejar as cookielib99- from http.cookies import SimpleCookie99+ from http.cookies import Morsel100 from io import StringIO101 102 str = str103 bytes = bytes2 unmodified linesadded:requests/cookies.py+264 added
1+"""2+Compatibility code to be able to use `cookielib.CookieJar` with requests.3+4+requests.utils imports from here, so be careful with imports.5+"""6+7+import collections8+from .compat import cookielib, urlparse, Morsel9+10+try:11+ import threading12+ # grr, pyflakes: this fixes "redefinition of unused 'threading'"13+ threading14+except ImportError:15+ import dummy_threading as threading16+17+class MockRequest(object):18+ """Wraps a `requests.Request` to mimic a `urllib2.Request`.19+20+ The code in `cookielib.CookieJar` expects this interface in order to correctly21+ manage cookie policies, i.e., determine whether a cookie can be set, given the22+ domains of the request and the cookie.23+24+ The original request object is read-only. The client is responsible for collecting25+ the new headers via `get_new_headers()` and interpreting them appropriately. You26+ probably want `get_cookie_header`, defined below.27+ """28+29+ def __init__(self, request):30+ self._r = request31+ self._new_headers = {}32+33+ def get_type(self):34+ return urlparse(self._r.full_url).scheme35+36+ def get_host(self):37+ return urlparse(self._r.full_url).netloc38+39+ def get_origin_req_host(self):40+ if self._r.response.history:41+ r = self._r.response.history[0]42+ return urlparse(r).netloc43+ else:44+ return self.get_host()45+46+ def get_full_url(self):47+ return self._r.full_url48+49+ def is_unverifiable(self):50+ # unverifiable == redirected51+ return bool(self._r.response.history)52+53+ def has_header(self, name):54+ return name in self._r.headers or name in self._new_headers55+56+ def get_header(self, name, default=None):57+ return self._r.headers.get(name, self._new_headers.get(name, default))58+59+ def add_header(self, key, val):60+ """cookielib has no legitimate use for this method; add it back if you find one."""61+ raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")62+63+ def add_unredirected_header(self, name, value):64+ self._new_headers[name] = value65+66+ def get_new_headers(self):67+ return self._new_headers68+69+class MockResponse(object):70+ """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.71+72+ ...what? Basically, expose the parsed HTTP headers from the server response73+ the way `cookielib` expects to see them.74+ """75+76+ def __init__(self, headers):77+ """Make a MockResponse for `cookielib` to read.78+79+ :param headers: a httplib.HTTPMessage or analogous carrying the headers80+ """81+ self._headers = headers82+83+ def info(self):84+ return self._headers85+86+ def getheaders(self, name):87+ self._headers.getheaders(name)88+89+def extract_cookies_to_jar(jar, request, response):90+ """Extract the cookies from the response into a CookieJar.91+92+ :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)93+ :param request: our own requests.Request object94+ :param response: urllib3.HTTPResponse object95+ """96+ # the _original_response field is the wrapped httplib.HTTPResponse object,97+ # and in safe mode, it may be None if the request didn't actually complete.98+ # in that case, just skip the cookie extraction.99+ if response._original_response is not None:100+ req = MockRequest(request)101+ # pull out the HTTPMessage with the headers and put it in the mock:102+ res = MockResponse(response._original_response.msg)103+ jar.extract_cookies(res, req)104+105+def get_cookie_header(jar, request):106+ """Produce an appropriate Cookie header string to be sent with `request`, or None."""107+ r = MockRequest(request)108+ jar.add_cookie_header(r)109+ return r.get_new_headers().get('Cookie')110+111+def remove_cookie_by_name(cookiejar, name, domain=None, path=None):112+ """Unsets a cookie by name, by default over all domains and paths.113+114+ Wraps CookieJar.clear(), is O(n).115+ """116+ clearables = []117+ for cookie in cookiejar:118+ if cookie.name == name:119+ if domain is None or domain == cookie.domain:120+ if path is None or path == cookie.path:121+ clearables.append((cookie.domain, cookie.path, cookie.name))122+123+ for domain, path, name in clearables:124+ cookiejar.clear(domain, path, name)125+126+class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):127+ """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface.128+129+ This is the CookieJar we create by default for requests and sessions that130+ don't specify one, since some clients may expect response.cookies and131+ session.cookies to support dict operations.132+133+ Don't use the dict interface internally; it's just for compatibility with134+ with external client code. All `requests` code should work out of the box135+ with externally provided instances of CookieJar, e.g., LWPCookieJar and136+ FileCookieJar.137+138+ Caution: dictionary operations that are normally O(1) may be O(n).139+140+ Unlike a regular CookieJar, this class is pickleable.141+ """142+143+ def get(self, name, domain=None, path=None, default=None):144+ try:145+ return self._find(name, domain, path)146+ except KeyError:147+ return default148+149+ def set(self, name, value, **kwargs):150+ # support client code that unsets cookies by assignment of a None value:151+ if value is None:152+ remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))153+ return154+155+ if isinstance(value, Morsel):156+ c = morsel_to_cookie(value)157+ else:158+ c = create_cookie(name, value, **kwargs)159+ self.set_cookie(c)160+ return c161+162+ def __getitem__(self, name):163+ return self._find(name)164+165+ def __setitem__(self, name, value):166+ self.set(name, value)167+168+ def __delitem__(self, name):169+ remove_cookie_by_name(self, name)170+171+ def _find(self, name, domain=None, path=None):172+ for cookie in iter(self):173+ if cookie.name == name:174+ if domain is None or cookie.domain == domain:175+ if path is None or cookie.path == path:176+ return cookie.value177+178+ raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))179+180+ def __getstate__(self):181+ state = self.__dict__.copy()182+ # remove the unpickleable RLock object183+ state.pop('_cookies_lock')184+ return state185+186+ def __setstate__(self, state):187+ self.__dict__.update(state)188+ if '_cookies_lock' not in self.__dict__:189+ self._cookies_lock = threading.RLock()190+191+ def copy(self):192+ """We're probably better off forbidding this."""193+ raise NotImplementedError194+195+def create_cookie(name, value, **kwargs):196+ """Make a cookie from underspecified parameters.197+198+ By default, the pair of `name` and `value` will be set for the domain ''199+ and sent on every request (this is sometimes called a "supercookie").200+ """201+ result = dict(202+ version=0,203+ name=name,204+ value=value,205+ port=None,206+ domain='',207+ path='/',208+ secure=False,209+ expires=None,210+ discard=True,211+ comment=None,212+ comment_url=None,213+ rest={'HttpOnly': None},214+ rfc2109=False,215+ )216+217+ badargs = set(kwargs) - set(result)218+ if badargs:219+ err = 'create_cookie() got unexpected keyword arguments: %s'220+ raise TypeError(err % list(badargs))221+222+ result.update(kwargs)223+ result['port_specified'] = bool(result['port'])224+ result['domain_specified'] = bool(result['domain'])225+ result['domain_initial_dot'] = result['domain'].startswith('.')226+ result['path_specified'] = bool(result['path'])227+228+ return cookielib.Cookie(**result)229+230+def morsel_to_cookie(morsel):231+ """Convert a Morsel object into a Cookie containing the one k/v pair."""232+ c = create_cookie(233+ name=morsel.key,234+ value=morsel.value,235+ version=morsel['version'] or 0,236+ port=None,237+ port_specified=False,238+ domain=morsel['domain'],239+ domain_specified=bool(morsel['domain']),240+ domain_initial_dot=morsel['domain'].startswith('.'),241+ path=morsel['path'],242+ path_specified=bool(morsel['path']),243+ secure=bool(morsel['secure']),244+ expires=morsel['max-age'] or morsel['expires'],245+ discard=False,246+ comment=morsel['comment'],247+ comment_url=bool(morsel['comment']),248+ rest={'HttpOnly': morsel['httponly']},249+ rfc2109=False,250+ )251+ return c252+253+def cookiejar_from_dict(cookie_dict, cookiejar=None):254+ """Returns a CookieJar from a key/value dictionary.255+256+ :param cookie_dict: Dict of key/values to insert into CookieJar.257+ """258+ if cookiejar is None:259+ cookiejar = RequestsCookieJar()260+261+ if cookie_dict is not None:262+ for name in cookie_dict:263+ cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))264+ return cookiejarmodified:requests/models.py+25 added-32 removed
13 unmodified lines14 from .structures import CaseInsensitiveDict15 from .status_codes import codes16 17 from .auth import HTTPBasicAuth, HTTPProxyAuth18+from .cookies import cookiejar_from_dict, extract_cookies_to_jar, get_cookie_header19 from .packages.urllib3.response import HTTPResponse20 from .packages.urllib3.exceptions import MaxRetryError, LocationParseError21 from .packages.urllib3.exceptions import SSLError as _SSLError22 from .packages.urllib3.exceptions import HTTPError as _HTTPError4 unmodified lines27 ConnectionError, HTTPError, RequestException, Timeout, TooManyRedirects,28 URLRequired, SSLError, MissingSchema, InvalidSchema, InvalidURL)29 from .utils import (30 get_encoding_from_headers, stream_untransfer, guess_filename, requote_uri,30- dict_from_string, stream_decode_response_unicode, get_netrc_auth,31+ stream_decode_response_unicode, get_netrc_auth,32 DEFAULT_CA_BUNDLE_PATH)33 from .compat import (33- urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,34- SimpleCookie, is_py2)34+ cookielib, urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,35+ is_py2)36 37 # Import chardet if it is available.38 try:39 import chardet86 unmodified lines126 #: Authentication tuple or object to attach to :class:`Request <Request>`.127 self.auth = auth128 129 #: CookieJar to attach to :class:`Request <Request>`.129- self.cookies = dict(cookies or [])130+ if isinstance(cookies, cookielib.CookieJar):131+ self.cookies = cookies132+ else:133+ self.cookies = cookiejar_from_dict(cookies)134 135 #: True if Request has been sent.136 self.sent = False137 58 unmodified lines196 197 # Set encoding.198 response.encoding = get_encoding_from_headers(response.headers)199 196- # Start off with our local cookies.197- cookies = self.cookies or dict()198-200 # Add new cookies from the server.200- if 'set-cookie' in response.headers:201- cookie_header = response.headers['set-cookie']202- cookies = dict_from_string(cookie_header)201+ extract_cookies_to_jar(self.cookies, self, resp)202 203 # Save cookies in Response.205- response.cookies = cookies204+ response.cookies = self.cookies205 206 # No exceptions were harmed in the making of this request.207 response.error = getattr(resp, 'error', None)208 9 unmodified lines218 history = []219 220 r = build(resp)221 223- self.cookies.update(r.cookies)224-222 if r.status_code in REDIRECT_STATI and not self.redirect:223 224 while (('location' in r.headers) and225 ((r.status_code is codes.see_other) or (self.allow_redirects))):69 unmodified lines295 )296 297 request.send()298 r = request.response302- self.cookies.update(r.cookies)299 300 r.history = history301 302 self.response = r303 self.response.request = self308- self.response.cookies.update(self.cookies)304 305 @staticmethod306 def _encode_params(data):307 """Encode parameters in a piece of data.251 unmodified lines559 conn.cert_file = self.cert560 561 if not self.sent or anyway:562 568- if self.cookies:569-570- # Skip if 'cookie' header is explicitly set.571- if 'cookie' not in self.headers:572-573- # Simple cookie with our dict.574- c = SimpleCookie()575- for (k, v) in list(self.cookies.items()):576- c[k] = v577-578- # Turn it into a header.579- cookie_header = c.output(header='', sep='; ').strip()580-581- # Attach Cookie header to request.563+ # Skip if 'cookie' header is explicitly set.564+ if 'cookie' not in self.headers:565+ cookie_header = get_cookie_header(self.cookies, self)566+ if cookie_header is not None:567 self.headers['Cookie'] = cookie_header568 569 # Pre-request hook.570 r = dispatch_hook('pre_request', self.hooks, self)36 unmodified lines607 r.error = e608 else:609 raise610 611+ # build_response can throw TooManyRedirects612+ try:626- self._build_response(r)613+ self._build_response(r)614+ except RequestException as e:615+ if self.config.get('safe_mode', False):616+ # In safe mode, catch the exception617+ self.response.error = e618+ else:619+ raise620 621 # Response manipulation hook.622 self.response = dispatch_hook('response', self.hooks, self.response)623 51 unmodified lines675 676 #: The :class:`Request <Request>` that created the Response.677 self.request = None678 686- #: A dictionary of Cookies the server sent back.687- self.cookies = {}679+ #: A CookieJar of Cookies the server sent back.680+ self.cookies = None681 682 #: Dictionary of configurations for this request.683 self.config = {}684 153 unmodified linesmodified:requests/sessions.py+31 added-10 removed
7 unmodified lines8 requests (cookies, auth, proxies).9 10 """11 12+from .compat import cookielib13+from .cookies import cookiejar_from_dict, remove_cookie_by_name14 from .defaults import defaults15 from .models import Request16 from .hooks import dispatch_hook17 from .utils import header_expand18 from .packages.urllib3.poolmanager import PoolManager19 18-20 def merge_kwargs(local_kwarg, default_kwarg):21 """Merges kwarg dictionaries.22 23 If a local key in the dictionary is set to None, it will be removed.45 unmodified lines69 verify=True,70 cert=None):71 72 self.headers = headers or {}72- self.cookies = cookies or {}73 self.auth = auth74 self.timeout = timeout75 self.proxies = proxies or {}76 self.hooks = hooks or {}8 unmodified lines85 86 self.init_poolmanager()87 88 # Set up a CookieJar to be used by default89+ if isinstance(cookies, cookielib.CookieJar):89- self.cookies = {}90+ self.cookies = cookies91+ else:92+ self.cookies = cookiejar_from_dict(cookies)93 91- # Add passed cookies in.92- if cookies is not None:93- self.cookies.update(cookies)94-94 def init_poolmanager(self):95 self.poolmanager = PoolManager(96 num_pools=self.config.get('pool_connections'),97 maxsize=self.config.get('pool_maxsize')48 unmodified lines146 147 method = str(method).upper()148 149 # Default empty dicts for dict params.151- cookies = {} if cookies is None else cookies150 data = {} if data is None else data151 files = {} if files is None else files152 headers = {} if headers is None else headers153 params = {} if params is None else params28 unmodified lines182 cert=cert,183 _poolmanager=self.poolmanager184 )185 186+ # merge session cookies into passed-in ones187+ dead_cookies = None188+ # passed-in cookies must become a CookieJar:189+ if not isinstance(cookies, cookielib.CookieJar):190+ args['cookies'] = cookiejar_from_dict(cookies)191+ # support unsetting cookies that have been passed in with None values192+ # this is only meaningful when `cookies` is a dict ---193+ # for a real CookieJar, the client should use session.cookies.clear()194+ if cookies is not None:195+ dead_cookies = [name for name in cookies if cookies[name] is None]196+ # merge the session's cookies into the passed-in cookies:197+ for cookie in self.cookies:198+ args['cookies'].set_cookie(cookie)199+ # remove the unset cookies from the jar we'll be using with the current request200+ # (but not from the session's own store of cookies):201+ if dead_cookies is not None:202+ for name in dead_cookies:203+ remove_cookie_by_name(args['cookies'], name)204+205 # Merge local kwargs with session kwargs.206 for attr in self.__attrs__:207+ # we already merged cookies:208+ if attr == 'cookies':209+ continue210+211 session_val = getattr(self, attr, None)212 local_val = args.get(attr)192-213 args[attr] = merge_kwargs(local_val, session_val)214 215 # Arguments manipulation hook.216 args = dispatch_hook('args', args['hooks'], args)11 unmodified lines228 # Send the HTTP Request.229 r.send(prefetch=prefetch)230 231 # Send any cookies back up the to the session.212- self.cookies.update(r.response.cookies)232+ for cookie in r.response.cookies:233+ self.cookies.set_cookie(cookie)234 235 # Return the response.236 return r.response237 90 unmodified linesmodified:requests/utils.py+6 added-62 removed
16 unmodified lines17 import zlib18 from netrc import netrc, NetrcParseError19 20 from .compat import parse_http_list as _parse_list_header21-from .compat import quote, cookielib, SimpleCookie, is_py2, urlparse21+from .compat import quote, is_py2, urlparse22 from .compat import basestring, bytes, str23+from .cookies import RequestsCookieJar, cookiejar_from_dict24 25+_hush_pyflakes = (RequestsCookieJar,)26+27 CERTIFI_BUNDLE_PATH = None28 try:29 # see if requests's own CA certificate bundle is installed30 import certifi68 unmodified lines99 except AttributeError:100 pass101 102 100-101-def dict_from_string(s):102- """Returns a MultiDict with Cookies."""103-104- cookies = dict()105-106- try:107- c = SimpleCookie()108- c.load(s)109-110- for k, v in list(c.items()):111- cookies.update({k: v.value})112- # This stuff is not to be trusted.113- except Exception:114- pass115-116- return cookies117-118-103 def guess_filename(obj):104 """Tries to guess the filename of the given object."""105 name = getattr(obj, 'name', None)106 if name and name[0] != '<' and name[-1] != '>':166 unmodified lines273 274 return cookie_dict275 276 293-def cookiejar_from_dict(cookie_dict):294- """Returns a CookieJar from a key/value dictionary.295-296- :param cookie_dict: Dict of key/values to insert into CookieJar.297- """298-299- # return cookiejar if one was passed in300- if isinstance(cookie_dict, cookielib.CookieJar):301- return cookie_dict302-303- # create cookiejar304- cj = cookielib.CookieJar()305-306- cj = add_dict_to_cookiejar(cj, cookie_dict)307-308- return cj309-310-277 def add_dict_to_cookiejar(cj, cookie_dict):278 """Returns a CookieJar from a key/value dictionary.279 280 :param cj: CookieJar to insert cookies into.281 :param cookie_dict: Dict of key/values to insert into CookieJar.282 """283 318- for k, v in list(cookie_dict.items()):319-320- cookie = cookielib.Cookie(321- version=0,322- name=k,323- value=v,324- port=None,325- port_specified=False,326- domain='',327- domain_specified=False,328- domain_initial_dot=False,329- path='/',330- path_specified=True,331- secure=False,332- expires=None,333- discard=True,334- comment=None,335- comment_url=None,336- rest={'HttpOnly': None},337- rfc2109=False338- )339-340- # add cookie to cookiejar284+ cj2 = cookiejar_from_dict(cookie_dict)285+ for cookie in cj2:286 cj.set_cookie(cookie)342-287 return cj288 289 290 def get_encodings_from_content(content):158 unmodified linesadded:tests/test_cookies.py+166 added
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+4+import sys5+import json6+import os7+import tempfile8+import unittest9+10+# Path hack.11+sys.path.insert(0, os.path.abspath('..'))12+import requests13+from requests.compat import cookielib14+15+# More hacks16+sys.path.append('.')17+from test_requests import httpbin, TestBaseMixin18+19+class CookieTests(TestBaseMixin, unittest.TestCase):20+21+ def test_cookies_from_response(self):22+ """Basic test that we correctly parse received cookies in the Response object."""23+ r = requests.get(httpbin('cookies', 'set', 'myname', 'myvalue'))24+25+ # test deprecated dictionary interface26+ self.assertEqual(r.cookies['myname'], 'myvalue')27+ # test CookieJar interface28+ jar = r.cookies29+ self.assertEqual(len(jar), 1)30+ cookie_from_jar = list(jar)[0]31+ self.assertCookieHas(cookie_from_jar, name='myname', value='myvalue')32+33+ q = requests.get(httpbin('cookies'), cookies=jar)34+ self.assertEqual(json.loads(q.text)['cookies'], {'myname': 'myvalue'})35+36+ def test_crossdomain_cookies(self):37+ """Cookies should not be sent to domains they didn't originate from."""38+ r = requests.get("http://github.com")39+ c = r.cookies40+ # github should send us cookies41+ self.assertGreaterEqual(len(c), 1)42+43+ # github cookies should not be sent to httpbin.org:44+ r2 = requests.get(httpbin('cookies'), cookies=c)45+ self.assertEqual(json.loads(r2.text)['cookies'], {})46+47+ # let's do this again using the session object48+ s = requests.session()49+ s.get("http://github.com")50+ self.assertGreaterEqual(len(s.cookies), 1)51+ r = s.get(httpbin('cookies'))52+ self.assertEqual(json.loads(r.text)['cookies'], {})53+ # we can set a cookie and get exactly that same-domain cookie back:54+ r = s.get(httpbin('cookies', 'set', 'myname', 'myvalue'))55+ self.assertEqual(json.loads(r.text)['cookies'], {'myname': 'myvalue'})56+57+ def test_overwrite(self):58+ """Cookies should get overwritten when appropriate."""59+ r = requests.get(httpbin('cookies', 'set', 'shimon', 'yochai'))60+ cookies = r.cookies61+ requests.get(httpbin('cookies', 'set', 'elazar', 'shimon'), cookies=cookies)62+ r = requests.get(httpbin('cookies'), cookies=cookies)63+ self.assertEqual(json.loads(r.text)['cookies'],64+ {'shimon': 'yochai', 'elazar': 'shimon'})65+ # overwrite the value of 'shimon'66+ r = requests.get(httpbin('cookies', 'set', 'shimon', 'gamaliel'), cookies=cookies)67+ self.assertEqual(len(cookies), 2)68+ r = requests.get(httpbin('cookies'), cookies=cookies)69+ self.assertEqual(json.loads(r.text)['cookies'],70+ {'shimon': 'gamaliel', 'elazar': 'shimon'})71+72+ def test_redirects(self):73+ """Test that cookies set by a 302 page are correctly processed."""74+ r = requests.get(httpbin('cookies', 'set', 'redirects', 'work'))75+ self.assertEqual(r.history[0].status_code, 302)76+ expected_cookies = {'redirects': 'work'}77+ self.assertEqual(json.loads(r.text)['cookies'], expected_cookies)78+79+ r2 = requests.get(httpbin('cookies', 'set', 'very', 'well'), cookies=r.cookies)80+ expected_cookies = {'redirects': 'work', 'very': 'well'}81+ self.assertEqual(json.loads(r2.text)['cookies'], expected_cookies)82+ self.assertIs(r.cookies, r2.cookies)83+84+ def test_none_cookie(self):85+ """Regression test: don't send a Cookie header with a string value of 'None'!"""86+ page = json.loads(requests.get(httpbin('headers')).text)87+ self.assertNotIn('Cookie', page['headers'])88+89+class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):90+ """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""91+92+ COOKIEJAR_CLASS = cookielib.LWPCookieJar93+94+ def setUp(self):95+ # blank the file96+ self.cookiejar_file = tempfile.NamedTemporaryFile()97+ self.cookiejar_filename = self.cookiejar_file.name98+ cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)99+ cookiejar.save()100+101+ def tearDown(self):102+ try:103+ self.cookiejar_file.close()104+ except OSError:105+ pass106+107+ def test_cookiejar_persistence(self):108+ """Test that we can save cookies to a FileCookieJar."""109+ cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)110+ cookiejar.load()111+ # initially should be blank112+ self.assertEqual(len(cookiejar), 0)113+114+ response = requests.get(httpbin('cookies', 'set', 'key', 'value'), cookies=cookiejar)115+ self.assertEqual(len(cookiejar), 1)116+ cookie = list(cookiejar)[0]117+ self.assertEqual(json.loads(response.text)['cookies'], {'key': 'value'})118+ self.assertCookieHas(cookie, name='key', value='value')119+120+ # save and reload the cookies from the file:121+ cookiejar.save(ignore_discard=True)122+ cookiejar_2 = self.COOKIEJAR_CLASS(self.cookiejar_filename)123+ cookiejar_2.load(ignore_discard=True)124+ self.assertEqual(len(cookiejar_2), 1)125+ cookie_2 = list(cookiejar_2)[0]126+ # this cookie should have been saved with the correct domain restriction:127+ self.assertCookieHas(cookie_2, name='key', value='value',128+ domain='httpbin.org', path='/')129+130+ # httpbin sets session cookies, so if we don't ignore the discard attribute,131+ # there should be no cookie:132+ cookiejar_3 = self.COOKIEJAR_CLASS(self.cookiejar_filename)133+ cookiejar_3.load()134+ self.assertEqual(len(cookiejar_3), 0)135+136+ def test_crossdomain(self):137+ """Test persistence of the domains associated with the cookies."""138+ cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)139+ cookiejar.load()140+ self.assertEqual(len(cookiejar), 0)141+142+ # github sets a cookie143+ requests.get("http://github.com", cookies=cookiejar)144+ num_github_cookies = len(cookiejar)145+ self.assertGreaterEqual(num_github_cookies, 1)146+ # httpbin sets another147+ requests.get(httpbin('cookies', 'set', 'key', 'value'), cookies=cookiejar)148+ num_total_cookies = len(cookiejar)149+ self.assertGreaterEqual(num_total_cookies, 2)150+ self.assertGreater(num_total_cookies, num_github_cookies)151+152+ # save and load153+ cookiejar.save(ignore_discard=True)154+ cookiejar_2 = self.COOKIEJAR_CLASS(self.cookiejar_filename)155+ cookiejar_2.load(ignore_discard=True)156+ self.assertEqual(len(cookiejar_2), num_total_cookies)157+ r = requests.get(httpbin('cookies'), cookies=cookiejar_2)158+ self.assertEqual(json.loads(r.text)['cookies'], {'key': 'value'})159+160+class MozCookieJarTest(LWPCookieJarTest):161+ """Same test, but substitute MozillaCookieJar."""162+163+ COOKIEJAR_CLASS = cookielib.MozillaCookieJar164+165+if __name__ == '__main__':166+ unittest.main()modified:tests/test_requests_async.py-1 removed
10 unmodified lines11 import select12 has_poll = hasattr(select, "poll")13 14 from requests import async15-import envoy15 16 sys.path.append('.')17 from test_requests import httpbin, RequestsTestSuite, SERVICES18 49 unmodified linesmodified:tests/test_requests_ext.py+19 added
102 unmodified lines103 'News/~3/BQtUJRJeZlo/deal_view_investment.' +104 'php')105 assert r.ok106 107+ def test_cookies_on_redirects(self):108+ """Test interaction between cookie handling and redirection."""109+ # get a cookie for tinyurl.com ONLY110+ s = requests.session()111+ s.get(url='http://tinyurl.com/preview.php?disable=1')112+ # we should have set a cookie for tinyurl: preview=0113+ self.assertIn('preview', s.cookies)114+ self.assertEqual(s.cookies['preview'], '0')115+ self.assertEqual(list(s.cookies)[0].name, 'preview')116+ self.assertEqual(list(s.cookies)[0].domain, 'tinyurl.com')117 118+ # get cookies on another domain119+ r2 = s.get(url='http://httpbin.org/cookies')120+ # the cookie is not there121+ self.assertNotIn('preview', json.loads(r2.text)['cookies'])122 123+ # this redirects to another domain, httpbin.org124+ # cookies of the first domain should NOT be sent to the next one125+ r3 = s.get(url='http://tinyurl.com/7zp3jnr')126+ assert r3.url == 'http://httpbin.org/cookies'127+ self.assertNotIn('preview', json.loads(r2.text)['cookies'])128 129 if __name__ == '__main__':130 unittest.main()131 modified:tests/test_requests.py+17 added-7 removed
8 unmodified lines9 sys.path.insert(0, os.path.abspath('..'))10 11 import json12 import os13-import sys13 import unittest14 import pickle15 16 import requests33 unmodified lines50 # c = envoy.connect('httpbin %s' % (PORT))51 # time.sleep(1)52 _httpbin = True53 54+class TestBaseMixin(object):55 56+ def assertCookieHas(self, cookie, **kwargs):57+ """Assert that a cookie has various specified properties."""58+ for attr, expected_value in kwargs.items():59+ message = 'Failed comparison for %s' % (attr,)60+ self.assertEqual(getattr(cookie, attr), expected_value, message)61+56-class RequestsTestSuite(TestSetup, unittest.TestCase):62+class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):63 """Requests test cases."""64 65 def test_entry_points(self):66 570 unmodified lines637 r = get(httpbin('cookies'), session=s)638 639 # Those cookies persist transparently.640 c = json.loads(r.text).get('cookies')635- assert c == _c641+ self.assertEqual(c, _c)642 643 # Double check.644 r = get(httpbin('cookies'), cookies={}, session=s)645 c = json.loads(r.text).get('cookies')640- assert c == _c646+ self.assertEqual(c, _c)647 648 # Remove a cookie by setting it's value to None.649 r = get(httpbin('cookies'), cookies={'bessie': None}, session=s)650 c = json.loads(r.text).get('cookies')651 del _c['bessie']646- assert c == _c652+ self.assertEqual(c, _c)653 654 # Test session-level cookies.655 s = requests.session(cookies=_c)656 r = get(httpbin('cookies'), session=s)657 c = json.loads(r.text).get('cookies')652- assert c == _c658+ self.assertEqual(c, _c)659 660 # Have the server set a cookie.661 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)662 c = json.loads(r.text).get('cookies')40 unmodified lines703 704 ds = pickle.loads(pickle.dumps(s))705 706 self.assertEqual(s.headers, ds.headers)701- self.assertEqual(s.cookies, ds.cookies)707 self.assertEqual(s.auth, ds.auth)708 709+ # Cookie doesn't have a good __eq__, so verify manually:710+ self.assertEqual(len(ds.cookies), 1)711+ for cookie in ds.cookies:712+ self.assertCookieHas(cookie, name='a-cookie', value='cookie-value')713+714 def test_unpickled_session_requests(self):715 s = requests.session()716 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)717 c = json.loads(r.text).get('cookies')134 unmodified linesmodified:.gitignore+4 added-4 removed
1 MANIFEST2 coverage.xml3 nosetests.xml4 pylint.txt5-*.pyc6-docs/_build5 toy.py8-.gitignore6 junit-report.xml10-requests.egg-info/7+requests.egg-info/8+docs/_build9+*.pyc10+*.swpmodified:AUTHORS.rst+1 added
94 unmodified lines95 - Michael Kelly96 - Michael Newman <newmaniese@gmail.com>97 - Jonty Wareing <jonty@jonty.co.uk>98 - Shivaram Lingamneni99+- Miguel Turnermodified:setup.py+26 added-15 removed
1 #!/usr/bin/env python2-# -*- coding: utf-8 -*-2 4-import os3+"""4+distutils/setuptools install script. See inline comments for packaging documentation.5+"""6+7 import sys8+9 import requests7-from requests.compat import is_py3, is_py210+from requests.compat import is_py311 12 try:13 from setuptools import setup14 except ImportError:15 from distutils.core import setup16 14-15-17 if sys.argv[-1] == 'publish':18 os.system('python setup.py sdist upload')19 sys.exit()20 20-if sys.argv[-1] == 'test':21- os.system('python tests/test_requests.py')22- sys.exit()23-24-required = ['certifi>=0.0.7']21 packages = [22 'requests',23 'requests.packages',24 'requests.packages.urllib3',1 unmodified line26 'requests.packages.urllib3.packages.ssl_match_hostname',27 'requests.packages.urllib3.packages.mimetools_choose_boundary',28 ]29 30+# certifi is a Python package containing a CA certificate bundle for SSL verification.31+# On certain supported platforms (e.g., Red Hat / Debian / FreeBSD), Requests can32+# use the system CA bundle instead; see `requests.utils` for details.33+# If your platform is supported, set `requires` to [] instead:34+requires = ['certifi>=0.0.7']35+36+# chardet is used to optimally guess the encodings of pages that don't declare one.37+# At this time, chardet is not a required dependency. However, it's sufficiently38+# important that pip/setuptools should install it when it's unavailable.39 if is_py3:35- required.append('chardet2')40+ chardet_package = 'chardet2'41 else:37- required.append('chardet>=1.0.0')38- required.append('oauthlib')39- packages.append('requests.packages.oreos')42+ chardet_package = 'chardet>=1.0.0'43+requires.append(chardet_package)44 45+# The async API in requests.async requires the gevent package.46+# This is also not a required dependency.47+extras_require = {48+ 'async': ['gevent'],49+}50+51 setup(52 name='requests',53 version=requests.__version__,54 description='Python HTTP for Humans.',4 unmodified lines59 url='http://python-requests.org',60 packages=packages,61 package_data={'': ['LICENSE', 'NOTICE']},62 include_package_data=True,53- install_requires=required,63+ install_requires=requires,64+ extras_require=extras_require,65 license=open("LICENSE").read(),66 classifiers=(67 'Development Status :: 5 - Production/Stable',68 'Intended Audience :: Developers',10 unmodified lines