-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware_test.go
95 lines (74 loc) · 2.17 KB
/
middleware_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
92
93
94
95
package errornotifier_test
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/theplant/appkit/errornotifier"
au "github.com/theplant/appkit/errornotifier/utils"
)
var errHandlerException = errors.New("panic on handler")
func TestRecoverMiddleware(t *testing.T) {
bufferNotifier := &au.BufferNotifier{}
server := newRecoverTestServer(bufferNotifier)
defer func() {
server.Close()
}()
if len(bufferNotifier.Notices) != 0 {
t.Fatalf("Notices must be empty.")
}
_, err := http.Get(server.URL + "/recover")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(bufferNotifier.Notices) != 1 {
t.Fatalf("Unexpected notices length, got %d.", len(bufferNotifier.Notices))
}
if bufferNotifier.Notices[0].Error != errHandlerException {
t.Fatalf("Got unexpected error: %v ", bufferNotifier.Notices[0].Error)
}
if bufferNotifier.Notices[0].Context == nil {
t.Fatalf("Context shouldn't be nil")
}
}
// newRecoverTestServer prepares a test HTTP server that has the Recover
// middleware configured at `/recover`
func newRecoverTestServer(n errornotifier.Notifier) *httptest.Server {
// Catch handler panics so that test can continue.
clearPanics := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
recover()
}()
h.ServeHTTP(w, r)
})
}
mux := http.NewServeMux()
mux.HandleFunc("/recover", func(w http.ResponseWriter, r *http.Request) {
panic(errHandlerException)
})
// Recover middleware is executed first.
server := httptest.NewServer(clearPanics(errornotifier.Recover(n)(mux)))
return server
}
func ExampleNotifyOnPanic() {
bufferNotifier := &au.BufferNotifier{}
// return nil => Do nothing
err := errornotifier.NotifyOnPanic(bufferNotifier, nil, func() {
fmt.Println("do nothing")
})
fmt.Printf("%v %d\n", err, len(bufferNotifier.Notices))
// panic in func => return panic error
err = errornotifier.NotifyOnPanic(bufferNotifier, nil, func() {
panicErr := "panic"
fmt.Println(panicErr)
panic(panicErr)
})
fmt.Printf("%v %d\n", err, len(bufferNotifier.Notices))
// Output:
// do nothing
// <nil> 0
// panic
// panic 1
}