在pytes中模拟连接类

2024-09-27 00:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

class Aggregator(ConsumerProducerMixin):

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

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

^{pr2}$

使用调试器进入Aggregator.__init__,我发现{}仍然没有被修补为Mock实例:

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

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


Tags: selfurlexchangeinitdefrabbitmq情况broker
1条回答
网友
1楼 · 发布于 2024-09-27 00:13:43

好的,docs声明如下:

patch() works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.

The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined. A couple of examples will help to clarify this.

因此,解决方案:

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

相关问题 更多 >

    热门问题