Skip to content

Commit a861309

Browse files
committed
chore: cleanup leftover code; add debug
1 parent d88aa80 commit a861309

File tree

7 files changed

+37
-40
lines changed

7 files changed

+37
-40
lines changed

tests/e2e/infrastructure.py

Whitespace-only changes.

tests/e2e/logger/infrastructure.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55

66
class LoggerStack(BaseInfrastructureV2):
7-
def __init__(self, handlers_dir: Path, feature_name: str = "logger", layer_arn: str = "") -> None:
7+
FEATURE_NAME = "logger"
8+
9+
def __init__(self, handlers_dir: Path, feature_name: str = FEATURE_NAME, layer_arn: str = "") -> None:
810
super().__init__(feature_name, handlers_dir, layer_arn)
911

1012
def create_resources(self):

tests/e2e/metrics/infrastructure.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55

66
class MetricsStack(BaseInfrastructureV2):
7-
def __init__(self, handlers_dir: Path, feature_name: str = "metrics", layer_arn: str = "") -> None:
7+
FEATURE_NAME = "metrics"
8+
9+
def __init__(self, handlers_dir: Path, feature_name: str = FEATURE_NAME, layer_arn: str = "") -> None:
810
super().__init__(feature_name, handlers_dir, layer_arn)
911

1012
def create_resources(self):

tests/e2e/tracer/infrastructure.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@ class TracerStack(BaseInfrastructureV2):
88
# Maintenance: Tracer doesn't support dynamic service injection (tracer.py L310)
99
# we could move after handler response or adopt env vars usage in e2e tests
1010
SERVICE_NAME: str = build_service_name()
11+
FEATURE_NAME = "tracer"
1112

12-
def __init__(self, handlers_dir: Path, feature_name: str = "tracer", layer_arn: str = "") -> None:
13+
def __init__(self, handlers_dir: Path, feature_name: str = FEATURE_NAME, layer_arn: str = "") -> None:
1314
super().__init__(feature_name, handlers_dir, layer_arn)
1415

1516
def create_resources(self) -> None:

tests/e2e/utils/asset.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import io
22
import json
3+
import logging
34
import zipfile
45
from pathlib import Path
56
from typing import Dict, List, Optional
@@ -9,9 +10,7 @@
910
from mypy_boto3_s3 import S3Client
1011
from pydantic import BaseModel, Field
1112

12-
from aws_lambda_powertools import Logger
13-
14-
logger = Logger(service="e2e-utils")
13+
logger = logging.getLogger(__name__)
1514

1615

1716
class AssetManifest(BaseModel):
@@ -113,6 +112,7 @@ def upload(self):
113112
We follow the same design cdk-assets:
114113
https://github.com/aws/aws-cdk-rfcs/blob/master/text/0092-asset-publishing.md.
115114
"""
115+
logger.debug(f"Upload {len(self.assets)} assets")
116116
for asset in self.assets:
117117
if not asset.is_zip:
118118
logger.debug(f"Asset '{asset.object_key}' is not zip. Skipping upload.")

tests/e2e/utils/infrastructure.py

+26-34
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
import logging
23
import sys
34
from abc import ABC, abstractmethod
45
from enum import Enum
@@ -18,6 +19,8 @@
1819

1920
PYTHON_RUNTIME_VERSION = f"V{''.join(map(str, sys.version_info[:2]))}"
2021

22+
logger = logging.getLogger(__name__)
23+
2124

2225
class BaseInfrastructureStack(ABC):
2326
@abstractmethod
@@ -36,19 +39,19 @@ class PythonVersion(Enum):
3639

3740

3841
class BaseInfrastructureV2(ABC):
39-
STACKS_OUTPUT: dict = {}
40-
4142
def __init__(self, feature_name: str, handlers_dir: Path, layer_arn: str = "") -> None:
4243
self.feature_name = feature_name
4344
self.stack_name = f"test-{feature_name}-{uuid4()}"
4445
self.handlers_dir = handlers_dir
46+
self.layer_arn = layer_arn
4547
self.stack_outputs: Dict[str, str] = {}
48+
49+
# NOTE: Investigate why cdk.Environment in Stack
50+
# changes synthesized asset (no object_key in asset manifest)
4651
self.app = App()
47-
# NOTE: Investigate why env changes synthesized asset (no object_key in asset manifest)
4852
self.stack = Stack(self.app, self.stack_name)
4953
self.session = boto3.Session()
5054
self.cfn: CloudFormationClient = self.session.client("cloudformation")
51-
self.layer_arn = layer_arn
5255

5356
# NOTE: CDK stack account and region are tokens, we need to resolve earlier
5457
self.account_id = self.session.client("sts").get_caller_identity()["Account"]
@@ -86,6 +89,7 @@ def create_lambda_functions(self, function_props: Optional[Dict] = None):
8689
handlers = list(self.handlers_dir.rglob("*.py"))
8790
source = Code.from_asset(f"{self.handlers_dir}")
8891
props_override = function_props or {}
92+
logger.debug(f"Creating functions for handlers: {handlers}")
8993
if not self.layer_arn:
9094
raise ValueError(
9195
"""Lambda Layer ARN cannot be empty when creating Lambda functions.
@@ -96,6 +100,8 @@ def create_lambda_functions(self, function_props: Optional[Dict] = None):
96100

97101
for fn in handlers:
98102
fn_name = fn.stem
103+
fn_name_pascal_case = fn_name.title().replace("_", "") # basic_handler -> BasicHandler
104+
logger.debug(f"Creating function: {fn_name_pascal_case}")
99105
function_settings = {
100106
"id": f"{fn_name}-lambda",
101107
"code": source,
@@ -116,9 +122,8 @@ def create_lambda_functions(self, function_props: Optional[Dict] = None):
116122
removal_policy=RemovalPolicy.DESTROY,
117123
)
118124

119-
# CFN Outputs only support hyphen
120-
fn_name_pascal_case = fn_name.title().replace("_", "") # basic_handler -> BasicHandler
121-
self._add_resource_output(
125+
# CFN Outputs only support hyphen hence pascal case
126+
self.add_cfn_output(
122127
name=fn_name_pascal_case, value=function_python.function_name, arn=function_python.function_arn
123128
)
124129

@@ -133,14 +138,12 @@ def deploy(self) -> Dict[str, str]:
133138
template, asset_manifest_file = self._synthesize()
134139
assets = Assets(asset_manifest=asset_manifest_file, account_id=self.account_id, region=self.region)
135140
assets.upload()
136-
outputs = self._deploy_stack(self.stack_name, template)
137-
# NOTE: hydrate map of stack resolved outputs for future access
138-
self.STACKS_OUTPUT[self.feature_name] = outputs
139-
140-
return outputs
141+
self.stack_outputs = self._deploy_stack(self.stack_name, template)
142+
return self.stack_outputs
141143

142144
def delete(self) -> None:
143145
"""Delete CloudFormation Stack"""
146+
logger.debug(f"Deleting stack: {self.stack_name}")
144147
self.cfn.delete_stack(StackName=self.stack_name)
145148

146149
@abstractmethod
@@ -157,7 +160,7 @@ def created_resources(self):
157160
s3 = s3.Bucket(self.stack, "MyBucket")
158161
159162
# This will create MyBucket and MyBucketArn CloudFormation Output
160-
self._add_resource_output(name="MyBucket", value=s3.bucket_name, arn_value=bucket.bucket_arn)
163+
self.add_cfn_output(name="MyBucket", value=s3.bucket_name, arn_value=bucket.bucket_arn)
161164
```
162165
163166
Creating Lambda functions available in the handlers directory
@@ -170,7 +173,9 @@ def created_resources(self):
170173
...
171174

172175
def _synthesize(self) -> Tuple[Dict, Path]:
176+
logger.debug("Creating CDK Stack resources")
173177
self.create_resources()
178+
logger.debug("Synthesizing CDK Stack into raw CloudFormation template")
174179
cloud_assembly = self.app.synth()
175180
cf_template: Dict = cloud_assembly.get_stack_by_name(self.stack_name).template
176181
cloud_assembly_assets_manifest_path: str = (
@@ -179,6 +184,7 @@ def _synthesize(self) -> Tuple[Dict, Path]:
179184
return cf_template, Path(cloud_assembly_assets_manifest_path)
180185

181186
def _deploy_stack(self, stack_name: str, template: Dict) -> Dict[str, str]:
187+
logger.debug(f"Creating CloudFormation Stack: {stack_name}")
182188
self.cfn.create_stack(
183189
StackName=stack_name,
184190
TemplateBody=yaml.dump(template),
@@ -191,16 +197,10 @@ def _deploy_stack(self, stack_name: str, template: Dict) -> Dict[str, str]:
191197

192198
stack_details = self.cfn.describe_stacks(StackName=stack_name)
193199
stack_outputs = stack_details["Stacks"][0]["Outputs"]
194-
self.stack_outputs = {
195-
output["OutputKey"]: output["OutputValue"] for output in stack_outputs if output["OutputKey"]
196-
}
197-
198-
return self.stack_outputs
199-
200-
def _add_resource_output(self, name: str, value: str, arn: str):
201-
"""Add both resource value and ARN as Outputs to facilitate tests.
200+
return {output["OutputKey"]: output["OutputValue"] for output in stack_outputs if output["OutputKey"]}
202201

203-
This will create two outputs: {Name} and {Name}Arn
202+
def add_cfn_output(self, name: str, value: str, arn: str = ""):
203+
"""Create {Name} and optionally {Name}Arn CloudFormation Outputs.
204204
205205
Parameters
206206
----------
@@ -212,7 +212,8 @@ def _add_resource_output(self, name: str, value: str, arn: str):
212212
CloudFormation Output Value for ARN
213213
"""
214214
CfnOutput(self.stack, f"{name}", value=value)
215-
CfnOutput(self.stack, f"{name}Arn", value=arn)
215+
if arn:
216+
CfnOutput(self.stack, f"{name}Arn", value=arn)
216217

217218

218219
def deploy_once(
@@ -241,13 +242,7 @@ def deploy_once(
241242
Generator[Dict[str, str], None, None]
242243
stack CloudFormation outputs
243244
"""
244-
try:
245-
handlers_dir = f"{request.path.parent}/handlers"
246-
except AttributeError:
247-
# session fixture has a slightly different object
248-
# luckily it only runs Lambda Layer Stack which doesn't deploy Lambda fns
249-
handlers_dir = f"{request.node.path.parent}/handlers"
250-
245+
handlers_dir = f"{request.node.path.parent}/handlers"
251246
stack = stack(handlers_dir=Path(handlers_dir), layer_arn=layer_arn)
252247

253248
try:
@@ -257,10 +252,6 @@ def deploy_once(
257252
else:
258253
# tmp dir shared by all workers
259254
root_tmp_dir = tmp_path_factory.getbasetemp().parent
260-
261-
# cache and lock must be unique per stack
262-
# otherwise separate processes deploy the first stack collected only
263-
# since the original lock was based on parallel workers cache tmp dir
264255
cache = root_tmp_dir / "cache.json"
265256

266257
with FileLock(f"{cache}.lock"):
@@ -288,6 +279,7 @@ def create_resources(self):
288279
CfnOutput(self.stack, "LayerArn", value=layer)
289280

290281
def _create_layer(self) -> str:
282+
logger.debug("Creating Lambda Layer with latest source code available")
291283
output_dir = Path(str(AssetStaging.BUNDLING_OUTPUT_DIR), "python")
292284
input_dir = Path(str(AssetStaging.BUNDLING_INPUT_DIR), "aws_lambda_powertools")
293285
build_commands = [f"pip install . -t {output_dir}", f"cp -R {input_dir} {output_dir}"]

tests/utils.py

Whitespace-only changes.

0 commit comments

Comments
 (0)