-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecovery_test.go
64 lines (48 loc) · 1.43 KB
/
recovery_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package middlewares
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"github.com/mojixcoder/kid"
"github.com/stretchr/testify/assert"
)
var flag bool
var recoveryHandler kid.HandlerFunc = func(c *kid.Context) {
panic("err")
}
func TestNewRecoveryWithConfig(t *testing.T) {
k := kid.New()
var buf bytes.Buffer
recovery := NewRecoveryWithConfig(RecoveryConfig{LogRecovers: true, Writer: &buf})
ctx := k.NewContext(nil, httptest.NewRecorder())
recovery(recoveryHandler)(ctx)
assert.Equal(t, "[RECOVERY] panic recovered: err\n", buf.String())
buf.Reset()
recovery = NewRecoveryWithConfig(RecoveryConfig{PrintStacktrace: true, Writer: &buf})
ctx = k.NewContext(nil, httptest.NewRecorder())
recovery(recoveryHandler)(ctx)
assert.NotEmpty(t, buf.String())
buf.Reset()
k.ApplyOptions(kid.WithDebug(false))
recovery(recoveryHandler)(ctx)
assert.Empty(t, buf.String())
buf.Reset()
recovery = NewRecoveryWithConfig(RecoveryConfig{
OnRecovery: func(c *kid.Context, err any) {
flag = true
},
})
ctx = k.NewContext(nil, httptest.NewRecorder())
recovery(recoveryHandler)(ctx)
assert.True(t, flag)
}
func TestNewRecovery(t *testing.T) {
k := kid.New()
recovery := NewRecovery()
res := httptest.NewRecorder()
ctx := k.NewContext(nil, res)
recovery(recoveryHandler)(ctx)
assert.Equal(t, res.Code, http.StatusInternalServerError)
assert.Equal(t, "{\"message\":\"Internal Server Error\"}\n", res.Body.String())
}