-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_test.go
91 lines (81 loc) · 2.29 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
package httperror
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
)
func TestMiddleware(t *testing.T) {
tests := []struct {
name string
panicValue interface{} // Value to panic with
expectedCode int // Expected HTTP status code
expectedBody string // Expected response body
}{
{
name: "OK",
panicValue: nil,
expectedCode: http.StatusOK,
expectedBody: "",
},
{
name: "Internal Error",
panicValue: errors.New("test error"),
expectedCode: http.StatusInternalServerError,
expectedBody: `{"message":"an error occurred","code":"INTERNAL_SERVER_ERROR"}`,
},
{
name: "Error with httperror.Error",
panicValue: NewBadRequest("bad request"),
expectedCode: http.StatusBadRequest,
expectedBody: `{"message":"bad request"}`,
},
{
name: "Error with text",
panicValue: "oops",
expectedCode: http.StatusInternalServerError,
expectedBody: `{"message":"an error occurred","code":"INTERNAL_SERVER_ERROR"}`,
},
{
name: "Abort",
panicValue: http.ErrAbortHandler,
expectedCode: http.StatusOK,
expectedBody: "",
},
}
for _, tt := range tests {
dummyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tt.panicValue != nil {
panic(tt.panicValue)
}
})
t.Run(tt.name, func(t *testing.T) {
// Create a recorder to capture the response
recorder := httptest.NewRecorder()
// Create a request to pass to the middleware
req := httptest.NewRequest("GET", "/", nil)
// Set up the middleware
middleware := Middleware(dummyHandler)
// Execute the middleware with the panic value
func() {
defer func() {
if rvr := recover(); rvr != nil {
if rvr != http.ErrAbortHandler {
t.Errorf("unexpected panic value: %v", rvr)
}
}
}()
req = httptest.NewRequest("GET", "/", nil) // Reset request after panic
middleware.ServeHTTP(recorder, req)
}()
// Check the response status code
if recorder.Code != tt.expectedCode {
t.Errorf("expected status code %d, got %d", tt.expectedCode, recorder.Code)
}
// Check the response body
if recorder.Body.String() != tt.expectedBody {
t.Errorf("expected body %s, got %s", tt.expectedBody, recorder.Body.String())
}
})
}
}