Skip to content

Commit c9df765

Browse files
Wrap header mapping iteration failures
Co-authored-by: Shri Sukhani <shrisukhani@users.noreply.github.com>
1 parent 750f476 commit c9df765

2 files changed

Lines changed: 44 additions & 1 deletion

File tree

hyperbrowser/header_utils.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,17 @@
88
_MAX_HEADER_NAME_LENGTH = 256
99

1010

11+
def _read_header_items(
12+
headers: Mapping[str, str], *, mapping_error_message: str
13+
) -> list[tuple[object, object]]:
14+
try:
15+
return list(headers.items())
16+
except HyperbrowserError:
17+
raise
18+
except Exception as exc:
19+
raise HyperbrowserError(mapping_error_message, original_error=exc) from exc
20+
21+
1122
def normalize_headers(
1223
headers: Optional[Mapping[str, str]],
1324
*,
@@ -22,7 +33,9 @@ def normalize_headers(
2233
effective_pair_error_message = pair_error_message or mapping_error_message
2334
normalized_headers: Dict[str, str] = {}
2435
seen_header_names = set()
25-
for key, value in headers.items():
36+
for key, value in _read_header_items(
37+
headers, mapping_error_message=mapping_error_message
38+
):
2639
if not isinstance(key, str) or not isinstance(value, str):
2740
raise HyperbrowserError(effective_pair_error_message)
2841
normalized_key = key.strip()

tests/test_header_utils.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@
88
)
99

1010

11+
class _BrokenHeadersMapping(dict):
12+
def items(self):
13+
raise RuntimeError("broken header iteration")
14+
15+
1116
def test_normalize_headers_trims_header_names():
1217
headers = normalize_headers(
1318
{" X-Correlation-Id ": "abc123"},
@@ -161,3 +166,28 @@ def test_merge_headers_rejects_duplicate_base_header_names_case_insensitive():
161166
None,
162167
mapping_error_message="headers must be a mapping of string pairs",
163168
)
169+
170+
171+
def test_normalize_headers_wraps_mapping_iteration_failures():
172+
with pytest.raises(
173+
HyperbrowserError, match="headers must be a mapping of string pairs"
174+
) as exc_info:
175+
normalize_headers(
176+
_BrokenHeadersMapping({"X-Trace-Id": "abc123"}),
177+
mapping_error_message="headers must be a mapping of string pairs",
178+
)
179+
180+
assert exc_info.value.original_error is not None
181+
182+
183+
def test_merge_headers_wraps_override_mapping_iteration_failures():
184+
with pytest.raises(
185+
HyperbrowserError, match="headers must be a mapping of string pairs"
186+
) as exc_info:
187+
merge_headers(
188+
{"X-Trace-Id": "abc123"},
189+
_BrokenHeadersMapping({"X-Correlation-Id": "corr-1"}),
190+
mapping_error_message="headers must be a mapping of string pairs",
191+
)
192+
193+
assert exc_info.value.original_error is not None

0 commit comments

Comments
 (0)