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 进行翻译

评论