gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:36:26 26 4
gpt4 key购买 nike

在我的单元测试中:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com