Skip to content
Myr

Further changes to move cookies to CookieJar

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

authored by Shivaram Lingamneni · committed by Shivaram Lingamneni · parent c4ab96b · Browse files · 9 files+473 added−298 removed
This commit

State

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

Diff stats

9 files+473 added−298 removed

  • tests:+166 added−7 removed
  • other:+307 added−291 removed

9 files+473 added−298 removed

deleted:requests/packages/oreos/cookiejar.py-193 removed
1"""2Wrapper for CookieJar allow dict-like access.3Ideally there would be wrappers for LWPCookieJar and MozillaCookieJar as well.4"""56import urlparse7import Cookie8from Cookie import Morsel9import cookielib10import collections1112class MockRequest:13 """14 Wraps a *requests.Request* to mimic a *urllib2.Request*.15 """16 def __init__(self, request):17 self._r = request18 19 def get_type(self):20 return urlparse.urlparse(self._r.full_url).scheme21 22 def get_host(self):23 return urlparse.urlparse(self._r.full_url).netloc24 25 def get_origin_req_host(self):26 if self._r.response.history:27 r = self._r.response.history[0]28 return urlparse.urlparse(r).netloc29 else:30 return self.get_host()31 32 def get_full_url(self):33 return self._r.full_url34 35 def has_header(self, name):36 return name in self._r.headers37 38 def get_header(self, name, default=None):39 return self._r.headers.get(name, default)40 41 def add_unredirected_header(self, name, value):42 # XXX: This is incorrect.43 # To do this correctly the *requests.Request* class would need44 # to keep track of headers that are only sent with the original45 # request.46 self._r.headers[name] = value47 48 def is_unverifiable(self):49 # unverifiable == redirected50 return bool(self._r.response.history)5152class MockResponse:53 """54 Wraps a *requests.Response* to mimic a *urllib.addinfourl*.55 """56 def __init__(self, response):57 self._r = response58 59 def info(self):60 return self._r.msg61 62 def getheaders(self, name):63 self._r.msg.getheaders(name)6465class CookieJar(cookielib.CookieJar, collections.MutableMapping):66 def extract_cookies(self, response, request):67 if response.raw._original_response:68 req = MockRequest(request)69 res = MockResponse(response.raw._original_response)70 cookielib.CookieJar.extract_cookies(self, res, req)71 72 def get_header(self, request):73 r = MockRequest(request)74 self.add_cookie_header(r)75 return r._r.headers['Cookie']76 77 def get(self, name, domain=None, path=None, default=None):78 try:79 return self._find(name, domain, path)80 except KeyError:81 return default82 83 def set(self, name, value, **kwargs):84 if isinstance(value, Morsel):85 c = morsel_to_cookielib(value)86 else:87 c = create_cookie(name, value, **kwargs)88 self.set_cookie(c)89 return c90 91 def update(self, other):92 if isinstance(other, cookielib.CookieJar):93 for cookie in other:94 self.set_cookie(cookie)95 else:96 collections.MutableMapping.update(self, other)97 98 def __getitem__(self, name):99 return self._find(name)100 101 def __setitem__(self, name, value):102 self.set(name, value)103 104 def __delitem__(self, name):105 raise NotImplementedError('cookies can be removed using *clear*')106 107 def _find(self, name, domain=None, path=None):108 try:109 if domain is None:110 dompaths = self._cookies.itervalues()111 else:112 dompaths = [self._cookies[domain]]113 for paths in dompaths:114 if path is None:115 pathcookies = paths.itervalues()116 else:117 pathcookies = [paths[path]]118 for cookies in pathcookies:119 for cname, cookie in cookies.iteritems():120 if name == cname:121 return cookielib_to_morsel(cookie)122 except KeyError:123 pass124 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))125126def create_cookie(name, value, **kwargs):127 result = dict(128 version=0,129 name=name,130 value=value,131 port=None,132 domain='',133 path='/',134 secure=False,135 expires=None,136 discard=True,137 comment=None,138 comment_url=None,139 rest={'HttpOnly': None},140 rfc2109=False,141 )142 143 badargs = set(kwargs) - set(result)144 if badargs:145 err = 'create_cookie() got unexpected keyword arguments: %s'146 raise TypeError(err % list(badargs))147 148 result.update(kwargs)149 result['port_specified'] = bool(result['port'])150 result['domain_specified'] = bool(result['domain'])151 result['domain_initial_dot'] = result['domain'].startswith('.')152 result['path_specified'] = bool(result['path'])153 154 return cookielib.Cookie(**result)155156def cookielib_to_morsel(cookie):157 m = Morsel()158 m.key = cookie.name159 m.value = cookie.value160 m.coded_value = Cookie._quote(cookie.value)161 m.update({162 'expires': cookie.expires or '',163 'path': cookie.path or '',164 'comment': cookie.comment or '',165 'domain': cookie.domain or '',166 'max-age': cookie.expires or '',167 'secure': cookie.secure or '',168 'httponly': cookie._rest.get('HttpOnly', ''),169 'version': cookie.version or '',170 })171 return m172173def morsel_to_cookielib(morsel):174 c = create_cookie(175 name=morsel.key,176 value=morsel.value,177 version=morsel['version'] or 0,178 port=None,179 port_specified=False,180 domain=morsel['domain'],181 domain_specified=bool(morsel['domain']),182 domain_initial_dot=morsel['domain'].startswith('.'),183 path=morsel['path'],184 path_specified=bool(morsel['path']),185 secure=bool(morsel['secure']),186 expires=morsel['max-age'] or morsel['expires'],187 discard=False,188 comment=morsel['comment'],189 comment_url=bool(morsel['comment']),190 rest={'HttpOnly': morsel['httponly']},191 rfc2109=False,192 )193 return c
modified:requests/compat.py+2 added-2 removed
81 unmodified lines
82 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 StringIO8889 bytes = str90 str = unicode
4 unmodified lines
95elif 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 StringIO101102 str = str103 bytes = bytes
2 unmodified lines
added:requests/cookies.py+258 added
1"""2Compatibility code to be able to use `cookielib.CookieJar` with requests.34requests.utils imports from here, so be careful with imports.5"""67import collections8from .compat import cookielib, urlparse, Morsel910try:11 import threading12 # grr, pyflakes: this fixes "redefinition of unused 'threading'"13 threading14except ImportError:15 import dummy_threading as threading1617class MockRequest(object):18 """Wraps a `requests.Request` to mimic a `urllib2.Request`.1920 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.2324 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 """2829 def __init__(self, request):30 self._r = request31 self._new_headers = {}3233 def get_type(self):34 return urlparse.urlparse(self._r.full_url).scheme3536 def get_host(self):37 return urlparse.urlparse(self._r.full_url).netloc3839 def get_origin_req_host(self):40 if self._r.response.history:41 r = self._r.response.history[0]42 return urlparse.urlparse(r).netloc43 else:44 return self.get_host()4546 def get_full_url(self):47 return self._r.full_url4849 def is_unverifiable(self):50 # unverifiable == redirected51 return bool(self._r.response.history)5253 def has_header(self, name):54 return name in self._r.headers or name in self._new_headers5556 def get_header(self, name, default=None):57 return self._r.headers.get(name, self._new_headers.get(name, default))5859 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()")6263 def add_unredirected_header(self, name, value):64 self._new_headers[name] = value6566 def get_new_headers(self):67 return self._new_headers6869class MockResponse(object):70 """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.7172 ...what? Basically, expose the parsed HTTP headers from the server response73 the way `cookielib` expects to see them.74 """7576 def __init__(self, headers):77 """Make a MockResponse for `cookielib` to read.7879 :param headers: a httplib.HTTPMessage or analogous carrying the headers80 """81 self._headers = headers8283 def info(self):84 return self._headers8586 def getheaders(self, name):87 self._headers.getheaders(name)8889def extract_cookies_to_jar(jar, request, response):90 """Extract the cookies from the headers of `response`, into `jar`."""91 if response._original_response is None:92 # TODO why would this happen?93 return94 req = MockRequest(request)95 # pull out the HTTPMessage with the headers and put it in the mock:96 res = MockResponse(response._original_response.msg)97 jar.extract_cookies(res, req)9899def get_cookie_header(jar, request):100 """Produce an appropriate Cookie header string to be sent with `request`, or None."""101 r = MockRequest(request)102 jar.add_cookie_header(r)103 return r.get_new_headers().get('Cookie')104105def remove_cookie_by_name(cookiejar, name, domain=None, path=None):106 """Unsets a cookie by name, by default over all domains and paths.107108 Wraps CookieJar.clear(), is O(n).109 """110 clearables = []111 for cookie in cookiejar:112 if cookie.name == name:113 if domain is None or domain == cookie.domain:114 if path is None or path == cookie.path:115 clearables.append((cookie.domain, cookie.path, cookie.name))116117 for domain, path, name in clearables:118 cookiejar.clear(domain, path, name)119120class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):121 """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface.122123 This is the CookieJar we create by default for requests and sessions that124 don't specify one, since some clients may expect response.cookies and125 session.cookies to support dict operations.126127 Don't use the dict interface internally; it's just for compatibility with128 with external client code. All `requests` code should work out of the box129 with externally provided instances of CookieJar, e.g., LWPCookieJar and130 FileCookieJar.131132 Caution: dictionary operations that are normally O(1) may be O(n).133134 Unlike a regular CookieJar, this class is pickleable.135 """136137 def get(self, name, domain=None, path=None, default=None):138 try:139 return self._find(name, domain, path)140 except KeyError:141 return default142143 def set(self, name, value, **kwargs):144 # support client code that unsets cookies by assignment of a None value:145 if value is None:146 remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))147 return148149 if isinstance(value, Morsel):150 c = morsel_to_cookie(value)151 else:152 c = create_cookie(name, value, **kwargs)153 self.set_cookie(c)154 return c155156 def __getitem__(self, name):157 return self._find(name)158159 def __setitem__(self, name, value):160 self.set(name, value)161162 def __delitem__(self, name):163 remove_cookie_by_name(self, name)164165 def _find(self, name, domain=None, path=None):166 for cookie in iter(self):167 if cookie.name == name:168 if domain is None or cookie.domain == domain:169 if path is None or cookie.path == path:170 return cookie.value171172 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))173174 def __getstate__(self):175 state = self.__dict__.copy()176 # remove the unpickleable RLock object177 state.pop('_cookies_lock')178 return state179180 def __setstate__(self, state):181 self.__dict__.update(state)182 if '_cookies_lock' not in self.__dict__:183 self._cookies_lock = threading.RLock()184185 def copy(self):186 """We're probably better off forbidding this."""187 raise NotImplementedError188189def create_cookie(name, value, **kwargs):190 """Make a cookie from underspecified parameters.191192 By default, the pair of `name` and `value` will be set for the domain ''193 and sent on every request (this is sometimes called a "supercookie").194 """195 result = dict(196 version=0,197 name=name,198 value=value,199 port=None,200 domain='',201 path='/',202 secure=False,203 expires=None,204 discard=True,205 comment=None,206 comment_url=None,207 rest={'HttpOnly': None},208 rfc2109=False,209 )210211 badargs = set(kwargs) - set(result)212 if badargs:213 err = 'create_cookie() got unexpected keyword arguments: %s'214 raise TypeError(err % list(badargs))215216 result.update(kwargs)217 result['port_specified'] = bool(result['port'])218 result['domain_specified'] = bool(result['domain'])219 result['domain_initial_dot'] = result['domain'].startswith('.')220 result['path_specified'] = bool(result['path'])221222 return cookielib.Cookie(**result)223224def morsel_to_cookie(morsel):225 """Convert a Morsel object into a Cookie containing the one k/v pair."""226 c = create_cookie(227 name=morsel.key,228 value=morsel.value,229 version=morsel['version'] or 0,230 port=None,231 port_specified=False,232 domain=morsel['domain'],233 domain_specified=bool(morsel['domain']),234 domain_initial_dot=morsel['domain'].startswith('.'),235 path=morsel['path'],236 path_specified=bool(morsel['path']),237 secure=bool(morsel['secure']),238 expires=morsel['max-age'] or morsel['expires'],239 discard=False,240 comment=morsel['comment'],241 comment_url=bool(morsel['comment']),242 rest={'HttpOnly': morsel['httponly']},243 rfc2109=False,244 )245 return c246247def cookiejar_from_dict(cookie_dict, cookiejar=None):248 """Returns a CookieJar from a key/value dictionary.249250 :param cookie_dict: Dict of key/values to insert into CookieJar.251 """252 if cookiejar is None:253 cookiejar = RequestsCookieJar()254255 if cookie_dict is not None:256 for name, value in cookie_dict.iteritems():257 cookiejar.set_cookie(create_cookie(name, value))258 return cookiejar
modified:requests/models.py+11 added-25 removed
13 unmodified lines
14from .structures import CaseInsensitiveDict15from .status_codes import codes1617from .auth import HTTPBasicAuth, HTTPProxyAuth18from .packages.oreos.cookiejar import CookieJar18from .cookies import cookiejar_from_dict, extract_cookies_to_jar, get_cookie_header19from .packages.urllib3.response import HTTPResponse20from .packages.urllib3.exceptions import MaxRetryError, LocationParseError21from .packages.urllib3.exceptions import SSLError as _SSLError22from .packages.urllib3.exceptions import HTTPError as _HTTPError
4 unmodified lines
27 ConnectionError, HTTPError, RequestException, Timeout, TooManyRedirects,28 URLRequired, SSLError, MissingSchema, InvalidSchema, InvalidURL)29from .utils import (30 get_encoding_from_headers, stream_untransfer, guess_filename, requote_uri,31 dict_from_string, stream_decode_response_unicode, get_netrc_auth,31 stream_decode_response_unicode, get_netrc_auth,32 DEFAULT_CA_BUNDLE_PATH)33from .compat import (34 urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,35 SimpleCookie, is_py2)34 cookielib, urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,35 is_py2)3637# Import chardet if it is available.38try:39 import chardet
86 unmodified lines
126 #: Authentication tuple or object to attach to :class:`Request <Request>`.127 self.auth = auth128129 #: CookieJar to attach to :class:`Request <Request>`.130 if isinstance(cookies, CookieJar):130 if isinstance(cookies, cookielib.CookieJar):131 self.cookies = cookies132 else:133 self.cookies = CookieJar()134 135 # Add passed cookies in.136 if cookies is not None:137 self.cookies.update(cookies)133 self.cookies = cookiejar_from_dict(cookies)134135 #: True if Request has been sent.136 self.sent = False137
47 unmodified lines
185186 # Pass settings over.187 response.config = self.config188193 # Save original response for later.194 response.raw = resp195 response.url = self.full_url196189 if resp:190191 # Fallback to None if there's no status_code, for whatever reason.192 response.status_code = getattr(resp, 'status', None)201 193194 # Make headers case-insensitive.195 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))196197 # Set encoding.198 response.encoding = get_encoding_from_headers(response.headers)199200 # Add new cookies from the server.209 self.cookies.extract_cookies(response, self)201 extract_cookies_to_jar(self.cookies, self, resp)202203 # Save cookies in Response.204 response.cookies = self.cookies205
363 unmodified lines
569 if not self.sent or anyway:570571 # Skip if 'cookie' header is explicitly set.572 if 'cookie' not in self.headers:573 self.headers['Cookie'] = get_cookie_header(self.cookies, self)574582 # Turn it into a header.583 cookie_header = self.cookies.get_header(self)584 585 if cookie_header:586 # Attach Cookie header to request.587 self.headers['Cookie'] = cookie_header588575 # Pre-request hook.576 r = dispatch_hook('pre_request', self.hooks, self)577 self.__dict__.update(r.__dict__)578
102 unmodified lines
681682 #: The :class:`Request <Request>` that created the Response.683 self.request = None684699 #: A dictionary of Cookies the server sent back.700 self.cookies = {}685 #: A CookieJar of Cookies the server sent back.686 self.cookies = None687688 #: Dictionary of configurations for this request.689 self.config = {}690
155 unmodified lines
modified:requests/sessions.py+29 added-9 removed
7 unmodified lines
8requests (cookies, auth, proxies).910"""1112from .compat import cookielib13from .cookies import cookiejar_from_dict, remove_cookie_by_name14from .defaults import defaults15from .models import Request16from .hooks import dispatch_hook17from .utils import header_expand18from .packages.urllib3.poolmanager import PoolManager17from .packages.oreos.cookiejar import CookieJar1920def merge_kwargs(local_kwarg, default_kwarg):21 """Merges kwarg dictionaries.22
62 unmodified lines
8586 self.init_poolmanager()8788 # Set up a CookieJar to be used by default88 if isinstance(cookies, CookieJar):89 if isinstance(cookies, cookielib.CookieJar):90 self.cookies = cookies91 else:91 self.cookies = CookieJar()92 93 # Add passed cookies in.94 if cookies is not None:95 self.cookies.update(cookies)92 self.cookies = cookiejar_from_dict(cookies)9394 def init_poolmanager(self):95 self.poolmanager = PoolManager(96 num_pools=self.config.get('pool_connections'),
85 unmodified lines
182 cert=cert,183 _poolmanager=self.poolmanager184 )185186 # 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)204205 # Merge local kwargs with session kwargs.206 for attr in self.__attrs__:207 # we already merged cookies:208 if attr == 'cookies':209 continue210211 session_val = getattr(self, attr, None)212 local_val = args.get(attr)193213 args[attr] = merge_kwargs(local_val, session_val)214215 # Arguments manipulation hook.216 args = dispatch_hook('args', args['hooks'], args)
11 unmodified lines
228 # Send the HTTP Request.229 r.send(prefetch=prefetch)230231 # Send any cookies back up the to the session.213 self.cookies.update(r.response.cookies)232 for cookie in r.response.cookies:233 self.cookies.set_cookie(cookie)234235 # Return the response.236 return r.response237
90 unmodified lines
modified:requests/utils.py+6 added-62 removed
16 unmodified lines
17import zlib18from netrc import netrc, NetrcParseError1920from .compat import parse_http_list as _parse_list_header21from .compat import quote, cookielib, SimpleCookie, is_py2, urlparse21from .compat import quote, is_py2, urlparse22from .compat import basestring, bytes, str23from .cookies import RequestsCookieJar, cookiejar_from_dict2425_hush_pyflakes = (RequestsCookieJar,)2627CERTIFI_BUNDLE_PATH = None28try:29 # see if requests's own CA certificate bundle is installed30 import certifi
68 unmodified lines
99 except AttributeError:100 pass101102100101def dict_from_string(s):102 """Returns a MultiDict with Cookies."""103104 cookies = dict()105106 try:107 c = SimpleCookie()108 c.load(s)109110 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 pass115116 return cookies117118103def 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 lines
273274 return cookie_dict275276293def cookiejar_from_dict(cookie_dict):294 """Returns a CookieJar from a key/value dictionary.295296 :param cookie_dict: Dict of key/values to insert into CookieJar.297 """298299 # return cookiejar if one was passed in300 if isinstance(cookie_dict, cookielib.CookieJar):301 return cookie_dict302303 # create cookiejar304 cj = cookielib.CookieJar()305306 cj = add_dict_to_cookiejar(cj, cookie_dict)307308 return cj309310277def add_dict_to_cookiejar(cj, cookie_dict):278 """Returns a CookieJar from a key/value dictionary.279280 :param cj: CookieJar to insert cookies into.281 :param cookie_dict: Dict of key/values to insert into CookieJar.282 """283318 for k, v in list(cookie_dict.items()):319320 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 )339340 # add cookie to cookiejar284 cj2 = cookiejar_from_dict(cookie_dict)285 for cookie in cj2:286 cj.set_cookie(cookie)342287 return cj288289290def get_encodings_from_content(content):
158 unmodified lines
added:tests/test_cookies.py+149 added
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import sys5import json6import os7import tempfile8import unittest910# Path hack.11sys.path.insert(0, os.path.abspath('..'))12import requests13from requests.compat import cookielib1415# More hacks16sys.path.append('.')17from test_requests import httpbin, TestBaseMixin1819class CookieTests(TestBaseMixin, unittest.TestCase):2021 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'))2425 # 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')3233 q = requests.get(httpbin('cookies'), cookies=jar)34 self.assertEqual(json.loads(q.text)['cookies'], {'myname': 'myvalue'})3536 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)4243 # 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'], {})4647 # 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'})5657 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'})7172class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):73 """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""7475 COOKIEJAR_CLASS = cookielib.LWPCookieJar7677 def setUp(self):78 # blank the file79 self.cookiejar_file = tempfile.NamedTemporaryFile()80 self.cookiejar_filename = self.cookiejar_file.name81 cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)82 cookiejar.save()8384 def tearDown(self):85 try:86 self.cookiejar_file.close()87 except OSError:88 pass8990 def test_cookiejar_persistence(self):91 """Test that we can save cookies to a FileCookieJar."""92 cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)93 cookiejar.load()94 # initially should be blank95 self.assertEqual(len(cookiejar), 0)9697 response = requests.get(httpbin('cookies', 'set', 'key', 'value'), cookies=cookiejar)98 self.assertEqual(len(cookiejar), 1)99 cookie = list(cookiejar)[0]100 self.assertEqual(json.loads(response.text)['cookies'], {'key': 'value'})101 self.assertCookieHas(cookie, name='key', value='value')102103 # save and reload the cookies from the file:104 cookiejar.save(ignore_discard=True)105 cookiejar_2 = self.COOKIEJAR_CLASS(self.cookiejar_filename)106 cookiejar_2.load(ignore_discard=True)107 self.assertEqual(len(cookiejar_2), 1)108 cookie_2 = list(cookiejar_2)[0]109 # this cookie should have been saved with the correct domain restriction:110 self.assertCookieHas(cookie_2, name='key', value='value',111 domain='httpbin.org', path='/')112113 # httpbin sets session cookies, so if we don't ignore the discard attribute,114 # there should be no cookie:115 cookiejar_3 = self.COOKIEJAR_CLASS(self.cookiejar_filename)116 cookiejar_3.load()117 self.assertEqual(len(cookiejar_3), 0)118119 def test_crossdomain(self):120 """Test persistence of the domains associated with the cookies."""121 cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)122 cookiejar.load()123 self.assertEqual(len(cookiejar), 0)124125 # github sets a cookie126 requests.get("http://github.com", cookies=cookiejar)127 num_github_cookies = len(cookiejar)128 self.assertGreaterEqual(num_github_cookies, 1)129 # httpbin sets another130 requests.get(httpbin('cookies', 'set', 'key', 'value'), cookies=cookiejar)131 num_total_cookies = len(cookiejar)132 self.assertGreaterEqual(num_total_cookies, 2)133 self.assertGreater(num_total_cookies, num_github_cookies)134135 # save and load136 cookiejar.save(ignore_discard=True)137 cookiejar_2 = self.COOKIEJAR_CLASS(self.cookiejar_filename)138 cookiejar_2.load(ignore_discard=True)139 self.assertEqual(len(cookiejar_2), num_total_cookies)140 r = requests.get(httpbin('cookies'), cookies=cookiejar_2)141 self.assertEqual(json.loads(r.text)['cookies'], {'key': 'value'})142143class MozCookieJarTest(LWPCookieJarTest):144 """Same test, but substitute MozillaCookieJar."""145146 COOKIEJAR_CLASS = cookielib.MozillaCookieJar147148if __name__ == '__main__':149 unittest.main()
modified:tests/test_requests.py+17 added-7 removed
8 unmodified lines
9sys.path.insert(0, os.path.abspath('..'))1011import json12import os13import sys13import unittest14import pickle1516import requests
33 unmodified lines
50 # c = envoy.connect('httpbin %s' % (PORT))51 # time.sleep(1)52 _httpbin = True5354class TestBaseMixin(object):5556 def assertCookieHas(self, cookie, **kwargs):57 """Assert that a cookie has various specified properties."""58 for attr, expected_value in kwargs.iteritems():59 message = 'Failed comparison for %s' % (attr,)60 self.assertEqual(getattr(cookie, attr), expected_value, message)6156class RequestsTestSuite(TestSetup, unittest.TestCase):62class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):63 """Requests test cases."""6465 def test_entry_points(self):66
570 unmodified lines
637 r = get(httpbin('cookies'), session=s)638639 # Those cookies persist transparently.640 c = json.loads(r.text).get('cookies')635 assert c == _c641 self.assertEqual(c, _c)642643 # 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)647648 # 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)653654 # 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)659660 # 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 lines
703704 ds = pickle.loads(pickle.dumps(s))705706 self.assertEqual(s.headers, ds.headers)701 self.assertEqual(s.cookies, ds.cookies)707 self.assertEqual(s.auth, ds.auth)708709 # 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')713714 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 lines
modified:AUTHORS.rst+1 added
94 unmodified lines
95- Michael Kelly96- Michael Newman <newmaniese@gmail.com>97- Jonty Wareing <jonty@jonty.co.uk>98- Shivaram Lingamneni99- Miguel (dhagrow)