Moto在pytes中似乎并没有嘲笑aws的交互

2024-05-01 02:43:16 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我想嘲弄一下:

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

但我好像没法把它修好。我正在尝试这样做,以便我可以修补会话和该方法中的函数调用

我试着用摩托,结果发现:

@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

看来这不是在嘲笑什么:|

编辑:

事实证明,您需要在配置和凭据文件中具有模拟凭据才能使其工作。你知道吗


Tags: nameclientawsgetfoosessiondefaccount
2条回答

我不知道你到底想要什么,所以我会给你一些开始。你知道吗

例如,你让unittest.mock为你模拟一切。(有用的阅读:https://docs.python.org/3/library/unittest.mock.html

module.py

import boto3

def function():
    session = boto3.Session(profile_name="foobar")
    client = session.resource("sts")
    return client.get_caller_identity().get('Account')

test_module.py

from unittest.mock import patch

import module

@patch("module.boto3")  # this creates mock which is passed to test below
def test_function(mocked_boto):
    # mocks below are magically created by unittest.mock when they are accessed
    mocked_session = mocked_boto.Session()
    mocked_client = mocked_session.resource()
    mocked_identity = mocked_client.get_caller_identity()

    # now mock the return value of .get()
    mocked_identity.get.return_value = "foo-bar-baz"

    result = module.function()
    assert result == "foo-bar-baz"

    # we can make sure mocks were called properly, for example
    mocked_identity.get.assert_called_once_with("Account")

试运行结果:

$ 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,以确保您的测试不会意外地与网络通信。你知道吗

尽管使用mock.patch手动修补boto没有错,但是您也可以考虑使用更高级别的测试实用程序,如moto。你知道吗

相关问题 更多 >