From f8cf09ab8ce64ed887bd4a38acdcc24c3552692f Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 12 Dec 2024 14:57:05 +0100 Subject: [PATCH] Raise `TypeError` when setting `StreamResponse.last_modified` to an unsupported type (#10146) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What do these changes do? closes #10143 ## Are there changes in behavior for the user? Currently this would silently fail and discard the new value. Screenshot 2024-12-08 at 12 32 49 PM (cherry picked from commit a818e51cbba7daf8c7cebd246d9a0ba214ebeba3) --- CHANGES/10146.misc.rst | 1 + aiohttp/web_response.py | 3 +++ tests/test_web_response.py | 7 +++++++ 3 files changed, 11 insertions(+) create mode 100644 CHANGES/10146.misc.rst diff --git a/CHANGES/10146.misc.rst b/CHANGES/10146.misc.rst new file mode 100644 index 00000000000..bee4ef68fb3 --- /dev/null +++ b/CHANGES/10146.misc.rst @@ -0,0 +1 @@ +Setting :attr:`aiohttp.web.StreamResponse.last_modified` to an unsupported type will now raise :exc:`TypeError` instead of silently failing -- by :user:`bdraco`. diff --git a/aiohttp/web_response.py b/aiohttp/web_response.py index e498a905caf..e068b11f8e1 100644 --- a/aiohttp/web_response.py +++ b/aiohttp/web_response.py @@ -370,6 +370,9 @@ def last_modified( ) elif isinstance(value, str): self._headers[hdrs.LAST_MODIFIED] = value + else: + msg = f"Unsupported type for last_modified: {type(value).__name__}" # type: ignore[unreachable] + raise TypeError(msg) @property def etag(self) -> Optional[ETag]: diff --git a/tests/test_web_response.py b/tests/test_web_response.py index f4acf23f61b..2a3e09ae5c6 100644 --- a/tests/test_web_response.py +++ b/tests/test_web_response.py @@ -255,6 +255,13 @@ def test_last_modified_reset() -> None: assert resp.last_modified is None +def test_last_modified_invalid_type() -> None: + resp = web.StreamResponse() + + with pytest.raises(TypeError, match="Unsupported type for last_modified: object"): + resp.last_modified = object() # type: ignore[assignment] + + @pytest.mark.parametrize( ["header_val", "expected"], [