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