...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package storage
16
17 import (
18 "context"
19 "encoding/json"
20 "fmt"
21 "io"
22 "io/ioutil"
23 "net/http"
24 "strings"
25 "testing"
26
27 "google.golang.org/api/option"
28 )
29
30 type mockTransport struct {
31 gotReq *http.Request
32 gotBody []byte
33 results []transportResult
34 }
35
36 type transportResult struct {
37 res *http.Response
38 err error
39 }
40
41 func (t *mockTransport) addResult(res *http.Response, err error) {
42 t.results = append(t.results, transportResult{res, err})
43 }
44
45 func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
46 t.gotReq = req
47 t.gotBody = nil
48 if req.Body != nil {
49 bytes, err := ioutil.ReadAll(req.Body)
50 if err != nil {
51 return nil, err
52 }
53 t.gotBody = bytes
54 }
55 if len(t.results) == 0 {
56 return nil, fmt.Errorf("error handling request")
57 }
58 result := t.results[0]
59 t.results = t.results[1:]
60 return result.res, result.err
61 }
62
63 func (t *mockTransport) gotJSONBody() map[string]interface{} {
64 m := map[string]interface{}{}
65 if err := json.Unmarshal(t.gotBody, &m); err != nil {
66 panic(err)
67 }
68 return m
69 }
70
71 func mockClient(t *testing.T, m *mockTransport, opts ...option.ClientOption) *Client {
72 opts = append(opts, option.WithHTTPClient(&http.Client{Transport: m}))
73 client, err := NewClient(context.Background(), opts...)
74 if err != nil {
75 t.Fatal(err)
76 }
77 return client
78 }
79
80 func bodyReader(s string) io.ReadCloser {
81 return ioutil.NopCloser(strings.NewReader(s))
82 }
83
View as plain text