forked from gofiber/fiber
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout_test.go
More file actions
321 lines (281 loc) · 9.7 KB
/
Copy pathtimeout_test.go
File metadata and controls
321 lines (281 loc) · 9.7 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package timeout
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gofiber/fiber/v3"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp"
)
var (
// Custom error that we treat like a timeout when returned by the handler.
errCustomTimeout = errors.New("custom timeout error")
// Some unrelated error that should NOT trigger a request timeout.
errUnrelated = errors.New("unmatched error")
)
// sleepWithContext simulates a task that takes `d` time, but returns `te` if the context is canceled.
func sleepWithContext(ctx context.Context, d time.Duration, te error) error {
timer := time.NewTimer(d)
defer timer.Stop() // Clean up the timer
select {
case <-ctx.Done():
return te
case <-timer.C:
return nil
}
}
// TestTimeout_Success tests a handler that completes within the allotted timeout.
func TestTimeout_Success(t *testing.T) {
t.Parallel()
app := fiber.New()
// Our middleware wraps a handler that sleeps for 10ms, well under the 50ms limit.
app.Get("/fast", New(func(c fiber.Ctx) error {
// Simulate some work
if err := sleepWithContext(c.Context(), 10*time.Millisecond, context.DeadlineExceeded); err != nil {
return err
}
return c.SendString("OK")
}, Config{Timeout: 50 * time.Millisecond}))
req := httptest.NewRequest(fiber.MethodGet, "/fast", http.NoBody)
resp, err := app.Test(req)
require.NoError(t, err, "app.Test(req) should not fail")
require.Equal(t, fiber.StatusOK, resp.StatusCode, "Expected 200 OK for fast requests")
}
// TestTimeout_Exceeded tests a handler that exceeds the provided timeout.
func TestTimeout_Exceeded(t *testing.T) {
t.Parallel()
app := fiber.New()
// This handler sleeps 200ms, exceeding the 100ms limit.
app.Get("/slow", New(func(c fiber.Ctx) error {
if err := sleepWithContext(c.Context(), 200*time.Millisecond, context.DeadlineExceeded); err != nil {
return err
}
return c.SendString("Should never get here")
}, Config{Timeout: 100 * time.Millisecond}))
req := httptest.NewRequest(fiber.MethodGet, "/slow", http.NoBody)
start := time.Now()
resp, err := app.Test(req)
elapsed := time.Since(start)
require.NoError(t, err, "app.Test(req) should not fail")
require.Equal(t, fiber.StatusRequestTimeout, resp.StatusCode, "Expected 408 Request Timeout")
require.Less(t, elapsed, 150*time.Millisecond, "context did not cancel within timeout")
}
// TestTimeout_CustomError tests that returning a user-defined error is also treated as a timeout.
func TestTimeout_CustomError(t *testing.T) {
t.Parallel()
app := fiber.New()
// This handler sleeps 50ms and returns errCustomTimeout if canceled.
app.Get("/custom", New(func(c fiber.Ctx) error {
// Sleep might time out, or might return early. If the context is canceled,
// we treat errCustomTimeout as a 'timeout-like' condition.
if err := sleepWithContext(c.Context(), 200*time.Millisecond, errCustomTimeout); err != nil {
return fmt.Errorf("wrapped: %w", err)
}
return c.SendString("Should never get here")
}, Config{Timeout: 100 * time.Millisecond, Errors: []error{errCustomTimeout}}))
req := httptest.NewRequest(fiber.MethodGet, "/custom", http.NoBody)
resp, err := app.Test(req)
require.NoError(t, err, "app.Test(req) should not fail")
require.Equal(t, fiber.StatusRequestTimeout, resp.StatusCode, "Expected 408 for custom timeout error")
}
// TestTimeout_UnmatchedError checks that if the handler returns an error
// that is neither a deadline exceeded nor a custom 'timeout' error, it is
// propagated as a regular 500 (internal server error).
func TestTimeout_UnmatchedError(t *testing.T) {
t.Parallel()
app := fiber.New()
app.Get("/unmatched", New(func(_ fiber.Ctx) error {
return errUnrelated // Not in the custom error list
}, Config{Timeout: 100 * time.Millisecond, Errors: []error{errCustomTimeout}}))
req := httptest.NewRequest(fiber.MethodGet, "/unmatched", http.NoBody)
resp, err := app.Test(req)
require.NoError(t, err, "app.Test(req) should not fail")
require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode,
"Expected 500 because the error is not recognized as a timeout error")
}
// TestTimeout_ZeroDuration tests the edge case where the timeout is set to zero.
// Usually this means the request can never exceed a 'deadline' – effectively no timeout.
func TestTimeout_ZeroDuration(t *testing.T) {
t.Parallel()
app := fiber.New()
app.Get("/zero", New(func(c fiber.Ctx) error {
// Sleep 50ms, but there's no real 'deadline' since zero-timeout.
time.Sleep(50 * time.Millisecond)
return c.SendString("No timeout used")
}))
req := httptest.NewRequest(fiber.MethodGet, "/zero", http.NoBody)
resp, err := app.Test(req)
require.NoError(t, err, "app.Test(req) should not fail")
require.Equal(t, fiber.StatusOK, resp.StatusCode, "Expected 200 OK with zero timeout")
}
// TestTimeout_NegativeDuration ensures negative timeout values fall back to zero.
func TestTimeout_NegativeDuration(t *testing.T) {
t.Parallel()
app := fiber.New()
app.Get("/negative", New(func(c fiber.Ctx) error {
time.Sleep(50 * time.Millisecond)
return c.SendString("No timeout used")
}, Config{Timeout: -100 * time.Millisecond}))
req := httptest.NewRequest(fiber.MethodGet, "/negative", http.NoBody)
resp, err := app.Test(req)
require.NoError(t, err, "app.Test(req) should not fail")
require.Equal(t, fiber.StatusOK, resp.StatusCode, "Expected 200 OK with zero timeout")
}
// TestTimeout_CustomHandler ensures that a custom handler runs on timeout.
func TestTimeout_CustomHandler(t *testing.T) {
t.Parallel()
app := fiber.New()
called := 0
app.Get("/custom-handler", New(func(c fiber.Ctx) error {
if err := sleepWithContext(c.Context(), 100*time.Millisecond, context.DeadlineExceeded); err != nil {
return err
}
return c.SendString("should not reach")
}, Config{
Timeout: 20 * time.Millisecond,
OnTimeout: func(c fiber.Ctx) error {
called++
return c.Status(408).JSON(fiber.Map{"error": "timeout"})
},
}))
req := httptest.NewRequest(fiber.MethodGet, "/custom-handler", http.NoBody)
resp, err := app.Test(req)
require.NoError(t, err)
require.Equal(t, fiber.StatusRequestTimeout, resp.StatusCode)
require.Equal(t, 1, called)
}
// TestRunHandler_DefaultOnTimeout ensures context.DeadlineExceeded triggers ErrRequestTimeout.
func TestRunHandler_DefaultOnTimeout(t *testing.T) {
app := fiber.New()
ctx := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(ctx)
err := runHandler(ctx, func(_ fiber.Ctx) error {
return context.DeadlineExceeded
}, Config{})
require.Equal(t, fiber.ErrRequestTimeout, err)
}
// TestRunHandler_CustomOnTimeout verifies that a custom error and OnTimeout handler are used.
func TestRunHandler_CustomOnTimeout(t *testing.T) {
app := fiber.New()
ctx := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(ctx)
called := false
cfg := Config{
Errors: []error{errCustomTimeout},
OnTimeout: func(_ fiber.Ctx) error {
called = true
return errors.New("handled")
},
}
err := runHandler(ctx, func(_ fiber.Ctx) error {
return fmt.Errorf("wrap: %w", errCustomTimeout)
}, cfg)
require.True(t, called)
require.EqualError(t, err, "handled")
}
// TestTimeout_Issue_3671 tests various edge cases for the timeout middleware.
func TestTimeout_Issue_3671(t *testing.T) {
t.Parallel()
app := fiber.New()
testCases := []struct {
name string
path string
handler fiber.Handler
config Config
expectCode int
}{
{
name: "Handler panics after timeout",
path: "/panic-after-timeout",
handler: func(_ fiber.Ctx) error {
time.Sleep(50 * time.Millisecond)
panic("panic after timeout")
},
config: Config{Timeout: 10 * time.Millisecond},
expectCode: fiber.StatusRequestTimeout,
},
{
name: "Handler blocks forever",
path: "/block-forever",
handler: func(_ fiber.Ctx) error {
select {} // Block forever
},
config: Config{Timeout: 10 * time.Millisecond},
expectCode: fiber.StatusRequestTimeout,
},
{
name: "Timeout set to 1 nanosecond",
path: "/nano",
handler: func(c fiber.Ctx) error {
time.Sleep(1 * time.Millisecond)
return c.SendString("late")
},
config: Config{Timeout: 1 * time.Nanosecond},
expectCode: fiber.StatusRequestTimeout,
},
{
name: "Timeout set to a very large value",
path: "/maxint",
handler: func(c fiber.Ctx) error {
return c.SendString("ok")
},
config: Config{Timeout: 1<<63 - 1},
expectCode: fiber.StatusOK,
},
{
name: "Custom OnTimeout handler panics",
path: "/panic-ontimeout",
handler: func(_ fiber.Ctx) error {
time.Sleep(50 * time.Millisecond)
return nil
},
config: Config{
Timeout: 10 * time.Millisecond,
OnTimeout: func(_ fiber.Ctx) error {
panic("custom panic on timeout")
},
},
expectCode: fiber.StatusRequestTimeout,
},
{
name: "Custom OnTimeout",
path: "/panic-ontimeout",
handler: func(c fiber.Ctx) error {
if err := sleepWithContext(c.Context(), 100*time.Millisecond, context.DeadlineExceeded); err != nil {
return err
}
return c.SendString("should not reach")
},
config: Config{
Timeout: 20 * time.Millisecond,
OnTimeout: func(c fiber.Ctx) error {
return c.Status(408).JSON(fiber.Map{"error": "timeout"})
},
},
expectCode: fiber.StatusRequestTimeout,
},
}
for _, tc := range testCases {
app.Get(tc.path, New(tc.handler, tc.config))
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(fiber.MethodGet, tc.path, nil)
resp, err := app.Test(req)
require.NoError(t, err)
require.Equal(t, tc.expectCode, resp.StatusCode)
})
}
}
func TestSafeCall_Panic(t *testing.T) {
t.Parallel()
err := safeCall(func() error {
panic("test panic")
})
require.Equal(t, fiber.ErrRequestTimeout, err)
}