假设我想模拟以下内容:
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 中模拟这个?我可以通过创建一个虚拟类和必要的属性来创建模拟对象,但我怀疑这是错误的方法。
一些额外的细节,这是我想要测试的:
def test_check_aws_profile(self, mocker):
mocked_boto3 = mocker.patch('myapp.services.utils.boto3.Session')
mocker.patch(mocked_boto3.client.get_caller_identity.get, return_value='foo-account-id')
assert 'foo-account-id' == my_func('foo')
#in myapp.services.utils.py
def my_func(profile):
session = boto3.Session(profile_name=profile)
client = session.client('sts')
aws_account_number = client.get_caller_identity().get('Account')
return aws_account_number
但我似乎无法正确修补这个补丁。我正在努力做到这一点,以便我可以修补会话和该方法中的函数调用
我尝试使用 moto 并得到了这个:
@mock_sts
def test_check_aws_profile(self):
session = boto3.Session(profile_name='foo')
client = session.client('sts')
client.get_caller_identity().get('Account')
但我遇到了
> raise ProfileNotFound(profile=profile_name)
E botocore.exceptions.ProfileNotFound: The config profile (foo) could not be found
所以它似乎没有在嘲笑任何东西:|
编辑:
事实证明,您需要在配置和凭据文件中包含模拟凭据才能使其正常工作。