use*_*284 2 mocking python-3.x boto3
我正在尝试从 boto3 模块修补 S3get_object
方法,但我不断收到以下错误
AttributeError: <function client at 0x104570200> does not have the attribute 'get_object'
这令人困惑,因为我能够成功修补boto3.client
但不能boto3.client.get_object
,即使 boto3 文档声明它是客户端的方法之一
这是我的代码
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
Run Code Online (Sandbox Code Playgroud)
尝试嘲笑botocore.client.BaseClient._make_api_call
。
Boto3 客户端是在运行时生成的,因此它们的方法和属性取决于服务名称。基础“存根”客户端可能没有该方法。
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
Run Code Online (Sandbox Code Playgroud)
另请注意,您需要知道您要使用的操作的 API 调用是什么。
或者:使用moto 包,它对于 S3 等流行服务相当好。
归档时间: |
|
查看次数: |
5474 次 |
最近记录: |