Assertions
Custom assertions
Write your own checks with Assert, and package them for reuse.
Assert takes a function that receives the response and the request, and returns an error when the check fails:
apitest.Handler(handler).
Get("/user/1234").
Expect(t).
Assert(func(res *http.Response, req *http.Request) error {
if res.Header.Get("X-Rate-Limit") == "" {
return errors.New("expected a rate limit header")
}
return nil
}).
End()type Assert func(*http.Response, *http.Request) error- The function receives copies of the response and request, so it can read the body without affecting other checks.
Assertcan be called any number of times. The functions run after the built-in checks, in the order they were added.- A returned error is reported as a test failure with
t.Errorf, and the remaining checks still run.
Reusable assertions
Assertions are plain functions, so a function that returns one can be shared across tests and packages:
// hasCacheControl asserts on the Cache-Control header of the response.
func hasCacheControl(want string) apitest.Assert {
return func(res *http.Response, _ *http.Request) error {
if got := res.Header.Get("Cache-Control"); got != want {
return fmt.Errorf("Cache-Control: got %q, want %q", got, want)
}
return nil
}
}
func TestCaching(t *testing.T) {
apitest.Handler(cachedHandler).
Get("/static/app.js").
Expect(t).
Status(http.StatusOK).
Assert(hasCacheControl("public, max-age=31536000")).
End()
}
The JSONPath and CSS selector modules are built this way.
Ready-made assertions
apitest.IsSuccess, apitest.IsClientError and apitest.IsServerError assert that the status code is in a range. See status.