首页 > 解决方案 > Moto SNS 客户端无法发布工作 AttributeError:“sns.ServiceResource”对象没有属性“发布”

问题描述

我正在尝试使用 Moto 模拟 SNS,使用 pytest 文档中的示例。

sns.create_topic() 有效,但 sns.publish() 无效。从 boto 文档中,我应该能够像这样调用 publish() :

@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")

@mock_sts
def test_publish(sns):
    resp = sns.create_topic(Name="sdfsdfsdfsd")
    mesg = {"TopicArn": "arnsdfsdf", "Message": "sdfsdfsdfsd"}
    response = sns.publish(mesg)

我收到以下错误:

AttributeError:“sns.ServiceResource”对象没有属性“发布”

Moto 不支持发布吗?我希望它验证对 publish() 的调用对我有效 - 我不想发布猴子补丁。

标签: pythonamazon-web-servicesmoto

解决方案


SNS 使用 boto3 客户端,而不是资源。所以改变这个:

with mock_sns():
    yield boto3.resource("sns", region_name="us-east-1")

对此:

with mock_sns():
    yield boto3.client("sns", region_name="us-east-1")

它应该可以工作。

示例测试用例:https ://github.com/spulec/moto/blob/master/tests/test_sns/test_publishing_boto3.py#L28


推荐阅读