Repository navigation
Expand file tree
/
Copy pathdo_test.go
More file actions
411 lines (372 loc) · 14.1 KB
/
Copy pathdo_test.go
File metadata and controls
411 lines (372 loc) · 14.1 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
package client_test
import (
"bytes"
"context"
"encoding/xml"
"errors"
types "github.com/mutablelogic/go-server/pkg/types"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"unicode/utf8"
client "github.com/mutablelogic/go-client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// xmlDoc is used for XML decode tests.
type xmlDoc struct {
XMLName xml.Name `xml:"doc"`
Name string `xml:"name"`
}
// bodyCapture implements client.Unmarshaler and records the full body bytes.
type bodyCapture struct {
Body []byte
}
func (b *bodyCapture) Unmarshal(_ http.Header, r io.Reader) error {
var err error
b.Body, err = io.ReadAll(r)
return err
}
func Test_Do_NilOut_ReturnsNil(t *testing.T) {
srv, _ := newTestServer(t)
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
assert.NoError(t, c.Do(client.MethodGet, nil))
}
func Test_Do_NonOK_WithBody(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "invalid parameter")
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
err = c.Do(client.MethodGet, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid parameter")
}
func Test_Do_NonOK_HTMLBody(t *testing.T) {
// An HTML error page, such as a CDN's, is its title, and one without a
// title is only its status
for _, test := range []struct {
contentType, body, want string
}{
{"text/html; charset=UTF-8", "<!DOCTYPE html>\n<html><head>\n<title>api.example.com | 504: Gateway\n time-out & more</title></head><body>" + strings.Repeat("<div>noise</div>", 1000) + "</body></html>", "504 Gateway Timeout: api.example.com | 504: Gateway time-out & more"},
{"", "<html><body><h1>Bad gateway</h1></body></html>", "504 Gateway Timeout"},
{"Text/HTML", "<title>Upper case</title>", "504 Gateway Timeout: Upper case"},
} {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if test.contentType != "" {
w.Header().Set("Content-Type", test.contentType)
}
w.WriteHeader(http.StatusGatewayTimeout)
io.WriteString(w, test.body)
}))
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
err = c.Do(client.MethodGet, nil)
srv.Close()
require.Error(t, err)
assert.Contains(t, err.Error(), test.want)
assert.NotContains(t, err.Error(), "<")
}
}
func Test_Do_NonOK_TextNamedHTML(t *testing.T) {
// Plain text whose content type has a parameter which mentions HTML is
// plain text
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; name=error.html")
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "invalid parameter")
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
err = c.Do(client.MethodGet, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid parameter")
}
func Test_Do_NonOK_LongBody(t *testing.T) {
// A long error body is cut short
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, strings.Repeat("é", 1000))
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
err = c.Do(client.MethodGet, nil)
require.Error(t, err)
assert.Less(t, len(err.Error()), 600)
assert.True(t, strings.HasSuffix(err.Error(), "…"))
assert.True(t, utf8.ValidString(err.Error()))
}
func Test_Do_NonOK_EmptyBody(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
assert.Error(t, c.Do(client.MethodGet, nil))
}
func Test_Do_XMLDecode(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml")
io.WriteString(w, `<?xml version="1.0"?><doc><name>Alice</name></doc>`)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
var doc xmlDoc
require.NoError(t, c.Do(client.MethodGet, &doc))
assert.Equal(t, "Alice", doc.Name)
}
func Test_Do_CustomUnmarshaler(t *testing.T) {
const body = "raw response body"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, body)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
out := new(bodyCapture)
require.NoError(t, c.Do(client.MethodGet, out))
assert.Equal(t, body, string(out.Body))
}
func Test_Do_StrictMode_ContentTypeMismatch(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
io.WriteString(w, "hello")
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL), client.OptStrict())
require.NoError(t, err)
var out string
err = c.Do(client.NewRequestEx(http.MethodGet, types.ContentTypeJSON), &out)
assert.Error(t, err)
}
func Test_Do_TextPlain_ToString(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
io.WriteString(w, "hello world")
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
var out string
require.NoError(t, c.Do(client.MethodGet, &out))
assert.Equal(t, "hello world", out)
}
func Test_Do_TextPlain_ToBytes(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
io.WriteString(w, "bytes")
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
var out []byte
require.NoError(t, c.Do(client.MethodGet, &out))
assert.Equal(t, "bytes", string(out))
}
func Test_Do_TextPlain_ToWriter(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
io.WriteString(w, "writer")
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
var buf bytes.Buffer
require.NoError(t, c.Do(client.MethodGet, &buf))
assert.Equal(t, "writer", buf.String())
}
func Test_Do_Redirect_Following(t *testing.T) {
srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"result":"ok"}`)
}))
defer srv2.Close()
srv1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, srv2.URL, http.StatusMovedPermanently)
}))
defer srv1.Close()
c, err := client.New(client.OptEndpoint(srv1.URL))
require.NoError(t, err)
var out map[string]any
require.NoError(t, c.Do(client.MethodGet, &out))
assert.Equal(t, "ok", out["result"])
}
func Test_Do_Request(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"key":"value"}`)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL, nil)
require.NoError(t, err)
var out map[string]any
require.NoError(t, c.Request(req, &out))
assert.Equal(t, "value", out["key"])
}
func Test_Do_BinaryToWriter(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/octet-stream")
w.Write([]byte{0x01, 0x02, 0x03})
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
var buf bytes.Buffer
require.NoError(t, c.Do(client.MethodGet, &buf))
assert.Equal(t, []byte{0x01, 0x02, 0x03}, buf.Bytes())
}
// Test_Do_CrossOriginRedirectStripsCredentials verifies that when a redirect
// leads to a different host, TokenTransport does not re-inject the global
// Authorization header on the redirect hop, preventing credential leakage.
func Test_Do_CrossOriginRedirectStripsCredentials(t *testing.T) {
// Target server: records the Authorization header it receives (if any).
var targetAuth string
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
targetAuth = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"ok":true}`))
}))
defer target.Close()
// Origin server: issues a 301 redirect to the target (cross-origin: different port).
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL+"/", http.StatusMovedPermanently)
}))
defer origin.Close()
// Client with a global bearer token.
c, err := client.New(
client.OptEndpoint(origin.URL),
client.OptReqToken(client.Token{Scheme: "Bearer", Value: "supersecret"}),
)
require.NoError(t, err)
var out map[string]any
require.NoError(t, c.Do(client.MethodGet, &out))
// The cross-origin redirect target must never see the credential.
assert.Equal(t, "", targetAuth,
"Authorization must not be forwarded to a cross-origin redirect target")
}
func TestDoContentType(t *testing.T) {
// A server which records the content type and length of each request,
// and its body
var contentType, body string
var contentLength int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := io.ReadAll(r.Body)
contentType, contentLength, body = r.Header.Get("Content-Type"), r.ContentLength, string(data)
}))
t.Cleanup(server.Close)
c, err := client.New(client.OptEndpoint(server.URL))
require.NoError(t, err)
// A request without a payload has no body, and no content type
for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodDelete} {
require.NoError(t, c.Do(client.NewRequestEx(method, types.ContentTypeAny), nil), method)
assert.Empty(t, contentType, method)
assert.Zero(t, contentLength, method)
assert.Empty(t, body, method)
}
require.NoError(t, c.Do(client.NewRequest(), nil))
assert.Empty(t, contentType)
// A request with a payload has its content type
payload, err := client.NewJSONRequest(map[string]string{"a": "b"})
require.NoError(t, err)
require.NoError(t, c.Do(payload, nil))
assert.Equal(t, types.ContentTypeJSON, contentType)
assert.JSONEq(t, `{"a":"b"}`, body)
}
func Test_Do_OptResponse_Handled(t *testing.T) {
// A 308 of a resumable upload, without a Location, or a body, whose
// Range header the caller reads
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Range", "bytes=0-262143")
w.WriteHeader(http.StatusPermanentRedirect)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
var status int
var got string
require.NoError(t, c.Do(client.MethodPut, nil, client.OptResponse(func(response *http.Response) error {
status, got = response.StatusCode, response.Header.Get("Range")
return client.ErrResponseHandled
})))
assert.Equal(t, http.StatusPermanentRedirect, status)
assert.Equal(t, "bytes=0-262143", got)
// Without it, the 308 is an error
assert.Error(t, c.Do(client.MethodPut, nil))
}
func Test_Do_OptResponse_Error(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"name":"ok"}`)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
// An error of the function is returned as it is
sentinel := errors.New("not this one")
err = c.Do(client.MethodGet, nil, client.OptResponse(func(*http.Response) error { return sentinel }))
assert.Equal(t, sentinel, err)
// And nil carries on, so the body is decoded
var out struct {
Name string `json:"name"`
}
called := false
require.NoError(t, c.Do(client.MethodGet, &out, client.OptResponse(func(*http.Response) error { called = true; return nil })))
assert.True(t, called)
assert.Equal(t, "ok", out.Name)
}
func Test_Do_OptResponse_NotOK(t *testing.T) {
// A response which isn't a success is still an error, when it carries on
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
var status int
err = c.Do(client.MethodGet, nil, client.OptResponse(func(response *http.Response) error {
status = response.StatusCode
return nil
}))
assert.Error(t, err)
assert.Equal(t, http.StatusNotFound, status)
}
func Test_Do_BytesRequest_ContentLength(t *testing.T) {
// A payload of a buffer is sent with its length, rather than chunked
type seen struct {
length int64
chunked bool
mimetype string
body string
}
var got seen
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := io.ReadAll(r.Body)
got = seen{length: r.ContentLength, chunked: len(r.TransferEncoding) > 0, mimetype: r.Header.Get("Content-Type"), body: string(data)}
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
c, err := client.New(client.OptEndpoint(srv.URL))
require.NoError(t, err)
require.NoError(t, c.Do(client.NewBytesRequest(http.MethodPut, []byte("chunk"), "", ""), nil))
assert.Equal(t, seen{length: 5, mimetype: types.ContentTypeBinary, body: "chunk"}, got)
require.NoError(t, c.Do(client.NewBytesRequest(http.MethodPut, nil, "text/plain", ""), nil))
assert.Equal(t, seen{length: 0, mimetype: "text/plain"}, got, "an empty one")
payload, err := client.NewJSONRequestEx(http.MethodPost, map[string]string{"a": "b"}, "")
require.NoError(t, err)
require.NoError(t, c.Do(payload, nil))
assert.False(t, got.chunked, "a JSON payload too")
assert.Equal(t, int64(len(got.body)), got.length)
}