2017-03-08 83 views
3

我有一個繼承kombu.ConsumerProducerMixin的類,我希望在沒有運行實際的rabbitmq服務的情況下進行測試。在pytest中模擬一個連接類

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來運行測試?

回答

2

確定,docs狀態如下:

補丁()的工作方式(暫時)改變對象的名稱點 以另外一個人。可以有許多名稱指向任何對象,因此爲了使修補工作正常,您必須確保 修補了被測系統使用的名稱。

基本原理是,你修補了一個物體被查找的位置,它不一定與它定義的位置相同。幾個例子將有助於澄清這一點。

因此,該解決方案:

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