diff --git a/imednet/core/paginator.py b/imednet/core/paginator.py index cefbd9bd..76914d03 100644 --- a/imednet/core/paginator.py +++ b/imednet/core/paginator.py @@ -47,7 +47,12 @@ def _extract_items(self, payload: Dict[str, Any]) -> list[Any]: return items def _next_page(self, payload: Dict[str, Any], page: int) -> Optional[int]: - pagination = payload.get("pagination") or {} + pagination = payload.get("pagination") + if pagination is not None and not isinstance(pagination, dict): + raise TypeError( + f"Response field 'pagination' must be a dictionary, got {type(pagination).__name__}" + ) + pagination = pagination or {} total_pages = pagination.get("totalPages") if total_pages is None or page >= total_pages - 1: return None diff --git a/tests/unit/test_paginator_robustness.py b/tests/unit/test_paginator_robustness.py index cea02859..40922934 100644 --- a/tests/unit/test_paginator_robustness.py +++ b/tests/unit/test_paginator_robustness.py @@ -50,3 +50,17 @@ def test_paginator_raises_type_error_on_invalid_data_key(): with pytest.raises(TypeError, match="Expected a list of items"): list(paginator) + + +def test_paginator_raises_type_error_on_invalid_pagination_field(): + """ + Test that the Paginator raises a helpful TypeError when the pagination key in the response + is not a dictionary. + """ + # unexpected: 'pagination' is a string, not a dict + client = MockClient({"data": [{"id": 1}], "pagination": "invalid_structure"}) + paginator = Paginator(client, "/path") + + # Before the fix, this raises AttributeError because it tries to call .get() on a string + with pytest.raises(TypeError, match="Response field 'pagination' must be a dictionary"): + list(paginator)