简体   繁体   中英

Using Mock in python for DynamoDB and Table

I want to test my python function which work is to extract all the data from the dynamoDB table

import boto3
import json
import constant as const
def connection():
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('file')
    response = table.scan()['Items']
    return response

And I am testing my above code using unit test. The code that I have written is given below

import unittest
from unittest import mock
import retrive
import constant
import boto3
class Test(unittest.TestCase):
    @mock.patch('boto3.resource')
    @mock.patch('boto3.resource.Table')
    @mock.patch('table.scan')
    def test_fetch_db_data(self, mock_boto3,mock_dynamo,mock_table):
        mock_boto3.return_value()
        mock_dynamo.return_value()
        mock_table = {'Items':'key'}
        result = retrive.connection()
        self.assertEqual('key', result)

but this give me an error ie ModuleNotFoundError: No module named 'table'

Take a look at this answer: How to mock AWS DynamoDB service? .

It's also possible to do what you try to do, but it will look something like:

@mock.patch('botocore.client.BaseClient._make_api_call', new=mock_function)

It is a more complicated way to do things than moto since you need to define mock_function which will generate mocked client responses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM