-
Notifications
You must be signed in to change notification settings - Fork 1
/
map.go
101 lines (83 loc) · 2.29 KB
/
map.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
98
99
100
101
package schema
import (
"fmt"
"sort"
"strings"
)
// Map checks each key for a specific value or matcher.
//
type Map map[string]interface{}
// Match is the actual matching function to obey the Matcher Interface
func (m Map) Match(data interface{}) *Error {
fieldError := &Error{}
dataMap, ok := data.(map[string]interface{})
if !ok {
return SelfError(fmt.Sprintf("is no map: %t", data))
}
checkExtraKeys(fieldError, m, dataMap)
checkMissingKeys(fieldError, m, dataMap)
matchValues(fieldError, m, dataMap)
if fieldError.Any() {
return fieldError
}
return nil
}
// MapIncluding checks if a map contains keys that match the given values or matchers
type MapIncluding map[string]interface{}
// Match is the actual matching function to obey the Matcher Interface
func (m MapIncluding) Match(data interface{}) *Error {
fieldError := &Error{}
dataMap, ok := data.(map[string]interface{})
if !ok {
return SelfError(fmt.Sprintf("is no map: %t", data))
}
checkMissingKeys(fieldError, m, dataMap)
matchValues(fieldError, m, dataMap)
if fieldError.Any() {
return fieldError
}
return nil
}
func checkExtraKeys(fieldError *Error, m map[string]interface{}, dataMap map[string]interface{}) {
extraKeys := []string{}
for k := range dataMap {
if _, found := m[k]; !found {
extraKeys = append(extraKeys, k)
}
}
if len(extraKeys) > 0 {
sort.Strings(extraKeys)
fieldError.Add(selfField, fmt.Sprintf("Found extra keys: %q", strings.Join(extraKeys, ", ")))
}
}
func checkMissingKeys(fieldError *Error, m map[string]interface{}, dataMap map[string]interface{}) {
missingKeys := []string{}
for k := range m {
if _, found := dataMap[k]; !found {
missingKeys = append(missingKeys, k)
}
}
if len(missingKeys) > 0 {
sort.Strings(missingKeys)
fieldError.Add(selfField, fmt.Sprintf("Missing keys: %q", strings.Join(missingKeys, ", ")))
}
}
func matchValues(fieldError *Error, m map[string]interface{}, dataMap map[string]interface{}) {
keys := []string{}
exps := sortableExps{}
i := 0
for k, exp := range m {
keys = append(keys, k)
exps = append(exps, &origExp{OriginalIndex: i, Exp: exp})
i++
}
sort.Sort(exps)
for _, exp := range exps {
k := keys[exp.OriginalIndex]
actual, found := dataMap[k]
if !found {
continue
}
matchValue(fieldError, k, exp.Exp, actual)
}
}