github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/client/container_stats_test.go (about)

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