gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/handlers/recovery_test.go (about) 1 package handlers 2 3 import ( 4 "bytes" 5 "log" 6 "strings" 7 "testing" 8 9 http "gitee.com/ks-custle/core-gm/gmhttp" 10 "gitee.com/ks-custle/core-gm/gmhttp/httptest" 11 ) 12 13 func TestRecoveryLoggerWithDefaultOptions(t *testing.T) { 14 var buf bytes.Buffer 15 log.SetOutput(&buf) 16 17 handler := RecoveryHandler() 18 handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 19 panic("Unexpected error!") 20 }) 21 22 recovery := handler(handlerFunc) 23 recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf")) 24 25 if !strings.Contains(buf.String(), "Unexpected error!") { 26 t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "Unexpected error!") 27 } 28 } 29 30 func TestRecoveryLoggerWithCustomLogger(t *testing.T) { 31 var buf bytes.Buffer 32 var logger = log.New(&buf, "", log.LstdFlags) 33 34 handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 35 panic("Unexpected error!") 36 }) 37 38 t.Run("Without print stack", func(t *testing.T) { 39 handler := RecoveryHandler(RecoveryLogger(logger), PrintRecoveryStack(false)) 40 41 recovery := handler(handlerFunc) 42 recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf")) 43 44 if !strings.Contains(buf.String(), "Unexpected error!") { 45 t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "Unexpected error!") 46 } 47 }) 48 49 t.Run("With print stack enabled", func(t *testing.T) { 50 handler := RecoveryHandler(RecoveryLogger(logger), PrintRecoveryStack(true)) 51 52 recovery := handler(handlerFunc) 53 recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf")) 54 55 if !strings.Contains(buf.String(), "runtime/debug.Stack") { 56 t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "runtime/debug.Stack") 57 } 58 }) 59 }