github.com/vnpaycloud-console/gophercloud/v2@v2.0.5/pagination/testing/single_test.go (about) 1 package testing 2 3 import ( 4 "context" 5 "fmt" 6 "net/http" 7 "testing" 8 9 "github.com/vnpaycloud-console/gophercloud/v2/pagination" 10 th "github.com/vnpaycloud-console/gophercloud/v2/testhelper" 11 ) 12 13 // SinglePage sample and test cases. 14 15 type SinglePageResult struct { 16 pagination.SinglePageBase 17 } 18 19 func (r SinglePageResult) IsEmpty() (bool, error) { 20 is, err := ExtractSingleInts(r) 21 if err != nil { 22 return true, err 23 } 24 return len(is) == 0, nil 25 } 26 27 func ExtractSingleInts(r pagination.Page) ([]int, error) { 28 var s struct { 29 Ints []int `json:"ints"` 30 } 31 err := (r.(SinglePageResult)).ExtractInto(&s) 32 return s.Ints, err 33 } 34 35 func setupSinglePaged() pagination.Pager { 36 th.SetupHTTP() 37 client := createClient() 38 39 th.Mux.HandleFunc("/only", func(w http.ResponseWriter, r *http.Request) { 40 w.Header().Add("Content-Type", "application/json") 41 fmt.Fprint(w, `{ "ints": [1, 2, 3] }`) 42 }) 43 44 createPage := func(r pagination.PageResult) pagination.Page { 45 return SinglePageResult{pagination.SinglePageBase(r)} 46 } 47 48 return pagination.NewPager(client, th.Server.URL+"/only", createPage) 49 } 50 51 func TestEnumerateSinglePaged(t *testing.T) { 52 callCount := 0 53 pager := setupSinglePaged() 54 defer th.TeardownHTTP() 55 56 err := pager.EachPage(context.TODO(), func(_ context.Context, page pagination.Page) (bool, error) { 57 callCount++ 58 59 expected := []int{1, 2, 3} 60 actual, err := ExtractSingleInts(page) 61 th.AssertNoErr(t, err) 62 th.CheckDeepEquals(t, expected, actual) 63 return true, nil 64 }) 65 th.CheckNoErr(t, err) 66 th.CheckEquals(t, 1, callCount) 67 } 68 69 func TestAllPagesSingle(t *testing.T) { 70 pager := setupSinglePaged() 71 defer th.TeardownHTTP() 72 73 page, err := pager.AllPages(context.TODO()) 74 th.AssertNoErr(t, err) 75 76 expected := []int{1, 2, 3} 77 actual, err := ExtractSingleInts(page) 78 th.AssertNoErr(t, err) 79 th.CheckDeepEquals(t, expected, actual) 80 }