forked from aws/aws-sam-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_build_cmd.py
More file actions
2164 lines (1828 loc) · 85.7 KB
/
test_build_cmd.py
File metadata and controls
2164 lines (1828 loc) · 85.7 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 logging
import os
import random
import shutil
import sys
from pathlib import Path
from typing import Set
from unittest import skipIf
from uuid import uuid4
import jmespath
import pytest
from parameterized import parameterized, parameterized_class
from samcli.lib.utils import osutils
from samcli.local.docker.utils import get_validated_container_client
from samcli.local.docker.image_build_client import CLIBuildClient
from samcli.local.docker.container_client_factory import ContainerClientFactory
from samcli.yamlhelper import yaml_parse
from tests.testing_utils import (
IS_WINDOWS,
RUNNING_ON_CI,
RUNNING_TEST_FOR_MASTER_ON_CI,
RUN_BY_CANARY,
CI_OVERRIDE,
run_command,
SKIP_DOCKER_TESTS,
SKIP_DOCKER_BUILD,
SKIP_DOCKER_MESSAGE,
UpdatableSARTemplate,
)
from tests.integration.buildcmd.build_integ_base import (
BuildIntegBase,
DedupBuildIntegBase,
CachedBuildIntegBase,
BuildIntegRubyBase,
NestedBuildIntegBase,
IntrinsicIntegBase,
BuildIntegGoBase,
BuildIntegPythonBase,
show_container_in_test_name,
)
LOG = logging.getLogger(__name__)
# SAR tests require credentials. This is to skip running the test where credentials are not available.
SKIP_SAR_TESTS = RUNNING_ON_CI and RUNNING_TEST_FOR_MASTER_ON_CI and not RUN_BY_CANARY
@skipIf(SKIP_DOCKER_TESTS, SKIP_DOCKER_MESSAGE)
@parameterized_class(
("use_buildkit",),
[
(False,),
(True,),
],
)
@pytest.mark.filterwarnings("ignore::ResourceWarning")
class TestBuildingImageTypeLambdaDockerFileFailuresContainer(BuildIntegBase):
template = "template_image.yaml"
def setUp(self):
super().setUp()
if self.use_buildkit:
client = ContainerClientFactory.create_client()
is_available, error_msg = CLIBuildClient.is_available(client.get_runtime_type())
if not is_available:
self.skipTest(f"Buildkit not available: {error_msg}")
def test_with_invalid_dockerfile_location(self):
overrides = {
"Runtime": "3.10",
"Handler": "handler",
"DockerFile": "ThisDockerfileDoesNotExist",
"Tag": uuid4().hex,
}
cmdlist = self.get_command_list(parameter_overrides=overrides, use_buildkit=self.use_buildkit)
command_result = run_command(cmdlist, cwd=self.working_dir)
# confirm build failed
self.assertEqual(command_result.process.returncode, 1)
# Check for Dockerfile not found error messages from both Docker and Finch
docker_client = get_validated_container_client()
stderr_output = command_result.stderr.decode()
error_found = docker_client.is_dockerfile_error(stderr_output)
self.assertTrue(
error_found, f"Expected Dockerfile not found error message not found in stderr: {stderr_output}"
)
def test_with_invalid_dockerfile_definition(self):
overrides = {
"Runtime": "3.10",
"Handler": "handler",
"DockerFile": "InvalidDockerfile",
"Tag": uuid4().hex,
}
cmdlist = self.get_command_list(parameter_overrides=overrides, use_buildkit=self.use_buildkit)
command_result = run_command(cmdlist, cwd=self.working_dir)
# confirm build failed
self.assertEqual(command_result.process.returncode, 1)
self.assertIn("COPY requires at least two arguments", command_result.stderr.decode())
@skipIf(SKIP_DOCKER_TESTS, SKIP_DOCKER_MESSAGE)
@parameterized_class(
("use_buildkit",),
[
(False,),
(True,),
],
)
@pytest.mark.filterwarnings("ignore::ResourceWarning")
class TestLoadingImagesFromArchiveContainer(BuildIntegBase):
template = "template_loadable_image.yaml"
FUNCTION_LOGICAL_ID = "ImageFunction"
def setUp(self):
super().setUp()
if self.use_buildkit:
client = ContainerClientFactory.create_client()
is_available, error_msg = CLIBuildClient.is_available(client.get_runtime_type())
if not is_available:
self.skipTest(f"Buildkit not available: {error_msg}")
def test_load_not_an_archive_passthrough(self):
overrides = {"ImageUri": "./load_image_archive/this_file_does_not_exist.tar.gz"}
cmdlist = self.get_command_list(parameter_overrides=overrides, use_buildkit=self.use_buildkit)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
def test_bad_image_archive_fails(self):
overrides = {"ImageUri": "./load_image_archive/error.tar.gz"}
cmdlist = self.get_command_list(parameter_overrides=overrides, use_buildkit=self.use_buildkit)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 1)
self.assertIn("unexpected EOF", command_result.stderr.decode())
def test_load_success(self):
overrides = {"ImageUri": "./load_image_archive/archive.tar.gz"}
cmdlist = self.get_command_list(parameter_overrides=overrides, use_buildkit=self.use_buildkit)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
try:
self._verify_image_build_artifact(
self.built_template,
self.FUNCTION_LOGICAL_ID,
"ImageUri",
"sha256:66c45ad212dbddc4d5ebaa90d8ec30d5b209fb7a8afa3b41cb8399c55636d429",
)
except:
self._verify_image_build_artifact(
self.built_template,
self.FUNCTION_LOGICAL_ID,
"ImageUri",
"sha256:d6f0f7f932957887670574d2d484c9f0cedb6a5b03c497df041e1304e756a0b3",
)
@skipIf(
# Hits public ECR pull limitation, move it to canary tests
(not RUN_BY_CANARY and not CI_OVERRIDE),
"Skip build tests on windows when running in CI unless overridden",
)
@skipIf(
# Hits public ECR pull limitation, move it to canary tests
((not RUN_BY_CANARY) or (IS_WINDOWS and RUNNING_ON_CI) and not CI_OVERRIDE),
"Skip build tests on windows when running in CI unless overridden",
)
@parameterized_class(
("template", "prop", "use_buildkit"),
[
("template_local_prebuilt_image.yaml", "ImageUri", False),
("template_cfn_local_prebuilt_image.yaml", "Code.ImageUri", False),
("template_local_prebuilt_image.yaml", "ImageUri", True),
("template_cfn_local_prebuilt_image.yaml", "Code.ImageUri", True),
],
)
@pytest.mark.filterwarnings("ignore::ResourceWarning")
class TestSkipBuildingFunctionsWithLocalImageUriContainer(BuildIntegBase):
EXPECTED_FILES_PROJECT_MANIFEST: Set[str] = set()
FUNCTION_LOGICAL_ID_IMAGE = "ImageFunction"
def setUp(self):
super().setUp()
if self.use_buildkit:
client = ContainerClientFactory.create_client()
is_available, error_msg = CLIBuildClient.is_available(client.get_runtime_type())
if not is_available:
self.skipTest(f"Buildkit not available: {error_msg}")
@parameterized.expand(["3.8", "3.9", "3.10", "3.11", "3.12", "3.13", "3.14"])
def test_with_default_requirements(self, runtime):
_tag = uuid4().hex
image_uri = f"func:{_tag}"
docker_client = get_validated_container_client()
docker_client.images.build(
path=str(Path(self.test_data_path, "PythonImage")),
dockerfile="Dockerfile",
buildargs={"BASE_RUNTIME": runtime},
tag=image_uri,
)
overrides = {
"ImageUri": image_uri,
"Handler": "main.handler",
}
cmdlist = self.get_command_list(parameter_overrides=overrides, use_buildkit=self.use_buildkit)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
self._verify_image_build_artifact(
self.built_template,
self.FUNCTION_LOGICAL_ID_IMAGE,
self.prop,
{"Ref": "ImageUri"},
)
expected = {"pi": "3.14"}
self._verify_invoke_built_function(
self.built_template, self.FUNCTION_LOGICAL_ID_IMAGE, self._make_parameter_override_arg(overrides), expected
)
@skipIf(
# Hits public ECR pull limitation, move it to canary tests
((not RUN_BY_CANARY) or (IS_WINDOWS and RUNNING_ON_CI) and not CI_OVERRIDE),
"Skip build tests on windows when running in CI unless overridden",
)
@parameterized_class(
("template", "SKIPPED_FUNCTION_LOGICAL_ID", "src_code_path", "src_code_prop", "metadata_key"),
[
("template_function_flagged_to_skip_build.yaml", "SkippedFunction", "PreBuiltPython", "CodeUri", None),
("template_cfn_function_flagged_to_skip_build.yaml", "SkippedFunction", "PreBuiltPython", "Code", None),
(
"cdk_v1_synthesized_template_python_function_construct.json",
"SkippedFunctionDA0220D7",
"asset.7023fd47c81480184154c6e0e870d6920c50e35d8fae977873016832e127ded9",
None,
"aws:asset:path",
),
(
"cdk_v1_synthesized_template_function_construct_with_skip_build_metadata.json",
"SkippedFunctionDA0220D7",
"asset.7023fd47c81480184154c6e0e870d6920c50e35d8fae977873016832e127ded9",
None,
"aws:asset:path",
),
(
"cdk_v2_synthesized_template_python_function_construct.json",
"SkippedFunctionDA0220D7",
"asset.7023fd47c81480184154c6e0e870d6920c50e35d8fae977873016832e127ded9",
None,
"aws:asset:path",
),
(
"cdk_v2_synthesized_template_function_construct_with_skip_build_metadata.json",
"RandomSpaceFunction4F8564D0",
"asset.7023fd47c81480184154c6e0e870d6920c50e35d8fae977873016832e127ded9",
None,
"aws:asset:path",
),
],
)
class TestSkipBuildingFlaggedFunctionsContainer(BuildIntegPythonBase):
template = "template_cfn_function_flagged_to_skip_build.yaml"
SKIPPED_FUNCTION_LOGICAL_ID = "SkippedFunction"
src_code_path = "PreBuiltPython"
src_code_prop = "Code"
metadata_key = None
def test_with_default_requirements(self):
self._validate_skipped_built_function(
self.default_build_dir,
self.SKIPPED_FUNCTION_LOGICAL_ID,
self.test_data_path,
self.src_code_path,
self.src_code_prop,
self.metadata_key,
)
def _validate_skipped_built_function(
self, build_dir, skipped_function_logical_id, relative_path, src_code_path, src_code_prop, metadata_key
):
cmdlist = self.get_command_list()
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
self.assertTrue(build_dir.exists(), "Build directory should be created")
build_dir_files = os.listdir(str(build_dir))
self.assertNotIn(skipped_function_logical_id, build_dir_files)
expected_value = os.path.relpath(
os.path.normpath(os.path.join(str(relative_path), src_code_path)),
str(self.default_build_dir),
)
with open(self.built_template, "r") as fp:
template_dict = yaml_parse(fp.read())
if src_code_prop:
self.assertEqual(
expected_value,
jmespath.search(
f"Resources.{skipped_function_logical_id}.Properties.{src_code_prop}", template_dict
),
)
if metadata_key:
metadata = jmespath.search(f"Resources.{skipped_function_logical_id}.Metadata", template_dict)
metadata = metadata if metadata else {}
self.assertEqual(expected_value, metadata.get(metadata_key, ""))
expected = "Hello World"
if not SKIP_DOCKER_TESTS:
self._verify_invoke_built_function(
self.built_template, skipped_function_logical_id, self._make_parameter_override_arg({}), expected
)
@pytest.mark.ruby
class TestBuildCommand_RubyFunctions(BuildIntegRubyBase):
@parameterized.expand([(False,), ("use_container",)], name_func=show_container_in_test_name)
@pytest.mark.tier1
def test_building_ruby_3_2(self, use_container):
if use_container and SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD:
self.skipTest(SKIP_DOCKER_MESSAGE)
self._test_with_default_gemfile("ruby3.2", use_container, "Ruby", self.test_data_path)
@parameterized.expand([("ruby3.3",), ("ruby3.4",)])
@skipIf(SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD, SKIP_DOCKER_MESSAGE)
@pytest.mark.al2023
def test_building_ruby_al2023_in_container(self, runtime):
self._test_with_default_gemfile(runtime, "use_container", "Ruby", self.test_data_path)
class TestBuildCommand_RubyFunctions_With_Architecture(BuildIntegRubyBase):
template = "template_with_architecture.yaml"
@parameterized.expand([(False,), ("use_container",)], name_func=show_container_in_test_name)
def test_building_ruby_3_2(self, use_container):
if use_container and SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD:
self.skipTest(SKIP_DOCKER_MESSAGE)
self._test_with_default_gemfile("ruby3.2", use_container, "Ruby32", self.test_data_path, "x86_64")
@parameterized.expand(
[
("ruby3.3", "Ruby33", False),
("ruby3.3", "Ruby33", "use_container"),
# ("ruby3.4", "Ruby34", False), # TODO: Try to make this work in AppVeyor (windows-al2023)
("ruby3.4", "Ruby34", "use_container"),
],
name_func=show_container_in_test_name,
)
@skipIf(SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD, SKIP_DOCKER_MESSAGE)
@pytest.mark.al2023
def test_building_ruby_al2023(self, runtime, codeuri, use_container):
self._test_with_default_gemfile(runtime, use_container, codeuri, self.test_data_path, "x86_64")
class TestBuildCommand_RubyFunctionsWithGemfileInTheRoot(BuildIntegRubyBase):
"""
Tests use case where Gemfile will present in the root of the project folder.
This doesn't apply to containerized build, since it copies only the function folder to the container
"""
@parameterized.expand([("ruby3.2",), ("ruby3.3",), ("ruby3.4",)])
def test_building_ruby_in_process_with_root_gemfile(self, runtime):
self._prepare_application_environment(runtime)
self._test_with_default_gemfile(runtime, False, "RubyWithRootGemfile", self.working_dir)
def _prepare_application_environment(self, runtime):
"""
Create an application environment where Gemfile will be in the root folder of the app;
├── .ruby-version
├── RubyWithRootGemfile
│ └── app.rb
├── Gemfile
└── template.yaml
"""
# copy .ruby-version to the root of the project
ruby_runtime_path = runtime.replace(".", "").title() # ruby3.X to Ruby3X
shutil.copyfile(
Path(self.template_path).parent.joinpath(ruby_runtime_path, ".ruby-version"),
Path(self.working_dir).joinpath(".ruby-version"),
)
# copy gemfile to the root of the project
shutil.copyfile(Path(self.template_path).parent.joinpath("Gemfile"), Path(self.working_dir).joinpath("Gemfile"))
# copy function source code in its folder
osutils.copytree(
Path(self.template_path).parent.joinpath("RubyWithRootGemfile"),
Path(self.working_dir).joinpath("RubyWithRootGemfile"),
)
# copy template to the root folder
shutil.copyfile(Path(self.template_path), Path(self.working_dir).joinpath("template.yaml"))
# update template path with new location
self.template_path = str(Path(self.working_dir).joinpath("template.yaml"))
class TestBuildCommand_Go_Modules(BuildIntegGoBase):
@parameterized.expand(
[("go1.x", "Go", None, False), ("go1.x", "Go", "debug", "use_container")], name_func=show_container_in_test_name
)
def test_building_go(self, runtime, code_uri, mode, use_container):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
self._test_with_go(runtime, code_uri, mode, self.test_data_path, use_container=use_container)
class TestBuildCommand_Go_Modules_With_Specified_Architecture(BuildIntegGoBase):
template = "template_with_architecture.yaml"
@parameterized.expand(
[
("go1.x", "Go", None, "x86_64"),
]
)
def test_building_go(self, runtime, code_uri, mode, architecture):
self._test_with_go(runtime, code_uri, mode, self.test_data_path, architecture)
@parameterized.expand([("go1.x", "Go", "unknown_architecture")])
def test_go_must_fail_with_unknown_architecture(self, runtime, code_uri, architecture):
overrides = {"Runtime": runtime, "CodeUri": code_uri, "Handler": "hello-world", "Architectures": architecture}
cmdlist = self.get_command_list(parameter_overrides=overrides)
process_execute = run_command(cmdlist, cwd=self.working_dir)
# Must error out, because container builds are not supported
self.assertEqual(process_execute.process.returncode, 1)
class TestBuildCommand_SingleFunctionBuilds(BuildIntegBase):
template = "many-functions-template.yaml"
EXPECTED_FILES_PROJECT_MANIFEST = {
"__init__.py",
"main.py",
"numpy",
# 'cryptography',
"requirements.txt",
}
def test_function_not_found(self):
overrides = {"Runtime": "python3.11", "CodeUri": "Python", "Handler": "main.handler"}
cmdlist = self.get_command_list(parameter_overrides=overrides, function_identifier="FunctionNotInTemplate")
process_execute = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(process_execute.process.returncode, 1)
self.assertIn("FunctionNotInTemplate not found", str(process_execute.stderr))
@parameterized.expand(
[
("python3.11", False, "FunctionOne"),
("python3.11", "use_container", "FunctionOne"),
("python3.11", False, "FunctionTwo"),
("python3.11", "use_container", "FunctionTwo"),
],
name_func=show_container_in_test_name,
)
def test_build_single_function_invoke_in_container(self, runtime, use_container, function_identifier):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
overrides = {"Runtime": runtime, "CodeUri": "Python", "Handler": "main.handler"}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier=function_identifier
)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
self._verify_built_artifact(self.default_build_dir, function_identifier, self.EXPECTED_FILES_PROJECT_MANIFEST)
expected = {"pi": "3.14"}
if not SKIP_DOCKER_TESTS:
self._verify_invoke_built_function(
self.built_template, function_identifier, self._make_parameter_override_arg(overrides), expected
)
if use_container:
self.verify_docker_container_cleanedup(runtime)
self.verify_pulled_image(runtime)
def _verify_built_artifact(self, build_dir, function_logical_id, expected_files):
self.assertTrue(build_dir.exists(), "Build directory should be created")
build_dir_files = os.listdir(str(build_dir))
self.assertIn("template.yaml", build_dir_files)
self.assertIn(function_logical_id, build_dir_files)
template_path = build_dir.joinpath("template.yaml")
resource_artifact_dir = build_dir.joinpath(function_logical_id)
# Make sure the template has correct CodeUri for resource
self._verify_resource_property(str(template_path), function_logical_id, "CodeUri", function_logical_id)
all_artifacts = set(os.listdir(str(resource_artifact_dir)))
actual_files = all_artifacts.intersection(expected_files)
self.assertEqual(actual_files, expected_files)
def _get_python_version(self):
return "python{}.{}".format(sys.version_info.major, sys.version_info.minor)
@skipIf(
((IS_WINDOWS and RUNNING_ON_CI) and not CI_OVERRIDE),
"Skip build tests on windows when running in CI unless overridden",
)
class TestBuildCommand_ExcludeResources(BuildIntegBase):
template = "many-more-functions-template.yaml"
@parameterized.expand(
[
((), None),
(("FunctionOne",), None),
(("FunctionThree",), None),
(("FunctionOne",), "FunctionOne"),
(("FunctionOne",), "FunctionTwo"),
(("FunctionTwo", "FunctionThree")),
]
)
def test_build_without_resources(self, excluded_resources, function_identifier):
overrides = {"Runtime": "python3.12", "CodeUri": "Python", "Handler": "main.handler"}
cmdlist = self.get_command_list(
parameter_overrides=overrides, function_identifier=function_identifier, exclude=excluded_resources
)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
self._verify_resources_excluded(self.default_build_dir, excluded_resources, function_identifier)
def _verify_resources_excluded(self, build_dir, excluded_resources, function_identifier):
self.assertTrue(build_dir.exists(), "Build directory should be created")
build_dir_files = os.listdir(str(build_dir))
if function_identifier is not None and function_identifier in excluded_resources:
self.assertIn(function_identifier, build_dir_files) # If building 1 and excluding it, build anyway
else:
for resource in excluded_resources:
self.assertNotIn(resource, build_dir_files)
@skipIf(
((IS_WINDOWS and RUNNING_ON_CI) and not CI_OVERRIDE),
"Skip build tests on windows when running in CI unless overridden",
)
@pytest.mark.requires_credential
class TestBuildCommand_LayerBuilds(BuildIntegBase):
template = "layers-functions-template.yaml"
EXPECTED_FILES_PROJECT_MANIFEST = {"__init__.py", "main.py", "requirements.txt"}
EXPECTED_LAYERS_FILES_PROJECT_MANIFEST = {"__init__.py", "layer.py", "numpy", "requirements.txt"}
EXPECTED_LAYERS_FILES_NO_COMPATIBLE_RUNTIMES = {"__init__.py", "layer.py", "requirements.txt"}
@parameterized.expand(
[
("python3.12", False, "LayerOne", "ContentUri"),
("python3.12", "use_container", "LayerOne", "ContentUri"),
("python3.12", False, "LambdaLayerOne", "Content"),
("python3.12", "use_container", "LambdaLayerOne", "Content"),
],
name_func=show_container_in_test_name,
)
def test_build_single_layer(self, runtime, use_container, layer_identifier, content_property):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
self._do_build_single_layer(runtime, use_container, layer_identifier, content_property)
def _do_build_single_layer(self, runtime, use_container, layer_identifier, content_property):
overrides = {"LayerBuildMethod": runtime, "LayerContentUri": "PyLayer"}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier=layer_identifier
)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
LOG.info("Default build dir: %s", self.default_build_dir)
self._verify_built_artifact(
self.default_build_dir,
layer_identifier,
self.EXPECTED_LAYERS_FILES_PROJECT_MANIFEST,
content_property,
"python",
)
@parameterized.expand(
[("makefile", False, "LayerWithMakefile"), ("makefile", "use_container", "LayerWithMakefile")],
name_func=show_container_in_test_name,
)
def test_build_layer_with_makefile(self, build_method, use_container, layer_identifier):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
overrides = {"LayerBuildMethod": build_method, "LayerMakeContentUri": "PyLayerMake"}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier=layer_identifier
)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
LOG.info("Default build dir: %s", self.default_build_dir)
self._verify_built_artifact(
self.default_build_dir,
layer_identifier,
self.EXPECTED_LAYERS_FILES_PROJECT_MANIFEST,
"ContentUri",
"python",
)
@skipIf(SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD, SKIP_DOCKER_MESSAGE)
def test_build_layer_with_makefile_no_compatible_runtimes_in_container(self):
build_method = "makefile"
use_container = True
layer_identifier = "LayerWithMakefileNoCompatibleRuntimes"
overrides = {"LayerBuildMethod": build_method, "LayerMakeContentUri": "PyLayerMake"}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier=layer_identifier
)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
LOG.info("Default build dir: %s", self.default_build_dir)
self._verify_built_artifact(
self.default_build_dir,
layer_identifier,
self.EXPECTED_LAYERS_FILES_NO_COMPATIBLE_RUNTIMES,
"ContentUri",
"random",
)
@parameterized.expand(
[("makefile", False), ("makefile", "use_container"), ("python3.9", False), ("python3.9", "use_container")],
name_func=show_container_in_test_name,
)
def test_build_layer_with_architecture_not_compatible(self, build_method, use_container):
# The BuildArchitecture is not one of the listed CompatibleArchitectures
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
layer_identifier = "LayerWithNoCompatibleArchitectures"
overrides = {
"LayerBuildMethod": build_method,
"LayerMakeContentUri": "PyLayerMake",
"LayerBuildArchitecture": "x86_64",
"LayerCompatibleArchitecture": "arm64",
}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier=layer_identifier
)
command_result = run_command(cmdlist, cwd=self.working_dir)
# Capture warning
self.assertIn(
f"Layer '{layer_identifier}' has BuildArchitecture x86_64, which is not listed in CompatibleArchitectures",
str(command_result.stderr.decode("utf-8")),
)
# Build should still succeed
self.assertEqual(command_result.process.returncode, 0)
@parameterized.expand(
[("python3.11", False), ("python3.11", "use_container")], name_func=show_container_in_test_name
)
def test_build_arch_no_compatible_arch(self, runtime, use_container):
# BuildArchitecture is present, but CompatibleArchitectures section is missing
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
layer_identifier = "LayerWithBuildArchButNoCompatibleArchs"
overrides = {
"LayerBuildMethod": runtime,
"LayerMakeContentUri": "PyLayer",
"LayerBuildArchitecture": "arm64",
}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier=layer_identifier
)
command_result = run_command(cmdlist, cwd=self.working_dir)
# Capture warning
self.assertIn(
f"Layer '{layer_identifier}' has BuildArchitecture arm64, which is not listed in CompatibleArchitectures",
str(command_result.stderr),
)
# Build should still succeed
self.assertEqual(command_result.process.returncode, 0)
@parameterized.expand(
[("python3.11", False), ("python3.11", "use_container")], name_func=show_container_in_test_name
)
def test_compatible_arch_no_build_arch(self, runtime, use_container):
# CompatibleArchitectures is present, but BuildArchitecture section is missing
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
layer_identifier = "LayerWithCompatibleArchsButNoBuildArch"
overrides = {
"LayerBuildMethod": runtime,
"LayerMakeContentUri": "PyLayer",
"LayerCompatibleArchitecture": "arm64",
}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier=layer_identifier
)
command_result = run_command(cmdlist, cwd=self.working_dir)
# Capture warning
self.assertIn(
f"Layer '{layer_identifier}' has BuildArchitecture x86_64, which is not listed in CompatibleArchitectures",
str(command_result.stderr),
)
# Build should still succeed
self.assertEqual(command_result.process.returncode, 0)
def test_build_layer_with_makefile_with_fake_build_architecture(self):
build_method = "makefile"
use_container = False
# Re-use the same test Layer, this time with just a bad BuildArchitecture
layer_identifier = "LayerWithNoCompatibleArchitectures"
overrides = {
"LayerBuildMethod": build_method,
"LayerMakeContentUri": "PyLayerMake",
"LayerBuildArchitecture": "fake",
}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier=layer_identifier
)
command_result = run_command(cmdlist, cwd=self.working_dir)
# Capture warning
self.assertIn(
"`fake` in Layer `LayerWithNoCompatibleArchitectures` is not a valid architecture",
str(command_result.stderr),
)
# Build should still succeed
self.assertEqual(command_result.process.returncode, 0)
@parameterized.expand(
[("python3.12", False, "LayerTwo"), ("python3.12", "use_container", "LayerTwo")],
name_func=show_container_in_test_name,
)
def test_build_fails_with_missing_metadata(self, runtime, use_container, layer_identifier):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
overrides = {"LayerBuildMethod": runtime, "LayerContentUri": "PyLayer"}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier=layer_identifier
)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 1)
self.assertFalse(self.default_build_dir.joinpath(layer_identifier).exists())
@parameterized.expand([False, "use_container"], name_func=show_container_in_test_name)
def test_function_build_succeeds_with_referenced_layer(self, use_container):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
overrides = {"Runtime": "python3.11", "CodeUri": "Python"}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier="FunctionTwo"
)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
@parameterized.expand(
[("python3.12", False), ("python3.12", "use_container")], name_func=show_container_in_test_name
)
def test_build_function_and_layer_invoke_in_conatiner(self, runtime, use_container):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
overrides = {
"LayerBuildMethod": runtime,
"LayerContentUri": "PyLayer",
"LayerMakeContentUri": "PyLayerMake",
"Runtime": runtime,
"CodeUri": "PythonWithLayer",
"Handler": "main.handler",
}
cmdlist = self.get_command_list(use_container=use_container, parameter_overrides=overrides)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
LOG.info("Default build dir: %s", self.default_build_dir)
self._verify_built_artifact(
self.default_build_dir, "FunctionOne", self.EXPECTED_FILES_PROJECT_MANIFEST, "CodeUri"
)
self._verify_built_artifact(
self.default_build_dir, "LayerOne", self.EXPECTED_LAYERS_FILES_PROJECT_MANIFEST, "ContentUri", "python"
)
expected = {"pi": "3.14"}
if not SKIP_DOCKER_TESTS:
self._verify_invoke_built_function(
self.built_template, "FunctionOne", self._make_parameter_override_arg(overrides), expected
)
if use_container:
self.verify_docker_container_cleanedup(runtime)
self.verify_pulled_image(runtime)
@parameterized.expand(
[("python3.12", False), ("python3.12", "use_container")], name_func=show_container_in_test_name
)
def test_build_function_with_dependent_layer_invoke_in_container(self, runtime, use_container):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
overrides = {
"LayerBuildMethod": runtime,
"LayerContentUri": "PyLayer",
"Runtime": runtime,
"CodeUri": "PythonWithLayer",
"Handler": "main.handler",
}
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, function_identifier="FunctionOne"
)
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
LOG.info("Default build dir: %s", self.default_build_dir)
self._verify_built_artifact(
self.default_build_dir, "FunctionOne", self.EXPECTED_FILES_PROJECT_MANIFEST, "CodeUri"
)
self._verify_built_artifact(
self.default_build_dir, "LayerOne", self.EXPECTED_LAYERS_FILES_PROJECT_MANIFEST, "ContentUri", "python"
)
expected = {"pi": "3.14"}
if not SKIP_DOCKER_TESTS:
self._verify_invoke_built_function(
self.built_template, "FunctionOne", self._make_parameter_override_arg(overrides), expected
)
if use_container:
self.verify_docker_container_cleanedup(runtime)
self.verify_pulled_image(runtime)
@pytest.mark.tier1_extra
def test_tier1_layer_build(self):
"""Single layer build test for cross-platform validation."""
self._do_build_single_layer("python3.12", False, "LayerOne", "ContentUri")
def _verify_built_artifact(
self, build_dir, resource_logical_id, expected_files, code_property_name, artifact_subfolder=""
):
self.assertTrue(build_dir.exists(), "Build directory should be created")
build_dir_files = os.listdir(str(build_dir))
self.assertIn("template.yaml", build_dir_files)
self.assertIn(resource_logical_id, build_dir_files)
template_path = build_dir.joinpath("template.yaml")
resource_artifact_dir = build_dir.joinpath(resource_logical_id, artifact_subfolder)
# Make sure the template has correct CodeUri for resource
self._verify_resource_property(str(template_path), resource_logical_id, code_property_name, resource_logical_id)
all_artifacts = set(os.listdir(str(resource_artifact_dir)))
actual_files = all_artifacts.intersection(expected_files)
self.assertEqual(actual_files, expected_files)
def _get_python_version(self):
return "python{}.{}".format(sys.version_info.major, sys.version_info.minor)
@skipIf(
((IS_WINDOWS and RUNNING_ON_CI) and not CI_OVERRIDE),
"Skip build tests on windows when running in CI unless overridden",
)
class TestBuildWithBuildMethod(BuildIntegBase):
# Test Suite where `BuildMethod` is explicitly specified.
template = "custom-build-function.yaml"
EXPECTED_FILES_PROJECT_MANIFEST = {"__init__.py", "main.py", "requests", "requirements.txt"}
FUNCTION_LOGICAL_ID = "Function"
@parameterized.expand(
[(False, None, "makefile"), ("use_container", "Makefile-container", "makefile")],
name_func=show_container_in_test_name,
)
def test_with_makefile_builder_specified_python_runtime_invoke_in_container(
self, use_container, manifest, build_method
):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
# runtime is chosen based off current python version.
runtime = self._get_python_version()
# Codeuri is still Provided, since that directory has the makefile.
overrides = {"Runtime": runtime, "CodeUri": "Provided", "Handler": "main.handler", "BuildMethod": build_method}
manifest_path = None
if manifest:
manifest_path = os.path.join(self.test_data_path, "Provided", manifest)
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, manifest_path=manifest_path
)
# Built using Makefile for a python project.
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
self._verify_built_artifact(
self.default_build_dir, self.FUNCTION_LOGICAL_ID, self.EXPECTED_FILES_PROJECT_MANIFEST
)
expected = "2.23.0"
# Building was done with a makefile, invoke is checked with the same runtime image.
if not SKIP_DOCKER_TESTS:
self._verify_invoke_built_function(
self.built_template, self.FUNCTION_LOGICAL_ID, self._make_parameter_override_arg(overrides), expected
)
if use_container:
self.verify_docker_container_cleanedup(runtime)
self.verify_pulled_image(runtime)
@parameterized.expand([(False,), ("use_container")], name_func=show_container_in_test_name)
def test_with_native_builder_specified_python_runtime_invoke_in_container(self, use_container):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
# runtime is chosen based off current python version.
runtime = self._get_python_version()
# Codeuri is still Provided, since that directory has the makefile, but it also has the
# actual manifest file of `requirements.txt`.
# BuildMethod is set to the same name as of the runtime.
overrides = {"Runtime": runtime, "CodeUri": "Provided", "Handler": "main.handler", "BuildMethod": runtime}
manifest_path = os.path.join(self.test_data_path, "Provided", "requirements.txt")
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, manifest_path=manifest_path
)
# Built using `native` python-pip builder for a python project.
command_result = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command_result.process.returncode, 0)
self._verify_built_artifact(
self.default_build_dir, self.FUNCTION_LOGICAL_ID, self.EXPECTED_FILES_PROJECT_MANIFEST
)
expected = "2.23.0"
# Building was done with a `python-pip` builder, invoke is checked with the same runtime image.
if not SKIP_DOCKER_TESTS:
self._verify_invoke_built_function(
self.built_template, self.FUNCTION_LOGICAL_ID, self._make_parameter_override_arg(overrides), expected
)
if use_container:
self.verify_docker_container_cleanedup(runtime)
self.verify_pulled_image(runtime)
@parameterized.expand([(False,), ("use_container")])
def test_with_wrong_builder_specified_python_runtime(self, use_container):
if use_container and (SKIP_DOCKER_TESTS or SKIP_DOCKER_BUILD):
self.skipTest(SKIP_DOCKER_MESSAGE)
# runtime is chosen based off current python version.
runtime = self._get_python_version()
# BuildMethod is set to the java17, this should cause failure.
overrides = {"Runtime": runtime, "CodeUri": "Provided", "Handler": "main.handler", "BuildMethod": "java17"}
manifest_path = os.path.join(self.test_data_path, "Provided", "requirements.txt")
cmdlist = self.get_command_list(
use_container=use_container, parameter_overrides=overrides, manifest_path=manifest_path
)
# This will error out.
command = run_command(cmdlist, cwd=self.working_dir)
self.assertEqual(command.process.returncode, 1)
self.assertEqual(command.stdout.strip(), b"Build Failed")
def _verify_built_artifact(self, build_dir, function_logical_id, expected_files):