Skip to content

Commit 4b159bb

Browse files
Harden list parser key-display fallbacks
Co-authored-by: Shri Sukhani <shrisukhani@users.noreply.github.com>
1 parent 106c606 commit 4b159bb

2 files changed

Lines changed: 42 additions & 1 deletion

File tree

‎hyperbrowser/client/managers/list_parsing_utils.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,20 @@
66
T = TypeVar("T")
77

88

9+
def _safe_key_display_for_error(
10+
key: str,
11+
*,
12+
key_display: Callable[[str], str],
13+
) -> str:
14+
try:
15+
key_text = key_display(key)
16+
if type(key_text) is not str:
17+
raise TypeError("key display must be a string")
18+
return key_text
19+
except Exception:
20+
return "<unreadable key>"
21+
22+
923
def parse_mapping_list_items(
1024
items: List[Any],
1125
*,
@@ -41,8 +55,9 @@ def parse_mapping_list_items(
4155
except HyperbrowserError:
4256
raise
4357
except Exception as exc:
58+
key_text = _safe_key_display_for_error(key, key_display=key_display)
4459
raise HyperbrowserError(
45-
f"Failed to read {item_label} object value for key '{key_display(key)}' at index {index}",
60+
f"Failed to read {item_label} object value for key '{key_text}' at index {index}",
4661
original_error=exc,
4762
) from exc
4863
try:

‎tests/test_list_parsing_utils.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,32 @@ def test_parse_mapping_list_items_wraps_value_read_failures():
102102
assert isinstance(exc_info.value.original_error, RuntimeError)
103103

104104

105+
def test_parse_mapping_list_items_falls_back_when_key_display_raises():
106+
with pytest.raises(
107+
HyperbrowserError,
108+
match="Failed to read demo object value for key '<unreadable key>' at index 0",
109+
):
110+
parse_mapping_list_items(
111+
[_ExplodingValueMapping()],
112+
item_label="demo",
113+
parse_item=lambda payload: payload,
114+
key_display=lambda key: 1 / 0,
115+
)
116+
117+
118+
def test_parse_mapping_list_items_falls_back_when_key_display_returns_non_string():
119+
with pytest.raises(
120+
HyperbrowserError,
121+
match="Failed to read demo object value for key '<unreadable key>' at index 0",
122+
):
123+
parse_mapping_list_items(
124+
[_ExplodingValueMapping()],
125+
item_label="demo",
126+
parse_item=lambda payload: payload,
127+
key_display=lambda key: key.encode("utf-8"),
128+
)
129+
130+
105131
def test_parse_mapping_list_items_wraps_parse_failures():
106132
with pytest.raises(
107133
HyperbrowserError,

0 commit comments

Comments
 (0)