github.com/blend/go-sdk@v1.20220411.3/vault/mock_http_client.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package vault
     9  
    10  import (
    11  	"bytes"
    12  	"fmt"
    13  	"io"
    14  	"net/http"
    15  	"net/url"
    16  )
    17  
    18  // NewMockHTTPClient returns a new mock http client.
    19  // MockHTTPClient is used to test VaultClient itself, and should
    20  // not be used for your own mocks.
    21  func NewMockHTTPClient() *MockHTTPClient {
    22  	return &MockHTTPClient{
    23  		contents: make(map[string]*http.Response),
    24  	}
    25  }
    26  
    27  // MockHTTPClient is a mock http client.
    28  // It is used to test the vault client iself, and should not be used for your own mocks.
    29  type MockHTTPClient struct {
    30  	contents map[string]*http.Response
    31  }
    32  
    33  // With adds a mocked endpoint.
    34  func (mh *MockHTTPClient) With(verb string, url *url.URL, response *http.Response) *MockHTTPClient {
    35  	mh.contents[fmt.Sprintf("%s_%s", verb, url.String())] = response
    36  	return mh
    37  }
    38  
    39  // WithString adds a mocked endpoint.
    40  func (mh *MockHTTPClient) WithString(verb string, url *url.URL, contents string) *MockHTTPClient {
    41  	mh.contents[fmt.Sprintf("%s_%s", verb, url.String())] = &http.Response{
    42  		StatusCode: http.StatusOK,
    43  		Body:       io.NopCloser(bytes.NewBuffer([]byte(contents))),
    44  	}
    45  	return mh
    46  }
    47  
    48  // Do implements HTTPClient.
    49  func (mh *MockHTTPClient) Do(req *http.Request) (*http.Response, error) {
    50  	if res, hasRes := mh.contents[fmt.Sprintf("%s_%s", req.Method, req.URL.String())]; hasRes {
    51  		return res, nil
    52  	}
    53  	return nil, fmt.Errorf("not found")
    54  }