diff --git a/CHANGES/9172.misc.rst b/CHANGES/9172.misc.rst new file mode 120000 index 00000000000..d6a2f2aaaab --- /dev/null +++ b/CHANGES/9172.misc.rst @@ -0,0 +1 @@ +9174.misc.rst \ No newline at end of file diff --git a/aiohttp/web_response.py b/aiohttp/web_response.py index d4f18271a83..2ba135f54d2 100644 --- a/aiohttp/web_response.py +++ b/aiohttp/web_response.py @@ -759,10 +759,10 @@ async def write_eof(self, data: bytes = b"") -> None: await super().write_eof() async def _start(self, request: "BaseRequest") -> AbstractStreamWriter: - if should_remove_content_length(request.method, self.status): - if hdrs.CONTENT_LENGTH in self._headers: + if hdrs.CONTENT_LENGTH in self._headers: + if should_remove_content_length(request.method, self.status): del self._headers[hdrs.CONTENT_LENGTH] - elif not self._chunked and hdrs.CONTENT_LENGTH not in self._headers: + elif not self._chunked: if isinstance(self._body, Payload): if self._body.size is not None: self._headers[hdrs.CONTENT_LENGTH] = str(self._body.size) diff --git a/tests/test_web_response.py b/tests/test_web_response.py index b71730868e4..264ca5e93ee 100644 --- a/tests/test_web_response.py +++ b/tests/test_web_response.py @@ -667,6 +667,22 @@ async def write_headers(status_line, headers): assert resp.content_length is None +async def test_rm_content_length_if_204() -> None: + """Ensure content-length is removed for 204 responses.""" + writer = mock.create_autospec(StreamWriter, spec_set=True, instance=True) + + async def write_headers(status_line, headers): + assert hdrs.CONTENT_LENGTH not in headers + + writer.write_headers.side_effect = write_headers + req = make_request("GET", "/", writer=writer) + payload = BytesPayload(b"answer", headers={"Content-Length": "6"}) + resp = Response(body=payload, status=204) + resp.body = payload + await resp.prepare(req) + assert resp.content_length is None + + @pytest.mark.parametrize("status", (100, 101, 204, 304)) async def test_rm_transfer_encoding_rfc_9112_6_3_http_11(status: int) -> None: """Remove transfer encoding for RFC 9112 sec 6.3 with HTTP/1.1."""