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

feat(integ-tests): chain assertion api calls #22196

Merged
merged 5 commits into from
Sep 23, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import * as events from '@aws-cdk/aws-events';
import * as logs from '@aws-cdk/aws-logs';
import * as sqs from '@aws-cdk/aws-sqs';
import * as cdk from '@aws-cdk/core';
import { IntegTest, ExpectedResult } from '@aws-cdk/integ-tests';
import * as targets from '../../lib';
import { IntegTest, ExpectedResult, AssertionsProvider } from '@aws-cdk/integ-tests';
import { LogGroupTargetInput } from '../../lib';

const app = new cdk.App();
Expand Down Expand Up @@ -71,16 +71,15 @@ const putEvent = integ.assertions.awsApiCall('EventBridge', 'putEvents', {
},
],
});
const assertionProvider = putEvent.node.tryFindChild('SdkProvider') as AssertionsProvider;
assertionProvider.addPolicyStatementFromSdkCall('events', 'PutEvents');
putEvent.provider.addPolicyStatementFromSdkCall('events', 'PutEvents');

const logEvents = integ.assertions.awsApiCall('CloudWatchLogs', 'filterLogEvents', {
logGroupName: logGroup2.logGroupName,
startTime: putEventsDate,
limit: 1,
});

logEvents.node.addDependency(putEvent);
putEvent.next(logEvents);

logEvents.assertAtPath('events.0.message', ExpectedResult.stringLikeRegexp(expectedValue));

Expand Down
20 changes: 19 additions & 1 deletion packages/@aws-cdk/integ-tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ There are two main scenarios in which assertions are created.
- Part of an integration test using `integ-runner`

In this case you would create an integration test using the `IntegTest` construct and then make assertions using the `assert` property.
You should **not** utilize the assertion constructs directly, but should instead use the `methods` on `IntegTest.assert`.
You should **not** utilize the assertion constructs directly, but should instead use the `methods` on `IntegTest.assertions`.

```ts
declare const app: App;
Expand Down Expand Up @@ -410,3 +410,21 @@ describe.expect(ExpectedResult.objectLike({
}));
```

#### Chain ApiCalls

Sometimes it may be necessary to chain API Calls. Since each API call is its own resource, all you
need to do is add a dependency between the calls. There is an helper method `next` that can be used.

```ts
declare const integ: IntegTest;

integ.assertions.awsApiCall('S3', 'putObject', {
Bucket: 'my-bucket',
Key: 'my-key',
Body: 'helloWorld',
}).next(integ.assertions.awsApiCall('S3', 'getObject', {
Bucket: 'my-bucket',
Key: 'my-key',
}));
```

139 changes: 139 additions & 0 deletions packages/@aws-cdk/integ-tests/lib/assertions/api-call-base.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { CustomResource, Reference } from '@aws-cdk/core';
import { Construct, IConstruct } from 'constructs';
import { ExpectedResult } from './common';
import { AssertionsProvider } from './providers';

/**
* Represents an ApiCall
*/
export interface IApiCall extends IConstruct {
/**
* access the AssertionsProvider. This can be used to add additional IAM policies
* the the provider role policy
*
* @example
* declare const apiCall: AwsApiCall;
* apiCall.provider.addToRolePolicy({
* Effect: 'Allow',
* Action: ['s3:GetObject'],
* Resource: ['*'],
* });
*/
readonly provider: AssertionsProvider;

/**
* Returns the value of an attribute of the custom resource of an arbitrary
* type. Attributes are returned from the custom resource provider through the
* `Data` map where the key is the attribute name.
*
* @param attributeName the name of the attribute
* @returns a token for `Fn::GetAtt`. Use `Token.asXxx` to encode the returned `Reference` as a specific type or
* use the convenience `getAttString` for string attributes.
*/
getAtt(attributeName: string): Reference;

/**
* Returns the value of an attribute of the custom resource of type string.
* Attributes are returned from the custom resource provider through the
* `Data` map where the key is the attribute name.
*
* @param attributeName the name of the attribute
* @returns a token for `Fn::GetAtt` encoded as a string.
*/
getAttString(attributeName: string): string;

/**
* Assert that the ExpectedResult is equal
* to the result of the AwsApiCall
*
* @example
* declare const integ: IntegTest;
* const invoke = integ.assertions.invokeFunction({
* functionName: 'my-func',
* });
* invoke.expect(ExpectedResult.objectLike({ Payload: 'OK' }));
*/
expect(expected: ExpectedResult): void;

/**
* Assert that the ExpectedResult is equal
* to the result of the AwsApiCall at the given path.
*
* For example the SQS.receiveMessage api response would look
* like:
*
* If you wanted to assert the value of `Body` you could do
*
* @example
* const actual = {
* Messages: [{
* MessageId: '',
* ReceiptHandle: '',
* MD5OfBody: '',
* Body: 'hello',
* Attributes: {},
* MD5OfMessageAttributes: {},
* MessageAttributes: {}
* }]
* };
*
*
* declare const integ: IntegTest;
* const message = integ.assertions.awsApiCall('SQS', 'receiveMessage');
*
* message.assertAtPath('Messages.0.Body', ExpectedResult.stringLikeRegexp('hello'));
*/
assertAtPath(path: string, expected: ExpectedResult): void;

/**
* Allows you to chain IApiCalls. This adds an explicit dependency
* betweent the two resources.
*
* Returns the IApiCall provided as `next`
*
* @example
* declare const first: IApiCall;
* declare const second: IApiCall;
*
* first.next(second);
*/
next(next: IApiCall): IApiCall;
}

/**
* Base class for an ApiCall
*/
export abstract class ApiCallBase extends Construct implements IApiCall {
protected abstract readonly apiCallResource: CustomResource;
protected expectedResult?: string;
protected flattenResponse: string = 'false';
protected stateMachineArn?: string;

public abstract readonly provider: AssertionsProvider;

constructor(scope: Construct, id: string) {
super(scope, id);

}

public getAtt(attributeName: string): Reference {
this.flattenResponse = 'true';
return this.apiCallResource.getAtt(`apiCallResponse.${attributeName}`);
}

public getAttString(attributeName: string): string {
this.flattenResponse = 'true';
return this.apiCallResource.getAttString(`apiCallResponse.${attributeName}`);
}

public expect(expected: ExpectedResult): void {
this.expectedResult = expected.result;
}

public abstract assertAtPath(path: string, expected: ExpectedResult): void;

public next(next: IApiCall): IApiCall {
next.node.addDependency(this);
return next;
}
}
4 changes: 2 additions & 2 deletions packages/@aws-cdk/integ-tests/lib/assertions/common.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CustomResource } from '@aws-cdk/core';
import { IAwsApiCall } from './sdk';
import { IApiCall } from './api-call-base';

/**
* Represents the "actual" results to compare
Expand All @@ -17,7 +17,7 @@ export abstract class ActualResult {
/**
* Get the actual results from a AwsApiCall
*/
public static fromAwsApiCall(query: IAwsApiCall, attribute: string): ActualResult {
public static fromAwsApiCall(query: IApiCall, attribute: string): ActualResult {
return {
result: query.getAttString(attribute),
};
Expand Down
1 change: 1 addition & 0 deletions packages/@aws-cdk/integ-tests/lib/assertions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export * from './assertions';
export * from './providers';
export * from './common';
export * from './match';
export * from './api-call-base';
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Stack } from '@aws-cdk/core';
import { Construct, IConstruct, Node } from 'constructs';
import { IApiCall } from '../api-call-base';
import { EqualsAssertion } from '../assertions';
import { ExpectedResult, ActualResult } from '../common';
import { md5hash } from '../private/hash';
import { AwsApiCall, LambdaInvokeFunction, IAwsApiCall, LambdaInvokeFunctionProps } from '../sdk';
import { AwsApiCall, LambdaInvokeFunction, LambdaInvokeFunctionProps } from '../sdk';
import { IDeployAssert } from '../types';


Expand Down Expand Up @@ -49,15 +50,15 @@ export class DeployAssert extends Construct implements IDeployAssert {
Object.defineProperty(this, DEPLOY_ASSERT_SYMBOL, { value: true });
}

public awsApiCall(service: string, api: string, parameters?: any): IAwsApiCall {
public awsApiCall(service: string, api: string, parameters?: any): IApiCall {
return new AwsApiCall(this.scope, `AwsApiCall${service}${api}`, {
api,
service,
parameters,
});
}

public invokeFunction(props: LambdaInvokeFunctionProps): IAwsApiCall {
public invokeFunction(props: LambdaInvokeFunctionProps): IApiCall {
const hash = md5hash(this.scope.resolve(props));
return new LambdaInvokeFunction(this.scope, `LambdaInvoke${hash}`, props);
}
Expand Down
102 changes: 9 additions & 93 deletions packages/@aws-cdk/integ-tests/lib/assertions/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,93 +1,10 @@
import { ArnFormat, CfnResource, CustomResource, Lazy, Reference, Stack } from '@aws-cdk/core';
import { Construct, IConstruct } from 'constructs';
import { Construct } from 'constructs';
import { ApiCallBase } from './api-call-base';
import { EqualsAssertion } from './assertions';
import { ActualResult, ExpectedResult } from './common';
import { AssertionsProvider, SDK_RESOURCE_TYPE_PREFIX } from './providers';

/**
* Interface for creating a custom resource that will perform
* an API call using the AWS SDK
*/
export interface IAwsApiCall extends IConstruct {
/**
* access the AssertionsProvider. This can be used to add additional IAM policies
* the the provider role policy
*
* @example
* declare const apiCall: AwsApiCall;
* apiCall.provider.addToRolePolicy({
* Effect: 'Allow',
* Action: ['s3:GetObject'],
* Resource: ['*'],
* });
*/
readonly provider: AssertionsProvider;

/**
* Returns the value of an attribute of the custom resource of an arbitrary
* type. Attributes are returned from the custom resource provider through the
* `Data` map where the key is the attribute name.
*
* @param attributeName the name of the attribute
* @returns a token for `Fn::GetAtt`. Use `Token.asXxx` to encode the returned `Reference` as a specific type or
* use the convenience `getAttString` for string attributes.
*/
getAtt(attributeName: string): Reference;

/**
* Returns the value of an attribute of the custom resource of type string.
* Attributes are returned from the custom resource provider through the
* `Data` map where the key is the attribute name.
*
* @param attributeName the name of the attribute
* @returns a token for `Fn::GetAtt` encoded as a string.
*/
getAttString(attributeName: string): string;

/**
* Assert that the ExpectedResult is equal
* to the result of the AwsApiCall
*
* @example
* declare const integ: IntegTest;
* const invoke = integ.assertions.invokeFunction({
* functionName: 'my-func',
* });
* invoke.expect(ExpectedResult.objectLike({ Payload: 'OK' }));
*/
expect(expected: ExpectedResult): void;

/**
* Assert that the ExpectedResult is equal
* to the result of the AwsApiCall at the given path.
*
* For example the SQS.receiveMessage api response would look
* like:
*
* If you wanted to assert the value of `Body` you could do
*
* @example
* const actual = {
* Messages: [{
* MessageId: '',
* ReceiptHandle: '',
* MD5OfBody: '',
* Body: 'hello',
* Attributes: {},
* MD5OfMessageAttributes: {},
* MessageAttributes: {}
* }]
* };
*
*
* declare const integ: IntegTest;
* const message = integ.assertions.awsApiCall('SQS', 'receiveMessage');
*
* message.assertAtPath('Messages.0.Body', ExpectedResult.stringLikeRegexp('hello'));
*/
assertAtPath(path: string, expected: ExpectedResult): void;
}

/**
* Options to perform an AWS JavaScript V2 API call
*/
Expand Down Expand Up @@ -119,9 +36,8 @@ export interface AwsApiCallProps extends AwsApiCallOptions { }
* Construct that creates a custom resource that will perform
* a query using the AWS SDK
*/
export class AwsApiCall extends Construct implements IAwsApiCall {
private readonly sdkCallResource: CustomResource;
private flattenResponse: string = 'false';
export class AwsApiCall extends ApiCallBase {
protected readonly apiCallResource: CustomResource;
private readonly name: string;

public readonly provider: AssertionsProvider;
Expand All @@ -133,7 +49,7 @@ export class AwsApiCall extends Construct implements IAwsApiCall {
this.provider.addPolicyStatementFromSdkCall(props.service, props.api);
this.name = `${props.service}${props.api}`;

this.sdkCallResource = new CustomResource(this, 'Default', {
this.apiCallResource = new CustomResource(this, 'Default', {
serviceToken: this.provider.serviceToken,
properties: {
service: props.service,
Expand All @@ -146,23 +62,23 @@ export class AwsApiCall extends Construct implements IAwsApiCall {
});

// Needed so that all the policies set up by the provider should be available before the custom resource is provisioned.
this.sdkCallResource.node.addDependency(this.provider);
this.apiCallResource.node.addDependency(this.provider);
}

public getAtt(attributeName: string): Reference {
this.flattenResponse = 'true';
return this.sdkCallResource.getAtt(`apiCallResponse.${attributeName}`);
return this.apiCallResource.getAtt(`apiCallResponse.${attributeName}`);
}

public getAttString(attributeName: string): string {
this.flattenResponse = 'true';
return this.sdkCallResource.getAttString(`apiCallResponse.${attributeName}`);
return this.apiCallResource.getAttString(`apiCallResponse.${attributeName}`);
}

public expect(expected: ExpectedResult): void {
new EqualsAssertion(this, `AssertEquals${this.name}`, {
expected,
actual: ActualResult.fromCustomResource(this.sdkCallResource, 'apiCallResponse'),
actual: ActualResult.fromCustomResource(this.apiCallResource, 'apiCallResponse'),
});
}

Expand Down
Loading