feat(cloudFormation): support AWS::Serverless-2016-10-31 SAM Transform in CloudFormation (#1012)

* feat: support AWS::Serverless-2016-10-31 SAM Transform in CloudFormation

* fix: address review feedback for SAM transform

- Skip IAM role generation when explicit Role ARN is provided
- Add DeleteStack cleanup in @AfterEach to prevent IAM role leakage
- Make SamTransformProcessor a field on CloudFormationService
- Remove redundant DependsOn on Lambda (implicit via Fn::GetAtt)
- Add BillingMode: PAY_PER_REQUEST to SimpleTable expansion
- Reduce verbose inline comments to match project style
- Add assertion that explicit Role skips role resource creation

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Dixit R Jain <dixitrjain@Mac.lan>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-05-27 18:30:18 -05:00
1 parent 25d6988950
commit bd6e7795f8
4 files changed
+1410

No files matched your search

@@ -0,0 +1,596 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
@QuarkusTest
class SamTransformIntegrationTest {
private final List<String> stacksToDelete = new ArrayList<>();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@AfterEach
void deleteStacks() {
for (String stackName : stacksToDelete) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/");
}
stacksToDelete.clear();
}
@Test
void samFunction_withInlineCode_createsLambdaAndRole() {
String stackName = "sam-hello-stack";
stacksToDelete.add(stackName);
String template = """
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
HelloFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-hello-func
Handler: index.handler
Runtime: nodejs22.x
InlineCode: |
exports.handler = async () => ({ statusCode: 200, body: 'ok' });
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.when()
.get("/2015-03-31/functions/sam-hello-func")
.then()
.statusCode(200)
.body("Configuration.FunctionName", equalTo("sam-hello-func"))
.body("Configuration.Handler", equalTo("index.handler"))
.body("Configuration.Runtime", equalTo("nodejs22.x"));
String resourcesXml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
assertThat(resourcesXml, containsString("<ResourceType>AWS::Lambda::Function</ResourceType>"));
assertThat(resourcesXml, containsString("<ResourceType>AWS::IAM::Role</ResourceType>"));
assertThat(resourcesXml, not(containsString("AWS::Serverless::Function")));
}
@Test
void samFunction_withExplicitRole_skipsRoleGeneration() {
String stackName = "sam-explicit-role-stack";
stacksToDelete.add(stackName);
String template = """
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyFunc:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-explicit-role-func
Handler: index.handler
Runtime: nodejs20.x
InlineCode: "exports.handler = async () => ({});"
Role: arn:aws:iam::000000000000:role/my-existing-role
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.when()
.get("/2015-03-31/functions/sam-explicit-role-func")
.then()
.statusCode(200)
.body("Configuration.FunctionName", equalTo("sam-explicit-role-func"))
.body("Configuration.Role", equalTo("arn:aws:iam::000000000000:role/my-existing-role"));
// Verify no IAM role was created (only Lambda, no Role resource)
String resourcesXml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
assertThat(resourcesXml, containsString("<ResourceType>AWS::Lambda::Function</ResourceType>"));
assertThat(resourcesXml, not(containsString("<ResourceType>AWS::IAM::Role</ResourceType>")));
}
@Test
void samFunction_withEnvironmentAndTimeout() {
String stackName = "sam-configured-stack";
stacksToDelete.add(stackName);
String template = """
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
ConfiguredFunc:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-configured-func
Handler: app.handler
Runtime: python3.12
InlineCode: "def handler(event, context): return {'statusCode': 200}"
Timeout: 30
MemorySize: 256
Environment:
Variables:
TABLE_NAME: my-table
STAGE: local
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.when()
.get("/2015-03-31/functions/sam-configured-func")
.then()
.statusCode(200)
.body("Configuration.FunctionName", equalTo("sam-configured-func"))
.body("Configuration.Handler", equalTo("app.handler"))
.body("Configuration.Runtime", equalTo("python3.12"))
.body("Configuration.Timeout", equalTo(30))
.body("Configuration.MemorySize", equalTo(256))
.body("Configuration.Environment.Variables.TABLE_NAME", equalTo("my-table"))
.body("Configuration.Environment.Variables.STAGE", equalTo("local"));
}
@Test
void samSimpleTable_createsDynamoDbTable() {
String stackName = "sam-table-stack";
stacksToDelete.add(stackName);
String template = """
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyTable:
Type: AWS::Serverless::SimpleTable
Properties:
TableName: sam-simple-table
PrimaryKey:
Name: userId
Type: String
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.header("X-Amz-Target", "DynamoDB_20120810.DescribeTable")
.contentType("application/x-amz-json-1.0")
.body("""
{"TableName": "sam-simple-table"}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Table.TableName", equalTo("sam-simple-table"))
.body("Table.KeySchema[0].AttributeName", equalTo("userId"))
.body("Table.KeySchema[0].KeyType", equalTo("HASH"));
String resourcesXml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
assertThat(resourcesXml, containsString("<ResourceType>AWS::DynamoDB::Table</ResourceType>"));
assertThat(resourcesXml, not(containsString("AWS::Serverless::SimpleTable")));
}
@Test
void samApi_createsApiGatewayResources() {
String stackName = "sam-api-stack";
stacksToDelete.add(stackName);
String template = """
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
Name: sam-test-api
StageName: dev
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
String resourcesXml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
assertThat(resourcesXml, containsString("<ResourceType>AWS::ApiGateway::RestApi</ResourceType>"));
assertThat(resourcesXml, not(containsString("AWS::Serverless::Api")));
}
@Test
void samFunction_withCodeUri_s3Reference() {
String stackName = "sam-s3code-stack";
stacksToDelete.add(stackName);
given()
.when()
.put("/sam-code-bucket")
.then()
.statusCode(200);
byte[] zipBytes = buildHandlerZip();
given()
.contentType("application/zip")
.body(zipBytes)
.when()
.put("/sam-code-bucket/app.zip")
.then()
.statusCode(200);
String template = """
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
S3Func:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-s3code-func
Handler: index.handler
Runtime: nodejs20.x
CodeUri: s3://sam-code-bucket/app.zip
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.when()
.get("/2015-03-31/functions/sam-s3code-func")
.then()
.statusCode(200)
.body("Configuration.FunctionName", equalTo("sam-s3code-func"));
}
@Test
void samMixedTemplate_withStandardAndSamResources() {
String stackName = "sam-mixed-stack";
stacksToDelete.add(stackName);
String template = """
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: sam-mixed-queue
ProcessorFunc:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-mixed-func
Handler: index.handler
Runtime: nodejs20.x
InlineCode: "exports.handler = async (e) => ({});"
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueUrl")
.formParam("QueueName", "sam-mixed-queue")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("sam-mixed-queue"));
given()
.when()
.get("/2015-03-31/functions/sam-mixed-func")
.then()
.statusCode(200)
.body("Configuration.FunctionName", equalTo("sam-mixed-func"));
}
@Test
void templateWithoutTransform_isNotAffected() {
String stackName = "no-transform-stack";
stacksToDelete.add(stackName);
String template = """
{
"Resources": {
"MyQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "no-transform-queue"
}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueUrl")
.formParam("QueueName", "no-transform-queue")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("no-transform-queue"));
}
@Test
void samFunction_viaChangeSet_createsLambda() {
String stackName = "sam-changeset-stack";
stacksToDelete.add(stackName);
String template = """
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
CsFunc:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-changeset-func
Handler: index.handler
Runtime: nodejs20.x
InlineCode: "exports.handler = async () => ({});"
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "sam-cs-1")
.formParam("ChangeSetType", "CREATE")
.formParam("TemplateBody", template)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<Id>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ExecuteChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "sam-cs-1")
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.when()
.get("/2015-03-31/functions/sam-changeset-func")
.then()
.statusCode(200)
.body("Configuration.FunctionName", equalTo("sam-changeset-func"));
}
private static byte[] buildHandlerZip() {
try {
var baos = new java.io.ByteArrayOutputStream();
try (var zos = new java.util.zip.ZipOutputStream(baos)) {
zos.putNextEntry(new java.util.zip.ZipEntry("index.js"));
zos.write("exports.handler=async(e)=>({statusCode:200})".getBytes(java.nio.charset.StandardCharsets.UTF_8));
zos.closeEntry();
}
return baos.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,398 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for the SAM Transform processor logic.
*/
class SamTransformProcessorTest {
private ObjectMapper objectMapper;
private SamTransformProcessor processor;
@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
processor = new SamTransformProcessor(objectMapper);
}
@Test
void hasSamTransform_withStringTransform() throws Exception {
JsonNode template = objectMapper.readTree("""
{"Transform": "AWS::Serverless-2016-10-31", "Resources": {}}
""");
assertTrue(processor.hasSamTransform(template));
}
@Test
void hasSamTransform_withArrayTransform() throws Exception {
JsonNode template = objectMapper.readTree("""
{"Transform": ["AWS::Serverless-2016-10-31", "AWS::Other"], "Resources": {}}
""");
assertTrue(processor.hasSamTransform(template));
}
@Test
void hasSamTransform_withoutTransform() throws Exception {
JsonNode template = objectMapper.readTree("""
{"Resources": {"MyBucket": {"Type": "AWS::S3::Bucket"}}}
""");
assertFalse(processor.hasSamTransform(template));
}
@Test
void hasSamTransform_withDifferentTransform() throws Exception {
JsonNode template = objectMapper.readTree("""
{"Transform": "AWS::Include", "Resources": {}}
""");
assertFalse(processor.hasSamTransform(template));
}
@Test
void expandSamTemplate_functionWithInlineCode() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"InlineCode": "exports.handler = async () => ({});"
}
}
}
}
""");
JsonNode expanded = processor.expandSamTemplate(template);
// Transform should be removed
assertTrue(expanded.path("Transform").isMissingNode());
// Should have Lambda function and IAM role
JsonNode resources = expanded.path("Resources");
assertTrue(resources.has("MyFunc"));
assertTrue(resources.has("MyFuncRole"));
assertEquals("AWS::Lambda::Function", resources.path("MyFunc").path("Type").asText());
assertEquals("AWS::IAM::Role", resources.path("MyFuncRole").path("Type").asText());
// Lambda should have ZipFile code from InlineCode
JsonNode lambdaProps = resources.path("MyFunc").path("Properties");
assertEquals("index.handler", lambdaProps.path("Handler").asText());
assertEquals("nodejs20.x", lambdaProps.path("Runtime").asText());
assertEquals("exports.handler = async () => ({});",
lambdaProps.path("Code").path("ZipFile").asText());
// Role should reference the generated role via Fn::GetAtt
JsonNode roleRef = lambdaProps.path("Role");
assertTrue(roleRef.has("Fn::GetAtt"));
assertEquals("MyFuncRole", roleRef.path("Fn::GetAtt").get(0).asText());
assertEquals("Arn", roleRef.path("Fn::GetAtt").get(1).asText());
}
@Test
void expandSamTemplate_functionWithExplicitRole() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"InlineCode": "code",
"Role": "arn:aws:iam::123456789012:role/my-role"
}
}
}
}
""");
JsonNode expanded = processor.expandSamTemplate(template);
JsonNode resources = expanded.path("Resources");
JsonNode lambdaProps = resources.path("MyFunc").path("Properties");
// Should use the explicit role ARN
assertEquals("arn:aws:iam::123456789012:role/my-role", lambdaProps.path("Role").asText());
// Should NOT create a generated role resource
assertFalse(resources.has("MyFuncRole"));
}
@Test
void expandSamTemplate_functionWithS3CodeUri() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"CodeUri": "s3://my-bucket/code.zip"
}
}
}
}
""");
JsonNode expanded = processor.expandSamTemplate(template);
JsonNode code = expanded.path("Resources").path("MyFunc").path("Properties").path("Code");
assertEquals("my-bucket", code.path("S3Bucket").asText());
assertEquals("code.zip", code.path("S3Key").asText());
}
@Test
void expandSamTemplate_functionWithCodeUriObject() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"CodeUri": {
"Bucket": "my-bucket",
"Key": "path/to/code.zip",
"Version": "abc123"
}
}
}
}
}
""");
JsonNode expanded = processor.expandSamTemplate(template);
JsonNode code = expanded.path("Resources").path("MyFunc").path("Properties").path("Code");
assertEquals("my-bucket", code.path("S3Bucket").asText());
assertEquals("path/to/code.zip", code.path("S3Key").asText());
assertEquals("abc123", code.path("S3ObjectVersion").asText());
}
@Test
void expandSamTemplate_simpleTable() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyTable": {
"Type": "AWS::Serverless::SimpleTable",
"Properties": {
"TableName": "my-table",
"PrimaryKey": {
"Name": "pk",
"Type": "String"
}
}
}
}
}
""");
JsonNode expanded = processor.expandSamTemplate(template);
JsonNode resources = expanded.path("Resources");
assertEquals("AWS::DynamoDB::Table", resources.path("MyTable").path("Type").asText());
JsonNode tableProps = resources.path("MyTable").path("Properties");
assertEquals("my-table", tableProps.path("TableName").asText());
assertEquals("pk", tableProps.path("KeySchema").get(0).path("AttributeName").asText());
assertEquals("HASH", tableProps.path("KeySchema").get(0).path("KeyType").asText());
assertEquals("pk", tableProps.path("AttributeDefinitions").get(0).path("AttributeName").asText());
assertEquals("S", tableProps.path("AttributeDefinitions").get(0).path("AttributeType").asText());
assertEquals("PAY_PER_REQUEST", tableProps.path("BillingMode").asText());
}
@Test
void expandSamTemplate_simpleTableWithDefaultKey() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyTable": {
"Type": "AWS::Serverless::SimpleTable",
"Properties": {
"TableName": "default-key-table"
}
}
}
}
""");
JsonNode expanded = processor.expandSamTemplate(template);
JsonNode tableProps = expanded.path("Resources").path("MyTable").path("Properties");
// Default key should be "id" of type "S"
assertEquals("id", tableProps.path("KeySchema").get(0).path("AttributeName").asText());
assertEquals("S", tableProps.path("AttributeDefinitions").get(0).path("AttributeType").asText());
}
@Test
void expandSamTemplate_api() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyApi": {
"Type": "AWS::Serverless::Api",
"Properties": {
"Name": "test-api",
"StageName": "prod"
}
}
}
}
""");
JsonNode expanded = processor.expandSamTemplate(template);
JsonNode resources = expanded.path("Resources");
// Should create RestApi, Deployment, and Stage
assertEquals("AWS::ApiGateway::RestApi", resources.path("MyApi").path("Type").asText());
assertEquals("AWS::ApiGateway::Deployment", resources.path("MyApiDeployment").path("Type").asText());
assertEquals("AWS::ApiGateway::Stage", resources.path("MyApiStage").path("Type").asText());
// Stage should have the specified name
assertEquals("prod",
resources.path("MyApiStage").path("Properties").path("StageName").asText());
}
@Test
void expandSamTemplate_mixedResources() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {"BucketName": "my-bucket"}
},
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"InlineCode": "code"
}
}
}
}
""");
JsonNode expanded = processor.expandSamTemplate(template);
JsonNode resources = expanded.path("Resources");
// Standard resource should be preserved
assertEquals("AWS::S3::Bucket", resources.path("MyBucket").path("Type").asText());
assertEquals("my-bucket", resources.path("MyBucket").path("Properties").path("BucketName").asText());
// SAM resource should be expanded
assertEquals("AWS::Lambda::Function", resources.path("MyFunc").path("Type").asText());
assertTrue(resources.has("MyFuncRole"));
}
@Test
void expandSamTemplate_noTransform_returnsUnchanged() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {"BucketName": "my-bucket"}
}
}
}
""");
JsonNode result = processor.expandSamTemplate(template);
assertEquals(template, result);
}
@Test
void expandSamTemplate_functionWithEnvironmentAndTimeout() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "app.handler",
"Runtime": "python3.12",
"InlineCode": "def handler(e,c): pass",
"Timeout": 30,
"MemorySize": 512,
"Environment": {
"Variables": {
"TABLE": "my-table"
}
}
}
}
}
}
""");
JsonNode expanded = processor.expandSamTemplate(template);
JsonNode lambdaProps = expanded.path("Resources").path("MyFunc").path("Properties");
assertEquals(30, lambdaProps.path("Timeout").asInt());
assertEquals(512, lambdaProps.path("MemorySize").asInt());
assertEquals("my-table", lambdaProps.path("Environment").path("Variables").path("TABLE").asText());
}
@Test
void expandSamTemplate_functionWithSqsEvent() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"InlineCode": "code",
"Events": {
"SqsTrigger": {
"Type": "SQS",
"Properties": {
"Queue": "arn:aws:sqs:us-east-1:123456789012:my-queue",
"BatchSize": 10
}
}
}
}
}
}
}
""");
JsonNode expanded = processor.expandSamTemplate(template);
JsonNode resources = expanded.path("Resources");
// Should create an EventSourceMapping
assertTrue(resources.has("MyFuncSqsTrigger"));
assertEquals("AWS::Lambda::EventSourceMapping",
resources.path("MyFuncSqsTrigger").path("Type").asText());
JsonNode esmProps = resources.path("MyFuncSqsTrigger").path("Properties");
assertEquals("MyFunc", esmProps.path("FunctionName").path("Ref").asText());
assertEquals("arn:aws:sqs:us-east-1:123456789012:my-queue",
esmProps.path("EventSourceArn").asText());
assertEquals(10, esmProps.path("BatchSize").asInt());
}
}