-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrapper_test.go
105 lines (85 loc) · 1.97 KB
/
wrapper_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
96
97
98
99
100
101
102
103
104
105
package httpwrapper
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/rs/zerolog"
)
func TestWrapper(t *testing.T) {
t.Parallel()
zl := zerolog.New(io.Discard).With()
tests := []struct {
name string
httpResponse *Response
httpErrorResponse *ErrorResponse
expectedStatus int
}{
{
name: "normal path",
httpResponse: &Response{
Body: struct {
Test int `json:"test"`
}{Test: 123},
HTTPStatusCode: http.StatusCreated,
},
httpErrorResponse: nil,
expectedStatus: http.StatusCreated,
},
{
name: "error path",
httpResponse: nil,
httpErrorResponse: &ErrorResponse{
Error: fmt.Errorf("test render"),
HTTPStatusCode: http.StatusBadRequest,
ErrorCode: "test_render",
ErrorMsg: "test error user",
},
expectedStatus: http.StatusBadRequest,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(http.MethodGet, "/", &bytes.Reader{})
nr := httptest.NewRecorder()
f := func(r *http.Request) (*Response, *ErrorResponse) {
if tt.httpResponse != nil {
return tt.httpResponse, nil
}
return nil, tt.httpErrorResponse
}
handler := Wrapper(zl.Logger(), f)
handler.ServeHTTP(nr, req)
resp := nr.Result()
defer resp.Body.Close()
if resp.StatusCode != tt.expectedStatus {
t.Errorf("expected status %d, got %d", tt.expectedStatus, resp.StatusCode)
return
}
})
}
}
func BenchmarkHTTPWrapper(b *testing.B) {
zl := zerolog.New(io.Discard).With()
req := httptest.NewRequest(http.MethodGet, "/", &bytes.Reader{})
nr := httptest.NewRecorder()
f := func(r *http.Request) (*Response, *ErrorResponse) {
return &Response{
Body: struct {
Test int
}{
Test: 123,
},
HTTPStatusCode: 200,
}, nil
}
handler := Wrapper(zl.Logger(), f)
b.ResetTimer()
for i := 0; i <= b.N; i++ {
handler.ServeHTTP(nr, req)
}
}