blob: 8817d570f2813b01e8275f342a611092f89b3463 [file] [log] [blame]
Ash Wilsonc8e68872014-09-16 10:36:56 -04001package pagination
2
3import (
4 "fmt"
5 "net/http"
6 "testing"
7
8 "github.com/mitchellh/mapstructure"
9 "github.com/rackspace/gophercloud/testhelper"
10)
11
12// SinglePage sample and test cases.
13
14type SinglePageResult struct {
15 SinglePageBase
16}
17
18func (r SinglePageResult) IsEmpty() (bool, error) {
19 is, err := ExtractSingleInts(r)
20 if err != nil {
21 return true, err
22 }
23 return len(is) == 0, nil
24}
25
26func ExtractSingleInts(page Page) ([]int, error) {
27 var response struct {
28 Ints []int `mapstructure:"ints"`
29 }
30
31 err := mapstructure.Decode(page.(SinglePageResult).Body, &response)
32 if err != nil {
33 return nil, err
34 }
35
36 return response.Ints, nil
37}
38
39func setupSinglePaged() Pager {
40 testhelper.SetupHTTP()
41 client := createClient()
42
43 testhelper.Mux.HandleFunc("/only", func(w http.ResponseWriter, r *http.Request) {
44 w.Header().Add("Content-Type", "application/json")
45 fmt.Fprintf(w, `{ "ints": [1, 2, 3] }`)
46 })
47
Ash Wilsonb8b16f82014-10-20 10:19:49 -040048 createPage := func(r PageResult) Page {
Ash Wilsonc8e68872014-09-16 10:36:56 -040049 return SinglePageResult{SinglePageBase(r)}
50 }
51
Ash Wilson7049af42014-09-16 13:04:48 -040052 return NewPager(client, testhelper.Server.URL+"/only", createPage)
Ash Wilsonc8e68872014-09-16 10:36:56 -040053}
54
55func TestEnumerateSinglePaged(t *testing.T) {
56 callCount := 0
57 pager := setupSinglePaged()
58 defer testhelper.TeardownHTTP()
59
60 err := pager.EachPage(func(page Page) (bool, error) {
61 callCount++
62
63 expected := []int{1, 2, 3}
64 actual, err := ExtractSingleInts(page)
65 testhelper.AssertNoErr(t, err)
66 testhelper.CheckDeepEquals(t, expected, actual)
67 return true, nil
68 })
69 testhelper.CheckNoErr(t, err)
70 testhelper.CheckEquals(t, 1, callCount)
71}