Repository navigation
Expand file tree
/
Copy patherror_middleware_test.go
More file actions
344 lines (271 loc) · 9.09 KB
/
Copy patherror_middleware_test.go
File metadata and controls
344 lines (271 loc) · 9.09 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
package nanite
import (
"errors"
"net/http/httptest"
"testing"
)
// TestErrorMiddlewareFromRouteSpecificMiddleware tests that error middleware
// is triggered when c.Error() is called from route-specific middleware
func TestErrorMiddlewareFromRouteSpecificMiddleware(t *testing.T) {
r := New()
// Track if error middleware was called
errorMiddlewareCalled := false
var capturedError error
// Register error middleware
r.UseError(func(err error, c *Context, next func()) {
errorMiddlewareCalled = true
capturedError = err
c.JSON(500, map[string]string{"error": err.Error()})
})
// Route-specific middleware that calls c.Error()
sizeLimitMiddleware := func(c *Context, next func()) {
if c.Request.ContentLength > 1000 {
c.Error(errors.New("file too large"))
return
}
next()
}
// Handler that should not be called if middleware aborts
handlerCalled := false
uploadHandler := func(c *Context) {
handlerCalled = true
c.JSON(200, map[string]string{"status": "uploaded"})
}
// Register route with middleware
r.Post("/upload", uploadHandler, sizeLimitMiddleware)
// Create request with large content length
req := httptest.NewRequest("POST", "/upload", nil)
req.ContentLength = 2000
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
// Assertions
if handlerCalled {
t.Error("Handler should not be called when middleware aborts")
}
if !errorMiddlewareCalled {
t.Error("Error middleware should be called when c.Error() is invoked from route-specific middleware")
}
if capturedError == nil {
t.Error("Error should be captured by error middleware")
} else if capturedError.Error() != "file too large" {
t.Errorf("Expected error 'file too large', got '%s'", capturedError.Error())
}
if w.Code != 500 {
t.Errorf("Expected status 500, got %d", w.Code)
}
// Check response body
expectedBody := `{"error":"file too large"}` + "\n"
if w.Body.String() != expectedBody {
t.Errorf("Expected body '%s', got '%s'", expectedBody, w.Body.String())
}
}
// TestErrorMiddlewareFromGlobalMiddleware tests that error middleware
// works correctly when called from global middleware (baseline test)
func TestErrorMiddlewareFromGlobalMiddleware(t *testing.T) {
r := New()
errorMiddlewareCalled := false
var capturedError error
r.UseError(func(err error, c *Context, next func()) {
errorMiddlewareCalled = true
capturedError = err
c.JSON(500, map[string]string{"error": err.Error()})
})
// Global middleware that calls c.Error()
r.Use(func(c *Context, next func()) {
if c.Request.Header.Get("X-Fail") == "true" {
c.Error(errors.New("global middleware error"))
return
}
next()
})
handlerCalled := false
r.Get("/test", func(c *Context) {
handlerCalled = true
c.JSON(200, map[string]string{"status": "ok"})
})
req := httptest.NewRequest("GET", "/test", nil)
req.Header.Set("X-Fail", "true")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if handlerCalled {
t.Error("Handler should not be called when global middleware aborts")
}
if !errorMiddlewareCalled {
t.Error("Error middleware should be called when c.Error() is invoked from global middleware")
}
if capturedError == nil {
t.Error("Error should be captured by error middleware")
}
if w.Code != 500 {
t.Errorf("Expected status 500, got %d", w.Code)
}
}
// TestErrorMiddlewareFromHandler tests that error middleware
// works correctly when called from the handler itself
func TestErrorMiddlewareFromHandler(t *testing.T) {
r := New()
errorMiddlewareCalled := false
var capturedError error
r.UseError(func(err error, c *Context, next func()) {
errorMiddlewareCalled = true
capturedError = err
c.JSON(404, map[string]string{"error": err.Error()})
})
r.Get("/users/:id", func(c *Context) {
id := c.MustParam("id")
if id == "999" {
c.Error(errors.New("user not found"))
return
}
c.JSON(200, map[string]string{"user": id})
})
req := httptest.NewRequest("GET", "/users/999", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if !errorMiddlewareCalled {
t.Error("Error middleware should be called when c.Error() is invoked from handler")
}
if capturedError == nil {
t.Error("Error should be captured by error middleware")
} else if capturedError.Error() != "user not found" {
t.Errorf("Expected error 'user not found', got '%s'", capturedError.Error())
}
if w.Code != 404 {
t.Errorf("Expected status 404, got %d", w.Code)
}
}
// TestErrorMiddlewareWithAbortOnly tests that abort without error still returns 404
func TestErrorMiddlewareWithAbortOnly(t *testing.T) {
r := New()
errorMiddlewareCalled := false
r.UseError(func(err error, c *Context, next func()) {
errorMiddlewareCalled = true
c.JSON(500, map[string]string{"error": err.Error()})
})
// Middleware that aborts without calling c.Error()
abortMiddleware := func(c *Context, next func()) {
c.Abort() // Just abort, no error
return
}
handlerCalled := false
r.Get("/test", func(c *Context) {
handlerCalled = true
c.JSON(200, map[string]string{"status": "ok"})
}, abortMiddleware)
req := httptest.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if handlerCalled {
t.Error("Handler should not be called when middleware aborts")
}
if errorMiddlewareCalled {
t.Error("Error middleware should NOT be called when abort is called without error")
}
// Should return 404 when aborted without error
if w.Code != 404 {
t.Errorf("Expected status 404, got %d", w.Code)
}
}
// TestErrorMiddlewareWithResponseWritten tests that error middleware
// is NOT triggered if a response has already been written
func TestErrorMiddlewareWithResponseWritten(t *testing.T) {
r := New()
errorMiddlewareCalled := false
r.UseError(func(err error, c *Context, next func()) {
errorMiddlewareCalled = true
c.JSON(500, map[string]string{"error": err.Error()})
})
// Middleware that writes response then calls c.Error()
middleware := func(c *Context, next func()) {
c.JSON(400, map[string]string{"error": "custom error"})
c.Error(errors.New("this error should be ignored"))
return
}
r.Get("/test", func(c *Context) {
c.JSON(200, map[string]string{"status": "ok"})
}, middleware)
req := httptest.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if errorMiddlewareCalled {
t.Error("Error middleware should NOT be called when response is already written")
}
// Should keep the original response
if w.Code != 400 {
t.Errorf("Expected status 400, got %d", w.Code)
}
expectedBody := `{"error":"custom error"}` + "\n"
if w.Body.String() != expectedBody {
t.Errorf("Expected body '%s', got '%s'", expectedBody, w.Body.String())
}
}
// TestErrorMiddlewareChaining tests that multiple error handlers can be chained
func TestErrorMiddlewareChaining(t *testing.T) {
r := New()
var executionOrder []string
// First error handler: logging
r.UseError(func(err error, c *Context, next func()) {
executionOrder = append(executionOrder, "logger")
next() // Continue to next error handler
})
// Second error handler: send response
r.UseError(func(err error, c *Context, next func()) {
executionOrder = append(executionOrder, "responder")
c.JSON(500, map[string]string{"error": err.Error()})
next() // Continue (optional)
})
// Third error handler: cleanup
r.UseError(func(err error, c *Context, next func()) {
executionOrder = append(executionOrder, "cleanup")
})
r.Get("/test", func(c *Context) {
c.Error(errors.New("test error"))
})
req := httptest.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
// Verify execution order
expectedOrder := []string{"logger", "responder", "cleanup"}
if len(executionOrder) != len(expectedOrder) {
t.Errorf("Expected %d error handlers to execute, got %d", len(expectedOrder), len(executionOrder))
}
for i, expected := range expectedOrder {
if i >= len(executionOrder) || executionOrder[i] != expected {
t.Errorf("Expected handler %d to be '%s', got '%s'", i, expected, executionOrder[i])
}
}
if w.Code != 500 {
t.Errorf("Expected status 500, got %d", w.Code)
}
}
// TestErrorMiddlewareWithoutNext tests that not calling next() stops the chain
func TestErrorMiddlewareWithoutNext(t *testing.T) {
r := New()
var executionOrder []string
// First error handler: doesn't call next()
r.UseError(func(err error, c *Context, next func()) {
executionOrder = append(executionOrder, "first")
c.JSON(500, map[string]string{"error": err.Error()})
// Not calling next() - chain should stop here
})
// Second error handler: should NOT execute
r.UseError(func(err error, c *Context, next func()) {
executionOrder = append(executionOrder, "second")
})
r.Get("/test", func(c *Context) {
c.Error(errors.New("test error"))
})
req := httptest.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
// Only first handler should execute
if len(executionOrder) != 1 {
t.Errorf("Expected 1 error handler to execute, got %d", len(executionOrder))
}
if len(executionOrder) > 0 && executionOrder[0] != "first" {
t.Errorf("Expected first handler to execute, got '%s'", executionOrder[0])
}
if w.Code != 500 {
t.Errorf("Expected status 500, got %d", w.Code)
}
}