github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/client/node_inspect_test.go (about)

     1  package client // import "github.com/docker/docker/client"
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"encoding/json"
     7  	"fmt"
     8  	"io/ioutil"
     9  	"net/http"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/docker/docker/api/types/swarm"
    14  	"github.com/pkg/errors"
    15  )
    16  
    17  func TestNodeInspectError(t *testing.T) {
    18  	client := &Client{
    19  		client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
    20  	}
    21  
    22  	_, _, err := client.NodeInspectWithRaw(context.Background(), "nothing")
    23  	if err == nil || err.Error() != "Error response from daemon: Server error" {
    24  		t.Fatalf("expected a Server Error, got %v", err)
    25  	}
    26  }
    27  
    28  func TestNodeInspectNodeNotFound(t *testing.T) {
    29  	client := &Client{
    30  		client: newMockClient(errorMock(http.StatusNotFound, "Server error")),
    31  	}
    32  
    33  	_, _, err := client.NodeInspectWithRaw(context.Background(), "unknown")
    34  	if err == nil || !IsErrNotFound(err) {
    35  		t.Fatalf("expected a nodeNotFoundError error, got %v", err)
    36  	}
    37  }
    38  
    39  func TestNodeInspectWithEmptyID(t *testing.T) {
    40  	client := &Client{
    41  		client: newMockClient(func(req *http.Request) (*http.Response, error) {
    42  			return nil, errors.New("should not make request")
    43  		}),
    44  	}
    45  	_, _, err := client.NodeInspectWithRaw(context.Background(), "")
    46  	if !IsErrNotFound(err) {
    47  		t.Fatalf("Expected NotFoundError, got %v", err)
    48  	}
    49  }
    50  
    51  func TestNodeInspect(t *testing.T) {
    52  	expectedURL := "/nodes/node_id"
    53  	client := &Client{
    54  		client: newMockClient(func(req *http.Request) (*http.Response, error) {
    55  			if !strings.HasPrefix(req.URL.Path, expectedURL) {
    56  				return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
    57  			}
    58  			content, err := json.Marshal(swarm.Node{
    59  				ID: "node_id",
    60  			})
    61  			if err != nil {
    62  				return nil, err
    63  			}
    64  			return &http.Response{
    65  				StatusCode: http.StatusOK,
    66  				Body:       ioutil.NopCloser(bytes.NewReader(content)),
    67  			}, nil
    68  		}),
    69  	}
    70  
    71  	nodeInspect, _, err := client.NodeInspectWithRaw(context.Background(), "node_id")
    72  	if err != nil {
    73  		t.Fatal(err)
    74  	}
    75  	if nodeInspect.ID != "node_id" {
    76  		t.Fatalf("expected `node_id`, got %s", nodeInspect.ID)
    77  	}
    78  }