container_top_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package client // import "github.com/docker/docker/client"
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "reflect"
  10. "strings"
  11. "testing"
  12. "github.com/docker/docker/api/types/container"
  13. "github.com/docker/docker/errdefs"
  14. "gotest.tools/v3/assert"
  15. is "gotest.tools/v3/assert/cmp"
  16. )
  17. func TestContainerTopError(t *testing.T) {
  18. client := &Client{
  19. client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
  20. }
  21. _, err := client.ContainerTop(context.Background(), "nothing", []string{})
  22. assert.Check(t, is.ErrorType(err, errdefs.IsSystem))
  23. }
  24. func TestContainerTop(t *testing.T) {
  25. expectedURL := "/containers/container_id/top"
  26. expectedProcesses := [][]string{
  27. {"p1", "p2"},
  28. {"p3"},
  29. }
  30. expectedTitles := []string{"title1", "title2"}
  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. query := req.URL.Query()
  37. args := query.Get("ps_args")
  38. if args != "arg1 arg2" {
  39. return nil, fmt.Errorf("args not set in URL query properly. Expected 'arg1 arg2', got %v", args)
  40. }
  41. b, err := json.Marshal(container.ContainerTopOKBody{
  42. Processes: [][]string{
  43. {"p1", "p2"},
  44. {"p3"},
  45. },
  46. Titles: []string{"title1", "title2"},
  47. })
  48. if err != nil {
  49. return nil, err
  50. }
  51. return &http.Response{
  52. StatusCode: http.StatusOK,
  53. Body: io.NopCloser(bytes.NewReader(b)),
  54. }, nil
  55. }),
  56. }
  57. processList, err := client.ContainerTop(context.Background(), "container_id", []string{"arg1", "arg2"})
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. if !reflect.DeepEqual(expectedProcesses, processList.Processes) {
  62. t.Fatalf("Processes: expected %v, got %v", expectedProcesses, processList.Processes)
  63. }
  64. if !reflect.DeepEqual(expectedTitles, processList.Titles) {
  65. t.Fatalf("Titles: expected %v, got %v", expectedTitles, processList.Titles)
  66. }
  67. }