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)
- type Header
- type Mocker
- type Server
- func (s *Server) Close()
- func (s *Server) Expect(method string, requestURI interface{}) *request.Request
- func (s *Server) ExpectDelete(requestURI interface{}) *request.Request
- func (s *Server) ExpectGet(requestURI interface{}) *request.Request
- func (s *Server) ExpectHead(requestURI interface{}) *request.Request
- func (s *Server) ExpectPatch(requestURI interface{}) *request.Request
- func (s *Server) ExpectPost(requestURI interface{}) *request.Request
- func (s *Server) ExpectPut(requestURI interface{}) *request.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) WithDefaultRequestOptions(opt func(r *request.Request)) *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 ¶ added in v0.4.5
AssertHeaderContains asserts that the HTTP headers contains some specifics headers.
func DoRequest ¶ added in v0.3.0
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 ¶ added in v0.3.0
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 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 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 {
// Holds the requested that were made to this server.
Requests []request.Request
// 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"
"github.com/nhatthm/httpmock"
plannerMock "github.com/nhatthm/httpmock/mock/planner"
"github.com/nhatthm/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"
"github.com/nhatthm/httpmock"
"github.com/nhatthm/httpmock/matcher"
"github.com/nhatthm/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"
"github.com/nhatthm/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"
"github.com/nhatthm/httpmock"
"github.com/nhatthm/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 ¶
Expect adds a new expected request.
Server.Expect(httpmock.MethodGet, "/path").
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) WithDefaultRequestOptions ¶ added in v0.7.0
WithDefaultRequestOptions sets the default request options of the server.
func (*Server) WithDefaultResponseHeaders ¶
WithDefaultResponseHeaders sets the default response headers of the server.
func (*Server) WithPlanner ¶ added in v0.7.0
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. |
|
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. |
