diff --git a/src/website/pagination.go b/src/website/pagination.go index 7552244..6657725 100644 --- a/src/website/pagination.go +++ b/src/website/pagination.go @@ -3,6 +3,8 @@ package website import ( "math" "strconv" + + "git.handmade.network/hmn/hmn/src/utils" ) func getPageInfo( @@ -14,7 +16,7 @@ func getPageInfo( totalPages int, ok bool, ) { - totalPages = int(math.Ceil(float64(totalItems) / float64(itemsPerPage))) + totalPages = utils.IntMax(1, int(math.Ceil(float64(totalItems)/float64(itemsPerPage)))) ok = true page = 1 diff --git a/src/website/pagination_test.go b/src/website/pagination_test.go new file mode 100644 index 0000000..1fe5ac0 --- /dev/null +++ b/src/website/pagination_test.go @@ -0,0 +1,36 @@ +package website + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestGetPageInfo(t *testing.T) { + items := []struct { + name string + pageParam string + totalItems, perPage int + page, totalPages int + ok bool + }{ + {"good, no param", "", 85, 10, 1, 9, true}, + {"good", "2", 85, 10, 2, 9, true}, + {"too big", "10", 85, 10, 0, 0, false}, + {"too small", "0", 85, 10, 0, 0, false}, + {"pizza", "pizza", 85, 10, 0, 0, false}, + {"zero items, no param", "", 0, 10, 1, 1, true}, // should go to page 1 + {"zero items, page 1", "1", 0, 10, 1, 1, true}, + {"zero items, too big", "2", 0, 10, 0, 0, false}, + {"zero items, too small", "0", 0, 10, 0, 0, false}, + } + + for _, item := range items { + t.Run(item.name, func(t *testing.T) { + page, totalPages, ok := getPageInfo(item.pageParam, item.totalItems, item.perPage) + assert.Equal(t, item.page, page) + assert.Equal(t, item.totalPages, totalPages) + assert.Equal(t, item.ok, ok) + }) + } +}