我有一個(gè)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)這會(huì)產(chǎn)生錯(cuò)誤ModuleNotFoundError: No module named 'file.s3.S3'; 'file.s3' is not a package我一定是弄亂了補(bǔ)丁的位置,但我不知道怎么弄。
1 回答

喵喵時(shí)光機(jī)
TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
我發(fā)現(xiàn)模擬 boto3.resource 類比嘗試從我的自定義類中模擬這些方法更容易。因此,工作測(cè)試代碼是:
@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)
我現(xiàn)在確實(shí)收到警告,但測(cè)試通過并正確失敗。 ResourceWarning: unclosed <ssl.SSLSocket....
添加回答
舉報(bào)
0/150
提交
取消