-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpanicMiddleware_test.go
73 lines (59 loc) · 2 KB
/
panicMiddleware_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
package goCatch
import (
"fmt"
"github.com/matthewjamesboyle/go-panic-catch/catchers"
"net/http"
"net/http/httptest"
"testing"
)
func TestCatchPanicMiddleware(t *testing.T) {
t.Run("Calls next successfully with no panic", func(t *testing.T) {
fn := func(writer http.ResponseWriter, req *http.Request) {
writer.WriteHeader(http.StatusTeapot)
writer.Write([]byte("some-string"))
}
req := httptest.NewRequest("GET", "/aPath", nil)
w := httptest.NewRecorder()
log := catchers.Log{}
PanicMiddleware(log, "", http.HandlerFunc(fn)).ServeHTTP(w, req)
if w.Code != http.StatusTeapot {
t.Fatal(fmt.Sprintf("Expected %d, but got %d", http.StatusTeapot, w.Code))
}
if w.Body.String() != "some-string" {
t.Fatal(fmt.Sprintf("Expected %s, but got %s", "some-string", w.Body.String()))
}
})
t.Run("Catches panic if next panics", func(t *testing.T) {
fn := func(writer http.ResponseWriter, req *http.Request) {
panic("ut oh")
}
req := httptest.NewRequest("GET", "/aPath", nil)
w := httptest.NewRecorder()
log := catchers.Log{}
PanicMiddleware(log, "", http.HandlerFunc(fn)).ServeHTTP(w, req)
})
t.Run("server returns a 500 if next panics", func(t *testing.T) {
fn := func(writer http.ResponseWriter, req *http.Request) {
panic("ut oh")
}
req := httptest.NewRequest("GET", "/aPath", nil)
w := httptest.NewRecorder()
log := catchers.Log{}
PanicMiddleware(log, "", http.HandlerFunc(fn)).ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("Expected to get a 500, but got %d", w.Code)
}
})
// Todo: add a webhook url below and run this test to watch the panic appear in slack :)
//t.Run("test slack handler", func(t *testing.T) {
// fn := func(writer http.ResponseWriter, req *http.Request) {
// panic("ut oh")
// }
//
// req := httptest.NewRequest("GET", "/aPath", nil)
// w := httptest.NewRecorder()
// slack := catchers.NewSlack("")
// PanicMiddleware(*slack, "you just panicked!", http.HandlerFunc(fn)).ServeHTTP(w, req)
//
//})
}