python - 使用 moto 的 SNS 模拟无法正常工作

标签 python amazon-web-services unit-testing boto moto

在我的单元测试中:

def test_my_function_that_publishes_to_sns():
    conn = boto3.client("sns", region_name="us-east-1")
    mock_topic = conn.create_topic(Name="mock-topic")
    topic_arn = mock_topic.get("TopicArn")

    os.environ["SNS_TOPIC"] = topic_arn

    # call my_function
    my_module.my_method()

正在测试的函数

# inside my_module, my_function...
sns_client.publish(
            TopicArn=os.environ["SNS_TOPIC"], Message="my message",
        )

我收到错误:botocore.errorfactory.NotFoundException:调用发布操作时发生错误 (NotFound):Endpoint with arn arn:aws:sns:us-east-1:123456789012:mock-topic not找到

没有意义,这是 moto 应该创建和模拟的主题。为什么说它不存在?如果我在单元测试本身内部调用 conn.publish(TopicArn=topic_arn, Message="sdfsdsdf") 它似乎是在模拟它,但它不会为 my_module.my_method() 模拟它单元测试执行。也许它过早地破坏了 mock 的话题?

编辑我以各种方式尝试了这个,但我得到了完全相同的错误:

# Using context manager
def test_my_function_that_publishes_to_sns():
    with mock_sns():
        conn = boto3.client("sns", region_name="us-east-1")
        mock_topic = conn.create_topic(Name="mocktopic")
        topic_arn = mock_topic.get("TopicArn")
    
        os.environ["SNS_TOPIC"] = topic_arn
    
        # call my_function
        my_module.my_method()


# Using decorator
@mock_sns
def test_my_function_that_publishes_to_sns():
    conn = boto3.client("sns", region_name="us-east-1")
    mock_topic = conn.create_topic(Name="mocktopic")
    topic_arn = mock_topic.get("TopicArn")

    os.environ["SNS_TOPIC"] = topic_arn

    # call my_function
    my_module.my_method()


# Using decorator and context manager
@mock_sns
def test_my_function_that_publishes_to_sns():
    with mock_sns():
        conn = boto3.client("sns", region_name="us-east-1")
        mock_topic = conn.create_topic(Name="mocktopic")
        topic_arn = mock_topic.get("TopicArn")
    
        os.environ["SNS_TOPIC"] = topic_arn
    
        # call my_function
        my_module.my_method()

同时打开了 GitHub 问题:https://github.com/spulec/moto/issues/3027

最佳答案

问题是 my_module.my_method() 不是设置一个区域只是做 client = boto3.client("sns")

它找不到它,因为它默认为一个不同于硬编码到单元测试中的 us-east-1 的差异区域

关于python - 使用 moto 的 SNS 模拟无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62015260/

相关文章:

visual-studio - 用于 Elastic Beanstalk 配置以安装 Visual C++ Redistributable 的命令

javascript - 从 XUL 运行 JavaScript 代码的单元测试 - 内容和方式

python - Pandas:如何(干净地)反转具有相同类别的两列?

python - SQLAlchemy 中是否有与 django 的管理器等效的东西?

python - 在 pandas read_csv 中自定义分隔符

amazon-web-services - AWS S3 在 getSignedUrl 过期后优雅地处理 403

python - 使用 pygame 在 "Game of life"中查找相邻单元格的错误

python - boto3 已安装但出现 ModuleNotFoundError

c# - C# 单元测试套件的单线程

java - 在单元测试中使用 HttpClient 后如何正确清理