Skip to content

Commit

Permalink
added cdk-test
Browse files Browse the repository at this point in the history
  • Loading branch information
keithrozario committed Apr 24, 2024
1 parent 51d5a3d commit 1715147
Show file tree
Hide file tree
Showing 12 changed files with 237 additions and 4 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ class MockStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

runtime = aws_lambda.Runtime.PYTHON_3_12

# Initialize Klayers
klayers = Klayers(
self,
python_version = aws_lambda.Runtime.PYTHON_3_12
python_version = runtime
)

# get the latest layer version for the requests package
Expand All @@ -36,17 +38,15 @@ class MockStack(Stack):

lambda_function = aws_lambda.Function(
self, 'HelloHandler',
runtime= aws_lambda.Runtime.PYTHON_3_12,
runtime=runtime,
layers=[requests_layer, idna_layer],
code=aws_lambda.Code.from_asset('lambda'),
handler='hello.handler'
# other props
)



app = App()
# region must be specified in environment or within the Klayers __init__
env = Environment(region="us-east-1")
mock_stack =MockStack(app, "test", env=env)
```
Expand Down
10 changes: 10 additions & 0 deletions cdk_test/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
*.swp
package-lock.json
__pycache__
.pytest_cache
.venv
*.egg-info

# CDK asset staging directory
.cdk.staging
cdk.out
25 changes: 25 additions & 0 deletions cdk_test/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# CDK-Test

This directory is to an end-2-end test within a CDK `synth` process. The magic is here:

```python
sys.path.append(str(Path(os.getcwd()).parent))
from cdk_klayers import Klayers
```

Where we add the top level directory into the PYTHONPATH, and hence python can import the cdk_klayers directly from the top level directory.

The test should create lambda function with the following 3 layers, in ap-southeast-1:

Layers:
- arn:aws:lambda:ap-southeast-1:770693421928:layer:Klayers-p312-aws-xray-sdk:1
- arn:aws:lambda:ap-southeast-1:770693421928:layer:Klayers-p312-idna:1
- arn:aws:lambda:ap-southeast-1:770693421928:layer:Klayers-p312-requests:3

aws-xray-sdk will always be version 1 (as we request that). The other 2 layers will change version depending on what's the latest available.


## Run Test

$ cdk synth

48 changes: 48 additions & 0 deletions cdk_test/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
import os
import sys
from pathlib import Path

from cdk_test.cdk_test_stack import CdkTestStack

from aws_cdk import aws_lambda
from aws_cdk import App,Stack,Environment
from aws_cdk import Aws
from constructs import Construct

sys.path.append(str(Path(os.getcwd()).parent))
from cdk_klayers import Klayers


class MockStack(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

powertools_layer = aws_lambda.LayerVersion.from_layer_version_arn(
self,
id="lambda-powertools",
layer_version_arn=f"arn:aws:lambda:{Aws.REGION}:017000801446:layer:AWSLambdaPowertoolsPythonV2:69",
)

klayers = Klayers(
self, python_version=aws_lambda.Runtime.PYTHON_3_12
)

idna_layer = klayers.layer_version(self, "requests")
requests_layer = klayers.layer_version(self, "idna")
xray_layer = klayers.layer_version(self, "aws-xray-sdk", layer_version="1")
lambda_function = aws_lambda.Function(
self,
"HelloHandler",
runtime=aws_lambda.Runtime.PYTHON_3_12,
code=aws_lambda.Code.from_asset("lambda"),
handler="hello.handler",
layers=[idna_layer, requests_layer, xray_layer],
)


app = App()
env = Environment(region="ap-southeast-1")
mock_stack = MockStack(app, "test",env = env)
app.synth()
66 changes: 66 additions & 0 deletions cdk_test/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
{
"app": "python3 app.py",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"requirements*.txt",
"source.bat",
"**/__init__.py",
"**/__pycache__",
"tests"
]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
],
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-route53-patters:useCertificate": true,
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
"@aws-cdk/aws-redshift:columnId": true,
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
"@aws-cdk/aws-kms:aliasNameRef": true,
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true
}
}
Empty file added cdk_test/cdk_test/__init__.py
Empty file.
19 changes: 19 additions & 0 deletions cdk_test/cdk_test/cdk_test_stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from aws_cdk import (
# Duration,
Stack,
# aws_sqs as sqs,
)
from constructs import Construct

class CdkTestStack(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

# The code that defines your stack goes here

# example resource
# queue = sqs.Queue(
# self, "CdkTestQueue",
# visibility_timeout=Duration.seconds(300),
# )
10 changes: 10 additions & 0 deletions cdk_test/lambda/hello.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import json


def handler(event, context):
print("request: {}".format(json.dumps(event)))
return {
"statusCode": 200,
"headers": {"Content-Type": "text/plain"},
"body": "Klayers is awesome {}\n".format(event["path"]),
}
Empty file added cdk_test/tests/__init__.py
Empty file.
Empty file added cdk_test/tests/unit/__init__.py
Empty file.
15 changes: 15 additions & 0 deletions cdk_test/tests/unit/test_cdk_test_stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import aws_cdk as core
import aws_cdk.assertions as assertions

from cdk_test.cdk_test_stack import CdkTestStack

# example tests. To run these tests, uncomment this file along with the example
# resource in cdk_test/cdk_test_stack.py
def test_sqs_queue_created():
app = core.App()
stack = CdkTestStack(app, "cdk-test")
template = assertions.Template.from_stack(stack)

# template.has_resource_properties("AWS::SQS::Queue", {
# "VisibilityTimeout": 300
# })
40 changes: 40 additions & 0 deletions tests/mock_stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from aws_cdk import aws_lambda
from aws_cdk import Stack
from constructs import Construct
from cdk_klayers import Klayers

class MockStack(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

global global_runtime
self.klayers = Klayers(
self,
python_version = global_runtime
)

def layer_version(self, package, layer_version="latest"):
return self.klayers.layer_version(self, package, layer_version)

@Stack.environment.setter
def environment(self, environment):
self.environemnt = environment

class MockStackNoRegion(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

self.klayers = Klayers(
self,
python_version = aws_lambda.Runtime.PYTHON_3_12,
region=kwargs['region']
)

def layer_version(self, package, layer_version="latest"):
return self.klayers.layer_version(self, package, layer_version)

@Stack.environment.setter
def environment(self, environment):
self.environemnt = environment

0 comments on commit 1715147

Please sign in to comment.