我有一个递归函数,位于名为的模块中test_module
import requests
def send_msg(msg, retries=0):
try:
# send the message here, e.g. a http request
response = requests.get("http://www.doesnotexist98734.com")
# if url does not exist raise an exception
except Exception as e:
if retries == 0:
raise e
else:
return send_msg(msg, retries=retries-1)
我的问题是如何编写一个单元测试来检查send_msg
当我设置 retries = n 时,函数被调用 n 次。我正在玩模拟模块(我使用的是 python 2.7),我想我想要类似这样的东西,
import mock, unittest
class MyUnitTest(unittest.TestCase):
@mock.patch('test_module.send_msg')
def test_send_msg_tries_n_times(self, mock_send_msg):
with self.assertRaises(Exception):
mock_send_msg("hello", retries=3)
self.assertEqual(mock_send_msg.call_count, 4) # initial call + 3 retries
然而,由于我已经模拟了该函数,它不会调用真正的函数,所以我没有得到异常,也不会递归地调用自身......
您无法模拟被测试的函数。您想要测试预期成绩,如果函数正确使用了递归,则不会。
嘲笑request.get()
调用,并让它始终产生异常。然后计算你的模拟被调用的频率。
@mock.patch('requests.get')
def test_send_msg_tries_n_times(self, req_get_mock):
req_get_mock.side_effect = Exception
with self.assertRaises(Exception):
send_msg("hello", retries=3)
self.assertEqual(req_get_mock.call_count, 4) # 1 initial call + 3 retries
如果将来您想避免使用递归并希望使用迭代,您的测试仍然可以工作,因为它验证的是行为,而不是具体的实现。您可以安全地重构被测函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)