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 CallbackMatch
- type ExactMatch
- type Header
- type HeaderMatcher
- type JSONMatch
- type Matcher
- type Mocker
- type RegexMatch
- type Request
- func (r *Request) After(d time.Duration) *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) UnlimitedTimes() *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) WithHandler(handler func(r *http.Request) ([]byte, error)) *Request
- func (r *Request) WithHeader(header string, value interface{}) *Request
- func (r *Request) WithHeaders(headers map[string]interface{}) *Request
- type RequestMatcher
- type RequestMatcherError
- type Server
- func (s *Server) Close()
- func (s *Server) Expect(method string, requestURI interface{}) *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
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 CallbackMatch ¶ added in v0.6.0
type CallbackMatch struct {
// contains filtered or unexported fields
}
CallbackMatch matches by calling a function.
func (*CallbackMatch) Expected ¶ added in v0.6.0
func (m *CallbackMatch) Expected() string
Expected returns the expectation.
func (*CallbackMatch) Match ¶ added in v0.6.0
func (m *CallbackMatch) Match(actual string) bool
Match determines if the actual is expected.
type ExactMatch ¶ added in v0.6.0
type ExactMatch struct {
// contains filtered or unexported fields
}
ExactMatch matches by exact value.
func Exact ¶ added in v0.6.0
func Exact(expected string) *ExactMatch
Exact matches two objects by their exact values.
func Exactf ¶ added in v0.6.2
func Exactf(format string, args ...interface{}) *ExactMatch
Exactf matches two objects by the formatted expectation.
func (*ExactMatch) Expected ¶ added in v0.6.0
func (m *ExactMatch) Expected() string
Expected returns the expectation.
func (*ExactMatch) Match ¶ added in v0.6.0
func (m *ExactMatch) Match(actual string) bool
Match determines if the actual is expected.
type JSONMatch ¶ added in v0.6.0
type JSONMatch struct {
// contains filtered or unexported fields
}
JSONMatch matches by json with <ignore-diff> support.
type Matcher ¶ added in v0.6.0
Matcher determines if the actual matches the expectation.
func ValueMatcher ¶ added in v0.6.0
func ValueMatcher(v interface{}) Matcher
ValueMatcher returns a matcher according to its type.
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 RegexMatch ¶ added in v0.6.0
type RegexMatch struct {
// contains filtered or unexported fields
}
RegexMatch matches by regex.
func Regex ¶ added in v0.6.0
func Regex(regexp *regexp.Regexp) *RegexMatch
Regex matches two objects by using regex.
func RegexPattern ¶ added in v0.6.0
func RegexPattern(pattern string) *RegexMatch
RegexPattern matches two objects by using regex.
func (*RegexMatch) Expected ¶ added in v0.6.0
func (m *RegexMatch) Expected() string
Expected returns the expectation.
func (*RegexMatch) Match ¶ added in v0.6.0
func (m *RegexMatch) Match(actual string) bool
Match determines if the actual is expected.
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 Matcher
// RequestHeader is a list of expected headers of the given request.
RequestHeader HeaderMatcher
// RequestBody is the expected body of the given request.
RequestBody Matcher
// 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
// 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) 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) UnlimitedTimes ¶ added in v0.5.2
UnlimitedTimes indicates that the mock should return the value at least once and there is no max limit in the number of return.
Server.Expect(http.MethodGet, "/path").
Return("hello world!").
UnlimitedTimes()
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. It could be []byte, string, fmt.Stringer, or a Matcher.
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) WithHandler ¶ added in v0.5.4
WithHandler sets the handler to handle a given request.
Server.Expect(http.MethodGet, "/path").
WithHandler(func(_ *http.Request) ([]byte, error) {
return []byte("hello world!"), nil
})
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(map[string]interface{}{"foo": "bar"})
type RequestMatcher ¶
RequestMatcher matches a request with one of the expectations.
func SequentialRequestMatcher ¶
func SequentialRequestMatcher() RequestMatcher
SequentialRequestMatcher matches a request in sequence.
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 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.
