github.com/google/cadvisor@v0.49.1/client/client_test.go (about)

     1  // Copyright 2014 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package client
    16  
    17  import (
    18  	"encoding/json"
    19  	"fmt"
    20  	"net/http"
    21  	"net/http/httptest"
    22  	"path"
    23  	"reflect"
    24  	"strings"
    25  	"testing"
    26  	"time"
    27  
    28  	info "github.com/google/cadvisor/info/v1"
    29  	itest "github.com/google/cadvisor/info/v1/test"
    30  
    31  	"github.com/stretchr/testify/assert"
    32  )
    33  
    34  func cadvisorTestClient(path string, expectedPostObj *info.ContainerInfoRequest, replyObj interface{}, t *testing.T) (*Client, *httptest.Server, error) {
    35  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    36  		if r.URL.Path == path {
    37  			if expectedPostObj != nil {
    38  				expectedPostObjEmpty := new(info.ContainerInfoRequest)
    39  				decoder := json.NewDecoder(r.Body)
    40  				if err := decoder.Decode(expectedPostObjEmpty); err != nil {
    41  					t.Errorf("Received invalid object: %v", err)
    42  				}
    43  				if expectedPostObj.NumStats != expectedPostObjEmpty.NumStats ||
    44  					expectedPostObj.Start.Unix() != expectedPostObjEmpty.Start.Unix() ||
    45  					expectedPostObj.End.Unix() != expectedPostObjEmpty.End.Unix() {
    46  					t.Errorf("Received unexpected object: %+v, expected: %+v", expectedPostObjEmpty, expectedPostObj)
    47  				}
    48  			}
    49  			encoder := json.NewEncoder(w)
    50  			err := encoder.Encode(replyObj)
    51  			assert.NoError(t, err)
    52  		} else {
    53  			w.WriteHeader(http.StatusNotFound)
    54  			fmt.Fprintf(w, "Page not found.")
    55  		}
    56  	}))
    57  	client, err := NewClient(ts.URL)
    58  	if err != nil {
    59  		ts.Close()
    60  		return nil, nil, err
    61  	}
    62  	return client, ts, err
    63  }
    64  
    65  // TestGetMachineInfo performs one test to check if MachineInfo()
    66  // in a cAdvisor client returns the correct result.
    67  func TestGetMachineinfo(t *testing.T) {
    68  	minfo := &info.MachineInfo{
    69  		NumCores:       8,
    70  		MemoryCapacity: 31625871360,
    71  		DiskMap: map[string]info.DiskInfo{
    72  			"8:0": {
    73  				Name:  "sda",
    74  				Major: 8,
    75  				Minor: 0,
    76  				Size:  10737418240,
    77  			},
    78  		},
    79  	}
    80  	client, server, err := cadvisorTestClient("/api/v1.3/machine", nil, minfo, t)
    81  	if err != nil {
    82  		t.Fatalf("unable to get a client %v", err)
    83  	}
    84  	defer server.Close()
    85  	returned, err := client.MachineInfo()
    86  	if err != nil {
    87  		t.Fatal(err)
    88  	}
    89  	if !reflect.DeepEqual(returned, minfo) {
    90  		t.Fatalf("received unexpected machine info")
    91  	}
    92  }
    93  
    94  // TestGetContainerInfo generates a random container information object
    95  // and then checks that ContainerInfo returns the expected result.
    96  func TestGetContainerInfo(t *testing.T) {
    97  	query := &info.ContainerInfoRequest{
    98  		NumStats: 3,
    99  	}
   100  	containerName := "/some/container"
   101  	cinfo := itest.GenerateRandomContainerInfo(containerName, 4, query, 1*time.Second)
   102  	client, server, err := cadvisorTestClient(fmt.Sprintf("/api/v1.3/containers%v", containerName), query, cinfo, t)
   103  	if err != nil {
   104  		t.Fatalf("unable to get a client %v", err)
   105  	}
   106  	defer server.Close()
   107  	returned, err := client.ContainerInfo(containerName, query)
   108  	if err != nil {
   109  		t.Fatal(err)
   110  	}
   111  
   112  	if !returned.Eq(cinfo) {
   113  		t.Error("received unexpected ContainerInfo")
   114  	}
   115  }
   116  
   117  // Test a request failing
   118  func TestRequestFails(t *testing.T) {
   119  	errorText := "there was an error"
   120  	// Setup a server that simply fails.
   121  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   122  		http.Error(w, errorText, 500)
   123  	}))
   124  	client, err := NewClient(ts.URL)
   125  	if err != nil {
   126  		ts.Close()
   127  		t.Fatal(err)
   128  	}
   129  	defer ts.Close()
   130  
   131  	_, err = client.ContainerInfo("/", &info.ContainerInfoRequest{NumStats: 3})
   132  	if err == nil {
   133  		t.Fatalf("Expected non-nil error")
   134  	}
   135  	expectedError := fmt.Sprintf("request failed with error: %q", errorText)
   136  	if strings.Contains(err.Error(), expectedError) {
   137  		t.Fatalf("Expected error %q but received %q", expectedError, err)
   138  	}
   139  }
   140  
   141  func TestGetSubcontainersInfo(t *testing.T) {
   142  	query := &info.ContainerInfoRequest{
   143  		NumStats: 3,
   144  	}
   145  	containerName := "/some/container"
   146  	cinfo := itest.GenerateRandomContainerInfo(containerName, 4, query, 1*time.Second)
   147  	cinfo1 := itest.GenerateRandomContainerInfo(path.Join(containerName, "sub1"), 4, query, 1*time.Second)
   148  	cinfo2 := itest.GenerateRandomContainerInfo(path.Join(containerName, "sub2"), 4, query, 1*time.Second)
   149  	response := []info.ContainerInfo{
   150  		*cinfo,
   151  		*cinfo1,
   152  		*cinfo2,
   153  	}
   154  	client, server, err := cadvisorTestClient(fmt.Sprintf("/api/v1.3/subcontainers%v", containerName), query, response, t)
   155  	if err != nil {
   156  		t.Fatalf("unable to get a client %v", err)
   157  	}
   158  	defer server.Close()
   159  	returned, err := client.SubcontainersInfo(containerName, query)
   160  	if err != nil {
   161  		t.Fatal(err)
   162  	}
   163  
   164  	if len(returned) != 3 {
   165  		t.Errorf("unexpected number of results: got %d, expected 3", len(returned))
   166  	}
   167  	if !returned[0].Eq(cinfo) {
   168  		t.Error("received unexpected ContainerInfo")
   169  	}
   170  	if !returned[1].Eq(cinfo1) {
   171  		t.Error("received unexpected ContainerInfo")
   172  	}
   173  	if !returned[2].Eq(cinfo2) {
   174  		t.Error("received unexpected ContainerInfo")
   175  	}
   176  }