SAM CLI cho phép test Lambda functions locally trước khi deploy.
| Command | Mô tả |
|---|---|
sam local invoke | Invoke Lambda function locally |
sam local start-api | Start local API Gateway endpoint |
sam local start-lambda | Start local Lambda endpoint |
sam local generate-event | Generate sample event payloads |
# Invoke function với event file
sam local invoke MyFunction -e event.json
# Start local API Gateway
sam local start-api
# Generate S3 event
sam local generate-event s3 put --bucket my-bucket --key my-key
| Level | Mô tả | Tools |
|---|---|---|
| Unit Test | Test individual functions/methods | pytest, Jest, JUnit |
| Integration Test | Test với AWS services thật | SAM local, LocalStack |
| End-to-End Test | Test toàn bộ flow | AWS CDK integ-tests |
# Python — sử dụng moto library
import boto3
from moto import mock_aws
@mock_aws
def test_dynamodb_put():
client = boto3.client("dynamodb", region_name="us-east-1")
client.create_table(
TableName="test-table",
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST"
)
client.put_item(
TableName="test-table",
Item={"id": {"S": "123"}, "name": {"S": "test"}}
)
response = client.get_item(
TableName="test-table",
Key={"id": {"S": "123"}}
)
assert response["Item"]["name"]["S"] == "test"
# template.yaml — SAM template
Globals:
Function:
Environment:
Variables:
TABLE_NAME: !Ref MyTable
STAGE: !Ref Stage
env.json file cho local testing với sam local invoke --env-vars env.jsonExam Tip: SAM CLI là tool chính để test Lambda locally. sam local invoke cho single invocation, sam local start-api cho API testing liên tục.