Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add integration tests for remaining resources #209

Merged
merged 3 commits into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions integration/examples_nodejs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"testing"

"github.com/pulumi/pulumi/pkg/v3/testing/integration"
"github.com/stretchr/testify/assert"
)

func TestApiGateway(t *testing.T) {
Expand Down Expand Up @@ -82,6 +83,19 @@ func TestLogs(t *testing.T) {
integration.ProgramTest(t, &test)
}

func TestMisc(t *testing.T) {
test := getJSBaseOptions(t).
With(integration.ProgramTestOptions{
Dir: filepath.Join(getCwd(t), "misc-services"),
ExtraRuntimeValidation: func(t *testing.T, stack integration.RuntimeValidationStackInfo) {
repoName := stack.Outputs["repoName"].(string)
assert.Containsf(t, "testrepob5dda46f", repoName, "Expected repoName to contain 'testrepob5dda46f'; got %s", repoName)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we expect exactly this suffix? The b5dda46f is random, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the CDK generated suffix so it is a hash based on the construct tree. It will be the same everytime.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah and I guess it's fine anyways because there shouldn't be any change to the tree as those would essentially cause a replacement (because the name changes), right?
Thanks for the explanation!

},
})

integration.ProgramTest(t, &test)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A small assert on the outputs is appreciated!

}

func getJSBaseOptions(t *testing.T) integration.ProgramTestOptions {
base := getBaseOptions(t)
baseJS := base.With(integration.ProgramTestOptions{
Expand Down
3 changes: 3 additions & 0 deletions integration/misc-services/Pulumi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
name: pulumi-aws-misc
runtime: nodejs
description: misc integration test
94 changes: 94 additions & 0 deletions integration/misc-services/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import * as pulumi from '@pulumi/pulumi';
import * as events from 'aws-cdk-lib/aws-events';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as ssm from 'aws-cdk-lib/aws-ssm';
import * as ecr from 'aws-cdk-lib/aws-ecr';
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';
import * as pulumicdk from '@pulumi/cdk';
import { SecretValue } from 'aws-cdk-lib';
import { AwsCliLayer } from 'aws-cdk-lib/lambda-layer-awscli';

class MiscServicesStack extends pulumicdk.Stack {
public readonly repoName: pulumi.Output<string>;
constructor(app: pulumicdk.App, id: string, options?: pulumicdk.StackOptions) {
super(app, id, options);
const repo = new ecr.Repository(this, 'testrepo');
repo.grantPull(new iam.ServicePrincipal('lambda.amazonaws.com'));
this.repoName = this.asOutput(repo.repositoryName);

new ssm.StringParameter(this, 'testparam', {
stringValue: 'testvalue',
});

const eventBus = new events.EventBus(this, 'testbus');
eventBus.addToResourcePolicy(
new iam.PolicyStatement({
sid: 'testsid',
actions: ['events:PutEvents'],
principals: [new iam.AccountRootPrincipal()],
resources: [eventBus.eventBusArn],
}),
);

// This type of event bus policy is created for cross account access
new events.CfnEventBusPolicy(this, 'bus-policy', {
action: 'events:PutEvents',
statementId: 'statement-id',
principal: new iam.AccountRootPrincipal().accountId,
});
const connection = new events.Connection(this, 'testconn', {
authorization: events.Authorization.basic('user', SecretValue.unsafePlainText('password')),
});
new events.ApiDestination(this, ' testdest', {
endpoint: 'https://example.com',
connection,
});

const fn = new lambda.Function(this, 'testfn', {
runtime: lambda.Runtime.PYTHON_3_12,
handler: 'index.handler',
code: lambda.Code.fromInline('def handler(event, context): return {}'),
});
fn.addLayers(new AwsCliLayer(this, 'testlayer'));

const errors = fn.metricErrors();
const throttles = fn.metricThrottles();
const throttleAlarm = throttles.createAlarm(this, 'alarm-throttles', { threshold: 1, evaluationPeriods: 1 });
const errorsAlarm = errors.createAlarm(this, 'alarm-errors', { threshold: 1, evaluationPeriods: 1 });
const alarmRule = cloudwatch.AlarmRule.anyOf(throttleAlarm, errorsAlarm);
new cloudwatch.CompositeAlarm(this, 'compositealarm', {
alarmRule,
});

const dashboard = new cloudwatch.Dashboard(this, 'testdash');
dashboard.addWidgets(
new cloudwatch.GraphWidget({
left: [errors],
}),
);

new iam.User(this, 'User', {
groups: [new iam.Group(this, 'Group')],
managedPolicies: [
new iam.ManagedPolicy(this, 'ManagedPolicy', {
statements: [
new iam.PolicyStatement({
actions: ['s3:*'],
resources: ['*'],
effect: iam.Effect.DENY,
}),
],
}),
],
});
}
}

const app = new pulumicdk.App('app', (scope: pulumicdk.App) => {
const stack = new MiscServicesStack(scope, 'teststack');
return {
repoName: stack.repoName,
};
});
export const repoName = app.outputs['repoName'];
15 changes: 15 additions & 0 deletions integration/misc-services/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "pulumi-aws-cdk",
"devDependencies": {
"@types/node": "^10.0.0"
},
"dependencies": {
"@pulumi/aws": "^6.0.0",
"@pulumi/aws-native": "^1.5.0",
"@pulumi/cdk": "^0.5.0",
"@pulumi/pulumi": "^3.0.0",
"aws-cdk-lib": "2.149.0",
"constructs": "10.3.0",
"esbuild": "^0.24.0"
}
}
18 changes: 18 additions & 0 deletions integration/misc-services/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"strict": true,
"outDir": "bin",
"target": "es2019",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"experimentalDecorators": true,
"pretty": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"./*.ts"
]
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
}
},
"resolutions": {
"@pulumi/pulumi": "3.121.0",
"@pulumi/pulumi": "3.136.0",
"wrap-ansi": "7.0.0",
"string-width": "4.1.0"
},
Expand All @@ -30,7 +30,7 @@
"@pulumi/aws": "^6.32.0",
"@pulumi/aws-native": "^1.6.0",
"@pulumi/docker": "^4.5.0",
"@pulumi/pulumi": "3.121.0",
"@pulumi/pulumi": "3.136.0",
"@types/archiver": "^6.0.2",
"@types/fs-extra": "^11.0.4",
"@types/jest": "^29.5.2",
Expand Down
40 changes: 40 additions & 0 deletions src/aws-resource-mappings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,46 @@ export function mapToAwsResource(
);
}

case 'AWS::Events::EventBusPolicy': {
let props: aws.cloudwatch.EventBusPolicyArgs;
if (rawProps.Statement && (rawProps.Principal || rawProps.Action || rawProps.Condition)) {
throw new Error(
'EventBusPolicy args invalid. Only Statement or StatementId, Principal, Action, and Condition are allowed',
);
} else if (rawProps.Statement) {
props = {
policy: pulumi.jsonStringify({
Statement: [rawProps.Statement],
Version: '2012-10-17',
}),
eventBusName: rawProps.EventBusName,
};
} else {
const region = aws.getRegionOutput({}, options).name;
const partition = aws.getPartitionOutput({}, options).partition;
const busName = rawProps.EventBusName ?? 'default';
const arn = pulumi.interpolate`arn:${partition}:events:${region}:${rawProps.Principal}:event-bus/${busName}`;
props = {
policy: pulumi.jsonStringify({
Statement: [
{
Sid: rawProps.StatementId,
Principal: {
AWS: rawProps.Principal,
},
Action: rawProps.Action,
Effect: 'Allow',
Resource: arn,
Condition: rawProps.Condition,
},
],
Version: '2012-10-17',
}),
eventBusName: rawProps.EventBusName,
};
}
return new aws.cloudwatch.EventBusPolicy(logicalId, props, options);
}
default:
return undefined;
}
Expand Down
5 changes: 5 additions & 0 deletions src/cfn-resource-mappings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ export function mapToCfnResource(
// lowercase letters.
return new aws.s3.Bucket(logicalId.toLowerCase(), props, options);

case 'AWS::ECR::Repository':
// Lowercase the repository name to comply with the Repository resource's naming constraints, which only allow
// lowercase letters.
return new aws.ecr.Repository(logicalId.toLowerCase(), props, options);

// A couple of ApiGateway resources suffer from https://github.com/pulumi/pulumi-cdk/issues/173
// These are very popular resources so handling the workaround here since we can remove these
// manual mappings once the issue has been fixed without breaking users
Expand Down
70 changes: 67 additions & 3 deletions tests/aws-resource-mappings.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { mapToAwsResource } from '../src/aws-resource-mappings';
import * as route53 from 'aws-cdk-lib/aws-route53';
import * as aws from '@pulumi/aws';

jest.mock('@pulumi/aws', () => {
return {
getRegionOutput: jest.fn().mockImplementation(() => {
return {
name: 'us-east-1',
};
}),
getPartitionOutput: jest.fn().mockImplementation(() => {
return {
partition: 'aws',
};
}),
apigatewayv2: {
Integration: jest.fn().mockImplementation(() => {
return {};
Expand All @@ -19,6 +28,11 @@ jest.mock('@pulumi/aws', () => {
return {};
}),
},
cloudwatch: {
EventBusPolicy: jest.fn().mockImplementation(() => {
return {};
}),
},
iam: {
Policy: jest.fn().mockImplementation(() => {
return {};
Expand All @@ -41,11 +55,13 @@ jest.mock('@pulumi/aws', () => {
};
});

afterEach(() => {
afterAll(() => {
jest.resetAllMocks();
});

beforeAll(() => {});
beforeEach(() => {
jest.clearAllMocks();
});

describe('AWS Resource Mappings', () => {
test('maps iam.Policy', () => {
Expand Down Expand Up @@ -370,4 +386,52 @@ describe('AWS Resource Mappings', () => {
{},
);
});

test('successfully maps EventBusPolicy resource', () => {
// GIVEN
const cfnType = 'AWS::Events::EventBusPolicy';
const logicalId = 'my-resource';
const cfnProps = {
EventBusName: 'eventBus',
Action: 'events:PutEvents',
Principal: '123456789012',
StatementId: 'MyStatement',
};
// WHEN
mapToAwsResource(logicalId, cfnType, cfnProps, {});
// THEN
expect(aws.cloudwatch.EventBusPolicy).toHaveBeenCalledWith(
logicalId,
{
eventBusName: 'eventBus',
policy: expect.anything(),
},
{},
);
});

test('successfully maps EventBusPolicy resource when statement provided', () => {
// GIVEN
const cfnType = 'AWS::Events::EventBusPolicy';
const logicalId = 'my-resource';
const cfnProps = {
EventBusName: 'eventBus',
Statement: {
Effect: 'Allow',
Principal: '123456789012',
Action: 'events:PutEvents',
},
};
// WHEN
mapToAwsResource(logicalId, cfnType, cfnProps, {});
// THEN
expect(aws.cloudwatch.EventBusPolicy).toHaveBeenCalledWith(
logicalId,
{
eventBusName: 'eventBus',
policy: expect.anything(),
},
{},
);
});
});
Loading
Loading