2017-03-08 4 views
3

私は実際のrabbitmqサービスを実行することなくテストしたいと思っているkombu.ConsumerProducerMixinから継承するクラスを持っています。pytestで接続クラスを模擬してください

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'> 
私のテストファイルで

class Aggregator(ConsumerProducerMixin): 

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

は、私は次のようでした

私の質問は、私が正しくテストするためにrabbitmqを必要としないように接続を正しくパッチするかどうかです。

答えて

2

OK、以下docs状態:

パッチ()は別のもので、その名前点 にオブジェクトを変更する(一時的に)することによって機能します。 個のオブジェクトを指す多くの名前がある可能性があるので、パッチを適用するには、テスト対象のシステムで使用されている名前を にパッチする必要があります。

基本的な原則は、オブジェクトがどこで参照されているかを修正することです。 は、定義されている場所と必ずしも同じ場所である必要はありません。 A の例がこれを明確にするのに役立ちます。したがって

、溶液:

@patch('aggregator.aggregator.Connection') 
def test_on_request(mock_connect): 
    agg = Aggregator('localhost') 
関連する問題