This repository has been archived by the owner on Apr 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover_test.go
84 lines (75 loc) · 2.03 KB
/
recover_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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package recover
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/vicanso/elton"
)
func TestRecover(t *testing.T) {
t.Run("response text", func(t *testing.T) {
assert := assert.New(t)
var ctx *elton.Context
e := elton.New()
e.Use(New())
e.GET("/", func(c *elton.Context) error {
ctx = c
panic("abc")
})
req := httptest.NewRequest("GET", "https://aslant.site/", nil)
resp := httptest.NewRecorder()
keys := []string{
elton.HeaderETag,
elton.HeaderLastModified,
elton.HeaderContentEncoding,
elton.HeaderContentLength,
}
for _, key := range keys {
resp.Header().Set(key, "a")
}
catchError := false
e.OnError(func(_ *elton.Context, _ error) {
catchError = true
})
e.ServeHTTP(resp, req)
assert.Equal(resp.Code, http.StatusInternalServerError)
assert.Equal(resp.Body.String(), "category=elton-recover, message=abc")
assert.True(ctx.Committed)
assert.True(catchError)
for _, key := range keys {
assert.Empty(ctx.GetHeader(key), "header should be reseted")
}
})
t.Run("response json", func(t *testing.T) {
assert := assert.New(t)
e := elton.New()
e.Use(New())
e.GET("/", func(c *elton.Context) error {
panic("abc")
})
req := httptest.NewRequest("GET", "https://aslant.site/", nil)
req.Header.Set("Accept", "application/json, text/plain, */*")
resp := httptest.NewRecorder()
e.ServeHTTP(resp, req)
assert.Equal(500, resp.Code)
assert.Equal(elton.MIMEApplicationJSON, resp.Header().Get(elton.HeaderContentType))
assert.NotEmpty(resp.Body.Bytes())
})
}
// https://stackoverflow.com/questions/50120427/fail-unit-tests-if-coverage-is-below-certain-percentage
func TestMain(m *testing.M) {
// call flag.Parse() here if TestMain uses flags
rc := m.Run()
// rc 0 means we've passed,
// and CoverMode will be non empty if run with -cover
if rc == 0 && testing.CoverMode() != "" {
c := testing.Coverage()
if c < 0.9 {
fmt.Println("Tests passed but coverage failed at", c)
rc = -1
}
}
os.Exit(rc)
}