container_stats_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package client // import "github.com/docker/docker/client"
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "testing"
  10. "github.com/docker/docker/errdefs"
  11. "gotest.tools/v3/assert"
  12. is "gotest.tools/v3/assert/cmp"
  13. )
  14. func TestContainerStatsError(t *testing.T) {
  15. client := &Client{
  16. client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
  17. }
  18. _, err := client.ContainerStats(context.Background(), "nothing", false)
  19. assert.Check(t, is.ErrorType(err, errdefs.IsSystem))
  20. }
  21. func TestContainerStats(t *testing.T) {
  22. expectedURL := "/containers/container_id/stats"
  23. cases := []struct {
  24. stream bool
  25. expectedStream string
  26. }{
  27. {
  28. expectedStream: "0",
  29. },
  30. {
  31. stream: true,
  32. expectedStream: "1",
  33. },
  34. }
  35. for _, c := range cases {
  36. client := &Client{
  37. client: newMockClient(func(r *http.Request) (*http.Response, error) {
  38. if !strings.HasPrefix(r.URL.Path, expectedURL) {
  39. return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, r.URL)
  40. }
  41. query := r.URL.Query()
  42. stream := query.Get("stream")
  43. if stream != c.expectedStream {
  44. return nil, fmt.Errorf("stream not set in URL query properly. Expected '%s', got %s", c.expectedStream, stream)
  45. }
  46. return &http.Response{
  47. StatusCode: http.StatusOK,
  48. Body: io.NopCloser(bytes.NewReader([]byte("response"))),
  49. }, nil
  50. }),
  51. }
  52. resp, err := client.ContainerStats(context.Background(), "container_id", c.stream)
  53. if err != nil {
  54. t.Fatal(err)
  55. }
  56. defer resp.Body.Close()
  57. content, err := io.ReadAll(resp.Body)
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. if string(content) != "response" {
  62. t.Fatalf("expected response to contain 'response', got %s", string(content))
  63. }
  64. }
  65. }