mirror of
https://github.com/moby/moby.git
synced 2026-01-11 18:51:37 +00:00
client: tidy-up mock-utilities
- Add a `mockResponse` utility, and slightly enhance it to also include the request Headers and Status message, to be more closely to actual responses. - Add a `mockJSONResponse` utility, implemented using `mockResponse` - Remove `plainTextErrorMock` in favor of `mockResponse` Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -50,30 +49,41 @@ func WithMockClient(doer func(*http.Request) (*http.Response, error)) Opt {
|
||||
}
|
||||
|
||||
func errorMock(statusCode int, message string) func(req *http.Request) (*http.Response, error) {
|
||||
return mockJSONResponse(statusCode, nil, common.ErrorResponse{
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
|
||||
func mockJSONResponse[T any](statusCode int, headers http.Header, resp T) func(req *http.Request) (*http.Response, error) {
|
||||
respBody, err := json.Marshal(&resp)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
hdr := make(http.Header)
|
||||
if headers != nil {
|
||||
hdr = headers.Clone()
|
||||
}
|
||||
hdr.Set("Content-Type", "application/json")
|
||||
return mockResponse(statusCode, hdr, string(respBody))
|
||||
}
|
||||
|
||||
func mockResponse(statusCode int, headers http.Header, respBody string) func(req *http.Request) (*http.Response, error) {
|
||||
if headers == nil {
|
||||
headers = make(http.Header)
|
||||
}
|
||||
var body io.ReadCloser
|
||||
if respBody == "" {
|
||||
body = http.NoBody
|
||||
} else {
|
||||
body = io.NopCloser(strings.NewReader(respBody))
|
||||
}
|
||||
return func(req *http.Request) (*http.Response, error) {
|
||||
header := http.Header{}
|
||||
header.Set("Content-Type", "application/json")
|
||||
|
||||
body, err := json.Marshal(&common.ErrorResponse{
|
||||
Message: message,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &http.Response{
|
||||
Status: fmt.Sprintf("%d %s", statusCode, http.StatusText(statusCode)),
|
||||
StatusCode: statusCode,
|
||||
Body: io.NopCloser(bytes.NewReader(body)),
|
||||
Header: header,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func plainTextErrorMock(statusCode int, message string) func(req *http.Request) (*http.Response, error) {
|
||||
return func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: statusCode,
|
||||
Body: io.NopCloser(bytes.NewReader([]byte(message))),
|
||||
Header: headers,
|
||||
Body: body,
|
||||
Request: req,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user