gpt4 book ai didi

Python 模拟 : Patching Python Pika's "basic_publish" function

转载 作者:行者123 更新时间:2023-12-03 23:53:43 24 4
gpt4 key购买 nike

考虑下面的测试代码:

import pika

class MQ_Client():
connection = None
channel = None
exchange_name="my_exchange"

def connect(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host="mq_server")

def publish(self, message):

properties = pika.BasicProperties(content_type='text/json', delivery_mode=1)

if self.channel.basic_publish(exchange=self.exchange_name, routing_key='', properties=properties, body=message):
log.info("Successfully published this message to exchange \"" + self.exchange_name + "\": " + message)
else:
log.error("Failed to publish message \"" + message + "\" to the exchange \"" + self.exchange_name + "\"!")
raise Exception("Failed to publish message to the queue.")

我想要的是修补 Pika 的 basic_publish方法来引发异常,并且可以使用一些帮助来弄清楚如何做到这一点。这是我上次尝试的结果:
@mock.patch.object(pika.BlockingConnection, 'channel')
def test_that_mq_publish_problems_return_error(self, mocked_channel):
with self.client as client:

mocked_channel.basic_publish.side_effect = Exception()

response = client.put("/api/users/bob", json="somedata")
self.assertEqual(response.status_code, 500)

任何有关如何使这项工作的建议将不胜感激!

最佳答案

我让它工作了。模拟实例方法与模拟类方法完全不同。阅读后this excellent article我终于明白了如何做到这一点,结果我只需要修补 basic_publish方法是像这样稍微修改我的测试:

@mock.patch('mq_client.pika.BlockingConnection', spec=pika.BlockingConnection)
def test_that_mq_publish_problems_return_error(self, mocked_connection):
with self.client as client:
mocked_connection.return_value.channel.return_value.basic_publish.return_value = False

关于Python 模拟 : Patching Python Pika's "basic_publish" function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53222364/

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