container_stats_test.go 1.7 KB

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