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