-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpanic_test.go
91 lines (75 loc) · 1.98 KB
/
panic_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
85
86
87
88
89
90
91
package gohm_test
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/karrick/gohm"
)
func TestAllowPanicsFalse(t *testing.T) {
recorder := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/some/url", nil)
handler := gohm.New(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic("test error")
}), gohm.Config{})
var panicked bool
served := make(chan struct{})
go func() {
defer func() {
if r := recover(); r != nil {
panicked = true
}
close(served)
}()
handler.ServeHTTP(recorder, request)
}()
<-served
resp := recorder.Result()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if got, want := panicked, false; got != want {
t.Errorf("GOT: %v; WANT: %v", got, want)
}
if got, want := resp.StatusCode, http.StatusInternalServerError; got != want {
t.Errorf("GOT: %v; WANT: %v", got, want)
}
if got, want := string(body), "500 Internal Server Error"; !strings.Contains(got, want) {
t.Errorf("GOT: %v; WANT: %v", got, want)
}
}
func TestAllowPanicsTrue(t *testing.T) {
recorder := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/some/url", nil)
handler := gohm.New(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic("test error")
}), gohm.Config{AllowPanics: true})
var panicked bool
served := make(chan struct{})
go func() {
defer func() {
if r := recover(); r != nil {
panicked = true
}
close(served)
}()
handler.ServeHTTP(recorder, request)
}()
<-served
resp := recorder.Result()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if got, want := panicked, true; got != want {
t.Errorf("GOT: %v; WANT: %v", got, want)
}
// NOTE: Cannot verify resp.StatusCode because httptest.ResponseRecorder
// initializes StatusCode to http.StatusOK if not written, even though it is
// never set.
if got, want := string(body), ""; got != want {
t.Errorf("GOT: %v; WANT: %v", got, want)
}
}