我正在编写一些代码,这些代码将通过boto3与API进行交互,我正在进行的调用有很大的响应负载,需要一段时间才能处理,在开发过程中测试代码变得非常令人沮丧和不切实际。对于我来说,缓存特定api调用响应的最实际方法是什么,如下面的方法?
#!/usr/bin/python3.6
import boto3
client_cw = boto3.client('cloudwatch')
paginator = client_cw.get_paginator('describe_alarms')
for response in paginator.paginate():
print(response)任何帮助都将不胜感激。
发布于 2019-08-14 23:39:37
对于使用unittest的mock功能来说,这是一个很好的情况。这允许您重新定义整个对象或对象的特定行为。使用这种方法的解决方案有两部分:
get_paginator()函数定义自定义行为,因此您将模拟boto3.client.get_paginator()方法以返回一个简单的自定义分页器类。paginate(),当该方法被调用时,它应该返回一个硬编码的分页列表( JSON格式),该列表反映了您希望AWS返回的任何内容。以下是修改后的代码:
#!/usr/bin/python3.6
import boto3
from unittest import mock
client_cw = boto3.client('cloudwatch')
# ---
# This is where the mocking starts
with mock.patch("boto3.client") as client:
# Create a mock paginator to return mock pages
class MockPaginator(object):
def paginate(self):
# Customize this to whatever the "real"
# paginated list from AWS looks like
return [
{
"AlarmsList": [
{
"Name": "my_alarm_1"
},
{
"Name": "my_alarm_2"
}
]
}
]
# Tell the get_paginator method to return a fake Paginator
client.get_paginator.return_value = MockPaginator()
# This is where the mocking ends
# (but we're still in the mocking context)
# ---
# And now on with the show...
paginator = client.get_paginator('describe_alarms')
for response in paginator.paginate():
print(response)现在,当您调用paginator.paginate()时,它将返回您在自定义分页器类中提供的自定义硬编码JSON列表,而不是试图调用AWS。
发布于 2021-02-19 15:31:47
我可能要迟到了。但我有一个类似的用例,最后创建了一个名为botocache的项目。你可以在这里查看:- https://github.com/rams3sh/botocache
它使用相同的方法来修补boto3 3的特定方法,使用unittest的补丁。
https://stackoverflow.com/questions/57436085
复制相似问题