github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/client/volume_list_test.go (about) 1 package client 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io/ioutil" 8 "net/http" 9 "strings" 10 "testing" 11 12 "github.com/docker/docker/api/types" 13 "github.com/docker/docker/api/types/filters" 14 volumetypes "github.com/docker/docker/api/types/volume" 15 "golang.org/x/net/context" 16 ) 17 18 func TestVolumeListError(t *testing.T) { 19 client := &Client{ 20 client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), 21 } 22 23 _, err := client.VolumeList(context.Background(), filters.NewArgs()) 24 if err == nil || err.Error() != "Error response from daemon: Server error" { 25 t.Fatalf("expected a Server Error, got %v", err) 26 } 27 } 28 29 func TestVolumeList(t *testing.T) { 30 expectedURL := "/volumes" 31 32 noDanglingFilters := filters.NewArgs() 33 noDanglingFilters.Add("dangling", "false") 34 35 danglingFilters := filters.NewArgs() 36 danglingFilters.Add("dangling", "true") 37 38 labelFilters := filters.NewArgs() 39 labelFilters.Add("label", "label1") 40 labelFilters.Add("label", "label2") 41 42 listCases := []struct { 43 filters filters.Args 44 expectedFilters string 45 }{ 46 { 47 filters: filters.NewArgs(), 48 expectedFilters: "", 49 }, { 50 filters: noDanglingFilters, 51 expectedFilters: `{"dangling":{"false":true}}`, 52 }, { 53 filters: danglingFilters, 54 expectedFilters: `{"dangling":{"true":true}}`, 55 }, { 56 filters: labelFilters, 57 expectedFilters: `{"label":{"label1":true,"label2":true}}`, 58 }, 59 } 60 61 for _, listCase := range listCases { 62 client := &Client{ 63 client: newMockClient(func(req *http.Request) (*http.Response, error) { 64 if !strings.HasPrefix(req.URL.Path, expectedURL) { 65 return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) 66 } 67 query := req.URL.Query() 68 actualFilters := query.Get("filters") 69 if actualFilters != listCase.expectedFilters { 70 return nil, fmt.Errorf("filters not set in URL query properly. Expected '%s', got %s", listCase.expectedFilters, actualFilters) 71 } 72 content, err := json.Marshal(volumetypes.VolumesListOKBody{ 73 Volumes: []*types.Volume{ 74 { 75 Name: "volume", 76 Driver: "local", 77 }, 78 }, 79 }) 80 if err != nil { 81 return nil, err 82 } 83 return &http.Response{ 84 StatusCode: http.StatusOK, 85 Body: ioutil.NopCloser(bytes.NewReader(content)), 86 }, nil 87 }), 88 } 89 90 volumeResponse, err := client.VolumeList(context.Background(), listCase.filters) 91 if err != nil { 92 t.Fatal(err) 93 } 94 if len(volumeResponse.Volumes) != 1 { 95 t.Fatalf("expected 1 volume, got %v", volumeResponse.Volumes) 96 } 97 } 98 }