如何解决如何修复 botocore.exceptions.ClientError:调用 Invoke 操作时发生错误 (404)
我正在尝试使用 pytest 和 moto 模拟 lambda 调用。以下是我的工作代码。
import zipfile
import os
import boto3
from moto import mock_lambda,mock_iam
import pytest
import io
from botocore.exceptions import ClientError
import json
@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 lambda_mock(aws_credentials):
with mock_lambda():
yield boto3.client('lambda',region_name='us-east-1')
def get_role_name():
with mock_iam():
iam = boto3.client("iam",region_name='us-east-1')
try:
return iam.get_role(RoleName="my-role")["Role"]["Arn"]
except ClientError:
return iam.create_role(
RoleName="my-role",AssumeRolePolicyDocument="some policy",Path="/my-path/",)["Role"]["Arn"]
@pytest.fixture(scope='function')
def lambda_mock(aws_credentials):
with mock_lambda():
yield boto3.client('lambda',region_name='us-east-1')
def _process_lambda(func_str):
zip_output = io.BytesIO()
zip_file = zipfile.ZipFile(zip_output,"w",zipfile.ZIP_DEFLATED)
zip_file.writestr("lambda_function.py",func_str)
zip_file.close()
zip_output.seek(0)
return zip_output.read()
def get_test_zip_file1():
pfunc = """
def lambda_handler(event,context):
print("custom log event")
return "hello world"
"""
return _process_lambda(pfunc)
# create mocked lambda with zip file
@mock_lambda
def test_mock_some_lambda(lambda_mock):
lambda_mock.create_function(
FunctionName='abc',Runtime='python3.7',Role=get_role_name(),Handler='lambda_function.lambda_handler',Code={"ZipFile": get_test_zip_file1()},Publish=True,Timeout=30,MemorySize=128
)
resp=lambda_mock.invoke(FunctionName='abc')
response=json.load(resp['Payload'])
assert response=='hello world'
但是,我想将 lambda 模拟和我的测试功能分开。所以我创建了一个 pytest 固定装置,它创建了一个如下所示的 lambda 函数。
@pytest.fixture(scope='function')
def mock_some_lambda(lambda_mock):
yield lambda_mock.create_function(
FunctionName='abc',MemorySize=128
)
然后是一个使用这个夹具的新测试函数
@mock_lambda
def test_update_allowed(lambda_mock,mock_some_lambda):
resp=lambda_mock.invoke(FunctionName='abc')
response=json.load(resp['Payload'])
assert response=='hello world'
这会抛出 botocore.exceptions.ClientError: An error occurred (404) when calling the Invoke operation:
看起来 lambda 函数的创建没有停留在测试函数中,当我运行 invoke()
时,它无法找到该函数。
我该如何完成这项工作?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。