From fd968a3ffaf2f6f1f0a7c07d2952e8d02c65da4b Mon Sep 17 00:00:00 2001 From: Maksim Beliaev Date: Sat, 23 Sep 2023 01:00:50 +0200 Subject: [PATCH] deduplicate content-type headers --- CHANGES | 1 + responses/__init__.py | 9 ++++++++- responses/tests/test_responses.py | 23 +++++++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/CHANGES b/CHANGES index 59a59252..a1d27a3a 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,7 @@ * Added support for re.Pattern based header matching. * Added support for gzipped response bodies to `json_params_matcher`. +* Fix `Content-Type` headers issue when the header was duplicated. See #644 * Moved types-pyyaml dependency to `tests_requires` 0.23.3 diff --git a/responses/__init__.py b/responses/__init__.py index fb0a5fc2..655c99cd 100644 --- a/responses/__init__.py +++ b/responses/__init__.py @@ -479,10 +479,17 @@ def _req_attr_matches( def get_headers(self) -> HTTPHeaderDict: headers = HTTPHeaderDict() # Duplicate headers are legal - if self.content_type is not None: + + # Add Content-Type if it exists and is not already in headers + if self.content_type and ( + not self.headers or "Content-Type" not in self.headers + ): headers["Content-Type"] = self.content_type + + # Extend headers if they exist if self.headers: headers.extend(self.headers) + return headers def get_response(self, request: "PreparedRequest") -> HTTPResponse: diff --git a/responses/tests/test_responses.py b/responses/tests/test_responses.py index 2ae3d655..02db63e2 100644 --- a/responses/tests/test_responses.py +++ b/responses/tests/test_responses.py @@ -1330,6 +1330,29 @@ def run(): assert_reset() +def test_headers_deduplicated_content_type(): + """Test to ensure that we do not have two values for `content-type`. + + For more details see https://github.com/getsentry/responses/issues/644 + """ + + @responses.activate + def run(): + responses.get( + "https://example.org/", + json={}, + headers={"Content-Type": "application/json"}, + ) + responses.start() + + resp = requests.get("https://example.org/") + + assert resp.headers["Content-Type"] == "application/json" + + run() + assert_reset() + + def test_content_length_error(monkeypatch): """ Currently 'requests' does not enforce content length validation,