requests icon indicating copy to clipboard operation
requests copied to clipboard

Make RequestsCookieJar.popitem() work

Open vineethsaivs opened this issue 5 months ago • 1 comments

Closes #6190

RequestsCookieJar subclasses both CookieJar and MutableMapping[str, str | None]. Its __iter__ is inherited from CookieJar and yields Cookie objects rather than names. The popitem() it inherited from MutableMapping does roughly:

key = next(iter(self))   # a Cookie object, not a name
value = self[key]        # __getitem__ looks up by name -> KeyError

so popitem() always raised KeyError, even on a non-empty jar:

>>> jar = requests.cookies.RequestsCookieJar()
>>> jar.set("a", "1"); jar.set("b", "2")
>>> jar.popitem()
KeyError: "name=Cookie(version=0, name='a', ...), domain=None, path=None"

This overrides popitem() to remove and return a (name, value) pair using the jar's existing dict-like view (iteritems()), and to raise KeyError only when the jar is empty, matching the documented behavior and the MutableMapping[str, str | None] contract.

Added a regression test (test_cookie_popitem) that pops both entries, checks each returned pair is a real (name, value) from the jar, and confirms a KeyError on the empty jar. It fails on main and passes with this change.

vineethsaivs avatar Jun 13 '26 09:06 vineethsaivs

Good catch, fixed. popitem() now selects the cookie via the iterator and removes that exact object with clear(cookie.domain, cookie.path, cookie.name), so it can no longer drop other cookies that happen to share the name on a different domain or path. Added a regression test (test_cookie_popitem_removes_only_the_selected_cookie) that puts two cookies named dup on different domains and asserts popitem() removes exactly the one it returns and leaves the other intact.

vineethsaivs avatar Jun 16 '26 06:06 vineethsaivs

Nice to see RequestsCookieJar.popitem() behaving like a mapping again. A follow-up test for the empty-jar KeyError path might be useful if downstream code depends on that exception.

DTiming24 avatar Jun 25 '26 19:06 DTiming24

Good call, added test_cookie_popitem_on_empty_jar_raises_keyerror covering exactly that: popitem() on a freshly constructed jar raises KeyError, matching dict.popitem(). (The existing test_cookie_popitem reaches the empty case by popping a populated jar to zero; this isolates the never-populated jar.)

vineethsaivs avatar Jun 26 '26 19:06 vineethsaivs