我有一个file/s3.py带有自定义类S3(大写)的python文件,它有方法get_list_of_objects()。在此方法中,有称为链接的 boto3 方法,self.bucket.objects.filter()如何模拟这些 boto3 方法?project_dir/file/s3.pyimport boto3import botocoreimport pandasclass S3: def __init__(self, bucket_name="my_bucket_of_stuff"): self.s3_resource = boto3.resource("s3") self.bucket = self.s3_resource.Bucket(bucket_name) self.s3_client = boto3.client("s3") self._bucket_name = bucket_name def get_list_of_objects(self, key_prefix): key_list = [] for object_summary in self.bucket.objects.filter(Prefix=key_prefix): #mock this bucket.objects.filter key_list.append(object_summary.key) return key_list到目前为止我的尝试 project_dir/tests/test.pyimport unittestimport file.s3from unittest.mock import patchfrom file.s3 import S3class TestS3Class(unittest.TestCase): """TestCase for storage/s3.py""" def setUp(self): """Creates an instance of the live S3 class for testing""" self.s3_test_client = S3() @patch('file.s3.S3.bucket') @patch('file.s3.S3.bucket.objects') @patch('file.s3.S3.bucket.objects.filter') def test_get_list_of_objects(self, mock_filter, mock_objects, mock_bucket): """Asserts retrieved dictionary of S3 objects is processed and returned as type list""" mock_bucket.return_value = None mock_objects.return_value = None mock_filter.return_value = {'key': 'value'} self.assertIsInstance(self.s3_test_client.get_list_of_objects(key_prefix='key'), list)这会产生错误ModuleNotFoundError: No module named 'file.s3.S3'; 'file.s3' is not a package我一定是弄乱了补丁的位置,但我不知道怎么弄。
1 回答
喵喵时光机
TA贡献1846条经验 获得超7个赞
我发现模拟 boto3.resource 类比尝试从我的自定义类中模拟这些方法更容易。因此,工作测试代码是:
@patch('boto3.resource')
def test_get_list_of_objects(self, mock_resource):
"""Asserts retrieved dictionary of S3 objects is processed and returned as type list"""
mock_resource.Bucket.return_value = {'key': 'value'}
self.assertIsInstance(self.s3_test_client.get_list_of_objects(key_prefix='key'), list)
我现在确实收到警告,但测试通过并正确失败。 ResourceWarning: unclosed <ssl.SSLSocket....
添加回答
举报
0/150
提交
取消