Skip to content

Commit f86aa76

Browse files
committed
test: add regression test for Content-Type conflict in _add_from_file
Fixes the case where a YAML fixture has Content-Type in both headers and content_type fields — the recorder captures both, causing RuntimeError when _add_from_file calls add(). Added test_add_from_file_content_type_in_headers to verify the fix works end-to-end with a YAML fixture.
1 parent f514023 commit f86aa76

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

responses/tests/test_recorder.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,3 +238,63 @@ def _parse_resp_f(file_path):
238238
assert responses.registered()[3].content_type == "text/plain"
239239

240240
run()
241+
242+
def test_add_from_file_content_type_in_headers(self):
243+
"""Fixture files may contain Content-Type in both headers and content_type.
244+
245+
The recorder captures ``Content-Type`` inside the ``headers`` dict *and*
246+
as the dedicated ``content_type`` field. Passing both to ``add()``
247+
raises a ``RuntimeError`` because ``content_type`` and a ``Content-Type``
248+
header conflict. ``_add_from_file`` should strip the duplicate header
249+
entry so that the dedicated ``content_type`` kwarg wins.
250+
"""
251+
data = {
252+
"responses": [
253+
{
254+
"response": {
255+
"method": "GET",
256+
"url": "http://example.com/api",
257+
"body": '{"status": "ok"}',
258+
"status": 200,
259+
"headers": {"Content-Type": "application/json"},
260+
"content_type": "application/json",
261+
"auto_calculate_content_length": False,
262+
}
263+
},
264+
{
265+
"response": {
266+
"method": "POST",
267+
"url": "http://example.com/submit",
268+
"body": "created",
269+
"status": 201,
270+
"headers": {
271+
"Content-Type": "text/plain",
272+
"X-Request-Id": "abc123",
273+
},
274+
"content_type": "text/plain",
275+
"auto_calculate_content_length": False,
276+
}
277+
},
278+
]
279+
}
280+
281+
with open(self.out_file, "w") as f:
282+
yaml.dump(data, f)
283+
284+
@responses.activate
285+
def run():
286+
responses._add_from_file(file_path=self.out_file)
287+
288+
# Verify responses were registered without RuntimeError
289+
assert len(responses.registered()) == 2
290+
291+
assert responses.registered()[0].url == "http://example.com/api"
292+
assert responses.registered()[0].content_type == "application/json"
293+
294+
assert responses.registered()[1].url == "http://example.com/submit"
295+
assert responses.registered()[1].content_type == "text/plain"
296+
# Non-content-type headers should be preserved
297+
resp = requests.post("http://example.com/submit")
298+
assert resp.headers["X-Request-Id"] == "abc123"
299+
300+
run()

0 commit comments

Comments
 (0)