service_list_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package client
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "strings"
  9. "testing"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/api/types/filters"
  12. "github.com/docker/docker/api/types/swarm"
  13. "golang.org/x/net/context"
  14. )
  15. func TestServiceListError(t *testing.T) {
  16. client := &Client{
  17. client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
  18. }
  19. _, err := client.ServiceList(context.Background(), types.ServiceListOptions{})
  20. if err == nil || err.Error() != "Error response from daemon: Server error" {
  21. t.Fatalf("expected a Server Error, got %v", err)
  22. }
  23. }
  24. func TestServiceList(t *testing.T) {
  25. expectedURL := "/services"
  26. filters := filters.NewArgs()
  27. filters.Add("label", "label1")
  28. filters.Add("label", "label2")
  29. listCases := []struct {
  30. options types.ServiceListOptions
  31. expectedQueryParams map[string]string
  32. }{
  33. {
  34. options: types.ServiceListOptions{},
  35. expectedQueryParams: map[string]string{
  36. "filters": "",
  37. },
  38. },
  39. {
  40. options: types.ServiceListOptions{
  41. Filters: filters,
  42. },
  43. expectedQueryParams: map[string]string{
  44. "filters": `{"label":{"label1":true,"label2":true}}`,
  45. },
  46. },
  47. }
  48. for _, listCase := range listCases {
  49. client := &Client{
  50. client: newMockClient(func(req *http.Request) (*http.Response, error) {
  51. if !strings.HasPrefix(req.URL.Path, expectedURL) {
  52. return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
  53. }
  54. query := req.URL.Query()
  55. for key, expected := range listCase.expectedQueryParams {
  56. actual := query.Get(key)
  57. if actual != expected {
  58. return nil, fmt.Errorf("%s not set in URL query properly. Expected '%s', got %s", key, expected, actual)
  59. }
  60. }
  61. content, err := json.Marshal([]swarm.Service{
  62. {
  63. ID: "service_id1",
  64. },
  65. {
  66. ID: "service_id2",
  67. },
  68. })
  69. if err != nil {
  70. return nil, err
  71. }
  72. return &http.Response{
  73. StatusCode: http.StatusOK,
  74. Body: ioutil.NopCloser(bytes.NewReader(content)),
  75. }, nil
  76. }),
  77. }
  78. services, err := client.ServiceList(context.Background(), listCase.options)
  79. if err != nil {
  80. t.Fatal(err)
  81. }
  82. if len(services) != 2 {
  83. t.Fatalf("expected 2 services, got %v", services)
  84. }
  85. }
  86. }