-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequestopts_test.go
More file actions
470 lines (400 loc) · 14.8 KB
/
requestopts_test.go
File metadata and controls
470 lines (400 loc) · 14.8 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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
package client_test
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"sync/atomic"
"testing"
"time"
client "github.com/mutablelogic/go-client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
///////////////////////////////////////////////////////////////////////////////
// TEST TYPES
// jsonStreamEvent is used by OptJsonStreamCallback tests.
type jsonStreamEvent struct {
Value int `json:"value"`
}
///////////////////////////////////////////////////////////////////////////////
// OptReqEndpoint
func Test_OptReqEndpoint_RedirectsToOtherServer(t *testing.T) {
srv1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer srv1.Close()
var srv2Hit atomic.Bool
srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
srv2Hit.Store(true)
w.WriteHeader(http.StatusOK)
}))
defer srv2.Close()
c, err := client.New(client.OptEndpoint(srv1.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil, client.OptReqEndpoint(srv2.URL)))
assert.True(t, srv2Hit.Load(), "request should have been sent to srv2, not srv1")
}
func Test_OptReqEndpoint_InvalidURL_Errors(t *testing.T) {
srv, _ := newTestServer(t)
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
err = c.Do(client.MethodGet, nil, client.OptReqEndpoint("://bad"))
assert.Error(t, err)
}
///////////////////////////////////////////////////////////////////////////////
// OptPath
func Test_OptPath_SingleSegment(t *testing.T) {
var capturedPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil, client.OptPath("api")))
assert.Equal(t, "/api", capturedPath)
}
func Test_OptPath_MultipleSegmentsAndMixedTypes(t *testing.T) {
// This also exercises the private join() helper via mixed-type args.
var capturedPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil, client.OptPath("v2", "users", 42)))
assert.Equal(t, "/v2/users/42", capturedPath)
}
func Test_OptPath_EscapesSegments(t *testing.T) {
var capturedPath, capturedEscapedPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedPath = r.URL.Path
capturedEscapedPath = r.URL.EscapedPath()
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil, client.OptPath("object", "cn=test user#1,ou=users,dc=example,dc=com")))
assert.Equal(t, "/object/cn=test user#1,ou=users,dc=example,dc=com", capturedPath)
assert.Contains(t, capturedEscapedPath, "%20")
assert.Contains(t, capturedEscapedPath, "%23")
assert.NotContains(t, capturedEscapedPath, " ")
assert.NotContains(t, capturedEscapedPath, "#")
}
func Test_OptPath_TreatsEachArgumentAsOneSegment(t *testing.T) {
var capturedPath, capturedRequestURI string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil,
client.OptPath("a/b", "c"),
client.OptReqTransport(func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(req *http.Request) (*http.Response, error) {
capturedPath = req.URL.Path
capturedRequestURI = req.URL.RequestURI()
return next.RoundTrip(req)
})
}),
))
assert.Equal(t, "/a/b/c", capturedPath)
assert.Equal(t, "/a%2Fb/c", capturedRequestURI)
}
func Test_OptPath_PreservesDotSegmentsAsData(t *testing.T) {
var capturedPath, capturedRequestURI string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil,
client.OptPath("a/../b"),
client.OptReqTransport(func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(req *http.Request) (*http.Response, error) {
capturedPath = req.URL.Path
capturedRequestURI = req.URL.RequestURI()
return next.RoundTrip(req)
})
}),
))
assert.Equal(t, "/a/../b", capturedPath)
assert.Equal(t, "/a%2F..%2Fb", capturedRequestURI)
}
func Test_OptAbsPath_EmptyNormalizesToRoot(t *testing.T) {
var capturedPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil, client.OptAbsPath()))
assert.Equal(t, "/", capturedPath)
}
func Test_OptAbsPath_LeadingSlashNormalizesToRootedPath(t *testing.T) {
var capturedPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil, client.OptAbsPath("/auth", "login")))
assert.Equal(t, "/auth/login", capturedPath)
}
func Test_OptAbsPath_EscapesSegments(t *testing.T) {
var capturedPath, capturedEscapedPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedPath = r.URL.Path
capturedEscapedPath = r.URL.EscapedPath()
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil, client.OptAbsPath("/object", "cn=test user#1,ou=users,dc=example,dc=com")))
assert.Equal(t, "/object/cn=test user#1,ou=users,dc=example,dc=com", capturedPath)
assert.Contains(t, capturedEscapedPath, "%20")
assert.Contains(t, capturedEscapedPath, "%23")
assert.NotContains(t, capturedEscapedPath, " ")
assert.NotContains(t, capturedEscapedPath, "#")
}
func Test_OptAbsPath_TreatsEachArgumentAsOneSegment(t *testing.T) {
var capturedPath, capturedRequestURI string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil,
client.OptAbsPath("a/b", "c"),
client.OptReqTransport(func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(req *http.Request) (*http.Response, error) {
capturedPath = req.URL.Path
capturedRequestURI = req.URL.RequestURI()
return next.RoundTrip(req)
})
}),
))
assert.Equal(t, "/a/b/c", capturedPath)
assert.Equal(t, "/a%2Fb/c", capturedRequestURI)
}
func Test_OptAbsPath_PreservesDotSegmentsAsData(t *testing.T) {
var capturedPath, capturedRequestURI string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil,
client.OptAbsPath("a/../b"),
client.OptReqTransport(func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(req *http.Request) (*http.Response, error) {
capturedPath = req.URL.Path
capturedRequestURI = req.URL.RequestURI()
return next.RoundTrip(req)
})
}),
))
assert.Equal(t, "/a/../b", capturedPath)
assert.Equal(t, "/a%2F..%2Fb", capturedRequestURI)
}
func Test_OptPath_EmptyPreservesRoot(t *testing.T) {
var capturedPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil, client.OptPath()))
assert.Equal(t, "/", capturedPath)
}
///////////////////////////////////////////////////////////////////////////////
// OptToken
func Test_OptToken_SetsPerRequestHeader(t *testing.T) {
srv, captured := newTestServer(t)
defer srv.Close()
// Client has no persistent token.
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil,
client.OptToken(client.Token{Scheme: "ApiKey", Value: "qwerty"}),
))
assert.Equal(t, "ApiKey qwerty", (*captured).Get("Authorization"))
}
///////////////////////////////////////////////////////////////////////////////
// OptQuery
func Test_OptQuery_SetsQueryParameters(t *testing.T) {
var capturedQuery string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedQuery = r.URL.RawQuery
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
q := url.Values{"foo": {"bar"}, "n": {"1"}}
require.NoError(t, c.Do(client.MethodGet, nil, client.OptQuery(q)))
parsed, err := url.ParseQuery(capturedQuery)
require.NoError(t, err)
assert.Equal(t, "bar", parsed.Get("foo"))
assert.Equal(t, "1", parsed.Get("n"))
}
///////////////////////////////////////////////////////////////////////////////
// OptReqHeader
func Test_OptReqHeader_SetsPerRequestCustomHeader(t *testing.T) {
srv, captured := newTestServer(t)
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.MethodGet, nil,
client.OptReqHeader("X-Req-Only", "req-value"),
))
assert.Equal(t, "req-value", (*captured).Get("X-Req-Only"))
}
///////////////////////////////////////////////////////////////////////////////
// OptNoTimeout
func Test_OptNoTimeout_SucceedsWithSlowServer(t *testing.T) {
const serverDelay = 200 * time.Millisecond
const clientTimeout = 30 * time.Millisecond
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(serverDelay)
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c, err := client.New(
client.OptEndpoint(srv.URL),
client.OptTimeout(clientTimeout),
)
require.NoError(t, err)
// Without OptNoTimeout: expect a deadline error.
err = c.Do(client.MethodGet, nil)
assert.Error(t, err, "expected deadline/timeout without OptNoTimeout")
// With OptNoTimeout: should succeed even though the global timeout is short.
err = c.Do(client.MethodGet, nil, client.OptNoTimeout())
assert.NoError(t, err)
}
///////////////////////////////////////////////////////////////////////////////
// OptReqTransport
func Test_OptReqTransport_NilErrors(t *testing.T) {
srv, _ := newTestServer(t)
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
err = c.Do(client.MethodGet, nil, client.OptReqTransport(nil))
assert.Error(t, err)
}
func Test_OptReqTransport_PerRequestMiddlewareCalled(t *testing.T) {
srv, _ := newTestServer(t)
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
var called atomic.Bool
mw := func(next http.RoundTripper) http.RoundTripper {
return roundTripFunc(func(req *http.Request) (*http.Response, error) {
called.Store(true)
return next.RoundTrip(req)
})
}
// First request without the middleware: not called.
require.NoError(t, c.Do(client.MethodGet, nil))
assert.False(t, called.Load(), "middleware should not fire without OptReqTransport")
// Second request with the middleware: called.
require.NoError(t, c.Do(client.MethodGet, nil, client.OptReqTransport(mw)))
assert.True(t, called.Load(), "middleware should fire when passed via OptReqTransport")
}
///////////////////////////////////////////////////////////////////////////////
// OptTextStreamCallback
func Test_OptTextStreamCallback_EventsDelivered(t *testing.T) {
const sseBody = "data: hello\n\ndata: world\n\n"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
io.WriteString(w, sseBody)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
var events []string
// A non-nil dummy out is required to pass the nil-out exit in do().
dummy := new(struct{})
err = c.Do(
client.NewRequestEx(http.MethodGet, client.ContentTypeTextStream),
dummy,
client.OptTextStreamCallback(func(e client.TextStreamEvent) error {
events = append(events, e.Data)
return nil
}),
)
require.NoError(t, err)
require.Len(t, events, 2)
assert.Equal(t, "hello", events[0])
assert.Equal(t, "world", events[1])
}
///////////////////////////////////////////////////////////////////////////////
// OptJsonStreamCallback
func Test_OptJsonStreamCallback_EventsDelivered(t *testing.T) {
const ndjsonBody = "{\"value\":10}\n{\"value\":20}\n"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/x-ndjson")
w.WriteHeader(http.StatusOK)
io.WriteString(w, ndjsonBody)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
out := new(jsonStreamEvent)
var values []int
err = c.Do(
client.NewRequestEx(http.MethodGet, client.ContentTypeJsonStream),
out,
client.OptJsonStreamCallback(func(v json.RawMessage) error {
var event jsonStreamEvent
if err := json.Unmarshal(v, &event); err != nil {
return err
}
values = append(values, event.Value)
return nil
}),
)
require.NoError(t, err)
assert.Equal(t, []int{10, 20}, values)
}
func Test_OptJsonStreamCallback_EOFStopsCleanly(t *testing.T) {
const ndjsonBody = "{\"value\":1}\n{\"value\":2}\n{\"value\":3}\n"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/x-ndjson")
io.WriteString(w, ndjsonBody)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
out := new(jsonStreamEvent)
var count int
err = c.Do(
client.NewRequestEx(http.MethodGet, client.ContentTypeJsonStream),
out,
client.OptJsonStreamCallback(func(v json.RawMessage) error {
count++
return io.EOF // stop after the first decoded event
}),
)
require.NoError(t, err) // io.EOF from callback → clean stop, nil returned
assert.Equal(t, 1, count)
}