Skip to content

Commit

Permalink
test pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
ykkssyaa committed May 23, 2024
1 parent 849a32e commit 482232b
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pkg/pagination/pagination.go
Original file line number Diff line number Diff line change
@@ -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
}
Expand Down
80 changes: 80 additions & 0 deletions pkg/pagination/pagination_test.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 482232b

Please sign in to comment.