Repository navigation
Expand file tree
/
Copy pathrequest_test.go
More file actions
653 lines (583 loc) · 20.9 KB
/
Copy pathrequest_test.go
File metadata and controls
653 lines (583 loc) · 20.9 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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
package main
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
log "charm.land/log/v2"
)
func testClient() *Client {
return newClient(log.New(io.Discard), plainErrorChan{})
}
func TestClientDoSuccess(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer srv.Close()
res := testClient().Do(RequestSpec{Method: "GET", URL: srv.URL})
if res.Status != 200 {
t.Fatalf("status = %d, want 200", res.Status)
}
if !res.OK() {
t.Errorf("OK() = false, want true (err=%v)", res.Err)
}
if string(res.Body) != `{"ok":true}` {
t.Errorf("body = %q", res.Body)
}
if res.ContentType != "application/json" {
t.Errorf("content-type = %q", res.ContentType)
}
if res.DisplayErr != "" {
t.Errorf("DisplayErr should be empty on success, got %q", res.DisplayErr)
}
}
// Credentials — including env-injected custom headers Go's default policy
// never strips — must not follow a redirect to another origin.
func TestRedirectStripsCredentialsCrossOrigin(t *testing.T) {
t.Setenv("WEEB_BASE_URL", "")
t.Setenv("WEEB_HEADERS", "X-Api-Key:sekrit")
t.Setenv("WEEB_TOKEN", "tok")
var gotAuth, gotKey, gotAccept string
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
gotKey = r.Header.Get("X-Api-Key")
gotAccept = r.Header.Get("Accept")
}))
defer target.Close()
// A second loopback server has a different port: a different origin.
hopper := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL, http.StatusFound)
}))
defer hopper.Close()
res := testClient().Do(RequestSpec{
Method: "GET",
URL: hopper.URL,
Headers: []Header{{Key: "Accept", Value: "application/json"}},
})
if !res.OK() {
t.Fatalf("request failed: %v", res.Err)
}
if gotAuth != "" || gotKey != "" {
t.Errorf("credentials followed a cross-origin redirect: Authorization=%q X-Api-Key=%q", gotAuth, gotKey)
}
// Non-credential headers still follow the redirect.
if gotAccept != "application/json" {
t.Errorf("Accept should survive the redirect, got %q", gotAccept)
}
}
// A user-typed header whose name collides with a WEEB_HEADERS key is the
// user's own — resolveSpec never injects the env copy — so it must follow a
// cross-origin redirect like any custom header (as curl does), while a header
// that really came from the env is still stripped.
func TestRedirectKeepsUserTypedHeaderCrossOrigin(t *testing.T) {
t.Setenv("WEEB_BASE_URL", "")
t.Setenv("WEEB_HEADERS", "X-Api-Key:env-secret;X-Env-Only:sekrit")
t.Setenv("WEEB_TOKEN", "")
var gotKey, gotEnvOnly string
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotKey = r.Header.Get("X-Api-Key")
gotEnvOnly = r.Header.Get("X-Env-Only")
}))
defer target.Close()
// A second loopback server has a different port: a different origin.
hopper := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL, http.StatusFound)
}))
defer hopper.Close()
res := testClient().Do(RequestSpec{
Method: "GET",
URL: hopper.URL,
Headers: []Header{{Key: "X-Api-Key", Value: "mine"}},
})
if !res.OK() {
t.Fatalf("request failed: %v", res.Err)
}
if gotKey != "mine" {
t.Errorf("user-typed X-Api-Key should survive the redirect, got %q", gotKey)
}
if gotEnvOnly != "" {
t.Errorf("env-injected X-Env-Only followed a cross-origin redirect: %q", gotEnvOnly)
}
}
func TestRedirectKeepsCredentialsSameOrigin(t *testing.T) {
t.Setenv("WEEB_BASE_URL", "")
t.Setenv("WEEB_HEADERS", "X-Api-Key:sekrit")
t.Setenv("WEEB_TOKEN", "tok")
var gotAuth, gotKey string
mux := http.NewServeMux()
mux.HandleFunc("/start", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/final", http.StatusFound)
})
mux.HandleFunc("/final", func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
gotKey = r.Header.Get("X-Api-Key")
})
srv := httptest.NewServer(mux)
defer srv.Close()
res := testClient().Do(RequestSpec{Method: "GET", URL: srv.URL + "/start"})
if !res.OK() {
t.Fatalf("request failed: %v", res.Err)
}
if gotAuth != "Bearer tok" {
t.Errorf("same-origin redirect should keep Authorization, got %q", gotAuth)
}
if gotKey != "sekrit" {
t.Errorf("same-origin redirect should keep env-injected X-Api-Key, got %q", gotKey)
}
}
func TestNoFollowReturnsRedirectResponse(t *testing.T) {
t.Setenv("WEEB_BASE_URL", "")
t.Setenv("WEEB_HEADERS", "")
t.Setenv("WEEB_TOKEN", "")
targetHit := false
mux := http.NewServeMux()
mux.HandleFunc("/start", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/final", http.StatusFound)
})
mux.HandleFunc("/final", func(w http.ResponseWriter, r *http.Request) {
targetHit = true
})
srv := httptest.NewServer(mux)
defer srv.Close()
res := testClient().Do(RequestSpec{Method: "GET", URL: srv.URL + "/start", NoFollow: true})
if !res.OK() {
t.Fatalf("a 3xx with NoFollow is not an error (status < 400): %v", res.Err)
}
if res.Status != http.StatusFound {
t.Errorf("Status = %d, want 302", res.Status)
}
if loc := res.Headers.Get("Location"); loc != "/final" {
t.Errorf("Location = %q, want /final", loc)
}
if len(res.Body) == 0 {
t.Error("the 3xx response body should come through")
}
if targetHit {
t.Error("NoFollow must not request the redirect target")
}
if len(res.Redirects) != 0 {
t.Errorf("no hop was followed, but Redirects = %v", res.Redirects)
}
}
func TestRedirectChainRecorded(t *testing.T) {
t.Setenv("WEEB_BASE_URL", "")
t.Setenv("WEEB_HEADERS", "")
t.Setenv("WEEB_TOKEN", "")
mux := http.NewServeMux()
mux.HandleFunc("/start", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/next", http.StatusFound)
})
mux.HandleFunc("/next", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/final", http.StatusMovedPermanently)
})
mux.HandleFunc("/final", func(w http.ResponseWriter, r *http.Request) {})
srv := httptest.NewServer(mux)
defer srv.Close()
res := testClient().Do(RequestSpec{Method: "GET", URL: srv.URL + "/start"})
if !res.OK() {
t.Fatalf("request failed: %v", res.Err)
}
want := []string{srv.URL + "/start", srv.URL + "/next", srv.URL + "/final"}
if len(res.Redirects) != len(want) {
t.Fatalf("Redirects = %v, want %v", res.Redirects, want)
}
for i := range want {
if res.Redirects[i] != want[i] {
t.Errorf("Redirects[%d] = %q, want %q", i, res.Redirects[i], want[i])
}
}
if res.URL != srv.URL+"/final" {
t.Errorf("URL = %q, want the final URL %q", res.URL, srv.URL+"/final")
}
}
// keepsCredentials compares effective ports regardless of scheme: a redirect
// that changes both scheme AND port (http://h:8080 → https://h:8443) is a
// different service on the host and must strip credentials, while the plain
// default-port http→https upgrade stays credentialed.
func TestKeepsCredentials(t *testing.T) {
cases := []struct {
name string
orig string
next string
want bool
}{
{"same origin", "https://api.example.com/a", "https://api.example.com/b", true},
{"same origin explicit default port", "https://api.example.com", "https://api.example.com:443", true},
{"apex to www stripped", "https://example.com", "https://www.example.com", false},
{"https to http downgrade stripped", "https://example.com", "http://example.com", false},
{"http to https default upgrade kept", "http://example.com", "https://example.com", true},
{"http to https same explicit port kept", "http://example.com:8443", "https://example.com:8443", true},
{"same scheme different port stripped", "http://example.com:8080", "http://example.com:9090", false},
{"cross-scheme port change stripped", "http://example.com:8080", "https://example.com:8443", false},
{"cross-scheme to default https port stripped", "http://example.com:8080", "https://example.com", false},
{"host case-insensitive", "https://API.example.com", "https://api.example.com", true},
}
for _, c := range cases {
orig, err := url.Parse(c.orig)
if err != nil {
t.Fatalf("%s: parse %q: %v", c.name, c.orig, err)
}
next, err := url.Parse(c.next)
if err != nil {
t.Fatalf("%s: parse %q: %v", c.name, c.next, err)
}
if got := keepsCredentials(orig, next); got != c.want {
t.Errorf("%s: keepsCredentials(%q, %q) = %v, want %v", c.name, c.orig, c.next, got, c.want)
}
}
}
func TestClientDoStatusErrorSetsBothSeams(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte("nope"))
}))
defer srv.Close()
res := testClient().Do(RequestSpec{Method: "GET", URL: srv.URL})
if res.Status != 404 {
t.Fatalf("status = %d, want 404", res.Status)
}
if res.OK() {
t.Error("OK() = true, want false for 4xx")
}
if res.Err == nil {
t.Error("Err should be set on a 4xx (the record seam)")
}
if res.DisplayErr == "" {
t.Error("DisplayErr should be set on a 4xx (the voice seam)")
}
if string(res.Body) != "nope" {
t.Errorf("body should still be captured on 4xx, got %q", res.Body)
}
}
func TestClientDoSendsMethodHeadersBody(t *testing.T) {
var gotMethod, gotHeader string
var gotBody []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod = r.Method
gotHeader = r.Header.Get("X-Test")
gotBody, _ = io.ReadAll(r.Body)
w.WriteHeader(200)
}))
defer srv.Close()
testClient().Do(RequestSpec{
Method: "POST",
URL: srv.URL,
Headers: []Header{{Key: "X-Test", Value: "hi"}},
Body: []byte("payload"),
})
if gotMethod != "POST" {
t.Errorf("server saw method %q, want POST", gotMethod)
}
if gotHeader != "hi" {
t.Errorf("server saw X-Test %q, want hi", gotHeader)
}
if string(gotBody) != "payload" {
t.Errorf("server saw body %q, want payload", gotBody)
}
}
// An over-limit body must not be buffered unboundedly: the read is capped,
// the kept prefix is surfaced, and the truncation is reported as an error.
func TestClientDoCapsBodySize(t *testing.T) {
old := maxBodyBytes
maxBodyBytes = 1024
t.Cleanup(func() { maxBodyBytes = old })
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(bytes.Repeat([]byte("a"), 4096))
}))
defer srv.Close()
res := testClient().Do(RequestSpec{Method: "GET", URL: srv.URL})
if int64(len(res.Body)) != maxBodyBytes {
t.Errorf("body length = %d, want capped at %d", len(res.Body), maxBodyBytes)
}
if res.Err == nil || res.DisplayErr == "" {
t.Error("an over-limit body should surface a read error on both seams")
}
// The truncation notice is the only signal the body was cut, so it must
// name the real cap — a sub-MiB cap used to be floored to "0 MiB".
if res.Err != nil {
if strings.Contains(res.Err.Error(), "0 MiB") {
t.Errorf("over-cap message floors the cap to zero: %q", res.Err)
}
if !strings.Contains(res.Err.Error(), "1.0 KB") {
t.Errorf("over-cap message should name the 1.0 KB cap, got %q", res.Err)
}
}
// An exactly-at-limit body passes untouched.
exact := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(bytes.Repeat([]byte("a"), 1024))
}))
defer exact.Close()
if res := testClient().Do(RequestSpec{Method: "GET", URL: exact.URL}); !res.OK() || len(res.Body) != 1024 {
t.Errorf("at-limit body should succeed: err=%v len=%d", res.Err, len(res.Body))
}
}
// A BodySink streams the body uncapped — maxBodyBytes protects only buffered
// bodies weeb has to hold in memory to render.
func TestClientDoStreamsToSinkUncapped(t *testing.T) {
old := maxBodyBytes
maxBodyBytes = 1024
t.Cleanup(func() { maxBodyBytes = old })
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(bytes.Repeat([]byte("a"), 4096))
}))
defer srv.Close()
var sink bytes.Buffer
res := testClient().Do(RequestSpec{Method: "GET", URL: srv.URL, BodySink: &sink})
if !res.OK() {
t.Fatalf("streamed request failed: %v", res.Err)
}
if sink.Len() != 4096 {
t.Errorf("sink got %d bytes, want all 4096 (cap must not apply)", sink.Len())
}
if len(res.Body) != 0 {
t.Errorf("streamed body should not also be buffered, got %d bytes", len(res.Body))
}
if res.BodySize != 4096 {
t.Errorf("BodySize = %d, want 4096", res.BodySize)
}
}
// dripServer sends headers immediately, then dribbles the body one byte per
// sleep, so the full transfer takes chunks*pace — long enough to outlast a
// tiny client timeout without slowing the test suite down.
func dripServer(t *testing.T, chunks int, pace time.Duration) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fl := w.(http.Flusher)
w.WriteHeader(http.StatusOK)
fl.Flush()
for range chunks {
time.Sleep(pace)
if _, err := w.Write([]byte("x")); err != nil {
return // client gave up (the explicit-timeout case)
}
fl.Flush()
}
}))
t.Cleanup(srv.Close)
return srv
}
// The DEFAULT timeout must not cap a streamed body copy: headers arrive
// instantly, the transfer outlasts the client timeout, and the stream still
// completes — that's the whole point of the BodySink path (curl -o).
func TestClientDoStreamDefaultTimeoutDoesNotCapBody(t *testing.T) {
srv := dripServer(t, 8, 30*time.Millisecond) // ~240ms transfer
c := testClient()
c.http.Timeout = 50 * time.Millisecond // a tiny "default" timeout
var sink bytes.Buffer
res := c.Do(RequestSpec{Method: "GET", URL: srv.URL, BodySink: &sink})
if !res.OK() {
t.Fatalf("streamed transfer was killed by the default timeout: %v", res.Err)
}
if sink.Len() != 8 {
t.Errorf("sink got %d bytes, want 8", sink.Len())
}
}
// An explicit --timeout is a total cap, so it still kills a too-slow streamed
// transfer.
func TestClientDoStreamExplicitTimeoutCapsBody(t *testing.T) {
srv := dripServer(t, 8, 30*time.Millisecond)
c := testClient()
c.SetTimeout(50 * time.Millisecond)
var sink bytes.Buffer
res := c.Do(RequestSpec{Method: "GET", URL: srv.URL, BodySink: &sink})
if res.Err == nil {
t.Error("explicit timeout should kill a slow streamed transfer")
}
if res.DisplayErr == "" {
t.Error("DisplayErr should be set when the explicit timeout fires")
}
}
// Buffered (non-sink) requests keep the full-transfer timeout regardless.
func TestClientDoBufferedTimeoutStillCapsBody(t *testing.T) {
srv := dripServer(t, 8, 30*time.Millisecond)
c := testClient()
c.http.Timeout = 50 * time.Millisecond
res := c.Do(RequestSpec{Method: "GET", URL: srv.URL})
if res.Err == nil {
t.Error("default timeout should still cap a buffered transfer")
}
if res.DisplayErr == "" {
t.Error("DisplayErr should be set when a buffered transfer times out")
}
}
func TestParseSize(t *testing.T) {
good := map[string]int64{
"1048576": 1 << 20,
"64m": 64 << 20,
"1G": 1 << 30,
"512KiB": 512 << 10,
"2kb": 2 << 10,
"100b": 100,
"0": 0,
}
for in, want := range good {
if got, err := parseSize(in); err != nil || got != want {
t.Errorf("parseSize(%q) = (%d, %v), want %d", in, got, err, want)
}
}
for _, in := range []string{"", "abc", "-1", "12q", "9999999999g"} {
if _, err := parseSize(in); err == nil {
t.Errorf("parseSize(%q) should error", in)
}
}
}
func TestApplyMaxBody(t *testing.T) {
old := maxBodyBytes
t.Cleanup(func() { maxBodyBytes = old })
// Default stands when neither flag nor env is set.
t.Setenv("WEEB_MAX_BODY", "")
maxBodyBytes = old
if err := applyMaxBody(""); err != nil || maxBodyBytes != old {
t.Errorf("no overrides: cap = %d, err = %v; want default %d", maxBodyBytes, err, old)
}
// Env applies; flag wins over env.
t.Setenv("WEEB_MAX_BODY", "1m")
if err := applyMaxBody(""); err != nil || maxBodyBytes != 1<<20 {
t.Errorf("env: cap = %d, err = %v; want 1MiB", maxBodyBytes, err)
}
if err := applyMaxBody("2m"); err != nil || maxBodyBytes != 2<<20 {
t.Errorf("flag should beat env: cap = %d, err = %v; want 2MiB", maxBodyBytes, err)
}
// 0 disables the cap.
if err := applyMaxBody("0"); err != nil || maxBodyBytes != 1<<62 {
t.Errorf("0: cap = %d, err = %v; want uncapped", maxBodyBytes, err)
}
if err := applyMaxBody("nope"); err == nil {
t.Error("bad size should error")
}
}
// -o streams the body to a file, uncapped, with a zero exit.
func TestRunCLIOutputFile(t *testing.T) {
t.Setenv("WEEB_BASE_URL", "")
t.Setenv("WEEB_HEADERS", "")
t.Setenv("WEEB_TOKEN", "")
t.Setenv("WEEB_MAX_BODY", "")
payload := bytes.Repeat([]byte("weeb"), 1024)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(payload)
}))
defer srv.Close()
out := filepath.Join(t.TempDir(), "body.bin")
if code := runCLI(cliArgs{method: "GET", url: srv.URL, output: out}); code != 0 {
t.Fatalf("runCLI exit = %d, want 0", code)
}
got, err := os.ReadFile(out)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, payload) {
t.Errorf("output file has %d bytes, want %d", len(got), len(payload))
}
}
func TestClientDoTransportError(t *testing.T) {
// 127.0.0.1:1 refuses fast — no network round-trip, no hang.
res := testClient().Do(RequestSpec{Method: "GET", URL: "http://127.0.0.1:1"})
if res.Status != 0 {
t.Errorf("status = %d, want 0 (no response)", res.Status)
}
if res.Err == nil {
t.Error("Err should be set on a transport failure")
}
if res.DisplayErr == "" {
t.Error("DisplayErr should be set on a transport failure")
}
}
func TestClientDoBadRequest(t *testing.T) {
res := testClient().Do(RequestSpec{Method: "GET", URL: ""})
if res.Err == nil || res.DisplayErr == "" {
t.Error("empty URL should produce a bad-request error on both seams")
}
}
func TestBuildRequestBodyOnlyForBodyMethods(t *testing.T) {
// GET ignores a body; POST keeps it.
get, err := buildRequest(RequestSpec{Method: "GET", URL: "http://x", Body: []byte("x")})
if err != nil {
t.Fatal(err)
}
if get.Body != nil {
t.Error("GET should not carry a body")
}
post, err := buildRequest(RequestSpec{Method: "POST", URL: "http://x", Body: []byte("x")})
if err != nil {
t.Fatal(err)
}
if post.Body == nil {
t.Error("POST should carry a body")
}
if _, err := buildRequest(RequestSpec{Method: "GET", URL: ""}); err == nil {
t.Error("empty URL should error")
}
// Default method is GET.
def, err := buildRequest(RequestSpec{URL: "http://x"})
if err != nil {
t.Fatal(err)
}
if def.Method != "GET" {
t.Errorf("default method = %q, want GET", def.Method)
}
}
func TestResolveSpecNoEnvIsNoop(t *testing.T) {
t.Setenv("WEEB_BASE_URL", "")
t.Setenv("WEEB_HEADERS", "")
t.Setenv("WEEB_TOKEN", "")
in := RequestSpec{Method: "GET", URL: "https://x/y", Headers: []Header{{Key: "A", Value: "1"}}}
got := resolveSpec(in)
if got.URL != "https://x/y" || len(got.Headers) != 1 {
t.Errorf("resolveSpec changed a fully-specified spec: %+v", got)
}
// A relative URL with no base is left alone.
if got := resolveSpec(RequestSpec{URL: "/me"}); got.URL != "/me" {
t.Errorf("relative URL without base should be untouched, got %q", got.URL)
}
}
func TestResolveSpecBareHostDefaultsHTTP(t *testing.T) {
t.Setenv("WEEB_BASE_URL", "")
t.Setenv("WEEB_HEADERS", "")
t.Setenv("WEEB_TOKEN", "")
// A schemeless host (with or without an explicit port) defaults to http.
if got := resolveSpec(RequestSpec{URL: "example.com:8080/p"}); got.URL != "http://example.com:8080/p" {
t.Errorf("bare host should default to http, got %q", got.URL)
}
// Already-schemed URLs are untouched (https stays https).
if got := resolveSpec(RequestSpec{URL: "https://example.com"}); got.URL != "https://example.com" {
t.Errorf("https URL should be untouched, got %q", got.URL)
}
}
func TestParseHeaderList(t *testing.T) {
tests := []struct {
name string
in string
want []Header
}{
{"empty", "", nil},
{"plain multi-header", "A:1;B:2", []Header{{Key: "A", Value: "1"}, {Key: "B", Value: "2"}}},
{"trims spaces", " A : 1 ; B : 2 ", []Header{{Key: "A", Value: "1"}, {Key: "B", Value: "2"}}},
{"escaped semicolon in value", `A:1\;2;B:3`, []Header{{Key: "A", Value: "1;2"}, {Key: "B", Value: "3"}}},
{"literal backslash via double escape", `A:1\\2`, []Header{{Key: "A", Value: `1\2`}}},
{"stray backslash passes through", `A:1\2`, []Header{{Key: "A", Value: `1\2`}}},
{"trailing and empty segments", "A:1;;B:2;", []Header{{Key: "A", Value: "1"}, {Key: "B", Value: "2"}}},
{"colonless segment skipped", "junk;A:1", []Header{{Key: "A", Value: "1"}}},
{"accept with q param", `Accept:text/html\;q=0.9`, []Header{{Key: "Accept", Value: "text/html;q=0.9"}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := parseHeaderList(tt.in)
if len(got) != len(tt.want) {
t.Fatalf("parseHeaderList(%q) = %+v, want %+v", tt.in, got, tt.want)
}
for i := range got {
if got[i] != tt.want[i] {
t.Errorf("parseHeaderList(%q)[%d] = %+v, want %+v", tt.in, i, got[i], tt.want[i])
}
}
})
}
}