apitest

Handler timeouts

Test what clients see when a handler is too slow, and that handlers respect deadlines.

Server timeouts

Production servers usually cap how long a handler may run, with http.TimeoutHandler or the server's WriteTimeout. Wrap the handler in http.TimeoutHandler in the test to check the response clients get when a request runs too long:

func TestSlowEndpoint_TimesOut(t *testing.T) {
	handler := http.TimeoutHandler(slowHandler, 50*time.Millisecond, "request timed out")

	apitest.Handler(handler).
		Get("/reports/annual").
		Expect(t).
		Status(http.StatusServiceUnavailable).
		Body("request timed out").
		End()
}

TimeoutHandler responds 503 Service Unavailable with the message you give it, and cancels the request context, so a well behaved handler stops its work.

Deadlines from the client

To check that a handler honours a deadline set by its caller, pass a context with a deadline using WithContext.

Slow and failing dependencies

To check how a handler copes when the services it calls are slow or time out, use mock timeouts and delays.

On this page