考虑以下代码进行测试:
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)
任何有关如何实现此工作的建议将不胜感激!
答案 0 :(得分:0)
我知道了。模拟实例方法与模拟类方法完全不同。读完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