Python测试:如何处理循环逻辑及无效输入引发的无限循环问题
问题解决:测试含循环的输入函数时避免无限循环
你的问题根源在于:test_invalid_input用mock.patch固定返回无效值"apple",但原函数的while True会一直循环等待有效输入,导致测试无限卡死。以下是几种实用的解决办法:
方法1:模拟多次输入(无需修改原函数)
使用side_effect代替return_value,先返回无效值触发错误分支,最后返回有效输入让函数退出循环。这样既能验证错误提示逻辑,又能让函数正常返回。
修改后的测试代码:
def test_invalid_input(self): # 先返回无效值触发错误提示,再返回n让函数退出循环 with mock.patch("builtins.input", side_effect=["apple", "n"]): # 可选:验证错误提示是否正确输出 with mock.patch("builtins.print") as mock_print: result = confirm_user_choice("apple") mock_print.assert_called_once_with("\nSelect either 'y' (yes) or 'n' (no)") self.assertEqual(result, False)
方法2:给原函数添加重试次数限制(让函数更健壮)
在原函数中加入最大尝试次数参数,超过次数后抛出异常或返回默认值,从根源避免无限循环,同时让测试可以精准控制退出条件。
修改后的函数:
def confirm_user_choice(choice: str, max_attempts: int = 3): attempts = 0 while attempts < max_attempts: user_response = input(f"\nYou chose '{choice}', is this correct? y/n ") if user_response == "y": return True elif user_response == "n": return False else: attempts += 1 print(f"\nSelect either 'y' (yes) or 'n' (no). {max_attempts - attempts} attempts left.") # 超过次数后抛出异常,或根据需求返回默认值 raise ValueError("Too many invalid input attempts")
对应的测试代码:
def test_invalid_input_exceed_attempts(self): with mock.patch("builtins.input", return_value="apple"): with self.assertRaises(ValueError): confirm_user_choice("apple", max_attempts=3)
方法3:测试中设置超时(备选方案,不推荐)
使用第三方库如timeout-decorator给测试用例添加超时限制,超时自动终止测试。但这种方法可控性差,且依赖外部库,仅作为前两种方法的补充。
内容的提问来源于stack exchange,提问作者kevin
相关产品推荐
相关产品推荐

