apitest
Requests

Context

Pass deadlines, cancellation and context values to the handler.

WithContext sets the request context. The handler receives it from r.Context(), so deadlines, cancellation and context values all reach it:

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
ctx = context.WithValue(ctx, ctxKey("tenant"), "acme")

apitest.Handler(handler).
	Get("/hello").
	WithContext(ctx).
	Expect(t).
	Status(http.StatusOK).
	End()

Common uses are:

  • Checking that a handler stops work when the client goes away, by cancelling the context.
  • Checking that a handler respects a deadline.
  • Injecting values that middleware would normally add, such as an authenticated user, when testing a handler without its middleware.

To check what a client sees when a handler is too slow, see handler timeouts.