gin/recovery_test.go

65 lines
1.6 KiB
Go
Raw Normal View History

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"
"net/http"
2014-08-08 16:50:52 +04:00
"testing"
2015-04-08 14:30:17 +03:00
"github.com/stretchr/testify/assert"
2014-08-08 16:50:52 +04:00
)
// TestPanicInHandler assert that panic has been recovered.
func TestPanicInHandler(t *testing.T) {
2015-04-08 14:30:17 +03:00
buffer := new(bytes.Buffer)
router := New()
2015-05-12 16:22:13 +03:00
router.Use(RecoveryWithWriter(buffer))
2015-04-08 14:30:17 +03:00
router.GET("/recovery", func(_ *Context) {
2015-04-08 03:58:35 +03:00
panic("Oupps, Houston, we have a problem")
2014-08-08 16:50:52 +04:00
})
// RUN
2015-04-08 14:30:17 +03:00
w := performRequest(router, "GET", "/recovery")
// TEST
assert.Equal(t, http.StatusInternalServerError, w.Code)
2016-01-26 21:28:41 +03:00
assert.Contains(t, buffer.String(), "GET /recovery")
assert.Contains(t, buffer.String(), "Oupps, Houston, we have a problem")
2015-04-08 14:30:17 +03:00
assert.Contains(t, buffer.String(), "TestPanicInHandler")
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) {
2015-04-08 14:30:17 +03:00
router := New()
2015-05-12 16:22:13 +03:00
router.Use(RecoveryWithWriter(nil))
2015-04-08 14:30:17 +03:00
router.GET("/recovery", func(c *Context) {
c.AbortWithStatus(http.StatusBadRequest)
2015-04-08 03:58:35 +03:00
panic("Oupps, Houston, we have a problem")
2014-08-11 14:37:35 +04:00
})
// RUN
2015-04-08 14:30:17 +03:00
w := performRequest(router, "GET", "/recovery")
// TEST
assert.Equal(t, http.StatusBadRequest, w.Code)
2014-08-08 16:50:52 +04:00
}
func TestSource(t *testing.T) {
bs := source(nil, 0)
assert.Equal(t, []byte("???"), bs)
in := [][]byte{
[]byte("Hello world."),
[]byte("Hi, gin.."),
}
bs = source(in, 10)
assert.Equal(t, []byte("???"), bs)
bs = source(in, 1)
assert.Equal(t, []byte("Hello world."), bs)
}
func TestFunction(t *testing.T) {
bs := function(1)
assert.Equal(t, []byte("???"), bs)
}