github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/grpc/internal/testutils/http_client.go (about)

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