github.com/rish1988/moby@v25.0.2+incompatible/client/container_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" 9 "net/http" 10 "strings" 11 "testing" 12 13 "github.com/docker/docker/api/types" 14 "github.com/docker/docker/api/types/container" 15 "github.com/docker/docker/api/types/filters" 16 "github.com/docker/docker/errdefs" 17 "gotest.tools/v3/assert" 18 is "gotest.tools/v3/assert/cmp" 19 ) 20 21 func TestContainerListError(t *testing.T) { 22 client := &Client{ 23 client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), 24 } 25 _, err := client.ContainerList(context.Background(), container.ListOptions{}) 26 assert.Check(t, is.ErrorType(err, errdefs.IsSystem)) 27 } 28 29 func TestContainerList(t *testing.T) { 30 expectedURL := "/containers/json" 31 expectedFilters := `{"before":{"container":true},"label":{"label1":true,"label2":true}}` 32 client := &Client{ 33 client: newMockClient(func(req *http.Request) (*http.Response, error) { 34 if !strings.HasPrefix(req.URL.Path, expectedURL) { 35 return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) 36 } 37 query := req.URL.Query() 38 all := query.Get("all") 39 if all != "1" { 40 return nil, fmt.Errorf("all not set in URL query properly. Expected '1', got %s", all) 41 } 42 limit := query.Get("limit") 43 if limit != "" { 44 return nil, fmt.Errorf("limit should have not be present in query, got %s", limit) 45 } 46 since := query.Get("since") 47 if since != "container" { 48 return nil, fmt.Errorf("since not set in URL query properly. Expected 'container', got %s", since) 49 } 50 before := query.Get("before") 51 if before != "" { 52 return nil, fmt.Errorf("before should have not be present in query, got %s", before) 53 } 54 size := query.Get("size") 55 if size != "1" { 56 return nil, fmt.Errorf("size not set in URL query properly. Expected '1', got %s", size) 57 } 58 fltrs := query.Get("filters") 59 if fltrs != expectedFilters { 60 return nil, fmt.Errorf("expected filters incoherent '%v' with actual filters %v", expectedFilters, fltrs) 61 } 62 63 b, err := json.Marshal([]types.Container{ 64 { 65 ID: "container_id1", 66 }, 67 { 68 ID: "container_id2", 69 }, 70 }) 71 if err != nil { 72 return nil, err 73 } 74 75 return &http.Response{ 76 StatusCode: http.StatusOK, 77 Body: io.NopCloser(bytes.NewReader(b)), 78 }, nil 79 }), 80 } 81 82 containers, err := client.ContainerList(context.Background(), container.ListOptions{ 83 Size: true, 84 All: true, 85 Since: "container", 86 Filters: filters.NewArgs( 87 filters.Arg("label", "label1"), 88 filters.Arg("label", "label2"), 89 filters.Arg("before", "container"), 90 ), 91 }) 92 if err != nil { 93 t.Fatal(err) 94 } 95 if len(containers) != 2 { 96 t.Fatalf("expected 2 containers, got %v", containers) 97 } 98 }