【问题标题】:How to mock an AWS Lambda with moto如何使用 moto 模拟 AWS Lambda
【发布时间】:2022-11-06 14:07:03
【问题描述】:

我创建了一个代码来调用在其他地方创建的 AWS lambda 函数。

我想使用moto 来测试它,但我真的不明白该怎么做,并且我不断收到错误。

这是主要代码的一个简单示例:

import boto3
import json


class SimpleLambda:
    def __init__(self):
        self.aws_lambda = boto3.client("lambda", region_name="eu-west-2")

    def __call__(self):
        try:
            lambda_response = self.aws_lambda.invoke(
                FunctionName="test-lambda",
                Payload=json.dumps(
                    {
                        "Records": [
                            {
                                "Source": "test_source",
                                "Version": "test_version",
                            }
                        ]
                    }
                ),
            )
            return lambda_response["Payload"].read()
        except Exception as err:
            print(f"Could not invoke simple lambda: {err}")
            return None

和测试:

import os
import pytest
import unittest.mock as mock

import boto3
from moto import mock_lambda

from aws_lambda import SimpleLambda


@pytest.fixture
def aws_credentials():
    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
def lambda_client(aws_credentials):
    with mock_lambda():
        yield boto3.client("lambda", region_name="eu-west-2")


@pytest.fixture
def lambda_test(lambda_client):
    lambda_client.create_function(
        FunctionName="test-lambda",
        Role="arn:aws:iam::123456789012:role/doesnotexist",
        Code={"ZipFile": b"test"}
    )
    yield


def test_simple_lambda_call(lambda_client, lambda_test):
    simple_lambda = SimpleLambda()

    test = simple_lambda()

我得到错误:

botocore.errorfactory.InvalidParameterValueException: An error occurred (InvalidParameterValueException) when calling the CreateFunction operation: The role defined for the function cannot be assumed by Lambda.

我找到了几个关于如何将motoS3 bucket 一起使用的示例,但没有与lambda 一起使用。

运行this 其他问题中的代码,我得到了同样的错误。

有什么建议吗?

【问题讨论】:

    标签: python amazon-web-services boto3 moto


    【解决方案1】:

    Moto 还验证 IAM 角色是否存在,就像 AWS 一样。

    因此,请确保首先创建 IAM 角色:

    with mock_iam():
        iam = boto3.client("iam", region_name="eu-west-2")
        iam_role = iam.create_role(
            RoleName="my-role",
            AssumeRolePolicyDocument="some policy",
            Path="/my-path/",
        )["Role"]["Arn"]
    

    【讨论】:

    • 谢谢,解决了 boto 错误,但现在我有另一个错误。有效负载包含消息error running docker: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory')) 我是否必须以某种方式启动 moto 服务器?
    • 该错误特定于 Docker,并表明 Docker 服务未启动/无法访问。有关此问题的一些解决方案,请参阅stackoverflow.com/questions/64952238/…
    • 再次感谢。这意味着我必须在运行测试之前使用终端启动 Docker 服务。我对吗?有没有办法在 python 中启动它?
    • 我不知道在 Python @cicciodevoto 中启动它的好方法 - 我个人总是让它在启动时启动。
    猜你喜欢
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2023-01-17
    • 1970-01-01
    相关资源
    最近更新 更多