diff --git a/httpie/output/formatters/headers.py b/httpie/output/formatters/headers.py index 2188193902..4eec4ed301 100644 --- a/httpie/output/formatters/headers.py +++ b/httpie/output/formatters/headers.py @@ -14,5 +14,7 @@ def format_headers(self, headers: str) -> str: """ lines = headers.splitlines() - headers = sorted(lines[1:], key=lambda h: h.split(':')[0]) + # Field names are case insensitive, so compare them that way too. Sorting is + # stable, which keeps repeated fields in their original order. + headers = sorted(lines[1:], key=lambda h: h.split(':')[0].lower()) return '\r\n'.join(lines[:1] + headers) diff --git a/tests/test_output.py b/tests/test_output.py index 2242177dbc..e30fa5f24f 100644 --- a/tests/test_output.py +++ b/tests/test_output.py @@ -392,6 +392,19 @@ def get_headers(sort): assert f'XXX: foo{CRLF}ZZZ: foo' in r_sorted assert f'ZZZ: foo{CRLF}XXX: foo' in r_unsorted + def test_header_sort_ignores_case(self): + """Field names are case insensitive and repeated fields keep their order.""" + r = http( + '--offline', '--print=H', 'example.org', + 'set-cookie:first=1', 'X-Z:last', 'Set-Cookie:second=2', + 'accept:text/plain', + ) + names = [ + line.split(':')[0] for line in r.splitlines()[1:] + if line.split(':')[0].lower() in {'accept', 'set-cookie', 'x-z'} + ] + assert names == ['accept', 'set-cookie', 'Set-Cookie', 'X-Z'] + @pytest.mark.parametrize( 'options, expected_json', [