From 3b08e9c07a80b9bbbb6d953f034d986129a42478 Mon Sep 17 00:00:00 2001 From: Gore Williams <88089185+gorewilliams@users.noreply.github.com> Date: Fri, 4 Sep 2026 14:42:03 +0300 Subject: [PATCH] Improve invalid header encoding errors --- src/httpx2/httpx2/_models.py | 13 ++++++------- tests/httpx2/models/test_headers.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/httpx2/httpx2/_models.py b/src/httpx2/httpx2/_models.py index 0272f36d..3092bce9 100644 --- a/src/httpx2/httpx2/_models.py +++ b/src/httpx2/httpx2/_models.py @@ -152,15 +152,14 @@ def __init__( if isinstance(headers, Headers): self._list = list(headers._list) - elif isinstance(headers, Mapping): - for k, v in headers.items(): - bytes_key = _normalize_header_key(k, encoding) - bytes_value = _normalize_header_value(v, encoding) - self._list.append((bytes_key, bytes_key.lower(), bytes_value)) elif headers is not None: - for k, v in headers: + header_items = headers.items() if isinstance(headers, Mapping) else headers + for k, v in header_items: bytes_key = _normalize_header_key(k, encoding) - bytes_value = _normalize_header_value(v, encoding) + try: + bytes_value = _normalize_header_value(v, encoding) + except UnicodeEncodeError as exc: + raise ValueError(f"Unable to encode header value for {k!r}") from exc self._list.append((bytes_key, bytes_key.lower(), bytes_value)) self._encoding = encoding diff --git a/tests/httpx2/models/test_headers.py b/tests/httpx2/models/test_headers.py index 666b7886..fd081643 100644 --- a/tests/httpx2/models/test_headers.py +++ b/tests/httpx2/models/test_headers.py @@ -36,6 +36,22 @@ def test_headers() -> None: assert repr(h) == "Headers({'a': '123', 'b': '789'})" +@pytest.mark.parametrize( + "headers", + [ + {"auth": "שלום"}, + [("auth", "שלום")], + ], +) +def test_header_value_encoding_error_includes_header_name( + headers: dict[str, str] | list[tuple[str, str]], +) -> None: + with pytest.raises(ValueError, match="auth") as exc_info: + httpx2.Headers(headers) + + assert isinstance(exc_info.value.__cause__, UnicodeEncodeError) + + def test_header_mutations() -> None: h = httpx2.Headers() assert dict(h) == {}