def _make_paginated_response(path, params): results = [[ { 'id': 1, 'name': 'job_1' }, { 'id': 2, 'name': 'job_2' }, { 'id': 3, 'name': 'job_3' }, ], [ { 'id': 4, 'name': 'job_4' }, { 'id': 5, 'name': 'job_5' }, ], []] mock_endpoint = mock.MagicMock() mock_endpoint._make_request.side_effect = [ _create_mock_response(result, {}) for result in results ] mock_endpoint._return_type = 'snake' paginator = PaginatedResponse(path, params, mock_endpoint) return paginator, mock_endpoint
def _call_api(self, method, path=None, params=None, data=None, **kwargs): iterator = kwargs.pop('iterator', False) if iterator: return PaginatedResponse(path, params, self) else: resp = self._make_request(method, path, params, data, **kwargs) resp = convert_response_data_type(resp, return_type=self._return_type) return resp
def test_pagination(): results = [[ { 'id': 1, 'name': 'job_1' }, { 'id': 2, 'name': 'job_2' }, { 'id': 3, 'name': 'job_3' }, ], [ { 'id': 4, 'name': 'job_4' }, { 'id': 5, 'name': 'job_5' }, ], []] mock_endpoint = mock.MagicMock() mock_endpoint._make_request.side_effect = [ _create_mock_response(result, {}) for result in results ] mock_endpoint._return_type = 'snake' path = '/objects' params = {'param': 'value'} paginator = iter(PaginatedResponse(path, params, mock_endpoint)) # No API calls made yet. mock_endpoint._make_request.assert_not_called() all_data = [] for indx, obj in enumerate(paginator): assert obj['id'] == indx + 1 all_data.append(obj) # Test lazy evaluation. Should make only make one call up until the # first item of the second page is needed. if indx < 3: mock_endpoint._make_request.assert_called_once_with( 'GET', path, dict(params, **{'page_num': 1})) else: mock_endpoint._make_request.assert_called_with( 'GET', path, dict(params, **{'page_num': 2})) # One extra call is made. Pagination is stopped since the response is # empty. assert mock_endpoint._make_request.call_count == 3 assert len(all_data) == 5