我想import
的exception
是,当发生boto3
ssm
不与发现的参数get_parameter
.我正在尝试为库添加一些额外的ssm
功能moto
,但我在这一点上很难过.
>>> import boto3
>>> ssm = boto3.client('ssm')
>>> try:
ssm.get_parameter(Name='not_found')
except Exception as e:
print(type(e))
<class 'botocore.errorfactory.ParameterNotFound'>
>>> from botocore.errorfactory import ParameterNotFound
ImportError: cannot import name 'ParameterNotFound'
>>> import botocore.errorfactory.ParameterNotFound
ModuleNotFoundError: No module named 'botocore.errorfactory.ParameterNotFound'; 'botocore.errorfactory' is not a package
Run Code Online (Sandbox Code Playgroud)
但是,Exception
无法导入,并且似乎不存在于botocore代码中.如何导入此例外?
我正在使用 moto 和 Python 3.7 来模拟一些 S3 交互。如果所有模拟代码都包含在测试方法中,那么 moto 似乎可以正常工作。当我将一些初步代码移动到 时setUp()
,测试失败了,好像setUp()
从未运行过一样。
import unittest
import boto3
from moto import mock_s3
class BucketFacadeTests(unittest.TestCase):
@mock_s3
def setUp(self):
print('setUp called')
s3 = boto3.resource('s3', region_name='us-east-1')
s3.create_bucket(Bucket='bucket')
key = 'a/b/c/d.txt'
object = s3.Object('bucket', key)
object.put(Body='my dog has fleas')
def do_test(self):
s3 = boto3.resource('s3', region_name='us-east-1')
the_object = s3.Object('bucket', 'a/b/c/d.txt')
string_data = the_object.get()['Body'].read().decode('utf-8')
self.assertEqual('my dog has fleas', string_data)
@mock_s3
def test_bucket_can_be_accessed_with_setup(self):
self.do_test()
@mock_s3
def test_bucket_can_be_accessed_without_setup(self):
# This does what setUp() should
s3 = boto3.resource('s3', …
Run Code Online (Sandbox Code Playgroud) 我正在尝试测试一些使用boto的python代码.我宁愿不尝试对AWS进行集成测试,所以我试图用moto来模拟它,而且它的行为并不像我期望的那样.
这是测试代码:
import io
import boto3
from moto import mock_ec2
from unittest.mock import patch
from argparse import Namespace
from awswl import commands
@mock_ec2
@patch('awswl.externalip.get_external_ip', return_value='192.0.2.1')
def test_list_command_lists_ipv4_and_ipv6_cidrs(exip_method):
# Given
options = Namespace()
options.sgid = "sg-123456"
ec2 = boto3.resource('ec2')
sg = ec2.create_security_group(
Description='Security Group for SSH Whitelisting',
GroupName='SSH Whitelist'
)
print("Created security group: {0}".format(sg.GroupId))
Run Code Online (Sandbox Code Playgroud)
而错误:
Testing started at 16:46 ...
/path/.virtualenvs/awswl-Ir8BWU8l/bin/python "/path/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/173.4301.16/PyCharm.app/Contents/helpers/pycharm/_jb_pytest_runner.py" --target test_commands.py::test_list_command_lists_ipv4_and_ipv6_cidrs
Launching py.test with arguments test_commands.py::test_list_command_lists_ipv4_and_ipv6_cidrs in /path/awswl/tests
============================= test session starts ==============================
platform darwin -- Python …
Run Code Online (Sandbox Code Playgroud) I am currently trying to write unit tests for my python code using Moto & @mock_dynamodb2 . So far it's been working for me to test my "successful operation" test cases. But I'm having trouble getting it to work for my "failure cases".
In my test code I have:
@mock_dynamodb2
class TestClassUnderTestExample(unittest.TestCase):
def setUp(self):
ddb = boto3.resource("dynamodb", "us-east-1")
self.table = ddb.create_table(<the table definition)
self.example_under_test = ClassUnderTestExample(ddb)
def test_some_thing_success(self):
expected_response = {<some value>}
assert expected_response = self.example_under_test.write_entry(<some value>)
def test_some_thing_success(self):
response …
Run Code Online (Sandbox Code Playgroud) 我的应用程序在运行时不会中断.但是,始终显示以下错误消息
E/NetlinkEvent: NetlinkEvent::FindParam(): Parameter 'UID' not found
Run Code Online (Sandbox Code Playgroud)
这个日志打印不断,我不明白,这个错误的原因是什么,你们中的任何人都可以告诉我这些错误消息究竟与哪些有关?
设备是moto g3.
感谢您提供的任何帮助.
我发现了一些链接,但问题是
NetlinkEvent::FindParam(): Parameter 'UDEV_LOG' not found
Run Code Online (Sandbox Code Playgroud) 我想在本地使用 moto 测试我的 sts 设置。
get_aws_temp_credentials.py
import boto3
from botocore.exceptions import ClientError
def assume_role(aws_arn=None, aws_session_name=None):
if aws_arn is not None and aws_session_name is not None:
try:
local_session_name = aws_session_name[:64]
client = boto3.client('sts', region_name=Constants.pubAwsRegion)
response = client.assume_role(RoleArn=aws_arn,
RoleSessionName=local_session_name,
DurationSeconds=900)
return response
except ClientError as error:
logger.info({"message": "get_aws_temp_credentails.py: Can not assume Role"})
return 25
if __name__ == '__main__':
assume_role()
Run Code Online (Sandbox Code Playgroud)
test_assume_role.py :
import os
import pytest
from moto import mock_sts
@pytest.fixture
def aws_credentials():
"""Mocked AWS Credentials for moto."""
os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
os.environ['AWS_SECRET_ACCESS_KEY'] = …
Run Code Online (Sandbox Code Playgroud) 假设我想嘲笑以下内容:
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')
Run Code Online (Sandbox Code Playgroud)
我该如何开始在 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
Run Code Online (Sandbox Code Playgroud)
但我似乎无法正确地修复这个问题。我正在尝试这样做,以便我可以修补会话和该方法中的函数调用
我尝试使用 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')
Run Code Online (Sandbox Code Playgroud)
但我遇到了
> raise ProfileNotFound(profile=profile_name)
E botocore.exceptions.ProfileNotFound: The config profile (foo) could not be found
Run Code Online (Sandbox Code Playgroud)
所以看起来它并没有嘲笑任何东西:|
编辑:
事实证明,您需要在配置和凭据文件中包含模拟凭据才能使其工作。
我想创建一个由 AWS 管理的密钥。到目前为止,这就是我所拥有的
@mock_kms
def test_mocking_getting_keys(self):
session = boto3.Session(profile_name=profile)
client = session.client('kms', 'us-east-2')
key = client.create_key(
Policy='string',
Description='string',
KeyUsage='SIGN_VERIFY',
CustomerMasterKeySpec='RSA_2048',
Origin='AWS_KMS',
CustomKeyStoreId='string',
BypassPolicyLockoutSafetyCheck=True,
Tags=[
{
'TagKey': 'string',
'TagValue': 'string'
},
]
)
print(key)
Run Code Online (Sandbox Code Playgroud)
但密钥似乎没有 KeyManager 字段:
{'KeyMetadata': {'AWSAccountId': '012345678912', 'KeyId': '7fc3e676-0d1c-4526-9161-41b27a776033', 'Arn': 'arn:aws:kms:us-east-2:012345678912:key/7fc3e676-0d1c-4526-9161-41b27a776033', 'CreationDate': datetime.datetime(2020, 1, 3, 13, 31, 17, tzinfo=tzutc()), 'Enabled': True, 'Description': 'string', 'KeyUsage': 'SIGN_VERIFY', 'KeyState': 'Enabled'}, 'ResponseMetadata': {'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'}, 'RetryAttempts': 0}}
Run Code Online (Sandbox Code Playgroud)
我尝试在 create_key 调用期间将 KeyManager 添加为参数,但这也不起作用。
似乎 moto 不返回 KeyManager 字段。有没有办法专门模拟该返回值,但不更改其余参数的 dictionary.get 方法的行为?
IE …
我想对从 aws 导入的文件进行测试。我使用 moto 模拟 s3,以免弄乱实际数据。然而,现在 aws 似乎是空的,因此我决定在模拟的 s3 上上传一些测试文件。我怎样才能这样做呢?
这是我的设置,
Conftest.py:
@pytest.fixture(scope='function')
def aws_credentials():
"""Mocked AWS Credentials for moto."""
os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
os.environ['AWS_SECURITY_TOKEN'] = 'testing'
os.environ['AWS_SESSION_TOKEN'] = 'testing'
@pytest.fixture(scope='function')
def s3(aws_credentials):
with mock_s3():
yield boto3.client('s3', region_name='us-east-1')
Run Code Online (Sandbox Code Playgroud)
测试文件:
class TestLoadRecommendations:
@pytest.fixture(autouse=True)
def _setup(self, s3):
self.bucket = s3.create_bucket(Bucket=settings.SERVER_DATA_S3_BUCKET)
self.bucket.upload_file("tmp/recommendations-2021-04-13T17_28_06.csv", "tmp/recommendations-2021-04-13T17_28_06.csv")
Run Code Online (Sandbox Code Playgroud)
但是,上传它会引发错误TypeError: expected string or bytes-like object
,但我确信我使用了错误的命令来上传文件。有人可以帮忙吗?谢谢!
import pytest
from moto import mock_s3
@pytest.fixture(scope='module')
def s3():
with mock_s3():
os.environ['AWS_ACCESS_KEY_ID'] = 'test'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'test'
os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'
s3 = boto3.resource('s3')
s3.create_bucket(Bucket='test_bucket')
yield s3
Run Code Online (Sandbox Code Playgroud)
这段代码本来可以工作,但现在抛出异常Cannot import name mock_s3 from moto
。我究竟做错了什么?