Repository navigation
Expand file tree
/
Copy pathstruct_pages_extended_handler_test.go
More file actions
434 lines (364 loc) · 12.5 KB
/
Copy pathstruct_pages_extended_handler_test.go
File metadata and controls
434 lines (364 loc) · 12.5 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package structpages
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
// Test types for extended ServeHTTP with extra arguments
type (
ExtendedArg1 string
ExtendedArg2 int
ExtendedArg3 struct {
Data string
}
)
// Handler that returns an error (to test buffered writer path)
type extendedErrorReturningHandler struct{}
func (extendedErrorReturningHandler) ServeHTTP(
w http.ResponseWriter, r *http.Request, arg1 ExtendedArg1, arg2 ExtendedArg2,
) error {
// Write some data first
fmt.Fprintf(w, "arg1=%s, arg2=%d", arg1, arg2)
// Return error based on query param
if r.URL.Query().Get("error") == "true" {
return fmt.Errorf("handler error with args: %s, %d", arg1, arg2)
}
return nil
}
// Handler that returns multiple values including error
type extendedMultiReturnHandler struct{}
func (extendedMultiReturnHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, arg ExtendedArg3) (string, error) {
if r.URL.Query().Get("error") == "true" {
return "", fmt.Errorf("multi-return error: %s", arg.Data)
}
fmt.Fprintf(w, "success with %s", arg.Data)
return "result", nil
}
func TestExtendedServeHTTPWithExtraArgs(t *testing.T) {
tests := []struct {
name string
handler any
args []any
path string
query string
expectedStatus int
expectedBody string
expectError bool
}{
{
name: "error returning handler - success",
handler: &extendedErrorReturningHandler{},
args: []any{ExtendedArg1("test1"), ExtendedArg2(42)},
path: "/error-handler",
expectedStatus: http.StatusOK,
expectedBody: "arg1=test1, arg2=42",
},
{
name: "error returning handler - error",
handler: &extendedErrorReturningHandler{},
args: []any{ExtendedArg1("test1"), ExtendedArg2(42)},
path: "/error-handler",
query: "?error=true",
expectedStatus: http.StatusInternalServerError,
expectedBody: "handler error with args: test1, 42", // only error message when handler returns error
expectError: true,
},
{
name: "multi return handler - success",
handler: &extendedMultiReturnHandler{},
args: []any{ExtendedArg3{Data: "multi-data"}},
path: "/multi-handler",
expectedStatus: http.StatusOK,
expectedBody: "success with multi-data",
},
{
name: "multi return handler - error",
handler: &extendedMultiReturnHandler{},
args: []any{ExtendedArg3{Data: "multi-data"}},
path: "/multi-handler",
query: "?error=true",
expectedStatus: http.StatusInternalServerError,
expectedBody: "multi-return error: multi-data",
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create pages struct based on handler type
var p any
var capturedError error
errorHandler := func(w http.ResponseWriter, r *http.Request, err error) {
capturedError = err
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if tt.path == "/error-handler" {
type errorPages struct {
extendedErrorReturningHandler `route:"GET /error-handler"`
}
p = &errorPages{}
} else {
type multiPages struct {
extendedMultiReturnHandler `route:"GET /multi-handler"`
}
p = &multiPages{}
}
mux := http.NewServeMux()
opts := append([]Option{WithErrorHandler(errorHandler)}, WithArgs(tt.args...))
_, err := Mount(mux, p, "/", "Test Extended", opts...)
if err != nil {
t.Fatalf("Mount failed: %v", err)
}
req := httptest.NewRequest(http.MethodGet, tt.path+tt.query, http.NoBody)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != tt.expectedStatus {
t.Errorf("expected status %d, got %d", tt.expectedStatus, rec.Code)
}
body := rec.Body.String()
// For error cases, http.Error adds a newline, and buffered content is discarded
if tt.expectError {
expectedWithNewline := tt.expectedBody + "\n"
if body != expectedWithNewline {
t.Errorf("expected body %q, got %q", expectedWithNewline, body)
}
} else if body != tt.expectedBody {
t.Errorf("expected body %q, got %q", tt.expectedBody, body)
}
if tt.expectError && capturedError == nil {
t.Error("expected error but got none")
} else if !tt.expectError && capturedError != nil {
t.Errorf("unexpected error: %v", capturedError)
}
})
}
}
// Handler with wrong argument count expectation
type wrongArgHandler struct{}
// This handler expects an argument that won't be provided
func (wrongArgHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, missing string) {
fmt.Fprint(w, "should not reach here")
}
// Test callMethod error scenarios
func TestExtendedServeHTTPCallMethodError(t *testing.T) {
type pages struct {
wrongArgHandler `route:"GET /wrong"`
}
var capturedError error
errorHandler := func(w http.ResponseWriter, r *http.Request, err error) {
capturedError = err
t.Logf("Captured error: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
// Don't provide the string argument that the handler expects
mux := http.NewServeMux()
_, err := Mount(mux, &pages{}, "/", "Test", WithErrorHandler(errorHandler))
if err != nil {
t.Fatalf("Mount failed: %v", err)
}
req := httptest.NewRequest(http.MethodGet, "/wrong", http.NoBody)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Errorf("expected status %d, got %d", http.StatusInternalServerError, rec.Code)
}
if capturedError == nil {
t.Error("expected error for missing argument")
} else if !contains(capturedError.Error(), "error calling ServeHTTP method") {
t.Errorf("unexpected error message: %v", capturedError)
}
}
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || s != "" && (s[0:len(substr)] == substr || contains(s[1:], substr)))
}
// Types for testing
type pageWithServeHTTPError struct{}
func (p *pageWithServeHTTPError) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
return errors.New("test error")
}
type pageWithExtendedServeHTTP struct{}
func (p *pageWithExtendedServeHTTP) ServeHTTP(w http.ResponseWriter, r *http.Request, extra string) (string, error) {
_, _ = w.Write([]byte("response: " + extra))
return "result", nil
}
type pageWithExtendedServeHTTPError struct{}
func (p *pageWithExtendedServeHTTPError) ServeHTTP(w http.ResponseWriter, r *http.Request, extra string) error {
return errors.New("extended error")
}
// Test asHandler with ServeHTTP returning multiple values including error
func TestStructPages_asHandler_serveHTTPWithError(t *testing.T) {
sp, _ := Mount(nil, struct{}{}, "/", "Test")
// Create a value that implements the error handler interface
page := &pageWithServeHTTPError{}
pn := &PageNode{
Name: "test",
Value: reflect.ValueOf(page),
}
handler := sp.asHandler(pn)
if handler == nil {
t.Fatal("Expected handler")
}
req := httptest.NewRequest("GET", "/", http.NoBody)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Errorf("Expected 500, got %d", rec.Code)
}
}
// Test asHandler with extended ServeHTTP that has extra parameters and returns values
func TestStructPages_asHandler_extendedServeHTTPWithReturnValues(t *testing.T) {
sp, _ := Mount(nil, struct{}{}, "/", "Test")
pc := &parseContext{
args: make(argRegistry),
}
// Add the extra string argument
_ = pc.args.addArg("extra value")
sp.pc = pc // Set the pc on the StructPages instance
pn := &PageNode{
Name: "test",
Value: reflect.ValueOf(&pageWithExtendedServeHTTP{}),
}
handler := sp.asHandler(pn)
if handler == nil {
t.Fatal("Expected handler")
}
req := httptest.NewRequest("GET", "/", http.NoBody)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Body.String() != "response: extra value" {
t.Errorf("Expected 'response: extra value', got %s", rec.Body.String())
}
}
// Test asHandler with extended ServeHTTP that returns an error
func TestStructPages_asHandler_extendedServeHTTPReturnsError(t *testing.T) {
sp, _ := Mount(nil, struct{}{}, "/", "Test")
pc := &parseContext{
args: make(argRegistry),
}
_ = pc.args.addArg("extra")
pn := &PageNode{
Name: "test",
Value: reflect.ValueOf(&pageWithExtendedServeHTTPError{}),
}
handler := sp.asHandler(pn)
if handler == nil {
t.Fatal("Expected handler")
}
req := httptest.NewRequest("GET", "/", http.NoBody)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Errorf("Expected 500, got %d", rec.Code)
}
}
type pageWithValueReceiver struct{}
func (p pageWithValueReceiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("value receiver"))
}
// Test more edge cases for asHandler
func TestStructPages_asHandler_moreEdgeCases(t *testing.T) {
sp, _ := Mount(nil, struct{}{}, "/", "Test")
// Test with non-pointer receiver ServeHTTP
pn := &PageNode{
Name: "test",
Value: reflect.ValueOf(pageWithValueReceiver{}),
}
handler := sp.asHandler(pn)
if handler == nil {
t.Fatal("Expected handler for value receiver")
}
req := httptest.NewRequest("GET", "/", http.NoBody)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Body.String() != "value receiver" {
t.Errorf("Expected 'value receiver', got %s", rec.Body.String())
}
}
type pageWithExtendedNoReturn struct{}
func (p *pageWithExtendedNoReturn) ServeHTTP(w http.ResponseWriter, r *http.Request, extra string) {
_, _ = w.Write([]byte("no return: " + extra))
}
// Test extended ServeHTTP with no return values
func TestStructPages_asHandler_extendedServeHTTPNoReturn(t *testing.T) {
sp, _ := Mount(nil, struct{}{}, "/", "Test")
pc := &parseContext{
args: make(argRegistry),
}
_ = pc.args.addArg("extra")
sp.pc = pc // Set the pc on the StructPages instance
pn := &PageNode{
Name: "test",
Value: reflect.ValueOf(&pageWithExtendedNoReturn{}),
}
handler := sp.asHandler(pn)
if handler == nil {
t.Fatal("Expected handler")
}
req := httptest.NewRequest("GET", "/", http.NoBody)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Body.String() != "no return: extra" {
t.Errorf("Expected 'no return: extra', got %s", rec.Body.String())
}
}
// Asserts the documented contract (skills/structpages/reference.md:146-149):
// the bare ServeHTTP(w, r) and the DI no-return ServeHTTP(w, r, deps...) forms
// must receive the original http.ResponseWriter, not the *buffered wrapper that
// the error-returning forms use. The check runs inside the handler so a future
// regression that introduces buffering on these paths would be caught even if
// the final response body still looks correct.
type bareNoReturnAssertsUnbuffered struct {
gotBuffered bool
flushOK bool
}
func (p *bareNoReturnAssertsUnbuffered) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
if _, ok := w.(*buffered); ok {
p.gotBuffered = true
}
_, p.flushOK = w.(http.Flusher)
_, _ = w.Write([]byte("ok"))
}
type extendedNoReturnAssertsUnbuffered struct {
gotBuffered bool
}
func (p *extendedNoReturnAssertsUnbuffered) ServeHTTP(w http.ResponseWriter, _ *http.Request, _ ExtendedArg1) {
if _, ok := w.(*buffered); ok {
p.gotBuffered = true
}
_, _ = w.Write([]byte("ok"))
}
func TestAsHandler_NoReturnIsUnbuffered(t *testing.T) {
t.Run("bare ServeHTTP(w, r)", func(t *testing.T) {
p := &bareNoReturnAssertsUnbuffered{}
sp, _ := Mount(nil, struct{}{}, "/", "Test")
sp.pc = &parseContext{args: make(argRegistry)}
handler := sp.asHandler(&PageNode{Name: "bare", Value: reflect.ValueOf(p)})
if handler == nil {
t.Fatal("expected handler")
}
handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", http.NoBody))
if p.gotBuffered {
t.Errorf("bare ServeHTTP(w, r) must receive raw ResponseWriter, got *buffered wrapper")
}
if !p.flushOK {
t.Errorf("bare ServeHTTP(w, r) must preserve http.Flusher capability of the underlying writer")
}
})
t.Run("extended ServeHTTP(w, r, deps...) no return", func(t *testing.T) {
p := &extendedNoReturnAssertsUnbuffered{}
sp, _ := Mount(nil, struct{}{}, "/", "Test")
pc := &parseContext{args: make(argRegistry)}
_ = pc.args.addArg(ExtendedArg1("v"))
sp.pc = pc
handler := sp.asHandler(&PageNode{Name: "ext", Value: reflect.ValueOf(p)})
if handler == nil {
t.Fatal("expected handler")
}
handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", http.NoBody))
if p.gotBuffered {
t.Errorf("extended no-return ServeHTTP must receive raw ResponseWriter, got *buffered wrapper")
}
})
}