diff --git a/src/aignostics/platform/resources/utils.py b/src/aignostics/platform/resources/utils.py index 052a17a27..d8211ec2d 100644 --- a/src/aignostics/platform/resources/utils.py +++ b/src/aignostics/platform/resources/utils.py @@ -30,16 +30,24 @@ def paginate(func: Callable[..., list[T]], *args: object, page_size: int = PAGE_ page_size (int): The number of items to request per page **kwargs: Keyword arguments to pass to the function. + Raises: + ValueError: If page_size is 0 or negative. + Yields: Individual items from all pages. Example: >>> def list_items(page=1, page_size=20): - ... # API call that returns a list of items for the given page - ... return [f"item_{i}" for i in range(page_size)] + ... offset = (page - 1) * page_size + ... count = page_size if page == 1 else 5 # partial last page + ... return [f"item_{offset + i}" for i in range(count)] >>> items = list(paginate(list_items)) >>> print(len(items)) + 25 """ + if page_size <= 0: + message = f"page_size must be a positive integer, got {page_size}" + raise ValueError(message) page = 1 while True: try: diff --git a/tests/aignostics/platform/resources/resource_utils_test.py b/tests/aignostics/platform/resources/resource_utils_test.py index b1d1d2657..ef602409f 100644 --- a/tests/aignostics/platform/resources/resource_utils_test.py +++ b/tests/aignostics/platform/resources/resource_utils_test.py @@ -94,6 +94,15 @@ def test_paginate_custom_page_size() -> None: mock_func.assert_called_once_with(page=1, page_size=custom_page_size) +@pytest.mark.unit +@pytest.mark.parametrize("page_size", [0, -1, -100]) +def test_paginate_raises_for_non_positive_page_size(page_size: int) -> None: + """Test that paginate raises ValueError when page_size is zero or negative.""" + mock_func = Mock() + with pytest.raises(ValueError, match="page_size must be a positive integer"): + list(paginate(mock_func, page_size=page_size)) + + @pytest.mark.unit def test_paginate_multiple_pages() -> None: """Test that paginate correctly iterates through multiple pages.