request_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package client
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "strings"
  8. "testing"
  9. "github.com/docker/docker/api/types"
  10. "golang.org/x/net/context"
  11. )
  12. // TestSetHostHeader should set fake host for local communications, set real host
  13. // for normal communications.
  14. func TestSetHostHeader(t *testing.T) {
  15. testURL := "/test"
  16. testCases := []struct {
  17. host string
  18. expectedHost string
  19. expectedURLHost string
  20. }{
  21. {
  22. "unix:///var/run/docker.sock",
  23. "docker",
  24. "/var/run/docker.sock",
  25. },
  26. {
  27. "npipe:////./pipe/docker_engine",
  28. "docker",
  29. "//./pipe/docker_engine",
  30. },
  31. {
  32. "tcp://0.0.0.0:4243",
  33. "",
  34. "0.0.0.0:4243",
  35. },
  36. {
  37. "tcp://localhost:4243",
  38. "",
  39. "localhost:4243",
  40. },
  41. }
  42. for c, test := range testCases {
  43. proto, addr, basePath, err := ParseHost(test.host)
  44. if err != nil {
  45. t.Fatal(err)
  46. }
  47. client := &Client{
  48. client: newMockClient(func(req *http.Request) (*http.Response, error) {
  49. if !strings.HasPrefix(req.URL.Path, testURL) {
  50. return nil, fmt.Errorf("Test Case #%d: Expected URL %q, got %q", c, testURL, req.URL)
  51. }
  52. if req.Host != test.expectedHost {
  53. return nil, fmt.Errorf("Test Case #%d: Expected host %q, got %q", c, test.expectedHost, req.Host)
  54. }
  55. if req.URL.Host != test.expectedURLHost {
  56. return nil, fmt.Errorf("Test Case #%d: Expected URL host %q, got %q", c, test.expectedURLHost, req.URL.Host)
  57. }
  58. return &http.Response{
  59. StatusCode: http.StatusOK,
  60. Body: ioutil.NopCloser(bytes.NewReader(([]byte("")))),
  61. }, nil
  62. }),
  63. proto: proto,
  64. addr: addr,
  65. basePath: basePath,
  66. }
  67. _, err = client.sendRequest(context.Background(), "GET", testURL, nil, nil, nil)
  68. if err != nil {
  69. t.Fatal(err)
  70. }
  71. }
  72. }
  73. // TestPlainTextError tests the server returning an error in plain text for
  74. // backwards compatibility with API versions <1.24. All other tests use
  75. // errors returned as JSON
  76. func TestPlainTextError(t *testing.T) {
  77. client := &Client{
  78. client: newMockClient(plainTextErrorMock(http.StatusInternalServerError, "Server error")),
  79. }
  80. _, err := client.ContainerList(context.Background(), types.ContainerListOptions{})
  81. if err == nil || err.Error() != "Error response from daemon: Server error" {
  82. t.Fatalf("expected a Server Error, got %v", err)
  83. }
  84. }