forked from grpc-ecosystem/grpc-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_test.go
321 lines (292 loc) · 9.11 KB
/
handler_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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package runtime_test
import (
"context"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
pb "github.com/grpc-ecosystem/grpc-gateway/v2/runtime/internal/examplepb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
type fakeReponseBodyWrapper struct {
proto.Message
}
// XXX_ResponseBody returns id of SimpleMessage
func (r fakeReponseBodyWrapper) XXX_ResponseBody() interface{} {
resp := r.Message.(*pb.SimpleMessage)
return resp.Id
}
func TestForwardResponseStream(t *testing.T) {
type msg struct {
pb proto.Message
err error
}
tests := []struct {
name string
msgs []msg
statusCode int
responseBody bool
}{{
name: "encoding",
msgs: []msg{
{&pb.SimpleMessage{Id: "One"}, nil},
{&pb.SimpleMessage{Id: "Two"}, nil},
},
statusCode: http.StatusOK,
}, {
name: "empty",
statusCode: http.StatusOK,
}, {
name: "error",
msgs: []msg{{nil, status.Errorf(codes.OutOfRange, "400")}},
statusCode: http.StatusBadRequest,
}, {
name: "stream_error",
msgs: []msg{
{&pb.SimpleMessage{Id: "One"}, nil},
{nil, status.Errorf(codes.OutOfRange, "400")},
},
statusCode: http.StatusOK,
}, {
name: "response body stream case",
msgs: []msg{
{fakeReponseBodyWrapper{&pb.SimpleMessage{Id: "One"}}, nil},
{fakeReponseBodyWrapper{&pb.SimpleMessage{Id: "Two"}}, nil},
},
responseBody: true,
statusCode: http.StatusOK,
}, {
name: "response body stream error case",
msgs: []msg{
{fakeReponseBodyWrapper{&pb.SimpleMessage{Id: "One"}}, nil},
{nil, status.Errorf(codes.OutOfRange, "400")},
},
responseBody: true,
statusCode: http.StatusOK,
}}
newTestRecv := func(t *testing.T, msgs []msg) func() (proto.Message, error) {
var count int
return func() (proto.Message, error) {
if count == len(msgs) {
return nil, io.EOF
} else if count > len(msgs) {
t.Errorf("recv() called %d times for %d messages", count, len(msgs))
}
count++
msg := msgs[count-1]
return msg.pb, msg.err
}
}
ctx := runtime.NewServerMetadataContext(context.Background(), runtime.ServerMetadata{})
marshaler := &runtime.JSONPb{}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recv := newTestRecv(t, tt.msgs)
req := httptest.NewRequest("GET", "http://example.com/foo", nil)
resp := httptest.NewRecorder()
runtime.ForwardResponseStream(ctx, runtime.NewServeMux(), marshaler, resp, req, recv)
w := resp.Result()
if w.StatusCode != tt.statusCode {
t.Errorf("StatusCode %d want %d", w.StatusCode, tt.statusCode)
}
if h := w.Header.Get("Transfer-Encoding"); h != "chunked" {
t.Errorf("ForwardResponseStream missing header chunked")
}
body, err := ioutil.ReadAll(w.Body)
if err != nil {
t.Errorf("Failed to read response body with %v", err)
}
w.Body.Close()
if len(body) > 0 && w.Header.Get("Content-Type") != "application/json" {
t.Errorf("Content-Type %s want application/json", w.Header.Get("Content-Type"))
}
var want []byte
for i, msg := range tt.msgs {
if msg.err != nil {
if i == 0 {
// Skip non-stream errors
t.Skip("checking error encodings")
}
delimiter := marshaler.Delimiter()
st := status.Convert(msg.err)
b, err := marshaler.Marshal(map[string]proto.Message{
"error": st.Proto(),
})
if err != nil {
t.Errorf("marshaler.Marshal() failed %v", err)
}
errBytes := body[len(want):]
if string(errBytes) != string(b)+string(delimiter) {
t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", errBytes, b)
}
return
}
var b []byte
if tt.responseBody {
// responseBody interface is in runtime package and test is in runtime_test package. hence can't use responseBody directly
// So type casting to fakeReponseBodyWrapper struct to verify the data.
rb, ok := msg.pb.(fakeReponseBodyWrapper)
if !ok {
t.Errorf("stream responseBody failed %v", err)
}
b, err = marshaler.Marshal(map[string]interface{}{"result": rb.XXX_ResponseBody()})
} else {
b, err = marshaler.Marshal(map[string]interface{}{"result": msg.pb})
}
if err != nil {
t.Errorf("marshaler.Marshal() failed %v", err)
}
want = append(want, b...)
want = append(want, marshaler.Delimiter()...)
}
if string(body) != string(want) {
t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want)
}
})
}
}
// A custom marshaler implementation, that doesn't implement the delimited interface
type CustomMarshaler struct {
m *runtime.JSONPb
}
func (c *CustomMarshaler) Marshal(v interface{}) ([]byte, error) { return c.m.Marshal(v) }
func (c *CustomMarshaler) Unmarshal(data []byte, v interface{}) error { return c.m.Unmarshal(data, v) }
func (c *CustomMarshaler) NewDecoder(r io.Reader) runtime.Decoder { return c.m.NewDecoder(r) }
func (c *CustomMarshaler) NewEncoder(w io.Writer) runtime.Encoder { return c.m.NewEncoder(w) }
func (c *CustomMarshaler) ContentType(v interface{}) string { return "Custom-Content-Type" }
func TestForwardResponseStreamCustomMarshaler(t *testing.T) {
type msg struct {
pb proto.Message
err error
}
tests := []struct {
name string
msgs []msg
statusCode int
}{{
name: "encoding",
msgs: []msg{
{&pb.SimpleMessage{Id: "One"}, nil},
{&pb.SimpleMessage{Id: "Two"}, nil},
},
statusCode: http.StatusOK,
}, {
name: "empty",
statusCode: http.StatusOK,
}, {
name: "error",
msgs: []msg{{nil, status.Errorf(codes.OutOfRange, "400")}},
statusCode: http.StatusBadRequest,
}, {
name: "stream_error",
msgs: []msg{
{&pb.SimpleMessage{Id: "One"}, nil},
{nil, status.Errorf(codes.OutOfRange, "400")},
},
statusCode: http.StatusOK,
}}
newTestRecv := func(t *testing.T, msgs []msg) func() (proto.Message, error) {
var count int
return func() (proto.Message, error) {
if count == len(msgs) {
return nil, io.EOF
} else if count > len(msgs) {
t.Errorf("recv() called %d times for %d messages", count, len(msgs))
}
count++
msg := msgs[count-1]
return msg.pb, msg.err
}
}
ctx := runtime.NewServerMetadataContext(context.Background(), runtime.ServerMetadata{})
marshaler := &CustomMarshaler{&runtime.JSONPb{}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recv := newTestRecv(t, tt.msgs)
req := httptest.NewRequest("GET", "http://example.com/foo", nil)
resp := httptest.NewRecorder()
runtime.ForwardResponseStream(ctx, runtime.NewServeMux(), marshaler, resp, req, recv)
w := resp.Result()
if w.StatusCode != tt.statusCode {
t.Errorf("StatusCode %d want %d", w.StatusCode, tt.statusCode)
}
if h := w.Header.Get("Transfer-Encoding"); h != "chunked" {
t.Errorf("ForwardResponseStream missing header chunked")
}
body, err := ioutil.ReadAll(w.Body)
if err != nil {
t.Errorf("Failed to read response body with %v", err)
}
w.Body.Close()
if len(body) > 0 && w.Header.Get("Content-Type") != "Custom-Content-Type" {
t.Errorf("Content-Type %s want Custom-Content-Type", w.Header.Get("Content-Type"))
}
var want []byte
for _, msg := range tt.msgs {
if msg.err != nil {
t.Skip("checking erorr encodings")
}
b, err := marshaler.Marshal(map[string]proto.Message{"result": msg.pb})
if err != nil {
t.Errorf("marshaler.Marshal() failed %v", err)
}
want = append(want, b...)
want = append(want, "\n"...)
}
if string(body) != string(want) {
t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want)
}
})
}
}
func TestForwardResponseMessage(t *testing.T) {
msg := &pb.SimpleMessage{Id: "One"}
tests := []struct {
name string
marshaler runtime.Marshaler
contentType string
}{{
name: "standard marshaler",
marshaler: &runtime.JSONPb{},
contentType: "application/json",
}, {
name: "httpbody marshaler",
marshaler: &runtime.HTTPBodyMarshaler{&runtime.JSONPb{}},
contentType: "application/json",
}, {
name: "custom marshaler",
marshaler: &CustomMarshaler{&runtime.JSONPb{}},
contentType: "Custom-Content-Type",
}}
ctx := runtime.NewServerMetadataContext(context.Background(), runtime.ServerMetadata{})
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", "http://example.com/foo", nil)
resp := httptest.NewRecorder()
runtime.ForwardResponseMessage(ctx, runtime.NewServeMux(), tt.marshaler, resp, req, msg)
w := resp.Result()
if w.StatusCode != http.StatusOK {
t.Errorf("StatusCode %d want %d", w.StatusCode, http.StatusOK)
}
if h := w.Header.Get("Content-Type"); h != tt.contentType {
t.Errorf("Content-Type %v want %v", h, tt.contentType)
}
body, err := ioutil.ReadAll(w.Body)
if err != nil {
t.Errorf("Failed to read response body with %v", err)
}
w.Body.Close()
want, err := tt.marshaler.Marshal(msg)
if err != nil {
t.Errorf("marshaler.Marshal() failed %v", err)
}
if string(body) != string(want) {
t.Errorf("ForwardResponseMessage() = \"%s\" want \"%s\"", body, want)
}
})
}
}