github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/apim/HttpMockAPIM.go (about)

     1  //go:build !release
     2  // +build !release
     3  
     4  package apim
     5  
     6  import (
     7  	"bytes"
     8  	"io"
     9  	"net/http"
    10  
    11  	piperhttp "github.com/SAP/jenkins-library/pkg/http"
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  type HttpMockAPIM struct {
    16  	Method       string                  // is set during test execution
    17  	URL          string                  // is set before test execution
    18  	Header       map[string][]string     // is set before test execution
    19  	ResponseBody string                  // is set before test execution
    20  	Options      piperhttp.ClientOptions // is set during test
    21  	StatusCode   int                     // is set during test
    22  }
    23  
    24  // Sender provides an interface to the piper http client for uid/pwd and token authenticated requests
    25  type SenderMock interface {
    26  	SendRequest(method, url string, body io.Reader, header http.Header, cookies []*http.Cookie) (*http.Response, error)
    27  	SetOptions(options piperhttp.ClientOptions)
    28  }
    29  
    30  // Sender provides an interface to the piper http client for uid/pwd and token authenticated requests
    31  type ServciceKeyMock interface {
    32  	GetServiceKey() string
    33  }
    34  
    35  func (c *HttpMockAPIM) SetOptions(options piperhttp.ClientOptions) {
    36  	c.Options = options
    37  }
    38  
    39  func (c *HttpMockAPIM) SendRequest(method string, url string, r io.Reader, header http.Header, cookies []*http.Cookie) (*http.Response, error) {
    40  
    41  	c.Method = method
    42  	c.URL = url
    43  
    44  	if r != nil {
    45  		_, err := io.ReadAll(r)
    46  
    47  		if err != nil {
    48  			return nil, err
    49  		}
    50  	}
    51  
    52  	res := http.Response{
    53  		StatusCode: c.StatusCode,
    54  		Header:     c.Header,
    55  		Body:       io.NopCloser(bytes.NewReader([]byte(c.ResponseBody))),
    56  	}
    57  
    58  	if c.StatusCode >= 400 {
    59  		return &res, errors.New("Bad Request")
    60  	}
    61  
    62  	return &res, nil
    63  }
    64  
    65  func GetServiceKey() string {
    66  	apiServiceKey := `{
    67  		"oauth": {
    68  			"url": "https://demo",
    69  			"clientid": "demouser",
    70  			"clientsecret": "******",
    71  			"tokenurl": "https://demo/oauth/token"
    72  			}
    73  		}`
    74  	return apiServiceKey
    75  }