簡體   English   中英

如何模擬 AWS DynamoDB 服務?

[英]How to mock AWS DynamoDB service?

我的服務使用 AWS DynamoDB 作為依賴項。 我想編寫單元測試,但我不知道如何模擬 DynamoDB 服務。 有人可以幫我嗎?

您可以使用 moto python 庫來模擬 aws dynamodb,

https://github.com/splec/moto

moto 使用一個基於 python 裝飾器的簡單系統來描述 AWS 服務。 下面是一個例子:

import unittest
import boto3
from moto import mock_dynamodb2

class TestDynamo(unittest.TestCase):

    def setUp(self):
        pass

    @mock_dynamodb2
    def test_recoverBsaleAssociation(self):
        table_name = 'test'
        dynamodb = boto3.resource('dynamodb', 'us-east-1')

        table = dynamodb.create_table(
            TableName=table_name,
            KeySchema=[
                {
                    'AttributeName': 'key',
                    'KeyType': 'HASH'
                },
            ],
            AttributeDefinitions=[
                {
                    'AttributeName': 'key',
                    'AttributeType': 'S'
                },

            ],
            ProvisionedThroughput={
                'ReadCapacityUnits': 5,
                'WriteCapacityUnits': 5
            }
        )

        item = {}
        item['key'] = 'value'

        table.put_item(Item=item)

        table = dynamodb.Table(table_name)
        response = table.get_item(
            Key={
                'key': 'value'
            }
        )
        if 'Item' in response:
            item = response['Item']

        self.assertTrue("key" in item)
        self.assertEquals(item["key"], "value")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM