From 75eca96a1e3d74fc648d67eb1f082caf964b45b5 Mon Sep 17 00:00:00 2001 From: aler9 <46489434+aler9@users.noreply.github.com> Date: Thu, 18 May 2023 15:29:44 +0200 Subject: [PATCH] api: fix wrong pageCount in /list endpoints (#1813) --- internal/core/api.go | 5 ++++- internal/core/api_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/internal/core/api.go b/internal/core/api.go index 7cf7bec77ef..7462c7c4c98 100644 --- a/internal/core/api.go +++ b/internal/core/api.go @@ -84,7 +84,10 @@ func paginate2(itemsPtr interface{}, itemsPerPage int, page int) int { return 0 } - pageCount := (itemsLen / itemsPerPage) + 1 + pageCount := (itemsLen / itemsPerPage) + if (itemsLen % itemsPerPage) != 0 { + pageCount++ + } min := page * itemsPerPage if min >= itemsLen { diff --git a/internal/core/api_test.go b/internal/core/api_test.go index e1d024e16e6..f9d90d021cf 100644 --- a/internal/core/api_test.go +++ b/internal/core/api_test.go @@ -78,6 +78,38 @@ func httpRequest(method string, ur string, in interface{}, out interface{}) erro return json.NewDecoder(res.Body).Decode(out) } +func TestPagination(t *testing.T) { + items := make([]int, 5) + for i := 0; i < 5; i++ { + items[i] = i + } + + pageCount, err := paginate(&items, "1", "1") + require.NoError(t, err) + require.Equal(t, 5, pageCount) + require.Equal(t, []int{1}, items) + + items = make([]int, 5) + for i := 0; i < 5; i++ { + items[i] = i + } + + pageCount, err = paginate(&items, "3", "2") + require.NoError(t, err) + require.Equal(t, 2, pageCount) + require.Equal(t, []int{4}, items) + + items = make([]int, 6) + for i := 0; i < 6; i++ { + items[i] = i + } + + pageCount, err = paginate(&items, "3", "3") + require.NoError(t, err) + require.Equal(t, 2, pageCount) + require.Equal(t, []int{5}, items) +} + func TestAPIConfigGet(t *testing.T) { // since the HTTP server is created and deleted multiple times, // we can't reuse TCP connections.