1
2
3
4
5 package gensupport
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "net/http"
12 "testing"
13
14 "github.com/google/go-cmp/cmp"
15 "github.com/googleapis/gax-go/v2/callctx"
16 )
17
18 func TestSendRequest(t *testing.T) {
19
20 req, _ := http.NewRequest("GET", "url", nil)
21 req.Header.Set("Accept-Encoding", "")
22 _, err := SendRequest(context.Background(), nil, req)
23 if err == nil {
24 t.Error("got nil, want error")
25 }
26 }
27
28 func TestSendRequestWithRetry(t *testing.T) {
29
30 req, _ := http.NewRequest("GET", "url", nil)
31 req.Header.Set("Accept-Encoding", "")
32 _, err := SendRequestWithRetry(context.Background(), nil, req, nil)
33 if err == nil {
34 t.Error("got nil, want error")
35 }
36 }
37
38 type headerRoundTripper struct {
39 wantHeader http.Header
40 }
41
42 func (rt *headerRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
43
44 r.Header.Del("X-Goog-Api-Client")
45 r.Header.Del("X-Goog-Gcs-Idempotency-Token")
46 if diff := cmp.Diff(r.Header, rt.wantHeader); diff != "" {
47 return nil, fmt.Errorf("headers don't match: %v", diff)
48 }
49 return &http.Response{StatusCode: 200}, nil
50 }
51
52
53 func TestSendRequestHeader(t *testing.T) {
54 ctx := context.Background()
55 ctx = callctx.SetHeaders(ctx, "foo", "100", "bar", "200")
56 client := http.Client{
57 Transport: &headerRoundTripper{
58 wantHeader: map[string][]string{"Foo": {"100"}, "Bar": {"200"}},
59 },
60 }
61 req, _ := http.NewRequest("GET", "url", nil)
62 if _, err := SendRequest(ctx, &client, req); err != nil {
63 t.Errorf("SendRequest: %v", err)
64 }
65 req2, _ := http.NewRequest("GET", "url", nil)
66 if _, err := SendRequestWithRetry(ctx, &client, req2, nil); err != nil {
67 t.Errorf("SendRequest: %v", err)
68 }
69 }
70
71 type brokenRoundTripper struct{}
72
73 func (t *brokenRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
74 return nil, errors.New("this should not happen")
75 }
76
77 func TestCanceledContextDoesNotPerformRequest(t *testing.T) {
78 client := http.Client{
79 Transport: &brokenRoundTripper{},
80 }
81 for i := 0; i < 1000; i++ {
82 req, _ := http.NewRequest("GET", "url", nil)
83 ctx, cancel := context.WithCancel(context.Background())
84 cancel()
85 _, err := SendRequestWithRetry(ctx, &client, req, nil)
86 if !errors.Is(err, context.Canceled) {
87 t.Fatalf("got %v, want %v", err, context.Canceled)
88 }
89 }
90 }
91
View as plain text