-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext_test.go
More file actions
409 lines (337 loc) · 8.94 KB
/
context_test.go
File metadata and controls
409 lines (337 loc) · 8.94 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package celeris
import (
"context"
"net"
"testing"
"time"
"github.com/goceleris/celeris/protocol/h2/stream"
)
type mockResponseWriter struct {
status int
headers [][2]string
body []byte
}
func (m *mockResponseWriter) WriteResponse(_ *stream.Stream, status int, headers [][2]string, body []byte) error {
m.status = status
m.headers = make([][2]string, len(headers))
copy(m.headers, headers)
m.body = make([]byte, len(body))
copy(m.body, body)
return nil
}
func newTestStream(method, path string) (*stream.Stream, *mockResponseWriter) {
s := stream.NewStream(1)
s.Headers = [][2]string{
{":method", method},
{":path", path},
{":scheme", "http"},
{":authority", "localhost"},
}
rw := &mockResponseWriter{}
s.ResponseWriter = rw
return s, rw
}
type mockHijackerResponseWriter struct {
mockResponseWriter
hijackFn func(*stream.Stream) (net.Conn, error)
}
func (m *mockHijackerResponseWriter) Hijack(s *stream.Stream) (net.Conn, error) {
return m.hijackFn(s)
}
var _ stream.Hijacker = (*mockHijackerResponseWriter)(nil)
func TestContextAcquireRelease(t *testing.T) {
s, _ := newTestStream("GET", "/test?foo=bar")
defer s.Release()
c := acquireContext(s)
if c.Method() != "GET" {
t.Fatalf("expected GET, got %s", c.Method())
}
if c.Path() != "/test" {
t.Fatalf("expected /test, got %s", c.Path())
}
if c.Query("foo") != "bar" {
t.Fatalf("expected bar, got %s", c.Query("foo"))
}
releaseContext(c)
if c.method != "" {
t.Fatal("expected reset after release")
}
}
func TestContextAbort(t *testing.T) {
s, _ := newTestStream("GET", "/abort")
defer s.Release()
c := acquireContext(s)
defer releaseContext(c)
secondCalled := false
c.handlers = []HandlerFunc{
func(c *Context) error {
c.Abort()
return nil
},
func(_ *Context) error {
secondCalled = true
return nil
},
}
_ = c.Next()
if secondCalled {
t.Fatal("second handler should not have been called after abort")
}
if !c.IsAborted() {
t.Fatal("expected aborted")
}
}
func TestContextNext(t *testing.T) {
s, _ := newTestStream("GET", "/next")
defer s.Release()
c := acquireContext(s)
defer releaseContext(c)
order := ""
c.handlers = []HandlerFunc{
func(c *Context) error {
order += "1"
_ = c.Next()
order += "3"
return nil
},
func(_ *Context) error {
order += "2"
return nil
},
}
_ = c.Next()
if order != "123" {
t.Fatalf("expected order 123, got %s", order)
}
}
func TestContextSetGet(t *testing.T) {
s, _ := newTestStream("GET", "/kv")
defer s.Release()
c := acquireContext(s)
defer releaseContext(c)
_, ok := c.Get("key")
if ok {
t.Fatal("expected not found")
}
c.Set("key", "value")
v, ok := c.Get("key")
if !ok || v != "value" {
t.Fatalf("expected value, got %v", v)
}
}
func TestContextContext(t *testing.T) {
s, _ := newTestStream("GET", "/ctx")
defer s.Release()
c := acquireContext(s)
defer releaseContext(c)
// Default context should be non-nil.
ctx := c.Context()
if ctx == nil {
t.Fatal("expected non-nil context")
}
// SetContext should override.
type ctxKey struct{}
custom := context.WithValue(context.Background(), ctxKey{}, "test-value")
c.SetContext(custom)
got := c.Context()
if got != custom {
t.Fatal("expected custom context")
}
if got.Value(ctxKey{}) != "test-value" {
t.Fatal("expected context value")
}
}
func TestContextContextResetOnRelease(t *testing.T) {
s, _ := newTestStream("GET", "/ctx-reset")
defer s.Release()
c := acquireContext(s)
type ctxKey struct{}
c.SetContext(context.WithValue(context.Background(), ctxKey{}, "val"))
releaseContext(c)
if c.ctx != nil {
t.Fatal("expected ctx to be nil after release")
}
}
func TestContextFullPath(t *testing.T) {
s, _ := newTestStream("GET", "/users/42")
defer s.Release()
c := acquireContext(s)
defer releaseContext(c)
// Not set yet.
if c.FullPath() != "" {
t.Fatalf("expected empty fullPath, got %q", c.FullPath())
}
c.fullPath = "/users/:id"
if c.FullPath() != "/users/:id" {
t.Fatalf("expected /users/:id, got %q", c.FullPath())
}
}
func TestContextFullPathResetOnRelease(t *testing.T) {
s, _ := newTestStream("GET", "/test")
defer s.Release()
c := acquireContext(s)
c.fullPath = "/test"
releaseContext(c)
if c.fullPath != "" {
t.Fatal("expected fullPath to be empty after release")
}
}
func TestContextAddParam(t *testing.T) {
s, _ := newTestStream("GET", "/users/42")
defer s.Release()
c := acquireContext(s)
defer releaseContext(c)
c.params = append(c.params, Param{Key: "id", Value: "42"})
if c.Param("id") != "42" {
t.Fatalf("expected 42, got %s", c.Param("id"))
}
}
func TestContextNoDeadlineFromWriteTimeout(t *testing.T) {
// WriteTimeout is enforced at the engine level via timer wheel, not
// via context.WithTimeout. The handler's context should NOT have a deadline.
s := New(Config{WriteTimeout: 5 * time.Second})
var hadDeadline bool
s.GET("/test", func(c *Context) error {
_, ok := c.Context().Deadline()
hadDeadline = ok
return c.String(200, "ok")
})
adapter := &routerAdapter{server: s}
st, _ := newTestStream("GET", "/test")
if err := adapter.HandleStream(context.Background(), st); err != nil {
t.Fatal(err)
}
if hadDeadline {
t.Fatal("expected no context deadline — WriteTimeout is engine-level")
}
st.Release()
}
func TestContextNoDeadlineWithoutTimeout(t *testing.T) {
s := New(Config{})
var hadDeadline bool
s.GET("/test", func(c *Context) error {
_, ok := c.Context().Deadline()
hadDeadline = ok
return c.String(200, "ok")
})
adapter := &routerAdapter{server: s}
st, _ := newTestStream("GET", "/test")
if err := adapter.HandleStream(context.Background(), st); err != nil {
t.Fatal(err)
}
if hadDeadline {
t.Fatal("expected no deadline without WriteTimeout")
}
st.Release()
}
func TestContextKeys(t *testing.T) {
s, _ := newTestStream("GET", "/test")
defer s.Release()
c := acquireContext(s)
defer releaseContext(c)
if c.Keys() != nil {
t.Fatal("expected nil for empty keys")
}
c.Set("user", "alice")
c.Set("role", "admin")
keys := c.Keys()
if len(keys) != 2 {
t.Fatalf("expected 2 keys, got %d", len(keys))
}
if keys["user"] != "alice" || keys["role"] != "admin" {
t.Fatalf("unexpected keys: %v", keys)
}
// Verify it's a copy — mutating returned map doesn't affect context.
keys["user"] = "modified"
v, _ := c.Get("user")
if v != "alice" {
t.Fatal("Keys() should return a copy")
}
}
func TestOnReleaseFiresOnRelease(t *testing.T) {
s, _ := newTestStream("GET", "/release")
defer s.Release()
c := acquireContext(s)
var fired bool
c.OnRelease(func() { fired = true })
releaseContext(c)
if !fired {
t.Fatal("expected OnRelease callback to fire during releaseContext")
}
}
func TestOnReleaseLIFOOrder(t *testing.T) {
s, _ := newTestStream("GET", "/lifo")
defer s.Release()
c := acquireContext(s)
var order []int
c.OnRelease(func() { order = append(order, 1) })
c.OnRelease(func() { order = append(order, 2) })
c.OnRelease(func() { order = append(order, 3) })
releaseContext(c)
if len(order) != 3 || order[0] != 3 || order[1] != 2 || order[2] != 1 {
t.Fatalf("expected LIFO order [3 2 1], got %v", order)
}
}
func TestOnReleasePanicRecovery(t *testing.T) {
s, _ := newTestStream("GET", "/panic-release")
defer s.Release()
c := acquireContext(s)
var normalFired bool
c.OnRelease(func() { normalFired = true })
c.OnRelease(func() { panic("boom") })
releaseContext(c)
if !normalFired {
t.Fatal("expected normal callback to fire even after panic in another")
}
}
func TestOnReleaseResetClearsCallbacks(t *testing.T) {
s, _ := newTestStream("GET", "/clear")
defer s.Release()
c := acquireContext(s)
callCount := 0
c.OnRelease(func() { callCount++ })
releaseContext(c)
if callCount != 1 {
t.Fatalf("expected 1 call, got %d", callCount)
}
// Re-acquire and release again without registering new callbacks.
// The callback must NOT fire a second time.
c2 := acquireContext(s)
releaseContext(c2)
if callCount != 1 {
t.Fatalf("expected callback count to remain 1 after reuse, got %d", callCount)
}
}
func TestHandleUnmatchedFallback(t *testing.T) {
// Custom 404 handler that returns nil without writing should fall back
// to default response.
s, rw := newTestStream("GET", "/nonexistent")
defer s.Release()
srv := New(Config{Addr: ":0"})
srv.NotFound(func(_ *Context) error {
// deliberately don't write anything
return nil
})
srv.GET("/other", func(c *Context) error { return c.String(200, "ok") })
adapter := &routerAdapter{server: srv}
_ = adapter.HandleStream(context.Background(), s)
if rw.status != 404 {
t.Fatalf("expected 404 fallback response, got %d", rw.status)
}
}
func TestContextStartTime(t *testing.T) {
s, _ := newTestStream("GET", "/test")
defer s.Release()
before := time.Now()
c := acquireContext(s)
c.startTime = time.Now()
after := time.Now()
defer releaseContext(c)
st := c.StartTime()
if st.IsZero() {
t.Fatal("expected non-zero StartTime")
}
if st.Before(before) || st.After(after) {
t.Fatalf("StartTime %v not within bracket [%v, %v]", st, before, after)
}
}