如何模拟从自定义类的自定义方法中调用的 boto3 方法?

我有一个file/s3.py带有自定义类S3(大写)的python文件,它有方法get_list_of_objects()。在此方法中,有称为链接的 boto3 方法,self.bucket.objects.filter()


如何模拟这些 boto3 方法?


project_dir/file/s3.py


import boto3

import botocore

import pandas



class 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.py


import unittest

import file.s3

from unittest.mock import patch

from file.s3 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_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


我一定是弄乱了补丁的位置,但我不知道怎么弄。


LEATH
浏览 95回答 1
1回答

喵喵时光机

我发现模拟 boto3.resource 类比尝试从我的自定义类中模拟这些方法更容易。因此,工作测试代码是:@patch('boto3.resource')&nbsp; &nbsp; def test_get_list_of_objects(self, mock_resource):&nbsp; &nbsp; &nbsp; &nbsp; """Asserts retrieved dictionary of S3 objects is processed and returned as type list"""&nbsp; &nbsp; &nbsp; &nbsp; mock_resource.Bucket.return_value = {'key': 'value'}&nbsp; &nbsp; &nbsp; &nbsp; self.assertIsInstance(self.s3_test_client.get_list_of_objects(key_prefix='key'), list)我现在确实收到警告,但测试通过并正确失败。 ResourceWarning: unclosed <ssl.SSLSocket....
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python