...

Source file src/cloud.google.com/go/storage/mock_test.go

Documentation: cloud.google.com/go/storage

     1  // Copyright 2018 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    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