This repository has been archived by the owner on Feb 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext_test.go
80 lines (64 loc) · 1.63 KB
/
context_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
package core
import (
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
)
func TestRecover(t *testing.T) {
statusWant := http.StatusInternalServerError
bodyWant := http.StatusText(http.StatusInternalServerError) + "\n"
hs := NewHandlersStack()
hs.Use(func(c *Context) {
panic("")
})
oldOut := os.Stdout
log.SetOutput(ioutil.Discard)
r, _ := http.NewRequest("GET", "", nil)
w := httptest.NewRecorder()
hs.ServeHTTP(w, r)
log.SetOutput(oldOut)
statusGot := w.Code
if statusWant != statusGot {
t.Errorf("status code: want %d, got %d", statusWant, statusGot)
}
bodyGot := w.Body.String()
if bodyWant != bodyGot {
t.Errorf("body: want %q, got %q", bodyWant, bodyGot)
}
}
func TestRecoverCustom(t *testing.T) {
statusWant := http.StatusServiceUnavailable
bodyWant := http.StatusText(http.StatusServiceUnavailable)
var errorWant, errorGot interface{}
errorWant = "foobar"
hs := NewHandlersStack()
hs.HandlePanic(func(c *Context) {
errorGot = c.Data["panic"]
c.ResponseWriter.WriteHeader(statusWant)
c.ResponseWriter.Write([]byte(bodyWant))
})
hs.Use(func(c *Context) {
defer c.Recover()
panic(errorWant)
})
oldOut := os.Stdout
log.SetOutput(ioutil.Discard)
r, _ := http.NewRequest("GET", "", nil)
w := httptest.NewRecorder()
hs.ServeHTTP(w, r)
log.SetOutput(oldOut)
if errorWant != errorGot {
t.Errorf("panic error: want %q, got %q", errorWant, errorGot)
}
statusGot := w.Code
if statusWant != statusGot {
t.Errorf("status code: want %d, got %d", statusWant, statusGot)
}
bodyGot := w.Body.String()
if bodyWant != bodyGot {
t.Errorf("body: want %q, got %q", bodyWant, bodyGot)
}
}