Repository navigation
Expand file tree
/
Copy pathtest_helm.py
More file actions
2148 lines (1877 loc) · 76.4 KB
/
Copy pathtest_helm.py
File metadata and controls
2148 lines (1877 loc) · 76.4 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
import json
import logging
import os
import shutil
import subprocess
from pathlib import Path
import pytest
from test_util import write_tree
from ch_cli_tools.api import create_helm_chart
from ch_cli_tools.model import (
DependencyUnknownError,
KEY_APPS,
KEY_DATABASE,
KEY_DEPLOYMENT,
KEY_HARNESS,
KEY_SERVICE,
KEY_TASK_IMAGES,
KEY_TEST_IMAGES,
)
from ch_cli_tools.utils import ChartImageRef, find_chart_images, yaml
from cloudharness_utils.constants import APPS_PATH, DEPLOYMENT_CONFIGURATION_PATH, HELM_CHART_PATH
HERE = os.path.dirname(os.path.realpath(__file__))
RESOURCES = os.path.join(HERE, "resources")
CLOUDHARNESS_ROOT = os.path.dirname(
os.path.dirname(os.path.dirname(HERE))
)
def exists(path):
return path.exists()
def render_helm_chart(chart_path, values_files=(), set_values=()):
completed = subprocess.run(
[
"helm",
"template",
str(chart_path),
*(arg for f in values_files for arg in ("-f", str(f))),
*(arg for v in set_values for arg in ("--set", v)),
],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
return [manifest for manifest in yaml.load_all(completed.stdout) if manifest]
def find_manifest(manifests, kind, name):
for manifest in manifests:
if (
manifest.get("kind") == kind and
manifest.get("metadata", {}).get("name") == name
):
return manifest
raise AssertionError(f"Could not find {kind}/{name}")
def test_collect_helm_values(tmp_path):
out_folder = tmp_path / "test_collect_helm_values"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
include=["samples", "myapp"],
exclude=["events"],
domain="my.local",
namespace="test",
env="dev",
local=False,
tag=1,
registry="reg",
)
# First level include apps
assert "samples" in values[KEY_APPS]
assert "myapp" in values[KEY_APPS]
# Not included
assert "jupyterhub" not in values[KEY_APPS]
# Dependency include first level
assert "accounts" in values[KEY_APPS]
assert "legacy" in values[KEY_APPS]
# Dependency include second level
assert "argo" in values[KEY_APPS]
# Explicit exclude overrides include
assert "events" not in values[KEY_APPS]
assert (
values[KEY_APPS]["myapp"][KEY_HARNESS]["deployment"]["image"] ==
"reg/testprojectname/myapp:1"
)
assert values[KEY_APPS]["myapp"]["build"] == True
assert (
values.apps["myapp"].harness.deployment.image == "reg/testprojectname/myapp:1"
)
assert values[KEY_APPS]["myapp"][KEY_HARNESS]["name"] == "myapp"
assert values[KEY_APPS]["legacy"][KEY_HARNESS]["name"] == "legacy"
assert (
values[KEY_APPS]["accounts"][KEY_HARNESS]["deployment"]["image"] ==
"reg/testprojectname/accounts:1"
)
# Base values kept
assert values[KEY_APPS]["accounts"][KEY_HARNESS]["subdomain"] == "accounts"
# Defaults
assert "service" in values[KEY_APPS]["legacy"][KEY_HARNESS]
assert "common" in values[KEY_APPS]["legacy"]
assert "common" in values[KEY_APPS]["accounts"]
# Values overriding
assert (
values[KEY_APPS]["accounts"][KEY_HARNESS]["deployment"]["port"] == "overridden"
)
# Environment specific overriding
assert values[KEY_APPS]["accounts"]["a"] == "dev"
assert values["a"] == "dev"
assert values["database"]["auto"] is False
# legacy reading
assert values[KEY_APPS]["accounts"][KEY_HARNESS]["deployment"]["auto"] is True
assert values[KEY_APPS]["legacy"][KEY_HARNESS]["deployment"]["auto"] is False
helm_path = out_folder / HELM_CHART_PATH
assert exists(helm_path)
assert exists(helm_path / "values.yaml")
assert exists(helm_path / "resources" / "accounts" / "realm.json")
assert exists(helm_path / "resources" / "accounts" / "aresource.txt")
assert exists(helm_path / "resources" / "myapp" / "aresource.txt")
assert exists(helm_path / "templates" / "myapp" / "mytemplate.yaml")
assert values[KEY_TASK_IMAGES]
assert "cloudharness-base" in values[KEY_TASK_IMAGES]
assert (
values[KEY_TASK_IMAGES]["cloudharness-base"] ==
"reg/testprojectname/cloudharness-base:1"
)
assert (
values[KEY_TASK_IMAGES]["myapp-mytask"] == "reg/testprojectname/myapp-mytask:1"
)
assert (
values[KEY_TASK_IMAGES]["cloudharness-flask"] ==
"reg/testprojectname/cloudharness-flask:1"
)
assert "cloudharness-base-debian" not in values[KEY_TASK_IMAGES]
with open(helm_path / "charts/myapp/values.yaml", "r") as values_file:
chart_values = yaml.load(values_file)
assert chart_values is not None, "values.yaml should be valid YAML"
assert chart_values["test"] == "dev"
def test_overriding_root_deep_merges_data_files_and_replaces_templates(tmp_path):
"""A root overriding an application of a lower root states only the values it changes:
its sub-chart values.yaml and JSON resources are deep-merged over the lower root's ones,
while templates and other files replace them."""
base_root, top_root = tmp_path / "base", tmp_path / "top"
write_tree(base_root, {APPS_PATH: {"chartapp": {"deploy": {
"values.yaml": "harness: {}\n",
"resources": {"conf.json": '{"a": {"b": 1, "c": 2}}'},
"charts": {
"Chart.yaml": "apiVersion: v2\nname: vendored\nversion: 1.0.0\n",
"values.yaml": (
"workflow:\n rbac:\n create: true\n"
"controller:\n parallelism: null\n image:\n tag: v1\n"
),
"README.md": "vendored\n",
"templates": {"role.yaml": "{{- if .Values.workflow.rbac.create }}\nkind: Role\n{{- end }}\n"},
},
}}}})
write_tree(top_root, {APPS_PATH: {"chartapp": {"deploy": {
"resources": {"conf.json": '{"a": {"c": 3}}'},
"charts": {
"values.yaml": "controller:\n parallelism: 5\n",
"README.md": "overridden\n",
"templates": {"role.yaml": "{{- if .Values.workflow.rbac.create }}\nkind: ClusterRole\n{{- end }}\n"},
},
}}}})
out_folder = tmp_path / "out"
create_helm_chart(
[CLOUDHARNESS_ROOT, base_root, top_root],
output_path=out_folder,
include=["chartapp"],
domain="my.local",
namespace="test",
local=False,
tag=1,
)
helm_path = out_folder / HELM_CHART_PATH
chart_path = helm_path / "charts" / "chartapp"
chart_values = yaml.load(chart_path / "values.yaml")
assert chart_values["workflow"]["rbac"]["create"] is True
assert chart_values["controller"]["parallelism"] == 5
assert chart_values["controller"]["image"]["tag"] == "v1"
assert (chart_path / "README.md").read_text() == "overridden\n"
assert "ClusterRole" in (chart_path / "templates" / "role.yaml").read_text()
resource = json.loads((helm_path / "resources" / "chartapp" / "conf.json").read_text())
assert resource == {"a": {"b": 1, "c": 3}}
def test_collect_nobuild(tmp_path):
out_folder = tmp_path / "test_collect_helm_values"
values = create_helm_chart(
[RESOURCES],
output_path=out_folder,
include=["myapp"],
exclude=["events"],
domain="my.local",
namespace="test",
env="nobuild",
local=False,
tag=1,
registry="reg",
)
assert (
values[KEY_APPS]["myapp"][KEY_HARNESS]["deployment"]["image"] == "custom-image"
)
assert values[KEY_APPS]["myapp"]["build"] == False
def test_collect_helm_values_harness_image_name_override(tmp_path):
out_folder = tmp_path / "test_collect_helm_values_harness_image_name_override"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
include=["myapp"],
domain="my.local",
namespace="test",
env="imagename",
local=False,
tag=1,
registry="reg",
)
assert (
values[KEY_APPS]["myapp"][KEY_HARNESS]["deployment"]["image"] ==
"reg/testprojectname/custom-myapp:1"
)
assert (
values[KEY_APPS]["myapp"][KEY_TASK_IMAGES]["myapp-mytask"] ==
"reg/testprojectname/custom-myapp-mytask:1"
)
def test_collect_helm_values_noreg_noinclude(tmp_path):
out_path = tmp_path / "test_collect_helm_values_noreg_noinclude"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_path,
domain="my.local",
namespace="test",
env="dev",
local=False,
tag=1,
)
assert (
values[KEY_APPS]["myapp"][KEY_HARNESS]["deployment"]["image"] ==
"testprojectname/myapp:1"
)
assert values[KEY_APPS]["myapp"][KEY_HARNESS]["name"] == "myapp"
assert values[KEY_APPS]["legacy"][KEY_HARNESS]["name"] == "legacy"
assert (
values[KEY_APPS]["accounts"][KEY_HARNESS]["deployment"]["image"] ==
"testprojectname/accounts:1"
)
# First level include apps
assert "samples" in values[KEY_APPS]
assert "myapp" in values[KEY_APPS]
assert "jupyterhub" in values[KEY_APPS]
assert "accounts" in values[KEY_APPS]
assert "legacy" in values[KEY_APPS]
assert "argo" in values[KEY_APPS]
assert "events" in values[KEY_APPS]
# Base values kept
assert values[KEY_APPS]["accounts"][KEY_HARNESS]["subdomain"] == "accounts"
# Defaults
assert "service" in values[KEY_APPS]["legacy"][KEY_HARNESS]
assert "common" in values[KEY_APPS]["legacy"]
assert "common" in values[KEY_APPS]["accounts"]
# Values overriding
assert (
values[KEY_APPS]["accounts"][KEY_HARNESS]["deployment"]["port"] == "overridden"
)
assert (
values[KEY_APPS]["events"]["kafka"]["resources"]["limits"]["memory"] ==
"overridden"
)
# Environment specific overriding
assert values[KEY_APPS]["accounts"]["a"] == "dev"
assert values["a"] == "dev"
assert values["database"]["auto"] is False
# legacy reading
assert values[KEY_APPS]["accounts"][KEY_HARNESS]["deployment"]["auto"] is True
assert values[KEY_APPS]["legacy"][KEY_HARNESS]["deployment"]["auto"] is False
helm_path = out_path / HELM_CHART_PATH
assert exists(helm_path)
assert exists(helm_path / "values.yaml")
assert exists(helm_path / "resources" / "accounts" / "realm.json")
assert exists(helm_path / "resources" / "accounts" / "aresource.txt")
assert exists(helm_path / "resources" / "myapp" / "aresource.txt")
assert exists(helm_path / "templates" / "myapp" / "mytemplate.yaml")
assert values[KEY_TASK_IMAGES]
assert "cloudharness-base" in values[KEY_TASK_IMAGES]
assert (
values[KEY_TASK_IMAGES]["cloudharness-base"] ==
"testprojectname/cloudharness-base:1"
)
assert values[KEY_TASK_IMAGES]["myapp-mytask"] == "testprojectname/myapp-mytask:1"
assert values[KEY_TASK_IMAGES]["my-common"] == "testprojectname/my-common:1"
assert values["source_images"] == {
"GOLANG": "golang:1.26",
"ROCKYLINUX": "rockylinux/rockylinux:10.1-minimal",
"SENTRY": "sentry:9.1.2",
"KEYCLOAK": "myregistry.mykeycloak:99.9",
"mybase": "foo:bar",
"mybase2": "spam:egg",
"NODE": "node:22-alpine",
# Declared at the project level (deployment-configuration/values-template.yaml)
# rather than per-application, so that it is configured in one place.
"GATEKEEPER": "quay.io/gogatekeeper/gatekeeper:4.6.0",
}
def test_collect_helm_values_precedence(tmp_path):
out_folder = tmp_path / "test_collect_helm_values_precedence"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
namespace="test",
env="prod",
local=False,
tag=1,
include=["events"],
)
# Values.yaml from current app must override values-prod.yaml from cloudharness
assert (
values[KEY_APPS]["events"]["kafka"]["resources"]["limits"]["memory"] ==
"overridden"
)
assert (
values[KEY_APPS]["events"]["kafka"]["resources"]["limits"]["cpu"] ==
"overridden-prod"
)
def test_collect_helm_values_multiple_envs(tmp_path):
out_folder = tmp_path / "test_collect_helm_values_multiple_envs"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
namespace="test",
env=["dev", "test"],
local=False,
tag=1,
include=["myapp"],
)
assert values[KEY_APPS]["myapp"]["test"] is True, "values-test not loaded"
assert values[KEY_APPS]["myapp"]["dev"] is True, "values-dev not loaded"
assert values[KEY_APPS]["myapp"]["a"] == "test", "values-test not overriding"
def test_collect_app_defaults_env_specific_chart(tmp_path):
"""The deployment root value-template-[env].yaml lands in the generated chart values"""
out_folder = tmp_path / "test_collect_app_defaults_env_specific_chart"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
namespace="test",
env="dev",
local=False,
tag=1,
include=["myapp"],
)
assert values[KEY_APPS]["myapp"]["env-defaults"] == "resources-dev"
out_folder = tmp_path / "test_collect_app_defaults_no_env_chart"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
namespace="test",
local=False,
tag=1,
include=["myapp"],
)
assert "env-defaults" not in values[KEY_APPS]["myapp"]
# ng raises ch_cli_tools.model.DependencyUnknownError, not
# legacy's ValuesValidationException - a different exception class by design
# (see model.py's CHProject.all_values()/_combined_dependencies()). The build
# dependency case used to be unchecked by create_helm_chart entirely (that
# validation lived only in ng.skaffold's generate()), but
# CHProject.all_task_images() now walks the same build-dependency closure
# during build_final_helm_values() too, so it raises here as well - verified
# empirically against this exact fixture before porting.
def test_collect_helm_values_wrong_dependencies_validate(tmp_path):
out_folder = tmp_path / "test_collect_helm_values_wrong_dependencies_validate"
with pytest.raises(DependencyUnknownError):
create_helm_chart(
[CLOUDHARNESS_ROOT, f"{RESOURCES}/wrong-dependencies"],
output_path=out_folder,
domain="my.local",
namespace="test",
env="prod",
local=False,
tag=1,
include=["wrong-hard"],
)
try:
create_helm_chart(
[CLOUDHARNESS_ROOT, f"{RESOURCES}/wrong-dependencies"],
output_path=out_folder,
domain="my.local",
namespace="test",
env="prod",
local=False,
tag=1,
include=["wrong-soft"],
)
except DependencyUnknownError as e:
pytest.fail("Should not error because of wrong soft dependency")
with pytest.raises(DependencyUnknownError):
create_helm_chart(
[CLOUDHARNESS_ROOT, f"{RESOURCES}/wrong-dependencies"],
output_path=out_folder,
domain="my.local",
namespace="test",
env="prod",
local=False,
tag=1,
include=["wrong-build"],
)
try:
create_helm_chart(
[CLOUDHARNESS_ROOT, f"{RESOURCES}/wrong-dependencies"],
output_path=out_folder,
domain="my.local",
namespace="test",
env="prod",
local=False,
tag=1,
include=["wrong-services"],
)
except DependencyUnknownError:
pytest.fail("Should not error because of missing use_services dependency")
def test_collect_helm_values_build_dependencies(tmp_path):
out_folder = tmp_path / "test_collect_helm_values_build_dependencies"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
namespace="test",
env="prod",
local=False,
tag=1,
include=["myapp"],
)
assert "cloudharness-flask" in values[KEY_TASK_IMAGES], (
"Cloudharness-flask is included in the build dependencies"
)
assert "cloudharness-base" in values[KEY_TASK_IMAGES], (
"Cloudharness-base is included in cloudharness-flask Dockerfile and it should be guessed"
)
assert "cloudharness-base-debian" not in values[KEY_TASK_IMAGES], (
"Cloudharness-base-debian is not included in any dependency"
)
assert "cloudharness-frontend-build" not in values[KEY_TASK_IMAGES], (
"cloudharness-frontend-build is not included in any dependency"
)
def test_collect_helm_values_build_dependencies_nodeps(tmp_path):
out_folder = tmp_path / "test_collect_helm_values_build_dependencies_nodeps"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
namespace="test",
env="prod",
local=False,
tag=1,
include=["events"],
)
assert "cloudharness-flask" not in values[KEY_TASK_IMAGES], (
"Cloudharness-flask is not included in the build dependencies"
)
assert "cloudharness-base" not in values[KEY_TASK_IMAGES], (
"Cloudharness-base is not included in the build dependencies"
)
assert "cloudharness-base-debian" not in values[KEY_TASK_IMAGES], (
"Cloudharness-base-debian is not included in any dependency"
)
assert "cloudharness-frontend-build" not in values[KEY_TASK_IMAGES], (
"cloudharness-frontend-build is not included in any dependency"
)
def test_collect_helm_values_build_dependencies_exclude(tmp_path):
out_folder = tmp_path / "test_collect_helm_values_build_dependencies_exclude"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
namespace="test",
env="prod",
local=False,
tag=1,
include=["workflows"],
exclude=["workflows-extract-download"],
)
assert "cloudharness-flask" in values[KEY_TASK_IMAGES], (
"Cloudharness-flask is included in the build dependencies"
)
assert "cloudharness-base" in values[KEY_TASK_IMAGES], (
"Cloudharness-base is included in cloudharness-flask Dockerfile and it should be guessed"
)
assert "workflows-extract-download" not in values[KEY_TASK_IMAGES], (
"workflows-extract-download has been explicitly excluded"
)
def test_clear_unused_dbconfig(tmp_path):
out_folder = tmp_path / "test_clear_unused_dbconfig"
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
env="withpostgres",
local=False,
include=["myapp"],
exclude=["legacy"],
)
# There is a DB config
assert KEY_DATABASE in values[KEY_APPS]["myapp"][KEY_HARNESS]
db_config = values[KEY_APPS]["myapp"][KEY_HARNESS][KEY_DATABASE]
# postgres is set, but other entries are not.
assert db_config["postgres"] is not None
assert db_config["postgres"]["image"].startswith("postgres:")
assert db_config["mongo"] is None
assert db_config["neo4j"] is None
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
namespace="test",
env="withmongo",
local=False,
include=["myapp"],
exclude=["legacy"],
)
assert KEY_DATABASE in values[KEY_APPS]["myapp"][KEY_HARNESS]
db_config = values[KEY_APPS]["myapp"][KEY_HARNESS][KEY_DATABASE]
# mongo is set, but other entries are not.
assert db_config["mongo"] is not None
assert db_config["mongo"]["image"].startswith("mongo:")
assert db_config["neo4j"] is None
assert db_config["postgres"] is None
def test_cnpg_postgres_parameters_render_only_when_set(tmp_path):
out_folder = tmp_path / "test_cnpg_postgres_parameters_render_only_when_set"
create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
env="withpostgres",
local=False,
include=["myapp"],
exclude=["legacy"],
)
helm_path = out_folder / "helm"
shutil.rmtree(helm_path / "charts")
values_path = helm_path / "values.yaml"
with open(values_path, "r") as values_file:
values = yaml.load(values_file)
postgres = values["apps"]["myapp"]["harness"]["database"]["postgres"]
postgres["operator"] = True
postgres["parameters"] = {
# Simulate generated YAML values where on/off can be parsed as booleans before Helm renders the chart.
"autovacuum": True,
"max_connections": "200",
"shared_buffers": "1GB",
"synchronous_commit": True,
"track_io_timing": False,
}
with open(values_path, "w") as values_file:
yaml.dump(values, values_file)
manifests = render_helm_chart(helm_path)
db_name = values["apps"]["myapp"]["harness"]["database"]["name"]
cluster = find_manifest(manifests, "Cluster", db_name)
assert cluster["spec"]["postgresql"]["parameters"] == {
"autovacuum": "true",
"max_connections": "200",
"shared_buffers": "1GB",
"synchronous_commit": "true",
"track_io_timing": "false",
}
postgres["parameters"] = {}
with open(values_path, "w") as values_file:
yaml.dump(values, values_file)
manifests = render_helm_chart(helm_path)
cluster = find_manifest(manifests, "Cluster", db_name)
assert "postgresql" not in cluster["spec"]
postgres.pop("parameters")
with open(values_path, "w") as values_file:
yaml.dump(values, values_file)
manifests = render_helm_chart(helm_path)
cluster = find_manifest(manifests, "Cluster", db_name)
assert "postgresql" not in cluster["spec"]
def test_statefulset_option(tmp_path):
out_folder = tmp_path / "test_statefulset_option"
# nfsserver is included to provide the storage class values needed by the usenfs case
create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
env="withpostgres",
local=False,
include=["myapp", "nfsserver"],
exclude=["legacy"],
)
helm_path = out_folder / "helm"
shutil.rmtree(helm_path / "charts")
values_path = helm_path / "values.yaml"
with open(values_path, "r") as values_file:
values = yaml.load(values_file)
myapp = values["apps"]["myapp"]
harness = myapp["harness"]
dep_name = harness["deployment"]["name"]
db_name = harness["database"]["name"]
service_name = harness["service"]["name"]
harness["deployment"]["auto"] = True
harness["deployment"]["volume"] = {
"name": "myapp-data",
"mountpath": "/data",
"size": "1Gi",
"auto": True,
}
with open(values_path, "w") as values_file:
yaml.dump(values, values_file)
# Default: Deployments with the Recreate/affinity workaround and a standalone PVC
manifests = render_helm_chart(helm_path)
dep = find_manifest(manifests, "Deployment", dep_name)
assert dep["spec"]["strategy"]["type"] == "Recreate"
assert "affinity" in dep["spec"]["template"]["spec"]
find_manifest(manifests, "PersistentVolumeClaim", "myapp-data")
db_dep = find_manifest(manifests, "Deployment", db_name)
assert db_dep["spec"]["strategy"]["type"] == "Recreate"
assert "affinity" in db_dep["spec"]["template"]["spec"]
find_manifest(manifests, "PersistentVolumeClaim", db_name)
# Opt in to StatefulSets: volumes are provisioned via volumeClaimTemplates. The legacy
# volume migration (job copying a pre-existing PVC found by `lookup` into the statefulset
# volumes) cannot be exercised here: `helm template` runs without a cluster, so `lookup`
# finds nothing.
harness["deployment"]["statefulset"] = True
harness["database"]["statefulset"] = True
with open(values_path, "w") as values_file:
yaml.dump(values, values_file)
manifests = render_helm_chart(helm_path)
sts = find_manifest(manifests, "StatefulSet", dep_name)
assert sts["spec"]["serviceName"] == service_name
# OrderedReady would block template updates while an existing pod is unready,
# so a crash-looping pod could never be replaced by its own fix.
assert sts["spec"]["podManagementPolicy"] == "Parallel"
assert "strategy" not in sts["spec"]
assert "affinity" not in sts["spec"]["template"]["spec"]
assert "initContainers" not in sts["spec"]["template"]["spec"]
claims = [
v["persistentVolumeClaim"]["claimName"]
for v in sts["spec"]["template"]["spec"]["volumes"]
if "persistentVolumeClaim" in v
]
assert "myapp-data" not in claims
assert sts["spec"]["volumeClaimTemplates"][0]["metadata"]["name"] == "myapp-data"
assert not any(
m
for m in manifests
if m.get("kind") == "PersistentVolumeClaim" and
m.get("metadata", {}).get("name") == "myapp-data"
)
db_sts = find_manifest(manifests, "StatefulSet", db_name)
assert db_sts["spec"]["serviceName"] == db_name
assert db_sts["spec"]["podManagementPolicy"] == "Parallel"
assert "strategy" not in db_sts["spec"]
assert "affinity" not in db_sts["spec"]["template"]["spec"]
assert "initContainers" not in db_sts["spec"]["template"]["spec"]
assert db_sts["spec"]["volumeClaimTemplates"][0]["metadata"]["name"] == db_name
assert not any(
m
for m in manifests
if m.get("kind") == "PersistentVolumeClaim" and
m.get("metadata", {}).get("name") == db_name
)
find_manifest(manifests, "Service", db_name)
# without a legacy PVC no migration resources are rendered
assert not any(
m
for m in manifests
if "volume-migration" in m.get("metadata", {}).get("name", "")
)
# nfs (shared) volumes are never per-replica: the statefulset keeps mounting the common
# PVC by claimName and no volumeClaimTemplates are created.
harness["deployment"]["volume"]["usenfs"] = True
with open(values_path, "w") as values_file:
yaml.dump(values, values_file)
manifests = render_helm_chart(helm_path)
sts = find_manifest(manifests, "StatefulSet", dep_name)
assert "volumeClaimTemplates" not in sts["spec"]
claims = [
v["persistentVolumeClaim"]["claimName"]
for v in sts["spec"]["template"]["spec"]["volumes"]
if "persistentVolumeClaim" in v
]
assert "myapp-data" in claims
shared_pvc = find_manifest(manifests, "PersistentVolumeClaim", "myapp-data")
assert shared_pvc["spec"]["accessModes"] == ["ReadWriteMany"]
# volume.auto: false means the PVC is managed externally: always reference it by
# claimName, never via volumeClaimTemplates.
harness["deployment"]["volume"]["usenfs"] = False
harness["deployment"]["volume"]["auto"] = False
with open(values_path, "w") as values_file:
yaml.dump(values, values_file)
manifests = render_helm_chart(helm_path)
sts = find_manifest(manifests, "StatefulSet", dep_name)
assert "volumeClaimTemplates" not in sts["spec"]
claims = [
v["persistentVolumeClaim"]["claimName"]
for v in sts["spec"]["template"]["spec"]["volumes"]
if "persistentVolumeClaim" in v
]
assert "myapp-data" in claims
def test_volume_write_many(tmp_path):
out_folder = tmp_path / "test_volume_write_many"
# nfsserver is deliberately not included: a ReadWriteMany volume must not rely on it
create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
env="withpostgres",
local=False,
include=["myapp"],
exclude=["legacy"],
)
helm_path = out_folder / "helm"
shutil.rmtree(helm_path / "charts")
values_path = helm_path / "values.yaml"
with open(values_path, "r") as values_file:
values = yaml.load(values_file)
harness = values["apps"]["myapp"]["harness"]
dep_name = harness["deployment"]["name"]
harness["deployment"]["auto"] = True
volume = {"name": "myapp-data", "mountpath": "/data", "size": "1Gi", "auto": True}
harness["deployment"]["volume"] = volume
def render():
with open(values_path, "w") as values_file:
yaml.dump(values, values_file)
return render_helm_chart(helm_path)
# a null storage class is omitted, so the cluster default one is used
volume["storageClass"] = None
manifests = render()
pvc = find_manifest(manifests, "PersistentVolumeClaim", "myapp-data")
assert "storageClassName" not in pvc["spec"]
# a storage class can be set on a ReadWriteOnce volume, which keeps the node pinning
volume["storageClass"] = "gp3"
manifests = render()
pvc = find_manifest(manifests, "PersistentVolumeClaim", "myapp-data")
assert pvc["spec"]["accessModes"] == ["ReadWriteOnce"]
assert pvc["spec"]["storageClassName"] == "gp3"
dep = find_manifest(manifests, "Deployment", dep_name)
assert dep["spec"]["strategy"]["type"] == "Recreate"
assert "affinity" in dep["spec"]["template"]["spec"]
# a writeMany volume keeps its storage class, and its pod is neither pinned to a node nor
# recreated on update
volume["writeMany"] = True
manifests = render()
pvc = find_manifest(manifests, "PersistentVolumeClaim", "myapp-data")
assert pvc["spec"]["accessModes"] == ["ReadWriteMany"]
assert pvc["spec"]["storageClassName"] == "gp3"
dep = find_manifest(manifests, "Deployment", dep_name)
assert "strategy" not in dep["spec"]
assert "affinity" not in dep["spec"]["template"]["spec"]
# writeMany with an explicit ReadWriteMany capable storage class
volume["storageClass"] = "efs-sc"
manifests = render()
pvc = find_manifest(manifests, "PersistentVolumeClaim", "myapp-data")
assert pvc["spec"]["accessModes"] == ["ReadWriteMany"]
assert pvc["spec"]["storageClassName"] == "efs-sc"
# a null storage class is omitted from a ReadWriteMany claim too
volume["storageClass"] = None
manifests = render()
pvc = find_manifest(manifests, "PersistentVolumeClaim", "myapp-data")
assert "storageClassName" not in pvc["spec"]
volume["storageClass"] = "efs-sc"
manifests = render()
assert (
find_manifest(manifests, "PersistentVolumeClaim", "myapp-data")["spec"][
"storageClassName"
] ==
"efs-sc"
)
# ReadWriteMany volumes are shared: a statefulset keeps mounting the common PVC by
# claimName instead of provisioning one per replica
harness["deployment"]["statefulset"] = True
manifests = render()
sts = find_manifest(manifests, "StatefulSet", dep_name)
assert "volumeClaimTemplates" not in sts["spec"]
claims = [
v["persistentVolumeClaim"]["claimName"]
for v in sts["spec"]["template"]["spec"]["volumes"]
if "persistentVolumeClaim" in v
]
assert "myapp-data" in claims
pvc = find_manifest(manifests, "PersistentVolumeClaim", "myapp-data")
assert pvc["spec"]["accessModes"] == ["ReadWriteMany"]
# the storage class of a per-replica statefulset volume is configurable too
volume["writeMany"] = False
volume["storageClass"] = "gp3"
manifests = render()
sts = find_manifest(manifests, "StatefulSet", dep_name)
claim_template = sts["spec"]["volumeClaimTemplates"][0]
assert claim_template["metadata"]["name"] == "myapp-data"
assert claim_template["spec"]["accessModes"] == ["ReadWriteOnce"]
assert claim_template["spec"]["storageClassName"] == "gp3"
def test_volume_storage_class_default(tmp_path):
out_folder = tmp_path / "test_volume_storage_class_default"
# samples declares a volume, myapp does not
values = create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
env="withpostgres",
local=False,
include=["samples", "myapp"],
exclude=["legacy"],
)
# the value-template default applies to the volume declared by the application
volume = values[KEY_APPS]["samples"][KEY_HARNESS]["deployment"]["volume"]
assert volume["mountpath"]
assert volume["storageClass"] == "standard"
# ... and the defaults alone do not make a volume: a volume-less application has none
assert not values[KEY_APPS]["myapp"][KEY_HARNESS]["deployment"].get("volume")
helm_path = out_folder / "helm"
shutil.rmtree(helm_path / "charts")
manifests = render_helm_chart(helm_path)
sts = find_manifest(
manifests,
"StatefulSet",
values[KEY_APPS]["samples"][KEY_HARNESS]["deployment"]["name"],
)
assert (
sts["spec"]["volumeClaimTemplates"][0]["spec"]["storageClassName"] == "standard"
)
def test_volume_usenfs_prevails(tmp_path):
out_folder = tmp_path / "test_volume_usenfs_prevails"
create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
env="withpostgres",
local=False,
include=["myapp", "nfsserver"],
exclude=["legacy"],
)
helm_path = out_folder / "helm"
shutil.rmtree(helm_path / "charts")
values_path = helm_path / "values.yaml"
with open(values_path, "r") as values_file:
values = yaml.load(values_file)
harness = values["apps"]["myapp"]["harness"]
harness["deployment"]["auto"] = True
# colliding settings: the nfs server storage class and access mode prevail
harness["deployment"]["volume"] = {
"name": "myapp-data",
"mountpath": "/data",
"size": "1Gi",
"auto": True,
"usenfs": True,
"writeMany": False,
"storageClass": "efs-sc",
}
with open(values_path, "w") as values_file:
yaml.dump(values, values_file)
manifests = render_helm_chart(helm_path)
pvc = find_manifest(manifests, "PersistentVolumeClaim", "myapp-data")
nfs_class = (
f"{values['namespace']}-{values['apps']['nfsserver']['storageClass']['name']}"
)
assert pvc["spec"]["storageClassName"] == nfs_class
assert pvc["spec"]["accessModes"] == ["ReadWriteMany"]
dep = find_manifest(manifests, "Deployment", harness["deployment"]["name"])
assert "affinity" not in dep["spec"]["template"]["spec"]
def test_database_storage_class(tmp_path):
out_folder = tmp_path / "test_database_storage_class"
create_helm_chart(
[CLOUDHARNESS_ROOT, RESOURCES],
output_path=out_folder,
domain="my.local",
env="withpostgres",
local=False,
include=["myapp"],
exclude=["legacy"],
)
helm_path = out_folder / "helm"
shutil.rmtree(helm_path / "charts")
values_path = helm_path / "values.yaml"
with open(values_path, "r") as values_file:
values = yaml.load(values_file)
database = values["apps"]["myapp"]["harness"]["database"]
db_name = database["name"]
def render():