forked from Arrim/http-api-mock
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mock_match.go
97 lines (77 loc) · 2 KB
/
mock_match.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
91
92
93
94
95
96
97
package match
import (
"errors"
"strings"
"github.com/jmartin82/mmock/definition"
"github.com/ryanuber/go-glob"
)
var (
ErrMethodNotMatch = errors.New("Method not match")
ErrPathNotMatch = errors.New("Path not match")
ErrQueryStringMatch = errors.New("Query string not match")
ErrHeadersNotMatch = errors.New("Headers not match")
ErrCookiesNotMatch = errors.New("Cookies not match")
ErrBodyNotMatch = errors.New("Body not match")
)
type MockMatch struct {
}
func (mm MockMatch) matchKeyAndValues(reqMap definition.Values, mockMap definition.Values) bool {
if len(mockMap) > len(reqMap) {
return false
}
for key, mval := range mockMap {
if rval, exists := reqMap[key]; exists {
if len(mval) > len(rval) {
return false
}
for i, v := range mval {
if v != rval[i] {
return false
}
}
} else {
return false
}
}
return true
}
func (mm MockMatch) matchKeyAndValue(reqMap definition.Cookies, mockMap definition.Cookies) bool {
if len(mockMap) > len(reqMap) {
return false
}
for key, mval := range mockMap {
if rval, exists := reqMap[key]; !exists || mval != rval {
return false
}
}
return true
}
func mockIncludesMethod(mock *definition.Request, method string) bool {
for _, item := range strings.Split(mock.Method, "|") {
if item == method {
return true
}
}
return false
}
func (mm MockMatch) Match(req *definition.Request, mock *definition.Request) (bool, error) {
if !glob.Glob(mock.Path, req.Path) {
return false, ErrPathNotMatch
}
if !mockIncludesMethod(mock, req.Method) {
return false, ErrMethodNotMatch
}
if !mm.matchKeyAndValues(req.QueryStringParameters, mock.QueryStringParameters) {
return false, ErrQueryStringMatch
}
if !mm.matchKeyAndValue(req.Cookies, mock.Cookies) {
return false, ErrCookiesNotMatch
}
if !mm.matchKeyAndValues(req.Headers, mock.Headers) {
return false, ErrHeadersNotMatch
}
if len(mock.Body) > 0 && !glob.Glob(mock.Body, req.Body) {
return false, ErrBodyNotMatch
}
return true, nil
}