Documentation
¶
Overview ¶
Package apitest provides helpers for end-to-end HTTP tests that drive a real application handler through an httptest.Server. It removes the boilerplate of building requests, sending JSON, asserting status codes and decoding bodies.
srv := apitest.New(t, handler)
created := srv.PostJSON("/widgets", `{"name":"gadget"}`).
ExpectStatus(http.StatusCreated).JSON()
id := created["id"].(string)
srv.Get("/widgets/"+id, apitest.WithBearer(token)).ExpectStatus(http.StatusOK)
It depends only on the standard library, so it is safe to use from any module's tests without pulling heavy dependencies.
Index ¶
- type Option
- type Response
- type Server
- func (s *Server) Delete(path string, opts ...Option) *Response
- func (s *Server) Do(method, path, body string, opts ...Option) *Response
- func (s *Server) Get(path string, opts ...Option) *Response
- func (s *Server) PostJSON(path, body string, opts ...Option) *Response
- func (s *Server) PutJSON(path, body string, opts ...Option) *Response
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Option ¶
Option customizes an outbound request, e.g. to set headers.
func WithBearer ¶
WithBearer sets an Authorization: Bearer <token> header.
type Response ¶
type Response struct {
StatusCode int
Header http.Header
Body []byte
// contains filtered or unexported fields
}
Response holds a completed HTTP response with its body buffered for repeated assertions and decoding.
func (*Response) ExpectStatus ¶
ExpectStatus fails the test unless the response status equals want. It returns the receiver for chaining.
type Server ¶
Server wraps an httptest.Server with JSON request and assertion helpers.
func (*Server) Do ¶
Do sends method to path with an optional raw string body (JSON when non-empty) and returns the buffered response. It fails the test on transport errors.