Repository navigation
Expand file tree
/
Copy pathcontext_test.go
More file actions
211 lines (182 loc) · 5.96 KB
/
Copy pathcontext_test.go
File metadata and controls
211 lines (182 loc) · 5.96 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
package serpapi
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"testing"
"time"
)
type contextTransport struct{}
func (contextTransport) RoundTrip(request *http.Request) (*http.Response, error) {
<-request.Context().Done()
return nil, request.Context().Err()
}
func TestSearchContextCancellation(t *testing.T) {
client := NewClient(NewSerpApiClientSetting(""))
client.HttpSearch = &http.Client{Transport: contextTransport{}}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := client.SearchContext(ctx, map[string]string{"q": "coffee"})
if !errors.Is(err, context.Canceled) {
t.Fatalf("expected context.Canceled, got %v", err)
}
}
type responseTransport struct{}
func (responseTransport) RoundTrip(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(&stringReader{value: `{"ok":true}`}),
Header: make(http.Header),
}, nil
}
type stringReader struct {
value string
read bool
}
func (reader *stringReader) Read(buffer []byte) (int, error) {
if reader.read {
return 0, io.EOF
}
reader.read = true
return copy(buffer, reader.value), nil
}
type failingTransport struct{}
func (failingTransport) RoundTrip(*http.Request) (*http.Response, error) {
return nil, errors.New("connection refused")
}
func TestTransportErrorDoesNotLeakAPIKey(t *testing.T) {
client := NewClient(NewSerpApiClientSetting("secret_api_key"))
client.HttpSearch = &http.Client{Transport: failingTransport{}}
_, err := client.Search(map[string]string{"q": "coffee"})
if err == nil {
t.Fatal("expected an error")
}
if strings.Contains(err.Error(), "secret_api_key") {
t.Fatalf("error leaks the API key: %v", err)
}
}
func TestSearchRemainsUsableWithoutContext(t *testing.T) {
client := NewClient(NewSerpApiClientSetting(""))
client.HttpSearch = &http.Client{Transport: responseTransport{}}
result, err := client.Search(map[string]string{"q": "coffee"})
if err != nil {
t.Fatalf("Search returned an error: %v", err)
}
if result["ok"] != true {
t.Fatalf("expected ok response, got %#v", result)
}
}
type errorTransport struct{}
func (errorTransport) RoundTrip(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusTooManyRequests,
Status: "429 Too Many Requests",
Body: io.NopCloser(&stringReader{value: `{"error":"rate limit exceeded"}`}),
Header: make(http.Header),
}, nil
}
func TestSearchReturnsHTTPError(t *testing.T) {
client := NewClient(NewSerpApiClientSetting("secret_api_key"))
client.HttpSearch = &http.Client{Transport: errorTransport{}}
_, err := client.Search(map[string]string{"q": "coffee"})
var httpErr *HTTPError
if !errors.As(err, &httpErr) {
t.Fatalf("expected HTTPError, got %v", err)
}
if httpErr.StatusCode != http.StatusTooManyRequests {
t.Fatalf("expected status code %d, got %d", http.StatusTooManyRequests, httpErr.StatusCode)
}
if httpErr.Body != `{"error":"rate limit exceeded"}` {
t.Fatalf("unexpected response body: %q", httpErr.Body)
}
if httpErr.URL == "" {
t.Fatal("expected request URL in HTTPError")
}
if strings.Contains(httpErr.URL, "secret_api_key") {
t.Fatalf("HTTPError URL leaks the API key: %s", httpErr.URL)
}
if got := httpErr.Error(); got != fmt.Sprintf("serpapi request failed: 429 Too Many Requests: %s", httpErr.Body) {
t.Fatalf("unexpected error string: %q", got)
}
}
type captureTransport struct {
request *http.Request
}
func (transport *captureTransport) RoundTrip(request *http.Request) (*http.Response, error) {
transport.request = request
return &http.Response{
StatusCode: http.StatusOK,
Status: "200 OK",
Body: io.NopCloser(&stringReader{value: `{}`}),
Header: make(http.Header),
}, nil
}
func TestSearchContextBuildsExpectedQuery(t *testing.T) {
setting := NewSerpApiClientSetting("secret")
setting.Parameter = map[string]string{
"hl": "en",
"gl": "us",
}
client := NewClient(setting)
transport := &captureTransport{}
client.HttpSearch = &http.Client{Transport: transport}
_, err := client.SearchContext(context.Background(), map[string]string{
"q": "coffee",
"hl": "fr",
})
if err != nil {
t.Fatalf("SearchContext returned an error: %v", err)
}
query := transport.request.URL.Query()
expected := url.Values{
"api_key": {"secret"},
"engine": {"google"},
"gl": {"us"},
"hl": {"fr"},
"output": {"json"},
"q": {"coffee"},
"source": {"go:" + VERSION},
}
if query.Encode() != expected.Encode() {
t.Fatalf("unexpected query: got %s, want %s", query.Encode(), expected.Encode())
}
}
func TestSearchArchiveContextEscapesID(t *testing.T) {
client := NewClient(NewSerpApiClientSetting(""))
transport := &captureTransport{}
client.HttpSearch = &http.Client{Transport: transport}
_, err := client.SearchArchiveContext(context.Background(), "search/id")
if err != nil {
t.Fatalf("SearchArchiveContext returned an error: %v", err)
}
if got, want := transport.request.URL.EscapedPath(), "/searches/search%2Fid.json"; got != want {
t.Fatalf("unexpected archive path: got %q, want %q", got, want)
}
}
func TestNewClientConfiguresTransport(t *testing.T) {
setting := NewSerpApiClientSetting("")
setting.Persistent = true
setting.MaxIdleConnection = 12
setting.KeepAlive = 45 * time.Second
client := NewClient(setting)
transport, ok := client.HttpSearch.Transport.(*http.Transport)
if !ok {
t.Fatalf("expected *http.Transport, got %T", client.HttpSearch.Transport)
}
if transport.DisableKeepAlives {
t.Fatal("expected persistent client to keep connections alive")
}
if transport.MaxIdleConns != setting.MaxIdleConnection {
t.Fatalf("expected MaxIdleConns %d, got %d", setting.MaxIdleConnection, transport.MaxIdleConns)
}
if transport.MaxIdleConnsPerHost != setting.MaxIdleConnection {
t.Fatalf("expected MaxIdleConnsPerHost %d, got %d", setting.MaxIdleConnection, transport.MaxIdleConnsPerHost)
}
if transport.Proxy == nil {
t.Fatal("expected default proxy support to be preserved")
}
}