github.com/loafoe/cli@v7.1.0+incompatible/integration/helpers/ginkgo_routing_extension.go (about)

     1  package helpers
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net/http"
     7  	"net/url"
     8  	"strings"
     9  
    10  	. "github.com/onsi/gomega"
    11  	"github.com/onsi/gomega/ghttp"
    12  )
    13  
    14  type resp struct {
    15  	status int
    16  	body   []byte
    17  }
    18  
    19  var responses map[string]resp
    20  var seenRoutes map[string]bool
    21  
    22  // AddHandler adds a mock handler to the server making a request specified by "method" to the
    23  // endpoint specified by "pathAndQuery", returning a response with status code "status" and
    24  // response body "body".
    25  func AddHandler(ser *ghttp.Server, method string, pathAndQuery string, status int, body []byte) {
    26  	p, err := url.Parse(pathAndQuery)
    27  	if err != nil {
    28  		panic(err)
    29  	}
    30  	if len(responses) == 0 {
    31  		responses = make(map[string]resp)
    32  		seenRoutes = make(map[string]bool)
    33  	}
    34  
    35  	responses[key(ser.URL(), method, p)] = resp{status, body}
    36  
    37  	if !seenRoutes[key(ser.URL(), method, p)] {
    38  		ser.RouteToHandler(method, p.Path, func(w http.ResponseWriter, r *http.Request) {
    39  			res, ok := responses[key(ser.URL(), r.Method, r.URL)]
    40  			if !ok {
    41  				Expect(errors.New("Unexpected request: " + key(ser.URL(), r.Method, r.URL))).ToNot(HaveOccurred())
    42  			}
    43  			w.WriteHeader(res.status)
    44  			_, err := w.Write(res.body)
    45  			Expect(err).ToNot(HaveOccurred())
    46  		})
    47  		seenRoutes[key(ser.URL(), method, p)] = true
    48  	}
    49  }
    50  
    51  func key(url string, method string, pathAndQuery fmt.Stringer) string {
    52  	return strings.ToLower(url + method + pathAndQuery.String())
    53  }