Skip to content

Commit 747cf34

Browse files
mndevecimildaniel
andauthored
chore: sync foss changes (aws#2445)
* chore: sync foss changes * Add make target for creating companion stack, add config files * Fix cors tests * add --no-cov to companion setup * fix wrong test setups * fix wrong test setups * use parameters when doing local transform * Revert "use parameters when doing local transform" This reverts commit 4b987dc. Co-authored-by: Daniel Mil <[email protected]>
1 parent 4250ce1 commit 747cf34

24 files changed

+254
-232
lines changed

INTEGRATION_TESTS.md

+8
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,14 @@ If you haven't done so already, run the following command in a terminal at the r
3434
make init
3535
```
3636

37+
### Setting up a companion stack
38+
39+
To run the tests, a companion stack first needs to be created. This stack houses some resources that are required by the tests, such as an S3 bucket.
40+
41+
```
42+
make prepare-companion-stack
43+
```
44+
3745
### Running all the tests
3846

3947
From the root of the repository, run:

Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ lint:
2727
# Linter performs static analysis to catch latent bugs
2828
pylint --rcfile .pylintrc samtranslator
2929

30+
prepare-companion-stack:
31+
pytest -v --no-cov integration/setup -m setup
32+
3033
# Command to run everytime you make changes to verify everything works
3134
dev: test
3235

@@ -43,5 +46,6 @@ TARGETS
4346
integ-test Run the Integration tests.
4447
dev Run all development tests after a change.
4548
pr Perform all checks before submitting a Pull Request.
49+
prepare-companion-stack Create or update the companion stack for running integration tests.
4650

4751
endef

integration/combination/test_custom_http_api_domains_test.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
from integration.config.service_names import CUSTOM_DOMAIN
44
from integration.helpers.base_internal_test import BaseInternalTest
5-
from integration.helpers.file_resources import FILE_TO_S3_URI_MAP
65
from integration.helpers.resource import current_region_not_included
76

87

@@ -25,7 +24,7 @@ def test_custom_http_api_domains_regional(self):
2524
self.assertEqual("httpapi.sam-gamma-regional.com", result["DomainName"])
2625

2726
mtls_auth_config = result["MutualTlsAuthentication"]
28-
self.assertEqual(FILE_TO_S3_URI_MAP["MTLSCert.pem"]["uri"], mtls_auth_config["TruststoreUri"])
27+
self.assertEqual(self.file_to_s3_uri_map["MTLSCert.pem"]["uri"], mtls_auth_config["TruststoreUri"])
2928

3029
domain_name_configs = result["DomainNameConfigurations"]
3130
self.assertEqual(1, len(domain_name_configs))

integration/combination/test_custom_rest_api_domains.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
from integration.config.service_names import CUSTOM_DOMAIN
44
from integration.helpers.base_internal_test import BaseInternalTest
5-
from integration.helpers.file_resources import FILE_TO_S3_URI_MAP
65
from integration.helpers.resource import current_region_not_included
76

87

@@ -47,7 +46,7 @@ def test_custom_rest_api_domains_regional(self):
4746
self.assertEqual("REGIONAL", end_point_types[0])
4847

4948
mtls_auth_config = result["mutualTlsAuthentication"]
50-
self.assertEqual(FILE_TO_S3_URI_MAP["MTLSCert.pem"]["uri"], mtls_auth_config["truststoreUri"])
49+
self.assertEqual(self.file_to_s3_uri_map["MTLSCert.pem"]["uri"], mtls_auth_config["truststoreUri"])
5150

5251
def test_custom_rest_api_domains_regional_ownership_verification(self):
5352
self.create_and_verify_stack("combination/api_with_custom_domains_regional_ownership_verification")
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,23 @@
11
from unittest.case import skipIf
2+
import pytest
23

34
from integration.config.service_names import EFS
45
from integration.helpers.base_test import BaseTest
56
from integration.helpers.resource import current_region_does_not_support
67

78

89
class TestFunctionWithFileSystemConfig(BaseTest):
10+
@pytest.fixture(autouse=True)
11+
def companion_stack_outputs(self, get_companion_stack_outputs):
12+
self.companion_stack_outputs = get_companion_stack_outputs
13+
914
@skipIf(current_region_does_not_support([EFS]), "EFS is not supported in this testing region")
1015
def test_function_with_efs_integration(self):
11-
self.create_and_verify_stack("combination/function_with_file_system_config")
16+
parameters = self.get_parameters(self.companion_stack_outputs)
17+
self.create_and_verify_stack("combination/function_with_file_system_config", parameters)
18+
19+
def get_parameters(self, dictionary):
20+
parameters = []
21+
parameters.append(self.generate_parameter("PreCreatedSubnetOne", dictionary["PreCreatedSubnetOne"]))
22+
parameters.append(self.generate_parameter("PreCreatedVpc", dictionary["PreCreatedVpc"]))
23+
return parameters

integration/combination/test_function_with_http_api.py

+6
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
1+
import logging
12
from unittest.case import skipIf
23

4+
import pytest
5+
36
from integration.helpers.base_test import BaseTest
47
from integration.helpers.resource import current_region_does_not_support
58
from integration.config.service_names import HTTP_API
69

10+
LOG = logging.getLogger(__name__)
11+
712

813
@skipIf(current_region_does_not_support([HTTP_API]), "HttpApi is not supported in this testing region")
914
class TestFunctionWithHttpApi(BaseTest):
15+
@pytest.mark.flaky(reruns=5)
1016
def test_function_with_http_api(self):
1117
self.create_and_verify_stack("combination/function_with_http_api")
1218

integration/combination/test_intrinsic_function_support.py

+22-10
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
from parameterized import parameterized
21
from unittest.case import skipIf
2+
import pytest
33

44
from integration.helpers.base_test import BaseTest
55
from integration.helpers.resource import current_region_does_not_support
@@ -8,18 +8,24 @@
88

99
@skipIf(current_region_does_not_support([REST_API]), "Rest API is not supported in this testing region")
1010
class TestIntrinsicFunctionsSupport(BaseTest):
11+
@pytest.fixture(autouse=True)
12+
def companion_stack_outputs(self, get_companion_stack_outputs):
13+
self.companion_stack_outputs = get_companion_stack_outputs
1114

12-
# test code definition uri object and serverless function properties support
13-
@parameterized.expand(
14-
[
15-
"combination/intrinsics_code_definition_uri",
16-
"combination/intrinsics_serverless_function",
17-
]
18-
)
19-
def test_common_support(self, file_name):
15+
# test serverless function properties support
16+
def test_serverless_function_property_support(self):
2017
# Just a simple deployment will validate that Code & Swagger files were accessible
2118
# Just a simple deployment will validate that all properties were resolved expected
22-
self.create_and_verify_stack(file_name, self.get_default_test_template_parameters())
19+
parameters = self.get_parameters(self.companion_stack_outputs)
20+
parameters.extend(self.get_default_test_template_parameters())
21+
self.create_and_verify_stack("combination/intrinsics_serverless_function", parameters)
22+
23+
# test code definition uri object support
24+
def test_definition_uri_support(self):
25+
# Just a simple deployment will validate that Code & Swagger files were accessible
26+
# Just a simple deployment will validate that all properties were resolved expected
27+
parameters = self.get_default_test_template_parameters()
28+
self.create_and_verify_stack("combination/intrinsics_code_definition_uri", parameters)
2329

2430
def test_severless_api_properties_support(self):
2531
self.create_and_verify_stack(
@@ -62,3 +68,9 @@ def test_severless_api_properties_support(self):
6268
self.assertEqual(tags["lambda:createdBy"], "SAM", "Expected 'SAM' tag value, but not found.")
6369
self.assertTrue("TagKey1" in tags)
6470
self.assertEqual(tags["TagKey1"], api_stage_name)
71+
72+
def get_parameters(self, dictionary):
73+
parameters = []
74+
parameters.append(self.generate_parameter("PreCreatedSubnetOne", dictionary["PreCreatedSubnetOne"]))
75+
parameters.append(self.generate_parameter("PreCreatedVpc", dictionary["PreCreatedVpc"]))
76+
return parameters
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"codeuri": "code.zip",
3+
"contenturi": "layer1.zip",
4+
"definitionuri": "swagger1.json",
5+
"templateurl": "template.yaml",
6+
"binaryMediaCodeUri": "binary-media.zip",
7+
"mtlsuri": "MTLSCert.pem"
8+
}
+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"code.zip": {"type": "s3", "uri": ""},
3+
"code2.zip": {"type": "s3", "uri": ""},
4+
"layer1.zip": {"type": "s3", "uri": ""},
5+
"swagger1.json": {"type": "s3", "uri": ""},
6+
"swagger2.json": {"type": "s3", "uri": ""},
7+
"binary-media.zip": {"type": "s3", "uri": ""},
8+
"template.yaml": {"type": "http", "uri": ""},
9+
"MTLSCert.pem": {"type": "s3", "uri": ""},
10+
"MTLSCert-Updated.pem": {"type": "s3", "uri": ""}
11+
}

integration/conftest.py

+70-4
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66

77
from integration.helpers.base_test import S3_BUCKET_PREFIX
88
from integration.helpers.client_provider import ClientProvider
9-
from integration.helpers.deployer.exceptions.exceptions import ThrottlingError
9+
from integration.helpers.deployer.exceptions.exceptions import S3DoesNotExistException, ThrottlingError
1010
from integration.helpers.deployer.utils.retry import retry_with_exponential_backoff_and_jitter
1111
from integration.helpers.stack import Stack
1212
from integration.helpers.yaml_utils import load_yaml
13+
from integration.helpers.resource import read_test_config_file, write_test_config_file_to_json
1314

1415
try:
1516
from pathlib import Path
@@ -63,10 +64,57 @@ def setup_companion_stack_once(tmpdir_factory, get_prefix):
6364
cfn_client = ClientProvider().cfn_client
6465
output_dir = tmpdir_factory.mktemp("data")
6566
stack_name = get_prefix + COMPANION_STACK_NAME
66-
if _stack_exists(stack_name):
67-
return
6867
companion_stack = Stack(stack_name, companion_stack_tempalte_path, cfn_client, output_dir)
69-
companion_stack.create()
68+
companion_stack.create_or_update(_stack_exists(stack_name))
69+
70+
71+
@pytest.fixture()
72+
def upload_resources(get_s3):
73+
"""
74+
Creates the bucket and uploads the files used by the tests to it
75+
"""
76+
s3_bucket = get_s3
77+
if not _s3_exists(s3_bucket):
78+
raise S3DoesNotExistException(get_s3, "Check companion stack status")
79+
code_dir = Path(__file__).resolve().parents[0].joinpath("resources").joinpath("code")
80+
file_to_s3_uri_map = read_test_config_file("file_to_s3_map.json")
81+
82+
if not file_to_s3_uri_map or not file_to_s3_uri_map.items():
83+
LOG.debug("No resources to upload")
84+
return
85+
86+
current_file_name = ""
87+
88+
try:
89+
s3_client = ClientProvider().s3_client
90+
session = boto3.session.Session()
91+
region = session.region_name
92+
for file_name, file_info in file_to_s3_uri_map.items():
93+
current_file_name = file_name
94+
code_path = str(Path(code_dir, file_name))
95+
LOG.debug("Uploading file %s to bucket %s", file_name, s3_bucket)
96+
s3_client.upload_file(code_path, s3_bucket, file_name)
97+
LOG.debug("File %s uploaded successfully to bucket %s", file_name, s3_bucket)
98+
file_info["uri"] = get_s3_uri(file_name, file_info["type"], s3_bucket, region)
99+
except ClientError as error:
100+
LOG.error("Upload of file %s to bucket %s failed", current_file_name, s3_bucket, exc_info=error)
101+
raise error
102+
103+
write_test_config_file_to_json("file_to_s3_map_modified.json", file_to_s3_uri_map)
104+
105+
106+
def get_s3_uri(file_name, uri_type, bucket, region):
107+
if uri_type == "s3":
108+
return "s3://{}/{}".format(bucket, file_name)
109+
110+
if region == "us-east-1":
111+
return "https://s3.amazonaws.com/{}/{}".format(bucket, file_name)
112+
if region == "us-iso-east-1":
113+
return "https://s3.us-iso-east-1.c2s.ic.gov/{}/{}".format(bucket, file_name)
114+
if region == "us-isob-east-1":
115+
return "https://s3.us-isob-east-1.sc2s.sgov.gov/{}/{}".format(bucket, file_name)
116+
117+
return "https://s3-{}.amazonaws.com/{}/{}".format(region, bucket, file_name)
70118

71119

72120
@pytest.fixture()
@@ -99,6 +147,12 @@ def get_companion_stack_outputs(get_prefix):
99147
return get_stack_outputs(companion_stack_description)
100148

101149

150+
@pytest.fixture()
151+
def get_s3(get_companion_stack_outputs):
152+
s3_bucket = get_companion_stack_outputs.get("PreCreatedS3Bucket")
153+
return str(s3_bucket)
154+
155+
102156
@pytest.fixture()
103157
def get_prefix(request):
104158
prefix = ""
@@ -171,3 +225,15 @@ def _stack_exists(stack_name):
171225
raise ex
172226

173227
return True
228+
229+
230+
@retry_with_exponential_backoff_and_jitter(ThrottlingError, 5, 360)
231+
def _s3_exists(s3_bucket):
232+
s3 = boto3.resource("s3")
233+
bucket = s3.Bucket(s3_bucket)
234+
try:
235+
s3.meta.client.head_bucket(Bucket=bucket.name)
236+
except ClientError:
237+
return False
238+
239+
return True

0 commit comments

Comments
 (0)