forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request_matcher.go
90 lines (73 loc) · 2.33 KB
/
request_matcher.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package net
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
type JSONMapRequest map[string]interface{}
func (json *JSONMapRequest) String() string {
return fmt.Sprintf("%#v", *json)
}
type JSONArrayRequest []interface{}
func (json *JSONArrayRequest) String() string {
return fmt.Sprintf("%#v", *json)
}
func bytesToInterface(jsonBytes []byte) (interface{}, error) {
mapResult := &JSONMapRequest{}
err := json.Unmarshal(jsonBytes, mapResult)
if err == nil {
return mapResult, err
}
arrayResult := &JSONArrayRequest{}
err = json.Unmarshal(jsonBytes, arrayResult)
return arrayResult, err
}
func EmptyQueryParamMatcher() RequestMatcher {
return func(request *http.Request) {
defer GinkgoRecover()
Expect(request.URL.RawQuery).To(Equal(""))
}
}
func RequestBodyMatcher(expectedBodyString string) RequestMatcher {
return func(request *http.Request) {
defer GinkgoRecover()
bodyBytes, err := ioutil.ReadAll(request.Body)
if err != nil {
Fail(fmt.Sprintf("Error reading request body: %s", err))
}
actualBody, err := bytesToInterface(bodyBytes)
if err != nil {
Fail(fmt.Sprintf("Error unmarshalling request: %s", err.Error()))
}
expectedBody, err := bytesToInterface([]byte(expectedBodyString))
if err != nil {
Fail(fmt.Sprintf("Error unmarshalling expected json: %s", err.Error()))
}
Expect(actualBody).To(Equal(expectedBody))
Expect(request.Header.Get("content-type")).To(Equal("application/json"))
}
}
func RequestBodyMatcherWithContentType(expectedBody, expectedContentType string) RequestMatcher {
return func(request *http.Request) {
defer GinkgoRecover()
bodyBytes, err := ioutil.ReadAll(request.Body)
if err != nil {
Fail(fmt.Sprintf("Error reading request body: %s", err))
}
actualBody := string(bodyBytes)
Expect(RemoveWhiteSpaceFromBody(actualBody)).To(Equal(RemoveWhiteSpaceFromBody(expectedBody)), "Body did not match.")
actualContentType := request.Header.Get("content-type")
Expect(actualContentType).To(Equal(expectedContentType), "Content Type did not match.")
}
}
func RemoveWhiteSpaceFromBody(body string) string {
body = strings.Replace(body, " ", "", -1)
body = strings.Replace(body, "\n", "", -1)
body = strings.Replace(body, "\r", "", -1)
body = strings.Replace(body, "\t", "", -1)
return body
}