模拟:客户端没有属性"get_object" [英] Mock: Client does not have the attribute 'get_object'

查看:76
本文介绍了模拟:客户端没有属性"get_object"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从boto3模块打补丁S3 get_object方法,但我不断收到以下错误

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'

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

这令人困惑,因为我能够成功修补boto3.client而不是boto3.client.get_object,即使boto3文档指出它是客户端的一种方法

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

这是我的代码

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

推荐答案

尝试模拟botocore.client.BaseClient._make_api_call.

Boto3客户端在运行时生成,因此它们的方法和属性取决于服务名称.基本的存根"客户端可能没有该方法.

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

还请注意,您需要知道要使用的操作的API调用是什么.

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

或者:使用 moto软件包,对于流行的服务来说相当不错像S3.

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

这篇关于模拟:客户端没有属性"get_object"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆