1 parent
568e516b1a
commit
7ea7b153a2
10 files changed
+595
-46
No files matched your search
@@ -0,0 +1,56 @@
|
||||
package recovery
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type sensitivePanic struct{}
|
||||
|
||||
func (sensitivePanic) String() string { panic("formatter must not be invoked") }
|
||||
|
||||
func TestCustomRecoveryAndCommittedStream(t *testing.T) {
|
||||
for _, stream := range []bool{false, true} {
|
||||
reports, responses := 0, 0
|
||||
engine := gin.New()
|
||||
engine.Use(New(Options{Report: func(_ *gin.Context, incident Incident) {
|
||||
reports++
|
||||
if !strings.Contains(incident.Type, "sensitivePanic") || !strings.Contains(string(incident.Stack), "TestCustomRecoveryAndCommittedStream") {
|
||||
t.Fatal("missing diagnostic")
|
||||
}
|
||||
}, Respond: func(ctx *gin.Context) { responses++; ctx.JSON(503, gin.H{"message": "safe"}) }}))
|
||||
engine.GET("/panic", func(ctx *gin.Context) {
|
||||
if stream {
|
||||
ctx.SSEvent("ready", "hello")
|
||||
ctx.Writer.Flush()
|
||||
}
|
||||
panic(sensitivePanic{})
|
||||
}, func(*gin.Context) { t.Fatal("continued after panic") })
|
||||
out := httptest.NewRecorder()
|
||||
engine.ServeHTTP(out, httptest.NewRequest("GET", "/panic", nil))
|
||||
if reports != 1 {
|
||||
t.Fatalf("reports=%d", reports)
|
||||
}
|
||||
if stream {
|
||||
if responses != 0 || out.Code != 200 || !out.Flushed || strings.Contains(out.Body.String(), "safe") {
|
||||
t.Fatal("stream rewritten")
|
||||
}
|
||||
} else if responses != 1 || out.Code != 503 {
|
||||
t.Fatal("custom response missing")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultRecoveryHidesValue(t *testing.T) {
|
||||
engine := gin.New()
|
||||
engine.Use(New(Options{}))
|
||||
engine.GET("/panic", func(*gin.Context) { panic("private-token") })
|
||||
out := httptest.NewRecorder()
|
||||
engine.ServeHTTP(out, httptest.NewRequest("GET", "/panic", nil))
|
||||
if out.Code != 500 || strings.Contains(out.Body.String(), "private-token") {
|
||||
t.Fatalf("unsafe default: %s", out.Body.String())
|
||||
}
|
||||
}
|
||||