-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathshutdown_test.go
More file actions
67 lines (54 loc) · 1.23 KB
/
Copy pathshutdown_test.go
File metadata and controls
67 lines (54 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
)
func TestGracefulShutdown_WaitsForInFlightRequests(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(TrackInFlightRequests())
// Simulate slow handler
r.GET("/slow", func(c *gin.Context) {
time.Sleep(200 * time.Millisecond)
c.Status(http.StatusOK)
})
srv := &http.Server{
Handler: r,
}
// Start test server
ln := httptest.NewUnstartedServer(r)
ln.Config = srv
ln.Start()
defer ln.Close()
// Make request in background
done := make(chan struct{})
go func() {
resp, err := http.Get(ln.URL + "/slow")
if err != nil {
t.Errorf("request failed: %v", err)
return
}
resp.Body.Close()
close(done)
}()
// Give request time to start
time.Sleep(50 * time.Millisecond)
// Shutdown server
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
start := time.Now()
if err := srv.Shutdown(ctx); err != nil {
t.Fatalf("shutdown failed: %v", err)
}
WaitForInFlightRequests()
elapsed := time.Since(start)
<-done
// Assert shutdown waited for request
if elapsed < 200*time.Millisecond {
t.Fatalf("shutdown did not wait for in-flight request")
}
}