【问题标题】:Mock a connection class in pytest在 pytest 中模拟连接类
【发布时间】:2017-03-08 10:21:21
【问题描述】:

我有一个继承自 kombu.ConsumerProducerMixin 的类,我想在没有实际运行 rabbitmq 服务的情况下对其进行测试。

class Aggregator(ConsumerProducerMixin):

    def __init__(self, broker_url):
        exchange_name = 'chargers'
        self.status = 0
        self.connection = Connection(broker_url)
        ...

在我的测试文件中,我执行了以下操作:

from unittest.mock import Mock, patch

from aggregator import Aggregator

@patch('kombu.connection.Connection')
def test_on_request(conn_mock):

    agg = Aggregator('localhost')
    m = Message("", {"action": "start"}, content_type="application/json")

使用调试器进入Aggregator.__init__,我看到connection 仍未修补为Mock 实例:

(Pdb) self.connection
<Connection: amqp://guest:**@localhost:5672// at 0x7fc8b7f636d8>
(Pdb) Connection
<class 'kombu.connection.Connection'>

我的问题是如何正确修补连接,这样我就不需要 rabbitmq 来运行测试了?

【问题讨论】:

    标签: python unit-testing mocking rabbitmq kombu


    【解决方案1】:

    好的,docs 声明如下:

    patch() 通过(临时)更改名称指向的对象来工作 与另一个。可以有许多名称指向任何 单个对象,因此要使修补工作,您必须确保您 修补被测系统使用的名称。

    基本原则是在查找对象的位置打补丁, 这不一定与定义它的地方相同。一种 几个例子将有助于澄清这一点。

    因此,解决方案:

    @patch('aggregator.aggregator.Connection')
    def test_on_request(mock_connect):
        agg = Aggregator('localhost')
    

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 2020-02-02
      • 2022-08-19
      • 2019-11-07
      相关资源
      最近更新 更多