client_mock_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package client // import "github.com/docker/docker/client"
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "github.com/docker/docker/api/types"
  8. )
  9. // transportFunc allows us to inject a mock transport for testing. We define it
  10. // here so we can detect the tlsconfig and return nil for only this type.
  11. type transportFunc func(*http.Request) (*http.Response, error)
  12. func (tf transportFunc) RoundTrip(req *http.Request) (*http.Response, error) {
  13. return tf(req)
  14. }
  15. func transportEnsureBody(f transportFunc) transportFunc {
  16. return func(req *http.Request) (*http.Response, error) {
  17. resp, err := f(req)
  18. if resp != nil && resp.Body == nil {
  19. resp.Body = http.NoBody
  20. }
  21. return resp, err
  22. }
  23. }
  24. func newMockClient(doer func(*http.Request) (*http.Response, error)) *http.Client {
  25. return &http.Client{
  26. // Some tests return a response with a nil body, this is incorrect semantically and causes a panic with wrapper transports (such as otelhttp's)
  27. // Wrap the doer to ensure a body is always present even if it is empty.
  28. Transport: transportEnsureBody(transportFunc(doer)),
  29. }
  30. }
  31. func errorMock(statusCode int, message string) func(req *http.Request) (*http.Response, error) {
  32. return func(req *http.Request) (*http.Response, error) {
  33. header := http.Header{}
  34. header.Set("Content-Type", "application/json")
  35. body, err := json.Marshal(&types.ErrorResponse{
  36. Message: message,
  37. })
  38. if err != nil {
  39. return nil, err
  40. }
  41. return &http.Response{
  42. StatusCode: statusCode,
  43. Body: io.NopCloser(bytes.NewReader(body)),
  44. Header: header,
  45. }, nil
  46. }
  47. }
  48. func plainTextErrorMock(statusCode int, message string) func(req *http.Request) (*http.Response, error) {
  49. return func(req *http.Request) (*http.Response, error) {
  50. return &http.Response{
  51. StatusCode: statusCode,
  52. Body: io.NopCloser(bytes.NewReader([]byte(message))),
  53. }, nil
  54. }
  55. }