diff --git a/CHANGELOG.md b/CHANGELOG.md index 0497ac3508..7c4f9fb17c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ This document records all notable changes to [HTTPie](https://httpie.io). This project adheres to [Semantic Versioning](https://semver.org/). +## Unreleased + +- Sort HTTP header names case-insensitively while preserving the relative order of repeated fields. ([#1960](https://github.com/httpie/cli/issues/1960)) + ## [3.2.4](https://github.com/httpie/cli/compare/3.2.3...3.2.4) (2024-11-01) - Fix default certs loading and unpin `requests`. ([#1596](https://github.com/httpie/cli/issues/1596)) diff --git a/httpie/output/formatters/headers.py b/httpie/output/formatters/headers.py index 2188193902..1b701bee51 100644 --- a/httpie/output/formatters/headers.py +++ b/httpie/output/formatters/headers.py @@ -14,5 +14,5 @@ def format_headers(self, headers: str) -> str: """ lines = headers.splitlines() - headers = sorted(lines[1:], key=lambda h: h.split(':')[0]) + 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..5d9dc5a4cb 100644 --- a/tests/test_output.py +++ b/tests/test_output.py @@ -19,6 +19,7 @@ from httpie.cli.definition import parser from httpie.encoding import UTF8 from httpie.output.formatters.colors import get_lexer, PIE_STYLE_NAMES, BUNDLED_STYLES +from httpie.output.formatters.headers import HeadersFormatter from httpie.status import ExitStatus from .fixtures import XML_DATA_RAW, XML_DATA_FORMATTED from .utils import COLOR, CRLF, HTTP_OK, MockEnvironment, http, DUMMY_URL, strip_colors @@ -378,6 +379,27 @@ def test_CRLF_formatted_request(self, httpbin): class TestFormatOptions: + def test_header_sort_is_case_insensitive_and_stable(self): + formatter = HeadersFormatter( + env=MockEnvironment(), + format_options=PARSED_DEFAULT_FORMAT_OPTIONS, + ) + headers = ( + 'HTTP/1.1 200 OK\n' + 'set-cookie: first=1\n' + 'X-Z: last\n' + 'Set-Cookie: second=2\n' + 'accept: text/plain' + ) + + assert formatter.format_headers(headers) == ( + 'HTTP/1.1 200 OK\r\n' + 'accept: text/plain\r\n' + 'set-cookie: first=1\r\n' + 'Set-Cookie: second=2\r\n' + 'X-Z: last' + ) + def test_header_formatting_options(self): def get_headers(sort): return http(