single_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package testing
  2. import (
  3. "fmt"
  4. "net/http"
  5. "testing"
  6. "devel.mephi.ru/iacherepanov/openstack-gophercloud/pagination"
  7. "devel.mephi.ru/iacherepanov/openstack-gophercloud/testhelper"
  8. )
  9. // SinglePage sample and test cases.
  10. type SinglePageResult struct {
  11. pagination.SinglePageBase
  12. }
  13. func (r SinglePageResult) IsEmpty() (bool, error) {
  14. is, err := ExtractSingleInts(r)
  15. if err != nil {
  16. return true, err
  17. }
  18. return len(is) == 0, nil
  19. }
  20. func ExtractSingleInts(r pagination.Page) ([]int, error) {
  21. var s struct {
  22. Ints []int `json:"ints"`
  23. }
  24. err := (r.(SinglePageResult)).ExtractInto(&s)
  25. return s.Ints, err
  26. }
  27. func setupSinglePaged() pagination.Pager {
  28. testhelper.SetupHTTP()
  29. client := createClient()
  30. testhelper.Mux.HandleFunc("/only", func(w http.ResponseWriter, r *http.Request) {
  31. w.Header().Add("Content-Type", "application/json")
  32. fmt.Fprintf(w, `{ "ints": [1, 2, 3] }`)
  33. })
  34. createPage := func(r pagination.PageResult) pagination.Page {
  35. return SinglePageResult{pagination.SinglePageBase(r)}
  36. }
  37. return pagination.NewPager(client, testhelper.Server.URL+"/only", createPage)
  38. }
  39. func TestEnumerateSinglePaged(t *testing.T) {
  40. callCount := 0
  41. pager := setupSinglePaged()
  42. defer testhelper.TeardownHTTP()
  43. err := pager.EachPage(func(page pagination.Page) (bool, error) {
  44. callCount++
  45. expected := []int{1, 2, 3}
  46. actual, err := ExtractSingleInts(page)
  47. testhelper.AssertNoErr(t, err)
  48. testhelper.CheckDeepEquals(t, expected, actual)
  49. return true, nil
  50. })
  51. testhelper.CheckNoErr(t, err)
  52. testhelper.CheckEquals(t, 1, callCount)
  53. }
  54. func TestAllPagesSingle(t *testing.T) {
  55. pager := setupSinglePaged()
  56. defer testhelper.TeardownHTTP()
  57. page, err := pager.AllPages()
  58. testhelper.AssertNoErr(t, err)
  59. expected := []int{1, 2, 3}
  60. actual, err := ExtractSingleInts(page)
  61. testhelper.AssertNoErr(t, err)
  62. testhelper.CheckDeepEquals(t, expected, actual)
  63. }