OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The LUCI Authors. All rights reserved. |
| 2 // Use of this source code is governed under the Apache License, Version 2.0 |
| 3 // that can be found in the LICENSE file. |
| 4 |
| 5 package internal |
| 6 |
| 7 import ( |
| 8 "bytes" |
| 9 "io/ioutil" |
| 10 "net/http" |
| 11 "sync" |
| 12 |
| 13 "golang.org/x/net/context" |
| 14 ) |
| 15 |
| 16 var testTransportKey = "testTransport" |
| 17 |
| 18 // TestTransportCallback is used from unit tests. |
| 19 type TestTransportCallback func(r *http.Request, body string) (code int, respons
e string) |
| 20 |
| 21 // WithTestTransport puts a testing transport in the context to use for fetches. |
| 22 func WithTestTransport(c context.Context, cb TestTransportCallback) context.Cont
ext { |
| 23 return context.WithValue(c, &testTransportKey, &testTransport{cb: cb}) |
| 24 } |
| 25 |
| 26 type testTransport struct { |
| 27 lock sync.Mutex |
| 28 cb TestTransportCallback |
| 29 } |
| 30 |
| 31 func (t *testTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| 32 t.lock.Lock() |
| 33 defer t.lock.Unlock() |
| 34 body, err := ioutil.ReadAll(r.Body) |
| 35 r.Body.Close() |
| 36 if err != nil { |
| 37 return nil, err |
| 38 } |
| 39 code, resp := t.cb(r, string(body)) |
| 40 return &http.Response{ |
| 41 StatusCode: code, |
| 42 Body: ioutil.NopCloser(bytes.NewReader([]byte(resp))), |
| 43 }, nil |
| 44 } |
OLD | NEW |