Documentation
¶
Overview ¶
Package httptest builds on net/http/httptest to make process-local HTTP requests inside tests as smooth as possible.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler is a wrapper around http.Handler providing convenience methods for use in tests.
func NewHandler ¶
NewHandler wraps the given http.Handler in type Handler to provide extra convenience methods.
func (Handler) RespondTo ¶
func (h Handler) RespondTo(ctx context.Context, methodAndPath string, options ...RequestOption) *http.Response
RespondTo executes an HTTP request against this handler. The interface is optimized towards readability and brevity in tests for REST APIs:
- The request method and URL are given in a single string, e.g. "POST /v1/objects/new".
- Additional headers, a request body, etc. can be provided as a list of options.
The interface is optimized towards users of Ginkgo/Gomega. When you get the response, always check it with HaveHTTPStatus() first. This will catch any protocol-level and marshaling errors that may occur during the request.
var assets []Asset resp := h.RespondTo(ctx, "GET /v1/assets", httptest.ReceiveJSONInto(&assets)) Expect(resp).To(HaveHTTPStatus(http.StatusOK)) Expect(assets).To(HaveLen(4)) Expect(assets[2]).To(Equal("example"))
type RequestOption ¶
type RequestOption func(*requestParams)
RequestOption controls optional behavior in func Handler.RespondTo().
func ReceiveJSONInto ¶
func ReceiveJSONInto(target any) RequestOption
ReceiveJSONInto adds parsing of a JSON response body to an HTTP request. If the response has a 2xx status code, its response body will be unmarshaled into the provided target. If unmarshaling fails, the response will have status code 999 and contain the error message as a response body.
func WithBody ¶
func WithBody(r io.Reader) RequestOption
WithBody adds a request body to an HTTP request.
If the caller does not specify a Content-Type using WithBody(), application/octet-stream will be set.
func WithHeader ¶
func WithHeader(key, value string) RequestOption
WithHeader adds a single HTTP header to an HTTP request.
func WithHeaders ¶
func WithHeaders(hdr http.Header) RequestOption
WithHeaders adds several HTTP headers to an HTTP request.
func WithJSONBody ¶
func WithJSONBody(payload any) RequestOption
WithJSONBody adds a JSON request body to an HTTP request. The provided payload will be serialized into JSON.
If the caller does not specify a Content-Type using WithBody(), application/json will be set.