forked from kubernetes-sigs/structured-merge-diff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.go
353 lines (313 loc) · 10.2 KB
/
state.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
Copyright 2018 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 fixture
import (
"bytes"
"fmt"
"sigs.k8s.io/structured-merge-diff/fieldpath"
"sigs.k8s.io/structured-merge-diff/merge"
"sigs.k8s.io/structured-merge-diff/typed"
)
// State of the current test in terms of live object. One can check at
// any time that Live and Managers match the expectations.
type State struct {
Live *typed.TypedValue
Parser typed.ParseableType
Managers fieldpath.ManagedFields
Updater *merge.Updater
}
// FixTabsOrDie counts the number of tab characters preceding the first
// line in the given yaml object. It removes that many tabs from every
// line. It panics (it's a test funtion) if some line has fewer tabs
// than the first line.
//
// The purpose of this is to make it easier to read tests.
func FixTabsOrDie(in typed.YAMLObject) typed.YAMLObject {
lines := bytes.Split([]byte(in), []byte{'\n'})
if len(lines[0]) == 0 && len(lines) > 1 {
lines = lines[1:]
}
// Create prefix made of tabs that we want to remove.
var prefix []byte
for _, c := range lines[0] {
if c != '\t' {
break
}
prefix = append(prefix, byte('\t'))
}
// Remove prefix from all tabs, fail otherwise.
for i := range lines {
line := lines[i]
// It's OK for the last line to be blank (trailing \n)
if i == len(lines)-1 && len(line) <= len(prefix) && bytes.TrimSpace(line) == nil {
lines[i] = []byte{}
break
}
if !bytes.HasPrefix(line, prefix) {
panic(fmt.Errorf("line %d doesn't start with expected number (%d) of tabs: %v", i, len(prefix), line))
}
lines[i] = line[len(prefix):]
}
return typed.YAMLObject(bytes.Join(lines, []byte{'\n'}))
}
func (s *State) checkInit() error {
if s.Live == nil {
obj, err := s.Parser.FromYAML("{}")
if err != nil {
return fmt.Errorf("failed to create new empty object: %v", err)
}
s.Live = obj
}
return nil
}
// Update the current state with the passed in object
func (s *State) Update(obj typed.YAMLObject, version fieldpath.APIVersion, manager string) error {
obj = FixTabsOrDie(obj)
if err := s.checkInit(); err != nil {
return err
}
tv, err := s.Parser.FromYAML(obj)
s.Live, err = s.Updater.Converter.Convert(s.Live, version)
if err != nil {
return err
}
newObj, managers, err := s.Updater.Update(s.Live, tv, version, s.Managers, manager)
if err != nil {
return err
}
s.Live = newObj
s.Managers = managers
return nil
}
// Apply the passed in object to the current state
func (s *State) Apply(obj typed.YAMLObject, version fieldpath.APIVersion, manager string, force bool) error {
obj = FixTabsOrDie(obj)
if err := s.checkInit(); err != nil {
return err
}
tv, err := s.Parser.FromYAML(obj)
if err != nil {
return err
}
s.Live, err = s.Updater.Converter.Convert(s.Live, version)
if err != nil {
return err
}
new, managers, err := s.Updater.Apply(s.Live, tv, version, s.Managers, manager, force)
if err != nil {
return err
}
s.Live = new
s.Managers = managers
return nil
}
// CompareLive takes a YAML string and returns the comparison with the
// current live object or an error.
func (s *State) CompareLive(obj typed.YAMLObject) (*typed.Comparison, error) {
obj = FixTabsOrDie(obj)
if err := s.checkInit(); err != nil {
return nil, err
}
tv, err := s.Parser.FromYAML(obj)
if err != nil {
return nil, err
}
return s.Live.Compare(tv)
}
// dummyConverter doesn't convert, it just returns the same exact object, as long as a version is provided.
type dummyConverter struct{}
var _ merge.Converter = dummyConverter{}
// Convert returns the object given in input, not doing any conversion.
func (dummyConverter) Convert(v *typed.TypedValue, version fieldpath.APIVersion) (*typed.TypedValue, error) {
if len(version) == 0 {
return nil, fmt.Errorf("cannot convert to invalid version: %q", version)
}
return v, nil
}
func (dummyConverter) IsMissingVersionError(err error) bool {
return false
}
// Operation is a step that will run when building a table-driven test.
type Operation interface {
run(*State) error
}
func hasConflict(conflicts merge.Conflicts, conflict merge.Conflict) bool {
for i := range conflicts {
if conflict.Equals(conflicts[i]) {
return true
}
}
return false
}
func addedConflicts(one, other merge.Conflicts) merge.Conflicts {
added := merge.Conflicts{}
for _, conflict := range other {
if !hasConflict(one, conflict) {
added = append(added, conflict)
}
}
return added
}
// Apply is a type of operation. It is a non-forced apply run by a
// manager with a given object. Since non-forced apply operation can
// conflict, the user can specify the expected conflicts. If conflicts
// don't match, an error will occur.
type Apply struct {
Manager string
APIVersion fieldpath.APIVersion
Object typed.YAMLObject
Conflicts merge.Conflicts
}
var _ Operation = &Apply{}
func (a Apply) run(state *State) error {
err := state.Apply(a.Object, a.APIVersion, a.Manager, false)
if err != nil {
if _, ok := err.(merge.Conflicts); !ok || a.Conflicts == nil {
return err
}
}
if a.Conflicts != nil {
conflicts := merge.Conflicts{}
if err != nil {
conflicts = err.(merge.Conflicts)
}
if len(addedConflicts(a.Conflicts, conflicts)) != 0 || len(addedConflicts(conflicts, a.Conflicts)) != 0 {
return fmt.Errorf("Expected conflicts:\n%v\ngot\n%v\nadded:\n%v\nremoved:\n%v",
a.Conflicts.Error(),
conflicts.Error(),
addedConflicts(a.Conflicts, conflicts).Error(),
addedConflicts(conflicts, a.Conflicts).Error(),
)
}
}
return nil
}
// ForceApply is a type of operation. It is a forced-apply run by a
// manager with a given object. Any error will be returned.
type ForceApply struct {
Manager string
APIVersion fieldpath.APIVersion
Object typed.YAMLObject
}
var _ Operation = &ForceApply{}
func (f ForceApply) run(state *State) error {
return state.Apply(f.Object, f.APIVersion, f.Manager, true)
}
// Update is a type of operation. It is a controller type of
// update. Errors are passed along.
type Update struct {
Manager string
APIVersion fieldpath.APIVersion
Object typed.YAMLObject
}
var _ Operation = &Update{}
func (u Update) run(state *State) error {
return state.Update(u.Object, u.APIVersion, u.Manager)
}
// TestCase is the list of operations that need to be run, as well as
// the object/managedfields as they are supposed to look like after all
// the operations have been successfully performed. If Object/Managed is
// not specified, then the comparison is not performed (any object or
// managed field will pass). Any error (conflicts aside) happen while
// running the operation, that error will be returned right away.
type TestCase struct {
// Ops is the list of operations to run sequentially
Ops []Operation
// Object, if not empty, is the object as it's expected to
// be after all the operations are run.
Object typed.YAMLObject
// Managed, if not nil, is the ManagedFields as expected
// after all operations are run.
Managed fieldpath.ManagedFields
// Set to true if the test case needs the union behavior enabled.
RequiresUnions bool
}
// Test runs the test-case using the given parser and a dummy converter.
func (tc TestCase) Test(parser typed.ParseableType) error {
return tc.TestWithConverter(parser, &dummyConverter{})
}
// Bench runs the test-case using the given parser and a dummy converter, but
// doesn't check exit conditions--see the comment for BenchWithConverter.
func (tc TestCase) Bench(parser typed.ParseableType) error {
return tc.BenchWithConverter(parser, &dummyConverter{})
}
// BenchWithConverter runs the test-case using the given parser and converter,
// but doesn't do any comparison operations aftewards; you should probably run
// TestWithConverter once and reset the benchmark, to make sure the test case
// actually passes..
func (tc TestCase) BenchWithConverter(parser typed.ParseableType, converter merge.Converter) error {
state := State{
Updater: &merge.Updater{Converter: converter},
Parser: parser,
}
if tc.RequiresUnions {
state.Updater.EnableUnionFeature()
}
// We currently don't have any test that converts, we can take
// care of that later.
for i, ops := range tc.Ops {
err := ops.run(&state)
if err != nil {
return fmt.Errorf("failed operation %d: %v", i, err)
}
}
return nil
}
// TestWithConverter runs the test-case using the given parser and converter.
func (tc TestCase) TestWithConverter(parser typed.ParseableType, converter merge.Converter) error {
state := State{
Updater: &merge.Updater{Converter: converter},
Parser: parser,
}
if tc.RequiresUnions {
state.Updater.EnableUnionFeature()
} else {
// Also test it with unions on.
tc2 := tc
tc2.RequiresUnions = true
err := tc2.TestWithConverter(parser, converter)
if err != nil {
return fmt.Errorf("fails if unions are on: %v", err)
}
}
// We currently don't have any test that converts, we can take
// care of that later.
for i, ops := range tc.Ops {
err := ops.run(&state)
if err != nil {
return fmt.Errorf("failed operation %d: %v", i, err)
}
}
// If LastObject was specified, compare it with LiveState
if tc.Object != typed.YAMLObject("") {
comparison, err := state.CompareLive(tc.Object)
if err != nil {
return fmt.Errorf("failed to compare live with config: %v", err)
}
if !comparison.IsSame() {
return fmt.Errorf("expected live and config to be the same:\n%v", comparison)
}
}
if tc.Managed != nil {
if diff := state.Managers.Difference(tc.Managed); len(diff) != 0 {
return fmt.Errorf("expected Managers to be %v, got %v", tc.Managed, state.Managers)
}
}
// Fail if any empty sets are present in the managers
for manager, set := range state.Managers {
if set.Set().Empty() {
return fmt.Errorf("expected Managers to have no empty sets, but found one managed by %v", manager)
}
}
return nil
}