MCPcopy
hub / github.com/grafana/dskit / TestTimeoutMiddleware

Function TestTimeoutMiddleware

middleware/http_timeout_test.go:18–62  ·  view source on GitHub ↗

TestTimeoutMiddleware tests the following behavior of the timeout middleware: - server write timeout is disabled - server returns 503 Service Unavailable with the proivded message - the context is cancelled

(t *testing.T)

Source from the content-addressed store, hash-verified

16// - server returns 503 Service Unavailable with the proivded message
17// - the context is cancelled
18func TestTimeoutMiddleware(t *testing.T) {
19 const (
20 serverWriteTimeout = time.Second
21 httpMiddlewareTimeout = 3 * time.Second
22 httpMiddlewareMessage = "foo"
23 )
24
25 timeoutMiddleware := NewTimeoutMiddleware(httpMiddlewareTimeout, httpMiddlewareMessage, log.NewNopLogger())
26
27 listener, err := net.Listen("tcp", "localhost:0")
28 require.NoError(t, err)
29
30 httpServer := &http.Server{
31 WriteTimeout: serverWriteTimeout,
32 Handler: Merge(timeoutMiddleware).Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
33 // block until the context is done. this is cancelled by the timeout handler
34 <-r.Context().Done()
35
36 w.WriteHeader(204)
37
38 // the context should be in error b/c the timeouthandler cancelled it
39 require.Error(t, r.Context().Err())
40 })),
41 }
42
43 go func() {
44 require.NoError(t, httpServer.Serve(listener))
45 }()
46
47 start := time.Now()
48 req, err := http.NewRequest("GET", "http://"+listener.Addr().String(), nil)
49 require.NoError(t, err)
50
51 resp, err := http.DefaultClient.Do(req)
52 require.NoError(t, err)
53
54 body, err := io.ReadAll(resp.Body)
55 require.NoError(t, err)
56 require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
57 require.Equal(t, httpMiddlewareMessage, string(body))
58 defer resp.Body.Close()
59
60 // confirm that we waited at least the middleware timeout (and not the server write timeout)
61 require.GreaterOrEqual(t, time.Since(start), httpMiddlewareTimeout)
62}

Callers

nothing calls this directly

Calls 12

NewTimeoutMiddlewareFunction · 0.85
MergeFunction · 0.85
WrapMethod · 0.65
DoneMethod · 0.65
StringMethod · 0.65
CloseMethod · 0.65
ContextMethod · 0.45
WriteHeaderMethod · 0.45
ErrorMethod · 0.45
ErrMethod · 0.45
DoMethod · 0.45
EqualMethod · 0.45

Tested by

no test coverage detected