如何验证prompt_process函数无效输入不会退出while True循环?
测试else分支的解决方案
你可以通过unittest.mock的side_effect参数实现连续输入的模拟,即可完整覆盖else分支的重试逻辑,不需要修改原函数代码。
side_effect支持传入可迭代序列,每次调用被mock的input函数时,会按顺序返回序列中的元素。你可以先传入若干个非法输入值,最后传入合法的y或n,既能验证重试逻辑正常触发,也能校验错误提示文本、重试后分支逻辑是否符合预期。
以下是补充完整的测试用例:
import unittest from unittest import mock import process class TestProcess(unittest.TestCase): # 原有测试用例保留 @mock.patch('process.process') def test_prompt_process_calls_process_if_input_is_y(self, mock_process): with mock.patch('process.input', return_value='y'): process.prompt_process() mock_process.assert_called_once() def test_prompt_process_exits_if_input_is_n(self): with mock.patch('process.input', return_value='n'): with self.assertRaises(SystemExit): process.prompt_process() # 新增else分支测试用例 @mock.patch('process.process') def test_retry_on_invalid_input_then_call_process(self, mock_process): # 第一次输入非法值,第二次输入y with mock.patch('process.input', side_effect=['invalid', 'y']) as mock_input: process.prompt_process() # 验证input总共调用了2次 self.assertEqual(mock_input.call_count, 2) # 验证第二次调用input时使用了错误提示 mock_input.assert_any_call("Invalid answer - please type y or n") # 验证最终正常调用process函数 mock_process.assert_called_once() def test_retry_on_invalid_input_then_exit(self): # 第一次输入非法值,第二次输入n with mock.patch('process.input', side_effect=['123', 'n']) as mock_input: with self.assertRaises(SystemExit): process.prompt_process() # 验证input总共调用了2次 self.assertEqual(mock_input.call_count, 2) # 验证第二次调用input时使用了错误提示 mock_input.assert_any_call("Invalid answer - please type y or n") if __name__ == '__main__': unittest.main()
如果需要验证多次连续非法输入的场景,只需要在side_effect的序列里增加更多非法值即可,比如side_effect=['x', '?', ' ', 'y']即可测试连续3次非法输入后正常走y分支的逻辑。
这个场景建议补充测试,避免后续修改重试逻辑、提示文本时引入bug,比如出现非法输入后未重新赋值answer导致死循环、错误提示文本不符合预期等问题。
内容的提问来源于stack exchange,提问作者jfaccioni
相关产品推荐
相关产品推荐

