Documentation ¶
Index ¶
- Constants
- Variables
- func MapFromMultipartFormData[K comparable, V any](ctx context.Context, r *http.Response, ...) (map[K]V, error)
- func NewMockClient(name string, wrap ...) (HttpClient, MockClient)
- func UnmarshalJSON[T any](ctx context.Context, r *http.Response) (T, error)
- type Client
- type ClientInterface
- type ClientOption
- type HttpClient
- type MockClient
- type MockExpectationsError
- type MockRequest
- func (rq MockRequest) String() string
- func (mock *MockRequest) WillNotBeCalled()
- func (mock *MockRequest) WillRespond() *mockResponse
- func (mock *MockRequest) WillReturnError(err error)
- func (mock *MockRequest) WithBody(b []byte) *MockRequest
- func (mock *MockRequest) WithHeader(k string, v ...string) *MockRequest
- func (mock *MockRequest) WithNonCanonicalHeader(k string, v ...string) *MockRequest
- type Request
- type RequestOption
- type Response
- type ResponseWriter
- type RoundTripper
- type Transport
Constants ¶
const ( MethodConnect = http.MethodConnect MethodDelete = http.MethodDelete MethodGet = http.MethodGet MethodHead = http.MethodHead MethodOptions = http.MethodOptions MethodPatch = http.MethodPatch MethodPost = http.MethodPost MethodPut = http.MethodPut MethodTrace = http.MethodTrace )
const ( StatusBadRequest = http.StatusBadRequest StatusForbidden = http.StatusForbidden StatusInternalServerError = http.StatusInternalServerError StatusNotAcceptable = http.StatusNotAcceptable StatusNotFound = http.StatusNotFound StatusOK = http.StatusOK )
Variables ¶
var ( NoBody = http.NoBody ListenAndServe = http.ListenAndServe )
var ( ErrInitialisingClient = errors.New("error initialising client") ErrInitialisingRequest = errors.New("error initialising request") ErrInvalidJSON = errors.New("invalid json") ErrInvalidRequestHeader = errors.New("invalid request headers") ErrInvalidURL = errors.New("invalid url") ErrMaxRetriesExceeded = errors.New("http retries exceeded") ErrNoResponseBody = errors.New("response body was empty") ErrReadingResponseBody = errors.New("error reading response body") ErrUnexpectedStatusCode = errors.New("unexpected status code") // errors related to the mock client ErrCannotChangeExpectations = errors.New("expectations cannot be changed") ErrUnexpectedRequest = errors.New("unexpected request") )
Functions ¶
func MapFromMultipartFormData ¶
func MapFromMultipartFormData[K comparable, V any]( ctx context.Context, r *http.Response, fn func(string, string, []byte) (K, V, error), ) (map[K]V, error)
MapFromMultipartFormData is a generic function that parses an http.Response body expected to contain multipart form data, transforming each part into a key-value pair using a supplied function.
func NewMockClient ¶
func NewMockClient(name string, wrap ...func(c interface { Do(*http.Request) (*http.Response, error) }) interface { Do(*http.Request) (*http.Response, error) }) (HttpClient, MockClient)
NewMockClient returns a new http.HttpClient to be used for making requests and an http.MockClient on which expected requests, and corresponding responses, may be configured.
params ¶
name // used to identify the mock client in test failure reports and errors wrap // optional function(s) to wrap the client with some other client // implementation, if required; nil functions are ignored
returns ¶
HttpClient // used to make requests; this should be injected into code under test MockClient // used to configure expected requests and provide details of responses // to be mocked for each request
Note the use of an anonymous interface in the exported function signature. This avoids creating coupling modules thru a shared reference to an interface type. In Go (currently at least) interfaces are fungible but interface types are not.
func UnmarshalJSON ¶
UnmarshalJSON is a generic function that unmarshals the body of an http.Response into a value of a specified type.
The function returns an error if the body cannot be read or if the body does not contain valid JSON and the result will be the zero value of the generic type.
Types ¶
type ClientInterface ¶
ClientInterface is an interface that describes a wrappable http client
type ClientOption ¶
type ClientOption func(*client) error
ClientOption is a function that applies an option to a client
func MaxRetries ¶
func MaxRetries(n uint) ClientOption
MaxRetries sets the maximum number of retries for requests made using the client. Individual requests may be configured to override this value on a case-by-case basis.
func URL ¶
func URL(u any) ClientOption
URL sets the base URL for requests made using the client. The URL may be specified as a string or a *url.URL.
If a string is provided, it will be parsed to ensure it is a valid, absolute URL.
If a URL is provided is must be absolute.
type HttpClient ¶
type HttpClient interface { Delete(context.Context, string, ...RequestOption) (*http.Response, error) Do(*http.Request) (*http.Response, error) Get(context.Context, string, ...RequestOption) (*http.Response, error) Patch(context.Context, string, ...RequestOption) (*http.Response, error) Post(context.Context, string, ...RequestOption) (*http.Response, error) Put(context.Context, string, ...RequestOption) (*http.Response, error) NewRequest(context.Context, string, string, ...RequestOption) (*http.Request, error) }
HttpClient is an interface that describes the methods of an http client.
The interface is intended to be used as a wrapper around an http.Client or other http client implementation, allowing for the addition of additional functionality or configuration.
func NewClient ¶
func NewClient(name string, opts ...ClientOption) (HttpClient, error)
NewClient returns a new HttpClient with the name and url specified, wrapping a supplied ClientInterface implementation. Additional configuration options may be optionally specified.
params ¶
name // identifies the client, e.g. in errors opts // optional configuration
The url typically includes the protocol, hostname and port for the client but may include any additional url components consistently required for requests performed using the client.
type MockClient ¶
type MockClient interface { Expect(method string, path string) *MockRequest ExpectDelete(path string) *MockRequest ExpectGet(path string) *MockRequest ExpectPatch(path string) *MockRequest ExpectPost(path string) *MockRequest ExpectPut(path string) *MockRequest ExpectationsWereMet() error Reset() }
MockClient is an interface that described the methods provided for mocking expectations on a client
type MockExpectationsError ¶
type MockExpectationsError struct {
// contains filtered or unexported fields
}
MockExpectationsError is the error returned by ExpectationsNotMet() when one or more configured expectations have not been met. It wraps all errors representing the failed expectations.
func (MockExpectationsError) Error ¶
func (err MockExpectationsError) Error() string
Error implements the error interface for MockExpectationsError by returning a string representation of the error, presenting each wrapped error indented under a summary identifying the mock client to which the failures relate.
type MockRequest ¶
type MockRequest struct { // configuration of the response to be mocked in response to the request Response *mockResponse // contains filtered or unexported fields }
MockRequest holds details of a request expected by a MockClient
func (MockRequest) String ¶
func (rq MockRequest) String() string
String implements the stringer interface for a MockRequest, returning a string consisting of the request method (or <ANY> if not specified) and url (or <any://hostname/and/path> if not specified)
func (*MockRequest) WillNotBeCalled ¶
func (mock *MockRequest) WillNotBeCalled()
WillNotBeCalled indicates that the request is not expected to be made. If a corresponding request is made by the client, this will be reflected as a failed expectation.
func (*MockRequest) WillRespond ¶
func (mock *MockRequest) WillRespond() *mockResponse
WillRespond establishes a default response for the request, returning a mock response to be used to provide details of the response such as status code, headers or a body etc.
func (*MockRequest) WillReturnError ¶
func (mock *MockRequest) WillReturnError(err error)
WillReturnError establishes an error to be returned by the client when attempting to perform this request. Any other response configuration is discarded if a request is configured to return an error.
func (*MockRequest) WithBody ¶
func (mock *MockRequest) WithBody(b []byte) *MockRequest
WithBody identifies the expected body to be sent with the request.
func (*MockRequest) WithHeader ¶
func (mock *MockRequest) WithHeader(k string, v ...string) *MockRequest
WithHeader identifies a header expected to be included with the request. The key (k) is normalised using textproto.CanonicalMIMEHeaderKey. An option value (v) may be specified; if no value is specified then the header only needs to be present; if a value is also specified then the header must be present with the specified value.
If multiple values are specified only the first is significant; additional values are discarded.
To configured a non-canonical header, use WithNonCanonicalHeader().
func (*MockRequest) WithNonCanonicalHeader ¶
func (mock *MockRequest) WithNonCanonicalHeader(k string, v ...string) *MockRequest
WithNonCanonicalHeader identifies a non-canonical header expected to be included with the request. The key (k) is expected to match the case as specified. An option value (v) may be specified; if no value is specified then the header only needs to be present; if a value is also specified then the header must be present with the specified value.
If multiple values are specified only the first is significant; additional values are discarded.
To configured a canonical header, ensuring that the header key is normalised using textproto.CanonicalMIMEHeaderKey, use WithHeader().
type RequestOption ¶
RequestOption is a function that applies an option to a request
type ResponseWriter ¶
type ResponseWriter = http.ResponseWriter
type RoundTripper ¶
type RoundTripper = http.RoundTripper