...

Source file src/google.golang.org/grpc/internal/testutils/http_client.go

Documentation: google.golang.org/grpc/internal/testutils

     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  
    18  package testutils
    19  
    20  import (
    21  	"context"
    22  	"net/http"
    23  	"time"
    24  )
    25  
    26  // DefaultHTTPRequestTimeout is the default timeout value for the amount of time
    27  // this client waits for a response to be pushed on RespChan before it fails the
    28  // Do() call.
    29  const DefaultHTTPRequestTimeout = 1 * time.Second
    30  
    31  // FakeHTTPClient helps mock out HTTP calls made by the code under test. It
    32  // makes HTTP requests made by the code under test available through a channel,
    33  // and makes it possible to inject various responses.
    34  type FakeHTTPClient struct {
    35  	// ReqChan exposes the HTTP.Request made by the code under test.
    36  	ReqChan *Channel
    37  	// RespChan is a channel on which this fake client accepts responses to be
    38  	// sent to the code under test.
    39  	RespChan *Channel
    40  	// Err, if set, is returned by Do().
    41  	Err error
    42  	// RecvTimeout is the amount of the time this client waits for a response to
    43  	// be pushed on RespChan before it fails the Do() call. If this field is
    44  	// left unspecified, DefaultHTTPRequestTimeout is used.
    45  	RecvTimeout time.Duration
    46  }
    47  
    48  // Do pushes req on ReqChan and returns the response available on RespChan.
    49  func (fc *FakeHTTPClient) Do(req *http.Request) (*http.Response, error) {
    50  	fc.ReqChan.Send(req)
    51  
    52  	timeout := fc.RecvTimeout
    53  	if timeout == 0 {
    54  		timeout = DefaultHTTPRequestTimeout
    55  	}
    56  	ctx, cancel := context.WithTimeout(context.Background(), timeout)
    57  	defer cancel()
    58  	val, err := fc.RespChan.Receive(ctx)
    59  	if err != nil {
    60  		return nil, err
    61  	}
    62  	return val.(*http.Response), fc.Err
    63  }
    64  

View as plain text