Documentation ¶
Index ¶
- Variables
- func SafeReadBody(received *http.Request) ([]byte, error)
- type Mock
- func (m *Mock) AssertExpectations(t mock.TestingT) bool
- func (m *Mock) AssertNotRequested(t mock.TestingT, method string, path string, body []byte) bool
- func (m *Mock) AssertNumberOfRequests(t mock.TestingT, method string, path string, expectedRequests int) bool
- func (m *Mock) AssertRequested(t mock.TestingT, method string, path string, body []byte) bool
- func (m *Mock) On(method string, URL string, body []byte) *Request
- func (m *Mock) Requested(received *http.Request) *Response
- func (m *Mock) Test(t mock.TestingT) *Mock
- type Request
- func (r *Request) Matches(matchers ...RequestMatcher) *Request
- func (r *Request) Once() *Request
- func (r *Request) Respond(statusCode int, body []byte) *Response
- func (r *Request) RespondNoContent() *Response
- func (r *Request) RespondOK(body []byte) *Response
- func (r *Request) RespondUsing(writer ResponseWriter) *Response
- func (r *Request) String() string
- func (r *Request) Times(i int) *Request
- func (r *Request) Twice() *Request
- type RequestMatcher
- type Response
- func (r *Response) Header(key string, value string, values ...string) *Response
- func (r *Response) On(method string, path string, body []byte) *Request
- func (r *Response) Once() *Request
- func (r *Response) Times(i int) *Request
- func (r *Response) Twice() *Request
- func (r *Response) Write(w http.ResponseWriter, req *http.Request) (int, error)
- type ResponseWriter
- type Server
- type ServerConfig
Constants ¶
This section is empty.
Variables ¶
var ( ErrReadBody = errors.New("error reading body") AnyMethod = "httpmock.AnyMethod" AnyBody = []byte("httpmock.AnyBody") )
var ErrWriteReturnBody = errors.New("error writing return body")
Functions ¶
func SafeReadBody ¶ added in v0.4.0
SafeReadBody reads the body of a http.Request and resets the http.Request's body so that it may be read again afterward.
Types ¶
type Mock ¶
type Mock struct { // Represents the requests that are expected to be received. ExpectedRequests []*Request // Holds the requests that were made to a mocked handler or server. Requests []Request // contains filtered or unexported fields }
Mock is the workhorse used to track activity of a server's requesst. For an example of its usage, refer to the README.
func (*Mock) AssertExpectations ¶
AssertExpectations assert that everything specified with Mock.On and Request.Respond was in fact requested as expected. Request's may have occurred in any order.
func (*Mock) AssertNotRequested ¶
AssertRequested asserts that the request was not received.
func (*Mock) AssertNumberOfRequests ¶
func (m *Mock) AssertNumberOfRequests(t mock.TestingT, method string, path string, expectedRequests int) bool
AssertNumberOfRequests asserts that the request was made expectedRequests times.
This assertion behaves a bit differently than other assertions. There are a few parts of the request that are ignored when calculating, including:
- URL username/password information
- URL query parameters
- URL fragment
func (*Mock) AssertRequested ¶
AssertRequested asserts that the request was received.
func (*Mock) On ¶
On starts a description of an expectation of the specified Request being received.
Mock.On(http.MethodDelete, "/some/path/1234")
func (*Mock) Requested ¶
Requested tells the mock that a http.Request has been received and gets a response to return. Panics if the request is unexpected (i.e. not preceded by appropriate Mock.On calls).
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request represents a http.Request and is used for setting expectations, as well as recording activity.
func (*Request) Matches ¶ added in v0.3.0
func (r *Request) Matches(matchers ...RequestMatcher) *Request
Matches adds one or more RequestMatcher's to the Request. RequestMatcher's are called in FIFO order after the HTTP method, URL, and body have been matched.
func queryAtLeast(key string, minValue int) RequestMatcher { fn := func(received *http.Request) (output string, differences int) { v := received.URL.Query().Get(key) if v == "" { output = fmt.Sprintf("FAIL: queryAtLeast: (Missing) ((%s)) != %s", received.URL.Query().Encode(), key) differences = 1 return } val, err := strconv.Atoi(v) if err != nil { output = fmt.Sprintf("FAIL: queryAtLeast: %s value %q unable to coerce to int", key, v) differences = 1 return } if val < minValue { output = fmt.Sprintf("FAIL: queryAtLeast: %d < %d", val, minValue) differences = 1 return } output = fmt.Sprintf("PASS: queryAtLeast: %d >= %d", val, minValue) return } return fn } Mock.On(http.MethodGet, "/some/path/1234", nil).Matches(queryAtLeast("page", 2))
func (*Request) Once ¶
Once indicates that the Mock should only return the response once.
Mock.On(http.MethodDelete, "/some/path/1234").Once()
func (*Request) Respond ¶
Respond specifies the response arguments for the expectation.
Mock.On(http.GetMethod, "/some/path").Respond(http.StatusInternalServerError, nil)
func (*Request) RespondNoContent ¶
RespondNoContent is a convenience method that sets the status code as 204.
Mock.On(http.MethodDelete, "/some/path/1234").RespondNoContent()
func (*Request) RespondOK ¶
RespondOK is a convenience method that sets the status code as 200 and the provided body.
Mock.On(http.GetMethod, "/some/path").RespondOK([]byte(`{"foo", "bar"}`))
func (*Request) RespondUsing ¶ added in v0.5.0
func (r *Request) RespondUsing(writer ResponseWriter) *Response
RespondUsing overrides the Request.Respond functionality by allowing a custom writer to be invoked instead of the typical writing functionality.
Note: The `writer` is responsible for the entire response, including headers, status code, and body.
type RequestMatcher ¶ added in v0.3.0
RequestMatcher is used by the Request.Matches method to match a http.Request.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response hold the parts of the response that should be returned.
func (*Response) Header ¶
Header sets the value or values for a response header. Any prior values that have already been set for a header with the same key will be overridden.
func (*Response) On ¶
On chains a new expectation description onto the grandparent Mock. This allows syntax like:
Mock. On(http.MethodPost, "/some/path").RespondOk([]byte(`{"id": "1234"}`)). On(http.MethodDelete, "/some/path/1234").RespondNoContent(). On(http.MethodDelete, "/some/path/1234").Respond(http.StatusNotFound, nil)
func (*Response) Once ¶
Once is a convenience method which indicates that the grandparent Mock should only expect the parent request once.
Mock.On(http.MethodDelete, "/some/path/1234").RespondNoContent().Once()
func (*Response) Times ¶
Times is a convenience method which indicates that the grandparent Mock should only expect the parent request the indicated number of times.
Mock.On(http.MethodDelete, "/some/path/1234").RespondNoContent().Times(5)
func (*Response) Twice ¶
Twice is a convenience method which indicates that the grandparent Mock should only expect the parent request twice.
Mock.On(http.MethodDelete, "/some/path/1234").RespondNoContent().Twice()
func (*Response) Write ¶
Write the response to the provided http.ResponseWriter. The number of bytes successfully written to the http.ResponseWriter are returned, as well as any errors.
Note: If Request.RespondUsing was previously called, all response configurations are ignored except for the provided custom ResponseWriter.
type ResponseWriter ¶ added in v0.5.0
ResponseWriter writes a http.Response and returns the number of bytes written and whether or not the operation encountered an error.
*http.Request is provided as an argument so that the response writer can use information from the request when crafting the response. If the ResponseWriter is static, the *http.Request may be safely ignored.
type Server ¶
Server simplifies the orchestration of a Mock inside a handler and server. It wraps the stdlib httptest.Server implementation and provides a handler to log requests and write configured responses.
func NewServerWithConfig ¶ added in v0.6.0
func NewServerWithConfig(cfg ServerConfig) *Server
func (*Server) IsRecoverable ¶
IsRecoverable returns whether or not the Server is considered recoverable.
func (*Server) NotRecoverable ¶ added in v0.6.0
NotRecoverable sets a Server as not recoverable, so that panics are allowed to propagate to the main process. With the default handler, panics are caught and printed to stdout, with a final 404 returned to the client.
404 was chosen rather than 500 due to panics almost always occurring when a matching Request cannot be found. However, custom handlers can choose to implement their recovery mechanism however they would like, using the Server.IsRecoverable method to access this value.
type ServerConfig ¶ added in v0.6.0
type ServerConfig struct { // Create TLS-configured server TLS bool // Custom server handler Handler http.HandlerFunc }
ServerConfig contains settings for configuring a Server. It is used with NewServerWithConfig. For default behavior, use NewServer.