[英]Python3 mock on setup
我试图在安装时模拟一些第三部分库,以便我可以假装它按我的代码预期的那样工作。
我能够在本地模拟它,在该函数上配置函数本身的所有返回值
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')
但是,当我尝试通过模拟启动/停止从这种方法转到更清洁的方法时,我在断言中收到错误消息:
AttributeError:“ _ patch”对象没有属性“ assert_drawn_with”
我正在尝试像这样移植
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()
我可能不完全了解启动和停止的过程,我曾假设安装时会应用补丁,并据此提供断言。 我也欢迎有关如何使几个模拟游戏更清洁的任何建议
patch
对象是补丁,而不是模拟对象。 mock
框架有两个主要职责:
很多时候我们可以使用补丁来安装模拟...但是补丁不是模拟的。
patch.start()
返回用于修补原始引用的新引用(通常是模拟)。
def setUp(self):
self.params_ret = {"FOO":"BAR"}
self.mock_conn = Mock(wraps=conn)
self.patch_params = patch('task_queues.queue.pika.ConnectionParameters', return_value = self.params_ret)
self.patch_block = patch('task_queues.queue.pika.BlockingConnection', return_value=self.mock_conn)
mock_params = self.patch_params.start()
mock_block = self.patch_block.start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.