diff --git a/CHANGES/7784.bugfix b/CHANGES/7784.bugfix new file mode 100644 index 00000000000..1f8ba8ddb44 --- /dev/null +++ b/CHANGES/7784.bugfix @@ -0,0 +1 @@ +Fix duplicate cookie expiration calls in the CookieJar implementation diff --git a/aiohttp/cookiejar.py b/aiohttp/cookiejar.py index 87f05a0de3c..3c7629c7f33 100644 --- a/aiohttp/cookiejar.py +++ b/aiohttp/cookiejar.py @@ -154,7 +154,12 @@ def __iter__(self) -> "Iterator[Morsel[str]]": yield from val.values() def __len__(self) -> int: - return sum(1 for i in self) + """Return number of cookies. + + This function does not iterate self to avoid unnecessary expiration + checks. + """ + return sum(len(cookie.values()) for cookie in self._cookies.values()) def _do_expiration(self) -> None: self.clear(lambda x: False) diff --git a/tests/test_cookiejar.py b/tests/test_cookiejar.py index 70ab0a4864e..261dbecd992 100644 --- a/tests/test_cookiejar.py +++ b/tests/test_cookiejar.py @@ -854,7 +854,28 @@ async def test_cookie_jar_clear_expired(): assert len(sut) == 0 -async def test_cookie_jar_clear_domain(): +async def test_cookie_jar_filter_cookies_expires(): + """Test that calling filter_cookies will expire stale cookies.""" + jar = CookieJar() + assert len(jar) == 0 + + cookie = SimpleCookie() + + cookie["foo"] = "bar" + cookie["foo"]["expires"] = "Tue, 1 Jan 1990 12:00:00 GMT" + + with freeze_time("1980-01-01"): + jar.update_cookies(cookie) + + assert len(jar) == 1 + + # filter_cookies should expire stale cookies + jar.filter_cookies(URL("http://any.com/")) + + assert len(jar) == 0 + + +async def test_cookie_jar_clear_domain() -> None: sut = CookieJar() cookie = SimpleCookie() cookie["foo"] = "bar"