http_client.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. *
  3. * Copyright 2020 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package testutils
  18. import (
  19. "context"
  20. "net/http"
  21. "time"
  22. )
  23. // DefaultHTTPRequestTimeout is the default timeout value for the amount of time
  24. // this client waits for a response to be pushed on RespChan before it fails the
  25. // Do() call.
  26. const DefaultHTTPRequestTimeout = 1 * time.Second
  27. // FakeHTTPClient helps mock out HTTP calls made by the code under test. It
  28. // makes HTTP requests made by the code under test available through a channel,
  29. // and makes it possible to inject various responses.
  30. type FakeHTTPClient struct {
  31. // ReqChan exposes the HTTP.Request made by the code under test.
  32. ReqChan *Channel
  33. // RespChan is a channel on which this fake client accepts responses to be
  34. // sent to the code under test.
  35. RespChan *Channel
  36. // Err, if set, is returned by Do().
  37. Err error
  38. // RecvTimeout is the amount of the time this client waits for a response to
  39. // be pushed on RespChan before it fails the Do() call. If this field is
  40. // left unspecified, DefaultHTTPRequestTimeout is used.
  41. RecvTimeout time.Duration
  42. }
  43. // Do pushes req on ReqChan and returns the response available on RespChan.
  44. func (fc *FakeHTTPClient) Do(req *http.Request) (*http.Response, error) {
  45. fc.ReqChan.Send(req)
  46. timeout := fc.RecvTimeout
  47. if timeout == 0 {
  48. timeout = DefaultHTTPRequestTimeout
  49. }
  50. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  51. defer cancel()
  52. val, err := fc.RespChan.Receive(ctx)
  53. if err != nil {
  54. return nil, err
  55. }
  56. return val.(*http.Response), fc.Err
  57. }