blob: 8d95e948bfb9aedf24055f45c4a9bf69b18e9a81 [file] [log] [blame]
jrperritt3d966162016-06-06 14:08:54 -05001package testing
Ash Wilsonc8e68872014-09-16 10:36:56 -04002
3import (
4 "fmt"
5 "net/http"
6 "testing"
7
jrperritt3d966162016-06-06 14:08:54 -05008 "github.com/gophercloud/gophercloud/pagination"
Jon Perritt27249f42016-02-18 10:35:59 -06009 "github.com/gophercloud/gophercloud/testhelper"
Ash Wilsonc8e68872014-09-16 10:36:56 -040010)
11
12// SinglePage sample and test cases.
13
14type SinglePageResult struct {
jrperritt3d966162016-06-06 14:08:54 -050015 pagination.SinglePageBase
Ash Wilsonc8e68872014-09-16 10:36:56 -040016}
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
jrperritt3d966162016-06-06 14:08:54 -050026func ExtractSingleInts(r pagination.Page) ([]int, error) {
Jon Perrittc7d828e2016-02-25 03:06:33 -060027 var s struct {
28 Ints []int `json:"ints"`
Ash Wilsonc8e68872014-09-16 10:36:56 -040029 }
Jon Perrittc7d828e2016-02-25 03:06:33 -060030 err := (r.(SinglePageResult)).ExtractInto(&s)
31 return s.Ints, err
Ash Wilsonc8e68872014-09-16 10:36:56 -040032}
33
jrperritt3d966162016-06-06 14:08:54 -050034func setupSinglePaged() pagination.Pager {
Ash Wilsonc8e68872014-09-16 10:36:56 -040035 testhelper.SetupHTTP()
36 client := createClient()
37
38 testhelper.Mux.HandleFunc("/only", func(w http.ResponseWriter, r *http.Request) {
39 w.Header().Add("Content-Type", "application/json")
40 fmt.Fprintf(w, `{ "ints": [1, 2, 3] }`)
41 })
42
jrperritt3d966162016-06-06 14:08:54 -050043 createPage := func(r pagination.PageResult) pagination.Page {
44 return SinglePageResult{pagination.SinglePageBase(r)}
Ash Wilsonc8e68872014-09-16 10:36:56 -040045 }
46
jrperritt3d966162016-06-06 14:08:54 -050047 return pagination.NewPager(client, testhelper.Server.URL+"/only", createPage)
Ash Wilsonc8e68872014-09-16 10:36:56 -040048}
49
50func TestEnumerateSinglePaged(t *testing.T) {
51 callCount := 0
52 pager := setupSinglePaged()
53 defer testhelper.TeardownHTTP()
54
jrperritt3d966162016-06-06 14:08:54 -050055 err := pager.EachPage(func(page pagination.Page) (bool, error) {
Ash Wilsonc8e68872014-09-16 10:36:56 -040056 callCount++
57
58 expected := []int{1, 2, 3}
59 actual, err := ExtractSingleInts(page)
60 testhelper.AssertNoErr(t, err)
61 testhelper.CheckDeepEquals(t, expected, actual)
62 return true, nil
63 })
64 testhelper.CheckNoErr(t, err)
65 testhelper.CheckEquals(t, 1, callCount)
66}
Jon Perrittdb319f12015-02-17 19:32:40 -070067
68func TestAllPagesSingle(t *testing.T) {
69 pager := setupSinglePaged()
70 defer testhelper.TeardownHTTP()
71
Jon Perrittdb319f12015-02-17 19:32:40 -070072 page, err := pager.AllPages()
73 testhelper.AssertNoErr(t, err)
74
75 expected := []int{1, 2, 3}
76 actual, err := ExtractSingleInts(page)
77 testhelper.AssertNoErr(t, err)
78 testhelper.CheckDeepEquals(t, expected, actual)
79}