|
| 1 | +package 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/alibaba/pouch/apis/types" |
| 14 | +) |
| 15 | + |
| 16 | +func TestContainerTopError(t *testing.T) { |
| 17 | + client := &APIClient{ |
| 18 | + HTTPCli: newMockClient(errorMockResponse(http.StatusInternalServerError, "Server error")), |
| 19 | + } |
| 20 | + _, err := client.ContainerTop(context.Background(), "nothing", []string{}) |
| 21 | + if err == nil || !strings.Contains(err.Error(), "Server error") { |
| 22 | + t.Fatalf("expected a Server Error, got %v", err) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +func TestContainerTop(t *testing.T) { |
| 27 | + expectedURL := "/containers/container_id/top" |
| 28 | + |
| 29 | + httpClient := newMockClient(func(req *http.Request) (*http.Response, error) { |
| 30 | + if !strings.HasPrefix(req.URL.Path, expectedURL) { |
| 31 | + return nil, fmt.Errorf("expected URL '%s', got '%s'", expectedURL, req.URL) |
| 32 | + } |
| 33 | + query := req.URL.Query() |
| 34 | + args := query.Get("ps_args") |
| 35 | + if args != "arg1 arg2" { |
| 36 | + return nil, fmt.Errorf("args not set in URL properly. Expected 'arg1 arg2', got %s", args) |
| 37 | + } |
| 38 | + psListJSON := types.ContainerProcessList{ |
| 39 | + Processes: [][]string{{"bar11", "bar12"}, {"bar21", "bar22"}}, |
| 40 | + Titles: []string{"foo1", "foo2"}, |
| 41 | + } |
| 42 | + b, err := json.Marshal(psListJSON) |
| 43 | + if err != nil { |
| 44 | + return nil, err |
| 45 | + } |
| 46 | + return &http.Response{ |
| 47 | + StatusCode: http.StatusOK, |
| 48 | + Body: ioutil.NopCloser(bytes.NewReader([]byte(b))), |
| 49 | + }, nil |
| 50 | + }) |
| 51 | + client := &APIClient{ |
| 52 | + HTTPCli: httpClient, |
| 53 | + } |
| 54 | + psList, err := client.ContainerTop(context.Background(), "container_id", []string{"arg1", "arg2"}) |
| 55 | + if err != nil { |
| 56 | + t.Fatal(err) |
| 57 | + } |
| 58 | + |
| 59 | + if len(psList.Titles) != 2 { |
| 60 | + t.Fatalf("expected 2 titles, got %v", len(psList.Titles)) |
| 61 | + } |
| 62 | + for _, ps := range psList.Processes { |
| 63 | + if len(ps) != len(psList.Titles) { |
| 64 | + t.Fatalf("expected 2 values, got %v", len(ps)) |
| 65 | + break |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments