Documentation ¶
Overview ¶
Package httpmock provides utilities to test HTTP REST API.
Index ¶
- type Client
- func (c *Client) CheckUnexpectedOtherResponses() error
- func (c *Client) Concurrently() *Client
- func (c *Client) ExpectNoOtherResponses() error
- func (c *Client) ExpectOtherResponsesBody(body []byte) error
- func (c *Client) ExpectOtherResponsesHeader(key, value string) error
- func (c *Client) ExpectOtherResponsesStatus(statusCode int) error
- func (c *Client) ExpectResponseBody(body []byte) error
- func (c *Client) ExpectResponseHeader(key, value string) error
- func (c *Client) ExpectResponseStatus(statusCode int) error
- func (c *Client) FollowRedirects() *Client
- func (c *Client) Reset() *Client
- func (c *Client) SetBaseURL(baseURL string)
- func (c *Client) WithBody(body []byte) *Client
- func (c *Client) WithContentType(contentType string) *Client
- func (c *Client) WithContext(ctx context.Context) *Client
- func (c *Client) WithCookie(name, value string) *Client
- func (c *Client) WithHeader(key, value string) *Client
- func (c *Client) WithMethod(method string) *Client
- func (c *Client) WithPath(path string) *Clientdeprecated
- func (c *Client) WithURI(uri string) *Client
- type Expectation
- type Server
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct { ConcurrencyLevel int JSONComparer assertjson.Comparer OnBodyMismatch func(received []byte) // Optional, called when received body does not match expected. Transport http.RoundTripper // Headers are default headers added to all requests, can be overridden by WithHeader. Headers map[string]string // Cookies are default cookies added to all requests, can be overridden by WithCookie. Cookies map[string]string // contains filtered or unexported fields }
Client keeps state of expectations.
func NewClient ¶
NewClient creates client instance, baseURL may be empty if Client.SetBaseURL is used later.
Example ¶
package main import ( "fmt" "net/http" "github.com/bool64/httpmock" ) func main() { // Prepare server mock. sm, url := httpmock.NewServer() defer sm.Close() // This example shows Client and Server working together for sake of portability. // In real-world scenarios Client would complement real server or Server would complement real HTTP client. // Set successful expectation for first request out of concurrent batch. exp := httpmock.Expectation{ Method: http.MethodPost, RequestURI: "/foo?q=1", RequestHeader: map[string]string{ "X-Custom": "def", "X-Header": "abc", "Content-Type": "application/json", }, RequestBody: []byte(`{"foo":"bar"}`), Status: http.StatusAccepted, ResponseBody: []byte(`{"bar":"foo"}`), } sm.Expect(exp) // Set failing expectation for other requests of concurrent batch. exp.Status = http.StatusConflict exp.ResponseBody = []byte(`{"error":"conflict"}`) exp.Unlimited = true sm.Expect(exp) // Prepare client request. c := httpmock.NewClient(url) c.ConcurrencyLevel = 50 c.Headers = map[string]string{ "X-Header": "abc", } c.Reset(). WithMethod(http.MethodPost). WithHeader("X-Custom", "def"). WithContentType("application/json"). WithBody([]byte(`{"foo":"bar"}`)). WithURI("/foo?q=1"). Concurrently() // Check expectations errors. fmt.Println( c.ExpectResponseStatus(http.StatusAccepted), c.ExpectResponseBody([]byte(`{"bar":"foo"}`)), c.ExpectOtherResponsesStatus(http.StatusConflict), c.ExpectOtherResponsesBody([]byte(`{"error":"conflict"}`)), ) }
Output: <nil> <nil> <nil> <nil>
func (*Client) CheckUnexpectedOtherResponses ¶
CheckUnexpectedOtherResponses fails if other responses were present, but not expected with ExpectOther* functions.
Does not affect single (non-concurrent) calls.
func (*Client) Concurrently ¶
Concurrently enables concurrent calls to idempotent endpoint.
func (*Client) ExpectNoOtherResponses ¶
ExpectNoOtherResponses sets expectation for only one response status to be received during concurrent calling.
Does not affect single (non-concurrent) calls.
func (*Client) ExpectOtherResponsesBody ¶
ExpectOtherResponsesBody sets expectation for response body to be received one or more times during concurrent calling.
For example, it may describe "Not Found" response on multiple DELETE or "Conflict" response on multiple POST. Does not affect single (non-concurrent) calls.
func (*Client) ExpectOtherResponsesHeader ¶
ExpectOtherResponsesHeader sets expectation for response header value to be received one or more times during concurrent calling.
func (*Client) ExpectOtherResponsesStatus ¶
ExpectOtherResponsesStatus sets expectation for response status to be received one or more times during concurrent calling.
For example, it may describe "Not Found" response on multiple DELETE or "Conflict" response on multiple POST. Does not affect single (non-concurrent) calls.
func (*Client) ExpectResponseBody ¶
ExpectResponseBody sets expectation for response body to be received.
In concurrent mode such response mush be met only once or for all calls.
func (*Client) ExpectResponseHeader ¶
ExpectResponseHeader asserts expected response header value.
func (*Client) ExpectResponseStatus ¶
ExpectResponseStatus sets expected response status code.
func (*Client) FollowRedirects ¶ added in v0.1.3
FollowRedirects enables automatic following of Location header.
func (*Client) SetBaseURL ¶
SetBaseURL changes baseURL configured with constructor.
func (*Client) WithContentType ¶
WithContentType sets request content type.
func (*Client) WithContext ¶ added in v0.1.3
WithContext adds context to request.
func (*Client) WithCookie ¶
WithCookie sets request cookie.
func (*Client) WithHeader ¶
WithHeader sets request header.
func (*Client) WithMethod ¶
WithMethod sets request HTTP method.
type Expectation ¶
type Expectation struct { Method string RequestURI string RequestHeader map[string]string RequestCookie map[string]string RequestBody []byte Status int ResponseHeader map[string]string ResponseBody []byte // Unlimited enables reusing of this expectation unlimited number of times. Unlimited bool // Repeated defines how many times this expectation should be used. Repeated int }
Expectation describes expected request and defines response.
type Server ¶
type Server struct { // OnError is called on expectations mismatch or internal errors, optional. OnError func(err error) // OnRequest is called on before every request, optional. OnRequest func(rw http.ResponseWriter, req *http.Request) // ErrorResponder allows custom failure responses. ErrorResponder func(rw http.ResponseWriter, err error) // DefaultResponseHeaders are added to every response to an expected request. DefaultResponseHeaders map[string]string // JSONComparer controls JSON equality check. JSONComparer assertjson.Comparer // OnBodyMismatch is called when received body does not match expected, optional. OnBodyMismatch func(received []byte) // contains filtered or unexported fields }
Server serves predefined response for predefined request.
func (*Server) ExpectAsync ¶
func (sm *Server) ExpectAsync(e Expectation)
ExpectAsync sets non-sequential expectation.
Asynchronous expectations are checked for every incoming request, first match is used for response. If there are no matches, regular (sequential expectations are used).
func (*Server) ExpectationsWereMet ¶
ExpectationsWereMet checks whether all queued expectations were met in order. If any of them was not met - an error is returned.
func (*Server) ResetExpectations ¶
func (sm *Server) ResetExpectations()
ResetExpectations discards all expectation to reset the state of mock.