github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/client/swarm_get_unlock_key_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"
    14  	"gotest.tools/assert"
    15  	is "gotest.tools/assert/cmp"
    16  )
    17  
    18  func TestSwarmGetUnlockKeyError(t *testing.T) {
    19  	client := &Client{
    20  		client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
    21  	}
    22  
    23  	_, err := client.SwarmGetUnlockKey(context.Background())
    24  	assert.Check(t, is.ErrorContains(err, "Error response from daemon: Server error"))
    25  }
    26  
    27  func TestSwarmGetUnlockKey(t *testing.T) {
    28  	expectedURL := "/swarm/unlockkey"
    29  	unlockKey := "SWMKEY-1-y6guTZNTwpQeTL5RhUfOsdBdXoQjiB2GADHSRJvbXeE"
    30  
    31  	client := &Client{
    32  		client: newMockClient(func(req *http.Request) (*http.Response, error) {
    33  			if !strings.HasPrefix(req.URL.Path, expectedURL) {
    34  				return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
    35  			}
    36  			if req.Method != "GET" {
    37  				return nil, fmt.Errorf("expected GET method, got %s", req.Method)
    38  			}
    39  
    40  			key := types.SwarmUnlockKeyResponse{
    41  				UnlockKey: unlockKey,
    42  			}
    43  
    44  			b, err := json.Marshal(key)
    45  			if err != nil {
    46  				return nil, err
    47  			}
    48  
    49  			return &http.Response{
    50  				StatusCode: http.StatusOK,
    51  				Body:       ioutil.NopCloser(bytes.NewReader(b)),
    52  			}, nil
    53  		}),
    54  	}
    55  
    56  	resp, err := client.SwarmGetUnlockKey(context.Background())
    57  	assert.NilError(t, err)
    58  	assert.Check(t, is.Equal(unlockKey, resp.UnlockKey))
    59  }