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 aa63d280079..da16254310f 100644 --- a/aiohttp/cookiejar.py +++ b/aiohttp/cookiejar.py @@ -152,7 +152,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 b2f8085ef21..6ff00bf41a6 100644 --- a/tests/test_cookiejar.py +++ b/tests/test_cookiejar.py @@ -864,6 +864,27 @@ async def test_cookie_jar_clear_expired(): assert len(sut) == 0 +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()