Mocking Boto3 with pytest

Alex O'Callaghan

pytest로 Boto3 모킹하기

원문은 Alex O'Callaghan님이 에 게재했습니다. 이 블로그 구독하기

boto3 Python 라이브러리를 사용해 S3나 DynamoDB 같은 AWS 서비스와 상호작용하는 단위 테스트를 작성할 때는 해당 요청을 모킹해야 합니다. botocore Stubber를 사용하면 이를 구현할 수 있습니다.

DynamoDB에서 아이템을 조회하는 함수가 있다고 가정해 보겠습니다:

import boto3

def get_item(id):
  dynamodb = boto3.client("dynamodb")
  response = dynamodb.get_item(
    TableName="item_table",
    Key={"id": id}
  )
  return response.get("Item")

pytestbotocore.stub을 사용해 다음과 같이 요청을 모킹하는 단위 테스트를 작성할 수 있습니다:

import boto3
from botocore.stub import Stubber

from my_project import get_item

def test_get_item(mocker):
  dynamodb = boto3.client("dynamodb")
  stubber = Stubber(dynamodb)

  stubber.add_response(
    "get_item",
    {"hello": "world"},
    {"TableName": "item_table", "Key": {"id": "hello-world"}}
  )

  with mocker.patch(
    "boto3.client", return_value=dynamodb
  ):
    with stubber:
      result = get_item("hello-world")

      assert result["hello"] == "world"
  • add_response 호출은 get_item 호출에 대해 {"hello": "world"}라는 모의 응답을 추가하고, 전달된 인자가 예상과 일치하는지 함께 검증합니다.
  • with stubber:는 Stubber를 활성화합니다 — 모의 응답을 설정한 뒤 stubber.activate()를 호출해도 됩니다.

boto3.resource API와 함께 stubber를 사용할 수도 있습니다:

import boto3

def get_item(id):
  dynamodb = boto3.resource("dynamodb")
  table = dynamodb.Table("item_table")
  response = table.get_item(
    Key={"id": id}
  )
  return response.get("Item")
import boto3
from botocore.stub import Stubber

from my_project import get_item

def test_get_item(mocker):
  dynamodb = boto3.resource("dynamodb")
  stubber = Stubber(dynamodb.meta.client) # Access the client through `meta`

  stubber.add_response(
    "get_item",
    {"hello": "world"},
    {"TableName": "item_table", "Key": {"id": "hello-world"}}
  )

  with mocker.patch(
    "boto3.resource", return_value=dynamodb
  ):
    with stubber:
      result = get_item("hello-world")

      assert result["hello"] == "world"

더 읽어보기

이 글은 muse-spark-1.2-contributor 모델을 사용해 번역했습니다.

댓글