forked from argoproj/argo-rollouts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller_test.go
711 lines (619 loc) · 22.3 KB
/
controller_test.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
package experiments
import (
"encoding/json"
"fmt"
"reflect"
"testing"
"time"
"github.com/bouk/monkey"
"github.com/stretchr/testify/assert"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/apimachinery/pkg/util/uuid"
kubeinformers "k8s.io/client-go/informers"
k8sfake "k8s.io/client-go/kubernetes/fake"
core "k8s.io/client-go/testing"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
"k8s.io/kubernetes/pkg/controller"
"k8s.io/utils/pointer"
"github.com/argoproj/argo-rollouts/controller/metrics"
"github.com/argoproj/argo-rollouts/pkg/apis/rollouts/v1alpha1"
"github.com/argoproj/argo-rollouts/pkg/client/clientset/versioned/fake"
informers "github.com/argoproj/argo-rollouts/pkg/client/informers/externalversions"
"github.com/argoproj/argo-rollouts/utils/conditions"
)
var (
noResyncPeriodFunc = func() time.Duration { return 0 }
)
const (
OnlyObservedGenerationPatch = `{
"status" : {
"observedGeneration": ""
}
}`
)
type fixture struct {
t *testing.T
client *fake.Clientset
kubeclient *k8sfake.Clientset
// Objects to put in the store.
// rolloutLister []*v1alpha1.Rollout
experimentLister []*v1alpha1.Experiment
replicaSetLister []*appsv1.ReplicaSet
// Actions expected to happen on the client.
kubeactions []core.Action
actions []core.Action
// Objects from here preloaded into NewSimpleFake.
kubeobjects []runtime.Object
objects []runtime.Object
enqueuedObjects map[string]int
unfreezeTime func()
}
func newFixture(t *testing.T) *fixture {
f := &fixture{}
f.t = t
f.objects = []runtime.Object{}
f.kubeobjects = []runtime.Object{}
f.enqueuedObjects = make(map[string]int)
now := time.Now()
patch := monkey.Patch(time.Now, func() time.Time { return now })
f.unfreezeTime = patch.Unpatch
return f
}
func (f *fixture) Close() {
f.unfreezeTime()
}
func generateTemplates(imageNames ...string) []v1alpha1.TemplateSpec {
templates := make([]v1alpha1.TemplateSpec, 0)
for _, imageName := range imageNames {
selector := map[string]string{
"key": imageName,
}
template := v1alpha1.TemplateSpec{
Name: imageName,
Selector: &metav1.LabelSelector{
MatchLabels: selector,
},
Replicas: pointer.Int32Ptr(1),
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: selector,
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Image: imageName,
},
},
},
},
}
templates = append(templates, template)
}
return templates
}
func generateTemplatesStatus(name string, replica, availableReplicas int32) v1alpha1.TemplateStatus {
return v1alpha1.TemplateStatus{
Name: name,
Replicas: replica,
UpdatedReplicas: availableReplicas,
ReadyReplicas: availableReplicas,
AvailableReplicas: availableReplicas,
}
}
func newExperiment(name string, templates []v1alpha1.TemplateSpec, duration *int32, running *bool) *v1alpha1.Experiment {
ex := &v1alpha1.Experiment{
ObjectMeta: metav1.ObjectMeta{
UID: uuid.NewUUID(),
Name: name,
Namespace: metav1.NamespaceDefault,
},
Spec: v1alpha1.ExperimentSpec{
Templates: templates,
Duration: duration,
},
Status: v1alpha1.ExperimentStatus{
Running: running,
},
}
if duration != nil {
// Ensure that the experiment created is valid by making the ProgressDeadlineSeconds smaller than the duration
ex.Spec.ProgressDeadlineSeconds = pointer.Int32Ptr(*duration - 1)
}
return ex
}
func newCondition(reason string, experiment *v1alpha1.Experiment) *v1alpha1.ExperimentCondition {
if reason == conditions.ReplicaSetUpdatedReason {
return &v1alpha1.ExperimentCondition{
Type: v1alpha1.ExperimentProgressing,
Status: corev1.ConditionTrue,
LastUpdateTime: metav1.Now().Rfc3339Copy(),
LastTransitionTime: metav1.Now().Rfc3339Copy(),
Reason: reason,
Message: fmt.Sprintf(conditions.ExperimentProgressingMessage, experiment.Name),
}
}
if reason == conditions.ExperimentCompleteReason {
return &v1alpha1.ExperimentCondition{
Type: v1alpha1.ExperimentProgressing,
Status: corev1.ConditionFalse,
LastUpdateTime: metav1.Now().Rfc3339Copy(),
LastTransitionTime: metav1.Now().Rfc3339Copy(),
Reason: reason,
Message: fmt.Sprintf(conditions.ExperimentCompletedMessage, experiment.Name),
}
}
if reason == conditions.ReplicaSetUpdatedReason {
return &v1alpha1.ExperimentCondition{
Type: v1alpha1.ExperimentProgressing,
Status: corev1.ConditionFalse,
LastUpdateTime: metav1.Now().Rfc3339Copy(),
LastTransitionTime: metav1.Now().Rfc3339Copy(),
Reason: reason,
Message: fmt.Sprintf(conditions.ExperimentRunningMessage, experiment.Name),
}
}
if reason == conditions.TimedOutReason {
return &v1alpha1.ExperimentCondition{
Type: v1alpha1.ExperimentProgressing,
Status: corev1.ConditionFalse,
LastUpdateTime: metav1.Now().Rfc3339Copy(),
LastTransitionTime: metav1.Now().Rfc3339Copy(),
Reason: reason,
Message: fmt.Sprintf(conditions.ExperimentTimeOutMessage, experiment.Name),
}
}
if reason == conditions.InvalidSpecReason {
return &v1alpha1.ExperimentCondition{
Type: v1alpha1.InvalidExperimentSpec,
Status: corev1.ConditionTrue,
LastUpdateTime: metav1.Now().Rfc3339Copy(),
LastTransitionTime: metav1.Now().Rfc3339Copy(),
Reason: reason,
Message: fmt.Sprintf(conditions.ExperimentTemplateNameEmpty, experiment.Name, 0),
}
}
return nil
}
func templateToRS(ex *v1alpha1.Experiment, template v1alpha1.TemplateSpec, availableReplicas int32) *appsv1.ReplicaSet {
newRSTemplate := *template.Template.DeepCopy()
podHash := controller.ComputeHash(&newRSTemplate, nil)
rsLabels := map[string]string{
v1alpha1.DefaultRolloutUniqueLabelKey: podHash,
}
for k, v := range template.Selector.MatchLabels {
rsLabels[k] = v
}
rs := &appsv1.ReplicaSet{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-%s-%s", ex.Name, template.Name, podHash),
UID: uuid.NewUUID(),
Namespace: metav1.NamespaceDefault,
Labels: rsLabels,
OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(ex, controllerKind)},
},
Spec: appsv1.ReplicaSetSpec{
Selector: metav1.SetAsLabelSelector(rsLabels),
Replicas: template.Replicas,
Template: template.Template,
},
Status: appsv1.ReplicaSetStatus{
Replicas: availableReplicas,
ReadyReplicas: availableReplicas,
AvailableReplicas: availableReplicas,
},
}
return rs
}
func generateRSName(ex *v1alpha1.Experiment, template v1alpha1.TemplateSpec) string {
return fmt.Sprintf("%s-%s-%s", ex.Name, template.Name, controller.ComputeHash(&template.Template, nil))
}
func calculatePatch(ex *v1alpha1.Experiment, patch string, templates []v1alpha1.TemplateStatus, condition *v1alpha1.ExperimentCondition) string {
patchMap := make(map[string]interface{})
err := json.Unmarshal([]byte(patch), &patchMap)
if err != nil {
panic(err)
}
newStatus := patchMap["status"].(map[string]interface{})
if templates != nil {
newStatus["templateStatuses"] = templates
patchMap["status"] = newStatus
}
if condition != nil {
newStatus["conditions"] = []v1alpha1.ExperimentCondition{*condition}
patchMap["status"] = newStatus
}
patchBytes, err := json.Marshal(patchMap)
if err != nil {
panic(err)
}
origBytes, err := json.Marshal(ex)
if err != nil {
panic(err)
}
newBytes, err := strategicpatch.StrategicMergePatch(origBytes, patchBytes, v1alpha1.Experiment{})
if err != nil {
panic(err)
}
newEx := &v1alpha1.Experiment{}
json.Unmarshal(newBytes, newEx)
newPatch := make(map[string]interface{})
json.Unmarshal(patchBytes, &newPatch)
newPatchBytes, _ := json.Marshal(newPatch)
return string(newPatchBytes)
}
func getKey(experiment *v1alpha1.Experiment, t *testing.T) string {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(experiment)
if err != nil {
t.Errorf("Unexpected error getting key for experiment %v: %v", experiment.Name, err)
return ""
}
return key
}
type resyncFunc func() time.Duration
func (f *fixture) newController(resync resyncFunc) (*ExperimentController, informers.SharedInformerFactory, kubeinformers.SharedInformerFactory) {
f.client = fake.NewSimpleClientset(f.objects...)
f.kubeclient = k8sfake.NewSimpleClientset(f.kubeobjects...)
i := informers.NewSharedInformerFactory(f.client, resync())
k8sI := kubeinformers.NewSharedInformerFactory(f.kubeclient, resync())
rolloutWorkqueue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "Rollouts")
experimentWorkqueue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "Experiments")
c := NewExperimentController(f.kubeclient, f.client,
k8sI.Apps().V1().ReplicaSets(),
i.Argoproj().V1alpha1().Rollouts(),
i.Argoproj().V1alpha1().Experiments(),
resync(),
rolloutWorkqueue,
experimentWorkqueue,
metrics.NewMetricsServer("localhost:8080", i.Argoproj().V1alpha1().Rollouts().Lister()),
&record.FakeRecorder{})
c.enqueueExperiment = func(obj interface{}) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
panic(err)
}
count, ok := f.enqueuedObjects[key]
if !ok {
count = 0
}
count++
f.enqueuedObjects[key] = count
c.experimentWorkqueue.Add(obj)
}
c.enqueueExperimentAfter = func(obj interface{}, duration time.Duration) {
c.enqueueExperiment(obj)
}
for _, e := range f.experimentLister {
i.Argoproj().V1alpha1().Experiments().Informer().GetIndexer().Add(e)
}
for _, r := range f.replicaSetLister {
k8sI.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(r)
}
return c, i, k8sI
}
func (f *fixture) run(experimentName string) {
c, i, k8sI := f.newController(noResyncPeriodFunc)
f.runController(experimentName, true, false, c, i, k8sI)
}
func (f *fixture) runExpectError(experimentName string, startInformers bool) {
c, i, k8sI := f.newController(noResyncPeriodFunc)
f.runController(experimentName, startInformers, true, c, i, k8sI)
}
func (f *fixture) runController(experimentName string, startInformers bool, expectError bool, c *ExperimentController, i informers.SharedInformerFactory, k8sI kubeinformers.SharedInformerFactory) *ExperimentController {
if startInformers {
stopCh := make(chan struct{})
defer close(stopCh)
i.Start(stopCh)
k8sI.Start(stopCh)
assert.True(f.t, cache.WaitForCacheSync(stopCh, c.replicaSetSynced, c.rolloutSynced, c.experimentSynced))
}
err := c.syncHandler(experimentName)
if !expectError && err != nil {
f.t.Errorf("error syncing experiment: %v", err)
} else if expectError && err == nil {
f.t.Error("expected error syncing experiment, got nil")
}
actions := filterInformerActions(f.client.Actions())
for i, action := range actions {
if len(f.actions) < i+1 {
f.t.Errorf("%d unexpected actions: %+v", len(actions)-len(f.actions), actions[i:])
break
}
expectedAction := f.actions[i]
checkAction(expectedAction, action, f.t)
}
if len(f.actions) > len(actions) {
f.t.Errorf("%d additional expected actions:%+v", len(f.actions)-len(actions), f.actions[len(actions):])
}
k8sActions := filterInformerActions(f.kubeclient.Actions())
for i, action := range k8sActions {
if len(f.kubeactions) < i+1 {
f.t.Errorf("%d unexpected actions: %+v", len(k8sActions)-len(f.kubeactions), k8sActions[i:])
break
}
expectedAction := f.kubeactions[i]
checkAction(expectedAction, action, f.t)
}
if len(f.kubeactions) > len(k8sActions) {
f.t.Errorf("%d additional expected actions:%+v", len(f.kubeactions)-len(k8sActions), f.kubeactions[len(k8sActions):])
}
return c
}
// checkAction verifies that expected and actual actions are equal
func checkAction(expected, actual core.Action, t *testing.T) {
if !(expected.Matches(actual.GetVerb(), actual.GetResource().Resource) && actual.GetSubresource() == expected.GetSubresource()) {
t.Errorf("Expected\n\t%#v\ngot\n\t%#v", expected, actual)
if patch, ok := actual.(core.PatchAction); ok {
patchBytes := patch.GetPatch()
t.Errorf("Patch Received: %s", string(patchBytes))
}
if patch, ok := expected.(core.PatchAction); ok {
patchBytes := patch.GetPatch()
t.Errorf("Expected Patch: %s", string(patchBytes))
}
return
}
if reflect.TypeOf(actual) != reflect.TypeOf(expected) {
t.Errorf("Action has wrong type. Expected: %t. Got: %t", expected, actual)
return
}
}
// filterInformerActions filters list, and watch actions for testing resources.
// Since list, and watch don't change resource state we can filter it to lower
// nose level in our tests.
func filterInformerActions(actions []core.Action) []core.Action {
ret := []core.Action{}
for _, action := range actions {
if action.Matches("list", "rollouts") ||
action.Matches("watch", "rollouts") ||
action.Matches("list", "replicaSets") ||
action.Matches("watch", "replicaSets") ||
action.Matches("list", "experiments") ||
action.Matches("watch", "experiments") {
continue
}
ret = append(ret, action)
}
return ret
}
func (f *fixture) expectCreateReplicaSetAction(r *appsv1.ReplicaSet) int {
len := len(f.kubeactions)
f.kubeactions = append(f.kubeactions, core.NewCreateAction(schema.GroupVersionResource{Resource: "replicasets"}, r.Namespace, r))
return len
}
func (f *fixture) expectUpdateReplicaSetAction(r *appsv1.ReplicaSet) int {
len := len(f.kubeactions)
f.kubeactions = append(f.kubeactions, core.NewUpdateAction(schema.GroupVersionResource{Resource: "replicasets"}, r.Namespace, r))
return len
}
func (f *fixture) expectGetExperimentAction(experiment *v1alpha1.Experiment) int {
len := len(f.actions)
f.actions = append(f.actions, core.NewGetAction(schema.GroupVersionResource{Resource: "experiments"}, experiment.Namespace, experiment.Name))
return len
}
func (f *fixture) expectUpdateExperimentAction(experiment *v1alpha1.Experiment) int {
action := core.NewUpdateAction(schema.GroupVersionResource{Resource: "experiments"}, experiment.Namespace, experiment)
len := len(f.actions)
f.actions = append(f.actions, action)
return len
}
func (f *fixture) expectGetReplicaSetAction(r *appsv1.ReplicaSet) int {
len := len(f.kubeactions)
f.kubeactions = append(f.kubeactions, core.NewGetAction(schema.GroupVersionResource{Resource: "replicasets"}, r.Namespace, r.Name))
return len
}
func (f *fixture) expectPatchReplicaSetAction(r *appsv1.ReplicaSet) int {
len := len(f.kubeactions)
f.kubeactions = append(f.kubeactions, core.NewPatchAction(schema.GroupVersionResource{Resource: "replicasets"}, r.Namespace, r.Name, types.MergePatchType, nil))
return len
}
func (f *fixture) expectPatchExperimentAction(experiment *v1alpha1.Experiment) int {
serviceSchema := schema.GroupVersionResource{
Resource: "experiments",
Version: "v1alpha1",
}
len := len(f.actions)
f.actions = append(f.actions, core.NewPatchAction(serviceSchema, experiment.Namespace, experiment.Name, types.MergePatchType, nil))
return len
}
func (f *fixture) getCreatedReplicaSet(index int) *appsv1.ReplicaSet {
action := filterInformerActions(f.kubeclient.Actions())[index]
createAction, ok := action.(core.CreateAction)
if !ok {
assert.Failf(f.t, "Expected Created action, not %s", action.GetVerb())
}
obj := createAction.GetObject()
rs := &appsv1.ReplicaSet{}
converter := runtime.NewTestUnstructuredConverter(equality.Semantic)
objMap, _ := converter.ToUnstructured(obj)
runtime.NewTestUnstructuredConverter(equality.Semantic).FromUnstructured(objMap, rs)
return rs
}
func (f *fixture) getUpdatedReplicaSet(index int) *appsv1.ReplicaSet {
action := filterInformerActions(f.kubeclient.Actions())[index]
updateAction, ok := action.(core.UpdateAction)
if !ok {
assert.Fail(f.t, "Expected Update action, not %s", action.GetVerb())
}
obj := updateAction.GetObject()
rs := &appsv1.ReplicaSet{}
converter := runtime.NewTestUnstructuredConverter(equality.Semantic)
objMap, _ := converter.ToUnstructured(obj)
runtime.NewTestUnstructuredConverter(equality.Semantic).FromUnstructured(objMap, rs)
return rs
}
func (f *fixture) getUpdatedExperiment(index int) *v1alpha1.Experiment {
action := filterInformerActions(f.client.Actions())[index]
updateAction, ok := action.(core.UpdateAction)
if !ok {
assert.Fail(f.t, "Expected Update action, not %s", action.GetVerb())
}
obj := updateAction.GetObject()
experiment := &v1alpha1.Experiment{}
converter := runtime.NewTestUnstructuredConverter(equality.Semantic)
objMap, _ := converter.ToUnstructured(obj)
runtime.NewTestUnstructuredConverter(equality.Semantic).FromUnstructured(objMap, experiment)
return experiment
}
func (f *fixture) getPatchedExperiment(index int) string {
action := filterInformerActions(f.client.Actions())[index]
patchAction, ok := action.(core.PatchAction)
if !ok {
f.t.Fatalf("Expected Patch action, not %s", action.GetVerb())
}
return string(patchAction.GetPatch())
}
func TestNoReconcileForDeletedExperiment(t *testing.T) {
f := newFixture(t)
defer f.Close()
e := newExperiment("foo", nil, pointer.Int32Ptr(10), pointer.BoolPtr(true))
now := metav1.Now()
e.DeletionTimestamp = &now
f.experimentLister = append(f.experimentLister, e)
f.objects = append(f.objects, e)
f.run(getKey(e, t))
}
type availableAtResults string
const (
Set availableAtResults = "Set"
Nulled availableAtResults = "NulledOut"
NoChange availableAtResults = "NoChange"
)
func validatePatch(t *testing.T, patch string, running *bool, availableleAt availableAtResults, templateStatuses []v1alpha1.TemplateStatus, conditions []v1alpha1.ExperimentCondition) {
e := v1alpha1.Experiment{}
err := json.Unmarshal([]byte(patch), &e)
if err != nil {
panic(err)
}
actualStatus := e.Status
if availableleAt == Set {
assert.NotNil(t, actualStatus.AvailableAt)
} else if availableleAt == Nulled {
assert.Contains(t, patch, `"availableAt": null`)
} else if availableleAt == NoChange {
assert.Nil(t, actualStatus.AvailableAt)
}
assert.Equal(t, e.Status.Running, running)
assert.Len(t, actualStatus.TemplateStatuses, len(templateStatuses))
for i := range templateStatuses {
assert.Contains(t, actualStatus.TemplateStatuses, templateStatuses[i])
}
assert.Len(t, actualStatus.Conditions, len(conditions))
for i := range conditions {
expectedCond := conditions[i]
for j := range actualStatus.Conditions {
hasComparedConditions := false
actualCond := conditions[j]
if actualCond.Type == expectedCond.Type {
assert.Equal(t, expectedCond.Status, actualCond.Status)
assert.Equal(t, expectedCond.LastUpdateTime, actualCond.LastUpdateTime)
assert.Equal(t, expectedCond.LastTransitionTime, actualCond.LastTransitionTime)
assert.Equal(t, expectedCond.Reason, actualCond.Reason)
assert.Equal(t, expectedCond.Message, actualCond.Message)
hasComparedConditions = true
}
assert.True(t, hasComparedConditions)
}
}
}
func TestAddInvalidSpec(t *testing.T) {
f := newFixture(t)
defer f.Close()
templates := generateTemplates("bar", "baz")
e := newExperiment("foo", templates, nil, pointer.BoolPtr(true))
e.Spec.Templates[0].Name = ""
f.experimentLister = append(f.experimentLister, e)
f.objects = append(f.objects, e)
patchIndex := f.expectPatchExperimentAction(e)
f.run(getKey(e, t))
patch := f.getPatchedExperiment(patchIndex)
cond := newCondition(conditions.InvalidSpecReason, e)
expectedPatch := calculatePatch(e, `{
"status":{
}
}`, nil, cond)
assert.Equal(t, expectedPatch, patch)
}
func TestKeepInvalidSpec(t *testing.T) {
f := newFixture(t)
defer f.Close()
templates := generateTemplates("bar", "baz")
e := newExperiment("foo", templates, nil, pointer.BoolPtr(true))
e.Status.Conditions = []v1alpha1.ExperimentCondition{{
Type: v1alpha1.InvalidExperimentSpec,
Status: corev1.ConditionTrue,
Reason: conditions.InvalidSpecReason,
Message: fmt.Sprintf(conditions.ExperimentTemplateNameEmpty, e.Name, 0),
}}
e.Spec.Templates[0].Name = ""
f.experimentLister = append(f.experimentLister, e)
f.objects = append(f.objects, e)
f.run(getKey(e, t))
}
func TestUpdateInvalidSpec(t *testing.T) {
f := newFixture(t)
defer f.Close()
templates := generateTemplates("bar", "baz")
e := newExperiment("foo", templates, nil, pointer.BoolPtr(true))
e.Status.Conditions = []v1alpha1.ExperimentCondition{{
Type: v1alpha1.InvalidExperimentSpec,
Status: corev1.ConditionTrue,
Reason: conditions.InvalidSpecReason,
Message: conditions.ExperimentSelectAllMessage,
}}
e.Spec.Templates[0].Name = ""
f.experimentLister = append(f.experimentLister, e)
f.objects = append(f.objects, e)
patchIndex := f.expectPatchExperimentAction(e)
f.run(getKey(e, t))
patch := f.getPatchedExperiment(patchIndex)
cond := newCondition(conditions.InvalidSpecReason, e)
expectedPatch := calculatePatch(e, `{
"status":{
}
}`, nil, cond)
assert.Equal(t, expectedPatch, patch)
}
func TestRemoveInvalidSpec(t *testing.T) {
f := newFixture(t)
defer f.Close()
templates := generateTemplates("bar", "baz")
e := newExperiment("foo", templates, nil, pointer.BoolPtr(true))
e.Status.Conditions = []v1alpha1.ExperimentCondition{{
Type: v1alpha1.InvalidExperimentSpec,
Status: corev1.ConditionTrue,
Reason: conditions.InvalidSpecReason,
}}
f.experimentLister = append(f.experimentLister, e)
f.objects = append(f.objects, e)
createFirstRSIndex := f.expectCreateReplicaSetAction(templateToRS(e, templates[0], 0))
createSecondRSIndex := f.expectCreateReplicaSetAction(templateToRS(e, templates[1], 0))
patchIndex := f.expectPatchExperimentAction(e)
f.run(getKey(e, t))
patch := f.getPatchedExperiment(patchIndex)
firstRS := f.getCreatedReplicaSet(createFirstRSIndex)
assert.NotNil(t, firstRS)
assert.Equal(t, generateRSName(e, templates[0]), firstRS.Name)
secondRS := f.getCreatedReplicaSet(createSecondRSIndex)
assert.NotNil(t, secondRS)
assert.Equal(t, generateRSName(e, templates[1]), secondRS.Name)
templateStatus := []v1alpha1.TemplateStatus{
generateTemplatesStatus("bar", 0, 0),
generateTemplatesStatus("baz", 0, 0),
}
cond := newCondition(conditions.ReplicaSetUpdatedReason, e)
expectedPatch := calculatePatch(e, `{
"status":{
}
}`, templateStatus, cond)
assert.Equal(t, expectedPatch, patch)
}