Moto sns client cant call create_topic AttributeError: 'generator' object has no attribute 'create_topic'

Moto sns client cant call create_topic AttributeError: 'generator' object has no attribute 'create_topic'

我正在尝试按照文档来执行此操作:

@pytest.fixture()
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()
def sts(aws_credentials):
    with mock_sts():
        yield boto3.client("sts", region_name="us-east-1")


@pytest.fixture
def sns(aws_credentials):
    with mock_sns():
        yield boto3.resource("sns", region_name="us-east-1")


def test_publish(sns):
    resp = sns.create_topic(Name="sdfsdfsdfsd")

我收到错误:

    def test_publish(sns):
>       topic_arn = sns.create_topic(Name="sdfsdfsdfsd")
E       AttributeError: 'generator' object has no attribute 'create_topic'

好的,我不是 100% 确定为什么,但添加 sts 装饰器似乎解决了这个问题:

@mock_sts
def test_publish(sns):
    resp = sns.create_topic(Name="sdfsdfsdfsd")

我从这篇文章中了解到这一点,但我仍然不清楚它是如何工作的:https://www.serverlessops.io/blog/aws-lambda-serverless-development-workflow-part2-testing-debugging

这是因为 boto 需要使用 sts 所以我也需要模拟它吗?我使用带有配置文件的凭证文件从笔记本电脑访问 AWS

编辑

您也必须对 return 客户端使用 yield。在这里使用 return 给了我一个 sts 错误。我也想更好地理解这一点。我假设我需要使用 yield 因为它是一个生成器?

@pytest.fixture
def sns(aws_credentials):
    with mock_sns():
        # using return here causes below error
        return boto3.resource("sns", region_name="us-east-1")

不使用 yield 时出错:

botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the CreateTopic operation: The security token included in the request is invalid