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