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")

botocore.stubを使ってリクエストをモックするpytestのユニットテストは、次のように書けます:

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()を呼び出すこともできます

stubberはboto3.resource APIでも利用できます:

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」を使用して翻訳されました。

コメント