-
Notifications
You must be signed in to change notification settings - Fork 7
/
paginator_test.go
83 lines (72 loc) · 2.2 KB
/
paginator_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package paginator
import (
"fmt"
"net/url"
"testing"
"github.com/stretchr/testify/assert"
)
func TestPaginator(t *testing.T) {
var (
opt = Opt{
DefaultPerPage: 10,
MaxPerPage: 50,
NumPageNums: 10,
PageParam: "page",
PerPageParam: "per_page",
AllowAll: false,
AllowAllParam: "all",
}
p = New(opt)
)
type testCase struct {
Page int
PerPage int
Total int
}
type test struct {
testCase
result Set
}
cases := []test{
{testCase{Page: 0, PerPage: 5, Total: 0}, Set{PerPage: 5, Page: 1, Offset: 0, Limit: 5}},
{testCase{Page: -1, PerPage: 5, Total: 0}, Set{PerPage: 5, Page: 1, Offset: 0, Limit: 5}},
{testCase{Page: 1, PerPage: 5, Total: 0}, Set{PerPage: 5, Page: 1, Offset: 0, Limit: 5}},
{testCase{Page: 10, PerPage: 5, Total: 100}, Set{PerPage: 5, Page: 10, Offset: 45, Limit: 5}},
{testCase{Page: 10, PerPage: 10, Total: 100}, Set{PerPage: 10, Page: 10, Offset: 90, Limit: 10}},
{testCase{Page: -1, PerPage: 10, Total: 100}, Set{PerPage: 10, Page: 1, Offset: 0, Limit: 10}},
{testCase{Page: 100, PerPage: 10, Total: 10}, Set{PerPage: 10, Page: 1, Offset: 0, Limit: 10}},
}
q := url.Values{}
for _, c := range cases {
s := p.New(c.testCase.Page, c.testCase.PerPage)
s.SetTotal(c.testCase.Total)
assert.Equal(t, s.Page, c.result.Page)
assert.Equal(t, s.PerPage, c.result.PerPage)
assert.Equal(t, s.Offset, c.result.Offset)
assert.Equal(t, s.Limit, c.result.Limit)
q.Set("page", fmt.Sprintf("%v", s.Page))
q.Set("per_page", fmt.Sprintf("%v", s.PerPage))
s = p.NewFromURL(q)
assert.Equal(t, s.Page, c.result.Page)
assert.Equal(t, s.PerPage, c.result.PerPage)
assert.Equal(t, s.Offset, c.result.Offset)
assert.Equal(t, s.Limit, c.result.Limit)
}
// Exceed per page with AlloWall = false
q.Set("page", "1")
q.Set("per_page", "500")
s := p.NewFromURL(q)
assert.Equal(t, s.Page, 1)
assert.Equal(t, s.PerPage, 50)
// Exceed per page with AllowAll = true
opt.AllowAll = true
p = New(opt)
s = p.NewFromURL(q)
assert.Equal(t, s.Page, 1)
// This is now allowed because AllowAll = true;
assert.Equal(t, s.PerPage, 500)
q.Set("per_page", "all")
s = p.NewFromURL(q)
assert.Equal(t, s.Page, 1)
assert.Equal(t, s.PerPage, 0)
}