github.com/docker/docker@v299999999.0.0-20200612211812-aaf470eca7b5+incompatible/client/container_top_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  	"reflect"
    11  	"strings"
    12  	"testing"
    13  
    14  	"github.com/docker/docker/api/types/container"
    15  	"github.com/docker/docker/errdefs"
    16  )
    17  
    18  func TestContainerTopError(t *testing.T) {
    19  	client := &Client{
    20  		client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
    21  	}
    22  	_, err := client.ContainerTop(context.Background(), "nothing", []string{})
    23  	if !errdefs.IsSystem(err) {
    24  		t.Fatalf("expected a Server Error, got %[1]T: %[1]v", err)
    25  	}
    26  }
    27  
    28  func TestContainerTop(t *testing.T) {
    29  	expectedURL := "/containers/container_id/top"
    30  	expectedProcesses := [][]string{
    31  		{"p1", "p2"},
    32  		{"p3"},
    33  	}
    34  	expectedTitles := []string{"title1", "title2"}
    35  
    36  	client := &Client{
    37  		client: newMockClient(func(req *http.Request) (*http.Response, error) {
    38  			if !strings.HasPrefix(req.URL.Path, expectedURL) {
    39  				return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
    40  			}
    41  			query := req.URL.Query()
    42  			args := query.Get("ps_args")
    43  			if args != "arg1 arg2" {
    44  				return nil, fmt.Errorf("args not set in URL query properly. Expected 'arg1 arg2', got %v", args)
    45  			}
    46  
    47  			b, err := json.Marshal(container.ContainerTopOKBody{
    48  				Processes: [][]string{
    49  					{"p1", "p2"},
    50  					{"p3"},
    51  				},
    52  				Titles: []string{"title1", "title2"},
    53  			})
    54  			if err != nil {
    55  				return nil, err
    56  			}
    57  
    58  			return &http.Response{
    59  				StatusCode: http.StatusOK,
    60  				Body:       ioutil.NopCloser(bytes.NewReader(b)),
    61  			}, nil
    62  		}),
    63  	}
    64  
    65  	processList, err := client.ContainerTop(context.Background(), "container_id", []string{"arg1", "arg2"})
    66  	if err != nil {
    67  		t.Fatal(err)
    68  	}
    69  	if !reflect.DeepEqual(expectedProcesses, processList.Processes) {
    70  		t.Fatalf("Processes: expected %v, got %v", expectedProcesses, processList.Processes)
    71  	}
    72  	if !reflect.DeepEqual(expectedTitles, processList.Titles) {
    73  		t.Fatalf("Titles: expected %v, got %v", expectedTitles, processList.Titles)
    74  	}
    75  }