aws-samples / cdk-integ-tests-sample

MIT No Attribution
21 stars 2 forks source link

feat: add example for invoking a lambda function in integ tests #7

Closed mavogel closed 1 year ago

mavogel commented 1 year ago

Thank you for the great repo and example code coming with the blog post :)

Is it possible to add an example for a NodejsFunction in the functions/my-func-handler.ts with the content

import * as AWS from 'aws-sdk';
const SES = new AWS.SES({ region: 'eu-west-1' });
export const handler = async (event: any) => {
  // Note: this is NOT wrapped into another object... πŸ€”
  const k1 = event.k1 || 'k1-default';
  try {
    await SES.sendEmail({/*...*/}}).promise();
    return { resultCode: 200 };
  } catch (err) {
    return { resultCode: 500, err: err };
  }
};

and the integ.test.ts file containing

const myfunc = new NodejsFunction(stackUnderTest, 'my-func-handler', {
  entry: path.join(__dirname, 'functions', 'my-func-handler.ts'),
  runtime: lambda.Runtime.NODEJS_18_X,
  timeout: Duration.minutes(5),
  // works ... βœ…
  initialPolicy: [
    new iam.PolicyStatement({
      actions: [
        'ses:SendEmail',
      ],
      resources: ['*'],
    }),
  ],
});

// ...
const myAssertion = integ.assertions
.invokeFunction({
  functionName: myfunc.functionName,
  logType: LogType.TAIL,
  invocationType: InvocationType.REQUEST_RESPONE, // to run it synchronously
  payload: JSON.stringify({
    k1: 'v1',
    k2: 'v2',
  }),
}).expect(ExpectedResult.objectLike({
  // Note: it's wrapped into a Payload object πŸ€” Keep in mind while asserting
  Payload: {
    {resultCode:  200},
  }
}),
),

// πŸ›‘ whereas this does not work -> gives a 403 
// myAssertion.provider.addToRolePolicy({
//   Effect: 'Allow',
//   Action: [
//     'ses:SendEmail',
//   ],
//   Resource: [
//     '*',
//   ],
// });

This would be helpful. I found most code in the linked reference.

References

phch commented 1 year ago

Typically that NodejsFunction would go into your stack under test with the appropriate permissions for ses:SendEmail. Then in your integration test file you would write assertions in that folder.

This code repo is aligned to our blog example, so we will be keeping this example with the sample application flow.

mavogel commented 1 year ago

Hi @phch, would it be an option to extend / update the repo AND the corresponding blog post?