我的webapp希望用boto向AWS SQS发送消息,我想模拟发送实际消息,只是检查调用send_message是否被调用。但是我不明白如何使用python mock来修补被测试函数调用的函数。
如何在下面的伪类代码中实现模拟boto con.send_message?
views.py:
@app.route('/test')
def send_msg():
con = boto.sqs.connect_to_region("eu-west-1",aws_access_key_id="asd",aws_secret_access_key="asd")
que = con.get_queue('my_queue')
msg = json.dumps({'data':'asd'})
r=con.send_message(que, msg)
tests.py
class MyTestCase(unittest.TestCase):
def test_test(self):
with patch('views.con.send_message') as sqs_send:
self.test_client.get('/test')
assert(sqs_send.called)
答案 0 :(得分:3)
要进行此类测试,您需要patch
connect_to_region()
。修补此方法后,返回可用于测试所有函数行为的MagicMock()
对象。
您的测试用例可能是这样的:
class MyTestCase(unittest.TestCase):
@patch("boto.sqs.connect_to_region", autospec=True)
def test_test(self, mock_connect_to_region):
#grab the mocked connection returned by patched connect_to_region
mock_con = mock_connect_to_region.return_value
#call client
self.test_client.get('/test')
#test connect_to_region call
mock_connect_to_region.assert_called_with("eu-west-1",aws_access_key_id="asd",aws_secret_access_key="asd")
#test get_queue()
mock_con.get_queue.assert_called_with('my_queue')
#finaly test send_message
mock_con.send_message.assert_called_with(mock_con.get_queue.return_value, json.dumps({'data':'asd'}))
只是一些注释:
self.assertTrue(mock_con.send_message.called)
,如果您对某些参数内容不感兴趣,请使用mock.ANY
作为参数。autospec=True
不是强制性的,但非常有用:请查看autospeccing。