-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathtimeout_test.go
More file actions
298 lines (256 loc) · 8.34 KB
/
timeout_test.go
File metadata and controls
298 lines (256 loc) · 8.34 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package timeout
import (
"context"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func emptySuccessResponse(c *gin.Context) {
time.Sleep(20 * time.Millisecond)
c.String(http.StatusOK, "")
}
func TestTimeout(t *testing.T) {
r := gin.New()
r.GET("/", New(
WithTimeout(5*time.Millisecond),
),
emptySuccessResponse,
)
w := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), "GET", "/", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusRequestTimeout, w.Code)
assert.Equal(t, http.StatusText(http.StatusRequestTimeout), w.Body.String())
}
func TestTimeoutWithUse(t *testing.T) {
r := gin.New()
r.Use(New(
WithTimeout(5 * time.Millisecond),
))
r.GET("/", emptySuccessResponse)
w := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), "GET", "/", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusRequestTimeout, w.Code)
assert.Equal(t, http.StatusText(http.StatusRequestTimeout), w.Body.String())
}
func TestWithoutTimeout(t *testing.T) {
r := gin.New()
r.GET("/", New(
WithTimeout(-1*time.Millisecond),
),
emptySuccessResponse,
)
w := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), "GET", "/", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusRequestTimeout, w.Code)
assert.Equal(t, http.StatusText(http.StatusRequestTimeout), w.Body.String())
}
func testResponse(c *gin.Context) {
c.String(http.StatusRequestTimeout, "test response")
}
func TestCustomResponse(t *testing.T) {
r := gin.New()
r.GET("/", New(
WithTimeout(5*time.Millisecond),
WithResponse(testResponse),
),
emptySuccessResponse,
)
w := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), "GET", "/", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusRequestTimeout, w.Code)
assert.Equal(t, "test response", w.Body.String())
}
func emptySuccessResponse2(c *gin.Context) {
time.Sleep(1 * time.Millisecond)
c.String(http.StatusOK, "")
}
func TestSuccess(t *testing.T) {
r := gin.New()
r.GET("/", New(
WithTimeout(1*time.Second),
WithResponse(testResponse),
),
emptySuccessResponse2,
)
w := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), "GET", "/", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "", w.Body.String())
}
func TestLargeResponse(t *testing.T) {
r := gin.New()
r.GET("/slow", New(
WithTimeout(50*time.Millisecond),
WithResponse(func(c *gin.Context) {
c.String(http.StatusRequestTimeout, `{"error": "timeout error"}`)
}),
),
func(c *gin.Context) {
// Sleep longer than the timeout to ensure the timeout path is always taken.
// Do NOT use context cancellation here because ctx.Done() fires at the same
// time as the timer, making the select nondeterministic.
time.Sleep(200 * time.Millisecond)
c.String(http.StatusBadRequest, `{"error": "handler error"}`)
},
)
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
w := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), "GET", "/slow", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusRequestTimeout, w.Code)
assert.Equal(t, `{"error": "timeout error"}`, w.Body.String())
}()
}
wg.Wait()
}
/*
Test to ensure no further middleware executes meaningful work after timeout.
Handlers that respect context cancellation will exit early when the timeout fires.
*/
func TestNoNextAfterTimeout(t *testing.T) {
r := gin.New()
called := false
r.Use(New(
WithTimeout(50*time.Millisecond),
),
func(c *gin.Context) {
// Use context-aware wait so the handler exits when timeout fires
select {
case <-time.After(100 * time.Millisecond):
case <-c.Request.Context().Done():
return
}
c.String(http.StatusOK, "should not reach")
},
)
r.Use(func(c *gin.Context) {
// Check context cancellation before doing work
if c.Request.Context().Err() != nil {
return
}
called = true
})
w := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), "GET", "/", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusRequestTimeout, w.Code)
assert.False(t, called, "next middleware should not run after context timeout")
}
/*
TestTimeoutPanic: verifies the behavior when a panic occurs inside a handler wrapped by the timeout middleware.
This test ensures that a panic in the handler is caught by CustomRecovery and returns a 500 status code
with the panic message.
*/
func TestTimeoutPanic(t *testing.T) {
r := gin.New()
// Use CustomRecovery to catch panics and return a custom error message.
r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
c.String(http.StatusInternalServerError, "panic caught: %v", recovered)
}))
// Register the timeout middleware; the handler will panic.
r.GET("/panic", New(
WithTimeout(100*time.Millisecond),
),
func(c *gin.Context) {
panic("timeout panic test")
},
)
w := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), "GET", "/panic", nil)
r.ServeHTTP(w, req)
// Verify the response status code and body.
assert.Equal(t, http.StatusInternalServerError, w.Code)
assert.Contains(t, w.Body.String(), "panic caught: timeout panic test")
}
func TestDataRace(t *testing.T) {
r := gin.New()
r.GET("/race", New(
WithTimeout(50*time.Millisecond),
), func(c *gin.Context) {
// Sleep longer than the timeout to ensure the timeout path is always taken.
// Do NOT use context cancellation here because ctx.Done() fires at the same
// time as the timer, making the select nondeterministic.
time.Sleep(200 * time.Millisecond)
c.String(http.StatusOK, "done")
})
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
w := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), "GET", "/race", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusRequestTimeout, w.Code)
}()
}
wg.Wait()
}
/*
TestWriteAfterTimeout: verifies that a timed-out handler's goroutine cannot
contaminate a subsequent request's response (issue #81).
Root cause on master: after timeout the middleware returned immediately,
causing gin to recycle *gin.Context via sync.Pool while the goroutine was
still running. The next request reused the same Context, c.reset() changed
c.Writer to &c.writermem pointing at the NEW recorder, and the old goroutine's
c.String() bypassed the timeout Writer's check — writing directly into
the new request's response.
The fix waits for the goroutine before returning, so pool.Put(c) only happens
after the goroutine is done.
*/
func TestWriteAfterTimeout(t *testing.T) {
r := gin.New()
r.GET("/slow", New(
WithTimeout(5*time.Millisecond),
), func(c *gin.Context) {
// Simulate a handler that writes AFTER the timeout has fired.
time.Sleep(30 * time.Millisecond)
c.String(http.StatusOK, `{"leaked":"data"}`)
})
r.GET("/fast", func(c *gin.Context) {
c.String(http.StatusOK, `{"clean":"response"}`)
})
for i := 0; i < 50; i++ {
// Request A — will time out; goroutine keeps running on master.
w1 := httptest.NewRecorder()
req1, _ := http.NewRequestWithContext(context.Background(), "GET", "/slow", nil)
r.ServeHTTP(w1, req1)
assert.Equal(t, http.StatusRequestTimeout, w1.Code)
// Request B — fast endpoint, likely reuses the same *gin.Context from pool.
// With the goroutine-wait fix, the goroutine is guaranteed done before
// ServeHTTP returns, so no sleep is needed.
w2 := httptest.NewRecorder()
req2, _ := http.NewRequestWithContext(context.Background(), "GET", "/fast", nil)
r.ServeHTTP(w2, req2)
// The fast endpoint must return exactly its own data — no leaked prefix.
assert.Equal(t, `{"clean":"response"}`, w2.Body.String(),
"iteration %d: response contaminated by timed-out request's goroutine", i)
}
}
func TestContextDeadlineSet(t *testing.T) {
r := gin.New()
var hasDeadline bool
r.GET("/deadline", New(
WithTimeout(1*time.Second),
), func(c *gin.Context) {
_, hasDeadline = c.Request.Context().Deadline()
})
w := httptest.NewRecorder()
req, _ := http.NewRequestWithContext(context.Background(), "GET", "/deadline", nil)
r.ServeHTTP(w, req)
assert.True(t, hasDeadline, "request context should have a deadline set by the middleware")
assert.Equal(t, http.StatusOK, w.Code)
}