From 11a0b15194be42c0474d968444b12c650eeb6c1f Mon Sep 17 00:00:00 2001 From: Liam Coatman Date: Sun, 9 Jul 2023 08:34:40 +0100 Subject: [PATCH] Handle case when `headers` argument of `ResponseStream` constructor is `None` (#2729) * Handle case when headers is None * Add test for response stream with default headers * Move test --------- Co-authored-by: Adam Hopkins --- sanic/response/types.py | 4 +++- tests/test_response.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/sanic/response/types.py b/sanic/response/types.py index 3c897935..73a997da 100644 --- a/sanic/response/types.py +++ b/sanic/response/types.py @@ -522,7 +522,9 @@ class ResponseStream: headers: Optional[Union[Header, Dict[str, str]]] = None, content_type: Optional[str] = None, ): - if not isinstance(headers, Header): + if headers is None: + headers = Header() + elif not isinstance(headers, Header): headers = Header(headers) self.streaming_fn = streaming_fn self.status = status diff --git a/tests/test_response.py b/tests/test_response.py index 8d2d9e08..65a875cd 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -23,6 +23,7 @@ from sanic.compat import Header from sanic.cookies import CookieJar from sanic.response import ( HTTPResponse, + ResponseStream, empty, file, file_stream, @@ -943,3 +944,17 @@ def test_file_validating_304_response( ) assert response.status == 304 assert response.body == b"" + + +def test_stream_response_with_default_headers(app: Sanic): + async def sample_streaming_fn(response_): + await response_.write("foo") + + @app.route("/") + async def test(request: Request): + return ResponseStream(sample_streaming_fn, content_type="text/csv") + + _, response = app.test_client.get("/") + assert response.text == "foo" + assert response.headers["Transfer-Encoding"] == "chunked" + assert response.headers["Content-Type"] == "text/csv"