LoginSignup
0
0

More than 1 year has passed since last update.

DynamoDBをモック化する

Posted at

背景

ローカル環境でLambdaからDynamoDBへの処理をテストをしたかったので
motoを使ってDynamoDBをモックした。
忘れないように備忘録を残す

前提

python がインストール済み
pytest がインストール済み

インストール

pip install moto

実装

受け取ったIDをKeyとして登録データを返却する関数を実装

src/get.py

import boto3

dynamodb = boto3.resource('dynamodb',region_name='ap-northeast-1')
table = dynamodb.Table('messages')

def get_messages(id):
   return table.get_item(Key={'id': id})

テストコード

  • dynamodb_messages()にモック化するDB情報を記述する
  • モック化したいテスト関数の先頭に『@mock_dynamodb2』を記述する
  • dynamodb_messages()を実行する。
  • モック化したDBへの書き込み、取得が可能になる
import boto3
from moto import mock_dynamodb2
import importlib


@mock_dynamodb2
def dynamodb_messages():
    dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-1')
    table = dynamodb.create_table(
        TableName='messages',
        KeySchema=[
            {
                'AttributeName': 'id',
                'KeyType': 'HASH'
            }
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'id',
                'AttributeType': 'S'
            },
        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 10,
            'WriteCapacityUnits': 10
        }
    )
    return table


@mock_dynamodb2
def test_get_messages():

    table = dynamodb_messages()
    item = {
        'id': '1',
        'message': 'hello',
    }
    table.put_item(Item=item)
    module = importlib.import_module(".get", ".src")
    res = module.get_messages(1)

    assert item == res.get("Item")

ローカル上でDBのテストが可能となる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0