-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover_test.go
74 lines (55 loc) · 1.49 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
package recover
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/suite"
)
type RecoverSuite struct {
suite.Suite
server *httptest.Server
}
func (s *RecoverSuite) SetupSuite() {
mux := http.NewServeMux()
mux.Handle("/hello", http.HandlerFunc(helloHandler))
mux.Handle("/panic", http.HandlerFunc(panicHandler))
s.server = httptest.NewServer(Handler(mux, DefaultRecoverHandler))
}
func (s *RecoverSuite) TestNotPanic() {
req, err := http.NewRequest(http.MethodGet, s.server.URL+"/hello", nil)
s.Nil(err)
res, err := sendRequest(req)
s.Nil(err)
s.Equal(http.StatusOK, res.StatusCode)
s.Equal([]byte("Hello World"), getResRawBody(res))
}
func (s *RecoverSuite) TestPanic() {
req, err := http.NewRequest(http.MethodGet, s.server.URL+"/panic", nil)
s.Nil(err)
res, err := sendRequest(req)
s.Nil(err)
s.Equal(http.StatusInternalServerError, res.StatusCode)
s.Equal([]byte("Internal Server Error"), getResRawBody(res))
}
func TestRecover(t *testing.T) {
suite.Run(t, new(RecoverSuite))
}
func helloHandler(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
res.Write([]byte("Hello World"))
}
func panicHandler(res http.ResponseWriter, req *http.Request) {
panic("test")
}
func sendRequest(req *http.Request) (*http.Response, error) {
cli := &http.Client{}
return cli.Do(req)
}
func getResRawBody(res *http.Response) []byte {
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
return bytes
}