本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
測試簡介 sam local start-lambda
使用指 AWS Serverless Application Model 令行介面 (AWS SAMCLI) sam local start-lambda
子指令透過 AWS Command Line Interface (AWS CLI) 或 SDK 叫用您的 AWS Lambda 函數。此指令會啟動模擬 AWS Lambda的本機端點。
-
如需「」的簡介 AWS SAMCLI,請參閱什麼是 AWS SAMCLI?。
-
如需指
sam local start-lambda
令選項的清單,請參閱sam local start-lambda。
若要使用sam local start-lambda
,請完成下列 AWS SAMCLI步驟來安裝:
在使用之前sam local start-lambda
,我們建議對以下內容進行基本了解:
使用山姆本地啟動
當您執行時sam local start-lambda
,會 AWS SAMCLI假設您目前的工作目錄是專案的根目錄。 AWS SAMCLI將首先查找子template.[yaml|yml]
文件.aws-sam
夾中的文件。如果找不到, AWS SAMCLI會在您目前的工作目錄中尋找template.[yaml|yml]
檔案。
要使用山姆本地開始-拉姆達
-
從專案的根目錄中,執行下列命令:
$
sam local start-lambda
<options>
-
這會在本機Docker容器中 AWS SAMCLI建置您的 Lambda 函數。然後,它將本地地址輸出到您的 HTTP 服務器端點。以下是範例:
$
sam local start-lambda
Initializing the lambda functions containers. Local image is up-to-date Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64. Mounting /Users/.../sam-app/hello_world as /var/task:ro,delegated, inside runtime container Containers Initialization is done. Starting the Local Lambda Service. You can now invoke your Lambda Functions defined in your template through the endpoint. 2023-04-13 07:25:43 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:3001 2023-04-13 07:25:43 Press CTRL+C to quit -
使用 AWS CLI 或開發套件在本機叫用 Lambda 函數。
以下是使用下列項目的範例 AWS CLI:
$
aws lambda invoke --function-name
StatusCode: 200 (END)"HelloWorldFunction"
--endpoint-url"http://127.0.0.1:3001"
--no-verify-ssl out.txt以下是使用 in 的範 AWS SDK例Python:
import boto3 from botocore.config import Config from botocore import UNSIGNED lambda_client = boto3.client('lambda', endpoint_url="http://127.0.0.1:3001", use_ssl=False, verify=False, config=Config(signature_version=UNSIGNED, read_timeout=1, retries={'max_attempts': 0} ) ) lambda_client.invoke(FunctionName="HelloWorldFunction")
選項
指定範本
若要指定要參考 AWS SAMCLI的範本,請使用--template
選項。 AWS SAMCLI將只加載該 AWS SAM 模板及其指向的資源。以下是範例:
$
sam local start-lambda --template
myTemplate.yaml
最佳實務
如果您的應用程式有執行中的.aws-sam
目錄sam build
,請務必在sam build
每次更新函數程式碼時執行。然後,運行sam local start-lambda
以在本地測試更新的函數代碼。
本地測試是部署到雲之前快速開發和測試的絕佳解決方案。但是,本地測試不會驗證所有內容,例如雲中資源之間的權限。請盡可能在雲端中測試您的應用程式。我們建議您使sam sync用以加速雲端測試工作流程。
進一步了解
如需所有sam local start-lambda
選項的清單,請參閱sam local start-lambda。