recovery_test.go
This file
Path
recovery_test.go
413 lines · 11.7 KiB · Go
Last changed by
fix(recovery): record recovered panics in c.Errors (#4698)DadaVinqibefore adoption4a3eb31
History of this fileTake it
The walk stopped after 200 commits: lines older than cf32d2d point at it.
chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 1–7why, one step back1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (fix(recovery): record recovered panics in c.Errors (#4698)DadaVinqibefore adoption4a3eb31
line 8why, one step back8 "errors"chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 9–25why, one step back9 "net"10 "net/http"11 "os"12 "strings"13 "syscall"14 "testing"1516 "github.com/stretchr/testify/assert"17)1819func TestPanicClean(t *testing.T) {20 buffer := new(strings.Builder)21 router := New()22 password := "my-super-secret-password"23 router.Use(RecoveryWithWriter(buffer))24 router.GET("/recovery", func(c *Context) {25 c.AbortWithStatus(http.StatusBadRequest)fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 26why, one step back26 panic("Oops, Houston, we have a problem")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 27–55why, one step back27 })28 // RUN29 w := PerformRequest(router, http.MethodGet, "/recovery",30 header{31 Key: "Host",32 Value: "www.google.com",33 },34 header{35 Key: "Authorization",36 Value: "Bearer " + password,37 },38 header{39 Key: "Content-Type",40 Value: "application/json",41 },42 )43 // TEST44 assert.Equal(t, http.StatusBadRequest, w.Code)4546 // Check the buffer does not have the secret key47 assert.NotContains(t, buffer.String(), password)48}4950// TestPanicInHandler assert that panic has been recovered.51func TestPanicInHandler(t *testing.T) {52 buffer := new(strings.Builder)53 router := New()54 router.Use(RecoveryWithWriter(buffer))55 router.GET("/recovery", func(_ *Context) {fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 56why, one step back56 panic("Oops, Houston, we have a problem")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 57–62why, one step back57 })58 // RUN59 w := PerformRequest(router, http.MethodGet, "/recovery")60 // TEST61 assert.Equal(t, http.StatusInternalServerError, w.Code)62 assert.Contains(t, buffer.String(), "panic recovered")fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 63why, one step back63 assert.Contains(t, buffer.String(), "Oops, Houston, we have a problem")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 64–83why, one step back64 assert.Contains(t, buffer.String(), t.Name())65 assert.NotContains(t, buffer.String(), "GET /recovery")6667 // Debug mode prints the request68 SetMode(DebugMode)69 // RUN70 w = PerformRequest(router, http.MethodGet, "/recovery")71 // TEST72 assert.Equal(t, http.StatusInternalServerError, w.Code)73 assert.Contains(t, buffer.String(), "GET /recovery")7475 SetMode(TestMode)76}7778// TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.79func TestPanicWithAbort(t *testing.T) {80 router := New()81 router.Use(RecoveryWithWriter(nil))82 router.GET("/recovery", func(c *Context) {83 c.AbortWithStatus(http.StatusBadRequest)fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 84why, one step back84 panic("Oops, Houston, we have a problem")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 85–101why, one step back85 })86 // RUN87 w := PerformRequest(router, http.MethodGet, "/recovery")88 // TEST89 assert.Equal(t, http.StatusBadRequest, w.Code)90}9192func TestFunction(t *testing.T) {93 bs := function(1)94 assert.Equal(t, dunno, bs)95}9697// TestPanicWithBrokenPipe asserts that recovery specifically handles98// writing responses to broken pipes99func TestPanicWithBrokenPipe(t *testing.T) {100 const expectCode = 204101refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d
lines 102–104why, one step back102 expectErrnos := []syscall.Errno{103 syscall.EPIPE,104 syscall.ECONNRESET,chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 105–106why, one step back105 }106refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d
lines 107–108why, one step back107 for _, errno := range expectErrnos {108 t.Run("Recovery from "+errno.Error(), func(t *testing.T) {chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 109–125why, one step back109 var buf strings.Builder110111 router := New()112 router.Use(RecoveryWithWriter(&buf))113 router.GET("/recovery", func(c *Context) {114 // Start writing response115 c.Header("X-Test", "Value")116 c.Status(expectCode)117118 // Oops. Client connection closed119 e := &net.OpError{Err: &os.SyscallError{Err: errno}}120 panic(e)121 })122 // RUN123 w := PerformRequest(router, http.MethodGet, "/recovery")124 // TEST125 assert.Equal(t, expectCode, w.Code)refactor(recovery): smart error comparison (#4142)OHZEKI Naokibefore adoption3ab698d
lines 126–127why, one step back126 assert.Contains(t, strings.ToLower(buf.String()), errno.Error())127 assert.NotContains(t, strings.ToLower(buf.String()), "[Recovery]")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 128–131why, one step back128 })129 }130}131fix(recover): suppress http.ErrAbortHandler in recover (#4336)Yilong Libefore adoption63dd3e6
lines 132–153why, one step back132// TestPanicWithAbortHandler asserts that recovery handles http.ErrAbortHandler as broken pipe133func TestPanicWithAbortHandler(t *testing.T) {134 const expectCode = 204135136 var buf strings.Builder137 router := New()138 router.Use(RecoveryWithWriter(&buf))139 router.GET("/recovery", func(c *Context) {140 // Start writing response141 c.Header("X-Test", "Value")142 c.Status(expectCode)143144 // Panic with ErrAbortHandler which should be treated as broken pipe145 panic(http.ErrAbortHandler)146 })147 // RUN148 w := PerformRequest(router, http.MethodGet, "/recovery")149 // TEST150 assert.Equal(t, expectCode, w.Code)151 out := buf.String()152 assert.Contains(t, out, "net/http: abort Handler")153 assert.NotContains(t, out, "panic recovered")fix(recovery): record recovered panics in c.Errors (#4698)DadaVinqibefore adoption4a3eb31
lines 154–196why, one step back154}155156func TestPanicInHandlerRecordsError(t *testing.T) {157 tests := []struct {158 name string159 recoveredErr any160 expectedErr string161 }{162 {163 name: "string panic",164 recoveredErr: "Oops, Houston, we have a problem",165 expectedErr: "Oops, Houston, we have a problem",166 },167 {168 name: "error panic",169 recoveredErr: errors.New("recovered error"),170 expectedErr: "recovered error",171 },172 }173174 for _, tt := range tests {175 t.Run(tt.name, func(t *testing.T) {176 router := New()177178 var recoveredErrors errorMsgs179 router.Use(func(c *Context) {180 c.Next()181 recoveredErrors = c.Errors182 })183 router.Use(RecoveryWithWriter(nil))184 router.GET("/recovery", func(_ *Context) {185 panic(tt.recoveredErr)186 })187188 w := PerformRequest(router, http.MethodGet, "/recovery")189190 assert.Equal(t, http.StatusInternalServerError, w.Code)191 if assert.Len(t, recoveredErrors, 1) {192 assert.EqualError(t, recoveredErrors[0], tt.expectedErr)193 assert.Equal(t, ErrorTypePrivate, recoveredErrors[0].Type)194 }195 })196 }fix(recover): suppress http.ErrAbortHandler in recover (#4336)Yilong Libefore adoption63dd3e6
lines 197–198why, one step back197}198chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 199–208why, one step back199func TestCustomRecoveryWithWriter(t *testing.T) {200 errBuffer := new(strings.Builder)201 buffer := new(strings.Builder)202 router := New()203 handleRecovery := func(c *Context, err any) {204 errBuffer.WriteString(err.(string))205 c.AbortWithStatus(http.StatusBadRequest)206 }207 router.Use(CustomRecoveryWithWriter(buffer, handleRecovery))208 router.GET("/recovery", func(_ *Context) {fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 209why, one step back209 panic("Oops, Houston, we have a problem")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 210–215why, one step back210 })211 // RUN212 w := PerformRequest(router, http.MethodGet, "/recovery")213 // TEST214 assert.Equal(t, http.StatusBadRequest, w.Code)215 assert.Contains(t, buffer.String(), "panic recovered")fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 216why, one step back216 assert.Contains(t, buffer.String(), "Oops, Houston, we have a problem")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 217–227why, one step back217 assert.Contains(t, buffer.String(), t.Name())218 assert.NotContains(t, buffer.String(), "GET /recovery")219220 // Debug mode prints the request221 SetMode(DebugMode)222 // RUN223 w = PerformRequest(router, http.MethodGet, "/recovery")224 // TEST225 assert.Equal(t, http.StatusBadRequest, w.Code)226 assert.Contains(t, buffer.String(), "GET /recovery")227fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 228why, one step back228 assert.Equal(t, strings.Repeat("Oops, Houston, we have a problem", 2), errBuffer.String())chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 229–243why, one step back229230 SetMode(TestMode)231}232233func TestCustomRecovery(t *testing.T) {234 errBuffer := new(strings.Builder)235 buffer := new(strings.Builder)236 router := New()237 DefaultErrorWriter = buffer238 handleRecovery := func(c *Context, err any) {239 errBuffer.WriteString(err.(string))240 c.AbortWithStatus(http.StatusBadRequest)241 }242 router.Use(CustomRecovery(handleRecovery))243 router.GET("/recovery", func(_ *Context) {fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 244why, one step back244 panic("Oops, Houston, we have a problem")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 245–250why, one step back245 })246 // RUN247 w := PerformRequest(router, http.MethodGet, "/recovery")248 // TEST249 assert.Equal(t, http.StatusBadRequest, w.Code)250 assert.Contains(t, buffer.String(), "panic recovered")fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 251why, one step back251 assert.Contains(t, buffer.String(), "Oops, Houston, we have a problem")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 252–262why, one step back252 assert.Contains(t, buffer.String(), t.Name())253 assert.NotContains(t, buffer.String(), "GET /recovery")254255 // Debug mode prints the request256 SetMode(DebugMode)257 // RUN258 w = PerformRequest(router, http.MethodGet, "/recovery")259 // TEST260 assert.Equal(t, http.StatusBadRequest, w.Code)261 assert.Contains(t, buffer.String(), "GET /recovery")262fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 263why, one step back263 assert.Equal(t, strings.Repeat("Oops, Houston, we have a problem", 2), errBuffer.String())chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 264–278why, one step back264265 SetMode(TestMode)266}267268func TestRecoveryWithWriterWithCustomRecovery(t *testing.T) {269 errBuffer := new(strings.Builder)270 buffer := new(strings.Builder)271 router := New()272 DefaultErrorWriter = buffer273 handleRecovery := func(c *Context, err any) {274 errBuffer.WriteString(err.(string))275 c.AbortWithStatus(http.StatusBadRequest)276 }277 router.Use(RecoveryWithWriter(DefaultErrorWriter, handleRecovery))278 router.GET("/recovery", func(_ *Context) {fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 279why, one step back279 panic("Oops, Houston, we have a problem")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 280–285why, one step back280 })281 // RUN282 w := PerformRequest(router, http.MethodGet, "/recovery")283 // TEST284 assert.Equal(t, http.StatusBadRequest, w.Code)285 assert.Contains(t, buffer.String(), "panic recovered")fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 286why, one step back286 assert.Contains(t, buffer.String(), "Oops, Houston, we have a problem")chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 287–297why, one step back287 assert.Contains(t, buffer.String(), t.Name())288 assert.NotContains(t, buffer.String(), "GET /recovery")289290 // Debug mode prints the request291 SetMode(DebugMode)292 // RUN293 w = PerformRequest(router, http.MethodGet, "/recovery")294 // TEST295 assert.Equal(t, http.StatusBadRequest, w.Code)296 assert.Contains(t, buffer.String(), "GET /recovery")297fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37
line 298why, one step back298 assert.Equal(t, strings.Repeat("Oops, Houston, we have a problem", 2), errBuffer.String())chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
lines 299–300why, one step back299300 SetMode(TestMode)perf(recovery): optimize the log output of CustomRecoveryWithWriter (#4258)Namebefore adoption45b805f
lines 301–361why, one step back301}302303func TestSecureRequestDump(t *testing.T) {304 tests := []struct {305 name string306 req *http.Request307 wantContains string308 wantNotContain string309 }{310 {311 name: "Authorization header standard case",312 req: func() *http.Request {313 r, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)314 r.Header.Set("Authorization", "Bearer secret-token")315 return r316 }(),317 wantContains: "Authorization: *",318 wantNotContain: "Bearer secret-token",319 },320 {321 name: "authorization header lowercase",322 req: func() *http.Request {323 r, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)324 r.Header.Set("authorization", "some-secret")325 return r326 }(),327 wantContains: "Authorization: *",328 wantNotContain: "some-secret",329 },330 {331 name: "Authorization header mixed case",332 req: func() *http.Request {333 r, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)334 r.Header.Set("AuThOrIzAtIoN", "token123")335 return r336 }(),337 wantContains: "Authorization: *",338 wantNotContain: "token123",339 },340 {341 name: "No Authorization header",342 req: func() *http.Request {343 r, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)344 r.Header.Set("Content-Type", "application/json")345 return r346 }(),347 wantContains: "",348 wantNotContain: "Authorization: *",349 },350 }351352 for _, tt := range tests {353 t.Run(tt.name, func(t *testing.T) {354 result := secureRequestDump(tt.req)355 if tt.wantContains != "" && !strings.Contains(result, tt.wantContains) {356 t.Errorf("maskHeaders() = %q, want contains %q", result, tt.wantContains)357 }358 if tt.wantNotContain != "" && strings.Contains(result, tt.wantNotContain) {359 t.Errorf("maskHeaders() = %q, want NOT contain %q", result, tt.wantNotContain)360 }361 })perf(recovery): optimize line reading in stack function (#4466)Namebefore adoption64a6ed9
lines 362–411why, one step back362 }363}364365// TestReadNthLine tests the readNthLine function with various scenarios.366func TestReadNthLine(t *testing.T) {367 // Create a temporary test file368 testContent := "line 0 \n line 1 \nline 2 \nline 3 \nline 4"369 tempFile, err := os.CreateTemp("", "testfile*.txt")370 if err != nil {371 t.Fatal(err)372 }373 defer os.Remove(tempFile.Name())374375 // Write test content to the temporary file376 if _, err := tempFile.WriteString(testContent); err != nil {377 t.Fatal(err)378 }379 if err := tempFile.Close(); err != nil {380 t.Fatal(err)381 }382383 // Test cases384 tests := []struct {385 name string386 lineNum int387 fileName string388 want string389 wantErr bool390 }{391 {name: "Read first line", lineNum: 0, fileName: tempFile.Name(), want: "line 0", wantErr: false},392 {name: "Read middle line", lineNum: 2, fileName: tempFile.Name(), want: "line 2", wantErr: false},393 {name: "Read last line", lineNum: 4, fileName: tempFile.Name(), want: "line 4", wantErr: false},394 {name: "Line number exceeds file length", lineNum: 10, fileName: tempFile.Name(), want: "", wantErr: false},395 {name: "Negative line number", lineNum: -1, fileName: tempFile.Name(), want: "", wantErr: false},396 {name: "Non-existent file", lineNum: 1, fileName: "/non/existent/file.txt", want: "", wantErr: true},397 }398399 for _, tt := range tests {400 t.Run(tt.name, func(t *testing.T) {401 got, err := readNthLine(tt.fileName, tt.lineNum)402 assert.Equal(t, tt.wantErr, err != nil)403 assert.Equal(t, tt.want, got)404 })405 }406}407408func BenchmarkStack(b *testing.B) {409 b.ReportAllocs()410 for b.Loop() {411 _ = stack(stackSkip)perf(recovery): optimize the log output of CustomRecoveryWithWriter (#4258)Namebefore adoption45b805f
line 412why, one step back412 }chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d
line 413why, one step back413}