github.com/moby/docker@v26.1.3+incompatible/client/client_mock_test.go (about)

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