How to mock a boto3 client object/call

后端 未结 2 924
后悔当初
后悔当初 2021-02-14 20:45

I\'m trying to mock one particular boto3 function. My module, Cleanup, imports boto3. Cleanup also has a class, \"cleaner\". During init, cleaner creates an ec2 client:

2条回答
  •  遥遥无期
    2021-02-14 21:15

    I found a solution to this when trying to mock a different method for the S3 client

    import botocore
    from mock import patch
    import boto3
    
    orig = botocore.client.BaseClient._make_api_call
    
    def mock_make_api_call(self, operation_name, kwarg):
        if operation_name == 'DescribeTags':
            # Your Operation here!
            print(kwarg)
        return orig(self, operation_name, kwarg)
    
    with patch('botocore.client.BaseClient._make_api_call', new=mock_make_api_call):
        client = boto3.client('ec2')
        # Calling describe tags will perform your mocked operation e.g. print args
        e = client.describe_tags()
    

    Hope it helps :)

提交回复
热议问题