generated from amazon-archives/__template_MIT-0
-
Notifications
You must be signed in to change notification settings - Fork 1k
New Pattern Submission - Add Lambda Durable Functions testing pattern in TypeScript #2878
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
Open
agawanea
wants to merge
6
commits into
aws-samples:main
Choose a base branch
from
agawanea:lambda-durable-testing-typescript-sam
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
54be2c6
Add Lambda Durable Functions testing pattern in TypeScript
agawanea f0b9844
Merge branch 'aws-samples:main' into lambda-durable-testing-typescrip…
agawanea df844fe
Address PR feedback: fix feature naming, update Node.js to 24+, remov…
agawanea 9a49853
Fix TypeScript linting error: remove invalid 'region' parameter from …
agawanea 59dbb52
Fix TypeScript linting error and update test script
agawanea 8e6aadd
Add final pattern file
bfreiberg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| node_modules/ | ||
| .aws-sam/ | ||
| dist/ | ||
| coverage/ | ||
| *.log | ||
| .env | ||
| .DS_Store | ||
|
|
||
| # SAM | ||
| samconfig.toml |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| # Testing artifacts | ||
| tests/ | ||
| *.test.ts | ||
| *.test.js | ||
| jest.config.js | ||
| coverage/ | ||
|
|
||
| # Development files | ||
| node_modules/ | ||
| .git/ | ||
| .gitignore | ||
| README.md | ||
|
|
||
| # Build artifacts | ||
| dist/ | ||
| .aws-sam/ | ||
|
|
||
| # IDE | ||
| .vscode/ | ||
| .idea/ | ||
| *.swp | ||
| *.swo | ||
| .DS_Store |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| # Testing AWS Lambda Durable Functions in TypeScript | ||
|
|
||
| This pattern demonstrates comprehensive testing strategies for AWS Lambda Durable Functions using the Durable Execution SDK testing library. It covers local testing, cloud integration testing, and best practices for testing long-running workflows. | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-durable-testing-typescript-sam | ||
|
|
||
| Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. | ||
|
|
||
| ## Requirements | ||
|
|
||
| * [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. | ||
| * [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured | ||
| * [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) | ||
| * [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed | ||
| * [Node.js 22.x or later](https://nodejs.org/en/) installed | ||
|
|
||
| ## Deployment Instructions | ||
|
|
||
| 1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: | ||
| ``` | ||
| git clone https://github.com/aws-samples/serverless-patterns | ||
| ``` | ||
| 2. Change directory to the pattern directory: | ||
| ``` | ||
| cd lambda-durable-testing-typescript-sam | ||
| ``` | ||
| 3. Install dependencies: | ||
| ``` | ||
| npm install | ||
| ``` | ||
| 4. Run the test suite locally (no AWS credentials required): | ||
| ``` | ||
| npm test | ||
| ``` | ||
| 5. From the command line, use AWS SAM to build and deploy the AWS resources: | ||
| ``` | ||
| sam build | ||
| sam deploy --guided | ||
| ``` | ||
| 6. During the prompts: | ||
| * Enter a stack name | ||
| * Enter the desired AWS Region | ||
| * Allow SAM CLI to create IAM roles with the required permissions. | ||
|
|
||
| Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults. | ||
|
|
||
| 7. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing. | ||
|
|
||
| ## How it works | ||
|
|
||
| This pattern demonstrates five key testing scenarios for durable functions: | ||
|
|
||
| ### 1. Basic Workflow Testing (Order Processor) | ||
| Tests simple step operations and wait operations with time-skipping enabled for instant execution. | ||
|
|
||
| ### 2. Retry Logic Testing (Payment Processor) | ||
| Validates retry strategies, failure scenarios, and exhausting retry attempts with mocked external API calls. | ||
|
|
||
| ### 3. Callback Testing (Approval Workflow) | ||
| Demonstrates testing external event integration patterns, including callback sending and timeout handling. | ||
|
|
||
| ### 4. Parallel Operations Testing (Batch Processor) | ||
| Shows how to test concurrent execution patterns with independent operation tracking and result aggregation. | ||
|
|
||
| ### 5. Nested Functions Testing (Main + Child Workflow) | ||
| Validates function composition and orchestration using function invocation and registration. | ||
|
|
||
| ## Testing | ||
|
|
||
| ### Local Testing (No AWS Required) | ||
|
|
||
| Run all local tests: | ||
| ```bash | ||
| npm test | ||
| ``` | ||
|
|
||
| Run tests in watch mode: | ||
| ```bash | ||
| npm run test:watch | ||
| ``` | ||
|
|
||
| Run tests with coverage: | ||
| ```bash | ||
| npm run test:coverage | ||
| ``` | ||
|
|
||
| ### Cloud Integration Testing | ||
|
|
||
| After deployment, update the function names in `tests/cloud/` files with your deployed function names, then run: | ||
|
|
||
| ```bash | ||
| npm run test:cloud | ||
| ``` | ||
|
|
||
| Run all tests (local + cloud): | ||
| ```bash | ||
| npm run test:all | ||
| ``` | ||
|
|
||
| ## Example Test Output | ||
|
|
||
| ``` | ||
| PASS tests/order-processor.test.ts | ||
| Order Processor | ||
| ✓ should process order successfully (45ms) | ||
| ✓ should execute operations in correct order (32ms) | ||
|
|
||
| PASS tests/payment-processor.test.ts | ||
| Payment Processor | ||
| ✓ should succeed on first attempt (28ms) | ||
| ✓ should retry on failure (41ms) | ||
| ✓ should exhaust retries (55ms) | ||
|
|
||
| PASS tests/approval-workflow.test.ts | ||
| Approval Workflow | ||
| ✓ should timeout when no approval is received (38ms) | ||
|
|
||
| PASS tests/batch-processor.test.ts | ||
| Batch Processor | ||
| ✓ should process items in parallel (52ms) | ||
|
|
||
| PASS tests/main-workflow.test.ts | ||
| Main Workflow | ||
| ✓ should invoke child workflow (44ms) | ||
|
|
||
| Test Suites: 5 passed, 5 total | ||
| Tests: 8 passed, 8 total | ||
| ``` | ||
|
|
||
| ## Cleanup | ||
|
|
||
| 1. Delete the stack | ||
| ```bash | ||
| sam delete | ||
| ``` | ||
|
|
||
| ## Key Testing Patterns | ||
|
|
||
| This pattern demonstrates these essential testing practices: | ||
|
|
||
| 1. **Setup/Teardown**: Use `beforeAll` and `afterAll` for test environment configuration | ||
| 2. **Skip Time**: Enable `skipTime: true` for instant test execution without waiting | ||
| 3. **Operation Inspection**: Use `getOperation()` and `getOperationByIndex()` to verify execution flow | ||
| 4. **Mock External Dependencies**: Mock fetch and other external calls with Jest | ||
| 5. **Callback Simulation**: Use `getOperation().sendCallback()` for testing callbacks | ||
| 6. **Function Registration**: Use `registerDurableFunction()` for nested workflows | ||
|
|
||
| ## Best Practices | ||
|
|
||
| ✅ **DO:** | ||
| - Use `LocalDurableTestRunner` for fast local tests | ||
| - Enable `skipTime: true` to skip waits instantly | ||
| - Mock external API calls with Jest | ||
| - Test both success and failure scenarios | ||
| - Inspect operations to verify execution flow | ||
|
|
||
| ❌ **DON'T:** | ||
| - Run tests against real AWS services in unit tests | ||
| - Wait for actual timeouts in tests | ||
| - Skip testing error handling | ||
| - Forget to test retry logic | ||
|
|
||
| ---- | ||
| Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
|
||
| SPDX-License-Identifier: MIT-0 | ||
73 changes: 73 additions & 0 deletions
73
lambda-durable-testing-typescript-sam/example-pattern.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| { | ||
| "title": "Testing AWS Lambda Durable Functions in TypeScript", | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| "description": "Comprehensive testing strategies for AWS Lambda Durable Functions using local and cloud test runners with TypeScript", | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| "language": "TypeScript", | ||
| "level": "200", | ||
| "framework": "AWS SAM", | ||
| "introBox": { | ||
| "headline": "How it works", | ||
| "text": [ | ||
| "This pattern demonstrates comprehensive testing strategies for AWS Lambda Durable Functions using the Durable Execution SDK testing library.", | ||
| "It includes five key testing scenarios: basic workflows with wait operations, retry logic validation, callback testing for external events, parallel operations testing, and nested function composition.", | ||
| "The pattern uses LocalDurableTestRunner for fast local testing with time-skipping and CloudDurableTestRunner for integration testing against deployed functions.", | ||
| "All tests demonstrate best practices including operation inspection, mock external dependencies, callback simulation, and function registration for nested workflows." | ||
| ] | ||
| }, | ||
| "gitHub": { | ||
| "template": { | ||
| "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-durable-testing-typescript-sam", | ||
| "templateURL": "serverless-patterns/lambda-durable-testing-typescript-sam", | ||
| "projectFolder": "lambda-durable-testing-typescript-sam", | ||
| "templateFile": "template.yaml" | ||
| } | ||
| }, | ||
| "resources": { | ||
| "bullets": [ | ||
| { | ||
| "text": "AWS Lambda Durable Functions Documentation", | ||
| "link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html" | ||
| }, | ||
| { | ||
| "text": "Durable Execution SDK for JavaScript/TypeScript", | ||
| "link": "https://github.com/aws/aws-durable-execution-sdk-js" | ||
| }, | ||
| { | ||
| "text": "Durable Execution SDK Testing Library", | ||
| "link": "https://www.npmjs.com/package/@aws/durable-execution-sdk-js-testing" | ||
| }, | ||
| { | ||
| "text": "Testing AWS Lambda Durable Functions in TypeScript (Blog Post)", | ||
| "link": "https://dev.to/aws/testing-aws-lambda-durable-functions-in-typescript-5bj2" | ||
| } | ||
| ] | ||
| }, | ||
| "deploy": { | ||
| "text": [ | ||
| "sam build", | ||
| "sam deploy --guided" | ||
| ] | ||
| }, | ||
| "testing": { | ||
| "text": [ | ||
| "See the GitHub repo for detailed testing instructions." | ||
| ] | ||
| }, | ||
| "cleanup": { | ||
| "text": [ | ||
| "Delete the stack: <code>sam delete</code>." | ||
| ] | ||
| }, | ||
| "authors": [ | ||
| { | ||
| "name": "Abhishek Agawane", | ||
| "image": "https://drive.google.com/file/d/1E-5koDaKEaMUtOctX32I9TLwfh3kgpAq/view?usp=drivesdk", | ||
| "bio": "Abhishek Agawane is a Security Consultant at Amazon Web Services with more than 8 years of industry experience. He helps organizations architect resilient, secure, and efficient cloud environments, guiding them through complex challenges and large-scale infrastructure transformations. He has helped numerous organizations enhance their cloud operations through targeted optimizations, robust architectures, and best-practice implementations.", | ||
| "linkedin": "https://www.linkedin.com/in/agawabhi/" | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| }, | ||
| { | ||
| "name": "Eric Johnson", | ||
| "bio": "Principal Developer Advocate for Serverless Applications at AWS and is based in Northern Colorado. Eric is a fanatic about serverless and enjoys helping developers understand how serverless technologies introduces a major paradigm shift in how they approach building and running applications at massive scale with minimal administration overhead.", | ||
| "linkedin": "https://www.linkedin.com/in/singledigit/" | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| ] | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| export default { | ||
| preset: 'ts-jest/presets/default-esm', | ||
| testEnvironment: 'node', | ||
| extensionsToTreatAsEsm: ['.ts'], | ||
| moduleNameMapper: { | ||
| '^(\\.{1,2}/.*)\\.js$': '$1', | ||
| }, | ||
| transform: { | ||
| '^.+\\.tsx?$': [ | ||
| 'ts-jest', | ||
| { | ||
| useESM: true, | ||
| }, | ||
| ], | ||
| }, | ||
| testMatch: ['**/tests/**/*.test.ts'], | ||
| collectCoverageFrom: [ | ||
| 'src/**/*.ts', | ||
| '!src/**/*.d.ts', | ||
| ], | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| { | ||
| "name": "test-ts-validation", | ||
| "version": "1.0.0", | ||
| "description": "Validation project for durable functions testing blog", | ||
| "type": "module", | ||
| "scripts": { | ||
| "test": "jest --testPathIgnorePatterns=cloud", | ||
| "test:cloud": "AWS_PROFILE=private jest tests/cloud", | ||
agawanea marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| "test:all": "jest", | ||
| "test:watch": "jest --watch --testPathIgnorePatterns=cloud", | ||
| "test:coverage": "jest --coverage --testPathIgnorePatterns=cloud" | ||
| }, | ||
| "devDependencies": { | ||
| "@aws-sdk/credential-providers": "^3.940.0", | ||
| "@aws/durable-execution-sdk-js-testing": "latest", | ||
| "@types/jest": "^29.0.0", | ||
| "@types/node": "^20.0.0", | ||
| "esbuild": "^0.27.1", | ||
| "jest": "^29.0.0", | ||
| "ts-jest": "^29.0.0", | ||
| "typescript": "^5.0.0" | ||
| } | ||
| } | ||
16 changes: 16 additions & 0 deletions
16
lambda-durable-testing-typescript-sam/src/approval-workflow/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import { DurableContext, withDurableExecution } from '@aws/durable-execution-sdk-js'; | ||
|
|
||
| export const handler = withDurableExecution( | ||
| async (event: any, context: DurableContext) => { | ||
| const request = await context.step('create-request', async () => { | ||
| return { requestId: event.requestId, status: 'pending' }; | ||
| }); | ||
|
|
||
| try { | ||
| const approval = await context.waitForCallback('approval', 86400); | ||
| return { status: 'approved', approvedBy: approval.userId }; | ||
| } catch (error) { | ||
| return { status: 'timeout' }; | ||
| } | ||
| } | ||
| ); |
6 changes: 6 additions & 0 deletions
6
lambda-durable-testing-typescript-sam/src/approval-workflow/package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "type": "module", | ||
| "dependencies": { | ||
| "@aws/durable-execution-sdk-js": "latest" | ||
| } | ||
| } |
21 changes: 21 additions & 0 deletions
21
lambda-durable-testing-typescript-sam/src/batch-processor/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import { DurableContext, withDurableExecution } from '@aws/durable-execution-sdk-js'; | ||
|
|
||
| export const handler = withDurableExecution( | ||
| async (event: any, context: DurableContext) => { | ||
| await context.parallel( | ||
| 'process-items', | ||
| event.items.map((item: any, index: number) => | ||
| async (childContext: DurableContext) => { | ||
| return await childContext.step(`process-item-${index}`, async () => { | ||
| return { id: item.id, processed: true }; | ||
| }); | ||
| } | ||
| ) | ||
| ); | ||
|
|
||
| return { | ||
| total: event.items.length, | ||
| successful: event.items.length | ||
| }; | ||
| } | ||
| ); |
6 changes: 6 additions & 0 deletions
6
lambda-durable-testing-typescript-sam/src/batch-processor/package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "type": "module", | ||
| "dependencies": { | ||
| "@aws/durable-execution-sdk-js": "latest" | ||
| } | ||
| } |
10 changes: 10 additions & 0 deletions
10
lambda-durable-testing-typescript-sam/src/child-workflow/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| import { DurableContext, withDurableExecution } from '@aws/durable-execution-sdk-js'; | ||
|
|
||
| export const handler = withDurableExecution( | ||
| async (event: any, context: DurableContext) => { | ||
| const result = await context.step('child-step', async () => { | ||
| return { processed: event.data }; | ||
| }); | ||
| return result; | ||
| } | ||
| ); |
6 changes: 6 additions & 0 deletions
6
lambda-durable-testing-typescript-sam/src/child-workflow/package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "type": "module", | ||
| "dependencies": { | ||
| "@aws/durable-execution-sdk-js": "latest" | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.