github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/engine/client/container_stats_test.go (about) 1 package client // import "github.com/docker/docker/client" 2 3 import ( 4 "bytes" 5 "context" 6 "fmt" 7 "io" 8 "net/http" 9 "strings" 10 "testing" 11 12 "github.com/docker/docker/errdefs" 13 ) 14 15 func TestContainerStatsError(t *testing.T) { 16 client := &Client{ 17 client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), 18 } 19 _, err := client.ContainerStats(context.Background(), "nothing", false) 20 if !errdefs.IsSystem(err) { 21 t.Fatalf("expected a Server Error, got %[1]T: %[1]v", err) 22 } 23 } 24 25 func TestContainerStats(t *testing.T) { 26 expectedURL := "/containers/container_id/stats" 27 cases := []struct { 28 stream bool 29 expectedStream string 30 }{ 31 { 32 expectedStream: "0", 33 }, 34 { 35 stream: true, 36 expectedStream: "1", 37 }, 38 } 39 for _, c := range cases { 40 client := &Client{ 41 client: newMockClient(func(r *http.Request) (*http.Response, error) { 42 if !strings.HasPrefix(r.URL.Path, expectedURL) { 43 return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, r.URL) 44 } 45 46 query := r.URL.Query() 47 stream := query.Get("stream") 48 if stream != c.expectedStream { 49 return nil, fmt.Errorf("stream not set in URL query properly. Expected '%s', got %s", c.expectedStream, stream) 50 } 51 52 return &http.Response{ 53 StatusCode: http.StatusOK, 54 Body: io.NopCloser(bytes.NewReader([]byte("response"))), 55 }, nil 56 }), 57 } 58 resp, err := client.ContainerStats(context.Background(), "container_id", c.stream) 59 if err != nil { 60 t.Fatal(err) 61 } 62 defer resp.Body.Close() 63 content, err := io.ReadAll(resp.Body) 64 if err != nil { 65 t.Fatal(err) 66 } 67 if string(content) != "response" { 68 t.Fatalf("expected response to contain 'response', got %s", string(content)) 69 } 70 } 71 }