From 482232b69f0b4af885ab21d311daf0b146de76d8 Mon Sep 17 00:00:00 2001 From: ykkssyaa Date: Thu, 23 May 2024 13:02:03 +0300 Subject: [PATCH] test pagination --- pkg/pagination/pagination.go | 10 ++++ pkg/pagination/pagination_test.go | 80 +++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 pkg/pagination/pagination_test.go diff --git a/pkg/pagination/pagination.go b/pkg/pagination/pagination.go index badf70a..e3a9e09 100644 --- a/pkg/pagination/pagination.go +++ b/pkg/pagination/pagination.go @@ -1,10 +1,20 @@ package pagination func GetOffsetAndLimit(page, pageSize *int) (offset, limit int) { + + if page != nil && *page <= 0 { + page = nil + } + + if pageSize != nil && *pageSize < 0 { + pageSize = nil + } + if page == nil || pageSize == nil { limit = -1 offset = 0 } else { + offset = (*page - 1) * *pageSize limit = *pageSize } diff --git a/pkg/pagination/pagination_test.go b/pkg/pagination/pagination_test.go new file mode 100644 index 0000000..b1f7ff1 --- /dev/null +++ b/pkg/pagination/pagination_test.go @@ -0,0 +1,80 @@ +package pagination + +import "testing" + +func TestGetOffsetAndLimit(t *testing.T) { + type args struct { + page *int + pageSize *int + } + tests := []struct { + name string + args args + wantOffset int + wantLimit int + }{ + { + name: "Both nil", + args: args{nil, nil}, + wantOffset: 0, + wantLimit: -1, + }, + { + name: "Nil page", + args: args{nil, ptr(10)}, + wantOffset: 0, + wantLimit: -1, + }, + { + name: "Nil pageSize", + args: args{ptr(2), nil}, + wantOffset: 0, + wantLimit: -1, + }, + { + name: "First page", + args: args{ptr(1), ptr(10)}, + wantOffset: 0, + wantLimit: 10, + }, + { + name: "Second page", + args: args{ptr(2), ptr(10)}, + wantOffset: 10, + wantLimit: 10, + }, + { + name: "Third page", + args: args{ptr(3), ptr(5)}, + wantOffset: 10, + wantLimit: 5, + }, + { + name: "Zero page", + args: args{ptr(0), ptr(10)}, + wantOffset: 0, + wantLimit: -1, + }, + { + name: "Negative page", + args: args{ptr(-1), ptr(10)}, + wantOffset: 0, + wantLimit: -1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotOffset, gotLimit := GetOffsetAndLimit(tt.args.page, tt.args.pageSize) + if gotOffset != tt.wantOffset { + t.Errorf("GetOffsetAndLimit() gotOffset = %v, want %v", gotOffset, tt.wantOffset) + } + if gotLimit != tt.wantLimit { + t.Errorf("GetOffsetAndLimit() gotLimit = %v, want %v", gotLimit, tt.wantLimit) + } + }) + } +} + +func ptr(i int) *int { + return &i +}