Documentation ¶
Overview ¶
Package httpmock provides functionalities for mocking http server.
Index ¶
- Constants
- Variables
- func AssertHeaderContains(t test.T, headers, contains Header) bool
- func DoRequest(tb testing.TB, method, requestURI string, headers Header, body []byte) (int, map[string]string, []byte, time.Duration)
- func DoRequestWithTimeout(tb testing.TB, method, requestURI string, headers Header, body []byte, ...) (int, map[string]string, []byte, time.Duration)
- func FailResponse(w http.ResponseWriter, format string, args ...any) error
- type Expectation
- type ExpectationHandler
- type Header
- type Mocker
- type Server
- func (s *Server) Close()
- func (s *Server) Expect(method string, requestURI any) Expectation
- func (s *Server) ExpectDelete(requestURI any) Expectation
- func (s *Server) ExpectGet(requestURI any) Expectation
- func (s *Server) ExpectHead(requestURI any) Expectation
- func (s *Server) ExpectPatch(requestURI any) Expectation
- func (s *Server) ExpectPost(requestURI any) Expectation
- func (s *Server) ExpectPut(requestURI any) Expectation
- 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) WithDefaultRequestOptions(opt func(e Expectation)) *Server
- func (s *Server) WithDefaultResponseHeaders(headers map[string]string) *Server
- func (s *Server) WithPlanner(p planner.Planner) *Server
- func (s *Server) WithTest(t test.T) *Server
Examples ¶
Constants ¶
const ( MethodGet = http.MethodGet MethodHead = http.MethodHead MethodPost = http.MethodPost MethodPut = http.MethodPut MethodPatch = http.MethodPatch MethodDelete = http.MethodDelete MethodConnect = http.MethodConnect MethodOptions = http.MethodOptions MethodTrace = http.MethodTrace StatusContinue = http.StatusContinue StatusSwitchingProtocols = http.StatusSwitchingProtocols StatusProcessing = http.StatusProcessing StatusEarlyHints = http.StatusEarlyHints StatusOK = http.StatusOK StatusCreated = http.StatusCreated StatusAccepted = http.StatusAccepted StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo StatusNoContent = http.StatusNoContent StatusResetContent = http.StatusResetContent StatusPartialContent = http.StatusPartialContent StatusMultiStatus = http.StatusMultiStatus StatusAlreadyReported = http.StatusAlreadyReported StatusIMUsed = http.StatusIMUsed StatusMultipleChoices = http.StatusMultipleChoices StatusMovedPermanently = http.StatusMovedPermanently StatusFound = http.StatusFound StatusSeeOther = http.StatusSeeOther StatusNotModified = http.StatusNotModified StatusUseProxy = http.StatusUseProxy StatusTemporaryRedirect = http.StatusTemporaryRedirect StatusPermanentRedirect = http.StatusPermanentRedirect StatusBadRequest = http.StatusBadRequest StatusPaymentRequired = http.StatusPaymentRequired StatusForbidden = http.StatusForbidden StatusNotFound = http.StatusNotFound StatusMethodNotAllowed = http.StatusMethodNotAllowed StatusNotAcceptable = http.StatusNotAcceptable StatusProxyAuthRequired = http.StatusProxyAuthRequired StatusRequestTimeout = http.StatusRequestTimeout StatusConflict = http.StatusConflict StatusGone = http.StatusGone StatusLengthRequired = http.StatusLengthRequired StatusPreconditionFailed = http.StatusPreconditionFailed StatusRequestEntityTooLarge = http.StatusRequestEntityTooLarge StatusRequestURITooLong = http.StatusRequestURITooLong StatusUnsupportedMediaType = http.StatusUnsupportedMediaType StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable StatusExpectationFailed = http.StatusExpectationFailed StatusTeapot = http.StatusTeapot StatusMisdirectedRequest = http.StatusMisdirectedRequest StatusUnprocessableEntity = http.StatusUnprocessableEntity StatusLocked = http.StatusLocked StatusFailedDependency = http.StatusFailedDependency StatusTooEarly = http.StatusTooEarly StatusUpgradeRequired = http.StatusUpgradeRequired StatusPreconditionRequired = http.StatusPreconditionRequired StatusTooManyRequests = http.StatusTooManyRequests StatusRequestHeaderFieldsTooLarge = http.StatusRequestHeaderFieldsTooLarge StatusInternalServerError = http.StatusInternalServerError StatusNotImplemented = http.StatusNotImplemented StatusBadGateway = http.StatusBadGateway StatusGatewayTimeout = http.StatusGatewayTimeout StatusHTTPVersionNotSupported = http.StatusHTTPVersionNotSupported StatusVariantAlsoNegotiates = http.StatusVariantAlsoNegotiates StatusInsufficientStorage = http.StatusInsufficientStorage StatusLoopDetected = http.StatusLoopDetected StatusNotExtended = http.StatusNotExtended StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired )
nolint: revive,nolintlint
Variables ¶
var Exact = matcher.Exact
Exact matches two objects by their exact values.
var Exactf = matcher.Exactf
Exactf matches two strings by the formatted expectation.
var IsEmpty = matcher.IsEmpty
IsEmpty checks whether the value is empty.
var IsNotEmpty = matcher.IsNotEmpty
IsNotEmpty checks whether the value is not empty.
var JSON = matcher.JSON
JSON matches two json strings with <ignore-diff> support.
var Len = matcher.Len
Len matches by the length of the value.
var Match = matcher.Match
Match returns a matcher according to its type.
var Regex = matcher.Regex
Regex matches two strings by using regex.
var RegexPattern = matcher.RegexPattern
RegexPattern matches two strings by using regex.
Functions ¶
func AssertHeaderContains ¶
AssertHeaderContains asserts that the HTTP headers contains some specifics headers.
func DoRequest ¶
func DoRequest( tb testing.TB, 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 ¶
func DoRequestWithTimeout( tb testing.TB, method, requestURI string, headers Header, body []byte, timeout time.Duration, ) (int, map[string]string, []byte, time.Duration)
DoRequestWithTimeout sends a simple HTTP requestExpectation 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, "/", map[string]string{}, nil, 0)
func FailResponse ¶ added in v0.10.0
func FailResponse(w http.ResponseWriter, format string, args ...any) error
FailResponse responds a failure to client.
Types ¶
type Expectation ¶ added in v0.10.0
type Expectation interface { // WithHeader sets an expected header of the given request. // // Server.Expect(httpmock.MethodGet, "/path"). // WithHeader("foo", "bar") WithHeader(header string, value any) Expectation // WithHeaders sets a list of expected headers of the given request. // // Server.Expect(httpmock.MethodGet, "/path"). // WithHeaders(map[string]any{"foo": "bar"}) WithHeaders(headers map[string]any) Expectation // WithBody sets the expected body of the given request. It could be []byte, string, fmt.Stringer, or a Matcher. // // Server.Expect(httpmock.MethodGet, "/path"). // WithBody("hello world!") WithBody(body any) Expectation // WithBodyf formats according to a format specifier and use it as the expected body of the given request. // // Server.Expect(httpmock.MethodGet, "/path"). // WithBodyf("hello %s", "john) WithBodyf(format string, args ...any) Expectation // WithBodyJSON marshals the object and use it as the expected body of the given request. // // Server.Expect(httpmock.MethodGet, "/path"). // WithBodyJSON(map[string]string{"foo": "bar"}) // WithBodyJSON(v any) Expectation // ReturnCode sets the response code. // // Server.Expect(httpmock.MethodGet, "/path"). // ReturnCode(httpmock.StatusBadRequest) ReturnCode(code int) Expectation // ReturnHeader sets a response header. // // Server.Expect(httpmock.MethodGet, "/path"). // ReturnHeader("foo", "bar") ReturnHeader(header, value string) Expectation // ReturnHeaders sets a list of response headers. // // Server.Expect(httpmock.MethodGet, "/path"). // ReturnHeaders(httpmock.Header{"foo": "bar"}) ReturnHeaders(headers Header) Expectation // Return sets the result to return to client. // // Server.Expect(httpmock.MethodGet, "/path"). // Return("hello world!") Return(v any) Expectation // Returnf formats according to a format specifier and use it as the result to return to client. // // Server.Expect(httpmock.MethodGet, "/path"). // Returnf("hello %s", "john") Returnf(format string, args ...any) Expectation // ReturnJSON marshals the object using json.Marshal and uses it as the result to return to client. // // Server.Expect(httpmock.MethodGet, "/path"). // ReturnJSON(map[string]string{"foo": "bar"}) ReturnJSON(body any) Expectation // ReturnFile reads the file using ioutil.ReadFile and uses it as the result to return to client. // // Server.Expect(httpmock.MethodGet, "/path"). // ReturnFile("resources/fixtures/response.txt") ReturnFile(filePath string) Expectation // Run sets the handler to handle a given request. // // Server.Expect(httpmock.MethodGet, "/path"). // Run(func(*http.Request) ([]byte, error) { // return []byte("hello world!"), nil // }) Run(handle func(r *http.Request) ([]byte, error)) Expectation // Once indicates that the mock should only return the value once. // // Server.Expect(http.MethodGet, "/path"). // Return("hello world!"). // Once() Once() Expectation // Twice indicates that the mock should only return the value twice. // // Server.Expect(http.MethodGet, "/path"). // Return("hello world!"). // Twice() Twice() Expectation // 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() UnlimitedTimes() Expectation // Times indicates that the mock should only return the indicated number of times. // // Server.Expect(http.MethodGet, "/path"). // Return("hello world!"). // Times(5) Times(i uint) Expectation // WaitUntil sets the channel that will block the mocked return until its closed // or a message is received. // // Server.Expect(http.MethodGet, "/path"). // WaitUntil(time.After(time.Second)). // Return("hello world!") WaitUntil(w <-chan time.Time) Expectation // After sets how long to block until the call returns. // // Server.Expect(http.MethodGet, "/path"). // After(time.Second). // Return("hello world!") After(d time.Duration) Expectation }
Expectation sets the expectations for a http request.
nolint: interfacebloat
type ExpectationHandler ¶ added in v0.11.0
type ExpectationHandler interface {
Handle(http.ResponseWriter, *http.Request, map[string]string) error
}
ExpectationHandler handles 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(httpmock.StatusCreated). Return(`{"id":1,"foo":"bar"}`) })(t) code, _, body, _ := httpmock.DoRequest(t, httpmock.MethodPost, s.URL()+"/create", map[string]string{"Authorization": "Bearer token"}, []byte(`{"foo":"bar"}`), ) expectedCode := httpmock.StatusCreated expectedBody := []byte(`{"id":1,"foo":"bar"}`) assert.Equal(t, expectedCode, code) assert.Equal(t, expectedBody, body)
type Server ¶
type Server struct { // Requests are the matched expectations. Requests []planner.Expectation // contains filtered or unexported fields }
Server is a Mock server.
func MockServer ¶
MockServer creates a mocked server.
Example (AlwaysFailPlanner) ¶
package main import ( "context" "errors" "fmt" "io" "net/http" "github.com/stretchr/testify/mock" "go.nhat.io/httpmock" plannermock "go.nhat.io/httpmock/mock/planner" "go.nhat.io/httpmock/must" ) func main() { srv := httpmock.MockServer(func(s *httpmock.Server) { p := &plannermock.Planner{} p.On("IsEmpty").Return(false) p.On("Expect", mock.Anything) p.On("Plan", mock.Anything). Return(nil, errors.New("always fail")) s.WithPlanner(p) s.ExpectGet("/hi"). Run(func(r *http.Request) ([]byte, error) { panic(`this never happens`) }) }) requestURI := srv.URL() + "/hi" req, err := http.NewRequestWithContext(context.Background(), httpmock.MethodGet, requestURI, nil) must.NotFail(err) resp, err := http.DefaultClient.Do(req) must.NotFail(err) defer resp.Body.Close() // nolint: errcheck output, err := io.ReadAll(resp.Body) must.NotFail(err) fmt.Println(resp.Status) fmt.Println(string(output)) }
Output: 500 Internal Server Error always fail
Example (CustomHandle) ¶
package main import ( "context" "fmt" "io" "net/http" "go.nhat.io/httpmock" "go.nhat.io/httpmock/matcher" "go.nhat.io/httpmock/must" ) func main() { srv := httpmock.MockServer(func(s *httpmock.Server) { s.ExpectGet(matcher.RegexPattern(`^/uri.*`)). WithHeader("Authorization", "Bearer token"). Run(func(r *http.Request) ([]byte, error) { return []byte(r.RequestURI), nil }) }) requestURI := srv.URL() + "/uri?a=1&b=2" req, err := http.NewRequestWithContext(context.Background(), httpmock.MethodGet, requestURI, nil) must.NotFail(err) req.Header.Set("Authorization", "Bearer token") resp, err := http.DefaultClient.Do(req) must.NotFail(err) defer resp.Body.Close() // nolint: errcheck output, err := io.ReadAll(resp.Body) must.NotFail(err) fmt.Println(resp.Status) fmt.Println(string(output)) }
Output: 200 OK /uri?a=1&b=2
Example (ExpectationsWereNotMet) ¶
package main import ( "fmt" "go.nhat.io/httpmock" ) func main() { srv := httpmock.MockServer(func(s *httpmock.Server) { s.ExpectGet("/hi"). Return(`hello world`) s.ExpectGet("/pay").Twice(). Return(`paid`) }) err := srv.ExpectationsWereMet() fmt.Println(err.Error()) }
Output: there are remaining expectations that were not met: - GET /hi - GET /pay (called: 0 time(s), remaining: 2 time(s))
Example (Simple) ¶
package main import ( "context" "fmt" "io" "net/http" "go.nhat.io/httpmock" "go.nhat.io/httpmock/must" ) func main() { srv := httpmock.MockServer(func(s *httpmock.Server) { s.ExpectGet("/hi"). Return(`hello world`) }) requestURI := srv.URL() + "/hi" req, err := http.NewRequestWithContext(context.Background(), httpmock.MethodGet, requestURI, nil) must.NotFail(err) resp, err := http.DefaultClient.Do(req) must.NotFail(err) defer resp.Body.Close() // nolint: errcheck output, err := io.ReadAll(resp.Body) must.NotFail(err) fmt.Println(resp.Status) fmt.Println(string(output)) }
Output: 200 OK hello world
func (*Server) Expect ¶
func (s *Server) Expect(method string, requestURI any) Expectation
Expect adds a new expected request.
Server.Expect(httpmock.MethodGet, "/path").
func (*Server) ExpectDelete ¶
func (s *Server) ExpectDelete(requestURI any) Expectation
ExpectDelete adds a new expected http.MethodDelete request.
Server.ExpectDelete("/path")
func (*Server) ExpectGet ¶
func (s *Server) ExpectGet(requestURI any) Expectation
ExpectGet adds a new expected http.MethodGet request.
Server.ExpectGet("/path")
func (*Server) ExpectHead ¶
func (s *Server) ExpectHead(requestURI any) Expectation
ExpectHead adds a new expected http.MethodHead request.
Server.ExpectHead("/path")
func (*Server) ExpectPatch ¶
func (s *Server) ExpectPatch(requestURI any) Expectation
ExpectPatch adds a new expected http.MethodPatch request.
Server.ExpectPatch("/path")
func (*Server) ExpectPost ¶
func (s *Server) ExpectPost(requestURI any) Expectation
ExpectPost adds a new expected http.MethodPost request.
Server.ExpectPost("/path")
func (*Server) ExpectPut ¶
func (s *Server) ExpectPut(requestURI any) Expectation
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 ¶
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) WithDefaultRequestOptions ¶
func (s *Server) WithDefaultRequestOptions(opt func(e Expectation)) *Server
WithDefaultRequestOptions sets the default request options of the server.
func (*Server) WithDefaultResponseHeaders ¶
WithDefaultResponseHeaders sets the default response headers of the server.
func (*Server) WithPlanner ¶
WithPlanner sets the planner.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package format formats the requests.
|
Package format formats the requests. |
Package matcher provides functionalities for matching header and body.
|
Package matcher provides functionalities for matching header and body. |
mock
|
|
http
Package http provides functionalities for mocking net/http components.
|
Package http provides functionalities for mocking net/http components. |
httpmock
Package httpmock provides functionalities for mocking the httpmock components.
|
Package httpmock provides functionalities for mocking the httpmock components. |
planner
Package planner provides mock for planner.
|
Package planner provides mock for planner. |
Package must panic on error.
|
Package must panic on error. |
Package planner provides functionalities for deciding what expectation matches the given request.
|
Package planner provides functionalities for deciding what expectation matches the given request. |
Package request provides all the expectations for a HTTP request.
|
Package request provides all the expectations for a HTTP request. |
Package test provides functionalities for testing the project.
|
Package test provides functionalities for testing the project. |
Package value provides functionalities to convert a generic value to string.
|
Package value provides functionalities to convert a generic value to string. |