-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
equalobject.go
210 lines (179 loc) · 7.11 KB
/
equalobject.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/*
Copyright 2022 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package komega
import (
"fmt"
"reflect"
"strings"
"github.com/google/go-cmp/cmp"
"github.com/onsi/gomega/format"
"github.com/onsi/gomega/types"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
)
// These package variables hold pre-created commonly used options that can be used to reduce the manual work involved in
// identifying the paths that need to be compared for testing equality between objects.
var (
// IgnoreAutogeneratedMetadata contains the paths for all the metadata fields that are commonly set by the
// client and APIServer. This is used as a MatchOption for situations when only user-provided metadata is relevant.
IgnoreAutogeneratedMetadata = IgnorePaths{
"ObjectMeta.UID",
"ObjectMeta.Generation",
"ObjectMeta.CreationTimestamp",
"ObjectMeta.ResourceVersion",
"ObjectMeta.ManagedFields",
"ObjectMeta.DeletionGracePeriodSeconds",
"ObjectMeta.DeletionTimestamp",
"ObjectMeta.SelfLink",
"ObjectMeta.GenerateName",
}
)
// equalObjectMatcher is a Gomega matcher used to establish equality between two Kubernetes runtime.Objects.
type equalObjectMatcher struct {
// original holds the object that will be used to Match.
original runtime.Object
// diffPaths contains the paths that differ between two objects.
diffPaths []string
// options holds the options that identify what should and should not be matched.
options *EqualObjectOptions
}
// EqualObject returns a Matcher for the passed Kubernetes runtime.Object with the passed Options. This function can be
// used as a Gomega Matcher in Gomega Assertions.
func EqualObject(original runtime.Object, opts ...EqualObjectOption) types.GomegaMatcher {
matchOptions := &EqualObjectOptions{}
matchOptions = matchOptions.ApplyOptions(opts)
return &equalObjectMatcher{
options: matchOptions,
original: original,
}
}
// Match compares the current object to the passed object and returns true if the objects are the same according to
// the Matcher and MatchOptions.
func (m *equalObjectMatcher) Match(actual interface{}) (success bool, err error) {
// Nil checks required first here for:
// 1) Nil equality which returns true
// 2) One object nil which returns an error
actualIsNil := reflect.ValueOf(actual).IsNil()
originalIsNil := reflect.ValueOf(m.original).IsNil()
if actualIsNil && originalIsNil {
return true, nil
}
if actualIsNil || originalIsNil {
return false, fmt.Errorf("can not compare an object with a nil. original %v , actual %v", m.original, actual)
}
m.diffPaths = m.calculateDiff(actual)
return len(m.diffPaths) == 0, nil
}
// FailureMessage returns a message comparing the full objects after an unexpected failure to match has occurred.
func (m *equalObjectMatcher) FailureMessage(actual interface{}) (message string) {
return fmt.Sprintf("the following fields were expected to match but did not:\n%v\n%s", m.diffPaths,
format.Message(actual, "expected to match", m.original))
}
// NegatedFailureMessage returns a string comparing the full objects after an unexpected match has occurred.
func (m *equalObjectMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return fmt.Sprintf("the following fields were not expected to match \n%v\n%s", m.diffPaths,
format.Message(actual, "expected to match", m.original))
}
// diffReporter is a custom recorder for cmp.Diff which records all paths that are
// different between two objects.
type diffReporter struct {
stack []cmp.PathStep
diffPaths []string
}
func (r *diffReporter) PushStep(s cmp.PathStep) {
r.stack = append(r.stack, s)
}
func (r *diffReporter) Report(res cmp.Result) {
if !res.Equal() {
r.diffPaths = append(r.diffPaths, r.currPath())
}
}
func (r *diffReporter) currPath() string {
p := []string{}
for _, s := range r.stack[1:] {
switch s := s.(type) {
case cmp.StructField, cmp.SliceIndex, cmp.MapIndex:
p = append(p, s.String())
}
}
return strings.Join(p, "")[1:]
}
func (r *diffReporter) PopStep() {
r.stack = r.stack[:len(r.stack)-1]
}
// calculateDiff calculates the difference between two objects and returns the
// paths of the fields that do not match.
func (m *equalObjectMatcher) calculateDiff(actual interface{}) []string {
r := diffReporter{}
cmp.Diff(m.original, actual, cmp.Reporter(&r))
return filterDiffPaths(*m.options, r.diffPaths)
}
// filterDiffPaths filters the diff paths using the paths in EqualObjectOptions.
func filterDiffPaths(opts EqualObjectOptions, paths []string) []string {
result := sets.NewString(paths...)
for _, c := range result.List() {
if len(opts.matchPaths) > 0 && !matchesAnyPath(c, opts.matchPaths) {
result.Delete(c)
continue
}
if matchesAnyPath(c, opts.ignorePaths) {
result.Delete(c)
}
}
return result.List()
}
// matchesAnyPath returns true if path matches any of the path prefixes.
// It respects the name boundaries within paths, so 'ObjectMeta.Name' does not
// match 'ObjectMeta.Namespace' for example.
func matchesAnyPath(path string, prefixes []string) bool {
for _, prefix := range prefixes {
if strings.HasPrefix(path, prefix) {
rpath := path[len(prefix):]
// It's a full attribute name if it's a full match, or the next character of the path is
// either a . or a [
if len(rpath) == 0 || rpath[0] == '.' || rpath[0] == '[' {
return true
}
}
}
return false
}
// EqualObjectOption describes an Option that can be applied to a Matcher.
type EqualObjectOption interface {
// ApplyToEqualObjectMatcher applies this configuration to the given MatchOption.
ApplyToEqualObjectMatcher(options *EqualObjectOptions)
}
// EqualObjectOptions holds the available types of EqualObjectOptions that can be applied to a Matcher.
type EqualObjectOptions struct {
ignorePaths []string
matchPaths []string
}
// ApplyOptions adds the passed MatchOptions to the MatchOptions struct.
func (o *EqualObjectOptions) ApplyOptions(opts []EqualObjectOption) *EqualObjectOptions {
for _, opt := range opts {
opt.ApplyToEqualObjectMatcher(o)
}
return o
}
// IgnorePaths instructs the Matcher to ignore given paths when computing a diff.
type IgnorePaths []string
// ApplyToEqualObjectMatcher applies this configuration to the given MatchOptions.
func (i IgnorePaths) ApplyToEqualObjectMatcher(opts *EqualObjectOptions) {
opts.ignorePaths = append(opts.ignorePaths, i...)
}
// MatchPaths instructs the Matcher to restrict its diff to the given paths. If empty the Matcher will look at all paths.
type MatchPaths []string
// ApplyToEqualObjectMatcher applies this configuration to the given MatchOptions.
func (i MatchPaths) ApplyToEqualObjectMatcher(opts *EqualObjectOptions) {
opts.matchPaths = append(opts.matchPaths, i...)
}