를 사용한 테스트 소개 sam local start-api - AWS Serverless Application Model

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

를 사용한 테스트 소개 sam local start-api

AWS Serverless Application Model Command Line Interface (AWS SAMCLI) sam local start-api 하위 명령을 사용하여 AWS Lambda 함수를 로컬에서 실행하고 로컬 HTTP 서버 호스트를 통해 테스트할 수 있습니다. 이 유형의 테스트는 Amazon API Gateway 엔드포인트에서 호출되는 Lambda 함수에 유용합니다.

sam local start-api를 사용하려면 다음을 완료하여 AWS SAM CLI를 설치합니다.

sam local start-api를 사용하기 전에 다음 사항에 대한 기본적인 이해를 하는 것이 좋습니다.

sam local start-api 사용하기

sam local start-api를 실행하면 AWS SAMCLI는 현재 작업 디렉터리가 프로젝트의 루트 디렉터리라고 가정합니다. AWS SAMCLI는 먼저 .aws-sam 하위 폴더에서 template.[yaml|yml] 파일을 찾습니다. 찾을 수 없는 경우 AWS SAMCLI는 현재 작업 디렉터리 내에서 template.[yaml|yml] 파일을 찾습니다.

로컬 HTTP 서버를 시작하려면
  1. 프로젝트 디렉터리에서 다음 명령을 실행합니다.

    $ sam local start-api <options>
  2. AWS SAMCLI는 Lambda 함수를 로컬 Docker 컨테이너에 빌드합니다. 그런 다음 HTTP 서버 엔드포인트의 로컬 주소를 출력합니다. 다음은 그 예제입니다.

    $ sam local start-api 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/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container Containers Initialization is done. Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET] You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you update your AWS SAM template 2023-04-12 14:41:05 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:3000
  3. 브라우저 또는 명령 프롬프트를 통해 Lambda 함수를 호출할 수 있습니다. 다음은 그 예제입니다.

    sam-app$ curl http://127.0.0.1:3000/hello {"message": "Hello world!"}%
  4. Lambda 함수 코드를 변경할 때는 다음 사항을 고려하여 로컬 HTTP 서버를 새로 고침합니다.

    • 애플리케이션에 .aws-sam 디렉터리가 없고 함수가 해석된 언어를 사용하는 경우, AWS SAMCLI는 새 컨테이너를 생성하고 호스팅하여 함수를 자동으로 업데이트합니다.

    • 애플리케이션에 .aws-sam 디렉터리가 있는 경우 함수를 업데이트하려면 sam build를 실행해야 합니다. 그런 다음 다시 sam local start-api를 실행하여 함수를 호스팅합니다.

    • 함수가 컴파일된 언어를 사용하거나 프로젝트에 복잡한 패키징 지원이 필요한 경우, 자체 빌드 솔루션을 실행하여 함수를 업데이트합니다. 그런 다음 다시 sam local start-api를 실행하여 함수를 호스팅합니다.

Lambda 권한 부여자를 사용하는 Lambda 함수

참고

AWS SAM CLI 버전 1.80.0의 새로운 기능 업그레이드하려면 AWS SAMCLI업그레이드 섹션을 참조하세요.

Lambda 권한 부여자를 사용하는 Lambda 함수의 경우 AWS SAMCLI는 Lambda 함수 엔드포인트를 호출하기 전에 Lambda 권한 부여자를 자동으로 호출합니다.

다음은 Lambda 권한 부여자를 사용하는 함수의 로컬 HTTP 서버를 시작하는 예제입니다.

$ sam local start-api 2023-04-17 15:02:13 Attaching import module proxy for analyzing dynamic imports AWS SAM CLI does not guarantee 100% fidelity between authorizers locally and authorizers deployed on AWS. Any application critical behavior should be validated thoroughly before deploying to production. Testing application behaviour against authorizers deployed on AWS can be done using the sam sync command. Mounting HelloWorldFunction at http://127.0.0.1:3000/authorized-request [GET] You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you update your AWS SAM template 2023-04-17 15:02:13 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:3000 2023-04-17 15:02:13 Press CTRL+C to quit

로컬 HTTP 서버를 통해 Lambda 함수 엔드포인트를 호출하면 AWS SAMCLI가 먼저 Lambda 권한 부여자를 호출합니다. 승인이 성공하면 AWS SAMCLI가 Lambda 함수 엔드포인트를 호출합니다. 다음은 그 예제입니다.

$ curl http://127.0.0.1:3000/authorized-request --header "header:my_token" {"message": "from authorizer"}% Invoking app.authorizer_handler (python3.8) Local image is up-to-date Using local image: public.ecr.aws/lambda/python:3.8-rapid-x86_64. Mounting /Users/.../sam-app/... as /var/task:ro,delegated, inside runtime container START RequestId: 38d3b472-a2c8-4ea6-9a77-9b386989bef0 Version: $LATEST END RequestId: 38d3b472-a2c8-4ea6-9a77-9b386989bef0 REPORT RequestId: 38d3b472-a2c8-4ea6-9a77-9b386989bef0 Init Duration: 1.08 ms Duration: 628.26 msBilled Duration: 629 ms Memory Size: 128 MB Max Memory Used: 128 MB Invoking app.request_handler (python3.8) Using local image: public.ecr.aws/lambda/python:3.8-rapid-x86_64. Mounting /Users/.../sam-app/... as /var/task:ro,delegated, inside runtime container START RequestId: fdc12255-79a3-4365-97e9-9459d06446ff Version: $LATEST END RequestId: fdc12255-79a3-4365-97e9-9459d06446ff REPORT RequestId: fdc12255-79a3-4365-97e9-9459d06446ff Init Duration: 0.95 ms Duration: 659.13 msBilled Duration: 660 ms Memory Size: 128 MB Max Memory Used: 128 MB No Content-Type given. Defaulting to 'application/json'. 2023-04-17 15:03:03 127.0.0.1 - - [17/Apr/2023 15:03:03] "GET /authorized-request HTTP/1.1" 200 -

옵션

컨테이너를 지속적으로 재사용하여 로컬 함수 호출 속도 높이기

기본적으로 AWS SAMCLI는 함수가 로컬 HTTP 서버를 통해 호출될 때마다 새 컨테이너를 만듭니다. --warm-containers 옵션을 사용하면 함수 호출에 컨테이너를 자동으로 재사용할 수 있습니다. 이렇게 하면 AWS SAMCLI가 로컬 호출을 위해 Lambda 함수를 준비하는 데 걸리는 시간이 단축됩니다. eager 또는 lazy 인수를 제공하여 이 옵션을 추가로 사용자 지정할 수 있습니다.

  • eager - 모든 함수의 컨테이너는 시작 시 로드되며 호출 이후에도 유지됩니다.

  • lazy - 컨테이너는 각 함수를 처음 호출할 때만 로드됩니다. 그런 다음 추가 호출 시에도 계속 유지됩니다.

다음은 그 예제입니다.

$ sam local start-api --warm-containers eager

--warm-containers를 사용하고 Lambda 함수 코드를 수정할 때:

  • 애플리케이션에 .aws-sam 디렉터리가 있는 경우 sam build를 실행하여 애플리케이션 빌드 아티팩트의 함수 코드를 업데이트합니다.

  • 코드 변경이 감지되면 AWS SAMCLI가 Lambda 함수 컨테이너를 자동으로 종료합니다.

  • 함수를 다시 호출하면 AWS SAMCLI가 자동으로 새 컨테이너를 생성합니다.

Lambda 함수에 사용할 컨테이너 이미지 지정

기본적으로 AWS SAMCLI는 Amazon Elastic Container Registry(Amazon ECR)에서 Lambda 기본 이미지를 사용하여 로컬에서 함수를 호출합니다. --invoke-image 옵션을 사용하여 사용자 지정 컨테이너 이미지를 참조할 수 있습니다. 다음은 그 예제입니다.

$ sam local start-api --invoke-image public.ecr.aws/sam/emu-python3.8

사용자 지정 컨테이너 이미지와 함께 사용할 함수를 지정할 수 있습니다. 다음은 그 예제입니다.

$ sam local start-api --invoke-image Function1=amazon/aws/sam-cli-emulation-image-python3.8

로컬에서 테스트할 템플릿 지정

AWS SAMCLI가 참조할 템플릿을 지정하려면 --template 옵션을 사용합니다. AWS SAMCLI그러면 해당 AWS SAM 템플릿과 해당 템플릿이 가리키는 리소스만 로드됩니다. 다음은 그 예제입니다.

$ sam local start-api --template myTemplate.yaml

Lambda 함수의 호스트 개발 환경 지정

기본적으로 sam local start-api 하위 명령은 IP 주소 127.0.0.1가 포함된 localhost를 사용하여 HTTP 서버를 생성합니다. 로컬 개발 환경이 로컬 컴퓨터와 격리되어 있는 경우 이러한 값을 사용자 지정할 수 있습니다.

--container-host 옵션을 사용하여 호스트를 지정합니다. 다음은 그 예제입니다.

$ sam local start-api --container-host host.docker.internal

--container-host-interface 옵션을 사용하여 컨테이너 포트가 바인딩해야 하는 호스트 네트워크의 IP 주소를 지정합니다. 다음은 그 예제입니다.

$ sam local start-api --container-host-interface 0.0.0.0

모범 사례

애플리케이션에 실행 중인 sam build.aws-sam 디렉터리가 있는 경우 함수 코드를 업데이트할 때마다 sam build를 실행해야 합니다. 그런 다음 sam local start-api를 실행하여 업데이트된 함수 코드를 로컬에서 테스트합니다.

로컬 테스트는 클라우드에 배포하기 전에 빠르게 개발하고 테스트할 수 있는 훌륭한 솔루션입니다. 하지만 로컬 테스트는 클라우드의 리소스 간 권한 등 모든 것을 검증하지는 않습니다. 가능한 한 클라우드에서 애플리케이션을 테스트하세요. 클라우드 테스트 워크플로의 속도를 높이려면 sam sync를 사용하는 것이 좋습니다.

자세히 알아보기

sam local start-api 옵션 목록은 sam local start-api 섹션을 참조하세요.