This repository has been archived by the owner on Oct 6, 2021. It is now read-only.
forked from jarcoal/httpmock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransport.go
424 lines (368 loc) · 12.5 KB
/
transport.go
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
package httpmock
import (
"errors"
"fmt"
"net/http"
"sort"
"strings"
"sync"
)
// Responders are callbacks that receive and http request and return a mocked response.
type Responder func(*http.Request) (*http.Response, error)
// NoResponderFound is returned when no responders are found for a given HTTP method and URL.
var NoResponderFound = errors.New("no responder found")
// ConnectionFailure is a responder that returns a connection failure. This is the default
// responder, and is called when no other matching responder is found.
func ConnectionFailure(*http.Request) (*http.Response, error) {
return nil, NoResponderFound
}
// NewMockTransport creates a new *MockTransport with no responders.
func NewMockTransport() *MockTransport {
return &MockTransport{
responders: make(map[string]Responder),
callCountInfo: make(map[string]int),
}
}
// MockTransport implements http.RoundTripper, which fulfills single http requests issued by
// an http.Client. This implementation doesn't actually make the call, instead deferring to
// the registered list of responders.
type MockTransport struct {
mu sync.RWMutex
responders map[string]Responder
noResponder Responder
callCountInfo map[string]int
totalCallCount int
}
// RoundTrip receives HTTP requests and routes them to the appropriate responder. It is required to
// implement the http.RoundTripper interface. You will not interact with this directly, instead
// the *http.Client you are using will call it for you.
func (m *MockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
queryAsMap := make(map[string]string)
for k, v := range map[string][]string(req.URL.Query()) {
queryAsMap[k] = v[0]
}
query := mapToSortedQuery(queryAsMap)
url := req.URL.String()
if query != nil {
url = strings.Replace(url, req.URL.RawQuery, *query, -1)
}
method := req.Method
if method == "" {
// http.Request.Method is documented to default to GET:
method = http.MethodGet
}
// try and get a responder that matches the method and URL
key := method + " " + url
responder := m.responderForKey(key)
// if we weren't able to find a responder
if responder == nil {
strippedURL := *req.URL
strippedURL.RawQuery = ""
strippedURL.Fragment = ""
// go1.6 does not handle URL.ForceQuery, so in case it is set in go>1.6,
// remove the "?" manually if present.
surl := strings.TrimSuffix(strippedURL.String(), "?")
hasQueryString := url != surl
// if the URL contains a querystring then we strip off the
// querystring and try again.
if hasQueryString {
key = method + " " + surl
responder = m.responderForKey(key)
}
// if we weren't able to find a responder for the full URL, try with
// the path part only
if responder == nil {
keyPathAlone := method + " " + req.URL.Path
key = keyPathAlone
// First with querystring
if hasQueryString {
key += strings.TrimPrefix(url, surl) // concat after-path part
responder = m.responderForKey(key)
}
// Then using path alone
if responder == nil || key == keyPathAlone {
responder = m.responderForKey(keyPathAlone)
}
}
}
m.mu.Lock()
defer m.mu.Unlock()
// if we found a responder, call it
if responder != nil {
m.callCountInfo[key]++
m.totalCallCount++
return runCancelable(responder, req)
}
// we didn't find a responder, so fire the 'no responder' responder
if m.noResponder == nil {
return ConnectionFailure(req)
}
m.callCountInfo["NO_RESPONDER"]++
m.totalCallCount++
return runCancelable(m.noResponder, req)
}
func runCancelable(responder Responder, req *http.Request) (*http.Response, error) {
if req.Cancel == nil {
return responder(req)
}
// Set up a goroutine that translates a close(req.Cancel) into a
// "request canceled" error, and another one that runs the
// responder. Then race them: first to the result channel wins.
type result struct {
response *http.Response
err error
}
resultch := make(chan result, 1)
done := make(chan struct{}, 1)
go func() {
select {
case <-req.Cancel:
resultch <- result{
response: nil,
err: errors.New("request canceled"),
}
case <-done:
}
}()
go func() {
defer func() {
if err := recover(); err != nil {
resultch <- result{
response: nil,
err: fmt.Errorf("panic in responder: got %q", err),
}
}
}()
response, err := responder(req)
resultch <- result{
response: response,
err: err,
}
}()
r := <-resultch
// if a close(req.Cancel) is never coming,
// we'll need to unblock the first goroutine.
done <- struct{}{}
return r.response, r.err
}
// do nothing with timeout
func (m *MockTransport) CancelRequest(req *http.Request) {}
// responderForKey returns a responder for a given key
func (m *MockTransport) responderForKey(key string) Responder {
m.mu.RLock()
defer m.mu.RUnlock()
return m.responders[key]
}
// RegisterResponder adds a new responder, associated with a given HTTP method and URL (or path). When a
// request comes in that matches, the responder will be called and the response returned to the client.
func (m *MockTransport) RegisterResponder(method, url string, responder Responder) {
key := method + " " + url
m.mu.Lock()
m.responders[key] = responder
m.callCountInfo[key] = 0
m.mu.Unlock()
}
// RegisterResponderWithQuery is same as RegisterResponder, but it doesn't depend on query items order
func (m *MockTransport) RegisterResponderWithQuery(method, path string, query map[string]string, responder Responder) {
url := path
queryString := mapToSortedQuery(query)
if queryString != nil {
url = path + "?" + *queryString
}
m.RegisterResponder(method, url, responder)
}
func mapToSortedQuery(m map[string]string) *string {
if m == nil {
return nil
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
if len(keys) == 0 {
return nil
}
sort.Strings(keys)
var queryArray []string
for _, k := range keys {
queryArray = append(queryArray, fmt.Sprintf("%s=%s", k, m[k]))
}
query := strings.Join(queryArray, "&")
return &query
}
// RegisterNoResponder is used to register a responder that will be called if no other responder is
// found. The default is ConnectionFailure.
func (m *MockTransport) RegisterNoResponder(responder Responder) {
m.mu.Lock()
m.noResponder = responder
m.mu.Unlock()
}
// Reset removes all registered responders (including the no responder) from the MockTransport
func (m *MockTransport) Reset() {
m.mu.Lock()
m.responders = make(map[string]Responder)
m.noResponder = nil
m.callCountInfo = make(map[string]int)
m.totalCallCount = 0
m.mu.Unlock()
}
// GetCallCountInfo returns callCountInfo
func (m *MockTransport) GetCallCountInfo() map[string]int {
res := map[string]int{}
m.mu.RLock()
for k, v := range m.callCountInfo {
res[k] = v
}
m.mu.RUnlock()
return res
}
// GetTotalCallCount returns the totalCallCount
func (m *MockTransport) GetTotalCallCount() int {
m.mu.RLock()
count := m.totalCallCount
m.mu.RUnlock()
return count
}
// DefaultTransport is the default mock transport used by Activate, Deactivate, Reset,
// DeactivateAndReset, RegisterResponder, and RegisterNoResponder.
var DefaultTransport = NewMockTransport()
// InitialTransport is a cache of the original transport used so we can put it back
// when Deactivate is called.
var InitialTransport = http.DefaultTransport
// Used to handle custom http clients (i.e clients other than http.DefaultClient)
var oldTransport http.RoundTripper
var oldClient *http.Client
// Activate starts the mock environment. This should be called before your tests run. Under the
// hood this replaces the Transport on the http.DefaultClient with DefaultTransport.
//
// To enable mocks for a test, simply activate at the beginning of a test:
// func TestFetchArticles(t *testing.T) {
// httpmock.Activate()
// // all http requests will now be intercepted
// }
//
// If you want all of your tests in a package to be mocked, just call Activate from init():
// func init() {
// httpmock.Activate()
// }
func Activate() {
if Disabled() {
return
}
// make sure that if Activate is called multiple times it doesn't overwrite the InitialTransport
// with a mock transport.
if http.DefaultTransport != DefaultTransport {
InitialTransport = http.DefaultTransport
}
http.DefaultTransport = DefaultTransport
}
// ActivateNonDefault starts the mock environment with a non-default http.Client.
// This emulates the Activate function, but allows for custom clients that do not use
// http.DefaultTransport
//
// To enable mocks for a test using a custom client, activate at the beginning of a test:
// client := &http.Client{Transport: &http.Transport{TLSHandshakeTimeout: 60 * time.Second}}
// httpmock.ActivateNonDefault(client)
func ActivateNonDefault(client *http.Client) {
if Disabled() {
return
}
// save the custom client & it's RoundTripper
oldTransport = client.Transport
oldClient = client
client.Transport = DefaultTransport
}
// GetCallCountInfo gets the info on all the calls httpmock has taken since it was activated or
// reset. The info is returned as a map of the calling keys with the number of calls made to them
// as their value. The key is the method, a space, and the url all concatenated together.
func GetCallCountInfo() map[string]int {
return DefaultTransport.GetCallCountInfo()
}
// GetTotalCallCount gets the total number of calls httpmock has taken since it was activated or
// reset.
func GetTotalCallCount() int {
return DefaultTransport.GetTotalCallCount()
}
// Deactivate shuts down the mock environment. Any HTTP calls made after this will use a live
// transport.
//
// Usually you'll call it in a defer right after activating the mock environment:
// func TestFetchArticles(t *testing.T) {
// httpmock.Activate()
// defer httpmock.Deactivate()
//
// // when this test ends, the mock environment will close
// }
func Deactivate() {
if Disabled() {
return
}
http.DefaultTransport = InitialTransport
// reset the custom client to use it's original RoundTripper
if oldClient != nil {
oldClient.Transport = oldTransport
}
}
// Reset will remove any registered mocks and return the mock environment to it's initial state.
func Reset() {
DefaultTransport.Reset()
}
// DeactivateAndReset is just a convenience method for calling Deactivate() and then Reset()
// Happy deferring!
func DeactivateAndReset() {
Deactivate()
Reset()
}
// RegisterResponder adds a mock that will catch requests to the given HTTP method and URL (or path), then
// route them to the Responder which will generate a response to be returned to the client.
//
// Example:
// func TestFetchArticles(t *testing.T) {
// httpmock.Activate()
// httpmock.DeactivateAndReset()
//
// httpmock.RegisterResponder("GET", "http://example.com/",
// httpmock.NewStringResponder("hello world", 200))
//
// httpmock.RegisterResponder("GET", "/path/only",
// httpmock.NewStringResponder("any host hello world", 200))
//
// // requests to http://example.com/ will now return 'hello world' and
// // requests to any host with path /path/only will return 'any host hello world'
// }
func RegisterResponder(method, url string, responder Responder) {
DefaultTransport.RegisterResponder(method, url, responder)
}
// RegisterResponderWithQuery it is same as RegisterResponder, but doesn't depends on query objects order.
//
// Example:
// func TestFetchArticles(t *testing.T) {
// httpmock.Activate()
// httpmock.DeactivateAndReset()
// expecedQuery := map[string]string{
// "a": "1",
// "b": "2"
// }
//
// httpmock.RegisterResponderWithQuery("GET", "http://example.com/", expecedQuery,
// httpmock.NewStringResponder("hello world", 200))
//
// // requests to http://example.com?a=1&b=2 and http://example.com?b=2&a=1 will now return 'hello world'
// }
func RegisterResponderWithQuery(method, path string, query map[string]string, responder Responder) {
DefaultTransport.RegisterResponderWithQuery(method, path, query, responder)
}
// RegisterNoResponder adds a mock that will be called whenever a request for an unregistered URL
// is received. The default behavior is to return a connection error.
//
// In some cases you may not want all URLs to be mocked, in which case you can do this:
// func TestFetchArticles(t *testing.T) {
// httpmock.Activate()
// httpmock.DeactivateAndReset()
// httpmock.RegisterNoResponder(httpmock.InitialTransport.RoundTrip)
//
// // any requests that don't have a registered URL will be fetched normally
// }
func RegisterNoResponder(responder Responder) {
DefaultTransport.RegisterNoResponder(responder)
}