-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_helm.py
More file actions
1430 lines (1147 loc) · 66.8 KB
/
Copy pathtest_helm.py
File metadata and controls
1430 lines (1147 loc) · 66.8 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
from ch_cli_tools.helm import *
from ch_cli_tools.configurationgenerator import *
from ch_cli_tools import configurationgenerator
from ch_cli_tools.preprocessing import preprocess_build_overrides, generate_hash_based_image_tags
import logging
import pytest
import shutil
import subprocess
import pytest
from ch_cli_tools import configurationgenerator
from ch_cli_tools.configurationgenerator import *
from ch_cli_tools.helm import *
from ch_cli_tools.preprocessing import (
generate_hash_based_image_tags,
preprocess_build_overrides,
)
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):
completed = subprocess.run(
["helm", "template", str(chart_path)],
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]
# Auto values
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
# Check files
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')
# Checl base and task images
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'
# Not indicated as a build dependency
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) # Check if the values.yaml is valid YAML
assert chart_values is not None, "values.yaml should be valid YAML"
assert chart_values["test"] == "dev"
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)
# Auto values
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
# Check files
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'
# Check source images
# KEYCLOAK is overriden and mybase and mybase2 should appear as they have been collected
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",
}
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(tmp_path):
"""value-template-[env].yaml overrides value-template.yaml application defaults"""
conf_path = tmp_path / DEPLOYMENT_CONFIGURATION_PATH
conf_path.mkdir(parents=True)
(conf_path / 'value-template.yaml').write_text('base: 1\nenv-defaults: base\n')
(conf_path / 'value-template-dev.yaml').write_text('env-defaults: dev\n')
assert collect_app_defaults(tmp_path, env=('dev',)) == {
'base': 1, 'env-defaults': 'dev'}
assert collect_app_defaults(tmp_path, env=('other',)) == {
'base': 1, 'env-defaults': 'base'}, 'value-template-dev.yaml loaded for the wrong environment'
assert collect_app_defaults(tmp_path) == {
'base': 1, 'env-defaults': 'base'}, 'value-template-dev.yaml loaded without environment'
def test_init_app_values_env_specific_defaults(tmp_path, monkeypatch):
"""Cloudharness application defaults, including the environment specific ones,
apply to the applications of any root, and are overridden by the current root"""
ch_root = tmp_path / 'cloudharness'
(ch_root / DEPLOYMENT_CONFIGURATION_PATH).mkdir(parents=True)
(ch_root / DEPLOYMENT_CONFIGURATION_PATH /
'value-template.yaml').write_text('ch-defaults: base\nenv-defaults: ch-base\n')
(ch_root / DEPLOYMENT_CONFIGURATION_PATH /
'value-template-dev.yaml').write_text('ch-env-defaults: ch-dev\nenv-defaults: ch-dev\n')
deployment_root = tmp_path / 'deployment'
(deployment_root / APPS_PATH / 'myapp').mkdir(parents=True)
(deployment_root / DEPLOYMENT_CONFIGURATION_PATH).mkdir(parents=True)
(deployment_root / DEPLOYMENT_CONFIGURATION_PATH /
'value-template-dev.yaml').write_text('env-defaults: root-dev\n')
monkeypatch.setattr(configurationgenerator, 'CH_ROOT', str(ch_root))
values = init_app_values(deployment_root, exclude=(), env=('dev',))
assert values['myapp']['ch-defaults'] == 'base'
assert values['myapp']['ch-env-defaults'] == 'ch-dev', 'cloudharness value-template-dev.yaml not applied'
assert values['myapp']['env-defaults'] == 'root-dev', 'current root must take precedence'
values = init_app_values(deployment_root, exclude=(), env=())
assert 'ch-env-defaults' not in values['myapp']
assert values['myapp']['env-defaults'] == 'ch-base'
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']
def test_collect_helm_values_wrong_dependencies_validate(tmp_path):
out_folder = tmp_path / 'test_collect_helm_values_wrong_dependencies_validate'
with pytest.raises(ValuesValidationException):
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 ValuesValidationException as e:
pytest.fail("Should not error because of wrong soft dependency")
with pytest.raises(ValuesValidationException):
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 ValuesValidationException:
pytest.fail("Should not error because of missing use_services dependency")
def test_validate_dependencies_accepts_app_local_build_images():
values = {
KEY_APPS: {
'portal': {
KEY_HARNESS: {
'dependencies': {
'soft': [],
'hard': [],
'build': ['cloudharness-base', 'cloudharness-django'],
},
'use_services': [],
},
KEY_TASK_IMAGES: {
'cloudharness-base': 'reg/project/cloudharness-base:1',
'cloudharness-django': 'reg/project/cloudharness-django:1',
},
}
},
KEY_TASK_IMAGES: {},
}
validate_dependencies(values)
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:')
# However, it seems that even after removing unused entries,
# the finale instance of the HarnessMainConfig class that is created
# adds back those entries and set them to None.
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",
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_CHART_PATH
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_CHART_PATH
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_CHART_PATH
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_CHART_PATH
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_without_mountpath_is_rejected():
harness = {'name': 'myapp', KEY_DEPLOYMENT: {'volume': {'name': 'myapp-data', 'size': '1Gi'}}}
with pytest.raises(ValuesValidationException):
clear_unused_volume_configuration(harness)
# the defaults alone are dropped, a declared volume is kept
harness = {'name': 'myapp', KEY_DEPLOYMENT: {'volume': {'storageClass': 'standard'}}}
clear_unused_volume_configuration(harness)
assert 'volume' not in harness[KEY_DEPLOYMENT]
volume = {'name': 'myapp-data', 'mountpath': '/data', 'storageClass': 'standard'}
harness = {'name': 'myapp', KEY_DEPLOYMENT: {'volume': volume}}
clear_unused_volume_configuration(harness)
assert harness[KEY_DEPLOYMENT]['volume'] == volume
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_CHART_PATH
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_validate_volumes_warns_on_nfs_collisions(caplog):
volume = {'name': 'myapp-data', 'usenfs': True, 'writeMany': False, 'storageClass': 'efs-sc'}
values = {'apps': {'myapp': {KEY_HARNESS: {'deployment': {'volume': volume}}}}}
with caplog.at_level(logging.WARNING):
validate_volumes(values)
assert 'the nfs server storage class prevails' in caplog.text
assert 'always mounted ReadWriteMany' in caplog.text
# no collision: nothing to warn about
caplog.clear()
with caplog.at_level(logging.WARNING):
validate_volumes({'apps': {'myapp': {KEY_HARNESS: {'deployment': {'volume': {
'name': 'myapp-data', 'usenfs': True, 'writeMany': True}}}}}})
validate_volumes({'apps': {'myapp': {KEY_HARNESS: {'deployment': {'volume': {
'name': 'myapp-data', 'storageClass': 'efs-sc', 'writeMany': True}}}}}})
validate_volumes({'apps': {'myapp': {KEY_HARNESS: {'deployment': {}}}}})
assert not caplog.text
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_CHART_PATH
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():
with open(values_path, 'w') as values_file:
yaml.dump(values, values_file)
return render_helm_chart(helm_path)
# not set by default: the claim carries no storage class, so the cluster default one is used.
# The storage class is immutable on an existing claim, hence never set implicitly: database
# volumes of existing deployments must keep rendering without it.
assert database['storageClass'] is None
manifests = render()
assert 'storageClassName' not in find_manifest(manifests, 'PersistentVolumeClaim', db_name)['spec']
database['storageClass'] = 'gp3'
manifests = render()
assert find_manifest(manifests, 'PersistentVolumeClaim', db_name)['spec']['storageClassName'] == 'gp3'
# statefulset databases provision their volume through volumeClaimTemplates
database['statefulset'] = True
manifests = render()
sts = find_manifest(manifests, 'StatefulSet', db_name)
assert sts['spec']['volumeClaimTemplates'][0]['spec']['storageClassName'] == 'gp3'
database['storageClass'] = None
manifests = render()
sts = find_manifest(manifests, 'StatefulSet', db_name)
assert 'storageClassName' not in sts['spec']['volumeClaimTemplates'][0]['spec']
# the postgres operator cluster storage honours the same setting
database['statefulset'] = False
database['postgres']['operator'] = True
database['storageClass'] = 'gp3'
manifests = render()
assert find_manifest(manifests, 'Cluster', db_name)['spec']['storage']['storageClass'] == 'gp3'
database['storageClass'] = None
manifests = render()
assert 'storageClass' not in find_manifest(manifests, 'Cluster', db_name)['spec']['storage']
def test_statefulset_leader_service(tmp_path):
out_folder = tmp_path / 'test_statefulset_leader_service'
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_CHART_PATH
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']
service_name = harness['service']['name']
rw_name = f"{service_name}-rw"
def ingress_paths(manifests):
ingress = find_manifest(manifests, 'Ingress', 'myapp')
return [path for rule in ingress['spec']['rules'] for path in rule['http']['paths']]
# write methods in uri_role_mapping without statefulset: no leader service, no leader routing
harness['uri_role_mapping'] = harness.get('uri_role_mapping', []) + [
{'uri': '/api/edit/*', 'methods': ['POST', 'PUT', 'PATCH']},
{'uri': '/upload', 'methods': ['POST']},
{'uri': '/api/remove', 'methods': ['DELETE']},
{'uri': '/readonly', 'methods': ['GET']},
]
with open(values_path, 'w') as values_file:
yaml.dump(values, values_file)
manifests = render_helm_chart(helm_path)
assert not any(m for m in manifests
if m.get('kind') == 'Service' and m.get('metadata', {}).get('name') == rw_name)
assert not any(p for p in ingress_paths(manifests)
if p['backend']['service']['name'] == rw_name)
harness['deployment']['statefulset'] = True
with open(values_path, 'w') as values_file:
yaml.dump(values, values_file)
manifests = render_helm_chart(helm_path)
rw_service = find_manifest(manifests, 'Service', rw_name)
assert rw_service['spec']['selector']['app'] == dep_name
assert rw_service['spec']['selector']['statefulset.kubernetes.io/pod-name'] == f"{dep_name}-0"
main_service = find_manifest(manifests, 'Service', service_name)
assert rw_service['spec']['ports'] == main_service['spec']['ports']
paths = ingress_paths(manifests)
rw_paths = {p['path']: p for p in paths if p['backend']['service']['name'] == rw_name}
# wildcard uris map to Prefix rules, plain uris to ImplementationSpecific; any write method
# (POST/PUT/PATCH/DELETE) triggers leader routing, while entries without one (the default
# catch-all, /readonly) are not routed to the leader
assert set(rw_paths) == {'/api/edit', '/upload', '/api/remove'}
assert rw_paths['/api/edit']['pathType'] == 'Prefix'
assert rw_paths['/upload']['pathType'] == 'ImplementationSpecific'
# the catch-all still routes to the normal service
assert any(p for p in paths
if p['path'] == '/' and p['backend']['service']['name'] == service_name)
def test_gatekeeper_native_configuration_rendering_and_checksum(tmp_path):
out_folder = tmp_path / 'test_gatekeeper_native_configuration'
create_helm_chart([CLOUDHARNESS_ROOT, RESOURCES], output_path=out_folder, domain="my.local",
local=False, tls=True, include=["myapp", "accounts"], exclude=["legacy"])
helm_path = out_folder / HELM_CHART_PATH
shutil.rmtree(helm_path / 'charts')
values_path = helm_path / 'values.yaml'
with open(values_path, 'r') as values_file:
values = yaml.load(values_file)
app_harness = values['apps']['myapp']['harness']
app_harness['secured'] = True
app_harness['proxy']['gatekeeper']['configuration'] = {
'same-site-cookie': 'None',
'enable-pkce': False,
'http-only-cookie': True,
'cors-exposed-headers': ['X-Request-ID', 'X-Trace-ID'],
}
values['proxy']['gatekeeper']['configuration'] = {
'same-site-cookie': 'Strict',
'enable-pkce': True,
'max-token-size': 65536,
}
def render_gatekeeper():
with open(values_path, 'w') as values_file:
yaml.dump(values, values_file)
manifests = render_helm_chart(helm_path)
config = find_manifest(manifests, 'ConfigMap', 'mysubdomain-gk')
deployment = find_manifest(manifests, 'Deployment', 'mysubdomain-gk')
return (
yaml.load(config['data']['proxy.yml']),
deployment['spec']['template']['metadata']['annotations']['checksum/config'],
)
tls_config, tls_checksum = render_gatekeeper()
assert tls_config['secure-cookie'] is True
assert tls_config['same-site-cookie'] == 'None'
assert tls_config['enable-pkce'] is False
assert tls_config['http-only-cookie'] is True
assert tls_config['max-token-size'] == 65536
assert tls_config['cors-exposed-headers'] == ['X-Request-ID', 'X-Trace-ID']
values['tls'] = False
non_tls_config, non_tls_checksum = render_gatekeeper()
assert non_tls_config['secure-cookie'] is False
assert non_tls_config['same-site-cookie'] == 'Lax'
assert non_tls_config['enable-pkce'] is False
assert non_tls_config['max-token-size'] == 65536
assert non_tls_checksum != tls_checksum
values['tls'] = True
app_harness['proxy']['gatekeeper']['configuration'].pop('same-site-cookie')
inherited_config, inherited_checksum = render_gatekeeper()
assert inherited_config['same-site-cookie'] == 'Strict'
assert inherited_config['enable-pkce'] is False
assert inherited_checksum != tls_checksum
def test_clear_all_dbconfig_if_nodb(tmp_path):
out_folder = tmp_path / 'test_clear_all_dbconfig_if_nodb'
values = create_helm_chart([CLOUDHARNESS_ROOT, RESOURCES], output_path=out_folder, domain="my.local",
env='withoutdb', local=False, include=["myapp"], exclude=["legacy"])
# There is a DB config
assert KEY_DATABASE in values[KEY_APPS]['myapp'][KEY_HARNESS]
# But it is None
db_config = values[KEY_APPS]['myapp'][KEY_HARNESS][KEY_DATABASE]
assert db_config is None
def test_tag_hash_generation():
v1 = generate_tag_from_content(RESOURCES)
v2 = generate_tag_from_content(RESOURCES, ignore=['myapp'])
assert v1 != v2
v3 = generate_tag_from_content(RESOURCES, ignore=['*/myapp/*'])
assert v3 != v1
v4 = generate_tag_from_content(RESOURCES, ignore=['applications/myapp/*'])
assert v4 == v3
v5 = generate_tag_from_content(RESOURCES, ignore=['/applications/myapp/*'])
assert v5 == v4
fname = Path(RESOURCES) / 'applications' / 'myapp' / 'afile.txt'
try:
fname.write_text('a')
v6 = generate_tag_from_content(RESOURCES, ignore=['/applications/myapp/*'])
assert v6 == v5
v7 = generate_tag_from_content(RESOURCES)
assert v7 != v1
finally:
fname.unlink()
def test_collect_helm_values_auto_tag(tmp_path):
out_folder = str(tmp_path / 'test_collect_helm_values_auto_tag')
merge_build_path = str(tmp_path / '.overrides')
first_pass = 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=None, registry='reg')
assert first_pass[KEY_APPS]['myapp'][KEY_HARNESS]['deployment']['image'] == 'reg/testprojectname/myapp'
def create():
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=None, registry='reg')
preprocess_build_overrides([CLOUDHARNESS_ROOT, RESOURCES], values, merge_build_path=merge_build_path)
generate_hash_based_image_tags([CLOUDHARNESS_ROOT, RESOURCES], values, merge_build_path=merge_build_path)
return values
BASE_KEY = "cloudharness-base"
values = create()
# Auto values are set by using the directory hash
assert 'reg/testprojectname/myapp:' in values[KEY_APPS]['myapp'][KEY_HARNESS]['deployment']['image']
assert 'reg/testprojectname/myapp:' in values.apps['myapp'].harness.deployment.image
assert 'testprojectname/myapp-mytask' in values[KEY_TASK_IMAGES]['myapp-mytask']
assert values[KEY_APPS]['myapp'][KEY_HARNESS]['deployment']['image'] == values.apps['myapp'].harness.deployment.image
v1 = values.apps['myapp'].harness.deployment.image
c1 = values["task-images"]["my-common"]
b1 = values["task-images"][BASE_KEY]
d1 = values["task-images"]["cloudharness-flask"]
values = create()
assert v1 == values.apps['myapp'].harness.deployment.image, "Nothing changed the hash value"
assert values["task-images"][BASE_KEY] == b1, "Base image should not change following the root .dockerignore"
fname = Path(RESOURCES) / 'applications' / 'myapp' / 'afile.txt'
try:
fname.write_text('a')
values = create()
assert v1 != values.apps['myapp'].harness.deployment.image, "Adding the file changed the hash value"
v2 = values.apps['myapp'].harness.deployment.image
assert values["task-images"][BASE_KEY] == b1, "Application files should be ignored for base image following the root .dockerignore"
finally:
fname.unlink()
try:
fname.write_text('a')
values = create()
assert v2 == values.apps['myapp'].harness.deployment.image, "Recreated an identical file, the hash value should be the same"
finally:
fname.unlink()
fname = Path(RESOURCES) / 'applications' / 'myapp' / 'afile.ignored'
try:
fname.write_text('a')
values = create()
assert values["task-images"][BASE_KEY] == b1, "2: Application files should be ignored for base image following the root .dockerignore"
assert v1 == values.apps['myapp'].harness.deployment.image, "Nothing should change the hash value as the file is ignored in the .dockerignore"