2014-08-29 21:49:50 +04:00
|
|
|
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2014-08-08 16:50:52 +04:00
|
|
|
package gin
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
// TestPanicInHandler assert that panic has been recovered.
|
|
|
|
func TestPanicInHandler(t *testing.T) {
|
2014-08-18 21:48:48 +04:00
|
|
|
// SETUP
|
|
|
|
log.SetOutput(bytes.NewBuffer(nil)) // Disable panic logs for testing
|
|
|
|
r := New()
|
|
|
|
r.Use(Recovery())
|
2014-08-11 14:37:35 +04:00
|
|
|
r.GET("/recovery", func(_ *Context) {
|
2015-03-23 07:50:10 +03:00
|
|
|
log.Panic("Oupps, Houston, we have a problem")
|
2014-08-08 16:50:52 +04:00
|
|
|
})
|
|
|
|
|
2014-08-18 21:48:48 +04:00
|
|
|
// RUN
|
|
|
|
w := PerformRequest(r, "GET", "/recovery")
|
2014-08-08 16:50:52 +04:00
|
|
|
|
|
|
|
// restore logging
|
|
|
|
log.SetOutput(os.Stderr)
|
|
|
|
|
|
|
|
if w.Code != 500 {
|
2015-03-23 06:41:29 +03:00
|
|
|
t.Errorf("Response code should be Internal Server Error, was: %d", w.Code)
|
2014-08-08 16:50:52 +04:00
|
|
|
}
|
2014-08-11 14:37:35 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// TestPanicWithAbort assert that panic has been recovered even if context.Abort was used.
|
|
|
|
func TestPanicWithAbort(t *testing.T) {
|
2014-08-18 21:48:48 +04:00
|
|
|
// SETUP
|
2014-08-11 14:37:35 +04:00
|
|
|
log.SetOutput(bytes.NewBuffer(nil))
|
2014-08-18 21:48:48 +04:00
|
|
|
r := New()
|
|
|
|
r.Use(Recovery())
|
2014-08-11 14:37:35 +04:00
|
|
|
r.GET("/recovery", func(c *Context) {
|
2014-10-08 23:37:26 +04:00
|
|
|
c.AbortWithStatus(400)
|
2015-03-23 07:50:10 +03:00
|
|
|
log.Panic("Oupps, Houston, we have a problem")
|
2014-08-11 14:37:35 +04:00
|
|
|
})
|
|
|
|
|
2014-08-18 21:48:48 +04:00
|
|
|
// RUN
|
|
|
|
w := PerformRequest(r, "GET", "/recovery")
|
2014-08-11 14:37:35 +04:00
|
|
|
|
|
|
|
// restore logging
|
|
|
|
log.SetOutput(os.Stderr)
|
|
|
|
|
2014-08-18 21:48:48 +04:00
|
|
|
// TEST
|
|
|
|
if w.Code != 500 {
|
2015-03-23 06:41:29 +03:00
|
|
|
t.Errorf("Response code should be Bad request, was: %d", w.Code)
|
2014-08-11 14:37:35 +04:00
|
|
|
}
|
2014-08-08 16:50:52 +04:00
|
|
|
}
|