You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

82 lines
1.9 KiB

  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. package storage
  15. import (
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. "io"
  20. "io/ioutil"
  21. "net/http"
  22. "strings"
  23. "testing"
  24. "google.golang.org/api/option"
  25. )
  26. type mockTransport struct {
  27. gotReq *http.Request
  28. gotBody []byte
  29. results []transportResult
  30. }
  31. type transportResult struct {
  32. res *http.Response
  33. err error
  34. }
  35. func (t *mockTransport) addResult(res *http.Response, err error) {
  36. t.results = append(t.results, transportResult{res, err})
  37. }
  38. func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  39. t.gotReq = req
  40. t.gotBody = nil
  41. if req.Body != nil {
  42. bytes, err := ioutil.ReadAll(req.Body)
  43. if err != nil {
  44. return nil, err
  45. }
  46. t.gotBody = bytes
  47. }
  48. if len(t.results) == 0 {
  49. return nil, fmt.Errorf("error handling request")
  50. }
  51. result := t.results[0]
  52. t.results = t.results[1:]
  53. return result.res, result.err
  54. }
  55. func (t *mockTransport) gotJSONBody() map[string]interface{} {
  56. m := map[string]interface{}{}
  57. if err := json.Unmarshal(t.gotBody, &m); err != nil {
  58. panic(err)
  59. }
  60. return m
  61. }
  62. func mockClient(t *testing.T, m *mockTransport) *Client {
  63. client, err := NewClient(context.Background(), option.WithHTTPClient(&http.Client{Transport: m}))
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. return client
  68. }
  69. func bodyReader(s string) io.ReadCloser {
  70. return ioutil.NopCloser(strings.NewReader(s))
  71. }