我应该使用外部库还是使用外部库方法来模拟自定义类?

时间:2019-10-18 02:47:30

标签: python amazon-s3 boto3 python-unittest

我要按照以下定义测试get_list_of_objects()。在该函数中有self.bucket.objects.filter(),我想对其进行模拟以简单地返回我想要的内容。我认为,自定义类S3使用外部库这一事实使情况变得复杂。所以我不确定是否应该尝试模拟自定义类或外部库?

class S3:
    def __init__(self, bucket_name="bucket_name"):
        self.s3_resource = boto3.resource("s3")
        self.bucket = self.s3_resource.Bucket(bucket_name)
        self.s3_client = boto3.client("s3")

    def get_list_of_objects(self, key_prefix):
        key_list = []
        for object_summary in self.bucket.objects.filter(Prefix=key_prefix):
            key_list.append(object_summary.key)
        return key_list

尝试1:在这种情况下,我仅测试一下我分配给模拟方法的返回值的空字典是否转换为列表

import unittest
from unittest.mock import patch
from filepath.filename import S3

class TestS3Class(unittest.TestCase):
    """TestCase for storage/s3.py"""

    def setUp(self):
        """Creates an instance of the live S3 class for testing"""
        self.s3_instance = S3()

@patch('S3.self.bucket.object.filter')
    def test_get_list_of_objects(self, mock_objects_filter):
        mock_objects_filter.return_value = {}
        self.assertIsInstance(self.s3_instance.get_list_of_objects(key_prefix='key'), list)

哪个会导致错误:ModuleNotFoundError: No module named 'S3'

0 个答案:

没有答案