-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaginator_test.go
More file actions
114 lines (104 loc) · 2.41 KB
/
paginator_test.go
File metadata and controls
114 lines (104 loc) · 2.41 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//
// paginator_test.go
// Copyright (C) 2017 weirdgiraffe <giraffe@cyberzoo.xyz>
//
// Distributed under terms of the MIT license.
//
package github
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"testing"
"github.com/weirdgiraffe/github/mock"
)
const paginatorMaxPages = 10
var paginatorClient = NewClient(&github_mock.HttpClient{
ActualDo: func(req *http.Request) (res *http.Response, err error) {
res = &http.Response{
Header: make(http.Header),
Body: ioutil.NopCloser(bytes.NewBufferString("Hello World")),
}
u := *req.URL
q := u.Query()
p := 1
if pstr := q.Get("page"); pstr != "" {
p, err = strconv.Atoi(pstr)
if err != nil {
return
}
}
if p < paginatorMaxPages {
p = p + 1
}
q.Set("page", strconv.Itoa(p))
u.RawQuery = q.Encode()
lnext := fmt.Sprintf("<%s>; rel=\"next\"", u.String())
q.Set("page", strconv.Itoa(paginatorMaxPages))
u.RawQuery = q.Encode()
llast := fmt.Sprintf("<%s>; rel=\"last\"", u.String())
res.Header.Set("Link", fmt.Sprintf("%s, %s", lnext, llast))
return res, nil
},
})
func TestPaginatorIteration(t *testing.T) {
req, err := paginatorClient.NewRequest("GET", "https://api.github.com")
if err != nil {
t.Fatalf("NewRequest: %v", err)
}
p := NewPaginator(paginatorClient, req)
for i := 0; i < paginatorMaxPages; i++ {
res, err := p.Next()
if err != nil {
t.Fatalf("Next(): %v", err)
}
if p.next == "" {
t.Error("Link next not set")
}
unext, err := url.Parse(p.next)
if err != nil {
t.Fatalf("next page: %v", err)
}
if pstr := unext.Query().Get("page"); pstr != "" {
pn, err := strconv.Atoi(pstr)
if err != nil {
t.Errorf("next page: %v", err)
} else {
ePage := i + 2
if i == paginatorMaxPages-1 {
// last page
ePage = paginatorMaxPages
}
if pn != ePage {
t.Errorf("unexpected next page: %d != %d", ePage, pn)
}
}
}
if p.last == "" {
t.Error("Link last not set")
}
ulast, err := url.Parse(p.last)
if err != nil {
t.Fatalf("last page: %v", err)
}
if pstr := ulast.Query().Get("page"); pstr != "" {
pn, err := strconv.Atoi(pstr)
if err != nil {
t.Errorf("last page: %v", err)
} else {
if pn != paginatorMaxPages {
t.Errorf("unexpected last page: %d != %d", paginatorMaxPages, pn)
}
}
}
res.Body.Close()
}
_, err = p.Next()
if err != io.EOF {
t.Errorf("No io.EOF after last page reached")
}
}