Skip to content

Commit

Permalink
Implement 'RequestsCookieJar.popitem' independantly
Browse files Browse the repository at this point in the history
  • Loading branch information
kianelbo committed Sep 2, 2023
1 parent d7d8920 commit 2fd8d11
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
19 changes: 11 additions & 8 deletions src/requests/cookies.py
Expand Up @@ -325,16 +325,14 @@ def __contains__(self, name):
except CookieConflictError:
return True

def __getitem__(self, key):
def __getitem__(self, name):
"""Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1).
"""
if isinstance(key, Cookie):
key = key.name
return self._find_no_duplicates(key)
return self._find_no_duplicates(name)

def __setitem__(self, name, value):
"""Dict-like __setitem__ for compatibility with client code. Throws
Expand All @@ -343,13 +341,18 @@ def __setitem__(self, name, value):
"""
self.set(name, value)

def __delitem__(self, key):
def __delitem__(self, name):
"""Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s
``remove_cookie_by_name()``.
"""
if isinstance(key, Cookie):
key = key.name
remove_cookie_by_name(self, key)
remove_cookie_by_name(self, name)

def popitem(self):
if not self:
raise KeyError("Cookie jar is empty")
next_cookie = next(iter(self))
self.clear(next_cookie.domain, next_cookie.path, next_cookie.name)
return next_cookie, next_cookie.value

def set_cookie(self, cookie, *args, **kwargs):
if (
Expand Down
5 changes: 3 additions & 2 deletions tests/test_requests.py
Expand Up @@ -1378,10 +1378,11 @@ def test_cookies_popitem(self):
expected_jar.set("2nd_key", "2nd_value")
assert jar == expected_jar

jar.set("2nd_key", "another_value")
jar.set("2nd_key", "2nd_value", path="another_path")
jar.set("2nd_key", "2nd_value", path="another_path", domain="another_dom")
cookie = next(iter(jar))
assert jar.popitem() == (cookie, cookie.value)

assert len(jar) == 2

def test_cookie_policy_copy(self):
class MyCookiePolicy(cookielib.DefaultCookiePolicy):
Expand Down

0 comments on commit 2fd8d11

Please sign in to comment.