我如何正确模拟boto3会话调用进行测试?

问题描述 投票:0回答:1

说我想模拟以下内容:

session = boto3.Session(profile_name=profile)
resource = session.resource('iam')
iam_users = resource.users.all()
policies = resource.policies.filter(Scope='AWS', OnlyAttached=True, PolicyUsageFilter='PermissionsPolicy')

我如何开始在pytest中使用它进行模拟?我可以通过创建虚拟类和必要的属性来创建模拟对象,但是我怀疑这是错误的方法。

python amazon-web-services pytest boto3
1个回答
0
投票

我不确定您到底想要什么,所以我给您一些开始。

例如,您让unittest.mock为您模拟一切。

module.py

import boto3

def function():
    session = boto3.Session(profile_name="foobar")
    resource = session.resource("iam")
    policies = resource.policies.filter(Scope="AWS", OnlyAttached=True, PolicyUsageFilter="PermissionsPolicy")
    return policies

test_module.py

from unittest.mock import patch

import module

@patch("module.boto3")
def test_function(mocked_boto):
    result = module.function()
    mocked_session = mocked_boto.Session.return_value
    mocked_resource = mocked_session.resource.return_value
    mocked_policies = mocked_resource.policies.filter.return_value

    assert result is mocked_policies

pytest运行的结果:

$ pytest
================================ test session starts ================================
platform darwin -- Python 3.7.6, pytest-5.3.2, py-1.8.1, pluggy-0.13.1
rootdir: /private/tmp/one
collected 1 item                                                                    

test_module.py .                                                              [100%]

================================= 1 passed in 0.09s =================================

我也建议安装pytest-socket并运行pytest --disable-socket以确保您的测试不会偶然与网络通信。

© www.soinside.com 2019 - 2024. All rights reserved.