github.com/toplink-cn/moby@v0.0.0-20240305205811-460b4aebdf81/client/service_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"
     9  	"net/http"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/docker/docker/api/types"
    14  	"github.com/docker/docker/api/types/swarm"
    15  	"github.com/docker/docker/errdefs"
    16  	"github.com/pkg/errors"
    17  	"gotest.tools/v3/assert"
    18  	is "gotest.tools/v3/assert/cmp"
    19  )
    20  
    21  func TestServiceInspectError(t *testing.T) {
    22  	client := &Client{
    23  		client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
    24  	}
    25  
    26  	_, _, err := client.ServiceInspectWithRaw(context.Background(), "nothing", types.ServiceInspectOptions{})
    27  	assert.Check(t, is.ErrorType(err, errdefs.IsSystem))
    28  }
    29  
    30  func TestServiceInspectServiceNotFound(t *testing.T) {
    31  	client := &Client{
    32  		client: newMockClient(errorMock(http.StatusNotFound, "Server error")),
    33  	}
    34  
    35  	_, _, err := client.ServiceInspectWithRaw(context.Background(), "unknown", types.ServiceInspectOptions{})
    36  	assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
    37  }
    38  
    39  func TestServiceInspectWithEmptyID(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.ServiceInspectWithRaw(context.Background(), "", types.ServiceInspectOptions{})
    46  	assert.Check(t, is.ErrorType(err, errdefs.IsNotFound))
    47  }
    48  
    49  func TestServiceInspect(t *testing.T) {
    50  	expectedURL := "/services/service_id"
    51  	client := &Client{
    52  		client: newMockClient(func(req *http.Request) (*http.Response, error) {
    53  			if !strings.HasPrefix(req.URL.Path, expectedURL) {
    54  				return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
    55  			}
    56  			content, err := json.Marshal(swarm.Service{
    57  				ID: "service_id",
    58  			})
    59  			if err != nil {
    60  				return nil, err
    61  			}
    62  			return &http.Response{
    63  				StatusCode: http.StatusOK,
    64  				Body:       io.NopCloser(bytes.NewReader(content)),
    65  			}, nil
    66  		}),
    67  	}
    68  
    69  	serviceInspect, _, err := client.ServiceInspectWithRaw(context.Background(), "service_id", types.ServiceInspectOptions{})
    70  	if err != nil {
    71  		t.Fatal(err)
    72  	}
    73  	if serviceInspect.ID != "service_id" {
    74  		t.Fatalf("expected `service_id`, got %s", serviceInspect.ID)
    75  	}
    76  }