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