apitest icon indicating copy to clipboard operation
apitest copied to clipboard

Implement TimeoutHandler

Open davidsonff opened this issue 1 year ago • 2 comments

Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. E.g. I'm always frustrated when ...

I'm having a problem testing the timeout feature of my request handlers

Describe the solution you'd like A clear and concise description of what you want to happen.

An ability to test the fact that a TimeoutHandler actually times out.

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

Tried to see if intercept functionality could help but doesn't appear to be able to wrap a handler with a timeouthandler

Additional context Add any other context or screenshots about the feature request here.

davidsonff avatar Jul 19 '24 19:07 davidsonff

Hey @davidsonff, thanks for the request. Just trying to understand what you would like to test on your side...

An example might help. Are you trying to force a timeout of a handler? Wondering if you could just wrap a handler in a custom middleware which sleeps, which could be incorporated into apitest, e.g.

func TestApiTest_ForcedTimeout(t *testing.T) {
	handler := http.NewServeMux()
	handler.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	wrappedHandler := timeoutSimulatorMiddleware(handler)

	timeoutHandler := http.TimeoutHandler(wrappedHandler, 1*time.Second, "timeout")

	request := httptest.NewRequest(http.MethodGet, "/test", nil)

	apitest.Handler(timeoutHandler).
		HttpRequest(request).
		Expect(t).
		Status(http.StatusServiceUnavailable).
		End()
}

func timeoutSimulatorMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Simulate a delay to trigger the timeout
		time.Sleep(2 * time.Second)
		next.ServeHTTP(w, r)
	})
}

Thanks.

steinfletcher avatar Sep 03 '24 09:09 steinfletcher

Hi! Thanks for responding. I am using the SL? https://pkg.go.dev/net/[email protected]#TimeoutHandler I could write a wrapper, I suppose, just seemed like a logical addition to the suite?

davidsonff avatar Sep 03 '24 13:09 davidsonff