I am trying to mock some 3rd part library on setup so i can pretend it works as expected on my code.
I was able to mock it locally on which i configure all the returns on the function itself
class MockConnecton:
def __init__(self):
self._ch = Mock()
def channel(self):
return self._ch
class QEmiterTest(unittest.TestCase):
@patch('task_queues.queue.pika.BlockingConnection')
@patch('task_queues.queue.pika.ConnectionParameters')
def test_emiter(self,mock_params,mock_block):
config = {
'host':'mq',
'exchange':'test'
}
params = {"FOO":"BAR"}
mock_params.return_value = params
conn = MockConnecton()
mock_conn = Mock(wraps=conn)
mock_block.return_value = mock_conn
emitter = QEmitter(config['host'],config['exchange'])
mock_params.assert_called_with(config['host'])
mock_block.assert_called_with(params)
mock_conn.channel.assert_called_with()
conn._ch.exchange_declare.assert_called_with(exchange=config['exchange'],type='topic')
But when i try to move from this approach to a cleaner one with the mock start/stop i receive an error on the assertion:
AttributeError: '_patch' object has no attribute 'assert_called_with'
I am trying to port it like this
class QEmiterTest(unittest.TestCase):
def setUp(self):
mock_params = patch('task_queues.queue.pika.ConnectionParameters')
mock_block = patch('task_queues.queue.pika.BlockingConnection')
self.params_ret = {"FOO":"BAR"}
mock_params.return_value = self.params_ret
conn = MockConnecton()
self.mock_conn = Mock(wraps=conn)
mock_block.return_value = self.mock_conn
self.patch_params = mock_params
self.patch_block = mock_block
self.patch_params.start()
self.patch_block.start()
def test_emiter(self):
config = {
'host':'mq',
'exchange':'test'
}
emitter = QEmitter(config['host'],config['exchange'])
self.patch_params.assert_called_with(config['host'])
self.patch_block.assert_called_with(self.params_ret)
self.mock_conn.channel.assert_called_with()
self.mock_conn._ch.exchange_declare.assert_called_with(exchange=config['exchange'],type='topic')
def tearDown(self):
self.patch_params.stop()
self.patch_block.stop()
I may not fully understand the start and stop, i was under the assumpton that on setup it would apply the patch and by it's reference i would be able to make assertions . I also welcome any suggestons on how to make several mocks cleaner
Aucun commentaire:
Enregistrer un commentaire