From bc1c0e5ae6d7667fb1ca237236ddefe10dd307d5 Mon Sep 17 00:00:00 2001 From: Zhiwei Liang Date: Tue, 4 Jun 2024 03:58:56 -0400 Subject: [PATCH] Not to remove entity headers for 412 responses --- sanic/response/types.py | 3 +-- tests/test_response.py | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/sanic/response/types.py b/sanic/response/types.py index 9d8a8e733a..a5c3717e8b 100644 --- a/sanic/response/types.py +++ b/sanic/response/types.py @@ -104,8 +104,7 @@ def processed_headers(self) -> Iterator[Tuple[bytes, bytes]]: Returns: Iterator[Tuple[bytes, bytes]]: A list of header tuples encoded in bytes for sending """ # noqa: E501 - # TODO: Make a blacklist set of header names and then filter with that - if self.status in (304, 412): # Not Modified, Precondition Failed + if self.status == 304: # Not Modified self.headers = remove_entity_headers(self.headers) if has_message_body(self.status): self.headers.setdefault("content-type", self.content_type) diff --git a/tests/test_response.py b/tests/test_response.py index 49665229b9..ff0dcbedd8 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -18,7 +18,7 @@ from aiofiles import os as async_os from pytest import LogCaptureFixture -from sanic import Request, Sanic +from sanic import Request, Sanic, exceptions from sanic.compat import Header from sanic.constants import DEFAULT_HTTP_CONTENT_TYPE from sanic.cookies import CookieJar @@ -218,6 +218,19 @@ def test_no_content(json_app): assert "Content-Length" not in response.headers +def test_412_should_has_content_length(app: Sanic): + @app.get("/failed-precondition") + async def failed_precondition(request: Request): + raise exceptions.SanicException("Failed Precondition", status_code=412) + + request, response = app.test_client.get("/failed-precondition") + assert response.status == 412 + assert "Content-Length" in response.headers + assert response.headers["Content-Length"] == str( + len(response.text.encode()) + ) + + @pytest.fixture def streaming_app(app): @app.route("/")