Documentation ¶
Overview ¶
Package web helps testing web handlers. A simulator can be started with the handler to test. Then standard http requests can be sent and the returned http responses can be analyzed.
h := NewMyHandler() s := web.NewSimulator(h) req := s.CreateRequest(http.MethodGet, "http://localhost:8080/", nil) resp, err := s.Do(req) assert.NoError(err) assert.Equal(resp.StatusCode, http.StatusOK) body, err := web.BodyToString(resp) assert.NoError(err) assert.Equal(body, test.expected)
Some smaller functions help working with the requests and responses.
Index ¶
- func BodyToJSON(r *http.Response, obj any) error
- func BodyToString(r *http.Response) (string, error)
- func JSONToBody(obj any, r *http.Request) error
- func StringToBody(s string, r *http.Request)
- type Preprocessor
- type Simulator
- func (s *Simulator) CreateRequest(method, target string, body io.Reader) *http.Request
- func (s *Simulator) Do(r *http.Request) (*http.Response, error)
- func (s *Simulator) Get(target string) (*http.Response, error)
- func (s *Simulator) Post(target, contentType string, body io.Reader) (*http.Response, error)
- func (s *Simulator) PostJSON(target string, body any) (*http.Response, error)
- func (s *Simulator) PostText(target, body string) (*http.Response, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BodyToJSON ¶ added in v0.6.1
BodyToJSON reads the whole body and decodes the JSON content into the given object.
func BodyToString ¶ added in v0.6.1
BodyToString reads the whole body and simply interprets it as string.
func JSONToBody ¶ added in v0.6.1
JSONToBody sets the request body to the JSON representation of the given object.
func StringToBody ¶ added in v0.6.1
StringToBody sets the request body to a given string.
Types ¶
type Preprocessor ¶
Preprocessor will be executed before a request is passed to the handler.
type Simulator ¶
type Simulator struct {
// contains filtered or unexported fields
}
Simulator locally simulates HTTP requests to handler.
func NewFuncSimulator ¶
func NewFuncSimulator(f http.HandlerFunc, pps ...Preprocessor) *Simulator
NewFuncSimulator is a convenient variant of NewSimulator just for a http.HandlerFunc.
func NewSimulator ¶
func NewSimulator(h http.Handler, pps ...Preprocessor) *Simulator
NewSimulator creates a new local HTTP request simulator.
func (*Simulator) CreateRequest ¶ added in v0.6.3
CreateRequest creates a request for the simulator.
func (*Simulator) Do ¶
Do executes first all registered preprocessors and then lets the handler executes it. The build response is returned.