Skip to content
Closed
8 changes: 7 additions & 1 deletion haystack/utils/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ def expand_page_range(page_range: list[str | int]) -> list[int]:
:param page_range: List of page numbers and ranges
:returns:
An expanded list of page integers
:raises ValueError:
If any element is not a valid integer or a range string in the format ``'start-end'``.

"""
expanded_page_range = []
Expand All @@ -55,7 +57,11 @@ def expand_page_range(page_range: list[str | int]) -> list[int]:
expanded_page_range.append(int(page))

elif isinstance(page, str) and "-" in page:
start, end = page.split("-")
parts = page.split("-", maxsplit=1)
if len(parts) != 2 or not parts[0].isdigit() or not parts[1].isdigit():
msg = "range must be a string in the format 'start-end'"
raise ValueError(f"Invalid page range: {page} - {msg}")
start, end = parts
expanded_page_range.extend(range(int(start), int(end) + 1))

else:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
fixes:
- |
Fixed a ``ValueError: too many values to unpack`` raised when a page range string
contained more than one hyphen (e.g. ``"10-20-30"``). The parser now validates the
format and raises a clear ``ValueError`` with an explanatory message for invalid inputs.
7 changes: 7 additions & 0 deletions test/utils/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
_normalize_metadata_field_name,
_parse_dict_from_json,
_reciprocal_rank_fusion,
expand_page_range,
)


Expand Down Expand Up @@ -168,3 +169,9 @@ def test_parse_dict_from_json_missing_keys_raise_false(self, mock_logger):
assert "Missing expected keys in JSON: {missing_keys}" in args[0]
assert kwargs["missing_keys"] == ["key2"]
assert kwargs["keys"] == ["key1"]


class TestExpandPageRange:
def test_malformed_range_with_multiple_hyphens_raises_clear_valueerror(self):
with pytest.raises(ValueError, match="Invalid page range"):
expand_page_range(["1-3", "5-10-15"])
Loading