github.com/hms58/moby@v1.13.1/client/info_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  	"golang.org/x/net/context"
    14  )
    15  
    16  func TestInfoServerError(t *testing.T) {
    17  	client := &Client{
    18  		client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
    19  	}
    20  	_, err := client.Info(context.Background())
    21  	if err == nil || err.Error() != "Error response from daemon: Server error" {
    22  		t.Fatalf("expected a Server Error, got %v", err)
    23  	}
    24  }
    25  
    26  func TestInfoInvalidResponseJSONError(t *testing.T) {
    27  	client := &Client{
    28  		client: newMockClient(func(req *http.Request) (*http.Response, error) {
    29  			return &http.Response{
    30  				StatusCode: http.StatusOK,
    31  				Body:       ioutil.NopCloser(bytes.NewReader([]byte("invalid json"))),
    32  			}, nil
    33  		}),
    34  	}
    35  	_, err := client.Info(context.Background())
    36  	if err == nil || !strings.Contains(err.Error(), "invalid character") {
    37  		t.Fatalf("expected a 'invalid character' error, got %v", err)
    38  	}
    39  }
    40  
    41  func TestInfo(t *testing.T) {
    42  	expectedURL := "/info"
    43  	client := &Client{
    44  		client: newMockClient(func(req *http.Request) (*http.Response, error) {
    45  			if !strings.HasPrefix(req.URL.Path, expectedURL) {
    46  				return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
    47  			}
    48  			info := &types.Info{
    49  				ID:         "daemonID",
    50  				Containers: 3,
    51  			}
    52  			b, err := json.Marshal(info)
    53  			if err != nil {
    54  				return nil, err
    55  			}
    56  
    57  			return &http.Response{
    58  				StatusCode: http.StatusOK,
    59  				Body:       ioutil.NopCloser(bytes.NewReader(b)),
    60  			}, nil
    61  		}),
    62  	}
    63  
    64  	info, err := client.Info(context.Background())
    65  	if err != nil {
    66  		t.Fatal(err)
    67  	}
    68  
    69  	if info.ID != "daemonID" {
    70  		t.Fatalf("expected daemonID, got %s", info.ID)
    71  	}
    72  
    73  	if info.Containers != 3 {
    74  		t.Fatalf("expected 3 containers, got %d", info.Containers)
    75  	}
    76  }