【问题标题】:python 3: mock a method of the boto3 S3 clientpython 3:模拟boto3 S3客户端的方法
【发布时间】:2018-06-12 05:20:32
【问题描述】:

我想对一些调用boto3s3 客户端方法的代码进行单元测试。 我不能使用moto,因为这个特定的方法(put_bucket_lifecycle_configuration)还没有在moto 中实现。 我想模拟 S3 客户端并确保使用特定参数调用此方法。

我要测试的代码如下所示:

# sut.py
import boto3

class S3Bucket(object):
    def __init__(self, name, lifecycle_config):
        self.name = name
        self.lifecycle_config = lifecycle_config

    def create(self):
        client = boto3.client("s3") 
        client.create_bucket(Bucket=self.name)
        rules = # some code that computes rules from self.lifecycle_config
        # I want to test that `rules` is correct in the following call:
        client.put_bucket_lifecycle_configuration(Bucket=self.name, \
          LifecycleConfiguration={"Rules": rules})

def create_a_bucket(name):
    lifecycle_policy = # a dict with a bunch of key/value pairs
    bucket = S3Bucket(name, lifecycle_policy)
    bucket.create()
    return bucket

在我的测试中,我想调用create_a_bucket()(尽管直接实例化S3Bucket 也是一种选择)并确保使用正确的参数调用put_bucket_lifecycle_configuration

我已经搞砸了unittest.mockbotocore.stub.Stubber,但没有设法破解它。除非另有要求,否则我不会发布我的尝试,因为到目前为止它们还没有成功。

我愿意接受有关重组我正在尝试测试的代码以使其更易于测试的建议。

【问题讨论】:

    标签: python-3.x unit-testing mocking boto3 botocore


    【解决方案1】:

    让测试与以下内容一起工作,其中... 是预期传递给s3.put_bucket_lifecycle_configuration() 的其余参数。

    # test.py
    from unittest.mock import patch
    import unittest
    
    import sut
    
    class MyTestCase(unittest.TestCase):
        @patch("sut.boto3")
        def test_lifecycle_config(self, cli):
            s3 = cli.client.return_value
            sut.create_a_bucket("foo")
            s3.put_bucket_lifecycle_configuration.assert_called_once_with(Bucket="foo", ...)
    
    
    if __name__ == '__main__':
        unittest.main()
    

    【讨论】:

    • 感谢这条评论帮助我让 boto3 使用 @patch 进行模拟
    猜你喜欢
    • 2016-09-05
    • 2020-10-06
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2022-11-05
    相关资源
    最近更新 更多