Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 1 | package pagination |
| 2 | |
| 3 | import ( |
| 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 | |
| 14 | type SinglePageResult struct { |
| 15 | SinglePageBase |
| 16 | } |
| 17 | |
| 18 | func (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 | |
| 26 | func 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 | |
| 39 | func 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 Wilson | b8b16f8 | 2014-10-20 10:19:49 -0400 | [diff] [blame] | 48 | createPage := func(r PageResult) Page { |
Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 49 | return SinglePageResult{SinglePageBase(r)} |
| 50 | } |
| 51 | |
Ash Wilson | 7049af4 | 2014-09-16 13:04:48 -0400 | [diff] [blame] | 52 | return NewPager(client, testhelper.Server.URL+"/only", createPage) |
Ash Wilson | c8e6887 | 2014-09-16 10:36:56 -0400 | [diff] [blame] | 53 | } |
| 54 | |
| 55 | func 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 | } |