Documentation
¶
Overview ¶
Package httpmock provides functionalities for mocking http server.
Index ¶
- Variables
- func AssertHeaderContains(t assert.TestingT, headers, contains Header) bool
- func DoRequest(t *testing.T, method, requestURI string, headers Header, body []byte) (int, map[string]string, []byte, time.Duration)
- func DoRequestWithTimeout(t *testing.T, method, requestURI string, headers Header, body []byte, ...) (int, map[string]string, []byte, time.Duration)
- func GetBody(r *http.Request) ([]byte, error)
- type BodyMatcher
- type Header
- type HeaderMatcher
- type Mocker
- type Request
- func (r *Request) After(d time.Duration) *Request
- func (r *Request) Handler(handler RequestHandler) *Request
- func (r *Request) Once() *Request
- func (r *Request) Return(v interface{}) *Request
- func (r *Request) ReturnCode(code int) *Request
- func (r *Request) ReturnFile(filePath string) *Request
- func (r *Request) ReturnHeader(header, value string) *Request
- func (r *Request) ReturnHeaders(headers Header) *Request
- func (r *Request) ReturnJSON(body interface{}) *Request
- func (r *Request) Returnf(format string, args ...interface{}) *Request
- func (r *Request) Times(i int) *Request
- func (r *Request) Twice() *Request
- func (r *Request) WaitUntil(w <-chan time.Time) *Request
- func (r *Request) WithBody(body interface{}) *Request
- func (r *Request) WithBodyJSON(v interface{}) *Request
- func (r *Request) WithBodyf(format string, args ...interface{}) *Request
- func (r *Request) WithHeader(header, value string) *Request
- func (r *Request) WithHeaders(headers Header) *Request
- type RequestHandler
- type RequestMatcher
- type RequestMatcherConfig
- type RequestMatcherError
- type RequestMatcherOption
- func WithBodyMatcher(m BodyMatcher) RequestMatcherOption
- func WithExactBodyMatcher() RequestMatcherOption
- func WithExactHeaderMatcher() RequestMatcherOption
- func WithExactURIMatcher() RequestMatcherOption
- func WithHeaderMatcher(m HeaderMatcher) RequestMatcherOption
- func WithURIMatcher(m URIMatcher) RequestMatcherOption
- type Server
- func (s *Server) Close()
- func (s *Server) Expect(method, requestURI string) *Request
- func (s *Server) ExpectDelete(requestURI string) *Request
- func (s *Server) ExpectGet(requestURI string) *Request
- func (s *Server) ExpectHead(requestURI string) *Request
- func (s *Server) ExpectPatch(requestURI string) *Request
- func (s *Server) ExpectPost(requestURI string) *Request
- func (s *Server) ExpectPut(requestURI string) *Request
- func (s *Server) ExpectationsWereMet() error
- func (s *Server) ResetExpectations()
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) URL() string
- func (s *Server) WithDefaultResponseHeaders(headers Header) *Server
- func (s *Server) WithRequestMatcher(matcher RequestMatcher) *Server
- type TestingT
- type URIMatcher
Constants ¶
This section is empty.
Variables ¶
var ErrUnsupportedDataType = errors.New("unsupported data type")
ErrUnsupportedDataType represents that the data type is not supported.
Functions ¶
func AssertHeaderContains ¶ added in v0.4.5
AssertHeaderContains asserts that the HTTP headers contains some specifics headers.
func DoRequest ¶ added in v0.3.0
func DoRequest( t *testing.T, method, requestURI string, headers Header, body []byte, ) (int, map[string]string, []byte, time.Duration)
DoRequest calls DoRequestWithTimeout with 1 second timeout. nolint:thelper // It is called in DoRequestWithTimeout.
func DoRequestWithTimeout ¶ added in v0.3.0
func DoRequestWithTimeout( t *testing.T, method, requestURI string, headers Header, body []byte, timeout time.Duration, ) (int, map[string]string, []byte, time.Duration)
DoRequestWithTimeout sends a simple HTTP request for testing and returns the status code, response headers and response body along with the total execution time.
code, headers, body, _ = DoRequestWithTimeout(t, http.MethodGet, "/", nil, nil, 0)
Types ¶
type BodyMatcher ¶
BodyMatcher matches a body with an expectation.
func ExactBodyMatcher ¶
func ExactBodyMatcher() BodyMatcher
ExactBodyMatcher matches a body by checking if it is equal to the expectation.
type HeaderMatcher ¶
HeaderMatcher matches header with an expectation.
func ExactHeaderMatcher ¶
func ExactHeaderMatcher() HeaderMatcher
ExactHeaderMatcher matches a header by checking if it is equal to the expectation.
type Mocker ¶
Mocker is a function that applies expectations to the mocked server.
func New ¶
New creates a mocker server with expectations and assures that ExpectationsWereMet() is called.
s := httpmock.New(func(s *Server) {
s.ExpectPost("/create").
WithHeader("Authorization", "Bearer token").
WithBody(`{"foo":"bar"}`).
ReturnCode(http.StatusCreated).
Return(`{"id":1,"foo":"bar"}`)
})(t)
code, _, body, _ := httpmock.DoRequest(t,
http.MethodPost,
s.URL()+"/create",
map[string]string{"Authorization": "Bearer token"},
[]byte(`{"foo":"bar"}`),
)
expectedCode := http.StatusCreated
expectedBody := []byte(`{"id":1,"foo":"bar"}`)
assert.Equal(t, expectedCode, code)
assert.Equal(t, expectedBody, body)
type Request ¶
type Request struct {
// Method is the expected HTTP Method of the given request.
Method string
// RequestURI is the expected HTTP Request URI of the given request.
// The uri does not need to be exactly same but satisfies the URIMatcher.
RequestURI string
// RequestHeader is a list of expected headers of the given request.
RequestHeader Header
// RequestBody is the expected body of the given request.
RequestBody []byte
// StatusCode is the response code when the request is handled.
StatusCode int
// ResponseHeader is a list of response headers to be sent to client when the request is handled.
ResponseHeader Header
// Do handles the request and returns a result or an error.
Do RequestHandler
// The number of times to return the return arguments when setting
// expectations. 0 means to always return the value.
Repeatability int
// contains filtered or unexported fields
}
Request is an expectation.
func (*Request) After ¶
After sets how long to block until the call returns
Server.Expect(http.MethodGet, "/path").
After(time.Second).
Return("hello world!")
func (*Request) Handler ¶ added in v0.2.0
func (r *Request) Handler(handler RequestHandler) *Request
Handler sets the handler to handle a given request.
Server.Expect(http.MethodGet, "/path").
Handler(func(_ *http.Request) ([]byte, error) {
return []byte("hello world!"), nil
})
func (*Request) Once ¶
Once indicates that the mock should only return the value once.
Server.Expect(http.MethodGet, "/path").
Return("hello world!").
Once()
func (*Request) Return ¶
Return sets the result to return to client.
Server.Expect(http.MethodGet, "/path").
Return("hello world!")
func (*Request) ReturnCode ¶
ReturnCode sets the response code.
Server.Expect(http.MethodGet, "/path"). ReturnCode(http.StatusBadRequest)
func (*Request) ReturnFile ¶ added in v0.1.1
ReturnFile reads the file using ioutil.ReadFile and uses it as the result to return to client.
Server.Expect(http.MethodGet, "/path").
ReturnFile("resources/fixtures/response.txt")
nolint:unparam
func (*Request) ReturnHeader ¶
ReturnHeader sets a response header.
Server.Expect(http.MethodGet, "/path").
ReturnHeader("foo", "bar")
func (*Request) ReturnHeaders ¶
ReturnHeaders sets a list of response headers.
Server.Expect(http.MethodGet, "/path").
ReturnHeaders(httpmock.Header{"foo": "bar"})
func (*Request) ReturnJSON ¶
ReturnJSON marshals the object using json.Marshal and uses it as the result to return to client.
Server.Expect(http.MethodGet, "/path").
ReturnJSON(map[string]string{"foo": "bar"})
func (*Request) Returnf ¶ added in v0.1.3
Returnf formats according to a format specifier and use it as the result to return to client.
Server.Expect(http.MethodGet, "/path").
Returnf("hello %s", "john")
func (*Request) Times ¶
Times indicates that the mock should only return the indicated number of times.
Server.Expect(http.MethodGet, "/path").
Return("hello world!").
Times(5)
func (*Request) Twice ¶
Twice indicates that the mock should only return the value twice.
Server.Expect(http.MethodGet, "/path").
Return("hello world!").
Twice()
func (*Request) WaitUntil ¶
WaitUntil sets the channel that will block the mock's return until its closed or a message is received.
Server.Expect(http.MethodGet, "/path").
WaitUntil(time.After(time.Second)).
Return("hello world!")
func (*Request) WithBody ¶
WithBody sets the expected body of the given request.
Server.Expect(http.MethodGet, "/path").
WithBody("hello world!")
func (*Request) WithBodyJSON ¶ added in v0.1.2
WithBodyJSON marshals the object and use it as the expected body of the given request.
Server.Expect(http.MethodGet, "/path").
WithBodyJSON(map[string]string{"foo": "bar"})
nolint:unparam
func (*Request) WithBodyf ¶ added in v0.1.3
WithBodyf formats according to a format specifier and use it as the expected body of the given request.
Server.Expect(http.MethodGet, "/path").
WithBodyf("hello %s", "john)
func (*Request) WithHeader ¶
WithHeader sets an expected header of the given request.
Server.Expect(http.MethodGet, "/path").
WithHeader("foo": "bar")
func (*Request) WithHeaders ¶
WithHeaders sets a list of expected headers of the given request.
Server.Expect(http.MethodGet, "/path").
WithHeaders(httpmock.Header{"foo": "bar"})
type RequestHandler ¶
RequestHandler handles the request and returns a result or an error.
type RequestMatcher ¶
type RequestMatcher func(t TestingT, r *http.Request, expectations []*Request) (*Request, []*Request, error)
RequestMatcher matches a request with one of the expectations.
func DefaultRequestMatcher ¶
func DefaultRequestMatcher() RequestMatcher
DefaultRequestMatcher instantiates a SequentialRequestMatcher with ExactURIMatcher, ExactHeaderMatcher and ExactBodyMatcher.
func SequentialRequestMatcher ¶
func SequentialRequestMatcher(options ...RequestMatcherOption) RequestMatcher
SequentialRequestMatcher matches a request in sequence.
type RequestMatcherConfig ¶
type RequestMatcherConfig struct {
// contains filtered or unexported fields
}
RequestMatcherConfig is config of RequestMatcher.
func ConfigureRequestMatcher ¶
func ConfigureRequestMatcher(options ...RequestMatcherOption) *RequestMatcherConfig
ConfigureRequestMatcher configures ConfigureRequestMatcher with RequestMatcherOption.
type RequestMatcherError ¶
type RequestMatcherError struct {
// contains filtered or unexported fields
}
RequestMatcherError represents an error that occurs while matching a request.
func MatcherError ¶
func MatcherError(expected *Request, request *http.Request, message string, args ...interface{}) *RequestMatcherError
MatcherError instantiates a new RequestMatcherError.
func (RequestMatcherError) Error ¶
func (e RequestMatcherError) Error() string
Error satisfies the error interface.
type RequestMatcherOption ¶
type RequestMatcherOption func(c *RequestMatcherConfig)
RequestMatcherOption configures RequestMatcherConfig.
func WithBodyMatcher ¶ added in v0.2.1
func WithBodyMatcher(m BodyMatcher) RequestMatcherOption
WithBodyMatcher sets BodyMatcher.
func WithExactBodyMatcher ¶
func WithExactBodyMatcher() RequestMatcherOption
WithExactBodyMatcher sets BodyMatcher to ExactBodyMatcher.
func WithExactHeaderMatcher ¶
func WithExactHeaderMatcher() RequestMatcherOption
WithExactHeaderMatcher sets HeaderMatcher to ExactHeaderMatcher.
func WithExactURIMatcher ¶
func WithExactURIMatcher() RequestMatcherOption
WithExactURIMatcher sets URIMatcher to ExactURIMatcher.
func WithHeaderMatcher ¶ added in v0.2.1
func WithHeaderMatcher(m HeaderMatcher) RequestMatcherOption
WithHeaderMatcher sets HeaderMatcher.
func WithURIMatcher ¶ added in v0.2.1
func WithURIMatcher(m URIMatcher) RequestMatcherOption
WithURIMatcher sets URIMatcher.
type Server ¶
type Server struct {
// Represents the requests that are expected of a server.
ExpectedRequests []*Request
// Holds the requested that were made to this server.
Requests []Request
// contains filtered or unexported fields
}
Server is a Mock server.
func MockServer ¶
MockServer creates a mocked server.
func (*Server) ExpectDelete ¶ added in v0.3.0
ExpectDelete adds a new expected http.MethodDelete request.
Server.ExpectDelete("/path")
func (*Server) ExpectGet ¶ added in v0.3.0
ExpectGet adds a new expected http.MethodGet request.
Server.ExpectGet("/path")
func (*Server) ExpectHead ¶ added in v0.3.0
ExpectHead adds a new expected http.MethodHead request.
Server.ExpectHead("/path")
func (*Server) ExpectPatch ¶ added in v0.3.0
ExpectPatch adds a new expected http.MethodPatch request.
Server.ExpectPatch("/path")
func (*Server) ExpectPost ¶ added in v0.3.0
ExpectPost adds a new expected http.MethodPost request.
Server.ExpectPost("/path")
func (*Server) ExpectPut ¶ added in v0.3.0
ExpectPut adds a new expected http.MethodPut request.
Server.ExpectPut("/path")
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 ¶ added in v0.4.4
func (s *Server) ResetExpectations()
ResetExpectations resets all the expectations.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves the request.
func (*Server) WithDefaultResponseHeaders ¶
WithDefaultResponseHeaders sets the default response headers of the server.
func (*Server) WithRequestMatcher ¶
func (s *Server) WithRequestMatcher(matcher RequestMatcher) *Server
WithRequestMatcher sets the RequestMatcher of the server.
type TestingT ¶
type TestingT interface {
Errorf(format string, args ...interface{})
FailNow()
Cleanup(func())
}
TestingT is an interface wrapper around *testing.T.
type URIMatcher ¶
URIMatcher matches an URI with an expectation.
func ExactURIMatcher ¶
func ExactURIMatcher() URIMatcher
ExactURIMatcher matches an url by checking if it is equal to the expectation.
