github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/pagination/testing/single_test.go (about) 1 package testing 2 3 import ( 4 "fmt" 5 "net/http" 6 "testing" 7 8 "github.com/huaweicloud/golangsdk/pagination" 9 "github.com/huaweicloud/golangsdk/testhelper" 10 ) 11 12 // SinglePage sample and test cases. 13 14 type SinglePageResult struct { 15 pagination.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(r pagination.Page) ([]int, error) { 27 var s struct { 28 Ints []int `json:"ints"` 29 } 30 err := (r.(SinglePageResult)).ExtractInto(&s) 31 return s.Ints, err 32 } 33 34 func setupSinglePaged() pagination.Pager { 35 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 43 createPage := func(r pagination.PageResult) pagination.Page { 44 return SinglePageResult{pagination.SinglePageBase(r)} 45 } 46 47 return pagination.NewPager(client, testhelper.Server.URL+"/only", createPage) 48 } 49 50 func TestEnumerateSinglePaged(t *testing.T) { 51 callCount := 0 52 pager := setupSinglePaged() 53 defer testhelper.TeardownHTTP() 54 55 err := pager.EachPage(func(page pagination.Page) (bool, error) { 56 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 } 67 68 func TestAllPagesSingle(t *testing.T) { 69 pager := setupSinglePaged() 70 defer testhelper.TeardownHTTP() 71 72 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 }