This repository has been archived by the owner on Jan 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
matcher.go
80 lines (65 loc) · 2.24 KB
/
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
package net
import (
"encoding/json"
"fmt"
"github.com/stretchr/testify/assert"
mr "github.com/tjarratt/mr_t"
"io/ioutil"
"net/http"
"strings"
)
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 RequestBodyMatcher(expectedBodyString string) RequestMatcher {
return func(t mr.TestingT, request *http.Request) {
bodyBytes, err := ioutil.ReadAll(request.Body)
if err != nil {
assert.Fail(t, "Error reading request body: %s", err)
}
actualBody, err := bytesToInterface(bodyBytes)
if err != nil {
assert.Fail(t, "Error unmarshalling request", err.Error())
}
expectedBody, err := bytesToInterface([]byte(expectedBodyString))
if err != nil {
assert.Fail(t, "Error unmarshalling expected json", err.Error())
}
assert.Equal(t, expectedBody, actualBody, "\nEXPECTED: %s\nACTUAL: %s", expectedBody, actualBody)
assert.Equal(t, request.Header.Get("content-type"), "application/json", "Content Type was not application/json.")
}
}
func RequestBodyMatcherWithContentType(expectedBody, expectedContentType string) RequestMatcher {
return func(t mr.TestingT, request *http.Request) {
bodyBytes, err := ioutil.ReadAll(request.Body)
if err != nil {
assert.Fail(t, "Error reading request body: %s", err)
}
actualBody := string(bodyBytes)
assert.Equal(t, RemoveWhiteSpaceFromBody(actualBody), RemoveWhiteSpaceFromBody(expectedBody), "Body did not match.")
actualContentType := request.Header.Get("content-type")
assert.Equal(t, actualContentType, 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
}