-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathclient_test.go
More file actions
1695 lines (1567 loc) · 53.2 KB
/
Copy pathclient_test.go
File metadata and controls
1695 lines (1567 loc) · 53.2 KB
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package helm
import (
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/skyhook-io/radar/pkg/helmhistory"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/cli"
kubefake "helm.sh/helm/v3/pkg/kube/fake"
"helm.sh/helm/v3/pkg/release"
helmstorage "helm.sh/helm/v3/pkg/storage"
storagedriver "helm.sh/helm/v3/pkg/storage/driver"
helmtime "helm.sh/helm/v3/pkg/time"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/fake"
ktesting "k8s.io/client-go/testing"
)
func TestFindBestUpgradeVersion(t *testing.T) {
tests := []struct {
name string
candidates []repoVersionInfo
sourceHosts []string
wantVersion string
wantRepo string
}{
{
name: "no candidates returns empty",
candidates: nil,
wantVersion: "",
wantRepo: "",
},
{
name: "single repo with current version",
candidates: []repoVersionInfo{
{repoName: "metallb", latestVersion: "0.15.3", hasCurrentVersion: true},
},
wantVersion: "0.15.3",
wantRepo: "metallb",
},
{
name: "multiple repos only one has current version - picks source repo",
candidates: []repoVersionInfo{
{repoName: "bitnami", latestVersion: "6.4.22", hasCurrentVersion: false},
{repoName: "metallb", latestVersion: "0.15.3", hasCurrentVersion: true},
},
wantVersion: "0.15.3",
wantRepo: "metallb",
},
{
name: "multiple repos both have current version without affinity - bail out",
candidates: []repoVersionInfo{
{repoName: "repo-a", latestVersion: "2.0.0", hasCurrentVersion: true, repoURL: "https://charts.example-a.com"},
{repoName: "repo-b", latestVersion: "3.0.0", hasCurrentVersion: true, repoURL: "https://charts.example-b.com"},
},
wantVersion: "",
wantRepo: "",
},
{
name: "multiple repos both have current version with affinity - picks matching repo",
candidates: []repoVersionInfo{
{repoName: "repo-a", latestVersion: "2.0.0", hasCurrentVersion: true, repoURL: "https://charts.example-a.com"},
{repoName: "repo-b", latestVersion: "3.0.0", hasCurrentVersion: true, repoURL: "https://charts.example-b.com"},
},
sourceHosts: []string{"example-b.com"},
wantVersion: "3.0.0",
wantRepo: "repo-b",
},
{
name: "source repo has lower latest than non-source - still picks source",
candidates: []repoVersionInfo{
{repoName: "community", latestVersion: "10.0.0", hasCurrentVersion: false},
{repoName: "official", latestVersion: "1.2.0", hasCurrentVersion: true},
},
wantVersion: "1.2.0",
wantRepo: "official",
},
{
name: "ambiguous chart-name collision without affinity - bail out",
candidates: []repoVersionInfo{
{repoName: "bitnami", latestVersion: "6.4.22", hasCurrentVersion: false, repoURL: "https://charts.bitnami.com/bitnami"},
{repoName: "argo", latestVersion: "8.5.0", hasCurrentVersion: false, repoURL: "https://argoproj.github.io/argo-helm"},
},
wantVersion: "",
wantRepo: "",
},
{
name: "single candidate without current version - accept (stale index case)",
candidates: []repoVersionInfo{
{repoName: "argo", latestVersion: "8.5.0", hasCurrentVersion: false, repoURL: "https://argoproj.github.io/argo-helm"},
},
wantVersion: "8.5.0",
wantRepo: "argo",
},
{
name: "source-affinity host match picks correct repo",
candidates: []repoVersionInfo{
{repoName: "bitnami", latestVersion: "6.4.22", hasCurrentVersion: false, repoURL: "https://charts.bitnami.com/bitnami"},
{repoName: "argo", latestVersion: "8.5.0", hasCurrentVersion: false, repoURL: "https://argoproj.github.io/argo-helm"},
},
sourceHosts: []string{"argoproj.github.io"},
wantVersion: "8.5.0",
wantRepo: "argo",
},
{
name: "source-affinity registered-domain match (charts.bitnami.com vs bitnami.com)",
candidates: []repoVersionInfo{
{repoName: "bitnami", latestVersion: "12.0.0", hasCurrentVersion: false, repoURL: "https://charts.bitnami.com/bitnami"},
{repoName: "argo", latestVersion: "8.5.0", hasCurrentVersion: false, repoURL: "https://argoproj.github.io/argo-helm"},
},
sourceHosts: []string{"bitnami.com"},
wantVersion: "12.0.0",
wantRepo: "bitnami",
},
{
name: "source-affinity hosts present but none match - bail out",
candidates: []repoVersionInfo{
{repoName: "bitnami", latestVersion: "6.4.22", hasCurrentVersion: false, repoURL: "https://charts.bitnami.com/bitnami"},
{repoName: "argo", latestVersion: "8.5.0", hasCurrentVersion: false, repoURL: "https://argoproj.github.io/argo-helm"},
},
sourceHosts: []string{"github.com"}, // chart-declared, but not the repo's host
wantVersion: "",
wantRepo: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotVersion, gotRepo := findBestUpgradeVersion(tt.candidates, tt.sourceHosts)
if gotVersion != tt.wantVersion {
t.Errorf("findBestUpgradeVersion() version = %q, want %q", gotVersion, tt.wantVersion)
}
if gotRepo != tt.wantRepo {
t.Errorf("findBestUpgradeVersion() repo = %q, want %q", gotRepo, tt.wantRepo)
}
})
}
}
func TestApplyNoClassicCandidateUpgrade_SourceIssueMapping(t *testing.T) {
tests := []struct {
name string
noClassicRepos bool
indexLoadFailed bool
hasRegisteredOCISources bool
ociFallback bool
wantIssue UpgradeSourceIssue
wantUntracked bool
wantSourceType string
wantErrorContains string
}{
{
name: "registered OCI source wins before repo index error",
indexLoadFailed: true,
hasRegisteredOCISources: true,
ociFallback: true,
wantSourceType: "oci",
},
{
name: "repo index error when OCI does not resolve",
indexLoadFailed: true,
hasRegisteredOCISources: true,
wantIssue: UpgradeSourceIssueRepoIndexError,
wantErrorContains: "failed to load one or more configured repository indexes",
},
{
name: "no configured chart sources",
noClassicRepos: true,
wantIssue: UpgradeSourceIssueUntracked,
wantUntracked: true,
wantErrorContains: "no chart sources configured",
},
{
name: "chart absent from configured sources",
hasRegisteredOCISources: true,
wantIssue: UpgradeSourceIssueUntracked,
wantUntracked: true,
wantErrorContains: "chart not found in configured repositories or registered OCI sources",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
info := &UpgradeInfo{}
applyNoClassicCandidateUpgrade(info, tt.noClassicRepos, tt.indexLoadFailed, tt.hasRegisteredOCISources, func() bool {
if !tt.ociFallback {
return false
}
info.SourceType = "oci"
info.ChartRef = "oci://reg/charts/app"
info.LatestVersion = "1.2.0"
return true
})
if info.SourceIssue != tt.wantIssue {
t.Fatalf("SourceIssue = %q, want %q (info=%+v)", info.SourceIssue, tt.wantIssue, info)
}
if info.Untracked != tt.wantUntracked {
t.Fatalf("Untracked = %v, want %v (info=%+v)", info.Untracked, tt.wantUntracked, info)
}
if info.SourceType != tt.wantSourceType {
t.Fatalf("SourceType = %q, want %q (info=%+v)", info.SourceType, tt.wantSourceType, info)
}
if tt.wantErrorContains != "" && !strings.Contains(info.Error, tt.wantErrorContains) {
t.Fatalf("Error = %q, want to contain %q", info.Error, tt.wantErrorContains)
}
if tt.wantErrorContains == "" && info.Error != "" {
t.Fatalf("Error = %q, want empty", info.Error)
}
})
}
}
func TestMarkUpgradeSourceIssue_AmbiguousRepositoryIsNotUntracked(t *testing.T) {
info := &UpgradeInfo{}
markUpgradeSourceIssue(info, UpgradeSourceIssueAmbiguousRepository, "could not identify upstream chart repository")
if info.SourceIssue != UpgradeSourceIssueAmbiguousRepository {
t.Fatalf("SourceIssue = %q, want %q", info.SourceIssue, UpgradeSourceIssueAmbiguousRepository)
}
if info.Untracked {
t.Fatal("ambiguous classic repository should not be marked untracked")
}
}
func TestChartSourceHosts(t *testing.T) {
tests := []struct {
name string
home string
sources []string
want []string
}{
{
name: "empty inputs",
want: nil,
},
{
name: "bitnami home only",
home: "https://bitnami.com",
want: []string{"bitnami.com"},
},
{
name: "subdomain expands to registered domain",
home: "https://charts.bitnami.com",
want: []string{"charts.bitnami.com", "bitnami.com"},
},
{
name: "deduplicates across home and sources",
home: "https://github.com/argoproj/argo-helm",
sources: []string{"https://github.com/argoproj/argo-cd"},
want: []string{"github.com", "argoproj.github.io"},
},
{
name: "argo-cd realistic chart metadata derives argoproj.github.io",
home: "https://github.com/argoproj/argo-helm",
want: []string{"github.com", "argoproj.github.io"},
},
{
name: "github.io chart home does not seed bare github.io (multi-tenant)",
home: "https://argoproj.github.io",
want: []string{"argoproj.github.io"},
},
{
name: "ipv4 host does not seed a bogus registered domain",
home: "http://127.0.0.1:8080/charts",
want: []string{"127.0.0.1"},
},
{
name: "skips invalid urls",
sources: []string{"not a url", "ftp://", ""},
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := chartSourceHosts(tt.home, tt.sources)
if !equalStringSlices(got, tt.want) {
t.Errorf("chartSourceHosts() = %v, want %v", got, tt.want)
}
})
}
}
func TestRepoURLMatchesAny(t *testing.T) {
tests := []struct {
name string
repoURL string
hosts []string
want bool
}{
{name: "empty repo url", repoURL: "", hosts: []string{"bitnami.com"}, want: false},
{name: "empty hosts", repoURL: "https://charts.bitnami.com", hosts: nil, want: false},
{name: "exact host match", repoURL: "https://argoproj.github.io/argo-helm", hosts: []string{"argoproj.github.io"}, want: true},
{name: "registered-domain match", repoURL: "https://charts.bitnami.com/bitnami", hosts: []string{"bitnami.com"}, want: true},
{name: "no match", repoURL: "https://charts.bitnami.com", hosts: []string{"argoproj.github.io"}, want: false},
{name: "github.io is multi-tenant: unrelated github.io repos do not match each other", repoURL: "https://kubernetes-sigs.github.io/external-dns", hosts: []string{"argoproj.github.io"}, want: false},
{name: "oci registry host match", repoURL: "oci://registry-1.docker.io/bitnamicharts/argo-cd", hosts: []string{"docker.io"}, want: true},
{name: "https with explicit port", repoURL: "https://charts.example.com:8443/charts", hosts: []string{"example.com"}, want: true},
{name: "https with userinfo", repoURL: "https://user:pass@charts.bitnami.com/bitnami", hosts: []string{"bitnami.com"}, want: true},
{name: "invalid url", repoURL: "://broken", hosts: []string{"bitnami.com"}, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := repoURLMatchesAny(tt.repoURL, tt.hosts); got != tt.want {
t.Errorf("repoURLMatchesAny(%q, %v) = %v, want %v", tt.repoURL, tt.hosts, got, tt.want)
}
})
}
}
func TestMarkCurrentVersion_DoesNotMutateBaseOrLeakAcrossReleases(t *testing.T) {
base := []repoVersionInfo{
{repoName: "bitnami", latestVersion: "20.0.0"},
{repoName: "argo", latestVersion: "8.5.0"},
}
versions := map[string][]string{
"bitnami": {"19.0.0", "20.0.0"},
"argo": {"8.4.0", "8.5.0"},
}
a := markCurrentVersion(base, versions, "20.0.0")
b := markCurrentVersion(base, versions, "8.5.0")
if !a[0].hasCurrentVersion || a[1].hasCurrentVersion {
t.Errorf("release A: bitnami should match, argo should not; got %+v", a)
}
if b[0].hasCurrentVersion || !b[1].hasCurrentVersion {
t.Errorf("release B: argo should match, bitnami should not; got %+v", b)
}
if base[0].hasCurrentVersion || base[1].hasCurrentVersion {
t.Errorf("base slice was mutated; per-release flags would leak across releases sharing a chart name: %+v", base)
}
}
func TestToHelmRelease_StorageNamespace(t *testing.T) {
rel := &release.Release{
Name: "podinfo",
Namespace: "demo-flux-helm",
Version: 1,
Info: &release.Info{
Status: release.StatusDeployed,
LastDeployed: helmtime.Unix(0, 0),
},
Chart: &chart.Chart{Metadata: &chart.Metadata{
Name: "podinfo",
Version: "6.11.2",
AppVersion: "6.11.2",
}},
}
same := toHelmRelease(rel, "demo-flux-helm")
if same.StorageNamespace != "" {
t.Fatalf("same storage namespace should be omitted, got %q", same.StorageNamespace)
}
different := toHelmRelease(rel, "flux-system")
if different.Namespace != "demo-flux-helm" {
t.Fatalf("target namespace changed: got %q", different.Namespace)
}
if different.StorageNamespace != "flux-system" {
t.Fatalf("storage namespace = %q, want flux-system", different.StorageNamespace)
}
}
func TestHelmReleaseStorageNamespacesWithClient(t *testing.T) {
assertStorageNamespaceFromSecret(t, false)
}
func TestHelmReleaseStorageNamespacesWithClient_GzippedPayload(t *testing.T) {
assertStorageNamespaceFromSecret(t, true)
}
func TestHelmReleaseRowsFromStorageSnapshot_AttachesLastOperation(t *testing.T) {
revisions := []*release.Release{
helmTestRelease("atomic", "demo", 1, release.StatusSuperseded, "Install complete"),
helmTestRelease("atomic", "demo", 2, release.StatusFailed, `Upgrade "atomic" failed: timed out waiting for the condition`),
helmTestRelease("atomic", "demo", 3, release.StatusDeployed, "Rollback to 1"),
}
secrets := make([]*corev1.Secret, 0, len(revisions))
for _, rel := range revisions {
secrets = append(secrets, helmReleaseSecret(t, "flux-system", rel, false))
}
client := fake.NewSimpleClientset(secretsToObjects(secrets)...)
snapshot, err := helmReleaseStorageSnapshotWithClient(client, "")
if err != nil {
t.Fatal(err)
}
rows := helmReleaseRowsFromStorageSnapshot(snapshot, nil)
if len(rows) != 1 {
t.Fatalf("len(rows) = %d, want 1", len(rows))
}
row := rows[0]
if row.Revision != 3 {
t.Fatalf("revision = %d, want 3", row.Revision)
}
if row.StorageNamespace != "flux-system" {
t.Fatalf("storage namespace = %q, want flux-system", row.StorageNamespace)
}
if row.LastOperation == nil {
t.Fatal("LastOperation = nil")
}
if row.LastOperation.Kind != helmhistory.KindUpgradeRolledBack {
t.Fatalf("kind = %q, want %q", row.LastOperation.Kind, helmhistory.KindUpgradeRolledBack)
}
if row.LastOperation.FailedRevision != 2 || row.LastOperation.RollbackRevision != 3 || row.LastOperation.TargetRevision != 1 {
t.Fatalf("operation revisions = failed:%d rollback:%d target:%d", row.LastOperation.FailedRevision, row.LastOperation.RollbackRevision, row.LastOperation.TargetRevision)
}
if row.LastOperation.FailureDescription == "" {
t.Fatal("FailureDescription is empty")
}
if len(row.Operations) != 1 {
t.Fatalf("len(Operations) = %d, want 1", len(row.Operations))
}
if row.Operations[0].Kind != helmhistory.KindUpgradeRolledBack {
t.Fatalf("operations[0].kind = %q, want %q", row.Operations[0].Kind, helmhistory.KindUpgradeRolledBack)
}
}
func TestHelmReleaseRowsFromStorageSnapshot_KeepsHealthyRowsCompact(t *testing.T) {
rel := helmTestRelease("healthy", "demo", 1, release.StatusDeployed, "Install complete")
client := fake.NewSimpleClientset(helmReleaseSecret(t, "demo", rel, false))
snapshot, err := helmReleaseStorageSnapshotWithClient(client, "")
if err != nil {
t.Fatal(err)
}
rows := helmReleaseRowsFromStorageSnapshot(snapshot, nil)
if len(rows) != 1 {
t.Fatalf("len(rows) = %d, want 1", len(rows))
}
if rows[0].LastOperation != nil {
t.Fatalf("LastOperation = %#v, want nil", rows[0].LastOperation)
}
if len(rows[0].Operations) != 0 {
t.Fatalf("Operations = %#v, want none", rows[0].Operations)
}
}
func TestHelmReleaseRowsFromStorageSnapshot_SkipsMalformedReleaseSecret(t *testing.T) {
malformed := &release.Release{
Name: "malformed",
Namespace: "demo",
Version: 1,
Info: &release.Info{
Status: release.StatusDeployed,
LastDeployed: helmtime.Unix(1, 0),
},
}
client := fake.NewSimpleClientset(helmReleaseSecret(t, "demo", malformed, false))
snapshot, err := helmReleaseStorageSnapshotWithClient(client, "")
if err != nil {
t.Fatal(err)
}
rows := helmReleaseRowsFromStorageSnapshot(snapshot, nil)
if len(rows) != 0 {
t.Fatalf("len(rows) = %d, want 0 for malformed release secret", len(rows))
}
}
func TestHelmReleaseRowsFromStorageSnapshot_CapsOperations(t *testing.T) {
revisions := []*release.Release{
helmTestRelease("repeat", "demo", 1, release.StatusSuperseded, "Install complete"),
helmTestRelease("repeat", "demo", 2, release.StatusFailed, `Upgrade "repeat" failed: first`),
helmTestRelease("repeat", "demo", 3, release.StatusSuperseded, "Rollback to 1"),
helmTestRelease("repeat", "demo", 4, release.StatusFailed, `Upgrade "repeat" failed: second`),
helmTestRelease("repeat", "demo", 5, release.StatusSuperseded, "Rollback to 3"),
helmTestRelease("repeat", "demo", 6, release.StatusFailed, `Upgrade "repeat" failed: third`),
helmTestRelease("repeat", "demo", 7, release.StatusSuperseded, "Rollback to 5"),
helmTestRelease("repeat", "demo", 8, release.StatusFailed, `Upgrade "repeat" failed: fourth`),
helmTestRelease("repeat", "demo", 9, release.StatusDeployed, "Rollback to 7"),
}
secrets := make([]*corev1.Secret, 0, len(revisions))
for _, rel := range revisions {
secrets = append(secrets, helmReleaseSecret(t, "demo", rel, false))
}
client := fake.NewSimpleClientset(secretsToObjects(secrets)...)
snapshot, err := helmReleaseStorageSnapshotWithClient(client, "")
if err != nil {
t.Fatal(err)
}
rows := helmReleaseRowsFromStorageSnapshot(snapshot, nil)
if len(rows) != 1 {
t.Fatalf("len(rows) = %d, want 1", len(rows))
}
if len(rows[0].Operations) != 3 {
t.Fatalf("len(Operations) = %d, want 3: %#v", len(rows[0].Operations), rows[0].Operations)
}
wantRollbackRevisions := []int{9, 7, 5}
for i, want := range wantRollbackRevisions {
if rows[0].Operations[i].RollbackRevision != want {
t.Fatalf("Operations[%d].RollbackRevision = %d, want %d", i, rows[0].Operations[i].RollbackRevision, want)
}
}
}
func TestHelmReleaseRowsFromStorageSnapshot_UsesDetailHistoryWindow(t *testing.T) {
revisions := []*release.Release{
helmTestRelease("long-lived", "demo", 1, release.StatusSuperseded, "Install complete"),
helmTestRelease("long-lived", "demo", 2, release.StatusFailed, `Upgrade "long-lived" failed: early failure`),
helmTestRelease("long-lived", "demo", 3, release.StatusSuperseded, "Rollback to 1"),
}
for rev := 4; rev <= releaseHistoryMax+44; rev++ {
status := release.StatusSuperseded
if rev == releaseHistoryMax+44 {
status = release.StatusDeployed
}
revisions = append(revisions, helmTestRelease("long-lived", "demo", rev, status, "Upgrade complete"))
}
secrets := make([]*corev1.Secret, 0, len(revisions))
for _, rel := range revisions {
secrets = append(secrets, helmReleaseSecret(t, "demo", rel, false))
}
client := fake.NewSimpleClientset(secretsToObjects(secrets)...)
snapshot, err := helmReleaseStorageSnapshotWithClient(client, "")
if err != nil {
t.Fatal(err)
}
rows := helmReleaseRowsFromStorageSnapshot(snapshot, nil)
if len(rows) != 1 {
t.Fatalf("len(rows) = %d, want 1", len(rows))
}
if rows[0].Revision != releaseHistoryMax+44 {
t.Fatalf("revision = %d, want %d", rows[0].Revision, releaseHistoryMax+44)
}
if rows[0].LastOperation != nil {
t.Fatalf("LastOperation = %#v, want nil for operations outside detail history window", rows[0].LastOperation)
}
if len(rows[0].Operations) != 0 {
t.Fatalf("Operations = %#v, want none for operations outside detail history window", rows[0].Operations)
}
if got := len(snapshot.histories["demo/long-lived"]); got != releaseHistoryMax {
t.Fatalf("history window = %d, want %d", got, releaseHistoryMax)
}
}
func TestComputeValuesDiffIsStableForReorderedMaps(t *testing.T) {
left := &HelmValues{UserSupplied: map[string]any{
"image": map[string]any{
"tag": "1.0.0",
"repository": "example/cart",
},
"replicaCount": 2,
}}
right := &HelmValues{UserSupplied: map[string]any{
"replicaCount": 2,
"image": map[string]any{
"repository": "example/cart",
"tag": "1.0.0",
},
}}
diff, err := computeValuesDiff(left, right, 1, 2, false)
if err != nil {
t.Fatal(err)
}
if diffHasBodyChange(diff) {
t.Fatalf("diff has body changes for reordered equal maps:\n%s", diff)
}
}
func TestGetValuesWithAllValuesKeepsComputedWhenUserValuesReadFails(t *testing.T) {
rel := helmTestRelease("values-demo", "demo", 1, release.StatusDeployed, "deployed")
rel.Chart = &chart.Chart{
Metadata: &chart.Metadata{Name: "values-demo"},
Values: map[string]any{
"replicaCount": 1,
"image": map[string]any{
"repository": "example/app",
"tag": "default",
},
},
}
rel.Config = map[string]any{
"image": map[string]any{
"tag": "2.0.0",
},
}
driver := &failSecondReadDriver{inner: storagedriver.NewMemory()}
actionConfig := &action.Configuration{
KubeClient: &kubefake.PrintingKubeClient{Out: io.Discard},
Releases: helmstorage.Init(driver),
}
if err := actionConfig.Releases.Create(rel); err != nil {
t.Fatal(err)
}
values, err := getValuesWith(actionConfig, rel.Name, true, rel.Version)
if err != nil {
t.Fatal(err)
}
if values.Computed == nil {
t.Fatal("Computed = nil, want computed values from successful all-values read")
}
if got := values.Computed["replicaCount"]; got != 1 {
t.Fatalf("Computed[replicaCount] = %#v, want 1", got)
}
image, ok := values.Computed["image"].(map[string]any)
if !ok {
t.Fatalf("Computed[image] = %#v, want map", values.Computed["image"])
}
if got := image["tag"]; got != "2.0.0" {
t.Fatalf("Computed[image][tag] = %#v, want user override", got)
}
if len(values.UserSupplied) != 0 {
t.Fatalf("UserSupplied = %#v, want empty when secondary read fails", values.UserSupplied)
}
}
func TestChartForUpgradeTargetReusesReleaseChartForSameVersion(t *testing.T) {
client := testHelmClientWithRepoConfigOnly(t)
rel := helmTestRelease("argo-cd", "demo", 1, release.StatusDeployed, "deployed")
rel.Chart.Metadata.Version = "9.5.11"
got, err := client.chartForUpgradeTarget(nil, rel, "9.5.11", "missing-repo", func(phase, message, detail string) {
t.Fatalf("same-version chart selection should not resolve/download chart, got progress %q %q %q", phase, message, detail)
})
if err != nil {
t.Fatal(err)
}
if got != rel.Chart {
t.Fatal("chartForUpgradeTarget returned a different chart, want current release chart")
}
}
func TestDiffResourceRefs(t *testing.T) {
left := []ResourceRef{
{APIVersion: "apps/v1", Kind: "Deployment", Namespace: "demo", Name: "cart"},
{APIVersion: "v1", Kind: "Service", Namespace: "demo", Name: "cart"},
}
right := []ResourceRef{
{APIVersion: "apps/v1", Kind: "Deployment", Namespace: "demo", Name: "cart"},
{APIVersion: "v1", Kind: "ConfigMap", Namespace: "demo", Name: "cart-config"},
}
removed, added, unchanged := diffResourceRefs(left, right)
if len(removed) != 1 || removed[0].Kind != "Service" {
t.Fatalf("removed = %#v, want Service", removed)
}
if len(added) != 1 || added[0].Kind != "ConfigMap" {
t.Fatalf("added = %#v, want ConfigMap", added)
}
if len(unchanged) != 1 || unchanged[0].Kind != "Deployment" {
t.Fatalf("unchanged = %#v, want Deployment", unchanged)
}
}
func TestDiffHooks(t *testing.T) {
now := time.Date(2026, 6, 29, 12, 0, 0, 0, time.UTC)
later := now.Add(time.Minute)
left := []HelmHook{
{Name: "migrate", Namespace: "demo", Kind: "Job", Events: []string{"pre-upgrade"}, Weight: 0, Status: "Succeeded", StartedAt: &now, CompletedAt: &now},
{Name: "cleanup", Namespace: "demo", Kind: "Job", Events: []string{"post-delete"}, Weight: 0, Status: "Succeeded"},
{Name: "seed", Namespace: "demo", Kind: "Job", Events: []string{"post-install", "post-upgrade"}, DeletePolicies: []string{"hook-succeeded", "before-hook-creation"}, Weight: 0, Status: "Succeeded"},
{Name: "schema", Namespace: "demo", Kind: "Job", Events: []string{"pre-upgrade"}, Weight: 0, ManifestDigest: "old-body"},
}
right := []HelmHook{
{Name: "migrate", Namespace: "demo", Kind: "Job", Events: []string{"pre-upgrade"}, Weight: 10, Status: "Succeeded"},
{Name: "seed", Namespace: "demo", Kind: "Job", Events: []string{"post-upgrade", "post-install"}, DeletePolicies: []string{"before-hook-creation", "hook-succeeded"}, Weight: 0, Status: "Failed", StartedAt: &later, CompletedAt: &later},
{Name: "schema", Namespace: "demo", Kind: "Job", Events: []string{"pre-upgrade"}, Weight: 0, ManifestDigest: "new-body"},
{Name: "verify", Namespace: "demo", Kind: "Job", Events: []string{"post-upgrade"}, Weight: 0, Status: "Succeeded"},
}
removed, added, modified, unchanged := diffHooks(left, right)
if len(removed) != 1 || removed[0].Name != "cleanup" {
t.Fatalf("removed = %#v, want cleanup", removed)
}
if len(added) != 1 || added[0].Name != "verify" {
t.Fatalf("added = %#v, want verify", added)
}
if len(modified) != 2 {
t.Fatalf("modified = %#v, want migrate and schema", modified)
}
modifiedByName := map[string]HelmHook{}
for _, hook := range modified {
modifiedByName[hook.Name] = hook
}
if modifiedByName["migrate"].Weight != 10 {
t.Fatalf("modified = %#v, want updated migrate hook", modified)
}
if modifiedByName["schema"].ManifestDigest != "new-body" || !modifiedByName["schema"].ManifestChanged {
t.Fatalf("modified = %#v, want hook body change", modified)
}
if len(unchanged) != 1 || unchanged[0].Name != "seed" {
t.Fatalf("unchanged = %#v, want seed", unchanged)
}
}
func TestDiffRenderedResourceObjectsDetectsModifiedDeploymentFields(t *testing.T) {
oldManifest := `apiVersion: apps/v1
kind: Deployment
metadata:
name: cart
namespace: demo
spec:
selector:
matchLabels:
app: cart
template:
metadata:
labels:
app: cart
spec:
containers:
- name: app
image: nginx:1.25
readinessProbe:
httpGet:
path: /healthz
port: 8080
`
newManifest := `apiVersion: apps/v1
kind: Deployment
metadata:
name: cart
namespace: demo
spec:
selector:
matchLabels:
app: cart
template:
metadata:
labels:
app: cart
spec:
containers:
- name: app
image: nginx:1.26
readinessProbe:
httpGet:
path: /ready
port: 8080
`
left, _ := parseManifestResourceObjects(oldManifest, "demo")
right, _ := parseManifestResourceObjects(newManifest, "demo")
removed, added, common := diffResourceRefs(resourceRefsFromRendered(left), resourceRefsFromRendered(right))
modified, unchanged := diffRenderedResourceObjects(common, left, right)
if len(removed) != 0 || len(added) != 0 || len(unchanged) != 0 {
t.Fatalf("removed=%#v added=%#v unchanged=%#v, want only modified", removed, added, unchanged)
}
if len(modified) != 1 {
t.Fatalf("modified = %#v, want one Deployment", modified)
}
gotPaths := map[string]bool{}
for _, field := range modified[0].Fields {
gotPaths[field.Path] = true
}
for _, want := range []string{
"spec.template.spec.containers[app].image",
"spec.template.spec.containers[app].readinessProbe",
} {
if !gotPaths[want] {
t.Fatalf("modified paths = %#v, missing %s", gotPaths, want)
}
}
}
func TestDiffRenderedResourceObjectsIgnoresDeploymentMetadataOnlyChanges(t *testing.T) {
oldManifest := `apiVersion: apps/v1
kind: Deployment
metadata:
name: cart
namespace: demo
labels:
helm.sh/chart: cart-1.0.0
spec:
replicas: 2
selector:
matchLabels:
app: cart
template:
metadata:
labels:
app: cart
spec:
containers:
- name: app
image: nginx:1.25
`
newManifest := `apiVersion: apps/v1
kind: Deployment
metadata:
name: cart
namespace: demo
labels:
helm.sh/chart: cart-1.0.1
spec:
replicas: 2
selector:
matchLabels:
app: cart
template:
metadata:
labels:
app: cart
spec:
containers:
- name: app
image: nginx:1.25
`
left, _ := parseManifestResourceObjects(oldManifest, "demo")
right, _ := parseManifestResourceObjects(newManifest, "demo")
_, _, common := diffResourceRefs(resourceRefsFromRendered(left), resourceRefsFromRendered(right))
modified, unchanged := diffRenderedResourceObjects(common, left, right)
if len(modified) != 0 {
t.Fatalf("modified = %#v, want metadata-only change ignored", modified)
}
if len(unchanged) != 1 {
t.Fatalf("unchanged = %#v, want one unchanged Deployment", unchanged)
}
}
func TestDiffRenderedResourceObjectsIgnoresGenericHelmChartLabelOnlyChanges(t *testing.T) {
oldManifest := `apiVersion: example.com/v1
kind: Widget
metadata:
name: cart
namespace: demo
labels:
helm.sh/chart: cart-1.0.0
spec:
size: medium
`
newManifest := `apiVersion: example.com/v1
kind: Widget
metadata:
name: cart
namespace: demo
labels:
helm.sh/chart: cart-1.0.1
spec:
size: medium
`
left, _ := parseManifestResourceObjects(oldManifest, "demo")
right, _ := parseManifestResourceObjects(newManifest, "demo")
_, _, common := diffResourceRefs(resourceRefsFromRendered(left), resourceRefsFromRendered(right))
modified, unchanged := diffRenderedResourceObjects(common, left, right)
if len(modified) != 0 {
t.Fatalf("modified = %#v, want Helm chart label-only change ignored", modified)
}
if len(unchanged) != 1 {
t.Fatalf("unchanged = %#v, want one unchanged custom resource", unchanged)
}
}
func TestDiffRenderedResourceObjectsIgnoresGenericHelmChartLabelAdded(t *testing.T) {
oldManifest := `apiVersion: example.com/v1
kind: Widget
metadata:
name: cart
namespace: demo
spec:
size: medium
`
newManifest := `apiVersion: example.com/v1
kind: Widget
metadata:
name: cart
namespace: demo
labels:
helm.sh/chart: cart-1.0.1
spec:
size: medium
`
left, _ := parseManifestResourceObjects(oldManifest, "demo")
right, _ := parseManifestResourceObjects(newManifest, "demo")
_, _, common := diffResourceRefs(resourceRefsFromRendered(left), resourceRefsFromRendered(right))
modified, unchanged := diffRenderedResourceObjects(common, left, right)
if len(modified) != 0 {
t.Fatalf("modified = %#v, want Helm chart label add ignored", modified)
}
if len(unchanged) != 1 {
t.Fatalf("unchanged = %#v, want one unchanged custom resource", unchanged)
}
}
func TestParseManifestResourceObjectsUsesMetadataName(t *testing.T) {
resources, parseErrors := parseManifestResourceObjects(`apiVersion: apps/v1
kind: Deployment
metadata:
name: cart
spec:
template:
spec:
containers:
- name: app
image: nginx
`, "demo")
if parseErrors != 0 {
t.Fatalf("parseErrors = %d, want 0", parseErrors)
}
if len(resources) != 1 {
t.Fatalf("resources = %#v, want one resource", resources)
}
ref := resources[0].Ref
if ref.Name != "cart" || ref.Namespace != "demo" || ref.Kind != "Deployment" || ref.APIVersion != "apps/v1" {
t.Fatalf("ref = %#v, want apps/v1 Deployment demo/cart", ref)
}
}
func TestParseManifestResourceObjectsKeepsClusterScopedNamespaceEmpty(t *testing.T) {
resources, parseErrors := parseManifestResourceObjects(`apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: chart-reader
rules: []
`, "demo")
if parseErrors != 0 {
t.Fatalf("parseErrors = %d, want 0", parseErrors)
}
if len(resources) != 1 {
t.Fatalf("resources = %#v, want one resource", resources)
}
ref := resources[0].Ref
if ref.Name != "chart-reader" || ref.Namespace != "" || ref.Kind != "ClusterRole" || ref.APIVersion != "rbac.authorization.k8s.io/v1" {
t.Fatalf("ref = %#v, want rbac.authorization.k8s.io/v1 ClusterRole chart-reader with empty namespace", ref)
}
}
func TestParseManifestResourceObjectsReportsParseErrors(t *testing.T) {
resources, parseErrors := parseManifestResourceObjects(`apiVersion: v1
kind: ConfigMap
metadata:
name: good
---
apiVersion: v1
kind: ConfigMap
metadata:
name: bad
labels:
broken: [
---
apiVersion: v1
kind: Service
metadata:
name: ok
spec:
ports:
- port: 80
`, "demo")
if parseErrors != 1 {
t.Fatalf("parseErrors = %d, want 1", parseErrors)
}
if len(resources) != 2 {
t.Fatalf("resources = %#v, want two parsed resources", resources)
}
}
type failSecondReadDriver struct {
inner *storagedriver.Memory
reads int
}
func (d *failSecondReadDriver) Name() string {
return d.inner.Name()
}