blob: 2a9466c469ba36827f364f8bc95ebfdd2472439c [file] [log] [blame]
Ash Wilsonc8e68872014-09-16 10:36:56 -04001package pagination
2
3import (
4 "fmt"
5 "net/http"
6 "testing"
7
Jon Perritt27249f42016-02-18 10:35:59 -06008 "github.com/gophercloud/gophercloud/testhelper"
Ash Wilsonc8e68872014-09-16 10:36:56 -04009)
10
11// SinglePage sample and test cases.
12
13type SinglePageResult struct {
14 SinglePageBase
15}
16
17func (r SinglePageResult) IsEmpty() (bool, error) {
18 is, err := ExtractSingleInts(r)
19 if err != nil {
20 return true, err
21 }
22 return len(is) == 0, nil
23}
24
Jon Perrittc7d828e2016-02-25 03:06:33 -060025func ExtractSingleInts(r Page) ([]int, error) {
26 var s struct {
27 Ints []int `json:"ints"`
Ash Wilsonc8e68872014-09-16 10:36:56 -040028 }
Jon Perrittc7d828e2016-02-25 03:06:33 -060029 err := (r.(SinglePageResult)).ExtractInto(&s)
30 return s.Ints, err
Ash Wilsonc8e68872014-09-16 10:36:56 -040031}
32
33func setupSinglePaged() Pager {
34 testhelper.SetupHTTP()
35 client := createClient()
36
37 testhelper.Mux.HandleFunc("/only", func(w http.ResponseWriter, r *http.Request) {
38 w.Header().Add("Content-Type", "application/json")
39 fmt.Fprintf(w, `{ "ints": [1, 2, 3] }`)
40 })
41
Ash Wilsonb8b16f82014-10-20 10:19:49 -040042 createPage := func(r PageResult) Page {
Ash Wilsonc8e68872014-09-16 10:36:56 -040043 return SinglePageResult{SinglePageBase(r)}
44 }
45
Ash Wilson7049af42014-09-16 13:04:48 -040046 return NewPager(client, testhelper.Server.URL+"/only", createPage)
Ash Wilsonc8e68872014-09-16 10:36:56 -040047}
48
49func TestEnumerateSinglePaged(t *testing.T) {
50 callCount := 0
51 pager := setupSinglePaged()
52 defer testhelper.TeardownHTTP()
53
54 err := pager.EachPage(func(page Page) (bool, error) {
55 callCount++
56
57 expected := []int{1, 2, 3}
58 actual, err := ExtractSingleInts(page)
59 testhelper.AssertNoErr(t, err)
60 testhelper.CheckDeepEquals(t, expected, actual)
61 return true, nil
62 })
63 testhelper.CheckNoErr(t, err)
64 testhelper.CheckEquals(t, 1, callCount)
65}
Jon Perrittdb319f12015-02-17 19:32:40 -070066
67func TestAllPagesSingle(t *testing.T) {
68 pager := setupSinglePaged()
69 defer testhelper.TeardownHTTP()
70
Jon Perrittdb319f12015-02-17 19:32:40 -070071 page, err := pager.AllPages()
72 testhelper.AssertNoErr(t, err)
73
74 expected := []int{1, 2, 3}
75 actual, err := ExtractSingleInts(page)
76 testhelper.AssertNoErr(t, err)
77 testhelper.CheckDeepEquals(t, expected, actual)
78}