Mock: Client does not have the attribute 'get_object'

非 Y 不嫁゛ 提交于 2020-05-17 06:27:07

问题


I am trying to patch the S3 get_object method from the boto3 module but I keep getting the following error

AttributeError: <function client at 0x104570200> does not have the attribute 'get_object'

This is baffling because I am able to successfully patch the boto3.client but not boto3.client.get_object , even though the boto3 documentation states that it is one of the methods for the client

Here is my code

import boto3
from mock import patch

@pytest.mark.parametrize(
    'response, expected',
    [
        (200, True),
        (400,False)
    ]
)

@patch('boto3.client.get_object')
def test_get_file(mock, response, expected):
    mock.return_values = response
    test = get_file('portfolio/test.xls')
    assert test == expected

def get_file(self, key):
    S3 = boto3.client('s3')
    response = S3.get_object(bucket='portfolios', key=key)
    if response.status == 200:
        return response

    return False

回答1:


Try mocking botocore.client.BaseClient._make_api_call instead.

Boto3 clients are generated at runtime, and therefore their methods and attributes depend on service name. Base "stub" client likely doesn't have that method.

def mock_client(self, operation_name, kwarg) -> dict:
    if operation_name == "GetObject":
        # do the thing

...

@mock.patch('botocore.client.BaseClient._make_api_call', new=mock_client)
def test_your_stuff():
    # do the test

Also notice that you need to know what is the API call for the operation you want to use.

Alternatively: use moto package, it's fairly good for popular services like S3.



来源:https://stackoverflow.com/questions/61479794/mock-client-does-not-have-the-attribute-get-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!