-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger_test.go
More file actions
552 lines (456 loc) · 13.1 KB
/
Copy pathlogger_test.go
File metadata and controls
552 lines (456 loc) · 13.1 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright 2025 coregx. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package middleware
import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/coregx/fursy"
)
// TestLogger tests the default Logger middleware.
func TestLogger(t *testing.T) {
var buf bytes.Buffer
logger := DefaultLogger(&buf)
r := fursy.New()
r.Use(LoggerWithConfig(LoggerConfig{
Logger: logger,
}))
r.GET("/test", func(c *fursy.Context) error {
return c.String(200, "OK")
})
req := httptest.NewRequest("GET", "/test", http.NoBody)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
output := buf.String()
// Check log contains expected fields
if !strings.Contains(output, "HTTP request") {
t.Error("log should contain 'HTTP request'")
}
if !strings.Contains(output, "method=GET") {
t.Error("log should contain method")
}
if !strings.Contains(output, "path=/test") {
t.Error("log should contain path")
}
if !strings.Contains(output, "status=200") {
t.Error("log should contain status")
}
if !strings.Contains(output, "latency_ms") {
t.Error("log should contain latency")
}
if !strings.Contains(output, "ip=") {
t.Error("log should contain IP")
}
}
// TestLogger_JSONFormat tests JSON output format.
func TestLogger_JSONFormat(t *testing.T) {
var buf bytes.Buffer
logger := JSONLogger(&buf)
r := fursy.New()
r.Use(LoggerWithConfig(LoggerConfig{
Logger: logger,
}))
r.GET("/api/users", func(c *fursy.Context) error {
return c.JSON(200, map[string]string{"status": "ok"})
})
req := httptest.NewRequest("GET", "/api/users", http.NoBody)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
output := buf.String()
// Check JSON format
if !strings.Contains(output, `"msg":"HTTP request"`) {
t.Error("JSON log should contain msg field")
}
if !strings.Contains(output, `"method":"GET"`) {
t.Error("JSON log should contain method field")
}
if !strings.Contains(output, `"path":"/api/users"`) {
t.Error("JSON log should contain path field")
}
if !strings.Contains(output, `"status":200`) {
t.Error("JSON log should contain status field")
}
}
// TestLogger_SkipPaths tests skipping specified paths.
func TestLogger_SkipPaths(t *testing.T) {
var buf bytes.Buffer
logger := DefaultLogger(&buf)
r := fursy.New()
r.Use(LoggerWithConfig(LoggerConfig{
Logger: logger,
SkipPaths: []string{"/health", "/metrics"},
}))
r.GET("/health", func(c *fursy.Context) error {
return c.String(200, "OK")
})
r.GET("/api/users", func(c *fursy.Context) error {
return c.String(200, "users")
})
// Request to skipped path
req1 := httptest.NewRequest("GET", "/health", http.NoBody)
w1 := httptest.NewRecorder()
r.ServeHTTP(w1, req1)
output1 := buf.String()
if strings.Contains(output1, "/health") {
t.Error("skipped path /health should not be logged")
}
// Request to normal path
buf.Reset()
req2 := httptest.NewRequest("GET", "/api/users", http.NoBody)
w2 := httptest.NewRecorder()
r.ServeHTTP(w2, req2)
output2 := buf.String()
if !strings.Contains(output2, "/api/users") {
t.Error("normal path /api/users should be logged")
}
}
// TestLogger_SkipFunc tests custom skip function.
func TestLogger_SkipFunc(t *testing.T) {
var buf bytes.Buffer
logger := DefaultLogger(&buf)
r := fursy.New()
r.Use(LoggerWithConfig(LoggerConfig{
Logger: logger,
SkipFunc: func(req *http.Request) bool {
// Skip requests with X-No-Log header
return req.Header.Get("X-No-Log") == "true"
},
}))
r.GET("/test", func(c *fursy.Context) error {
return c.String(200, "OK")
})
// Request with X-No-Log header
req1 := httptest.NewRequest("GET", "/test", http.NoBody)
req1.Header.Set("X-No-Log", "true")
w1 := httptest.NewRecorder()
r.ServeHTTP(w1, req1)
output1 := buf.String()
if output1 != "" {
t.Error("request with X-No-Log should not be logged")
}
// Normal request
req2 := httptest.NewRequest("GET", "/test", http.NoBody)
w2 := httptest.NewRecorder()
r.ServeHTTP(w2, req2)
output2 := buf.String()
if !strings.Contains(output2, "/test") {
t.Error("normal request should be logged")
}
}
// TestLogger_StatusCodes tests different status code handling.
func TestLogger_StatusCodes(t *testing.T) {
tests := []struct {
name string
status int
expectedLevel string
handler fursy.HandlerFunc
}{
{
name: "2xx success - INFO level",
status: 200,
expectedLevel: "INFO",
handler: func(c *fursy.Context) error {
return c.String(200, "OK")
},
},
{
name: "4xx client error - WARN level",
status: 404,
expectedLevel: "WARN",
handler: func(c *fursy.Context) error {
return c.String(404, "Not Found")
},
},
{
name: "5xx server error - ERROR level",
status: 500,
expectedLevel: "ERROR",
handler: func(c *fursy.Context) error {
return c.String(500, "Internal Server Error")
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf bytes.Buffer
logger := DefaultLogger(&buf)
r := fursy.New()
r.Use(LoggerWithConfig(LoggerConfig{
Logger: logger,
}))
r.GET("/test", tt.handler)
req := httptest.NewRequest("GET", "/test", http.NoBody)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
output := buf.String()
if !strings.Contains(output, "level="+tt.expectedLevel) {
t.Errorf("expected log level %s, got: %s", tt.expectedLevel, output)
}
if w.Code != tt.status {
t.Errorf("expected status %d, got %d", tt.status, w.Code)
}
})
}
}
// TestLogger_ErrorLogging tests error logging.
func TestLogger_ErrorLogging(t *testing.T) {
var buf bytes.Buffer
logger := DefaultLogger(&buf)
r := fursy.New()
r.Use(LoggerWithConfig(LoggerConfig{
Logger: logger,
}))
testErr := errors.New("test error")
r.GET("/error", func(_ *fursy.Context) error {
return testErr
})
req := httptest.NewRequest("GET", "/error", http.NoBody)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
output := buf.String()
if !strings.Contains(output, "error=\"test error\"") {
t.Errorf("log should contain error message, got: %s", output)
}
if !strings.Contains(output, "level=ERROR") {
t.Error("error should be logged at ERROR level")
}
}
// TestLogger_BytesWritten tests tracking bytes written.
func TestLogger_BytesWritten(t *testing.T) {
var buf bytes.Buffer
logger := DefaultLogger(&buf)
r := fursy.New()
r.Use(LoggerWithConfig(LoggerConfig{
Logger: logger,
}))
responseBody := "This is a test response body with some content"
r.GET("/test", func(c *fursy.Context) error {
return c.String(200, responseBody)
})
req := httptest.NewRequest("GET", "/test", http.NoBody)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
output := buf.String()
expectedBytes := len(responseBody)
if !strings.Contains(output, "bytes=") {
t.Errorf("log should contain bytes written, got: %s", output)
}
// Verify actual bytes written
if w.Body.Len() != expectedBytes {
t.Errorf("expected %d bytes written, got %d", expectedBytes, w.Body.Len())
}
}
// TestLogger_Latency tests latency measurement.
func TestLogger_Latency(t *testing.T) {
var buf bytes.Buffer
logger := DefaultLogger(&buf)
r := fursy.New()
r.Use(LoggerWithConfig(LoggerConfig{
Logger: logger,
}))
r.GET("/test", func(c *fursy.Context) error {
// Simulate some processing time
// (In real tests, avoid time.Sleep)
return c.String(200, "OK")
})
req := httptest.NewRequest("GET", "/test", http.NoBody)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
output := buf.String()
if !strings.Contains(output, "latency_ms=") {
t.Errorf("log should contain latency measurement, got: %s", output)
}
}
// TestGetClientIP tests client IP extraction.
func TestGetClientIP(t *testing.T) {
tests := []struct {
name string
setupReq func(*http.Request)
expectedIP string
}{
{
name: "X-Real-IP header",
setupReq: func(r *http.Request) {
r.Header.Set("X-Real-IP", "1.2.3.4")
},
expectedIP: "1.2.3.4",
},
{
name: "X-Forwarded-For single IP",
setupReq: func(r *http.Request) {
r.Header.Set("X-Forwarded-For", "5.6.7.8")
},
expectedIP: "5.6.7.8",
},
{
name: "X-Forwarded-For multiple IPs",
setupReq: func(r *http.Request) {
r.Header.Set("X-Forwarded-For", "9.10.11.12, 13.14.15.16")
},
expectedIP: "9.10.11.12",
},
{
name: "RemoteAddr with port",
setupReq: func(r *http.Request) {
r.RemoteAddr = "17.18.19.20:54321"
},
expectedIP: "17.18.19.20",
},
{
name: "X-Real-IP takes precedence",
setupReq: func(r *http.Request) {
r.Header.Set("X-Real-IP", "priority.ip")
r.Header.Set("X-Forwarded-For", "fallback.ip")
r.RemoteAddr = "final.fallback:8080"
},
expectedIP: "priority.ip",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "/", http.NoBody)
tt.setupReq(req)
ip := getClientIP(req)
if ip != tt.expectedIP {
t.Errorf("expected IP %s, got %s", tt.expectedIP, ip)
}
})
}
}
// TestCleanIP tests IP cleaning function.
func TestCleanIP(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"192.168.1.1", "192.168.1.1"},
{"192.168.1.1:8080", "192.168.1.1"},
{" 192.168.1.1 ", "192.168.1.1"},
{" 192.168.1.1:8080 ", "192.168.1.1"},
{"[2001:db8::1]", "2001:db8::1"},
{"2001:db8::1", "2001:db8::1"},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
result := cleanIP(tt.input)
if result != tt.expected {
t.Errorf("cleanIP(%q) = %q, want %q", tt.input, result, tt.expected)
}
})
}
}
// TestLogResponseWriter tests the response writer wrapper.
func TestLogResponseWriter(t *testing.T) {
t.Run("captures status code", func(t *testing.T) {
w := httptest.NewRecorder()
lrw := &logResponseWriter{ResponseWriter: w}
lrw.WriteHeader(404)
if lrw.statusCode != 404 {
t.Errorf("expected status 404, got %d", lrw.statusCode)
}
})
t.Run("captures bytes written", func(t *testing.T) {
w := httptest.NewRecorder()
lrw := &logResponseWriter{ResponseWriter: w}
data := []byte("test response body")
n, err := lrw.Write(data)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if n != len(data) {
t.Errorf("expected %d bytes written, got %d", len(data), n)
}
if lrw.bytesWritten != int64(len(data)) {
t.Errorf("expected bytesWritten %d, got %d", len(data), lrw.bytesWritten)
}
})
t.Run("defaults to 200 if WriteHeader not called", func(t *testing.T) {
w := httptest.NewRecorder()
lrw := &logResponseWriter{ResponseWriter: w, statusCode: http.StatusOK}
lrw.Write([]byte("body"))
if lrw.statusCode != 200 {
t.Errorf("expected default status 200, got %d", lrw.statusCode)
}
})
t.Run("Unwrap returns original ResponseWriter", func(t *testing.T) {
w := httptest.NewRecorder()
lrw := &logResponseWriter{ResponseWriter: w}
unwrapped := lrw.Unwrap()
if unwrapped != w {
t.Error("Unwrap() should return original ResponseWriter")
}
})
}
// TestLogger_DefaultConstructor tests that Logger() wrapper uses default configuration.
func TestLogger_DefaultConstructor(t *testing.T) {
// Logger() is a thin wrapper over LoggerWithConfig(LoggerConfig{}).
// We verify it returns a working middleware by using it with a real router.
r := fursy.New()
r.Use(Logger())
r.GET("/health", func(c *fursy.Context) error {
return c.String(http.StatusOK, "OK")
})
req := httptest.NewRequest(http.MethodGet, "/health", http.NoBody)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
if w.Body.String() != "OK" {
t.Errorf("expected body 'OK', got %q", w.Body.String())
}
}
// TestLogger_IntegrationWithGroups tests logger with route groups.
func TestLogger_IntegrationWithGroups(t *testing.T) {
var buf bytes.Buffer
logger := DefaultLogger(&buf)
r := fursy.New()
r.Use(LoggerWithConfig(LoggerConfig{
Logger: logger,
}))
api := r.Group("/api")
v1 := api.Group("/v1")
v1.GET("/users", func(c *fursy.Context) error {
return c.String(200, "users")
})
req := httptest.NewRequest("GET", "/api/v1/users", http.NoBody)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
output := buf.String()
if !strings.Contains(output, "path=/api/v1/users") {
t.Errorf("log should contain full path with group prefix, got: %s", output)
}
}
// TestLogResponseWriter_Flush tests that the logger wrapper implements http.Flusher.
func TestLogResponseWriter_Flush(t *testing.T) {
w := httptest.NewRecorder()
lrw := &logResponseWriter{
ResponseWriter: w,
statusCode: http.StatusOK,
}
// Verify Flusher interface.
flusher, ok := interface{}(lrw).(http.Flusher)
if !ok {
t.Fatal("logResponseWriter should implement http.Flusher")
}
flusher.Flush()
if !w.Flushed {
t.Error("Flush should delegate to underlying ResponseWriter")
}
}
// TestLogResponseWriter_Unwrap tests the Unwrap method.
func TestLogResponseWriter_Unwrap(t *testing.T) {
w := httptest.NewRecorder()
lrw := &logResponseWriter{
ResponseWriter: w,
statusCode: http.StatusOK,
}
unwrapped := lrw.Unwrap()
if unwrapped != w {
t.Error("Unwrap should return the original ResponseWriter")
}
}