generated from bool64/go-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_test.go
382 lines (298 loc) · 10.2 KB
/
server_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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package httpmock_test
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"strings"
"sync"
"testing"
"github.com/bool64/httpmock"
"github.com/bool64/shared"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func assertRoundTrip(t *testing.T, baseURL string, expectation httpmock.Expectation) {
t.Helper()
var bodyReader io.Reader
if expectation.RequestBody != nil {
bodyReader = bytes.NewReader(expectation.RequestBody)
}
req, err := http.NewRequest(expectation.Method, baseURL+expectation.RequestURI, bodyReader)
require.NoError(t, err)
for k, v := range expectation.RequestHeader {
req.Header.Set(k, v)
}
for n, v := range expectation.RequestCookie {
req.AddCookie(&http.Cookie{Name: n, Value: v})
}
resp, err := http.DefaultTransport.RoundTrip(req)
require.NoError(t, err)
body, err := ioutil.ReadAll(resp.Body)
require.NoError(t, resp.Body.Close())
require.NoError(t, err)
if expectation.Status == 0 {
expectation.Status = http.StatusOK
}
assert.Equal(t, expectation.Status, resp.StatusCode)
assert.Equal(t, string(expectation.ResponseBody), string(body))
// Asserting default for successful responses.
if resp.StatusCode != http.StatusInternalServerError {
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
}
if len(expectation.ResponseHeader) > 0 {
for k, v := range expectation.ResponseHeader {
assert.Equal(t, v, resp.Header.Get(k))
}
}
}
func TestServer_ServeHTTP(t *testing.T) {
// Creating REST service mock.
mock, baseURL := httpmock.NewServer()
defer mock.Close()
mock.OnBodyMismatch = func(received []byte) {
assert.Equal(t, `{"foo":"bar"}`, string(received))
}
mock.DefaultResponseHeaders = map[string]string{
"Content-Type": "application/json",
}
// Requesting mock without expectations fails.
assertRoundTrip(t, baseURL, httpmock.Expectation{
RequestURI: "/test?test=test",
Status: http.StatusInternalServerError,
ResponseBody: []byte("unexpected request received: GET /test?test=test"),
})
// Requesting mock without expectations fails.
assertRoundTrip(t, baseURL, httpmock.Expectation{
RequestURI: "/test?test=test",
Status: http.StatusInternalServerError,
RequestBody: []byte(`{"foo":"bar"}`),
ResponseBody: []byte("unexpected request received: GET /test?test=test, body:\n{\"foo\":\"bar\"}"),
})
// Setting expectations for first request.
exp1 := httpmock.Expectation{
Method: http.MethodPost,
RequestURI: "/test?test=test",
RequestHeader: map[string]string{"Authorization": "Bearer token"},
RequestCookie: map[string]string{"c1": "v1", "c2": "v2"},
RequestBody: []byte(`{"request":"body"}`),
Status: http.StatusCreated,
ResponseBody: []byte(`{"response":"body"}`),
}
mock.Expect(exp1)
// Setting expectations for second request.
exp2 := httpmock.Expectation{
Method: http.MethodPost,
RequestURI: "/test?test=test",
RequestBody: []byte(`not a JSON`),
ResponseHeader: map[string]string{
"X-Foo": "bar",
},
ResponseBody: []byte(`{"response":"body2"}`),
}
mock.Expect(exp2)
// Sending first request.
assertRoundTrip(t, baseURL, exp1)
// Expectations were not met yet.
require.EqualError(t, mock.ExpectationsWereMet(),
"there are remaining expectations that were not met: POST /test?test=test")
// Sending second request.
assertRoundTrip(t, baseURL, exp2)
// Expectations were met.
require.NoError(t, mock.ExpectationsWereMet())
// Requesting mock without expectations fails.
assertRoundTrip(t, baseURL, httpmock.Expectation{
RequestURI: "/test?test=test",
Status: http.StatusInternalServerError,
ResponseBody: []byte("unexpected request received: GET /test?test=test"),
})
}
func TestServer_ServeHTTP_error(t *testing.T) {
// Creating REST service mock.
mock, baseURL := httpmock.NewServer()
defer mock.Close()
mock.OnBodyMismatch = func(received []byte) {
assert.Equal(t, `{"request":"body"}`, string(received))
}
// Setting expectations for first request.
mock.Expect(httpmock.Expectation{
Method: http.MethodPost,
RequestURI: "/test?test=test",
RequestHeader: map[string]string{"X-Foo": "bar"},
RequestBody: []byte(`{"foo":"bar"}`),
})
// Sending request with wrong uri.
req, err := http.NewRequest(http.MethodPost, baseURL+"/wrong-uri", bytes.NewReader([]byte(`{"request":"body"}`)))
require.NoError(t, err)
req.Header.Set("X-Foo", "bar")
resp, err := http.DefaultTransport.RoundTrip(req)
require.NoError(t, err)
respBody, err := ioutil.ReadAll(resp.Body)
require.NoError(t, resp.Body.Close())
require.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
assert.Equal(t, `request uri "/test?test=test" expected, "/wrong-uri" received`, string(respBody))
// Sending request with wrong method.
req, err = http.NewRequest(http.MethodGet, baseURL+"/test?test=test", bytes.NewReader([]byte(`{"request":"body"}`)))
require.NoError(t, err)
req.Header.Set("X-Foo", "bar")
resp, err = http.DefaultTransport.RoundTrip(req)
require.NoError(t, err)
respBody, err = ioutil.ReadAll(resp.Body)
require.NoError(t, resp.Body.Close())
require.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
assert.Equal(t, `method "POST" expected, "GET" received`, string(respBody))
// Sending request with wrong header.
req, err = http.NewRequest(http.MethodPost, baseURL+"/test?test=test", bytes.NewReader([]byte(`{"request":"body"}`)))
require.NoError(t, err)
req.Header.Set("X-Foo", "space")
resp, err = http.DefaultTransport.RoundTrip(req)
require.NoError(t, err)
respBody, err = ioutil.ReadAll(resp.Body)
require.NoError(t, resp.Body.Close())
require.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
assert.Equal(t, `header "X-Foo" with value "bar" expected, "space" received`, string(respBody))
// Sending request with wrong body.
req, err = http.NewRequest(http.MethodPost, baseURL+"/test?test=test", bytes.NewReader([]byte(`{"request":"body"}`)))
require.NoError(t, err)
req.Header.Set("X-Foo", "bar")
resp, err = http.DefaultTransport.RoundTrip(req)
require.NoError(t, err)
respBody, err = ioutil.ReadAll(resp.Body)
require.NoError(t, resp.Body.Close())
require.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
assert.Equal(t, `unexpected request body: not equal:
{
- "foo": "bar"
+ "request": "body"
}
`, string(respBody))
}
func TestServer_ServeHTTP_concurrency(t *testing.T) {
// Creating REST service mock.
mock, url := httpmock.NewServer()
defer mock.Close()
n := 50
for i := 0; i < n; i++ {
// Setting expectations for first request.
mock.Expect(httpmock.Expectation{
Method: http.MethodGet,
RequestURI: "/test?test=test",
ResponseBody: []byte("body"),
})
}
wg := sync.WaitGroup{}
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
// Sending request with wrong header.
req, err := http.NewRequest(http.MethodGet, url+"/test?test=test", nil)
assert.NoError(t, err)
req.Header.Set("X-Foo", "space")
resp, err := http.DefaultTransport.RoundTrip(req)
assert.NoError(t, err)
respBody, err := ioutil.ReadAll(resp.Body)
assert.NoError(t, resp.Body.Close())
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, `body`, string(respBody))
}()
}
wg.Wait()
require.NoError(t, mock.ExpectationsWereMet())
}
func TestServer_ResetExpectations(t *testing.T) {
// Creating REST service mock.
mock, _ := httpmock.NewServer()
defer mock.Close()
mock.Expect(httpmock.Expectation{
Method: http.MethodGet,
RequestURI: "/test?test=test",
ResponseBody: []byte("body"),
})
mock.ExpectAsync(httpmock.Expectation{
Method: http.MethodGet,
RequestURI: "/test-async?test=test",
ResponseBody: []byte("body"),
})
require.Error(t, mock.ExpectationsWereMet())
mock.ResetExpectations()
require.NoError(t, mock.ExpectationsWereMet())
}
func TestServer_vars(t *testing.T) {
sm, url := httpmock.NewServer()
sm.JSONComparer.Vars = &shared.Vars{}
sm.Expect(httpmock.Expectation{
Method: http.MethodGet,
RequestURI: "/",
RequestBody: []byte(`{"foo":"bar","dyn":"$var1"}`),
ResponseBody: []byte(`{"bar":"foo","dynEcho":"$var1"}`),
})
req, err := http.NewRequest(http.MethodGet, url+"/", strings.NewReader(`{"foo":"bar","dyn":"abc"}`))
require.NoError(t, err)
resp, err := http.DefaultTransport.RoundTrip(req)
require.NoError(t, err)
body, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, `{"bar":"foo","dynEcho":"abc"}`, string(body))
}
func TestServer_ExpectAsync(t *testing.T) {
sm, url := httpmock.NewServer()
sm.Expect(httpmock.Expectation{
Method: http.MethodGet,
RequestURI: "/",
ResponseBody: []byte(`{"bar":"foo"}`),
})
sm.ExpectAsync(httpmock.Expectation{
Method: http.MethodGet,
RequestURI: "/async1",
ResponseBody: []byte(`{"bar":"async1"}`),
})
sm.ExpectAsync(httpmock.Expectation{
Method: http.MethodGet,
RequestURI: "/async2",
ResponseBody: []byte(`{"bar":"async2"}`),
Unlimited: true,
})
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
req, err := http.NewRequest(http.MethodGet, url+"/async1", nil)
assert.NoError(t, err)
resp, err := http.DefaultTransport.RoundTrip(req)
assert.NoError(t, err)
body, err := ioutil.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
assert.Equal(t, `{"bar":"async1"}`, string(body))
}()
go func() {
defer wg.Done()
for i := 0; i < 50; i++ {
req, err := http.NewRequest(http.MethodGet, url+"/async2", nil)
assert.NoError(t, err)
resp, err := http.DefaultTransport.RoundTrip(req)
assert.NoError(t, err)
body, err := ioutil.ReadAll(resp.Body)
assert.NoError(t, err)
assert.NoError(t, resp.Body.Close())
assert.Equal(t, `{"bar":"async2"}`, string(body))
}
}()
req, err := http.NewRequest(http.MethodGet, url+"/", nil)
require.NoError(t, err)
resp, err := http.DefaultTransport.RoundTrip(req)
require.NoError(t, err)
body, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, `{"bar":"foo"}`, string(body))
wg.Wait()
require.NoError(t, sm.ExpectationsWereMet())
}