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. It depends only on the standard library, so it is safe to use from any module's tests without pulling heavy dependencies. Every helper takes the *testing.T given to New and fails the test directly (t.Fatalf) on a transport error or unmet expectation.
Usage ¶
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)
New starts an httptest.Server for the handler and registers its shutdown with t.Cleanup. The request helpers (Get, Delete, PostJSON, PutJSON, and the underlying Do) return a *Response with the status, headers, and a buffered body for repeated assertions. ExpectStatus asserts the status code and returns the receiver for chaining; Decode, JSON, and JSONArray unmarshal the body.
Options ¶
Request Options customize the outbound request:
- WithHeader(key, value): sets a request header.
- WithBearer(token): sets "Authorization: Bearer <token>".
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.