-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpx_test.go
More file actions
65 lines (52 loc) · 1.47 KB
/
httpx_test.go
File metadata and controls
65 lines (52 loc) · 1.47 KB
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
package httpx
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
)
func TestOnError_HandlerError(t *testing.T) {
var capturedErr error
adapter := &HandlerAdapter{
OnError: func(r *http.Request, err error) {
capturedErr = err
},
InternalErrs: func(w http.ResponseWriter, r *http.Request, err error) {
w.WriteHeader(http.StatusInternalServerError)
},
}
expectedErr := errors.New("handler error")
handler := adapter.Handle(func(w http.ResponseWriter, r *http.Request) error {
return expectedErr
})
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if capturedErr != expectedErr {
t.Errorf("expected error %v, got %v", expectedErr, capturedErr)
}
}
func TestOnError_Panic(t *testing.T) {
var capturedErr error
adapter := &HandlerAdapter{
OnError: func(r *http.Request, err error) {
capturedErr = err
},
InternalErrs: func(w http.ResponseWriter, r *http.Request, err error) {
w.WriteHeader(http.StatusInternalServerError)
},
}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic("panic error")
})
wrapped := RecoverMiddleware(adapter, handler)
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
wrapped.ServeHTTP(w, req)
if capturedErr == nil {
t.Fatal("expected captured error, got nil")
}
if capturedErr.Error() != "panic error" {
t.Errorf("expected error string 'panic error', got %v", capturedErr)
}
}