Skip to content
Myr

Wrote tests for new CookieJar functionality and made them pass.

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

authored by Josh Imhoff · committed by Josh Imhoff · parent 9f26d0c · Browse files · 2 files+71 added−23 removed
This commit

State

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

Diff stats

2 files+71 added−23 removed

  • tests:+33 added−0 removed
  • other:+38 added−23 removed

2 files+71 added−23 removed

modified:requests/cookies.py+38 added-23 removed
139 unmodified lines
140141 Unlike a regular CookieJar, this class is pickleable.142 """143144 # TODO test, test, test144 def get(self, name, default=None, domain=None, path=None):145 """Dict-like get() that also supports optional domain and path args in146 order to resolve naming collisions from using one cookie jar over147 multiple domains. Caution: operation is O(n), not O(1)."""148 try:150 return self._find(name, domain, path)149 return self._find_no_duplicates(name, domain, path)150 except KeyError:151 return default152153 def set(self, name, value, **kwargs):
11 unmodified lines
165 c = create_cookie(name, value, **kwargs)166 self.set_cookie(c)167 return c168170 def keys():169 def keys(self):170 """Dict-like keys() that returns a list of names of cookies from the jar.171 See values() and items()."""172 keys = []173 for cookie in iter(self):174 keys.append(cookie.name)175 return keys176178 def values():177 def values(self):178 """Dict-like values() that returns a list of values of cookies from the jar.179 See keys() and items()."""180 values = []181 for cookie in iter(self):183 values.append(cookie.values)182 values.append(cookie.value)183 return values184 186 def items():185 def items(self):186 """Dict-like items() that returns a list of name-value tuples from the jar.187 See keys() and values(). Allows client-code to call "dict(RequestsCookieJar)188 and get a vanilla python dict of key value pairs."""189 items = []190 for cookie in iter(self):192 items.append((cookies.name, cookie.values))191 items.append((cookie.name, cookie.value))192 return items193194 def list_domains(self):195 """Utility method to list all the domains in the jar."""
10 unmodified lines
206 if cookie.path not in paths:207 paths.append(cookie.path)208 return paths209210 def multiple_domains(self):211 """Returns True if there are multiple domains in the jar.212 Returns False otherwise."""213 domains = []214 for cookie in iter(self):215 if cookie.domain is not None and cookie.domain in domains:216 return True217 domains.append(cookie.domain)218 return False # there is only one domain in jar219220 def get_dict(self, domain=None, path=None):221 """Takes as an argument an optional domain and path and returns a plain old222 Python dict of name-value pairs of cookies that meet the requirements."""223 dictionary = {}224 for cookie in iter(self):225 print path226 print cookie.path227 if (domain == None or cookie.domain == domain) and (path == None 228 or cookie.path == path):229 dictionary[cookie.name] = cookie.value230 return dictionary
1 unmodified line
232 def __getitem__(self, name):233 """Dict-like __getitem__() for compatibility with client code. Throws exception234 if there are more than one cookie with name. In that case, use the more235 explicit get() method instead. Caution: operation is O(n), not O(1)."""225 return self._find(name)236 return self._find_no_duplicates(name)237238 def __setitem__(self, name, value):239 """Dict-like __setitem__ for compatibility with client code. Throws exception240 if there is already a cookie of that name in the jar. In that case, use the more
4 unmodified lines
245 """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name()."""246 remove_cookie_by_name(self, name)247248 def _find(self, name, domain=None, path=None):238 """Requests uses this method internally to find cookies. Takes as args name 239 and optional domain and path. Returns a cookie.value. Throws KeyError240 if cookie is not found and CookieConflictError if there are multiple cookies241 that match name and optionally domain and path."""249 """Requests uses this method internally to get cookie values. Takes as args name 250 and optional domain and path. Returns a cookie.value. If there are conflicting cookies,251 _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown252 if there are conflicting cookies."""253 for cookie in iter(self):254 if cookie.name == name:255 if domain is None or cookie.domain == domain:256 if path is None or cookie.path == path:257 return cookie.value258259 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))260261 def _find_no_duplicates(self, name, domain=None, path=None):262 """__get_item__ and get call _find_no_duplicates -- never used in Requests internally. 263 Takes as args name and optional domain and path. Returns a cookie.value. 264 Throws KeyError if cookie is not found and CookieConflictError if there are 265 multiple cookies that match name and optionally domain and path."""266 toReturn = None267 for cookie in iter(self):268 if cookie.name == name:269 if domain is None or cookie.domain == domain:
5 unmodified lines
275 if toReturn:276 return toReturn277 raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))278255 def _multipleDomains(self):256 """Returns True if there are multiple domains in the jar.257 Returns False otherwise."""258 domains = []259 for cookie in iter(self):260 if cookie.domain is not None and cookie.domain in domains:261 return True262 domains.append(cookie.domain)263 return False # there is only one domain in jar264265 # TODO docstrings279 def __getstate__(self):280 """Unlike a normal CookieJar, this class is pickleable."""281 state = self.__dict__.copy()282 # remove the unpickleable RLock object283 state.pop('_cookies_lock')284 return state285286 def __setstate__(self, state):287 """Unlike a normal CookieJar, this class is pickleable."""288 self.__dict__.update(state)289 if '_cookies_lock' not in self.__dict__:290 self._cookies_lock = threading.RLock()291
74 unmodified lines
modified:tests/test_cookies.py+33 added
22 unmodified lines
23 r = requests.get(httpbin('cookies', 'set', 'myname', 'myvalue'))2425 # test deprecated dictionary interface26 self.assertEqual(r.cookies['myname'], 'myvalue')27 self.assertEqual(r.cookies.get('myname'), 'myvalue')28 # test CookieJar interface29 jar = r.cookies30 self.assertEqual(len(jar), 1)31 cookie_from_jar = list(jar)[0]
90 unmodified lines
122 s.get(httpbin('cookies', 'set', 'key', 'value'), store_cookies = False)123 r = s.get(httpbin('cookies'))124 self.assertEqual(json.loads(r.text)['cookies'], {})125126 def test_jar_utility_functions(self):127 """Test utility functions such as list_domains, list_paths, multiple_domains."""128 r = requests.get("http://github.com")129 c = r.cookies130 # github should send us cookies131 self.assertTrue(len(c) >= 1)132 self.assertEqual(len(c), len(r.cookies.keys()))133 self.assertEqual(len(c), len(r.cookies.values()))134 self.assertEqual(len(c), len(r.cookies.items()))135 136 # domain and path utility functions137 domain = r.cookies.list_domains()[0]138 path = r.cookies.list_paths()[0]139 self.assertEqual(dict(r.cookies), r.cookies.get_dict(domain=domain, path=path))140 self.assertEqual(len(r.cookies.list_domains()), 1)141 self.assertEqual(len(r.cookies.list_paths()), 1)142 self.assertFalse(r.cookies.multiple_domains())143144 def test_convert_jar_to_dict(self):145 """Test that keys, values, and items are defined and that we can convert146 cookie jars to plain old Python dicts."""147 r = requests.get(httpbin('cookies', 'set', 'myname', 'myvalue'))148149 # test keys, values, and items150 self.assertEqual(r.cookies.keys(), ['myname'])151 self.assertEqual(r.cookies.values(), ['myvalue'])152 self.assertEqual(r.cookies.items(), [('myname','myvalue')])153 154 # test if we can convert jar to dict155 dictOfCookies = dict(r.cookies)156 self.assertEqual(dictOfCookies, {'myname':'myvalue'})157 self.assertEqual(dictOfCookies, r.cookies.get_dict())158159class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):160 """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""161162 COOKIEJAR_CLASS = cookielib.LWPCookieJar
99 unmodified lines