github.com/wanddynosios/cli/v8@v8.7.9-0.20240221182337-1a92e3a7017f/integration/v7/selfcontained/fake/cf_api.go (about)

     1  package fake
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  	"strings"
     8  
     9  	. "github.com/onsi/gomega"
    10  	"github.com/onsi/gomega/ghttp"
    11  )
    12  
    13  type CFAPI struct {
    14  	server *ghttp.Server
    15  }
    16  
    17  type CFAPIConfig struct {
    18  	Routes map[string]Response
    19  }
    20  
    21  type Response struct {
    22  	Code int
    23  	Body interface{}
    24  }
    25  
    26  func NewCFAPI() *CFAPI {
    27  	server := ghttp.NewServer()
    28  	return &CFAPI{
    29  		server: server,
    30  	}
    31  }
    32  
    33  func (a *CFAPI) SetConfiguration(config CFAPIConfig) {
    34  	a.server.Reset()
    35  
    36  	for request, response := range config.Routes {
    37  		method, path := parseRequest(request)
    38  		responseBytes, err := json.Marshal(response.Body)
    39  		Expect(err).NotTo(HaveOccurred())
    40  
    41  		a.server.RouteToHandler(method, path, ghttp.RespondWith(response.Code, responseBytes))
    42  	}
    43  }
    44  
    45  func (a *CFAPI) Close() {
    46  	a.server.Close()
    47  }
    48  
    49  func (a *CFAPI) URL() string {
    50  	return a.server.URL()
    51  }
    52  
    53  func (a *CFAPI) ReceivedRequests() map[string][]*http.Request {
    54  	result := map[string][]*http.Request{}
    55  
    56  	for _, req := range a.server.ReceivedRequests() {
    57  		key := fmt.Sprintf("%s %s", req.Method, req.URL.Path)
    58  		result[key] = append(result[key], req)
    59  	}
    60  
    61  	return result
    62  }
    63  
    64  func parseRequest(request string) (string, string) {
    65  	fields := strings.Split(request, " ")
    66  	Expect(fields).To(HaveLen(2))
    67  	return fields[0], fields[1]
    68  }